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.

277644 lines
7.4MB

  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. #define JUCE_IOS 1
  51. #else
  52. #define JUCE_MAC 1
  53. #endif
  54. #else
  55. #error "Unknown platform!"
  56. #endif
  57. #if JUCE_WINDOWS
  58. #ifdef _MSC_VER
  59. #ifdef _WIN64
  60. #define JUCE_64BIT 1
  61. #else
  62. #define JUCE_32BIT 1
  63. #endif
  64. #endif
  65. #ifdef _DEBUG
  66. #define JUCE_DEBUG 1
  67. #endif
  68. #ifdef __MINGW32__
  69. #define JUCE_MINGW 1
  70. #endif
  71. /** If defined, this indicates that the processor is little-endian. */
  72. #define JUCE_LITTLE_ENDIAN 1
  73. #define JUCE_INTEL 1
  74. #endif
  75. #if JUCE_MAC
  76. #ifndef NDEBUG
  77. #define JUCE_DEBUG 1
  78. #endif
  79. #ifdef __LITTLE_ENDIAN__
  80. #define JUCE_LITTLE_ENDIAN 1
  81. #else
  82. #define JUCE_BIG_ENDIAN 1
  83. #endif
  84. #if defined (__ppc__) || defined (__ppc64__)
  85. #define JUCE_PPC 1
  86. #else
  87. #define JUCE_INTEL 1
  88. #endif
  89. #ifdef __LP64__
  90. #define JUCE_64BIT 1
  91. #else
  92. #define JUCE_32BIT 1
  93. #endif
  94. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  95. #error "Building for OSX 10.3 is no longer supported!"
  96. #endif
  97. #ifndef MAC_OS_X_VERSION_10_5
  98. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  99. #endif
  100. #endif
  101. #if JUCE_IOS
  102. #ifndef NDEBUG
  103. #define JUCE_DEBUG 1
  104. #endif
  105. #ifdef __LITTLE_ENDIAN__
  106. #define JUCE_LITTLE_ENDIAN 1
  107. #else
  108. #define JUCE_BIG_ENDIAN 1
  109. #endif
  110. #endif
  111. #if JUCE_LINUX
  112. #ifdef _DEBUG
  113. #define JUCE_DEBUG 1
  114. #endif
  115. // Allow override for big-endian Linux platforms
  116. #ifndef JUCE_BIG_ENDIAN
  117. #define JUCE_LITTLE_ENDIAN 1
  118. #endif
  119. #if defined (__LP64__) || defined (_LP64)
  120. #define JUCE_64BIT 1
  121. #else
  122. #define JUCE_32BIT 1
  123. #endif
  124. #define JUCE_INTEL 1
  125. #endif
  126. // Compiler type macros.
  127. #ifdef __GNUC__
  128. #define JUCE_GCC 1
  129. #elif defined (_MSC_VER)
  130. #define JUCE_MSVC 1
  131. #if _MSC_VER >= 1400
  132. #define JUCE_USE_INTRINSICS 1
  133. #endif
  134. #else
  135. #error unknown compiler
  136. #endif
  137. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  138. /*** End of inlined file: juce_TargetPlatform.h ***/
  139. // FORCE_AMALGAMATOR_INCLUDE
  140. /*** Start of inlined file: juce_Config.h ***/
  141. #ifndef __JUCE_CONFIG_JUCEHEADER__
  142. #define __JUCE_CONFIG_JUCEHEADER__
  143. /*
  144. This file contains macros that enable/disable various JUCE features.
  145. */
  146. /** The name of the namespace that all Juce classes and functions will be
  147. put inside. If this is not defined, no namespace will be used.
  148. */
  149. #ifndef JUCE_NAMESPACE
  150. #define JUCE_NAMESPACE juce
  151. #endif
  152. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  153. project settings, but if you define this value, you can override this to force
  154. it to be true or false.
  155. */
  156. #ifndef JUCE_FORCE_DEBUG
  157. //#define JUCE_FORCE_DEBUG 0
  158. #endif
  159. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  160. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  161. Enabling it will also leave this turned on in release builds. When it's disabled,
  162. however, the jassert and jassertfalse macros will not be compiled in a
  163. release build.
  164. @see jassert, jassertfalse, Logger
  165. */
  166. #ifndef JUCE_LOG_ASSERTIONS
  167. #define JUCE_LOG_ASSERTIONS 0
  168. #endif
  169. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  170. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  171. on your Windows build machine.
  172. See the comments in the ASIOAudioIODevice class's header file for more
  173. info about this.
  174. */
  175. #ifndef JUCE_ASIO
  176. #define JUCE_ASIO 0
  177. #endif
  178. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  179. */
  180. #ifndef JUCE_WASAPI
  181. #define JUCE_WASAPI 0
  182. #endif
  183. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  184. */
  185. #ifndef JUCE_DIRECTSOUND
  186. #define JUCE_DIRECTSOUND 1
  187. #endif
  188. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  189. #ifndef JUCE_ALSA
  190. #define JUCE_ALSA 1
  191. #endif
  192. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  193. #ifndef JUCE_JACK
  194. #define JUCE_JACK 0
  195. #endif
  196. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  197. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  198. installed, and its header files will need to be on your include path.
  199. */
  200. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || (JUCE_WINDOWS && ! JUCE_MSVC))
  201. #define JUCE_QUICKTIME 0
  202. #endif
  203. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  204. #undef JUCE_QUICKTIME
  205. #endif
  206. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  207. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  208. */
  209. #ifndef JUCE_OPENGL
  210. #define JUCE_OPENGL 1
  211. #endif
  212. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  213. If your app doesn't need to read FLAC files, you might want to disable this to
  214. reduce the size of your codebase and build time.
  215. */
  216. #ifndef JUCE_USE_FLAC
  217. #define JUCE_USE_FLAC 1
  218. #endif
  219. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  220. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  221. reduce the size of your codebase and build time.
  222. */
  223. #ifndef JUCE_USE_OGGVORBIS
  224. #define JUCE_USE_OGGVORBIS 1
  225. #endif
  226. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  227. Unless you're using CD-burning, you should probably turn this flag off to
  228. reduce code size.
  229. */
  230. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  231. #define JUCE_USE_CDBURNER 0
  232. #endif
  233. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  234. Unless you're using CD-reading, you should probably turn this flag off to
  235. reduce code size.
  236. */
  237. #ifndef JUCE_USE_CDREADER
  238. #define JUCE_USE_CDREADER 0
  239. #endif
  240. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  241. */
  242. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  243. #define JUCE_USE_CAMERA 0
  244. #endif
  245. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  246. gets repainted will flash in a random colour, so that you can check exactly how much and how
  247. often your components are being drawn.
  248. */
  249. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  250. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  251. #endif
  252. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  253. Unless you specifically want to disable this, it's best to leave this option turned on.
  254. */
  255. #ifndef JUCE_USE_XINERAMA
  256. #define JUCE_USE_XINERAMA 1
  257. #endif
  258. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  259. turned on unless you have a good reason to disable it.
  260. */
  261. #ifndef JUCE_USE_XSHM
  262. #define JUCE_USE_XSHM 1
  263. #endif
  264. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  265. */
  266. #ifndef JUCE_USE_XRENDER
  267. #define JUCE_USE_XRENDER 0
  268. #endif
  269. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  270. unless you have a good reason to disable it.
  271. */
  272. #ifndef JUCE_USE_XCURSOR
  273. #define JUCE_USE_XCURSOR 1
  274. #endif
  275. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  276. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  277. you're building a plugin hosting app.
  278. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  279. */
  280. #ifndef JUCE_PLUGINHOST_VST
  281. #define JUCE_PLUGINHOST_VST 0
  282. #endif
  283. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  284. of course, and should only be enabled if you're building a plugin hosting app.
  285. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  286. */
  287. #ifndef JUCE_PLUGINHOST_AU
  288. #define JUCE_PLUGINHOST_AU 0
  289. #endif
  290. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  291. This should be enabled if you're writing a console application.
  292. */
  293. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  294. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  295. #endif
  296. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  297. If you're not using any embedded web-pages, turning this off may reduce your code size.
  298. */
  299. #ifndef JUCE_WEB_BROWSER
  300. #define JUCE_WEB_BROWSER 1
  301. #endif
  302. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  303. Carbon isn't required for a normal app, but may be needed by specialised classes like
  304. plugin-hosts, which support older APIs.
  305. */
  306. #ifndef JUCE_SUPPORT_CARBON
  307. #define JUCE_SUPPORT_CARBON 1
  308. #endif
  309. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  310. You might need to tweak this if you're linking to an external zlib library in your app,
  311. but for normal apps, this option should be left alone.
  312. */
  313. #ifndef JUCE_INCLUDE_ZLIB_CODE
  314. #define JUCE_INCLUDE_ZLIB_CODE 1
  315. #endif
  316. #ifndef JUCE_INCLUDE_FLAC_CODE
  317. #define JUCE_INCLUDE_FLAC_CODE 1
  318. #endif
  319. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  320. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  321. #endif
  322. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  323. #define JUCE_INCLUDE_PNGLIB_CODE 1
  324. #endif
  325. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  326. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  327. #endif
  328. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check when an app terminates.
  329. (Currently, this only affects Windows builds in debug mode).
  330. */
  331. #ifndef JUCE_CHECK_MEMORY_LEAKS
  332. #define JUCE_CHECK_MEMORY_LEAKS 1
  333. #endif
  334. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  335. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  336. are passed to the JUCEApplication::unhandledException() callback for logging.
  337. */
  338. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  339. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  340. #endif
  341. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  342. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  343. #undef JUCE_QUICKTIME
  344. #define JUCE_QUICKTIME 0
  345. #undef JUCE_OPENGL
  346. #define JUCE_OPENGL 0
  347. #undef JUCE_USE_CDBURNER
  348. #define JUCE_USE_CDBURNER 0
  349. #undef JUCE_USE_CDREADER
  350. #define JUCE_USE_CDREADER 0
  351. #undef JUCE_WEB_BROWSER
  352. #define JUCE_WEB_BROWSER 0
  353. #undef JUCE_PLUGINHOST_AU
  354. #define JUCE_PLUGINHOST_AU 0
  355. #undef JUCE_PLUGINHOST_VST
  356. #define JUCE_PLUGINHOST_VST 0
  357. #endif
  358. #endif
  359. /*** End of inlined file: juce_Config.h ***/
  360. // FORCE_AMALGAMATOR_INCLUDE
  361. #ifndef JUCE_BUILD_CORE
  362. #define JUCE_BUILD_CORE 1
  363. #endif
  364. #ifndef JUCE_BUILD_MISC
  365. #define JUCE_BUILD_MISC 1
  366. #endif
  367. #ifndef JUCE_BUILD_GUI
  368. #define JUCE_BUILD_GUI 1
  369. #endif
  370. #ifndef JUCE_BUILD_NATIVE
  371. #define JUCE_BUILD_NATIVE 1
  372. #endif
  373. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  374. #undef JUCE_BUILD_MISC
  375. #undef JUCE_BUILD_GUI
  376. #endif
  377. //==============================================================================
  378. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  379. #if JUCE_WINDOWS
  380. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  381. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  382. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  383. #ifndef STRICT
  384. #define STRICT 1
  385. #endif
  386. #undef WIN32_LEAN_AND_MEAN
  387. #define WIN32_LEAN_AND_MEAN 1
  388. #if JUCE_MSVC
  389. #pragma warning (push)
  390. #pragma warning (disable : 4100 4201 4514 4312 4995)
  391. #endif
  392. #define _WIN32_WINNT 0x0500
  393. #define _UNICODE 1
  394. #define UNICODE 1
  395. #ifndef _WIN32_IE
  396. #define _WIN32_IE 0x0400
  397. #endif
  398. #include <windows.h>
  399. #include <windowsx.h>
  400. #include <commdlg.h>
  401. #include <shellapi.h>
  402. #include <mmsystem.h>
  403. #include <vfw.h>
  404. #include <tchar.h>
  405. #include <stddef.h>
  406. #include <ctime>
  407. #include <wininet.h>
  408. #include <nb30.h>
  409. #include <iphlpapi.h>
  410. #include <mapi.h>
  411. #include <float.h>
  412. #include <process.h>
  413. #include <Exdisp.h>
  414. #include <exdispid.h>
  415. #include <shlobj.h>
  416. #if ! JUCE_MINGW
  417. #include <crtdbg.h>
  418. #include <comutil.h>
  419. #endif
  420. #if JUCE_OPENGL
  421. #include <gl/gl.h>
  422. #endif
  423. #undef PACKED
  424. #if JUCE_ASIO
  425. /*
  426. This is very frustrating - we only need to use a handful of definitions from
  427. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  428. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  429. implementation...
  430. ..unfortunately that would break Steinberg's license agreement for use of
  431. their SDK, so I'm not allowed to do this.
  432. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  433. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  434. (see www.steinberg.net/Steinberg/Developers.asp).
  435. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  436. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  437. if you prefer). Make sure that your header search path will find the
  438. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  439. files are actually needed - so to simplify things, you could just copy
  440. these into your JUCE directory).
  441. If you're compiling and you get an error here because you don't have the
  442. ASIO SDK installed, you can disable ASIO support by commenting-out the
  443. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  444. */
  445. #include "iasiodrv.h"
  446. #endif
  447. #if JUCE_USE_CDBURNER
  448. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  449. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  450. flag in juce_Config.h to avoid these includes.
  451. */
  452. #include <imapi.h>
  453. #include <imapierror.h>
  454. #endif
  455. #if JUCE_USE_CAMERA
  456. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  457. These files are provided in the normal Windows SDK, but some Microsoft plonker
  458. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  459. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  460. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  461. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  462. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  463. The dummy file just needs to contain the following content:
  464. #define __IDxtCompositor_INTERFACE_DEFINED__
  465. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  466. #define __IDxtJpeg_INTERFACE_DEFINED__
  467. #define __IDxtKey_INTERFACE_DEFINED__
  468. ..and that should be enough to convince qedit.h that you have the SDK!
  469. */
  470. #include <dshow.h>
  471. #include <qedit.h>
  472. #include <dshowasf.h>
  473. #endif
  474. #if JUCE_WASAPI
  475. #include <MMReg.h>
  476. #include <mmdeviceapi.h>
  477. #include <Audioclient.h>
  478. #include <Avrt.h>
  479. #include <functiondiscoverykeys.h>
  480. #endif
  481. #if JUCE_QUICKTIME
  482. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  483. add its header directory to your include path.
  484. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  485. flag in juce_Config.h
  486. */
  487. #include <Movies.h>
  488. #include <QTML.h>
  489. #include <QuickTimeComponents.h>
  490. #include <MediaHandlers.h>
  491. #include <ImageCodec.h>
  492. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  493. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  494. your include search path to make these import statements work.
  495. */
  496. #import <QTOLibrary.dll>
  497. #import <QTOControl.dll>
  498. #endif
  499. #if JUCE_MSVC
  500. #pragma warning (pop)
  501. #endif
  502. /** A simple COM smart pointer.
  503. Avoids having to include ATL just to get one of these.
  504. */
  505. template <class ComClass>
  506. class ComSmartPtr
  507. {
  508. public:
  509. ComSmartPtr() throw() : p (0) {}
  510. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  511. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  512. ~ComSmartPtr() { if (p != 0) p->Release(); }
  513. operator ComClass*() const throw() { return p; }
  514. ComClass& operator*() const throw() { return *p; }
  515. ComClass** operator&() throw() { return &p; }
  516. ComClass* operator->() const throw() { return p; }
  517. ComClass* operator= (ComClass* const newP)
  518. {
  519. if (newP != 0) newP->AddRef();
  520. if (p != 0) p->Release();
  521. p = newP;
  522. return newP;
  523. }
  524. ComClass* operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  525. HRESULT CoCreateInstance (REFCLSID rclsid, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  526. {
  527. #ifndef __MINGW32__
  528. operator= (0);
  529. return ::CoCreateInstance (rclsid, 0, dwClsContext, __uuidof (ComClass), (void**) &p);
  530. #else
  531. return S_FALSE;
  532. #endif
  533. }
  534. private:
  535. ComClass* p;
  536. };
  537. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  538. */
  539. template <class ComClass>
  540. class ComBaseClassHelper : public ComClass
  541. {
  542. public:
  543. ComBaseClassHelper() : refCount (1) {}
  544. virtual ~ComBaseClassHelper() {}
  545. HRESULT __stdcall QueryInterface (REFIID refId, void __RPC_FAR* __RPC_FAR* result)
  546. {
  547. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  548. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  549. *result = 0;
  550. return E_NOINTERFACE;
  551. }
  552. ULONG __stdcall AddRef() { return ++refCount; }
  553. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  554. protected:
  555. int refCount;
  556. };
  557. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  558. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  559. #elif JUCE_LINUX
  560. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  561. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  562. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  563. /*
  564. This file wraps together all the linux-specific headers, so
  565. that we can include them all just once, and compile all our
  566. platform-specific stuff in one big lump, keeping it out of the
  567. way of the rest of the codebase.
  568. */
  569. #include <sched.h>
  570. #include <pthread.h>
  571. #include <sys/time.h>
  572. #include <errno.h>
  573. #include <sys/stat.h>
  574. #include <sys/dir.h>
  575. #include <sys/ptrace.h>
  576. #include <sys/vfs.h>
  577. #include <sys/wait.h>
  578. #include <fnmatch.h>
  579. #include <utime.h>
  580. #include <pwd.h>
  581. #include <fcntl.h>
  582. #include <dlfcn.h>
  583. #include <netdb.h>
  584. #include <arpa/inet.h>
  585. #include <netinet/in.h>
  586. #include <sys/types.h>
  587. #include <sys/ioctl.h>
  588. #include <sys/socket.h>
  589. #include <net/if.h>
  590. #include <sys/sysinfo.h>
  591. #include <sys/file.h>
  592. #include <signal.h>
  593. /* Got a build error here? You'll need to install the freetype library...
  594. The name of the package to install is "libfreetype6-dev".
  595. */
  596. #include <ft2build.h>
  597. #include FT_FREETYPE_H
  598. #include <X11/Xlib.h>
  599. #include <X11/Xatom.h>
  600. #include <X11/Xresource.h>
  601. #include <X11/Xutil.h>
  602. #include <X11/Xmd.h>
  603. #include <X11/keysym.h>
  604. #include <X11/cursorfont.h>
  605. #if JUCE_USE_XINERAMA
  606. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  607. #include <X11/extensions/Xinerama.h>
  608. #endif
  609. #if JUCE_USE_XSHM
  610. #include <X11/extensions/XShm.h>
  611. #include <sys/shm.h>
  612. #include <sys/ipc.h>
  613. #endif
  614. #if JUCE_USE_XRENDER
  615. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  616. #include <X11/extensions/Xrender.h>
  617. #include <X11/extensions/Xcomposite.h>
  618. #endif
  619. #if JUCE_USE_XCURSOR
  620. // If you're missing this header, try installing the libxcursor-dev package
  621. #include <X11/Xcursor/Xcursor.h>
  622. #endif
  623. #if JUCE_OPENGL
  624. /* Got an include error here?
  625. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  626. and "freeglut3-dev".
  627. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  628. want to disable it.
  629. */
  630. #include <GL/glx.h>
  631. #endif
  632. #undef KeyPress
  633. #if JUCE_ALSA
  634. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  635. not got your paths set up correctly to find its header files.
  636. The package you need to install to get ASLA support is "libasound2-dev".
  637. If you don't have the ALSA library and don't want to build Juce with audio support,
  638. just disable the JUCE_ALSA flag in juce_Config.h
  639. */
  640. #include <alsa/asoundlib.h>
  641. #endif
  642. #if JUCE_JACK
  643. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  644. installed, or you've not got your paths set up correctly to find its header files.
  645. The package you need to install to get JACK support is "libjack-dev".
  646. If you don't have the jack-audio-connection-kit library and don't want to build
  647. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  648. */
  649. #include <jack/jack.h>
  650. //#include <jack/transport.h>
  651. #endif
  652. #undef SIZEOF
  653. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  654. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  655. #elif JUCE_MAC || JUCE_IPHONE
  656. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  657. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  658. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  659. /*
  660. This file wraps together all the mac-specific code, so that
  661. we can include all the native headers just once, and compile all our
  662. platform-specific stuff in one big lump, keeping it out of the way of
  663. the rest of the codebase.
  664. */
  665. #define USE_COREGRAPHICS_RENDERING 1
  666. #if JUCE_IOS
  667. #import <Foundation/Foundation.h>
  668. #import <UIKit/UIKit.h>
  669. #import <AudioToolbox/AudioToolbox.h>
  670. #import <AVFoundation/AVFoundation.h>
  671. #import <CoreData/CoreData.h>
  672. #import <MobileCoreServices/MobileCoreServices.h>
  673. #import <QuartzCore/QuartzCore.h>
  674. #include <sys/fcntl.h>
  675. #if JUCE_OPENGL
  676. #include <OpenGLES/ES1/gl.h>
  677. #include <OpenGLES/ES1/glext.h>
  678. #endif
  679. #else
  680. #import <Cocoa/Cocoa.h>
  681. #import <CoreAudio/HostTime.h>
  682. #import <CoreAudio/AudioHardware.h>
  683. #import <CoreMIDI/MIDIServices.h>
  684. #import <QTKit/QTKit.h>
  685. #import <WebKit/WebKit.h>
  686. #import <DiscRecording/DiscRecording.h>
  687. #import <IOKit/IOKitLib.h>
  688. #import <IOKit/IOCFPlugIn.h>
  689. #import <IOKit/hid/IOHIDLib.h>
  690. #import <IOKit/hid/IOHIDKeys.h>
  691. #import <IOKit/pwr_mgt/IOPMLib.h>
  692. #include <Carbon/Carbon.h>
  693. #include <sys/dir.h>
  694. #endif
  695. #include <sys/socket.h>
  696. #include <sys/sysctl.h>
  697. #include <sys/stat.h>
  698. #include <sys/param.h>
  699. #include <sys/mount.h>
  700. #include <fnmatch.h>
  701. #include <utime.h>
  702. #include <dlfcn.h>
  703. #include <ifaddrs.h>
  704. #include <net/if_dl.h>
  705. #include <mach/mach_time.h>
  706. #if MACOS_10_4_OR_EARLIER
  707. #include <GLUT/glut.h>
  708. #endif
  709. #if ! CGFLOAT_DEFINED
  710. #define CGFloat float
  711. #endif
  712. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  713. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  714. #else
  715. #error "Unknown platform!"
  716. #endif
  717. #endif
  718. //==============================================================================
  719. #define DONT_SET_USING_JUCE_NAMESPACE 1
  720. #undef max
  721. #undef min
  722. #define NO_DUMMY_DECL
  723. #if JUCE_BUILD_NATIVE
  724. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  725. #endif
  726. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  727. #pragma warning (disable: 4309 4305)
  728. #endif
  729. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  730. BEGIN_JUCE_NAMESPACE
  731. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  732. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  733. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  734. /**
  735. Creates a floating carbon window that can be used to hold a carbon UI.
  736. This is a handy class that's designed to be inlined where needed, e.g.
  737. in the audio plugin hosting code.
  738. */
  739. class CarbonViewWrapperComponent : public Component,
  740. public ComponentMovementWatcher,
  741. public Timer
  742. {
  743. public:
  744. CarbonViewWrapperComponent()
  745. : ComponentMovementWatcher (this),
  746. wrapperWindow (0),
  747. embeddedView (0),
  748. recursiveResize (false)
  749. {
  750. }
  751. virtual ~CarbonViewWrapperComponent()
  752. {
  753. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  754. }
  755. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  756. virtual void removeView (HIViewRef embeddedView) = 0;
  757. virtual void mouseDown (int, int) {}
  758. virtual void paint() {}
  759. virtual bool getEmbeddedViewSize (int& w, int& h)
  760. {
  761. if (embeddedView == 0)
  762. return false;
  763. HIRect bounds;
  764. HIViewGetBounds (embeddedView, &bounds);
  765. w = jmax (1, roundToInt (bounds.size.width));
  766. h = jmax (1, roundToInt (bounds.size.height));
  767. return true;
  768. }
  769. void createWindow()
  770. {
  771. if (wrapperWindow == 0)
  772. {
  773. Rect r;
  774. r.left = getScreenX();
  775. r.top = getScreenY();
  776. r.right = r.left + getWidth();
  777. r.bottom = r.top + getHeight();
  778. CreateNewWindow (kDocumentWindowClass,
  779. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  780. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  781. &r, &wrapperWindow);
  782. jassert (wrapperWindow != 0);
  783. if (wrapperWindow == 0)
  784. return;
  785. NSWindow* carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  786. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  787. [ownerWindow addChildWindow: carbonWindow
  788. ordered: NSWindowAbove];
  789. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  790. EventTypeSpec windowEventTypes[] =
  791. {
  792. { kEventClassWindow, kEventWindowGetClickActivation },
  793. { kEventClassWindow, kEventWindowHandleDeactivate },
  794. { kEventClassWindow, kEventWindowBoundsChanging },
  795. { kEventClassMouse, kEventMouseDown },
  796. { kEventClassMouse, kEventMouseMoved },
  797. { kEventClassMouse, kEventMouseDragged },
  798. { kEventClassMouse, kEventMouseUp},
  799. { kEventClassWindow, kEventWindowDrawContent },
  800. { kEventClassWindow, kEventWindowShown },
  801. { kEventClassWindow, kEventWindowHidden }
  802. };
  803. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  804. InstallWindowEventHandler (wrapperWindow, upp,
  805. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  806. windowEventTypes, this, &eventHandlerRef);
  807. setOurSizeToEmbeddedViewSize();
  808. setEmbeddedWindowToOurSize();
  809. creationTime = Time::getCurrentTime();
  810. }
  811. }
  812. void deleteWindow()
  813. {
  814. removeView (embeddedView);
  815. embeddedView = 0;
  816. if (wrapperWindow != 0)
  817. {
  818. RemoveEventHandler (eventHandlerRef);
  819. DisposeWindow (wrapperWindow);
  820. wrapperWindow = 0;
  821. }
  822. }
  823. void setOurSizeToEmbeddedViewSize()
  824. {
  825. int w, h;
  826. if (getEmbeddedViewSize (w, h))
  827. {
  828. if (w != getWidth() || h != getHeight())
  829. {
  830. startTimer (50);
  831. setSize (w, h);
  832. if (getParentComponent() != 0)
  833. getParentComponent()->setSize (w, h);
  834. }
  835. else
  836. {
  837. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  838. }
  839. }
  840. else
  841. {
  842. stopTimer();
  843. }
  844. }
  845. void setEmbeddedWindowToOurSize()
  846. {
  847. if (! recursiveResize)
  848. {
  849. recursiveResize = true;
  850. if (embeddedView != 0)
  851. {
  852. HIRect r;
  853. r.origin.x = 0;
  854. r.origin.y = 0;
  855. r.size.width = (float) getWidth();
  856. r.size.height = (float) getHeight();
  857. HIViewSetFrame (embeddedView, &r);
  858. }
  859. if (wrapperWindow != 0)
  860. {
  861. Rect wr;
  862. wr.left = getScreenX();
  863. wr.top = getScreenY();
  864. wr.right = wr.left + getWidth();
  865. wr.bottom = wr.top + getHeight();
  866. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  867. ShowWindow (wrapperWindow);
  868. }
  869. recursiveResize = false;
  870. }
  871. }
  872. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  873. {
  874. setEmbeddedWindowToOurSize();
  875. }
  876. void componentPeerChanged()
  877. {
  878. deleteWindow();
  879. createWindow();
  880. }
  881. void componentVisibilityChanged (Component&)
  882. {
  883. if (isShowing())
  884. createWindow();
  885. else
  886. deleteWindow();
  887. setEmbeddedWindowToOurSize();
  888. }
  889. static void recursiveHIViewRepaint (HIViewRef view)
  890. {
  891. HIViewSetNeedsDisplay (view, true);
  892. HIViewRef child = HIViewGetFirstSubview (view);
  893. while (child != 0)
  894. {
  895. recursiveHIViewRepaint (child);
  896. child = HIViewGetNextView (child);
  897. }
  898. }
  899. void timerCallback()
  900. {
  901. setOurSizeToEmbeddedViewSize();
  902. // To avoid strange overpainting problems when the UI is first opened, we'll
  903. // repaint it a few times during the first second that it's on-screen..
  904. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  905. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  906. }
  907. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/,
  908. EventRef event)
  909. {
  910. switch (GetEventKind (event))
  911. {
  912. case kEventWindowHandleDeactivate:
  913. ActivateWindow (wrapperWindow, TRUE);
  914. break;
  915. case kEventWindowGetClickActivation:
  916. {
  917. getTopLevelComponent()->toFront (false);
  918. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  919. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  920. sizeof (ClickActivationResult), &howToHandleClick);
  921. HIViewSetNeedsDisplay (embeddedView, true);
  922. }
  923. break;
  924. }
  925. return noErr;
  926. }
  927. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef,
  928. EventRef event, void* userData)
  929. {
  930. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  931. }
  932. protected:
  933. WindowRef wrapperWindow;
  934. HIViewRef embeddedView;
  935. bool recursiveResize;
  936. Time creationTime;
  937. EventHandlerRef eventHandlerRef;
  938. };
  939. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  940. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  941. END_JUCE_NAMESPACE
  942. #endif
  943. #define JUCE_AMALGAMATED_TEMPLATE 1
  944. //==============================================================================
  945. #if JUCE_BUILD_CORE
  946. /*** Start of inlined file: juce_FileLogger.cpp ***/
  947. BEGIN_JUCE_NAMESPACE
  948. FileLogger::FileLogger (const File& logFile_,
  949. const String& welcomeMessage,
  950. const int maxInitialFileSizeBytes)
  951. : logFile (logFile_)
  952. {
  953. if (maxInitialFileSizeBytes >= 0)
  954. trimFileSize (maxInitialFileSizeBytes);
  955. if (! logFile_.exists())
  956. {
  957. // do this so that the parent directories get created..
  958. logFile_.create();
  959. }
  960. logStream = logFile_.createOutputStream (256);
  961. jassert (logStream != 0);
  962. String welcome;
  963. welcome << "\r\n**********************************************************\r\n"
  964. << welcomeMessage
  965. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  966. << "\r\n";
  967. logMessage (welcome);
  968. }
  969. FileLogger::~FileLogger()
  970. {
  971. }
  972. void FileLogger::logMessage (const String& message)
  973. {
  974. if (logStream != 0)
  975. {
  976. DBG (message);
  977. const ScopedLock sl (logLock);
  978. (*logStream) << message << "\r\n";
  979. logStream->flush();
  980. }
  981. }
  982. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  983. {
  984. if (maxFileSizeBytes <= 0)
  985. {
  986. logFile.deleteFile();
  987. }
  988. else
  989. {
  990. const int64 fileSize = logFile.getSize();
  991. if (fileSize > maxFileSizeBytes)
  992. {
  993. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  994. jassert (in != 0);
  995. if (in != 0)
  996. {
  997. in->setPosition (fileSize - maxFileSizeBytes);
  998. String content;
  999. {
  1000. MemoryBlock contentToSave;
  1001. contentToSave.setSize (maxFileSizeBytes + 4);
  1002. contentToSave.fillWith (0);
  1003. in->read (contentToSave.getData(), maxFileSizeBytes);
  1004. in = 0;
  1005. content = contentToSave.toString();
  1006. }
  1007. int newStart = 0;
  1008. while (newStart < fileSize
  1009. && content[newStart] != '\n'
  1010. && content[newStart] != '\r')
  1011. ++newStart;
  1012. logFile.deleteFile();
  1013. logFile.appendText (content.substring (newStart), false, false);
  1014. }
  1015. }
  1016. }
  1017. }
  1018. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1019. const String& logFileName,
  1020. const String& welcomeMessage,
  1021. const int maxInitialFileSizeBytes)
  1022. {
  1023. #if JUCE_MAC
  1024. File logFile ("~/Library/Logs");
  1025. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1026. .getChildFile (logFileName);
  1027. #else
  1028. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1029. if (logFile.isDirectory())
  1030. {
  1031. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1032. .getChildFile (logFileName);
  1033. }
  1034. #endif
  1035. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1036. }
  1037. END_JUCE_NAMESPACE
  1038. /*** End of inlined file: juce_FileLogger.cpp ***/
  1039. /*** Start of inlined file: juce_Logger.cpp ***/
  1040. BEGIN_JUCE_NAMESPACE
  1041. Logger::Logger()
  1042. {
  1043. }
  1044. Logger::~Logger()
  1045. {
  1046. }
  1047. Logger* Logger::currentLogger = 0;
  1048. void Logger::setCurrentLogger (Logger* const newLogger,
  1049. const bool deleteOldLogger)
  1050. {
  1051. Logger* const oldLogger = currentLogger;
  1052. currentLogger = newLogger;
  1053. if (deleteOldLogger)
  1054. delete oldLogger;
  1055. }
  1056. void Logger::writeToLog (const String& message)
  1057. {
  1058. if (currentLogger != 0)
  1059. currentLogger->logMessage (message);
  1060. else
  1061. outputDebugString (message);
  1062. }
  1063. #if JUCE_LOG_ASSERTIONS
  1064. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1065. {
  1066. String m ("JUCE Assertion failure in ");
  1067. m << filename << ", line " << lineNum;
  1068. Logger::writeToLog (m);
  1069. }
  1070. #endif
  1071. END_JUCE_NAMESPACE
  1072. /*** End of inlined file: juce_Logger.cpp ***/
  1073. /*** Start of inlined file: juce_Random.cpp ***/
  1074. BEGIN_JUCE_NAMESPACE
  1075. Random::Random (const int64 seedValue) throw()
  1076. : seed (seedValue)
  1077. {
  1078. }
  1079. Random::~Random() throw()
  1080. {
  1081. }
  1082. void Random::setSeed (const int64 newSeed) throw()
  1083. {
  1084. seed = newSeed;
  1085. }
  1086. void Random::combineSeed (const int64 seedValue) throw()
  1087. {
  1088. seed ^= nextInt64() ^ seedValue;
  1089. }
  1090. void Random::setSeedRandomly()
  1091. {
  1092. combineSeed ((int64) (pointer_sized_int) this);
  1093. combineSeed (Time::getMillisecondCounter());
  1094. combineSeed (Time::getHighResolutionTicks());
  1095. combineSeed (Time::getHighResolutionTicksPerSecond());
  1096. combineSeed (Time::currentTimeMillis());
  1097. }
  1098. int Random::nextInt() throw()
  1099. {
  1100. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1101. return (int) (seed >> 16);
  1102. }
  1103. int Random::nextInt (const int maxValue) throw()
  1104. {
  1105. jassert (maxValue > 0);
  1106. return (nextInt() & 0x7fffffff) % maxValue;
  1107. }
  1108. int64 Random::nextInt64() throw()
  1109. {
  1110. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1111. }
  1112. bool Random::nextBool() throw()
  1113. {
  1114. return (nextInt() & 0x80000000) != 0;
  1115. }
  1116. float Random::nextFloat() throw()
  1117. {
  1118. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1119. }
  1120. double Random::nextDouble() throw()
  1121. {
  1122. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1123. }
  1124. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1125. {
  1126. BigInteger n;
  1127. do
  1128. {
  1129. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1130. }
  1131. while (n >= maximumValue);
  1132. return n;
  1133. }
  1134. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1135. {
  1136. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1137. while ((startBit & 31) != 0 && numBits > 0)
  1138. {
  1139. arrayToChange.setBit (startBit++, nextBool());
  1140. --numBits;
  1141. }
  1142. while (numBits >= 32)
  1143. {
  1144. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1145. startBit += 32;
  1146. numBits -= 32;
  1147. }
  1148. while (--numBits >= 0)
  1149. arrayToChange.setBit (startBit + numBits, nextBool());
  1150. }
  1151. Random& Random::getSystemRandom() throw()
  1152. {
  1153. static Random sysRand (1);
  1154. return sysRand;
  1155. }
  1156. END_JUCE_NAMESPACE
  1157. /*** End of inlined file: juce_Random.cpp ***/
  1158. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1159. BEGIN_JUCE_NAMESPACE
  1160. RelativeTime::RelativeTime (const double seconds_) throw()
  1161. : seconds (seconds_)
  1162. {
  1163. }
  1164. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1165. : seconds (other.seconds)
  1166. {
  1167. }
  1168. RelativeTime::~RelativeTime() throw()
  1169. {
  1170. }
  1171. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1172. {
  1173. return RelativeTime (milliseconds * 0.001);
  1174. }
  1175. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1176. {
  1177. return RelativeTime (milliseconds * 0.001);
  1178. }
  1179. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1180. {
  1181. return RelativeTime (numberOfMinutes * 60.0);
  1182. }
  1183. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1184. {
  1185. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1186. }
  1187. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1188. {
  1189. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1190. }
  1191. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1192. {
  1193. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1194. }
  1195. int64 RelativeTime::inMilliseconds() const throw()
  1196. {
  1197. return (int64)(seconds * 1000.0);
  1198. }
  1199. double RelativeTime::inMinutes() const throw()
  1200. {
  1201. return seconds / 60.0;
  1202. }
  1203. double RelativeTime::inHours() const throw()
  1204. {
  1205. return seconds / (60.0 * 60.0);
  1206. }
  1207. double RelativeTime::inDays() const throw()
  1208. {
  1209. return seconds / (60.0 * 60.0 * 24.0);
  1210. }
  1211. double RelativeTime::inWeeks() const throw()
  1212. {
  1213. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1214. }
  1215. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const throw()
  1216. {
  1217. if (seconds < 0.001 && seconds > -0.001)
  1218. return returnValueForZeroTime;
  1219. String result;
  1220. if (seconds < 0)
  1221. result = "-";
  1222. int fieldsShown = 0;
  1223. int n = abs ((int) inWeeks());
  1224. if (n > 0)
  1225. {
  1226. result << n << ((n == 1) ? TRANS(" week ")
  1227. : TRANS(" weeks "));
  1228. ++fieldsShown;
  1229. }
  1230. n = abs ((int) inDays()) % 7;
  1231. if (n > 0)
  1232. {
  1233. result << n << ((n == 1) ? TRANS(" day ")
  1234. : TRANS(" days "));
  1235. ++fieldsShown;
  1236. }
  1237. if (fieldsShown < 2)
  1238. {
  1239. n = abs ((int) inHours()) % 24;
  1240. if (n > 0)
  1241. {
  1242. result << n << ((n == 1) ? TRANS(" hr ")
  1243. : TRANS(" hrs "));
  1244. ++fieldsShown;
  1245. }
  1246. if (fieldsShown < 2)
  1247. {
  1248. n = abs ((int) inMinutes()) % 60;
  1249. if (n > 0)
  1250. {
  1251. result << n << ((n == 1) ? TRANS(" min ")
  1252. : TRANS(" mins "));
  1253. ++fieldsShown;
  1254. }
  1255. if (fieldsShown < 2)
  1256. {
  1257. n = abs ((int) inSeconds()) % 60;
  1258. if (n > 0)
  1259. {
  1260. result << n << ((n == 1) ? TRANS(" sec ")
  1261. : TRANS(" secs "));
  1262. ++fieldsShown;
  1263. }
  1264. if (fieldsShown < 1)
  1265. {
  1266. n = abs ((int) inMilliseconds()) % 1000;
  1267. if (n > 0)
  1268. {
  1269. result << n << TRANS(" ms");
  1270. ++fieldsShown;
  1271. }
  1272. }
  1273. }
  1274. }
  1275. }
  1276. return result.trimEnd();
  1277. }
  1278. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1279. {
  1280. seconds = other.seconds;
  1281. return *this;
  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. bool RelativeTime::operator< (const RelativeTime& other) const throw()
  1296. {
  1297. return seconds < other.seconds;
  1298. }
  1299. bool RelativeTime::operator>= (const RelativeTime& other) const throw()
  1300. {
  1301. return seconds >= other.seconds;
  1302. }
  1303. bool RelativeTime::operator<= (const RelativeTime& other) const throw()
  1304. {
  1305. return seconds <= other.seconds;
  1306. }
  1307. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1308. {
  1309. return RelativeTime (seconds + timeToAdd.seconds);
  1310. }
  1311. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1312. {
  1313. return RelativeTime (seconds - timeToSubtract.seconds);
  1314. }
  1315. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1316. {
  1317. return RelativeTime (seconds + secondsToAdd);
  1318. }
  1319. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1320. {
  1321. return RelativeTime (seconds - secondsToSubtract);
  1322. }
  1323. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1324. {
  1325. seconds += timeToAdd.seconds;
  1326. return *this;
  1327. }
  1328. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1329. {
  1330. seconds -= timeToSubtract.seconds;
  1331. return *this;
  1332. }
  1333. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1334. {
  1335. seconds += secondsToAdd;
  1336. return *this;
  1337. }
  1338. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1339. {
  1340. seconds -= secondsToSubtract;
  1341. return *this;
  1342. }
  1343. END_JUCE_NAMESPACE
  1344. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1345. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1346. BEGIN_JUCE_NAMESPACE
  1347. SystemStats::CPUFlags SystemStats::cpuFlags;
  1348. const String SystemStats::getJUCEVersion()
  1349. {
  1350. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1351. + "." + String (JUCE_MINOR_VERSION)
  1352. + "." + String (JUCE_BUILDNUMBER);
  1353. }
  1354. const StringArray SystemStats::getMACAddressStrings()
  1355. {
  1356. int64 macAddresses [16];
  1357. const int numAddresses = getMACAddresses (macAddresses, numElementsInArray (macAddresses), false);
  1358. StringArray s;
  1359. for (int i = 0; i < numAddresses; ++i)
  1360. {
  1361. s.add (String::toHexString (0xff & (int) (macAddresses [i] >> 40)).paddedLeft ('0', 2)
  1362. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 32)).paddedLeft ('0', 2)
  1363. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 24)).paddedLeft ('0', 2)
  1364. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 16)).paddedLeft ('0', 2)
  1365. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 8)).paddedLeft ('0', 2)
  1366. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 0)).paddedLeft ('0', 2));
  1367. }
  1368. return s;
  1369. }
  1370. #ifdef JUCE_DLL
  1371. void* juce_Malloc (const int size)
  1372. {
  1373. return malloc (size);
  1374. }
  1375. void* juce_Calloc (const int size)
  1376. {
  1377. return calloc (1, size);
  1378. }
  1379. void* juce_Realloc (void* const block, const int size)
  1380. {
  1381. return realloc (block, size);
  1382. }
  1383. void juce_Free (void* const block)
  1384. {
  1385. free (block);
  1386. }
  1387. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1388. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1389. {
  1390. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1391. }
  1392. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1393. {
  1394. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1395. }
  1396. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1397. {
  1398. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1399. }
  1400. void juce_DebugFree (void* const block)
  1401. {
  1402. _free_dbg (block, _NORMAL_BLOCK);
  1403. }
  1404. #endif
  1405. #endif
  1406. END_JUCE_NAMESPACE
  1407. /*** End of inlined file: juce_SystemStats.cpp ***/
  1408. /*** Start of inlined file: juce_Time.cpp ***/
  1409. #if JUCE_MSVC
  1410. #pragma warning (push)
  1411. #pragma warning (disable: 4514)
  1412. #endif
  1413. #ifndef JUCE_WINDOWS
  1414. #include <sys/time.h>
  1415. #else
  1416. #include <ctime>
  1417. #endif
  1418. #include <sys/timeb.h>
  1419. #if JUCE_MSVC
  1420. #pragma warning (pop)
  1421. #ifdef _INC_TIME_INL
  1422. #define USE_NEW_SECURE_TIME_FNS
  1423. #endif
  1424. #endif
  1425. BEGIN_JUCE_NAMESPACE
  1426. namespace TimeHelpers
  1427. {
  1428. static struct tm millisToLocal (const int64 millis) throw()
  1429. {
  1430. struct tm result;
  1431. const int64 seconds = millis / 1000;
  1432. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1433. {
  1434. // use extended maths for dates beyond 1970 to 2037..
  1435. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1436. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1437. const int days = (int) (jdm / literal64bit (86400));
  1438. const int a = 32044 + days;
  1439. const int b = (4 * a + 3) / 146097;
  1440. const int c = a - (b * 146097) / 4;
  1441. const int d = (4 * c + 3) / 1461;
  1442. const int e = c - (d * 1461) / 4;
  1443. const int m = (5 * e + 2) / 153;
  1444. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1445. result.tm_mon = m + 2 - 12 * (m / 10);
  1446. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1447. result.tm_wday = (days + 1) % 7;
  1448. result.tm_yday = -1;
  1449. int t = (int) (jdm % literal64bit (86400));
  1450. result.tm_hour = t / 3600;
  1451. t %= 3600;
  1452. result.tm_min = t / 60;
  1453. result.tm_sec = t % 60;
  1454. result.tm_isdst = -1;
  1455. }
  1456. else
  1457. {
  1458. time_t now = static_cast <time_t> (seconds);
  1459. #if JUCE_WINDOWS
  1460. #ifdef USE_NEW_SECURE_TIME_FNS
  1461. if (now >= 0 && now <= 0x793406fff)
  1462. localtime_s (&result, &now);
  1463. else
  1464. zeromem (&result, sizeof (result));
  1465. #else
  1466. result = *localtime (&now);
  1467. #endif
  1468. #else
  1469. // more thread-safe
  1470. localtime_r (&now, &result);
  1471. #endif
  1472. }
  1473. return result;
  1474. }
  1475. static int extendedModulo (const int64 value, const int modulo) throw()
  1476. {
  1477. return (int) (value >= 0 ? (value % modulo)
  1478. : (value - ((value / modulo) + 1) * modulo));
  1479. }
  1480. static uint32 lastMSCounterValue = 0;
  1481. }
  1482. Time::Time() throw()
  1483. : millisSinceEpoch (0)
  1484. {
  1485. }
  1486. Time::Time (const Time& other) throw()
  1487. : millisSinceEpoch (other.millisSinceEpoch)
  1488. {
  1489. }
  1490. Time::Time (const int64 ms) throw()
  1491. : millisSinceEpoch (ms)
  1492. {
  1493. }
  1494. Time::Time (const int year,
  1495. const int month,
  1496. const int day,
  1497. const int hours,
  1498. const int minutes,
  1499. const int seconds,
  1500. const int milliseconds,
  1501. const bool useLocalTime) throw()
  1502. {
  1503. jassert (year > 100); // year must be a 4-digit version
  1504. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1505. {
  1506. // use extended maths for dates beyond 1970 to 2037..
  1507. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1508. : 0;
  1509. const int a = (13 - month) / 12;
  1510. const int y = year + 4800 - a;
  1511. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1512. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1513. - 32045;
  1514. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1515. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1516. + milliseconds;
  1517. }
  1518. else
  1519. {
  1520. struct tm t;
  1521. t.tm_year = year - 1900;
  1522. t.tm_mon = month;
  1523. t.tm_mday = day;
  1524. t.tm_hour = hours;
  1525. t.tm_min = minutes;
  1526. t.tm_sec = seconds;
  1527. t.tm_isdst = -1;
  1528. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1529. if (millisSinceEpoch < 0)
  1530. millisSinceEpoch = 0;
  1531. else
  1532. millisSinceEpoch += milliseconds;
  1533. }
  1534. }
  1535. Time::~Time() throw()
  1536. {
  1537. }
  1538. Time& Time::operator= (const Time& other) throw()
  1539. {
  1540. millisSinceEpoch = other.millisSinceEpoch;
  1541. return *this;
  1542. }
  1543. int64 Time::currentTimeMillis() throw()
  1544. {
  1545. static uint32 lastCounterResult = 0xffffffff;
  1546. static int64 correction = 0;
  1547. const uint32 now = getMillisecondCounter();
  1548. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1549. if (now < lastCounterResult)
  1550. {
  1551. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1552. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1553. {
  1554. // get the time once using normal library calls, and store the difference needed to
  1555. // turn the millisecond counter into a real time.
  1556. #if JUCE_WINDOWS
  1557. struct _timeb t;
  1558. #ifdef USE_NEW_SECURE_TIME_FNS
  1559. _ftime_s (&t);
  1560. #else
  1561. _ftime (&t);
  1562. #endif
  1563. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1564. #else
  1565. struct timeval tv;
  1566. struct timezone tz;
  1567. gettimeofday (&tv, &tz);
  1568. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1569. #endif
  1570. }
  1571. }
  1572. lastCounterResult = now;
  1573. return correction + now;
  1574. }
  1575. uint32 juce_millisecondsSinceStartup() throw();
  1576. uint32 Time::getMillisecondCounter() throw()
  1577. {
  1578. const uint32 now = juce_millisecondsSinceStartup();
  1579. if (now < TimeHelpers::lastMSCounterValue)
  1580. {
  1581. // in multi-threaded apps this might be called concurrently, so
  1582. // make sure that our last counter value only increases and doesn't
  1583. // go backwards..
  1584. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1585. TimeHelpers::lastMSCounterValue = now;
  1586. }
  1587. else
  1588. {
  1589. TimeHelpers::lastMSCounterValue = now;
  1590. }
  1591. return now;
  1592. }
  1593. uint32 Time::getApproximateMillisecondCounter() throw()
  1594. {
  1595. jassert (TimeHelpers::lastMSCounterValue != 0);
  1596. return TimeHelpers::lastMSCounterValue;
  1597. }
  1598. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1599. {
  1600. for (;;)
  1601. {
  1602. const uint32 now = getMillisecondCounter();
  1603. if (now >= targetTime)
  1604. break;
  1605. const int toWait = targetTime - now;
  1606. if (toWait > 2)
  1607. {
  1608. Thread::sleep (jmin (20, toWait >> 1));
  1609. }
  1610. else
  1611. {
  1612. // xxx should consider using mutex_pause on the mac as it apparently
  1613. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1614. for (int i = 10; --i >= 0;)
  1615. Thread::yield();
  1616. }
  1617. }
  1618. }
  1619. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1620. {
  1621. return ticks / (double) getHighResolutionTicksPerSecond();
  1622. }
  1623. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1624. {
  1625. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1626. }
  1627. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1628. {
  1629. return Time (currentTimeMillis());
  1630. }
  1631. const String Time::toString (const bool includeDate,
  1632. const bool includeTime,
  1633. const bool includeSeconds,
  1634. const bool use24HourClock) const throw()
  1635. {
  1636. String result;
  1637. if (includeDate)
  1638. {
  1639. result << getDayOfMonth() << ' '
  1640. << getMonthName (true) << ' '
  1641. << getYear();
  1642. if (includeTime)
  1643. result << ' ';
  1644. }
  1645. if (includeTime)
  1646. {
  1647. const int mins = getMinutes();
  1648. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1649. << (mins < 10 ? ":0" : ":") << mins;
  1650. if (includeSeconds)
  1651. {
  1652. const int secs = getSeconds();
  1653. result << (secs < 10 ? ":0" : ":") << secs;
  1654. }
  1655. if (! use24HourClock)
  1656. result << (isAfternoon() ? "pm" : "am");
  1657. }
  1658. return result.trimEnd();
  1659. }
  1660. const String Time::formatted (const String& format) const throw()
  1661. {
  1662. String buffer;
  1663. int bufferSize = 128;
  1664. buffer.preallocateStorage (bufferSize);
  1665. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1666. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1667. {
  1668. bufferSize += 128;
  1669. buffer.preallocateStorage (bufferSize);
  1670. }
  1671. return buffer;
  1672. }
  1673. int Time::getYear() const throw()
  1674. {
  1675. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1676. }
  1677. int Time::getMonth() const throw()
  1678. {
  1679. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1680. }
  1681. int Time::getDayOfMonth() const throw()
  1682. {
  1683. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1684. }
  1685. int Time::getDayOfWeek() const throw()
  1686. {
  1687. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1688. }
  1689. int Time::getHours() const throw()
  1690. {
  1691. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1692. }
  1693. int Time::getHoursInAmPmFormat() const throw()
  1694. {
  1695. const int hours = getHours();
  1696. if (hours == 0)
  1697. return 12;
  1698. else if (hours <= 12)
  1699. return hours;
  1700. else
  1701. return hours - 12;
  1702. }
  1703. bool Time::isAfternoon() const throw()
  1704. {
  1705. return getHours() >= 12;
  1706. }
  1707. int Time::getMinutes() const throw()
  1708. {
  1709. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1710. }
  1711. int Time::getSeconds() const throw()
  1712. {
  1713. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1714. }
  1715. int Time::getMilliseconds() const throw()
  1716. {
  1717. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1718. }
  1719. bool Time::isDaylightSavingTime() const throw()
  1720. {
  1721. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1722. }
  1723. const String Time::getTimeZone() const throw()
  1724. {
  1725. String zone[2];
  1726. #if JUCE_WINDOWS
  1727. _tzset();
  1728. #ifdef USE_NEW_SECURE_TIME_FNS
  1729. {
  1730. char name [128];
  1731. size_t length;
  1732. for (int i = 0; i < 2; ++i)
  1733. {
  1734. zeromem (name, sizeof (name));
  1735. _get_tzname (&length, name, 127, i);
  1736. zone[i] = name;
  1737. }
  1738. }
  1739. #else
  1740. const char** const zonePtr = (const char**) _tzname;
  1741. zone[0] = zonePtr[0];
  1742. zone[1] = zonePtr[1];
  1743. #endif
  1744. #else
  1745. tzset();
  1746. const char** const zonePtr = (const char**) tzname;
  1747. zone[0] = zonePtr[0];
  1748. zone[1] = zonePtr[1];
  1749. #endif
  1750. if (isDaylightSavingTime())
  1751. {
  1752. zone[0] = zone[1];
  1753. if (zone[0].length() > 3
  1754. && zone[0].containsIgnoreCase ("daylight")
  1755. && zone[0].contains ("GMT"))
  1756. zone[0] = "BST";
  1757. }
  1758. return zone[0].substring (0, 3);
  1759. }
  1760. const String Time::getMonthName (const bool threeLetterVersion) const throw()
  1761. {
  1762. return getMonthName (getMonth(), threeLetterVersion);
  1763. }
  1764. const String Time::getWeekdayName (const bool threeLetterVersion) const throw()
  1765. {
  1766. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1767. }
  1768. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion) throw()
  1769. {
  1770. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1771. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1772. monthNumber %= 12;
  1773. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1774. : longMonthNames [monthNumber]);
  1775. }
  1776. const String Time::getWeekdayName (int day, const bool threeLetterVersion) throw()
  1777. {
  1778. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1779. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1780. day %= 7;
  1781. return TRANS (threeLetterVersion ? shortDayNames [day]
  1782. : longDayNames [day]);
  1783. }
  1784. END_JUCE_NAMESPACE
  1785. /*** End of inlined file: juce_Time.cpp ***/
  1786. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1787. BEGIN_JUCE_NAMESPACE
  1788. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1789. #endif
  1790. #if JUCE_WINDOWS
  1791. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1792. #endif
  1793. #if JUCE_DEBUG
  1794. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1795. #endif
  1796. #if JUCE_DEBUG
  1797. namespace SimpleUnitTests
  1798. {
  1799. template <typename Type>
  1800. class AtomicTester
  1801. {
  1802. public:
  1803. AtomicTester() {}
  1804. static void testInteger()
  1805. {
  1806. Atomic<Type> a, b;
  1807. a.set ((Type) 10);
  1808. a += (Type) 15;
  1809. a.memoryBarrier();
  1810. a -= (Type) 5;
  1811. ++a; ++a; --a;
  1812. a.memoryBarrier();
  1813. testFloat();
  1814. }
  1815. static void testFloat()
  1816. {
  1817. Atomic<Type> a, b;
  1818. a = (Type) 21;
  1819. a.memoryBarrier();
  1820. /* These are some simple test cases to check the atomics - let me know
  1821. if any of these assertions fail on your system!
  1822. */
  1823. jassert (a.get() == (Type) 21);
  1824. jassert (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1825. jassert (a.get() == (Type) 21);
  1826. jassert (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1827. jassert (a.get() == (Type) 101);
  1828. jassert (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1829. jassert (a.get() == (Type) 101);
  1830. jassert (a.compareAndSetBool ((Type) 200, a.get()));
  1831. jassert (a.get() == (Type) 200);
  1832. jassert (a.exchange ((Type) 300) == (Type) 200);
  1833. jassert (a.get() == (Type) 300);
  1834. b = a;
  1835. jassert (b.get() == a.get());
  1836. }
  1837. };
  1838. static void runBasicTests()
  1839. {
  1840. // Some simple test code, to keep an eye on things and make sure these functions
  1841. // work ok on all platforms. Let me know if any of these assertions fail on your system!
  1842. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1843. static_jassert (sizeof (int8) == 1);
  1844. static_jassert (sizeof (uint8) == 1);
  1845. static_jassert (sizeof (int16) == 2);
  1846. static_jassert (sizeof (uint16) == 2);
  1847. static_jassert (sizeof (int32) == 4);
  1848. static_jassert (sizeof (uint32) == 4);
  1849. static_jassert (sizeof (int64) == 8);
  1850. static_jassert (sizeof (uint64) == 8);
  1851. char a1[7];
  1852. jassert (numElementsInArray(a1) == 7);
  1853. int a2[3];
  1854. jassert (numElementsInArray(a2) == 3);
  1855. jassert (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1856. jassert (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1857. jassert (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1858. // Some quick stream tests..
  1859. int randomInt = Random::getSystemRandom().nextInt();
  1860. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  1861. double randomDouble = Random::getSystemRandom().nextDouble();
  1862. String randomString;
  1863. for (int i = 50; --i >= 0;)
  1864. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  1865. MemoryOutputStream mo;
  1866. mo.writeInt (randomInt);
  1867. mo.writeIntBigEndian (randomInt);
  1868. mo.writeCompressedInt (randomInt);
  1869. mo.writeString (randomString);
  1870. mo.writeInt64 (randomInt64);
  1871. mo.writeInt64BigEndian (randomInt64);
  1872. mo.writeDouble (randomDouble);
  1873. mo.writeDoubleBigEndian (randomDouble);
  1874. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  1875. jassert (mi.readInt() == randomInt);
  1876. jassert (mi.readIntBigEndian() == randomInt);
  1877. jassert (mi.readCompressedInt() == randomInt);
  1878. jassert (mi.readString() == randomString);
  1879. jassert (mi.readInt64() == randomInt64);
  1880. jassert (mi.readInt64BigEndian() == randomInt64);
  1881. jassert (mi.readDouble() == randomDouble);
  1882. jassert (mi.readDoubleBigEndian() == randomDouble);
  1883. AtomicTester <int>::testInteger();
  1884. AtomicTester <unsigned int>::testInteger();
  1885. AtomicTester <int32>::testInteger();
  1886. AtomicTester <uint32>::testInteger();
  1887. AtomicTester <long>::testInteger();
  1888. AtomicTester <void*>::testInteger();
  1889. AtomicTester <int*>::testInteger();
  1890. AtomicTester <float>::testFloat();
  1891. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1892. AtomicTester <int64>::testInteger();
  1893. AtomicTester <uint64>::testInteger();
  1894. AtomicTester <double>::testFloat();
  1895. #endif
  1896. }
  1897. }
  1898. #endif
  1899. static bool juceInitialisedNonGUI = false;
  1900. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1901. {
  1902. if (! juceInitialisedNonGUI)
  1903. {
  1904. juceInitialisedNonGUI = true;
  1905. JUCE_AUTORELEASEPOOL
  1906. #if JUCE_DEBUG
  1907. SimpleUnitTests::runBasicTests();
  1908. #endif
  1909. DBG (SystemStats::getJUCEVersion());
  1910. SystemStats::initialiseStats();
  1911. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1912. }
  1913. }
  1914. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1915. {
  1916. if (juceInitialisedNonGUI)
  1917. {
  1918. juceInitialisedNonGUI = false;
  1919. JUCE_AUTORELEASEPOOL
  1920. LocalisedStrings::setCurrentMappings (0);
  1921. Thread::stopAllThreads (3000);
  1922. #if JUCE_WINDOWS
  1923. juce_shutdownWin32Sockets();
  1924. #endif
  1925. #if JUCE_DEBUG
  1926. juce_CheckForDanglingStreams();
  1927. #endif
  1928. }
  1929. }
  1930. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1931. void juce_setCurrentThreadName (const String& name);
  1932. static bool juceInitialisedGUI = false;
  1933. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  1934. {
  1935. if (! juceInitialisedGUI)
  1936. {
  1937. juceInitialisedGUI = true;
  1938. JUCE_AUTORELEASEPOOL
  1939. initialiseJuce_NonGUI();
  1940. MessageManager::getInstance();
  1941. LookAndFeel::setDefaultLookAndFeel (0);
  1942. juce_setCurrentThreadName ("Juce Message Thread");
  1943. #if JUCE_DEBUG
  1944. // This section is just for catching people who mess up their project settings and
  1945. // turn RTTI off..
  1946. try
  1947. {
  1948. TextButton tb (String::empty);
  1949. Component* c = &tb;
  1950. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1951. c = dynamic_cast <Button*> (c);
  1952. }
  1953. catch (...)
  1954. {
  1955. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1956. jassertfalse;
  1957. }
  1958. #endif
  1959. }
  1960. }
  1961. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  1962. {
  1963. if (juceInitialisedGUI)
  1964. {
  1965. juceInitialisedGUI = false;
  1966. JUCE_AUTORELEASEPOOL
  1967. DeletedAtShutdown::deleteAll();
  1968. LookAndFeel::clearDefaultLookAndFeel();
  1969. delete MessageManager::getInstance();
  1970. shutdownJuce_NonGUI();
  1971. }
  1972. }
  1973. #endif
  1974. END_JUCE_NAMESPACE
  1975. /*** End of inlined file: juce_Initialisation.cpp ***/
  1976. /*** Start of inlined file: juce_BigInteger.cpp ***/
  1977. BEGIN_JUCE_NAMESPACE
  1978. BigInteger::BigInteger()
  1979. : numValues (4),
  1980. highestBit (-1),
  1981. negative (false)
  1982. {
  1983. values.calloc (numValues + 1);
  1984. }
  1985. BigInteger::BigInteger (const int value)
  1986. : numValues (4),
  1987. highestBit (31),
  1988. negative (value < 0)
  1989. {
  1990. values.calloc (numValues + 1);
  1991. values[0] = abs (value);
  1992. highestBit = getHighestBit();
  1993. }
  1994. BigInteger::BigInteger (int64 value)
  1995. : numValues (4),
  1996. highestBit (63),
  1997. negative (value < 0)
  1998. {
  1999. values.calloc (numValues + 1);
  2000. if (value < 0)
  2001. value = -value;
  2002. values[0] = (unsigned int) value;
  2003. values[1] = (unsigned int) (value >> 32);
  2004. highestBit = getHighestBit();
  2005. }
  2006. BigInteger::BigInteger (const unsigned int value)
  2007. : numValues (4),
  2008. highestBit (31),
  2009. negative (false)
  2010. {
  2011. values.calloc (numValues + 1);
  2012. values[0] = value;
  2013. highestBit = getHighestBit();
  2014. }
  2015. BigInteger::BigInteger (const BigInteger& other)
  2016. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  2017. highestBit (other.getHighestBit()),
  2018. negative (other.negative)
  2019. {
  2020. values.malloc (numValues + 1);
  2021. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  2022. }
  2023. BigInteger::~BigInteger()
  2024. {
  2025. }
  2026. void BigInteger::swapWith (BigInteger& other) throw()
  2027. {
  2028. values.swapWith (other.values);
  2029. swapVariables (numValues, other.numValues);
  2030. swapVariables (highestBit, other.highestBit);
  2031. swapVariables (negative, other.negative);
  2032. }
  2033. BigInteger& BigInteger::operator= (const BigInteger& other)
  2034. {
  2035. if (this != &other)
  2036. {
  2037. highestBit = other.getHighestBit();
  2038. numValues = jmax (4, (highestBit >> 5) + 1);
  2039. negative = other.negative;
  2040. values.malloc (numValues + 1);
  2041. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  2042. }
  2043. return *this;
  2044. }
  2045. void BigInteger::ensureSize (const int numVals)
  2046. {
  2047. if (numVals + 2 >= numValues)
  2048. {
  2049. int oldSize = numValues;
  2050. numValues = ((numVals + 2) * 3) / 2;
  2051. values.realloc (numValues + 1);
  2052. while (oldSize < numValues)
  2053. values [oldSize++] = 0;
  2054. }
  2055. }
  2056. bool BigInteger::operator[] (const int bit) const throw()
  2057. {
  2058. return bit <= highestBit && bit >= 0
  2059. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  2060. }
  2061. int BigInteger::toInteger() const throw()
  2062. {
  2063. const int n = (int) (values[0] & 0x7fffffff);
  2064. return negative ? -n : n;
  2065. }
  2066. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2067. {
  2068. BigInteger r;
  2069. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2070. r.ensureSize (numBits >> 5);
  2071. r.highestBit = numBits;
  2072. int i = 0;
  2073. while (numBits > 0)
  2074. {
  2075. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2076. numBits -= 32;
  2077. startBit += 32;
  2078. }
  2079. r.highestBit = r.getHighestBit();
  2080. return r;
  2081. }
  2082. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2083. {
  2084. if (numBits > 32)
  2085. {
  2086. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2087. numBits = 32;
  2088. }
  2089. numBits = jmin (numBits, highestBit + 1 - startBit);
  2090. if (numBits <= 0)
  2091. return 0;
  2092. const int pos = startBit >> 5;
  2093. const int offset = startBit & 31;
  2094. const int endSpace = 32 - numBits;
  2095. uint32 n = ((uint32) values [pos]) >> offset;
  2096. if (offset > endSpace)
  2097. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2098. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2099. }
  2100. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet)
  2101. {
  2102. if (numBits > 32)
  2103. {
  2104. jassertfalse;
  2105. numBits = 32;
  2106. }
  2107. for (int i = 0; i < numBits; ++i)
  2108. {
  2109. setBit (startBit + i, (valueToSet & 1) != 0);
  2110. valueToSet >>= 1;
  2111. }
  2112. }
  2113. void BigInteger::clear()
  2114. {
  2115. if (numValues > 16)
  2116. {
  2117. numValues = 4;
  2118. values.calloc (numValues + 1);
  2119. }
  2120. else
  2121. {
  2122. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  2123. }
  2124. highestBit = -1;
  2125. negative = false;
  2126. }
  2127. void BigInteger::setBit (const int bit)
  2128. {
  2129. if (bit >= 0)
  2130. {
  2131. if (bit > highestBit)
  2132. {
  2133. ensureSize (bit >> 5);
  2134. highestBit = bit;
  2135. }
  2136. values [bit >> 5] |= (1 << (bit & 31));
  2137. }
  2138. }
  2139. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2140. {
  2141. if (shouldBeSet)
  2142. setBit (bit);
  2143. else
  2144. clearBit (bit);
  2145. }
  2146. void BigInteger::clearBit (const int bit) throw()
  2147. {
  2148. if (bit >= 0 && bit <= highestBit)
  2149. values [bit >> 5] &= ~(1 << (bit & 31));
  2150. }
  2151. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2152. {
  2153. while (--numBits >= 0)
  2154. setBit (startBit++, shouldBeSet);
  2155. }
  2156. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2157. {
  2158. if (bit >= 0)
  2159. shiftBits (1, bit);
  2160. setBit (bit, shouldBeSet);
  2161. }
  2162. bool BigInteger::isZero() const throw()
  2163. {
  2164. return getHighestBit() < 0;
  2165. }
  2166. bool BigInteger::isOne() const throw()
  2167. {
  2168. return getHighestBit() == 0 && ! negative;
  2169. }
  2170. bool BigInteger::isNegative() const throw()
  2171. {
  2172. return negative && ! isZero();
  2173. }
  2174. void BigInteger::setNegative (const bool neg) throw()
  2175. {
  2176. negative = neg;
  2177. }
  2178. void BigInteger::negate() throw()
  2179. {
  2180. negative = (! negative) && ! isZero();
  2181. }
  2182. int BigInteger::countNumberOfSetBits() const throw()
  2183. {
  2184. int total = 0;
  2185. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2186. {
  2187. unsigned int n = values[i];
  2188. if (n == 0xffffffff)
  2189. {
  2190. total += 32;
  2191. }
  2192. else
  2193. {
  2194. while (n != 0)
  2195. {
  2196. total += (n & 1);
  2197. n >>= 1;
  2198. }
  2199. }
  2200. }
  2201. return total;
  2202. }
  2203. int BigInteger::getHighestBit() const throw()
  2204. {
  2205. for (int i = highestBit + 1; --i >= 0;)
  2206. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2207. return i;
  2208. return -1;
  2209. }
  2210. int BigInteger::findNextSetBit (int i) const throw()
  2211. {
  2212. for (; i <= highestBit; ++i)
  2213. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2214. return i;
  2215. return -1;
  2216. }
  2217. int BigInteger::findNextClearBit (int i) const throw()
  2218. {
  2219. for (; i <= highestBit; ++i)
  2220. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2221. break;
  2222. return i;
  2223. }
  2224. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2225. {
  2226. if (other.isNegative())
  2227. return operator-= (-other);
  2228. if (isNegative())
  2229. {
  2230. if (compareAbsolute (other) < 0)
  2231. {
  2232. BigInteger temp (*this);
  2233. temp.negate();
  2234. *this = other;
  2235. operator-= (temp);
  2236. }
  2237. else
  2238. {
  2239. negate();
  2240. operator-= (other);
  2241. negate();
  2242. }
  2243. }
  2244. else
  2245. {
  2246. if (other.highestBit > highestBit)
  2247. highestBit = other.highestBit;
  2248. ++highestBit;
  2249. const int numInts = (highestBit >> 5) + 1;
  2250. ensureSize (numInts);
  2251. int64 remainder = 0;
  2252. for (int i = 0; i <= numInts; ++i)
  2253. {
  2254. if (i < numValues)
  2255. remainder += values[i];
  2256. if (i < other.numValues)
  2257. remainder += other.values[i];
  2258. values[i] = (unsigned int) remainder;
  2259. remainder >>= 32;
  2260. }
  2261. jassert (remainder == 0);
  2262. highestBit = getHighestBit();
  2263. }
  2264. return *this;
  2265. }
  2266. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2267. {
  2268. if (other.isNegative())
  2269. return operator+= (-other);
  2270. if (! isNegative())
  2271. {
  2272. if (compareAbsolute (other) < 0)
  2273. {
  2274. BigInteger temp (other);
  2275. swapWith (temp);
  2276. operator-= (temp);
  2277. negate();
  2278. return *this;
  2279. }
  2280. }
  2281. else
  2282. {
  2283. negate();
  2284. operator+= (other);
  2285. negate();
  2286. return *this;
  2287. }
  2288. const int numInts = (highestBit >> 5) + 1;
  2289. const int maxOtherInts = (other.highestBit >> 5) + 1;
  2290. int64 amountToSubtract = 0;
  2291. for (int i = 0; i <= numInts; ++i)
  2292. {
  2293. if (i <= maxOtherInts)
  2294. amountToSubtract += (int64) other.values[i];
  2295. if (values[i] >= amountToSubtract)
  2296. {
  2297. values[i] = (unsigned int) (values[i] - amountToSubtract);
  2298. amountToSubtract = 0;
  2299. }
  2300. else
  2301. {
  2302. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2303. values[i] = (unsigned int) n;
  2304. amountToSubtract = 1;
  2305. }
  2306. }
  2307. return *this;
  2308. }
  2309. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2310. {
  2311. BigInteger total;
  2312. highestBit = getHighestBit();
  2313. const bool wasNegative = isNegative();
  2314. setNegative (false);
  2315. for (int i = 0; i <= highestBit; ++i)
  2316. {
  2317. if (operator[](i))
  2318. {
  2319. BigInteger n (other);
  2320. n.setNegative (false);
  2321. n <<= i;
  2322. total += n;
  2323. }
  2324. }
  2325. total.setNegative (wasNegative ^ other.isNegative());
  2326. swapWith (total);
  2327. return *this;
  2328. }
  2329. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2330. {
  2331. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2332. const int divHB = divisor.getHighestBit();
  2333. const int ourHB = getHighestBit();
  2334. if (divHB < 0 || ourHB < 0)
  2335. {
  2336. // division by zero
  2337. remainder.clear();
  2338. clear();
  2339. }
  2340. else
  2341. {
  2342. const bool wasNegative = isNegative();
  2343. swapWith (remainder);
  2344. remainder.setNegative (false);
  2345. clear();
  2346. BigInteger temp (divisor);
  2347. temp.setNegative (false);
  2348. int leftShift = ourHB - divHB;
  2349. temp <<= leftShift;
  2350. while (leftShift >= 0)
  2351. {
  2352. if (remainder.compareAbsolute (temp) >= 0)
  2353. {
  2354. remainder -= temp;
  2355. setBit (leftShift);
  2356. }
  2357. if (--leftShift >= 0)
  2358. temp >>= 1;
  2359. }
  2360. negative = wasNegative ^ divisor.isNegative();
  2361. remainder.setNegative (wasNegative);
  2362. }
  2363. }
  2364. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2365. {
  2366. BigInteger remainder;
  2367. divideBy (other, remainder);
  2368. return *this;
  2369. }
  2370. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2371. {
  2372. // this operation doesn't take into account negative values..
  2373. jassert (isNegative() == other.isNegative());
  2374. if (other.highestBit >= 0)
  2375. {
  2376. ensureSize (other.highestBit >> 5);
  2377. int n = (other.highestBit >> 5) + 1;
  2378. while (--n >= 0)
  2379. values[n] |= other.values[n];
  2380. if (other.highestBit > highestBit)
  2381. highestBit = other.highestBit;
  2382. highestBit = getHighestBit();
  2383. }
  2384. return *this;
  2385. }
  2386. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2387. {
  2388. // this operation doesn't take into account negative values..
  2389. jassert (isNegative() == other.isNegative());
  2390. int n = numValues;
  2391. while (n > other.numValues)
  2392. values[--n] = 0;
  2393. while (--n >= 0)
  2394. values[n] &= other.values[n];
  2395. if (other.highestBit < highestBit)
  2396. highestBit = other.highestBit;
  2397. highestBit = getHighestBit();
  2398. return *this;
  2399. }
  2400. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2401. {
  2402. // this operation will only work with the absolute values
  2403. jassert (isNegative() == other.isNegative());
  2404. if (other.highestBit >= 0)
  2405. {
  2406. ensureSize (other.highestBit >> 5);
  2407. int n = (other.highestBit >> 5) + 1;
  2408. while (--n >= 0)
  2409. values[n] ^= other.values[n];
  2410. if (other.highestBit > highestBit)
  2411. highestBit = other.highestBit;
  2412. highestBit = getHighestBit();
  2413. }
  2414. return *this;
  2415. }
  2416. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2417. {
  2418. BigInteger remainder;
  2419. divideBy (divisor, remainder);
  2420. swapWith (remainder);
  2421. return *this;
  2422. }
  2423. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2424. {
  2425. shiftBits (numBitsToShift, 0);
  2426. return *this;
  2427. }
  2428. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2429. {
  2430. return operator<<= (-numBitsToShift);
  2431. }
  2432. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2433. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2434. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2435. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2436. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2437. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2438. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2439. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2440. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2441. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2442. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2443. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2444. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2445. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2446. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2447. int BigInteger::compare (const BigInteger& other) const throw()
  2448. {
  2449. if (isNegative() == other.isNegative())
  2450. {
  2451. const int absComp = compareAbsolute (other);
  2452. return isNegative() ? -absComp : absComp;
  2453. }
  2454. else
  2455. {
  2456. return isNegative() ? -1 : 1;
  2457. }
  2458. }
  2459. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2460. {
  2461. const int h1 = getHighestBit();
  2462. const int h2 = other.getHighestBit();
  2463. if (h1 > h2)
  2464. return 1;
  2465. else if (h1 < h2)
  2466. return -1;
  2467. for (int i = (h1 >> 5) + 1; --i >= 0;)
  2468. if (values[i] != other.values[i])
  2469. return (values[i] > other.values[i]) ? 1 : -1;
  2470. return 0;
  2471. }
  2472. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2473. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2474. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2475. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2476. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2477. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2478. void BigInteger::shiftBits (int bits, const int startBit)
  2479. {
  2480. if (highestBit < 0)
  2481. return;
  2482. if (startBit > 0)
  2483. {
  2484. if (bits < 0)
  2485. {
  2486. // right shift
  2487. for (int i = startBit; i <= highestBit; ++i)
  2488. setBit (i, operator[] (i - bits));
  2489. highestBit = getHighestBit();
  2490. }
  2491. else if (bits > 0)
  2492. {
  2493. // left shift
  2494. for (int i = highestBit + 1; --i >= startBit;)
  2495. setBit (i + bits, operator[] (i));
  2496. while (--bits >= 0)
  2497. clearBit (bits + startBit);
  2498. }
  2499. }
  2500. else
  2501. {
  2502. if (bits < 0)
  2503. {
  2504. // right shift
  2505. bits = -bits;
  2506. if (bits > highestBit)
  2507. {
  2508. clear();
  2509. }
  2510. else
  2511. {
  2512. const int wordsToMove = bits >> 5;
  2513. int top = 1 + (highestBit >> 5) - wordsToMove;
  2514. highestBit -= bits;
  2515. if (wordsToMove > 0)
  2516. {
  2517. int i;
  2518. for (i = 0; i < top; ++i)
  2519. values [i] = values [i + wordsToMove];
  2520. for (i = 0; i < wordsToMove; ++i)
  2521. values [top + i] = 0;
  2522. bits &= 31;
  2523. }
  2524. if (bits != 0)
  2525. {
  2526. const int invBits = 32 - bits;
  2527. --top;
  2528. for (int i = 0; i < top; ++i)
  2529. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2530. values[top] = (values[top] >> bits);
  2531. }
  2532. highestBit = getHighestBit();
  2533. }
  2534. }
  2535. else if (bits > 0)
  2536. {
  2537. // left shift
  2538. ensureSize (((highestBit + bits) >> 5) + 1);
  2539. const int wordsToMove = bits >> 5;
  2540. int top = 1 + (highestBit >> 5);
  2541. highestBit += bits;
  2542. if (wordsToMove > 0)
  2543. {
  2544. int i;
  2545. for (i = top; --i >= 0;)
  2546. values [i + wordsToMove] = values [i];
  2547. for (i = 0; i < wordsToMove; ++i)
  2548. values [i] = 0;
  2549. bits &= 31;
  2550. }
  2551. if (bits != 0)
  2552. {
  2553. const int invBits = 32 - bits;
  2554. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2555. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2556. values [wordsToMove] = values [wordsToMove] << bits;
  2557. }
  2558. highestBit = getHighestBit();
  2559. }
  2560. }
  2561. }
  2562. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2563. {
  2564. while (! m->isZero())
  2565. {
  2566. if (n->compareAbsolute (*m) > 0)
  2567. swapVariables (m, n);
  2568. *m -= *n;
  2569. }
  2570. return *n;
  2571. }
  2572. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2573. {
  2574. BigInteger m (*this);
  2575. while (! n.isZero())
  2576. {
  2577. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2578. return simpleGCD (&m, &n);
  2579. BigInteger temp1 (m), temp2;
  2580. temp1.divideBy (n, temp2);
  2581. m = n;
  2582. n = temp2;
  2583. }
  2584. return m;
  2585. }
  2586. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2587. {
  2588. BigInteger exp (exponent);
  2589. exp %= modulus;
  2590. BigInteger value (1);
  2591. swapWith (value);
  2592. value %= modulus;
  2593. while (! exp.isZero())
  2594. {
  2595. if (exp [0])
  2596. {
  2597. operator*= (value);
  2598. operator%= (modulus);
  2599. }
  2600. value *= value;
  2601. value %= modulus;
  2602. exp >>= 1;
  2603. }
  2604. }
  2605. void BigInteger::inverseModulo (const BigInteger& modulus)
  2606. {
  2607. if (modulus.isOne() || modulus.isNegative())
  2608. {
  2609. clear();
  2610. return;
  2611. }
  2612. if (isNegative() || compareAbsolute (modulus) >= 0)
  2613. operator%= (modulus);
  2614. if (isOne())
  2615. return;
  2616. if (! (*this)[0])
  2617. {
  2618. // not invertible
  2619. clear();
  2620. return;
  2621. }
  2622. BigInteger a1 (modulus);
  2623. BigInteger a2 (*this);
  2624. BigInteger b1 (modulus);
  2625. BigInteger b2 (1);
  2626. while (! a2.isOne())
  2627. {
  2628. BigInteger temp1, temp2, multiplier (a1);
  2629. multiplier.divideBy (a2, temp1);
  2630. temp1 = a2;
  2631. temp1 *= multiplier;
  2632. temp2 = a1;
  2633. temp2 -= temp1;
  2634. a1 = a2;
  2635. a2 = temp2;
  2636. temp1 = b2;
  2637. temp1 *= multiplier;
  2638. temp2 = b1;
  2639. temp2 -= temp1;
  2640. b1 = b2;
  2641. b2 = temp2;
  2642. }
  2643. while (b2.isNegative())
  2644. b2 += modulus;
  2645. b2 %= modulus;
  2646. swapWith (b2);
  2647. }
  2648. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2649. {
  2650. return stream << value.toString (10);
  2651. }
  2652. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2653. {
  2654. String s;
  2655. BigInteger v (*this);
  2656. if (base == 2 || base == 8 || base == 16)
  2657. {
  2658. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2659. static const char* const hexDigits = "0123456789abcdef";
  2660. for (;;)
  2661. {
  2662. const int remainder = v.getBitRangeAsInt (0, bits);
  2663. v >>= bits;
  2664. if (remainder == 0 && v.isZero())
  2665. break;
  2666. s = String::charToString (hexDigits [remainder]) + s;
  2667. }
  2668. }
  2669. else if (base == 10)
  2670. {
  2671. const BigInteger ten (10);
  2672. BigInteger remainder;
  2673. for (;;)
  2674. {
  2675. v.divideBy (ten, remainder);
  2676. if (remainder.isZero() && v.isZero())
  2677. break;
  2678. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2679. }
  2680. }
  2681. else
  2682. {
  2683. jassertfalse; // can't do the specified base!
  2684. return String::empty;
  2685. }
  2686. s = s.paddedLeft ('0', minimumNumCharacters);
  2687. return isNegative() ? "-" + s : s;
  2688. }
  2689. void BigInteger::parseString (const String& text, const int base)
  2690. {
  2691. clear();
  2692. const juce_wchar* t = text;
  2693. if (base == 2 || base == 8 || base == 16)
  2694. {
  2695. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2696. for (;;)
  2697. {
  2698. const juce_wchar c = *t++;
  2699. const int digit = CharacterFunctions::getHexDigitValue (c);
  2700. if (((unsigned int) digit) < (unsigned int) base)
  2701. {
  2702. operator<<= (bits);
  2703. operator+= (digit);
  2704. }
  2705. else if (c == 0)
  2706. {
  2707. break;
  2708. }
  2709. }
  2710. }
  2711. else if (base == 10)
  2712. {
  2713. const BigInteger ten ((unsigned int) 10);
  2714. for (;;)
  2715. {
  2716. const juce_wchar c = *t++;
  2717. if (c >= '0' && c <= '9')
  2718. {
  2719. operator*= (ten);
  2720. operator+= ((int) (c - '0'));
  2721. }
  2722. else if (c == 0)
  2723. {
  2724. break;
  2725. }
  2726. }
  2727. }
  2728. setNegative (text.trimStart().startsWithChar ('-'));
  2729. }
  2730. const MemoryBlock BigInteger::toMemoryBlock() const
  2731. {
  2732. const int numBytes = (getHighestBit() + 8) >> 3;
  2733. MemoryBlock mb ((size_t) numBytes);
  2734. for (int i = 0; i < numBytes; ++i)
  2735. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2736. return mb;
  2737. }
  2738. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2739. {
  2740. clear();
  2741. for (int i = (int) data.getSize(); --i >= 0;)
  2742. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2743. }
  2744. END_JUCE_NAMESPACE
  2745. /*** End of inlined file: juce_BigInteger.cpp ***/
  2746. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2747. BEGIN_JUCE_NAMESPACE
  2748. MemoryBlock::MemoryBlock() throw()
  2749. : size (0)
  2750. {
  2751. }
  2752. MemoryBlock::MemoryBlock (const size_t initialSize,
  2753. const bool initialiseToZero) throw()
  2754. {
  2755. if (initialSize > 0)
  2756. {
  2757. size = initialSize;
  2758. data.allocate (initialSize, initialiseToZero);
  2759. }
  2760. else
  2761. {
  2762. size = 0;
  2763. }
  2764. }
  2765. MemoryBlock::MemoryBlock (const MemoryBlock& other) throw()
  2766. : size (other.size)
  2767. {
  2768. if (size > 0)
  2769. {
  2770. jassert (other.data != 0);
  2771. data.malloc (size);
  2772. memcpy (data, other.data, size);
  2773. }
  2774. }
  2775. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom,
  2776. const size_t sizeInBytes) throw()
  2777. : size (jmax ((size_t) 0, sizeInBytes))
  2778. {
  2779. jassert (sizeInBytes >= 0);
  2780. if (size > 0)
  2781. {
  2782. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2783. data.malloc (size);
  2784. if (dataToInitialiseFrom != 0)
  2785. memcpy (data, dataToInitialiseFrom, size);
  2786. }
  2787. }
  2788. MemoryBlock::~MemoryBlock() throw()
  2789. {
  2790. jassert (size >= 0); // should never happen
  2791. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2792. }
  2793. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other) throw()
  2794. {
  2795. if (this != &other)
  2796. {
  2797. setSize (other.size, false);
  2798. memcpy (data, other.data, size);
  2799. }
  2800. return *this;
  2801. }
  2802. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2803. {
  2804. return matches (other.data, other.size);
  2805. }
  2806. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2807. {
  2808. return ! operator== (other);
  2809. }
  2810. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2811. {
  2812. return size == dataSize
  2813. && memcmp (data, dataToCompare, size) == 0;
  2814. }
  2815. // this will resize the block to this size
  2816. void MemoryBlock::setSize (const size_t newSize,
  2817. const bool initialiseToZero) throw()
  2818. {
  2819. if (size != newSize)
  2820. {
  2821. if (newSize <= 0)
  2822. {
  2823. data.free();
  2824. size = 0;
  2825. }
  2826. else
  2827. {
  2828. if (data != 0)
  2829. {
  2830. data.realloc (newSize);
  2831. if (initialiseToZero && (newSize > size))
  2832. zeromem (data + size, newSize - size);
  2833. }
  2834. else
  2835. {
  2836. data.allocate (newSize, initialiseToZero);
  2837. }
  2838. size = newSize;
  2839. }
  2840. }
  2841. }
  2842. void MemoryBlock::ensureSize (const size_t minimumSize,
  2843. const bool initialiseToZero) throw()
  2844. {
  2845. if (size < minimumSize)
  2846. setSize (minimumSize, initialiseToZero);
  2847. }
  2848. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2849. {
  2850. swapVariables (size, other.size);
  2851. data.swapWith (other.data);
  2852. }
  2853. void MemoryBlock::fillWith (const uint8 value) throw()
  2854. {
  2855. memset (data, (int) value, size);
  2856. }
  2857. void MemoryBlock::append (const void* const srcData,
  2858. const size_t numBytes) throw()
  2859. {
  2860. if (numBytes > 0)
  2861. {
  2862. const size_t oldSize = size;
  2863. setSize (size + numBytes);
  2864. memcpy (data + oldSize, srcData, numBytes);
  2865. }
  2866. }
  2867. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2868. {
  2869. const char* d = static_cast<const char*> (src);
  2870. if (offset < 0)
  2871. {
  2872. d -= offset;
  2873. num -= offset;
  2874. offset = 0;
  2875. }
  2876. if (offset + num > size)
  2877. num = size - offset;
  2878. if (num > 0)
  2879. memcpy (data + offset, d, num);
  2880. }
  2881. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2882. {
  2883. char* d = static_cast<char*> (dst);
  2884. if (offset < 0)
  2885. {
  2886. zeromem (d, -offset);
  2887. d -= offset;
  2888. num += offset;
  2889. offset = 0;
  2890. }
  2891. if (offset + num > size)
  2892. {
  2893. const size_t newNum = size - offset;
  2894. zeromem (d + newNum, num - newNum);
  2895. num = newNum;
  2896. }
  2897. if (num > 0)
  2898. memcpy (d, data + offset, num);
  2899. }
  2900. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove) throw()
  2901. {
  2902. if (startByte < 0)
  2903. {
  2904. numBytesToRemove += startByte;
  2905. startByte = 0;
  2906. }
  2907. if (startByte + numBytesToRemove >= size)
  2908. {
  2909. setSize (startByte);
  2910. }
  2911. else if (numBytesToRemove > 0)
  2912. {
  2913. memmove (data + startByte,
  2914. data + startByte + numBytesToRemove,
  2915. size - (startByte + numBytesToRemove));
  2916. setSize (size - numBytesToRemove);
  2917. }
  2918. }
  2919. const String MemoryBlock::toString() const throw()
  2920. {
  2921. return String (static_cast <const char*> (getData()), size);
  2922. }
  2923. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2924. {
  2925. int res = 0;
  2926. size_t byte = bitRangeStart >> 3;
  2927. int offsetInByte = (int) bitRangeStart & 7;
  2928. size_t bitsSoFar = 0;
  2929. while (numBits > 0 && (size_t) byte < size)
  2930. {
  2931. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2932. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2933. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2934. bitsSoFar += bitsThisTime;
  2935. numBits -= bitsThisTime;
  2936. ++byte;
  2937. offsetInByte = 0;
  2938. }
  2939. return res;
  2940. }
  2941. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2942. {
  2943. size_t byte = bitRangeStart >> 3;
  2944. int offsetInByte = (int) bitRangeStart & 7;
  2945. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2946. while (numBits > 0 && (size_t) byte < size)
  2947. {
  2948. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2949. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2950. const unsigned int tempBits = bitsToSet << offsetInByte;
  2951. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2952. ++byte;
  2953. numBits -= bitsThisTime;
  2954. bitsToSet >>= bitsThisTime;
  2955. mask >>= bitsThisTime;
  2956. offsetInByte = 0;
  2957. }
  2958. }
  2959. void MemoryBlock::loadFromHexString (const String& hex) throw()
  2960. {
  2961. ensureSize (hex.length() >> 1);
  2962. char* dest = data;
  2963. int i = 0;
  2964. for (;;)
  2965. {
  2966. int byte = 0;
  2967. for (int loop = 2; --loop >= 0;)
  2968. {
  2969. byte <<= 4;
  2970. for (;;)
  2971. {
  2972. const juce_wchar c = hex [i++];
  2973. if (c >= '0' && c <= '9')
  2974. {
  2975. byte |= c - '0';
  2976. break;
  2977. }
  2978. else if (c >= 'a' && c <= 'z')
  2979. {
  2980. byte |= c - ('a' - 10);
  2981. break;
  2982. }
  2983. else if (c >= 'A' && c <= 'Z')
  2984. {
  2985. byte |= c - ('A' - 10);
  2986. break;
  2987. }
  2988. else if (c == 0)
  2989. {
  2990. setSize (static_cast <size_t> (dest - data));
  2991. return;
  2992. }
  2993. }
  2994. }
  2995. *dest++ = (char) byte;
  2996. }
  2997. }
  2998. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  2999. const String MemoryBlock::toBase64Encoding() const throw()
  3000. {
  3001. const size_t numChars = ((size << 3) + 5) / 6;
  3002. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3003. const int initialLen = destString.length();
  3004. destString.preallocateStorage (initialLen + 2 + numChars);
  3005. juce_wchar* d = destString;
  3006. d += initialLen;
  3007. *d++ = '.';
  3008. for (size_t i = 0; i < numChars; ++i)
  3009. *d++ = encodingTable [getBitRange (i * 6, 6)];
  3010. *d++ = 0;
  3011. return destString;
  3012. }
  3013. bool MemoryBlock::fromBase64Encoding (const String& s) throw()
  3014. {
  3015. const int startPos = s.indexOfChar ('.') + 1;
  3016. if (startPos <= 0)
  3017. return false;
  3018. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3019. setSize (numBytesNeeded, true);
  3020. const int numChars = s.length() - startPos;
  3021. const juce_wchar* srcChars = s;
  3022. srcChars += startPos;
  3023. int pos = 0;
  3024. for (int i = 0; i < numChars; ++i)
  3025. {
  3026. const char c = (char) srcChars[i];
  3027. for (int j = 0; j < 64; ++j)
  3028. {
  3029. if (encodingTable[j] == c)
  3030. {
  3031. setBitRange (pos, 6, j);
  3032. pos += 6;
  3033. break;
  3034. }
  3035. }
  3036. }
  3037. return true;
  3038. }
  3039. END_JUCE_NAMESPACE
  3040. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3041. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3042. BEGIN_JUCE_NAMESPACE
  3043. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames) throw()
  3044. : properties (ignoreCaseOfKeyNames),
  3045. fallbackProperties (0),
  3046. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3047. {
  3048. }
  3049. PropertySet::PropertySet (const PropertySet& other) throw()
  3050. : properties (other.properties),
  3051. fallbackProperties (other.fallbackProperties),
  3052. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3053. {
  3054. }
  3055. PropertySet& PropertySet::operator= (const PropertySet& other) throw()
  3056. {
  3057. properties = other.properties;
  3058. fallbackProperties = other.fallbackProperties;
  3059. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3060. propertyChanged();
  3061. return *this;
  3062. }
  3063. PropertySet::~PropertySet()
  3064. {
  3065. }
  3066. void PropertySet::clear()
  3067. {
  3068. const ScopedLock sl (lock);
  3069. if (properties.size() > 0)
  3070. {
  3071. properties.clear();
  3072. propertyChanged();
  3073. }
  3074. }
  3075. const String PropertySet::getValue (const String& keyName,
  3076. const String& defaultValue) const throw()
  3077. {
  3078. const ScopedLock sl (lock);
  3079. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3080. if (index >= 0)
  3081. return properties.getAllValues() [index];
  3082. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3083. : defaultValue;
  3084. }
  3085. int PropertySet::getIntValue (const String& keyName,
  3086. const int defaultValue) const throw()
  3087. {
  3088. const ScopedLock sl (lock);
  3089. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3090. if (index >= 0)
  3091. return properties.getAllValues() [index].getIntValue();
  3092. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3093. : defaultValue;
  3094. }
  3095. double PropertySet::getDoubleValue (const String& keyName,
  3096. const double defaultValue) const throw()
  3097. {
  3098. const ScopedLock sl (lock);
  3099. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3100. if (index >= 0)
  3101. return properties.getAllValues()[index].getDoubleValue();
  3102. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3103. : defaultValue;
  3104. }
  3105. bool PropertySet::getBoolValue (const String& keyName,
  3106. const bool defaultValue) const throw()
  3107. {
  3108. const ScopedLock sl (lock);
  3109. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3110. if (index >= 0)
  3111. return properties.getAllValues() [index].getIntValue() != 0;
  3112. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3113. : defaultValue;
  3114. }
  3115. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3116. {
  3117. XmlDocument doc (getValue (keyName));
  3118. return doc.getDocumentElement();
  3119. }
  3120. void PropertySet::setValue (const String& keyName,
  3121. const String& value) throw()
  3122. {
  3123. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3124. if (keyName.isNotEmpty())
  3125. {
  3126. const ScopedLock sl (lock);
  3127. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3128. if (index < 0 || properties.getAllValues() [index] != value)
  3129. {
  3130. properties.set (keyName, value);
  3131. propertyChanged();
  3132. }
  3133. }
  3134. }
  3135. void PropertySet::removeValue (const String& keyName) throw()
  3136. {
  3137. if (keyName.isNotEmpty())
  3138. {
  3139. const ScopedLock sl (lock);
  3140. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3141. if (index >= 0)
  3142. {
  3143. properties.remove (keyName);
  3144. propertyChanged();
  3145. }
  3146. }
  3147. }
  3148. void PropertySet::setValue (const String& keyName, const int value) throw()
  3149. {
  3150. setValue (keyName, String (value));
  3151. }
  3152. void PropertySet::setValue (const String& keyName, const double value) throw()
  3153. {
  3154. setValue (keyName, String (value));
  3155. }
  3156. void PropertySet::setValue (const String& keyName, const bool value) throw()
  3157. {
  3158. setValue (keyName, String (value ? "1" : "0"));
  3159. }
  3160. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3161. {
  3162. setValue (keyName, (xml == 0) ? String::empty
  3163. : xml->createDocument (String::empty, true));
  3164. }
  3165. bool PropertySet::containsKey (const String& keyName) const throw()
  3166. {
  3167. const ScopedLock sl (lock);
  3168. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3169. }
  3170. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3171. {
  3172. const ScopedLock sl (lock);
  3173. fallbackProperties = fallbackProperties_;
  3174. }
  3175. XmlElement* PropertySet::createXml (const String& nodeName) const throw()
  3176. {
  3177. const ScopedLock sl (lock);
  3178. XmlElement* const xml = new XmlElement (nodeName);
  3179. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3180. {
  3181. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3182. e->setAttribute ("name", properties.getAllKeys()[i]);
  3183. e->setAttribute ("val", properties.getAllValues()[i]);
  3184. }
  3185. return xml;
  3186. }
  3187. void PropertySet::restoreFromXml (const XmlElement& xml) throw()
  3188. {
  3189. const ScopedLock sl (lock);
  3190. clear();
  3191. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3192. {
  3193. if (e->hasAttribute ("name")
  3194. && e->hasAttribute ("val"))
  3195. {
  3196. properties.set (e->getStringAttribute ("name"),
  3197. e->getStringAttribute ("val"));
  3198. }
  3199. }
  3200. if (properties.size() > 0)
  3201. propertyChanged();
  3202. }
  3203. void PropertySet::propertyChanged()
  3204. {
  3205. }
  3206. END_JUCE_NAMESPACE
  3207. /*** End of inlined file: juce_PropertySet.cpp ***/
  3208. /*** Start of inlined file: juce_Identifier.cpp ***/
  3209. BEGIN_JUCE_NAMESPACE
  3210. StringPool& Identifier::getPool()
  3211. {
  3212. static StringPool pool;
  3213. return pool;
  3214. }
  3215. Identifier::Identifier() throw()
  3216. : name (0)
  3217. {
  3218. }
  3219. Identifier::Identifier (const Identifier& other) throw()
  3220. : name (other.name)
  3221. {
  3222. }
  3223. Identifier& Identifier::operator= (const Identifier& other) throw()
  3224. {
  3225. name = other.name;
  3226. return *this;
  3227. }
  3228. Identifier::Identifier (const String& name_)
  3229. : name (Identifier::getPool().getPooledString (name_))
  3230. {
  3231. /* An Identifier string must be suitable for use as a script variable or XML
  3232. attribute, so it can only contain this limited set of characters.. */
  3233. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3234. }
  3235. Identifier::Identifier (const char* const name_)
  3236. : name (Identifier::getPool().getPooledString (name_))
  3237. {
  3238. /* An Identifier string must be suitable for use as a script variable or XML
  3239. attribute, so it can only contain this limited set of characters.. */
  3240. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3241. }
  3242. Identifier::~Identifier()
  3243. {
  3244. }
  3245. END_JUCE_NAMESPACE
  3246. /*** End of inlined file: juce_Identifier.cpp ***/
  3247. /*** Start of inlined file: juce_Variant.cpp ***/
  3248. BEGIN_JUCE_NAMESPACE
  3249. class var::VariantType
  3250. {
  3251. public:
  3252. VariantType() {}
  3253. virtual ~VariantType() {}
  3254. virtual int toInt (const ValueUnion&) const { return 0; }
  3255. virtual double toDouble (const ValueUnion&) const { return 0; }
  3256. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3257. virtual bool toBool (const ValueUnion&) const { return false; }
  3258. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3259. virtual bool isVoid() const throw() { return false; }
  3260. virtual bool isInt() const throw() { return false; }
  3261. virtual bool isBool() const throw() { return false; }
  3262. virtual bool isDouble() const throw() { return false; }
  3263. virtual bool isString() const throw() { return false; }
  3264. virtual bool isObject() const throw() { return false; }
  3265. virtual bool isMethod() const throw() { return false; }
  3266. virtual void cleanUp (ValueUnion&) const throw() {}
  3267. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3268. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3269. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3270. };
  3271. class var::VariantType_Void : public var::VariantType
  3272. {
  3273. public:
  3274. static const VariantType_Void* getInstance() { static const VariantType_Void i; return &i; }
  3275. bool isVoid() const throw() { return true; }
  3276. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3277. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3278. };
  3279. class var::VariantType_Int : public var::VariantType
  3280. {
  3281. public:
  3282. static const VariantType_Int* getInstance() { static const VariantType_Int i; return &i; }
  3283. int toInt (const ValueUnion& data) const { return data.intValue; };
  3284. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3285. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3286. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3287. bool isInt() const throw() { return true; }
  3288. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3289. {
  3290. return otherType.toInt (otherData) == data.intValue;
  3291. }
  3292. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3293. {
  3294. output.writeCompressedInt (5);
  3295. output.writeByte (1);
  3296. output.writeInt (data.intValue);
  3297. }
  3298. };
  3299. class var::VariantType_Double : public var::VariantType
  3300. {
  3301. public:
  3302. static const VariantType_Double* getInstance() { static const VariantType_Double i; return &i; }
  3303. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3304. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3305. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3306. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3307. bool isDouble() const throw() { return true; }
  3308. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3309. {
  3310. return otherType.toDouble (otherData) == data.doubleValue;
  3311. }
  3312. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3313. {
  3314. output.writeCompressedInt (9);
  3315. output.writeByte (4);
  3316. output.writeDouble (data.doubleValue);
  3317. }
  3318. };
  3319. class var::VariantType_Bool : public var::VariantType
  3320. {
  3321. public:
  3322. static const VariantType_Bool* getInstance() { static const VariantType_Bool i; return &i; }
  3323. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3324. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3325. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3326. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3327. bool isBool() const throw() { return true; }
  3328. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3329. {
  3330. return otherType.toBool (otherData) == data.boolValue;
  3331. }
  3332. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3333. {
  3334. output.writeCompressedInt (1);
  3335. output.writeByte (data.boolValue ? 2 : 3);
  3336. }
  3337. };
  3338. class var::VariantType_String : public var::VariantType
  3339. {
  3340. public:
  3341. static const VariantType_String* getInstance() { static const VariantType_String i; return &i; }
  3342. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3343. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3344. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3345. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3346. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3347. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3348. || data.stringValue->trim().equalsIgnoreCase ("true")
  3349. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3350. bool isString() const throw() { return true; }
  3351. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3352. {
  3353. return otherType.toString (otherData) == *data.stringValue;
  3354. }
  3355. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3356. {
  3357. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3358. output.writeCompressedInt (len + 1);
  3359. output.writeByte (5);
  3360. HeapBlock<char> temp (len);
  3361. data.stringValue->copyToUTF8 (temp, len);
  3362. output.write (temp, len);
  3363. }
  3364. };
  3365. class var::VariantType_Object : public var::VariantType
  3366. {
  3367. public:
  3368. static const VariantType_Object* getInstance() { static const VariantType_Object i; return &i; }
  3369. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3370. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3371. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3372. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3373. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3374. bool isObject() const throw() { return true; }
  3375. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3376. {
  3377. return otherType.toObject (otherData) == data.objectValue;
  3378. }
  3379. void writeToStream (const ValueUnion&, OutputStream& output) const
  3380. {
  3381. jassertfalse; // Can't write an object to a stream!
  3382. output.writeCompressedInt (0);
  3383. }
  3384. };
  3385. class var::VariantType_Method : public var::VariantType
  3386. {
  3387. public:
  3388. static const VariantType_Method* getInstance() { static const VariantType_Method i; return &i; }
  3389. const String toString (const ValueUnion&) const { return "Method"; }
  3390. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3391. bool isMethod() const throw() { return true; }
  3392. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3393. {
  3394. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3395. }
  3396. void writeToStream (const ValueUnion&, OutputStream& output) const
  3397. {
  3398. jassertfalse; // Can't write a method to a stream!
  3399. output.writeCompressedInt (0);
  3400. }
  3401. };
  3402. var::var() throw()
  3403. : type (VariantType_Void::getInstance())
  3404. {
  3405. }
  3406. var::~var() throw()
  3407. {
  3408. type->cleanUp (value);
  3409. }
  3410. const var var::null;
  3411. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3412. {
  3413. type->createCopy (value, valueToCopy.value);
  3414. }
  3415. var::var (const int value_) throw() : type (VariantType_Int::getInstance())
  3416. {
  3417. value.intValue = value_;
  3418. }
  3419. var::var (const bool value_) throw() : type (VariantType_Bool::getInstance())
  3420. {
  3421. value.boolValue = value_;
  3422. }
  3423. var::var (const double value_) throw() : type (VariantType_Double::getInstance())
  3424. {
  3425. value.doubleValue = value_;
  3426. }
  3427. var::var (const String& value_) : type (VariantType_String::getInstance())
  3428. {
  3429. value.stringValue = new String (value_);
  3430. }
  3431. var::var (const char* const value_) : type (VariantType_String::getInstance())
  3432. {
  3433. value.stringValue = new String (value_);
  3434. }
  3435. var::var (const juce_wchar* const value_) : type (VariantType_String::getInstance())
  3436. {
  3437. value.stringValue = new String (value_);
  3438. }
  3439. var::var (DynamicObject* const object) : type (VariantType_Object::getInstance())
  3440. {
  3441. value.objectValue = object;
  3442. if (object != 0)
  3443. object->incReferenceCount();
  3444. }
  3445. var::var (MethodFunction method_) throw() : type (VariantType_Method::getInstance())
  3446. {
  3447. value.methodValue = method_;
  3448. }
  3449. bool var::isVoid() const throw() { return type->isVoid(); }
  3450. bool var::isInt() const throw() { return type->isInt(); }
  3451. bool var::isBool() const throw() { return type->isBool(); }
  3452. bool var::isDouble() const throw() { return type->isDouble(); }
  3453. bool var::isString() const throw() { return type->isString(); }
  3454. bool var::isObject() const throw() { return type->isObject(); }
  3455. bool var::isMethod() const throw() { return type->isMethod(); }
  3456. var::operator int() const { return type->toInt (value); }
  3457. var::operator bool() const { return type->toBool (value); }
  3458. var::operator float() const { return (float) type->toDouble (value); }
  3459. var::operator double() const { return type->toDouble (value); }
  3460. const String var::toString() const { return type->toString (value); }
  3461. var::operator const String() const { return type->toString (value); }
  3462. DynamicObject* var::getObject() const { return type->toObject (value); }
  3463. void var::swapWith (var& other) throw()
  3464. {
  3465. swapVariables (type, other.type);
  3466. swapVariables (value, other.value);
  3467. }
  3468. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3469. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3470. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3471. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3472. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3473. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3474. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3475. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3476. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3477. bool var::equals (const var& other) const throw()
  3478. {
  3479. return type->equals (value, other.value, *other.type);
  3480. }
  3481. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3482. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3483. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3484. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3485. void var::writeToStream (OutputStream& output) const
  3486. {
  3487. type->writeToStream (value, output);
  3488. }
  3489. const var var::readFromStream (InputStream& input)
  3490. {
  3491. const int numBytes = input.readCompressedInt();
  3492. if (numBytes > 0)
  3493. {
  3494. switch (input.readByte())
  3495. {
  3496. case 1: return var (input.readInt());
  3497. case 2: return var (true);
  3498. case 3: return var (false);
  3499. case 4: return var (input.readDouble());
  3500. case 5:
  3501. {
  3502. MemoryOutputStream mo;
  3503. mo.writeFromInputStream (input, numBytes - 1);
  3504. return var (mo.toUTF8());
  3505. }
  3506. default: input.skipNextBytes (numBytes - 1); break;
  3507. }
  3508. }
  3509. return var::null;
  3510. }
  3511. const var var::operator[] (const Identifier& propertyName) const
  3512. {
  3513. DynamicObject* const o = getObject();
  3514. return o != 0 ? o->getProperty (propertyName) : var::null;
  3515. }
  3516. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3517. {
  3518. DynamicObject* const o = getObject();
  3519. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3520. }
  3521. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3522. {
  3523. if (isMethod())
  3524. {
  3525. DynamicObject* const target = targetObject.getObject();
  3526. if (target != 0)
  3527. return (target->*(value.methodValue)) (arguments, numArguments);
  3528. }
  3529. return var::null;
  3530. }
  3531. const var var::call (const Identifier& method) const
  3532. {
  3533. return invoke (method, 0, 0);
  3534. }
  3535. const var var::call (const Identifier& method, const var& arg1) const
  3536. {
  3537. return invoke (method, &arg1, 1);
  3538. }
  3539. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3540. {
  3541. var args[] = { arg1, arg2 };
  3542. return invoke (method, args, 2);
  3543. }
  3544. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3545. {
  3546. var args[] = { arg1, arg2, arg3 };
  3547. return invoke (method, args, 3);
  3548. }
  3549. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3550. {
  3551. var args[] = { arg1, arg2, arg3, arg4 };
  3552. return invoke (method, args, 4);
  3553. }
  3554. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3555. {
  3556. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3557. return invoke (method, args, 5);
  3558. }
  3559. END_JUCE_NAMESPACE
  3560. /*** End of inlined file: juce_Variant.cpp ***/
  3561. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3562. BEGIN_JUCE_NAMESPACE
  3563. NamedValueSet::NamedValue::NamedValue() throw()
  3564. {
  3565. }
  3566. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3567. : name (name_), value (value_)
  3568. {
  3569. }
  3570. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3571. {
  3572. return name == other.name && value == other.value;
  3573. }
  3574. NamedValueSet::NamedValueSet() throw()
  3575. {
  3576. }
  3577. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3578. : values (other.values)
  3579. {
  3580. }
  3581. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3582. {
  3583. values = other.values;
  3584. return *this;
  3585. }
  3586. NamedValueSet::~NamedValueSet()
  3587. {
  3588. }
  3589. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3590. {
  3591. return values == other.values;
  3592. }
  3593. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3594. {
  3595. return ! operator== (other);
  3596. }
  3597. int NamedValueSet::size() const throw()
  3598. {
  3599. return values.size();
  3600. }
  3601. const var& NamedValueSet::operator[] (const Identifier& name) const
  3602. {
  3603. for (int i = values.size(); --i >= 0;)
  3604. {
  3605. const NamedValue& v = values.getReference(i);
  3606. if (v.name == name)
  3607. return v.value;
  3608. }
  3609. return var::null;
  3610. }
  3611. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3612. {
  3613. const var* v = getItem (name);
  3614. return v != 0 ? *v : defaultReturnValue;
  3615. }
  3616. var* NamedValueSet::getItem (const Identifier& name) const
  3617. {
  3618. for (int i = values.size(); --i >= 0;)
  3619. {
  3620. NamedValue& v = values.getReference(i);
  3621. if (v.name == name)
  3622. return &(v.value);
  3623. }
  3624. return 0;
  3625. }
  3626. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3627. {
  3628. for (int i = values.size(); --i >= 0;)
  3629. {
  3630. NamedValue& v = values.getReference(i);
  3631. if (v.name == name)
  3632. {
  3633. if (v.value == newValue)
  3634. return false;
  3635. v.value = newValue;
  3636. return true;
  3637. }
  3638. }
  3639. values.add (NamedValue (name, newValue));
  3640. return true;
  3641. }
  3642. bool NamedValueSet::contains (const Identifier& name) const
  3643. {
  3644. return getItem (name) != 0;
  3645. }
  3646. bool NamedValueSet::remove (const Identifier& name)
  3647. {
  3648. for (int i = values.size(); --i >= 0;)
  3649. {
  3650. if (values.getReference(i).name == name)
  3651. {
  3652. values.remove (i);
  3653. return true;
  3654. }
  3655. }
  3656. return false;
  3657. }
  3658. const Identifier NamedValueSet::getName (const int index) const
  3659. {
  3660. jassert (((unsigned int) index) < (unsigned int) values.size());
  3661. return values [index].name;
  3662. }
  3663. const var NamedValueSet::getValueAt (const int index) const
  3664. {
  3665. jassert (((unsigned int) index) < (unsigned int) values.size());
  3666. return values [index].value;
  3667. }
  3668. void NamedValueSet::clear()
  3669. {
  3670. values.clear();
  3671. }
  3672. END_JUCE_NAMESPACE
  3673. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3674. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3675. BEGIN_JUCE_NAMESPACE
  3676. DynamicObject::DynamicObject()
  3677. {
  3678. }
  3679. DynamicObject::~DynamicObject()
  3680. {
  3681. }
  3682. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3683. {
  3684. var* const v = properties.getItem (propertyName);
  3685. return v != 0 && ! v->isMethod();
  3686. }
  3687. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3688. {
  3689. return properties [propertyName];
  3690. }
  3691. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3692. {
  3693. properties.set (propertyName, newValue);
  3694. }
  3695. void DynamicObject::removeProperty (const Identifier& propertyName)
  3696. {
  3697. properties.remove (propertyName);
  3698. }
  3699. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3700. {
  3701. return getProperty (methodName).isMethod();
  3702. }
  3703. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3704. const var* parameters,
  3705. int numParameters)
  3706. {
  3707. return properties [methodName].invoke (var (this), parameters, numParameters);
  3708. }
  3709. void DynamicObject::setMethod (const Identifier& name,
  3710. var::MethodFunction methodFunction)
  3711. {
  3712. properties.set (name, var (methodFunction));
  3713. }
  3714. void DynamicObject::clear()
  3715. {
  3716. properties.clear();
  3717. }
  3718. END_JUCE_NAMESPACE
  3719. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3720. /*** Start of inlined file: juce_BlowFish.cpp ***/
  3721. BEGIN_JUCE_NAMESPACE
  3722. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  3723. {
  3724. jassert (keyData != 0);
  3725. jassert (keyBytes > 0);
  3726. static const uint32 initialPValues [18] =
  3727. {
  3728. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  3729. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  3730. 0x9216d5d9, 0x8979fb1b
  3731. };
  3732. static const uint32 initialSValues [4 * 256] =
  3733. {
  3734. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  3735. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  3736. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  3737. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  3738. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  3739. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  3740. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  3741. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  3742. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  3743. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  3744. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  3745. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  3746. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  3747. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  3748. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  3749. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  3750. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  3751. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  3752. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  3753. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  3754. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  3755. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  3756. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  3757. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  3758. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  3759. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  3760. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  3761. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  3762. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  3763. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  3764. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  3765. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  3766. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  3767. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  3768. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  3769. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  3770. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  3771. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  3772. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  3773. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  3774. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  3775. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  3776. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  3777. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  3778. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  3779. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  3780. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  3781. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  3782. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  3783. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  3784. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  3785. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  3786. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  3787. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  3788. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  3789. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  3790. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  3791. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  3792. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  3793. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  3794. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  3795. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  3796. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  3797. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  3798. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  3799. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  3800. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  3801. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  3802. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  3803. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  3804. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  3805. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  3806. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  3807. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  3808. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  3809. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  3810. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  3811. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  3812. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  3813. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  3814. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  3815. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  3816. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  3817. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  3818. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  3819. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  3820. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  3821. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  3822. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  3823. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  3824. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  3825. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  3826. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  3827. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  3828. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  3829. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  3830. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  3831. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  3832. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  3833. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  3834. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  3835. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  3836. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  3837. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  3838. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  3839. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  3840. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  3841. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  3842. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  3843. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  3844. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  3845. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  3846. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  3847. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  3848. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  3849. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  3850. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  3851. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  3852. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  3853. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  3854. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  3855. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  3856. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  3857. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  3858. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  3859. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  3860. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  3861. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  3862. };
  3863. memcpy (p, initialPValues, sizeof (p));
  3864. int i, j = 0;
  3865. for (i = 4; --i >= 0;)
  3866. {
  3867. s[i].malloc (256);
  3868. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  3869. }
  3870. for (i = 0; i < 18; ++i)
  3871. {
  3872. uint32 d = 0;
  3873. for (int k = 0; k < 4; ++k)
  3874. {
  3875. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  3876. if (++j >= keyBytes)
  3877. j = 0;
  3878. }
  3879. p[i] = initialPValues[i] ^ d;
  3880. }
  3881. uint32 l = 0, r = 0;
  3882. for (i = 0; i < 18; i += 2)
  3883. {
  3884. encrypt (l, r);
  3885. p[i] = l;
  3886. p[i + 1] = r;
  3887. }
  3888. for (i = 0; i < 4; ++i)
  3889. {
  3890. for (j = 0; j < 256; j += 2)
  3891. {
  3892. encrypt (l, r);
  3893. s[i][j] = l;
  3894. s[i][j + 1] = r;
  3895. }
  3896. }
  3897. }
  3898. BlowFish::BlowFish (const BlowFish& other)
  3899. {
  3900. for (int i = 4; --i >= 0;)
  3901. s[i].malloc (256);
  3902. operator= (other);
  3903. }
  3904. BlowFish& BlowFish::operator= (const BlowFish& other)
  3905. {
  3906. memcpy (p, other.p, sizeof (p));
  3907. for (int i = 4; --i >= 0;)
  3908. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  3909. return *this;
  3910. }
  3911. BlowFish::~BlowFish()
  3912. {
  3913. }
  3914. uint32 BlowFish::F (const uint32 x) const throw()
  3915. {
  3916. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  3917. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  3918. }
  3919. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  3920. {
  3921. uint32 l = data1;
  3922. uint32 r = data2;
  3923. for (int i = 0; i < 16; ++i)
  3924. {
  3925. l ^= p[i];
  3926. r ^= F(l);
  3927. swapVariables (l, r);
  3928. }
  3929. data1 = r ^ p[17];
  3930. data2 = l ^ p[16];
  3931. }
  3932. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  3933. {
  3934. uint32 l = data1;
  3935. uint32 r = data2;
  3936. for (int i = 17; i > 1; --i)
  3937. {
  3938. l ^= p[i];
  3939. r ^= F(l);
  3940. swapVariables (l, r);
  3941. }
  3942. data1 = r ^ p[0];
  3943. data2 = l ^ p[1];
  3944. }
  3945. END_JUCE_NAMESPACE
  3946. /*** End of inlined file: juce_BlowFish.cpp ***/
  3947. /*** Start of inlined file: juce_MD5.cpp ***/
  3948. BEGIN_JUCE_NAMESPACE
  3949. MD5::MD5()
  3950. {
  3951. zerostruct (result);
  3952. }
  3953. MD5::MD5 (const MD5& other)
  3954. {
  3955. memcpy (result, other.result, sizeof (result));
  3956. }
  3957. MD5& MD5::operator= (const MD5& other)
  3958. {
  3959. memcpy (result, other.result, sizeof (result));
  3960. return *this;
  3961. }
  3962. MD5::MD5 (const MemoryBlock& data)
  3963. {
  3964. ProcessContext context;
  3965. context.processBlock (data.getData(), data.getSize());
  3966. context.finish (result);
  3967. }
  3968. MD5::MD5 (const void* data, const size_t numBytes)
  3969. {
  3970. ProcessContext context;
  3971. context.processBlock (data, numBytes);
  3972. context.finish (result);
  3973. }
  3974. MD5::MD5 (const String& text)
  3975. {
  3976. ProcessContext context;
  3977. const int len = text.length();
  3978. const juce_wchar* const t = text;
  3979. for (int i = 0; i < len; ++i)
  3980. {
  3981. // force the string into integer-sized unicode characters, to try to make it
  3982. // get the same results on all platforms + compilers.
  3983. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  3984. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  3985. }
  3986. context.finish (result);
  3987. }
  3988. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  3989. {
  3990. ProcessContext context;
  3991. if (numBytesToRead < 0)
  3992. numBytesToRead = std::numeric_limits<int64>::max();
  3993. while (numBytesToRead > 0)
  3994. {
  3995. uint8 tempBuffer [512];
  3996. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  3997. if (bytesRead <= 0)
  3998. break;
  3999. numBytesToRead -= bytesRead;
  4000. context.processBlock (tempBuffer, bytesRead);
  4001. }
  4002. context.finish (result);
  4003. }
  4004. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4005. {
  4006. processStream (input, numBytesToRead);
  4007. }
  4008. MD5::MD5 (const File& file)
  4009. {
  4010. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4011. if (fin != 0)
  4012. processStream (*fin, -1);
  4013. else
  4014. zerostruct (result);
  4015. }
  4016. MD5::~MD5()
  4017. {
  4018. }
  4019. namespace MD5Functions
  4020. {
  4021. static void encode (void* const output, const void* const input, const int numBytes) throw()
  4022. {
  4023. for (int i = 0; i < (numBytes >> 2); ++i)
  4024. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4025. }
  4026. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4027. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4028. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4029. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4030. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4031. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4032. {
  4033. a += F (b, c, d) + x + ac;
  4034. a = rotateLeft (a, s) + b;
  4035. }
  4036. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4037. {
  4038. a += G (b, c, d) + x + ac;
  4039. a = rotateLeft (a, s) + b;
  4040. }
  4041. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4042. {
  4043. a += H (b, c, d) + x + ac;
  4044. a = rotateLeft (a, s) + b;
  4045. }
  4046. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4047. {
  4048. a += I (b, c, d) + x + ac;
  4049. a = rotateLeft (a, s) + b;
  4050. }
  4051. }
  4052. MD5::ProcessContext::ProcessContext()
  4053. {
  4054. state[0] = 0x67452301;
  4055. state[1] = 0xefcdab89;
  4056. state[2] = 0x98badcfe;
  4057. state[3] = 0x10325476;
  4058. count[0] = 0;
  4059. count[1] = 0;
  4060. }
  4061. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4062. {
  4063. int bufferPos = ((count[0] >> 3) & 0x3F);
  4064. count[0] += (uint32) (dataSize << 3);
  4065. if (count[0] < ((uint32) dataSize << 3))
  4066. count[1]++;
  4067. count[1] += (uint32) (dataSize >> 29);
  4068. const size_t spaceLeft = 64 - bufferPos;
  4069. size_t i = 0;
  4070. if (dataSize >= spaceLeft)
  4071. {
  4072. memcpy (buffer + bufferPos, data, spaceLeft);
  4073. transform (buffer);
  4074. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4075. transform (static_cast <const char*> (data) + i);
  4076. bufferPos = 0;
  4077. }
  4078. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4079. }
  4080. void MD5::ProcessContext::finish (void* const result)
  4081. {
  4082. unsigned char encodedLength[8];
  4083. MD5Functions::encode (encodedLength, count, 8);
  4084. // Pad out to 56 mod 64.
  4085. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4086. const int paddingLength = (index < 56) ? (56 - index)
  4087. : (120 - index);
  4088. uint8 paddingBuffer [64];
  4089. zeromem (paddingBuffer, paddingLength);
  4090. paddingBuffer [0] = 0x80;
  4091. processBlock (paddingBuffer, paddingLength);
  4092. processBlock (encodedLength, 8);
  4093. MD5Functions::encode (result, state, 16);
  4094. zerostruct (buffer);
  4095. }
  4096. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4097. {
  4098. using namespace MD5Functions;
  4099. uint32 a = state[0];
  4100. uint32 b = state[1];
  4101. uint32 c = state[2];
  4102. uint32 d = state[3];
  4103. uint32 x[16];
  4104. encode (x, bufferToTransform, 64);
  4105. enum Constants
  4106. {
  4107. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4108. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4109. };
  4110. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4111. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4112. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4113. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4114. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4115. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4116. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4117. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4118. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4119. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4120. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4121. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4122. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4123. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4124. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4125. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4126. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4127. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4128. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4129. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4130. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4131. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4132. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4133. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4134. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4135. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4136. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4137. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4138. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4139. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4140. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4141. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4142. state[0] += a;
  4143. state[1] += b;
  4144. state[2] += c;
  4145. state[3] += d;
  4146. zerostruct (x);
  4147. }
  4148. const MemoryBlock MD5::getRawChecksumData() const
  4149. {
  4150. return MemoryBlock (result, sizeof (result));
  4151. }
  4152. const String MD5::toHexString() const
  4153. {
  4154. return String::toHexString (result, sizeof (result), 0);
  4155. }
  4156. bool MD5::operator== (const MD5& other) const
  4157. {
  4158. return memcmp (result, other.result, sizeof (result)) == 0;
  4159. }
  4160. bool MD5::operator!= (const MD5& other) const
  4161. {
  4162. return ! operator== (other);
  4163. }
  4164. END_JUCE_NAMESPACE
  4165. /*** End of inlined file: juce_MD5.cpp ***/
  4166. /*** Start of inlined file: juce_Primes.cpp ***/
  4167. BEGIN_JUCE_NAMESPACE
  4168. namespace PrimesHelpers
  4169. {
  4170. static void createSmallSieve (const int numBits, BigInteger& result)
  4171. {
  4172. result.setBit (numBits);
  4173. result.clearBit (numBits); // to enlarge the array
  4174. result.setBit (0);
  4175. int n = 2;
  4176. do
  4177. {
  4178. for (int i = n + n; i < numBits; i += n)
  4179. result.setBit (i);
  4180. n = result.findNextClearBit (n + 1);
  4181. }
  4182. while (n <= (numBits >> 1));
  4183. }
  4184. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  4185. const BigInteger& smallSieve, const int smallSieveSize)
  4186. {
  4187. jassert (! base[0]); // must be even!
  4188. result.setBit (numBits);
  4189. result.clearBit (numBits); // to enlarge the array
  4190. int index = smallSieve.findNextClearBit (0);
  4191. do
  4192. {
  4193. const int prime = (index << 1) + 1;
  4194. BigInteger r (base), remainder;
  4195. r.divideBy (prime, remainder);
  4196. int i = prime - remainder.getBitRangeAsInt (0, 32);
  4197. if (r.isZero())
  4198. i += prime;
  4199. if ((i & 1) == 0)
  4200. i += prime;
  4201. i = (i - 1) >> 1;
  4202. while (i < numBits)
  4203. {
  4204. result.setBit (i);
  4205. i += prime;
  4206. }
  4207. index = smallSieve.findNextClearBit (index + 1);
  4208. }
  4209. while (index < smallSieveSize);
  4210. }
  4211. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  4212. const int numBits, BigInteger& result, const int certainty)
  4213. {
  4214. for (int i = 0; i < numBits; ++i)
  4215. {
  4216. if (! sieve[i])
  4217. {
  4218. result = base + (unsigned int) ((i << 1) + 1);
  4219. if (Primes::isProbablyPrime (result, certainty))
  4220. return true;
  4221. }
  4222. }
  4223. return false;
  4224. }
  4225. static bool passesMillerRabin (const BigInteger& n, int iterations)
  4226. {
  4227. const BigInteger one (1), two (2);
  4228. const BigInteger nMinusOne (n - one);
  4229. BigInteger d (nMinusOne);
  4230. const int s = d.findNextSetBit (0);
  4231. d >>= s;
  4232. BigInteger smallPrimes;
  4233. int numBitsInSmallPrimes = 0;
  4234. for (;;)
  4235. {
  4236. numBitsInSmallPrimes += 256;
  4237. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  4238. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  4239. if (numPrimesFound > iterations + 1)
  4240. break;
  4241. }
  4242. int smallPrime = 2;
  4243. while (--iterations >= 0)
  4244. {
  4245. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  4246. BigInteger r (smallPrime);
  4247. r.exponentModulo (d, n);
  4248. if (r != one && r != nMinusOne)
  4249. {
  4250. for (int j = 0; j < s; ++j)
  4251. {
  4252. r.exponentModulo (two, n);
  4253. if (r == nMinusOne)
  4254. break;
  4255. }
  4256. if (r != nMinusOne)
  4257. return false;
  4258. }
  4259. }
  4260. return true;
  4261. }
  4262. }
  4263. const BigInteger Primes::createProbablePrime (const int bitLength,
  4264. const int certainty,
  4265. const int* randomSeeds,
  4266. int numRandomSeeds)
  4267. {
  4268. using namespace PrimesHelpers;
  4269. int defaultSeeds [16];
  4270. if (numRandomSeeds <= 0)
  4271. {
  4272. randomSeeds = defaultSeeds;
  4273. numRandomSeeds = numElementsInArray (defaultSeeds);
  4274. Random r (0);
  4275. for (int j = 10; --j >= 0;)
  4276. {
  4277. r.setSeedRandomly();
  4278. for (int i = numRandomSeeds; --i >= 0;)
  4279. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  4280. }
  4281. }
  4282. BigInteger smallSieve;
  4283. const int smallSieveSize = 15000;
  4284. createSmallSieve (smallSieveSize, smallSieve);
  4285. BigInteger p;
  4286. for (int i = numRandomSeeds; --i >= 0;)
  4287. {
  4288. BigInteger p2;
  4289. Random r (randomSeeds[i]);
  4290. r.fillBitsRandomly (p2, 0, bitLength);
  4291. p ^= p2;
  4292. }
  4293. p.setBit (bitLength - 1);
  4294. p.clearBit (0);
  4295. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  4296. while (p.getHighestBit() < bitLength)
  4297. {
  4298. p += 2 * searchLen;
  4299. BigInteger sieve;
  4300. bigSieve (p, searchLen, sieve,
  4301. smallSieve, smallSieveSize);
  4302. BigInteger candidate;
  4303. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  4304. return candidate;
  4305. }
  4306. jassertfalse;
  4307. return BigInteger();
  4308. }
  4309. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  4310. {
  4311. using namespace PrimesHelpers;
  4312. if (! number[0])
  4313. return false;
  4314. if (number.getHighestBit() <= 10)
  4315. {
  4316. const int num = number.getBitRangeAsInt (0, 10);
  4317. for (int i = num / 2; --i > 1;)
  4318. if (num % i == 0)
  4319. return false;
  4320. return true;
  4321. }
  4322. else
  4323. {
  4324. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  4325. return false;
  4326. return passesMillerRabin (number, certainty);
  4327. }
  4328. }
  4329. END_JUCE_NAMESPACE
  4330. /*** End of inlined file: juce_Primes.cpp ***/
  4331. /*** Start of inlined file: juce_RSAKey.cpp ***/
  4332. BEGIN_JUCE_NAMESPACE
  4333. RSAKey::RSAKey()
  4334. {
  4335. }
  4336. RSAKey::RSAKey (const String& s)
  4337. {
  4338. if (s.containsChar (','))
  4339. {
  4340. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  4341. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  4342. }
  4343. else
  4344. {
  4345. // the string needs to be two hex numbers, comma-separated..
  4346. jassertfalse;
  4347. }
  4348. }
  4349. RSAKey::~RSAKey()
  4350. {
  4351. }
  4352. bool RSAKey::operator== (const RSAKey& other) const throw()
  4353. {
  4354. return part1 == other.part1 && part2 == other.part2;
  4355. }
  4356. bool RSAKey::operator!= (const RSAKey& other) const throw()
  4357. {
  4358. return ! operator== (other);
  4359. }
  4360. const String RSAKey::toString() const
  4361. {
  4362. return part1.toString (16) + "," + part2.toString (16);
  4363. }
  4364. bool RSAKey::applyToValue (BigInteger& value) const
  4365. {
  4366. if (part1.isZero() || part2.isZero() || value <= 0)
  4367. {
  4368. jassertfalse; // using an uninitialised key
  4369. value.clear();
  4370. return false;
  4371. }
  4372. BigInteger result;
  4373. while (! value.isZero())
  4374. {
  4375. result *= part2;
  4376. BigInteger remainder;
  4377. value.divideBy (part2, remainder);
  4378. remainder.exponentModulo (part1, part2);
  4379. result += remainder;
  4380. }
  4381. value.swapWith (result);
  4382. return true;
  4383. }
  4384. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  4385. {
  4386. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  4387. // are fast to divide + multiply
  4388. for (int i = 2; i <= 65536; i *= 2)
  4389. {
  4390. const BigInteger e (1 + i);
  4391. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  4392. return e;
  4393. }
  4394. BigInteger e (4);
  4395. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  4396. ++e;
  4397. return e;
  4398. }
  4399. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  4400. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  4401. {
  4402. jassert (numBits > 16); // not much point using less than this..
  4403. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  4404. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  4405. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  4406. const BigInteger n (p * q);
  4407. const BigInteger m (--p * --q);
  4408. const BigInteger e (findBestCommonDivisor (p, q));
  4409. BigInteger d (e);
  4410. d.inverseModulo (m);
  4411. publicKey.part1 = e;
  4412. publicKey.part2 = n;
  4413. privateKey.part1 = d;
  4414. privateKey.part2 = n;
  4415. }
  4416. END_JUCE_NAMESPACE
  4417. /*** End of inlined file: juce_RSAKey.cpp ***/
  4418. /*** Start of inlined file: juce_InputStream.cpp ***/
  4419. BEGIN_JUCE_NAMESPACE
  4420. char InputStream::readByte()
  4421. {
  4422. char temp = 0;
  4423. read (&temp, 1);
  4424. return temp;
  4425. }
  4426. bool InputStream::readBool()
  4427. {
  4428. return readByte() != 0;
  4429. }
  4430. short InputStream::readShort()
  4431. {
  4432. char temp[2];
  4433. if (read (temp, 2) == 2)
  4434. return (short) ByteOrder::littleEndianShort (temp);
  4435. return 0;
  4436. }
  4437. short InputStream::readShortBigEndian()
  4438. {
  4439. char temp[2];
  4440. if (read (temp, 2) == 2)
  4441. return (short) ByteOrder::bigEndianShort (temp);
  4442. return 0;
  4443. }
  4444. int InputStream::readInt()
  4445. {
  4446. char temp[4];
  4447. if (read (temp, 4) == 4)
  4448. return (int) ByteOrder::littleEndianInt (temp);
  4449. return 0;
  4450. }
  4451. int InputStream::readIntBigEndian()
  4452. {
  4453. char temp[4];
  4454. if (read (temp, 4) == 4)
  4455. return (int) ByteOrder::bigEndianInt (temp);
  4456. return 0;
  4457. }
  4458. int InputStream::readCompressedInt()
  4459. {
  4460. const unsigned char sizeByte = readByte();
  4461. if (sizeByte == 0)
  4462. return 0;
  4463. const int numBytes = (sizeByte & 0x7f);
  4464. if (numBytes > 4)
  4465. {
  4466. jassertfalse; // trying to read corrupt data - this method must only be used
  4467. // to read data that was written by OutputStream::writeCompressedInt()
  4468. return 0;
  4469. }
  4470. char bytes[4] = { 0, 0, 0, 0 };
  4471. if (read (bytes, numBytes) != numBytes)
  4472. return 0;
  4473. const int num = (int) ByteOrder::littleEndianInt (bytes);
  4474. return (sizeByte >> 7) ? -num : num;
  4475. }
  4476. int64 InputStream::readInt64()
  4477. {
  4478. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4479. if (read (n.asBytes, 8) == 8)
  4480. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  4481. return 0;
  4482. }
  4483. int64 InputStream::readInt64BigEndian()
  4484. {
  4485. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4486. if (read (n.asBytes, 8) == 8)
  4487. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  4488. return 0;
  4489. }
  4490. float InputStream::readFloat()
  4491. {
  4492. // the union below relies on these types being the same size...
  4493. static_jassert (sizeof (int32) == sizeof (float));
  4494. union { int32 asInt; float asFloat; } n;
  4495. n.asInt = (int32) readInt();
  4496. return n.asFloat;
  4497. }
  4498. float InputStream::readFloatBigEndian()
  4499. {
  4500. union { int32 asInt; float asFloat; } n;
  4501. n.asInt = (int32) readIntBigEndian();
  4502. return n.asFloat;
  4503. }
  4504. double InputStream::readDouble()
  4505. {
  4506. union { int64 asInt; double asDouble; } n;
  4507. n.asInt = readInt64();
  4508. return n.asDouble;
  4509. }
  4510. double InputStream::readDoubleBigEndian()
  4511. {
  4512. union { int64 asInt; double asDouble; } n;
  4513. n.asInt = readInt64BigEndian();
  4514. return n.asDouble;
  4515. }
  4516. const String InputStream::readString()
  4517. {
  4518. MemoryBlock buffer (256);
  4519. char* data = static_cast<char*> (buffer.getData());
  4520. size_t i = 0;
  4521. while ((data[i] = readByte()) != 0)
  4522. {
  4523. if (++i >= buffer.getSize())
  4524. {
  4525. buffer.setSize (buffer.getSize() + 512);
  4526. data = static_cast<char*> (buffer.getData());
  4527. }
  4528. }
  4529. return String::fromUTF8 (data, (int) i);
  4530. }
  4531. const String InputStream::readNextLine()
  4532. {
  4533. MemoryBlock buffer (256);
  4534. char* data = static_cast<char*> (buffer.getData());
  4535. size_t i = 0;
  4536. while ((data[i] = readByte()) != 0)
  4537. {
  4538. if (data[i] == '\n')
  4539. break;
  4540. if (data[i] == '\r')
  4541. {
  4542. const int64 lastPos = getPosition();
  4543. if (readByte() != '\n')
  4544. setPosition (lastPos);
  4545. break;
  4546. }
  4547. if (++i >= buffer.getSize())
  4548. {
  4549. buffer.setSize (buffer.getSize() + 512);
  4550. data = static_cast<char*> (buffer.getData());
  4551. }
  4552. }
  4553. return String::fromUTF8 (data, (int) i);
  4554. }
  4555. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  4556. {
  4557. MemoryOutputStream mo (block, true);
  4558. return mo.writeFromInputStream (*this, numBytes);
  4559. }
  4560. const String InputStream::readEntireStreamAsString()
  4561. {
  4562. MemoryOutputStream mo;
  4563. mo.writeFromInputStream (*this, -1);
  4564. return mo.toString();
  4565. }
  4566. void InputStream::skipNextBytes (int64 numBytesToSkip)
  4567. {
  4568. if (numBytesToSkip > 0)
  4569. {
  4570. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  4571. HeapBlock<char> temp (skipBufferSize);
  4572. while (numBytesToSkip > 0 && ! isExhausted())
  4573. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  4574. }
  4575. }
  4576. END_JUCE_NAMESPACE
  4577. /*** End of inlined file: juce_InputStream.cpp ***/
  4578. /*** Start of inlined file: juce_OutputStream.cpp ***/
  4579. BEGIN_JUCE_NAMESPACE
  4580. #if JUCE_DEBUG
  4581. static CriticalSection activeStreamLock;
  4582. static Array<void*> activeStreams;
  4583. void juce_CheckForDanglingStreams()
  4584. {
  4585. /*
  4586. It's always a bad idea to leak any object, but if you're leaking output
  4587. streams, then there's a good chance that you're failing to flush a file
  4588. to disk properly, which could result in corrupted data and other similar
  4589. nastiness..
  4590. */
  4591. jassert (activeStreams.size() == 0);
  4592. };
  4593. #endif
  4594. OutputStream::OutputStream()
  4595. {
  4596. #if JUCE_DEBUG
  4597. const ScopedLock sl (activeStreamLock);
  4598. activeStreams.add (this);
  4599. #endif
  4600. }
  4601. OutputStream::~OutputStream()
  4602. {
  4603. #if JUCE_DEBUG
  4604. const ScopedLock sl (activeStreamLock);
  4605. activeStreams.removeValue (this);
  4606. #endif
  4607. }
  4608. void OutputStream::writeBool (const bool b)
  4609. {
  4610. writeByte (b ? (char) 1
  4611. : (char) 0);
  4612. }
  4613. void OutputStream::writeByte (char byte)
  4614. {
  4615. write (&byte, 1);
  4616. }
  4617. void OutputStream::writeShort (short value)
  4618. {
  4619. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  4620. write (&v, 2);
  4621. }
  4622. void OutputStream::writeShortBigEndian (short value)
  4623. {
  4624. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  4625. write (&v, 2);
  4626. }
  4627. void OutputStream::writeInt (int value)
  4628. {
  4629. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  4630. write (&v, 4);
  4631. }
  4632. void OutputStream::writeIntBigEndian (int value)
  4633. {
  4634. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  4635. write (&v, 4);
  4636. }
  4637. void OutputStream::writeCompressedInt (int value)
  4638. {
  4639. unsigned int un = (value < 0) ? (unsigned int) -value
  4640. : (unsigned int) value;
  4641. uint8 data[5];
  4642. int num = 0;
  4643. while (un > 0)
  4644. {
  4645. data[++num] = (uint8) un;
  4646. un >>= 8;
  4647. }
  4648. data[0] = (uint8) num;
  4649. if (value < 0)
  4650. data[0] |= 0x80;
  4651. write (data, num + 1);
  4652. }
  4653. void OutputStream::writeInt64 (int64 value)
  4654. {
  4655. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  4656. write (&v, 8);
  4657. }
  4658. void OutputStream::writeInt64BigEndian (int64 value)
  4659. {
  4660. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  4661. write (&v, 8);
  4662. }
  4663. void OutputStream::writeFloat (float value)
  4664. {
  4665. union { int asInt; float asFloat; } n;
  4666. n.asFloat = value;
  4667. writeInt (n.asInt);
  4668. }
  4669. void OutputStream::writeFloatBigEndian (float value)
  4670. {
  4671. union { int asInt; float asFloat; } n;
  4672. n.asFloat = value;
  4673. writeIntBigEndian (n.asInt);
  4674. }
  4675. void OutputStream::writeDouble (double value)
  4676. {
  4677. union { int64 asInt; double asDouble; } n;
  4678. n.asDouble = value;
  4679. writeInt64 (n.asInt);
  4680. }
  4681. void OutputStream::writeDoubleBigEndian (double value)
  4682. {
  4683. union { int64 asInt; double asDouble; } n;
  4684. n.asDouble = value;
  4685. writeInt64BigEndian (n.asInt);
  4686. }
  4687. void OutputStream::writeString (const String& text)
  4688. {
  4689. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  4690. // if lots of large, persistent strings were to be written to streams).
  4691. const int numBytes = text.getNumBytesAsUTF8() + 1;
  4692. HeapBlock<char> temp (numBytes);
  4693. text.copyToUTF8 (temp, numBytes);
  4694. write (temp, numBytes);
  4695. }
  4696. void OutputStream::writeText (const String& text, const bool asUnicode,
  4697. const bool writeUnicodeHeaderBytes)
  4698. {
  4699. if (asUnicode)
  4700. {
  4701. if (writeUnicodeHeaderBytes)
  4702. write ("\x0ff\x0fe", 2);
  4703. const juce_wchar* src = text;
  4704. bool lastCharWasReturn = false;
  4705. while (*src != 0)
  4706. {
  4707. if (*src == L'\n' && ! lastCharWasReturn)
  4708. writeShort ((short) L'\r');
  4709. lastCharWasReturn = (*src == L'\r');
  4710. writeShort ((short) *src++);
  4711. }
  4712. }
  4713. else
  4714. {
  4715. const char* src = text.toUTF8();
  4716. const char* t = src;
  4717. for (;;)
  4718. {
  4719. if (*t == '\n')
  4720. {
  4721. if (t > src)
  4722. write (src, (int) (t - src));
  4723. write ("\r\n", 2);
  4724. src = t + 1;
  4725. }
  4726. else if (*t == '\r')
  4727. {
  4728. if (t[1] == '\n')
  4729. ++t;
  4730. }
  4731. else if (*t == 0)
  4732. {
  4733. if (t > src)
  4734. write (src, (int) (t - src));
  4735. break;
  4736. }
  4737. ++t;
  4738. }
  4739. }
  4740. }
  4741. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  4742. {
  4743. if (numBytesToWrite < 0)
  4744. numBytesToWrite = std::numeric_limits<int64>::max();
  4745. int numWritten = 0;
  4746. while (numBytesToWrite > 0 && ! source.isExhausted())
  4747. {
  4748. char buffer [8192];
  4749. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  4750. if (num <= 0)
  4751. break;
  4752. write (buffer, num);
  4753. numBytesToWrite -= num;
  4754. numWritten += num;
  4755. }
  4756. return numWritten;
  4757. }
  4758. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  4759. {
  4760. return stream << String (number);
  4761. }
  4762. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  4763. {
  4764. return stream << String (number);
  4765. }
  4766. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  4767. {
  4768. stream.writeByte (character);
  4769. return stream;
  4770. }
  4771. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  4772. {
  4773. stream.write (text, (int) strlen (text));
  4774. return stream;
  4775. }
  4776. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  4777. {
  4778. stream.write (data.getData(), (int) data.getSize());
  4779. return stream;
  4780. }
  4781. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  4782. {
  4783. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  4784. if (in != 0)
  4785. stream.writeFromInputStream (*in, -1);
  4786. return stream;
  4787. }
  4788. END_JUCE_NAMESPACE
  4789. /*** End of inlined file: juce_OutputStream.cpp ***/
  4790. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  4791. BEGIN_JUCE_NAMESPACE
  4792. DirectoryIterator::DirectoryIterator (const File& directory,
  4793. bool isRecursive_,
  4794. const String& wildCard_,
  4795. const int whatToLookFor_)
  4796. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  4797. wildCard (wildCard_),
  4798. path (File::addTrailingSeparator (directory.getFullPathName())),
  4799. index (-1),
  4800. totalNumFiles (-1),
  4801. whatToLookFor (whatToLookFor_),
  4802. isRecursive (isRecursive_)
  4803. {
  4804. // you have to specify the type of files you're looking for!
  4805. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  4806. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  4807. }
  4808. DirectoryIterator::~DirectoryIterator()
  4809. {
  4810. }
  4811. bool DirectoryIterator::next()
  4812. {
  4813. return next (0, 0, 0, 0, 0, 0);
  4814. }
  4815. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  4816. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  4817. {
  4818. if (subIterator != 0)
  4819. {
  4820. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  4821. return true;
  4822. subIterator = 0;
  4823. }
  4824. String filename;
  4825. bool isDirectory, isHidden;
  4826. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  4827. {
  4828. ++index;
  4829. if (! filename.containsOnly ("."))
  4830. {
  4831. const File fileFound (path + filename, 0);
  4832. bool matches = false;
  4833. if (isDirectory)
  4834. {
  4835. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  4836. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  4837. matches = (whatToLookFor & File::findDirectories) != 0;
  4838. }
  4839. else
  4840. {
  4841. matches = (whatToLookFor & File::findFiles) != 0;
  4842. }
  4843. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  4844. if (matches && isRecursive)
  4845. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  4846. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  4847. matches = ! isHidden;
  4848. if (matches)
  4849. {
  4850. currentFile = fileFound;
  4851. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  4852. if (isDirResult != 0) *isDirResult = isDirectory;
  4853. return true;
  4854. }
  4855. else if (subIterator != 0)
  4856. {
  4857. return next();
  4858. }
  4859. }
  4860. }
  4861. return false;
  4862. }
  4863. const File DirectoryIterator::getFile() const
  4864. {
  4865. if (subIterator != 0)
  4866. return subIterator->getFile();
  4867. return currentFile;
  4868. }
  4869. float DirectoryIterator::getEstimatedProgress() const
  4870. {
  4871. if (totalNumFiles < 0)
  4872. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  4873. if (totalNumFiles <= 0)
  4874. return 0.0f;
  4875. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  4876. : (float) index;
  4877. return detailedIndex / totalNumFiles;
  4878. }
  4879. END_JUCE_NAMESPACE
  4880. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  4881. /*** Start of inlined file: juce_File.cpp ***/
  4882. #if ! JUCE_WINDOWS
  4883. #include <pwd.h>
  4884. #endif
  4885. BEGIN_JUCE_NAMESPACE
  4886. File::File (const String& fullPathName)
  4887. : fullPath (parseAbsolutePath (fullPathName))
  4888. {
  4889. }
  4890. File::File (const String& path, int)
  4891. : fullPath (path)
  4892. {
  4893. }
  4894. const File File::createFileWithoutCheckingPath (const String& path)
  4895. {
  4896. return File (path, 0);
  4897. }
  4898. File::File (const File& other)
  4899. : fullPath (other.fullPath)
  4900. {
  4901. }
  4902. File& File::operator= (const String& newPath)
  4903. {
  4904. fullPath = parseAbsolutePath (newPath);
  4905. return *this;
  4906. }
  4907. File& File::operator= (const File& other)
  4908. {
  4909. fullPath = other.fullPath;
  4910. return *this;
  4911. }
  4912. const File File::nonexistent;
  4913. const String File::parseAbsolutePath (const String& p)
  4914. {
  4915. if (p.isEmpty())
  4916. return String::empty;
  4917. #if JUCE_WINDOWS
  4918. // Windows..
  4919. String path (p.replaceCharacter ('/', '\\'));
  4920. if (path.startsWithChar (File::separator))
  4921. {
  4922. if (path[1] != File::separator)
  4923. {
  4924. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4925. If you're trying to parse a string that may be either a relative path or an absolute path,
  4926. you MUST provide a context against which the partial path can be evaluated - you can do
  4927. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4928. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4929. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4930. */
  4931. jassertfalse;
  4932. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  4933. }
  4934. }
  4935. else if (! path.containsChar (':'))
  4936. {
  4937. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4938. If you're trying to parse a string that may be either a relative path or an absolute path,
  4939. you MUST provide a context against which the partial path can be evaluated - you can do
  4940. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4941. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4942. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4943. */
  4944. jassertfalse;
  4945. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4946. }
  4947. #else
  4948. // Mac or Linux..
  4949. String path (p.replaceCharacter ('\\', '/'));
  4950. if (path.startsWithChar ('~'))
  4951. {
  4952. if (path[1] == File::separator || path[1] == 0)
  4953. {
  4954. // expand a name of the form "~/abc"
  4955. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  4956. + path.substring (1);
  4957. }
  4958. else
  4959. {
  4960. // expand a name of type "~dave/abc"
  4961. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  4962. struct passwd* const pw = getpwnam (userName.toUTF8());
  4963. if (pw != 0)
  4964. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  4965. }
  4966. }
  4967. else if (! path.startsWithChar (File::separator))
  4968. {
  4969. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4970. If you're trying to parse a string that may be either a relative path or an absolute path,
  4971. you MUST provide a context against which the partial path can be evaluated - you can do
  4972. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4973. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4974. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4975. */
  4976. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  4977. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4978. }
  4979. #endif
  4980. return path.trimCharactersAtEnd (separatorString);
  4981. }
  4982. const String File::addTrailingSeparator (const String& path)
  4983. {
  4984. return path.endsWithChar (File::separator) ? path
  4985. : path + File::separator;
  4986. }
  4987. #if JUCE_LINUX
  4988. #define NAMES_ARE_CASE_SENSITIVE 1
  4989. #endif
  4990. bool File::areFileNamesCaseSensitive()
  4991. {
  4992. #if NAMES_ARE_CASE_SENSITIVE
  4993. return true;
  4994. #else
  4995. return false;
  4996. #endif
  4997. }
  4998. bool File::operator== (const File& other) const
  4999. {
  5000. #if NAMES_ARE_CASE_SENSITIVE
  5001. return fullPath == other.fullPath;
  5002. #else
  5003. return fullPath.equalsIgnoreCase (other.fullPath);
  5004. #endif
  5005. }
  5006. bool File::operator!= (const File& other) const
  5007. {
  5008. return ! operator== (other);
  5009. }
  5010. bool File::operator< (const File& other) const
  5011. {
  5012. #if NAMES_ARE_CASE_SENSITIVE
  5013. return fullPath < other.fullPath;
  5014. #else
  5015. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5016. #endif
  5017. }
  5018. bool File::operator> (const File& other) const
  5019. {
  5020. #if NAMES_ARE_CASE_SENSITIVE
  5021. return fullPath > other.fullPath;
  5022. #else
  5023. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5024. #endif
  5025. }
  5026. bool File::setReadOnly (const bool shouldBeReadOnly,
  5027. const bool applyRecursively) const
  5028. {
  5029. bool worked = true;
  5030. if (applyRecursively && isDirectory())
  5031. {
  5032. Array <File> subFiles;
  5033. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5034. for (int i = subFiles.size(); --i >= 0;)
  5035. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5036. }
  5037. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5038. }
  5039. bool File::deleteRecursively() const
  5040. {
  5041. bool worked = true;
  5042. if (isDirectory())
  5043. {
  5044. Array<File> subFiles;
  5045. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5046. for (int i = subFiles.size(); --i >= 0;)
  5047. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5048. }
  5049. return deleteFile() && worked;
  5050. }
  5051. bool File::moveFileTo (const File& newFile) const
  5052. {
  5053. if (newFile.fullPath == fullPath)
  5054. return true;
  5055. #if ! NAMES_ARE_CASE_SENSITIVE
  5056. if (*this != newFile)
  5057. #endif
  5058. if (! newFile.deleteFile())
  5059. return false;
  5060. return moveInternal (newFile);
  5061. }
  5062. bool File::copyFileTo (const File& newFile) const
  5063. {
  5064. return (*this == newFile)
  5065. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5066. }
  5067. bool File::copyDirectoryTo (const File& newDirectory) const
  5068. {
  5069. if (isDirectory() && newDirectory.createDirectory())
  5070. {
  5071. Array<File> subFiles;
  5072. findChildFiles (subFiles, File::findFiles, false);
  5073. int i;
  5074. for (i = 0; i < subFiles.size(); ++i)
  5075. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5076. return false;
  5077. subFiles.clear();
  5078. findChildFiles (subFiles, File::findDirectories, false);
  5079. for (i = 0; i < subFiles.size(); ++i)
  5080. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5081. return false;
  5082. return true;
  5083. }
  5084. return false;
  5085. }
  5086. const String File::getPathUpToLastSlash() const
  5087. {
  5088. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5089. if (lastSlash > 0)
  5090. return fullPath.substring (0, lastSlash);
  5091. else if (lastSlash == 0)
  5092. return separatorString;
  5093. else
  5094. return fullPath;
  5095. }
  5096. const File File::getParentDirectory() const
  5097. {
  5098. return File (getPathUpToLastSlash(), (int) 0);
  5099. }
  5100. const String File::getFileName() const
  5101. {
  5102. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5103. }
  5104. int File::hashCode() const
  5105. {
  5106. return fullPath.hashCode();
  5107. }
  5108. int64 File::hashCode64() const
  5109. {
  5110. return fullPath.hashCode64();
  5111. }
  5112. const String File::getFileNameWithoutExtension() const
  5113. {
  5114. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5115. const int lastDot = fullPath.lastIndexOfChar ('.');
  5116. if (lastDot > lastSlash)
  5117. return fullPath.substring (lastSlash, lastDot);
  5118. else
  5119. return fullPath.substring (lastSlash);
  5120. }
  5121. bool File::isAChildOf (const File& potentialParent) const
  5122. {
  5123. if (potentialParent == File::nonexistent)
  5124. return false;
  5125. const String ourPath (getPathUpToLastSlash());
  5126. #if NAMES_ARE_CASE_SENSITIVE
  5127. if (potentialParent.fullPath == ourPath)
  5128. #else
  5129. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5130. #endif
  5131. {
  5132. return true;
  5133. }
  5134. else if (potentialParent.fullPath.length() >= ourPath.length())
  5135. {
  5136. return false;
  5137. }
  5138. else
  5139. {
  5140. return getParentDirectory().isAChildOf (potentialParent);
  5141. }
  5142. }
  5143. bool File::isAbsolutePath (const String& path)
  5144. {
  5145. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5146. #if JUCE_WINDOWS
  5147. || (path.isNotEmpty() && path[1] == ':');
  5148. #else
  5149. || path.startsWithChar ('~');
  5150. #endif
  5151. }
  5152. const File File::getChildFile (String relativePath) const
  5153. {
  5154. if (isAbsolutePath (relativePath))
  5155. {
  5156. // the path is really absolute..
  5157. return File (relativePath);
  5158. }
  5159. else
  5160. {
  5161. // it's relative, so remove any ../ or ./ bits at the start.
  5162. String path (fullPath);
  5163. if (relativePath[0] == '.')
  5164. {
  5165. #if JUCE_WINDOWS
  5166. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  5167. #else
  5168. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  5169. #endif
  5170. while (relativePath[0] == '.')
  5171. {
  5172. if (relativePath[1] == '.')
  5173. {
  5174. if (relativePath [2] == 0 || relativePath[2] == separator)
  5175. {
  5176. const int lastSlash = path.lastIndexOfChar (separator);
  5177. if (lastSlash >= 0)
  5178. path = path.substring (0, lastSlash);
  5179. relativePath = relativePath.substring (3);
  5180. }
  5181. else
  5182. {
  5183. break;
  5184. }
  5185. }
  5186. else if (relativePath[1] == separator)
  5187. {
  5188. relativePath = relativePath.substring (2);
  5189. }
  5190. else
  5191. {
  5192. break;
  5193. }
  5194. }
  5195. }
  5196. return File (addTrailingSeparator (path) + relativePath);
  5197. }
  5198. }
  5199. const File File::getSiblingFile (const String& fileName) const
  5200. {
  5201. return getParentDirectory().getChildFile (fileName);
  5202. }
  5203. const String File::descriptionOfSizeInBytes (const int64 bytes)
  5204. {
  5205. if (bytes == 1)
  5206. {
  5207. return "1 byte";
  5208. }
  5209. else if (bytes < 1024)
  5210. {
  5211. return String ((int) bytes) + " bytes";
  5212. }
  5213. else if (bytes < 1024 * 1024)
  5214. {
  5215. return String (bytes / 1024.0, 1) + " KB";
  5216. }
  5217. else if (bytes < 1024 * 1024 * 1024)
  5218. {
  5219. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  5220. }
  5221. else
  5222. {
  5223. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  5224. }
  5225. }
  5226. bool File::create() const
  5227. {
  5228. if (exists())
  5229. return true;
  5230. {
  5231. const File parentDir (getParentDirectory());
  5232. if (parentDir == *this || ! parentDir.createDirectory())
  5233. return false;
  5234. FileOutputStream fo (*this, 8);
  5235. }
  5236. return exists();
  5237. }
  5238. bool File::createDirectory() const
  5239. {
  5240. if (! isDirectory())
  5241. {
  5242. const File parentDir (getParentDirectory());
  5243. if (parentDir == *this || ! parentDir.createDirectory())
  5244. return false;
  5245. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  5246. return isDirectory();
  5247. }
  5248. return true;
  5249. }
  5250. const Time File::getCreationTime() const
  5251. {
  5252. int64 m, a, c;
  5253. getFileTimesInternal (m, a, c);
  5254. return Time (c);
  5255. }
  5256. const Time File::getLastModificationTime() const
  5257. {
  5258. int64 m, a, c;
  5259. getFileTimesInternal (m, a, c);
  5260. return Time (m);
  5261. }
  5262. const Time File::getLastAccessTime() const
  5263. {
  5264. int64 m, a, c;
  5265. getFileTimesInternal (m, a, c);
  5266. return Time (a);
  5267. }
  5268. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  5269. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  5270. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  5271. bool File::loadFileAsData (MemoryBlock& destBlock) const
  5272. {
  5273. if (! existsAsFile())
  5274. return false;
  5275. FileInputStream in (*this);
  5276. return getSize() == in.readIntoMemoryBlock (destBlock);
  5277. }
  5278. const String File::loadFileAsString() const
  5279. {
  5280. if (! existsAsFile())
  5281. return String::empty;
  5282. FileInputStream in (*this);
  5283. return in.readEntireStreamAsString();
  5284. }
  5285. bool File::fileTypeMatches (const int whatToLookFor, const bool isDir, const bool isHidden)
  5286. {
  5287. return (whatToLookFor & (isDir ? findDirectories
  5288. : findFiles)) != 0
  5289. && ((! isHidden) || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  5290. }
  5291. int File::findChildFiles (Array<File>& results,
  5292. const int whatToLookFor,
  5293. const bool searchRecursively,
  5294. const String& wildCardPattern) const
  5295. {
  5296. // you have to specify the type of files you're looking for!
  5297. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  5298. int total = 0;
  5299. if (isDirectory())
  5300. {
  5301. // find child files or directories in this directory first..
  5302. String path (addTrailingSeparator (fullPath)), filename;
  5303. bool itemIsDirectory, itemIsHidden;
  5304. DirectoryIterator::NativeIterator i (path, wildCardPattern);
  5305. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5306. {
  5307. if (! filename.containsOnly ("."))
  5308. {
  5309. const File fileFound (path + filename, 0);
  5310. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden))
  5311. {
  5312. results.add (fileFound);
  5313. ++total;
  5314. }
  5315. if (searchRecursively && itemIsDirectory
  5316. && fileTypeMatches (whatToLookFor | findDirectories, true, itemIsHidden))
  5317. {
  5318. total += fileFound.findChildFiles (results, whatToLookFor, true, wildCardPattern);
  5319. }
  5320. }
  5321. }
  5322. }
  5323. return total;
  5324. }
  5325. int File::getNumberOfChildFiles (const int whatToLookFor,
  5326. const String& wildCardPattern) const
  5327. {
  5328. // you have to specify the type of files you're looking for!
  5329. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  5330. int count = 0;
  5331. if (isDirectory())
  5332. {
  5333. String filename;
  5334. bool itemIsDirectory, itemIsHidden;
  5335. DirectoryIterator::NativeIterator i (*this, wildCardPattern);
  5336. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5337. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden)
  5338. && ! filename.containsOnly ("."))
  5339. ++count;
  5340. }
  5341. else
  5342. {
  5343. // trying to search for files inside a non-directory?
  5344. jassertfalse;
  5345. }
  5346. return count;
  5347. }
  5348. bool File::containsSubDirectories() const
  5349. {
  5350. if (isDirectory())
  5351. {
  5352. String filename;
  5353. bool itemIsDirectory;
  5354. DirectoryIterator::NativeIterator i (*this, "*");
  5355. while (i.next (filename, &itemIsDirectory, 0, 0, 0, 0, 0))
  5356. if (itemIsDirectory)
  5357. return true;
  5358. }
  5359. return false;
  5360. }
  5361. const File File::getNonexistentChildFile (const String& prefix_,
  5362. const String& suffix,
  5363. bool putNumbersInBrackets) const
  5364. {
  5365. File f (getChildFile (prefix_ + suffix));
  5366. if (f.exists())
  5367. {
  5368. int num = 2;
  5369. String prefix (prefix_);
  5370. // remove any bracketed numbers that may already be on the end..
  5371. if (prefix.trim().endsWithChar (')'))
  5372. {
  5373. putNumbersInBrackets = true;
  5374. const int openBracks = prefix.lastIndexOfChar ('(');
  5375. const int closeBracks = prefix.lastIndexOfChar (')');
  5376. if (openBracks > 0
  5377. && closeBracks > openBracks
  5378. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  5379. {
  5380. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  5381. prefix = prefix.substring (0, openBracks);
  5382. }
  5383. }
  5384. // also use brackets if it ends in a digit.
  5385. putNumbersInBrackets = putNumbersInBrackets
  5386. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  5387. do
  5388. {
  5389. if (putNumbersInBrackets)
  5390. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  5391. else
  5392. f = getChildFile (prefix + String (num++) + suffix);
  5393. } while (f.exists());
  5394. }
  5395. return f;
  5396. }
  5397. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  5398. {
  5399. if (exists())
  5400. {
  5401. return getParentDirectory()
  5402. .getNonexistentChildFile (getFileNameWithoutExtension(),
  5403. getFileExtension(),
  5404. putNumbersInBrackets);
  5405. }
  5406. else
  5407. {
  5408. return *this;
  5409. }
  5410. }
  5411. const String File::getFileExtension() const
  5412. {
  5413. String ext;
  5414. if (! isDirectory())
  5415. {
  5416. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  5417. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  5418. ext = fullPath.substring (indexOfDot);
  5419. }
  5420. return ext;
  5421. }
  5422. bool File::hasFileExtension (const String& possibleSuffix) const
  5423. {
  5424. if (possibleSuffix.isEmpty())
  5425. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  5426. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  5427. if (semicolon >= 0)
  5428. {
  5429. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  5430. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  5431. }
  5432. else
  5433. {
  5434. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  5435. {
  5436. if (possibleSuffix.startsWithChar ('.'))
  5437. return true;
  5438. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  5439. if (dotPos >= 0)
  5440. return fullPath [dotPos] == '.';
  5441. }
  5442. }
  5443. return false;
  5444. }
  5445. const File File::withFileExtension (const String& newExtension) const
  5446. {
  5447. if (fullPath.isEmpty())
  5448. return File::nonexistent;
  5449. String filePart (getFileName());
  5450. int i = filePart.lastIndexOfChar ('.');
  5451. if (i >= 0)
  5452. filePart = filePart.substring (0, i);
  5453. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  5454. filePart << '.';
  5455. return getSiblingFile (filePart + newExtension);
  5456. }
  5457. bool File::startAsProcess (const String& parameters) const
  5458. {
  5459. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  5460. }
  5461. FileInputStream* File::createInputStream() const
  5462. {
  5463. if (existsAsFile())
  5464. return new FileInputStream (*this);
  5465. return 0;
  5466. }
  5467. FileOutputStream* File::createOutputStream (const int bufferSize) const
  5468. {
  5469. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  5470. if (out->failedToOpen())
  5471. return 0;
  5472. return out.release();
  5473. }
  5474. bool File::appendData (const void* const dataToAppend,
  5475. const int numberOfBytes) const
  5476. {
  5477. if (numberOfBytes > 0)
  5478. {
  5479. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5480. if (out == 0)
  5481. return false;
  5482. out->write (dataToAppend, numberOfBytes);
  5483. }
  5484. return true;
  5485. }
  5486. bool File::replaceWithData (const void* const dataToWrite,
  5487. const int numberOfBytes) const
  5488. {
  5489. jassert (numberOfBytes >= 0); // a negative number of bytes??
  5490. if (numberOfBytes <= 0)
  5491. return deleteFile();
  5492. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5493. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  5494. return tempFile.overwriteTargetFileWithTemporary();
  5495. }
  5496. bool File::appendText (const String& text,
  5497. const bool asUnicode,
  5498. const bool writeUnicodeHeaderBytes) const
  5499. {
  5500. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5501. if (out != 0)
  5502. {
  5503. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  5504. return true;
  5505. }
  5506. return false;
  5507. }
  5508. bool File::replaceWithText (const String& textToWrite,
  5509. const bool asUnicode,
  5510. const bool writeUnicodeHeaderBytes) const
  5511. {
  5512. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5513. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  5514. return tempFile.overwriteTargetFileWithTemporary();
  5515. }
  5516. bool File::hasIdenticalContentTo (const File& other) const
  5517. {
  5518. if (other == *this)
  5519. return true;
  5520. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  5521. {
  5522. FileInputStream in1 (*this), in2 (other);
  5523. const int bufferSize = 4096;
  5524. HeapBlock <char> buffer1, buffer2;
  5525. buffer1.malloc (bufferSize);
  5526. buffer2.malloc (bufferSize);
  5527. for (;;)
  5528. {
  5529. const int num1 = in1.read (buffer1, bufferSize);
  5530. const int num2 = in2.read (buffer2, bufferSize);
  5531. if (num1 != num2)
  5532. break;
  5533. if (num1 <= 0)
  5534. return true;
  5535. if (memcmp (buffer1, buffer2, num1) != 0)
  5536. break;
  5537. }
  5538. }
  5539. return false;
  5540. }
  5541. const String File::createLegalPathName (const String& original)
  5542. {
  5543. String s (original);
  5544. String start;
  5545. if (s[1] == ':')
  5546. {
  5547. start = s.substring (0, 2);
  5548. s = s.substring (2);
  5549. }
  5550. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  5551. .substring (0, 1024);
  5552. }
  5553. const String File::createLegalFileName (const String& original)
  5554. {
  5555. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  5556. const int maxLength = 128; // only the length of the filename, not the whole path
  5557. const int len = s.length();
  5558. if (len > maxLength)
  5559. {
  5560. const int lastDot = s.lastIndexOfChar ('.');
  5561. if (lastDot > jmax (0, len - 12))
  5562. {
  5563. s = s.substring (0, maxLength - (len - lastDot))
  5564. + s.substring (lastDot);
  5565. }
  5566. else
  5567. {
  5568. s = s.substring (0, maxLength);
  5569. }
  5570. }
  5571. return s;
  5572. }
  5573. const String File::getRelativePathFrom (const File& dir) const
  5574. {
  5575. String thisPath (fullPath);
  5576. {
  5577. int len = thisPath.length();
  5578. while (--len >= 0 && thisPath [len] == File::separator)
  5579. thisPath [len] = 0;
  5580. }
  5581. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  5582. : dir.fullPath));
  5583. const int len = jmin (thisPath.length(), dirPath.length());
  5584. int commonBitLength = 0;
  5585. for (int i = 0; i < len; ++i)
  5586. {
  5587. #if NAMES_ARE_CASE_SENSITIVE
  5588. if (thisPath[i] != dirPath[i])
  5589. #else
  5590. if (CharacterFunctions::toLowerCase (thisPath[i])
  5591. != CharacterFunctions::toLowerCase (dirPath[i]))
  5592. #endif
  5593. {
  5594. break;
  5595. }
  5596. ++commonBitLength;
  5597. }
  5598. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  5599. --commonBitLength;
  5600. // if the only common bit is the root, then just return the full path..
  5601. if (commonBitLength <= 0
  5602. || (commonBitLength == 1 && thisPath [1] == File::separator))
  5603. return fullPath;
  5604. thisPath = thisPath.substring (commonBitLength);
  5605. dirPath = dirPath.substring (commonBitLength);
  5606. while (dirPath.isNotEmpty())
  5607. {
  5608. #if JUCE_WINDOWS
  5609. thisPath = "..\\" + thisPath;
  5610. #else
  5611. thisPath = "../" + thisPath;
  5612. #endif
  5613. const int sep = dirPath.indexOfChar (separator);
  5614. if (sep >= 0)
  5615. dirPath = dirPath.substring (sep + 1);
  5616. else
  5617. dirPath = String::empty;
  5618. }
  5619. return thisPath;
  5620. }
  5621. const File File::createTempFile (const String& fileNameEnding)
  5622. {
  5623. const File tempFile (getSpecialLocation (tempDirectory)
  5624. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  5625. .withFileExtension (fileNameEnding));
  5626. if (tempFile.exists())
  5627. return createTempFile (fileNameEnding);
  5628. else
  5629. return tempFile;
  5630. }
  5631. END_JUCE_NAMESPACE
  5632. /*** End of inlined file: juce_File.cpp ***/
  5633. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  5634. BEGIN_JUCE_NAMESPACE
  5635. void* juce_fileOpen (const File& file, bool forWriting);
  5636. void juce_fileClose (void* handle);
  5637. int juce_fileRead (void* handle, void* buffer, int size);
  5638. int64 juce_fileSetPosition (void* handle, int64 pos);
  5639. FileInputStream::FileInputStream (const File& f)
  5640. : file (f),
  5641. currentPosition (0),
  5642. needToSeek (true)
  5643. {
  5644. totalSize = f.getSize();
  5645. fileHandle = juce_fileOpen (f, false);
  5646. }
  5647. FileInputStream::~FileInputStream()
  5648. {
  5649. juce_fileClose (fileHandle);
  5650. }
  5651. int64 FileInputStream::getTotalLength()
  5652. {
  5653. return totalSize;
  5654. }
  5655. int FileInputStream::read (void* buffer, int bytesToRead)
  5656. {
  5657. int num = 0;
  5658. if (needToSeek)
  5659. {
  5660. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  5661. return 0;
  5662. needToSeek = false;
  5663. }
  5664. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  5665. currentPosition += num;
  5666. return num;
  5667. }
  5668. bool FileInputStream::isExhausted()
  5669. {
  5670. return currentPosition >= totalSize;
  5671. }
  5672. int64 FileInputStream::getPosition()
  5673. {
  5674. return currentPosition;
  5675. }
  5676. bool FileInputStream::setPosition (int64 pos)
  5677. {
  5678. pos = jlimit ((int64) 0, totalSize, pos);
  5679. needToSeek |= (currentPosition != pos);
  5680. currentPosition = pos;
  5681. return true;
  5682. }
  5683. END_JUCE_NAMESPACE
  5684. /*** End of inlined file: juce_FileInputStream.cpp ***/
  5685. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  5686. BEGIN_JUCE_NAMESPACE
  5687. void* juce_fileOpen (const File& file, bool forWriting);
  5688. void juce_fileClose (void* handle);
  5689. int juce_fileWrite (void* handle, const void* buffer, int size);
  5690. int64 juce_fileSetPosition (void* handle, int64 pos);
  5691. FileOutputStream::FileOutputStream (const File& f,
  5692. const int bufferSize_)
  5693. : file (f),
  5694. bufferSize (bufferSize_),
  5695. bytesInBuffer (0)
  5696. {
  5697. fileHandle = juce_fileOpen (f, true);
  5698. if (fileHandle != 0)
  5699. {
  5700. currentPosition = getPositionInternal();
  5701. if (currentPosition < 0)
  5702. {
  5703. jassertfalse;
  5704. juce_fileClose (fileHandle);
  5705. fileHandle = 0;
  5706. }
  5707. }
  5708. buffer.malloc (jmax (bufferSize_, 16));
  5709. }
  5710. FileOutputStream::~FileOutputStream()
  5711. {
  5712. flush();
  5713. juce_fileClose (fileHandle);
  5714. }
  5715. int64 FileOutputStream::getPosition()
  5716. {
  5717. return currentPosition;
  5718. }
  5719. bool FileOutputStream::setPosition (int64 newPosition)
  5720. {
  5721. if (newPosition != currentPosition)
  5722. {
  5723. flush();
  5724. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  5725. }
  5726. return newPosition == currentPosition;
  5727. }
  5728. void FileOutputStream::flush()
  5729. {
  5730. if (bytesInBuffer > 0)
  5731. {
  5732. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  5733. bytesInBuffer = 0;
  5734. }
  5735. flushInternal();
  5736. }
  5737. bool FileOutputStream::write (const void* const src, const int numBytes)
  5738. {
  5739. if (bytesInBuffer + numBytes < bufferSize)
  5740. {
  5741. memcpy (buffer + bytesInBuffer, src, numBytes);
  5742. bytesInBuffer += numBytes;
  5743. currentPosition += numBytes;
  5744. }
  5745. else
  5746. {
  5747. if (bytesInBuffer > 0)
  5748. {
  5749. // flush the reservoir
  5750. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  5751. bytesInBuffer = 0;
  5752. if (! wroteOk)
  5753. return false;
  5754. }
  5755. if (numBytes < bufferSize)
  5756. {
  5757. memcpy (buffer + bytesInBuffer, src, numBytes);
  5758. bytesInBuffer += numBytes;
  5759. currentPosition += numBytes;
  5760. }
  5761. else
  5762. {
  5763. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  5764. currentPosition += bytesWritten;
  5765. return bytesWritten == numBytes;
  5766. }
  5767. }
  5768. return true;
  5769. }
  5770. END_JUCE_NAMESPACE
  5771. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  5772. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  5773. BEGIN_JUCE_NAMESPACE
  5774. FileSearchPath::FileSearchPath()
  5775. {
  5776. }
  5777. FileSearchPath::FileSearchPath (const String& path)
  5778. {
  5779. init (path);
  5780. }
  5781. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  5782. : directories (other.directories)
  5783. {
  5784. }
  5785. FileSearchPath::~FileSearchPath()
  5786. {
  5787. }
  5788. FileSearchPath& FileSearchPath::operator= (const String& path)
  5789. {
  5790. init (path);
  5791. return *this;
  5792. }
  5793. void FileSearchPath::init (const String& path)
  5794. {
  5795. directories.clear();
  5796. directories.addTokens (path, ";", "\"");
  5797. directories.trim();
  5798. directories.removeEmptyStrings();
  5799. for (int i = directories.size(); --i >= 0;)
  5800. directories.set (i, directories[i].unquoted());
  5801. }
  5802. int FileSearchPath::getNumPaths() const
  5803. {
  5804. return directories.size();
  5805. }
  5806. const File FileSearchPath::operator[] (const int index) const
  5807. {
  5808. return File (directories [index]);
  5809. }
  5810. const String FileSearchPath::toString() const
  5811. {
  5812. StringArray directories2 (directories);
  5813. for (int i = directories2.size(); --i >= 0;)
  5814. if (directories2[i].containsChar (';'))
  5815. directories2.set (i, directories2[i].quoted());
  5816. return directories2.joinIntoString (";");
  5817. }
  5818. void FileSearchPath::add (const File& dir, const int insertIndex)
  5819. {
  5820. directories.insert (insertIndex, dir.getFullPathName());
  5821. }
  5822. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  5823. {
  5824. for (int i = 0; i < directories.size(); ++i)
  5825. if (File (directories[i]) == dir)
  5826. return;
  5827. add (dir);
  5828. }
  5829. void FileSearchPath::remove (const int index)
  5830. {
  5831. directories.remove (index);
  5832. }
  5833. void FileSearchPath::addPath (const FileSearchPath& other)
  5834. {
  5835. for (int i = 0; i < other.getNumPaths(); ++i)
  5836. addIfNotAlreadyThere (other[i]);
  5837. }
  5838. void FileSearchPath::removeRedundantPaths()
  5839. {
  5840. for (int i = directories.size(); --i >= 0;)
  5841. {
  5842. const File d1 (directories[i]);
  5843. for (int j = directories.size(); --j >= 0;)
  5844. {
  5845. const File d2 (directories[j]);
  5846. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  5847. {
  5848. directories.remove (i);
  5849. break;
  5850. }
  5851. }
  5852. }
  5853. }
  5854. void FileSearchPath::removeNonExistentPaths()
  5855. {
  5856. for (int i = directories.size(); --i >= 0;)
  5857. if (! File (directories[i]).isDirectory())
  5858. directories.remove (i);
  5859. }
  5860. int FileSearchPath::findChildFiles (Array<File>& results,
  5861. const int whatToLookFor,
  5862. const bool searchRecursively,
  5863. const String& wildCardPattern) const
  5864. {
  5865. int total = 0;
  5866. for (int i = 0; i < directories.size(); ++i)
  5867. total += operator[] (i).findChildFiles (results,
  5868. whatToLookFor,
  5869. searchRecursively,
  5870. wildCardPattern);
  5871. return total;
  5872. }
  5873. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  5874. const bool checkRecursively) const
  5875. {
  5876. for (int i = directories.size(); --i >= 0;)
  5877. {
  5878. const File d (directories[i]);
  5879. if (checkRecursively)
  5880. {
  5881. if (fileToCheck.isAChildOf (d))
  5882. return true;
  5883. }
  5884. else
  5885. {
  5886. if (fileToCheck.getParentDirectory() == d)
  5887. return true;
  5888. }
  5889. }
  5890. return false;
  5891. }
  5892. END_JUCE_NAMESPACE
  5893. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  5894. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  5895. BEGIN_JUCE_NAMESPACE
  5896. NamedPipe::NamedPipe()
  5897. : internal (0)
  5898. {
  5899. }
  5900. NamedPipe::~NamedPipe()
  5901. {
  5902. close();
  5903. }
  5904. bool NamedPipe::openExisting (const String& pipeName)
  5905. {
  5906. currentPipeName = pipeName;
  5907. return openInternal (pipeName, false);
  5908. }
  5909. bool NamedPipe::createNewPipe (const String& pipeName)
  5910. {
  5911. currentPipeName = pipeName;
  5912. return openInternal (pipeName, true);
  5913. }
  5914. bool NamedPipe::isOpen() const
  5915. {
  5916. return internal != 0;
  5917. }
  5918. const String NamedPipe::getName() const
  5919. {
  5920. return currentPipeName;
  5921. }
  5922. // other methods for this class are implemented in the platform-specific files
  5923. END_JUCE_NAMESPACE
  5924. /*** End of inlined file: juce_NamedPipe.cpp ***/
  5925. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  5926. BEGIN_JUCE_NAMESPACE
  5927. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  5928. {
  5929. createTempFile (File::getSpecialLocation (File::tempDirectory),
  5930. "temp_" + String (Random::getSystemRandom().nextInt()),
  5931. suffix,
  5932. optionFlags);
  5933. }
  5934. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  5935. : targetFile (targetFile_)
  5936. {
  5937. // If you use this constructor, you need to give it a valid target file!
  5938. jassert (targetFile != File::nonexistent);
  5939. createTempFile (targetFile.getParentDirectory(),
  5940. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  5941. targetFile.getFileExtension(),
  5942. optionFlags);
  5943. }
  5944. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  5945. const String& suffix, const int optionFlags)
  5946. {
  5947. if ((optionFlags & useHiddenFile) != 0)
  5948. name = "." + name;
  5949. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  5950. }
  5951. TemporaryFile::~TemporaryFile()
  5952. {
  5953. // Have a few attempts at deleting the file before giving up..
  5954. for (int i = 5; --i >= 0;)
  5955. {
  5956. if (temporaryFile.deleteFile())
  5957. return;
  5958. Thread::sleep (50);
  5959. }
  5960. // Failed to delete our temporary file! Check that you've deleted all the
  5961. // file output streams that were using it!
  5962. jassertfalse;
  5963. }
  5964. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  5965. {
  5966. // This method only works if you created this object with the constructor
  5967. // that takes a target file!
  5968. jassert (targetFile != File::nonexistent);
  5969. if (temporaryFile.exists())
  5970. {
  5971. // Have a few attempts at overwriting the file before giving up..
  5972. for (int i = 5; --i >= 0;)
  5973. {
  5974. if (temporaryFile.moveFileTo (targetFile))
  5975. return true;
  5976. Thread::sleep (100);
  5977. }
  5978. }
  5979. else
  5980. {
  5981. // There's no temporary file to use. If your write failed, you should
  5982. // probably check, and not bother calling this method.
  5983. jassertfalse;
  5984. }
  5985. return false;
  5986. }
  5987. END_JUCE_NAMESPACE
  5988. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  5989. /*** Start of inlined file: juce_Socket.cpp ***/
  5990. #if JUCE_WINDOWS
  5991. #include <winsock2.h>
  5992. #if JUCE_MSVC
  5993. #pragma warning (push)
  5994. #pragma warning (disable : 4127 4389 4018)
  5995. #endif
  5996. #else
  5997. #if JUCE_LINUX
  5998. #include <sys/types.h>
  5999. #include <sys/socket.h>
  6000. #include <sys/errno.h>
  6001. #include <unistd.h>
  6002. #include <netinet/in.h>
  6003. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6004. #include <CoreServices/CoreServices.h>
  6005. #endif
  6006. #include <fcntl.h>
  6007. #include <netdb.h>
  6008. #include <arpa/inet.h>
  6009. #include <netinet/tcp.h>
  6010. #endif
  6011. BEGIN_JUCE_NAMESPACE
  6012. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6013. typedef socklen_t juce_socklen_t;
  6014. #else
  6015. typedef int juce_socklen_t;
  6016. #endif
  6017. #if JUCE_WINDOWS
  6018. namespace SocketHelpers
  6019. {
  6020. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6021. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6022. }
  6023. static void initWin32Sockets()
  6024. {
  6025. static CriticalSection lock;
  6026. const ScopedLock sl (lock);
  6027. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  6028. {
  6029. WSADATA wsaData;
  6030. const WORD wVersionRequested = MAKEWORD (1, 1);
  6031. WSAStartup (wVersionRequested, &wsaData);
  6032. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  6033. }
  6034. }
  6035. void juce_shutdownWin32Sockets()
  6036. {
  6037. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6038. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6039. }
  6040. #endif
  6041. namespace SocketHelpers
  6042. {
  6043. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6044. {
  6045. const int sndBufSize = 65536;
  6046. const int rcvBufSize = 65536;
  6047. const int one = 1;
  6048. return handle > 0
  6049. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6050. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6051. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6052. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6053. }
  6054. static bool bindSocketToPort (const int handle, const int port) throw()
  6055. {
  6056. if (handle <= 0 || port <= 0)
  6057. return false;
  6058. struct sockaddr_in servTmpAddr;
  6059. zerostruct (servTmpAddr);
  6060. servTmpAddr.sin_family = PF_INET;
  6061. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6062. servTmpAddr.sin_port = htons ((uint16) port);
  6063. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6064. }
  6065. static int readSocket (const int handle,
  6066. void* const destBuffer, const int maxBytesToRead,
  6067. bool volatile& connected,
  6068. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6069. {
  6070. int bytesRead = 0;
  6071. while (bytesRead < maxBytesToRead)
  6072. {
  6073. int bytesThisTime;
  6074. #if JUCE_WINDOWS
  6075. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6076. #else
  6077. while ((bytesThisTime = (int) ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  6078. && errno == EINTR
  6079. && connected)
  6080. {
  6081. }
  6082. #endif
  6083. if (bytesThisTime <= 0 || ! connected)
  6084. {
  6085. if (bytesRead == 0)
  6086. bytesRead = -1;
  6087. break;
  6088. }
  6089. bytesRead += bytesThisTime;
  6090. if (! blockUntilSpecifiedAmountHasArrived)
  6091. break;
  6092. }
  6093. return bytesRead;
  6094. }
  6095. static int waitForReadiness (const int handle, const bool forReading,
  6096. const int timeoutMsecs) throw()
  6097. {
  6098. struct timeval timeout;
  6099. struct timeval* timeoutp;
  6100. if (timeoutMsecs >= 0)
  6101. {
  6102. timeout.tv_sec = timeoutMsecs / 1000;
  6103. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  6104. timeoutp = &timeout;
  6105. }
  6106. else
  6107. {
  6108. timeoutp = 0;
  6109. }
  6110. fd_set rset, wset;
  6111. FD_ZERO (&rset);
  6112. FD_SET (handle, &rset);
  6113. FD_ZERO (&wset);
  6114. FD_SET (handle, &wset);
  6115. fd_set* const prset = forReading ? &rset : 0;
  6116. fd_set* const pwset = forReading ? 0 : &wset;
  6117. #if JUCE_WINDOWS
  6118. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  6119. return -1;
  6120. #else
  6121. {
  6122. int result;
  6123. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  6124. && errno == EINTR)
  6125. {
  6126. }
  6127. if (result < 0)
  6128. return -1;
  6129. }
  6130. #endif
  6131. {
  6132. int opt;
  6133. juce_socklen_t len = sizeof (opt);
  6134. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  6135. || opt != 0)
  6136. return -1;
  6137. }
  6138. if ((forReading && FD_ISSET (handle, &rset))
  6139. || ((! forReading) && FD_ISSET (handle, &wset)))
  6140. return 1;
  6141. return 0;
  6142. }
  6143. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  6144. {
  6145. #if JUCE_WINDOWS
  6146. u_long nonBlocking = shouldBlock ? 0 : 1;
  6147. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  6148. return false;
  6149. #else
  6150. int socketFlags = fcntl (handle, F_GETFL, 0);
  6151. if (socketFlags == -1)
  6152. return false;
  6153. if (shouldBlock)
  6154. socketFlags &= ~O_NONBLOCK;
  6155. else
  6156. socketFlags |= O_NONBLOCK;
  6157. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  6158. return false;
  6159. #endif
  6160. return true;
  6161. }
  6162. static bool connectSocket (int volatile& handle,
  6163. const bool isDatagram,
  6164. void** serverAddress,
  6165. const String& hostName,
  6166. const int portNumber,
  6167. const int timeOutMillisecs) throw()
  6168. {
  6169. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  6170. if (hostEnt == 0)
  6171. return false;
  6172. struct in_addr targetAddress;
  6173. memcpy (&targetAddress.s_addr,
  6174. *(hostEnt->h_addr_list),
  6175. sizeof (targetAddress.s_addr));
  6176. struct sockaddr_in servTmpAddr;
  6177. zerostruct (servTmpAddr);
  6178. servTmpAddr.sin_family = PF_INET;
  6179. servTmpAddr.sin_addr = targetAddress;
  6180. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6181. if (handle < 0)
  6182. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  6183. if (handle < 0)
  6184. return false;
  6185. if (isDatagram)
  6186. {
  6187. *serverAddress = new struct sockaddr_in();
  6188. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  6189. return true;
  6190. }
  6191. setSocketBlockingState (handle, false);
  6192. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  6193. if (result < 0)
  6194. {
  6195. #if JUCE_WINDOWS
  6196. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  6197. #else
  6198. if (errno == EINPROGRESS)
  6199. #endif
  6200. {
  6201. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  6202. {
  6203. setSocketBlockingState (handle, true);
  6204. return false;
  6205. }
  6206. }
  6207. }
  6208. setSocketBlockingState (handle, true);
  6209. resetSocketOptions (handle, false, false);
  6210. return true;
  6211. }
  6212. }
  6213. StreamingSocket::StreamingSocket()
  6214. : portNumber (0),
  6215. handle (-1),
  6216. connected (false),
  6217. isListener (false)
  6218. {
  6219. #if JUCE_WINDOWS
  6220. initWin32Sockets();
  6221. #endif
  6222. }
  6223. StreamingSocket::StreamingSocket (const String& hostName_,
  6224. const int portNumber_,
  6225. const int handle_)
  6226. : hostName (hostName_),
  6227. portNumber (portNumber_),
  6228. handle (handle_),
  6229. connected (true),
  6230. isListener (false)
  6231. {
  6232. #if JUCE_WINDOWS
  6233. initWin32Sockets();
  6234. #endif
  6235. SocketHelpers::resetSocketOptions (handle_, false, false);
  6236. }
  6237. StreamingSocket::~StreamingSocket()
  6238. {
  6239. close();
  6240. }
  6241. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6242. {
  6243. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6244. : -1;
  6245. }
  6246. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6247. {
  6248. if (isListener || ! connected)
  6249. return -1;
  6250. #if JUCE_WINDOWS
  6251. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  6252. #else
  6253. int result;
  6254. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  6255. && errno == EINTR)
  6256. {
  6257. }
  6258. return result;
  6259. #endif
  6260. }
  6261. int StreamingSocket::waitUntilReady (const bool readyForReading,
  6262. const int timeoutMsecs) const
  6263. {
  6264. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  6265. : -1;
  6266. }
  6267. bool StreamingSocket::bindToPort (const int port)
  6268. {
  6269. return SocketHelpers::bindSocketToPort (handle, port);
  6270. }
  6271. bool StreamingSocket::connect (const String& remoteHostName,
  6272. const int remotePortNumber,
  6273. const int timeOutMillisecs)
  6274. {
  6275. if (isListener)
  6276. {
  6277. jassertfalse; // a listener socket can't connect to another one!
  6278. return false;
  6279. }
  6280. if (connected)
  6281. close();
  6282. hostName = remoteHostName;
  6283. portNumber = remotePortNumber;
  6284. isListener = false;
  6285. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  6286. remotePortNumber, timeOutMillisecs);
  6287. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  6288. {
  6289. close();
  6290. return false;
  6291. }
  6292. return true;
  6293. }
  6294. void StreamingSocket::close()
  6295. {
  6296. #if JUCE_WINDOWS
  6297. if (handle != SOCKET_ERROR || connected)
  6298. closesocket (handle);
  6299. connected = false;
  6300. #else
  6301. if (connected)
  6302. {
  6303. connected = false;
  6304. if (isListener)
  6305. {
  6306. // need to do this to interrupt the accept() function..
  6307. StreamingSocket temp;
  6308. temp.connect ("localhost", portNumber, 1000);
  6309. }
  6310. }
  6311. if (handle != -1)
  6312. ::close (handle);
  6313. #endif
  6314. hostName = String::empty;
  6315. portNumber = 0;
  6316. handle = -1;
  6317. isListener = false;
  6318. }
  6319. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  6320. {
  6321. if (connected)
  6322. close();
  6323. hostName = "listener";
  6324. portNumber = newPortNumber;
  6325. isListener = true;
  6326. struct sockaddr_in servTmpAddr;
  6327. zerostruct (servTmpAddr);
  6328. servTmpAddr.sin_family = PF_INET;
  6329. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6330. if (localHostName.isNotEmpty())
  6331. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  6332. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6333. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  6334. if (handle < 0)
  6335. return false;
  6336. const int reuse = 1;
  6337. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  6338. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  6339. || listen (handle, SOMAXCONN) < 0)
  6340. {
  6341. close();
  6342. return false;
  6343. }
  6344. connected = true;
  6345. return true;
  6346. }
  6347. StreamingSocket* StreamingSocket::waitForNextConnection() const
  6348. {
  6349. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  6350. // prepare this socket as a listener.
  6351. if (connected && isListener)
  6352. {
  6353. struct sockaddr address;
  6354. juce_socklen_t len = sizeof (sockaddr);
  6355. const int newSocket = (int) accept (handle, &address, &len);
  6356. if (newSocket >= 0 && connected)
  6357. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6358. portNumber, newSocket);
  6359. }
  6360. return 0;
  6361. }
  6362. bool StreamingSocket::isLocal() const throw()
  6363. {
  6364. return hostName == "127.0.0.1";
  6365. }
  6366. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  6367. : portNumber (0),
  6368. handle (-1),
  6369. connected (true),
  6370. allowBroadcast (allowBroadcast_),
  6371. serverAddress (0)
  6372. {
  6373. #if JUCE_WINDOWS
  6374. initWin32Sockets();
  6375. #endif
  6376. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  6377. bindToPort (localPortNumber);
  6378. }
  6379. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  6380. const int handle_, const int localPortNumber)
  6381. : hostName (hostName_),
  6382. portNumber (portNumber_),
  6383. handle (handle_),
  6384. connected (true),
  6385. allowBroadcast (false),
  6386. serverAddress (0)
  6387. {
  6388. #if JUCE_WINDOWS
  6389. initWin32Sockets();
  6390. #endif
  6391. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  6392. bindToPort (localPortNumber);
  6393. }
  6394. DatagramSocket::~DatagramSocket()
  6395. {
  6396. close();
  6397. delete ((struct sockaddr_in*) serverAddress);
  6398. serverAddress = 0;
  6399. }
  6400. void DatagramSocket::close()
  6401. {
  6402. #if JUCE_WINDOWS
  6403. closesocket (handle);
  6404. connected = false;
  6405. #else
  6406. connected = false;
  6407. ::close (handle);
  6408. #endif
  6409. hostName = String::empty;
  6410. portNumber = 0;
  6411. handle = -1;
  6412. }
  6413. bool DatagramSocket::bindToPort (const int port)
  6414. {
  6415. return SocketHelpers::bindSocketToPort (handle, port);
  6416. }
  6417. bool DatagramSocket::connect (const String& remoteHostName,
  6418. const int remotePortNumber,
  6419. const int timeOutMillisecs)
  6420. {
  6421. if (connected)
  6422. close();
  6423. hostName = remoteHostName;
  6424. portNumber = remotePortNumber;
  6425. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  6426. remoteHostName, remotePortNumber,
  6427. timeOutMillisecs);
  6428. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  6429. {
  6430. close();
  6431. return false;
  6432. }
  6433. return true;
  6434. }
  6435. DatagramSocket* DatagramSocket::waitForNextConnection() const
  6436. {
  6437. struct sockaddr address;
  6438. juce_socklen_t len = sizeof (sockaddr);
  6439. while (waitUntilReady (true, -1) == 1)
  6440. {
  6441. char buf[1];
  6442. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  6443. {
  6444. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6445. ntohs (((struct sockaddr_in*) &address)->sin_port),
  6446. -1, -1);
  6447. }
  6448. }
  6449. return 0;
  6450. }
  6451. int DatagramSocket::waitUntilReady (const bool readyForReading,
  6452. const int timeoutMsecs) const
  6453. {
  6454. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  6455. : -1;
  6456. }
  6457. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6458. {
  6459. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6460. : -1;
  6461. }
  6462. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6463. {
  6464. // You need to call connect() first to set the server address..
  6465. jassert (serverAddress != 0 && connected);
  6466. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  6467. numBytesToWrite, 0,
  6468. (const struct sockaddr*) serverAddress,
  6469. sizeof (struct sockaddr_in))
  6470. : -1;
  6471. }
  6472. bool DatagramSocket::isLocal() const throw()
  6473. {
  6474. return hostName == "127.0.0.1";
  6475. }
  6476. #if JUCE_MSVC
  6477. #pragma warning (pop)
  6478. #endif
  6479. END_JUCE_NAMESPACE
  6480. /*** End of inlined file: juce_Socket.cpp ***/
  6481. /*** Start of inlined file: juce_URL.cpp ***/
  6482. BEGIN_JUCE_NAMESPACE
  6483. URL::URL()
  6484. {
  6485. }
  6486. URL::URL (const String& url_)
  6487. : url (url_)
  6488. {
  6489. int i = url.indexOfChar ('?');
  6490. if (i >= 0)
  6491. {
  6492. do
  6493. {
  6494. const int nextAmp = url.indexOfChar (i + 1, '&');
  6495. const int equalsPos = url.indexOfChar (i + 1, '=');
  6496. if (equalsPos > i + 1)
  6497. {
  6498. if (nextAmp < 0)
  6499. {
  6500. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6501. removeEscapeChars (url.substring (equalsPos + 1)));
  6502. }
  6503. else if (nextAmp > 0 && equalsPos < nextAmp)
  6504. {
  6505. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6506. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  6507. }
  6508. }
  6509. i = nextAmp;
  6510. }
  6511. while (i >= 0);
  6512. url = url.upToFirstOccurrenceOf ("?", false, false);
  6513. }
  6514. }
  6515. URL::URL (const URL& other)
  6516. : url (other.url),
  6517. postData (other.postData),
  6518. parameters (other.parameters),
  6519. filesToUpload (other.filesToUpload),
  6520. mimeTypes (other.mimeTypes)
  6521. {
  6522. }
  6523. URL& URL::operator= (const URL& other)
  6524. {
  6525. url = other.url;
  6526. postData = other.postData;
  6527. parameters = other.parameters;
  6528. filesToUpload = other.filesToUpload;
  6529. mimeTypes = other.mimeTypes;
  6530. return *this;
  6531. }
  6532. URL::~URL()
  6533. {
  6534. }
  6535. static const String getMangledParameters (const StringPairArray& parameters)
  6536. {
  6537. String p;
  6538. for (int i = 0; i < parameters.size(); ++i)
  6539. {
  6540. if (i > 0)
  6541. p += '&';
  6542. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  6543. << '='
  6544. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  6545. }
  6546. return p;
  6547. }
  6548. const String URL::toString (const bool includeGetParameters) const
  6549. {
  6550. if (includeGetParameters && parameters.size() > 0)
  6551. return url + "?" + getMangledParameters (parameters);
  6552. else
  6553. return url;
  6554. }
  6555. bool URL::isWellFormed() const
  6556. {
  6557. //xxx TODO
  6558. return url.isNotEmpty();
  6559. }
  6560. static int findStartOfDomain (const String& url)
  6561. {
  6562. int i = 0;
  6563. while (CharacterFunctions::isLetterOrDigit (url[i])
  6564. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  6565. ++i;
  6566. return url[i] == ':' ? i + 1 : 0;
  6567. }
  6568. const String URL::getDomain() const
  6569. {
  6570. int start = findStartOfDomain (url);
  6571. while (url[start] == '/')
  6572. ++start;
  6573. const int end1 = url.indexOfChar (start, '/');
  6574. const int end2 = url.indexOfChar (start, ':');
  6575. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  6576. : jmin (end1, end2);
  6577. return url.substring (start, end);
  6578. }
  6579. const String URL::getSubPath() const
  6580. {
  6581. int start = findStartOfDomain (url);
  6582. while (url[start] == '/')
  6583. ++start;
  6584. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6585. return startOfPath <= 0 ? String::empty
  6586. : url.substring (startOfPath);
  6587. }
  6588. const String URL::getScheme() const
  6589. {
  6590. return url.substring (0, findStartOfDomain (url) - 1);
  6591. }
  6592. const URL URL::withNewSubPath (const String& newPath) const
  6593. {
  6594. int start = findStartOfDomain (url);
  6595. while (url[start] == '/')
  6596. ++start;
  6597. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6598. URL u (*this);
  6599. if (startOfPath > 0)
  6600. u.url = url.substring (0, startOfPath);
  6601. if (! u.url.endsWithChar ('/'))
  6602. u.url << '/';
  6603. if (newPath.startsWithChar ('/'))
  6604. u.url << newPath.substring (1);
  6605. else
  6606. u.url << newPath;
  6607. return u;
  6608. }
  6609. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  6610. {
  6611. if (possibleURL.startsWithIgnoreCase ("http:")
  6612. || possibleURL.startsWithIgnoreCase ("ftp:"))
  6613. return true;
  6614. if (possibleURL.startsWithIgnoreCase ("file:")
  6615. || possibleURL.containsChar ('@')
  6616. || possibleURL.endsWithChar ('.')
  6617. || (! possibleURL.containsChar ('.')))
  6618. return false;
  6619. if (possibleURL.startsWithIgnoreCase ("www.")
  6620. && possibleURL.substring (5).containsChar ('.'))
  6621. return true;
  6622. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  6623. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  6624. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  6625. return true;
  6626. return false;
  6627. }
  6628. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  6629. {
  6630. const int atSign = possibleEmailAddress.indexOfChar ('@');
  6631. return atSign > 0
  6632. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  6633. && (! possibleEmailAddress.endsWithChar ('.'));
  6634. }
  6635. void* juce_openInternetFile (const String& url,
  6636. const String& headers,
  6637. const MemoryBlock& optionalPostData,
  6638. const bool isPost,
  6639. URL::OpenStreamProgressCallback* callback,
  6640. void* callbackContext,
  6641. int timeOutMs);
  6642. void juce_closeInternetFile (void* handle);
  6643. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  6644. int juce_seekInInternetFile (void* handle, int newPosition);
  6645. int64 juce_getInternetFileContentLength (void* handle);
  6646. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers);
  6647. class WebInputStream : public InputStream
  6648. {
  6649. public:
  6650. WebInputStream (const URL& url,
  6651. const bool isPost_,
  6652. URL::OpenStreamProgressCallback* const progressCallback_,
  6653. void* const progressCallbackContext_,
  6654. const String& extraHeaders,
  6655. const int timeOutMs_,
  6656. StringPairArray* const responseHeaders)
  6657. : position (0),
  6658. finished (false),
  6659. isPost (isPost_),
  6660. progressCallback (progressCallback_),
  6661. progressCallbackContext (progressCallbackContext_),
  6662. timeOutMs (timeOutMs_)
  6663. {
  6664. server = url.toString (! isPost);
  6665. if (isPost_)
  6666. createHeadersAndPostData (url);
  6667. headers += extraHeaders;
  6668. if (! headers.endsWithChar ('\n'))
  6669. headers << "\r\n";
  6670. handle = juce_openInternetFile (server, headers, postData, isPost,
  6671. progressCallback_, progressCallbackContext_,
  6672. timeOutMs);
  6673. if (responseHeaders != 0)
  6674. juce_getInternetFileHeaders (handle, *responseHeaders);
  6675. }
  6676. ~WebInputStream()
  6677. {
  6678. juce_closeInternetFile (handle);
  6679. }
  6680. bool isError() const { return handle == 0; }
  6681. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  6682. bool isExhausted() { return finished; }
  6683. int64 getPosition() { return position; }
  6684. int read (void* dest, int bytes)
  6685. {
  6686. if (finished || isError())
  6687. {
  6688. return 0;
  6689. }
  6690. else
  6691. {
  6692. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  6693. position += bytesRead;
  6694. if (bytesRead == 0)
  6695. finished = true;
  6696. return bytesRead;
  6697. }
  6698. }
  6699. bool setPosition (int64 wantedPos)
  6700. {
  6701. if (wantedPos != position)
  6702. {
  6703. finished = false;
  6704. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  6705. if (actualPos == wantedPos)
  6706. {
  6707. position = wantedPos;
  6708. }
  6709. else
  6710. {
  6711. if (wantedPos < position)
  6712. {
  6713. juce_closeInternetFile (handle);
  6714. position = 0;
  6715. finished = false;
  6716. handle = juce_openInternetFile (server, headers, postData, isPost,
  6717. progressCallback, progressCallbackContext,
  6718. timeOutMs);
  6719. }
  6720. skipNextBytes (wantedPos - position);
  6721. }
  6722. }
  6723. return true;
  6724. }
  6725. juce_UseDebuggingNewOperator
  6726. private:
  6727. String server, headers;
  6728. MemoryBlock postData;
  6729. int64 position;
  6730. bool finished;
  6731. const bool isPost;
  6732. void* handle;
  6733. URL::OpenStreamProgressCallback* const progressCallback;
  6734. void* const progressCallbackContext;
  6735. const int timeOutMs;
  6736. void createHeadersAndPostData (const URL& url)
  6737. {
  6738. MemoryOutputStream data (postData, false);
  6739. if (url.getFilesToUpload().size() > 0)
  6740. {
  6741. // need to upload some files, so do it as multi-part...
  6742. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  6743. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  6744. data << "--" << boundary;
  6745. int i;
  6746. for (i = 0; i < url.getParameters().size(); ++i)
  6747. {
  6748. data << "\r\nContent-Disposition: form-data; name=\""
  6749. << url.getParameters().getAllKeys() [i]
  6750. << "\"\r\n\r\n"
  6751. << url.getParameters().getAllValues() [i]
  6752. << "\r\n--"
  6753. << boundary;
  6754. }
  6755. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  6756. {
  6757. const File file (url.getFilesToUpload().getAllValues() [i]);
  6758. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  6759. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  6760. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  6761. const String mimeType (url.getMimeTypesOfUploadFiles()
  6762. .getValue (paramName, String::empty));
  6763. if (mimeType.isNotEmpty())
  6764. data << "Content-Type: " << mimeType << "\r\n";
  6765. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  6766. << file << "\r\n--" << boundary;
  6767. }
  6768. data << "--\r\n";
  6769. data.flush();
  6770. }
  6771. else
  6772. {
  6773. data << getMangledParameters (url.getParameters())
  6774. << url.getPostData();
  6775. data.flush();
  6776. // just a short text attachment, so use simple url encoding..
  6777. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  6778. + String ((unsigned int) postData.getSize())
  6779. + "\r\n";
  6780. }
  6781. }
  6782. WebInputStream (const WebInputStream&);
  6783. WebInputStream& operator= (const WebInputStream&);
  6784. };
  6785. InputStream* URL::createInputStream (const bool usePostCommand,
  6786. OpenStreamProgressCallback* const progressCallback,
  6787. void* const progressCallbackContext,
  6788. const String& extraHeaders,
  6789. const int timeOutMs,
  6790. StringPairArray* const responseHeaders) const
  6791. {
  6792. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  6793. progressCallback, progressCallbackContext,
  6794. extraHeaders, timeOutMs, responseHeaders));
  6795. return wi->isError() ? 0 : wi.release();
  6796. }
  6797. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  6798. const bool usePostCommand) const
  6799. {
  6800. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6801. if (in != 0)
  6802. {
  6803. in->readIntoMemoryBlock (destData);
  6804. return true;
  6805. }
  6806. return false;
  6807. }
  6808. const String URL::readEntireTextStream (const bool usePostCommand) const
  6809. {
  6810. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6811. if (in != 0)
  6812. return in->readEntireStreamAsString();
  6813. return String::empty;
  6814. }
  6815. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  6816. {
  6817. XmlDocument doc (readEntireTextStream (usePostCommand));
  6818. return doc.getDocumentElement();
  6819. }
  6820. const URL URL::withParameter (const String& parameterName,
  6821. const String& parameterValue) const
  6822. {
  6823. URL u (*this);
  6824. u.parameters.set (parameterName, parameterValue);
  6825. return u;
  6826. }
  6827. const URL URL::withFileToUpload (const String& parameterName,
  6828. const File& fileToUpload,
  6829. const String& mimeType) const
  6830. {
  6831. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  6832. URL u (*this);
  6833. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  6834. u.mimeTypes.set (parameterName, mimeType);
  6835. return u;
  6836. }
  6837. const URL URL::withPOSTData (const String& postData_) const
  6838. {
  6839. URL u (*this);
  6840. u.postData = postData_;
  6841. return u;
  6842. }
  6843. const StringPairArray& URL::getParameters() const
  6844. {
  6845. return parameters;
  6846. }
  6847. const StringPairArray& URL::getFilesToUpload() const
  6848. {
  6849. return filesToUpload;
  6850. }
  6851. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  6852. {
  6853. return mimeTypes;
  6854. }
  6855. const String URL::removeEscapeChars (const String& s)
  6856. {
  6857. String result (s.replaceCharacter ('+', ' '));
  6858. int nextPercent = 0;
  6859. for (;;)
  6860. {
  6861. nextPercent = result.indexOfChar (nextPercent, '%');
  6862. if (nextPercent < 0)
  6863. break;
  6864. juce_wchar replacementChar = (juce_wchar) result.substring (nextPercent + 1, nextPercent + 3).getHexValue32();
  6865. result = result.replaceSection (nextPercent, 3, String::charToString (replacementChar));
  6866. ++nextPercent;
  6867. }
  6868. return result;
  6869. }
  6870. const String URL::addEscapeChars (const String& s, const bool isParameter)
  6871. {
  6872. String result;
  6873. result.preallocateStorage (s.length() + 8);
  6874. const char* utf8 = s.toUTF8();
  6875. const char* legalChars = isParameter ? "_-.*!'()"
  6876. : "_-$.*!'(),";
  6877. while (*utf8 != 0)
  6878. {
  6879. const char c = *utf8++;
  6880. if (CharacterFunctions::isLetterOrDigit (c)
  6881. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  6882. {
  6883. result << c;
  6884. }
  6885. else
  6886. {
  6887. const int v = (int) (uint8) c;
  6888. result << (v < 0x10 ? "%0" : "%") << String::toHexString (v);
  6889. }
  6890. }
  6891. return result;
  6892. }
  6893. bool URL::launchInDefaultBrowser() const
  6894. {
  6895. String u (toString (true));
  6896. if (u.containsChar ('@') && ! u.containsChar (':'))
  6897. u = "mailto:" + u;
  6898. return PlatformUtilities::openDocument (u, String::empty);
  6899. }
  6900. END_JUCE_NAMESPACE
  6901. /*** End of inlined file: juce_URL.cpp ***/
  6902. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  6903. BEGIN_JUCE_NAMESPACE
  6904. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  6905. const int bufferSize_,
  6906. const bool deleteSourceWhenDestroyed)
  6907. : source (source_),
  6908. sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0),
  6909. bufferSize (jmax (256, bufferSize_)),
  6910. position (source_->getPosition()),
  6911. lastReadPos (0),
  6912. bufferOverlap (128)
  6913. {
  6914. const int sourceSize = (int) source_->getTotalLength();
  6915. if (sourceSize >= 0)
  6916. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  6917. bufferStart = position;
  6918. buffer.malloc (bufferSize);
  6919. }
  6920. BufferedInputStream::~BufferedInputStream()
  6921. {
  6922. }
  6923. int64 BufferedInputStream::getTotalLength()
  6924. {
  6925. return source->getTotalLength();
  6926. }
  6927. int64 BufferedInputStream::getPosition()
  6928. {
  6929. return position;
  6930. }
  6931. bool BufferedInputStream::setPosition (int64 newPosition)
  6932. {
  6933. position = jmax ((int64) 0, newPosition);
  6934. return true;
  6935. }
  6936. bool BufferedInputStream::isExhausted()
  6937. {
  6938. return (position >= lastReadPos)
  6939. && source->isExhausted();
  6940. }
  6941. void BufferedInputStream::ensureBuffered()
  6942. {
  6943. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  6944. if (position < bufferStart || position >= bufferEndOverlap)
  6945. {
  6946. int bytesRead;
  6947. if (position < lastReadPos
  6948. && position >= bufferEndOverlap
  6949. && position >= bufferStart)
  6950. {
  6951. const int bytesToKeep = (int) (lastReadPos - position);
  6952. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  6953. bufferStart = position;
  6954. bytesRead = source->read (buffer + bytesToKeep,
  6955. bufferSize - bytesToKeep);
  6956. lastReadPos += bytesRead;
  6957. bytesRead += bytesToKeep;
  6958. }
  6959. else
  6960. {
  6961. bufferStart = position;
  6962. source->setPosition (bufferStart);
  6963. bytesRead = source->read (buffer, bufferSize);
  6964. lastReadPos = bufferStart + bytesRead;
  6965. }
  6966. while (bytesRead < bufferSize)
  6967. buffer [bytesRead++] = 0;
  6968. }
  6969. }
  6970. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  6971. {
  6972. if (position >= bufferStart
  6973. && position + maxBytesToRead <= lastReadPos)
  6974. {
  6975. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  6976. position += maxBytesToRead;
  6977. return maxBytesToRead;
  6978. }
  6979. else
  6980. {
  6981. if (position < bufferStart || position >= lastReadPos)
  6982. ensureBuffered();
  6983. int bytesRead = 0;
  6984. while (maxBytesToRead > 0)
  6985. {
  6986. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  6987. if (bytesAvailable > 0)
  6988. {
  6989. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  6990. maxBytesToRead -= bytesAvailable;
  6991. bytesRead += bytesAvailable;
  6992. position += bytesAvailable;
  6993. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  6994. }
  6995. const int64 oldLastReadPos = lastReadPos;
  6996. ensureBuffered();
  6997. if (oldLastReadPos == lastReadPos)
  6998. break; // if ensureBuffered() failed to read any more data, bail out
  6999. if (isExhausted())
  7000. break;
  7001. }
  7002. return bytesRead;
  7003. }
  7004. }
  7005. const String BufferedInputStream::readString()
  7006. {
  7007. if (position >= bufferStart
  7008. && position < lastReadPos)
  7009. {
  7010. const int maxChars = (int) (lastReadPos - position);
  7011. const char* const src = buffer + (int) (position - bufferStart);
  7012. for (int i = 0; i < maxChars; ++i)
  7013. {
  7014. if (src[i] == 0)
  7015. {
  7016. position += i + 1;
  7017. return String::fromUTF8 (src, i);
  7018. }
  7019. }
  7020. }
  7021. return InputStream::readString();
  7022. }
  7023. END_JUCE_NAMESPACE
  7024. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  7025. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  7026. BEGIN_JUCE_NAMESPACE
  7027. FileInputSource::FileInputSource (const File& file_)
  7028. : file (file_)
  7029. {
  7030. }
  7031. FileInputSource::~FileInputSource()
  7032. {
  7033. }
  7034. InputStream* FileInputSource::createInputStream()
  7035. {
  7036. return file.createInputStream();
  7037. }
  7038. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  7039. {
  7040. return file.getSiblingFile (relatedItemPath).createInputStream();
  7041. }
  7042. int64 FileInputSource::hashCode() const
  7043. {
  7044. return file.hashCode();
  7045. }
  7046. END_JUCE_NAMESPACE
  7047. /*** End of inlined file: juce_FileInputSource.cpp ***/
  7048. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  7049. BEGIN_JUCE_NAMESPACE
  7050. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  7051. const size_t sourceDataSize,
  7052. const bool keepInternalCopy)
  7053. : data (static_cast <const char*> (sourceData)),
  7054. dataSize (sourceDataSize),
  7055. position (0)
  7056. {
  7057. if (keepInternalCopy)
  7058. {
  7059. internalCopy.append (data, sourceDataSize);
  7060. data = static_cast <const char*> (internalCopy.getData());
  7061. }
  7062. }
  7063. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  7064. const bool keepInternalCopy)
  7065. : data (static_cast <const char*> (sourceData.getData())),
  7066. dataSize (sourceData.getSize()),
  7067. position (0)
  7068. {
  7069. if (keepInternalCopy)
  7070. {
  7071. internalCopy = sourceData;
  7072. data = static_cast <const char*> (internalCopy.getData());
  7073. }
  7074. }
  7075. MemoryInputStream::~MemoryInputStream()
  7076. {
  7077. }
  7078. int64 MemoryInputStream::getTotalLength()
  7079. {
  7080. return dataSize;
  7081. }
  7082. int MemoryInputStream::read (void* const buffer, const int howMany)
  7083. {
  7084. jassert (howMany >= 0);
  7085. const int num = jmin (howMany, (int) (dataSize - position));
  7086. memcpy (buffer, data + position, num);
  7087. position += num;
  7088. return (int) num;
  7089. }
  7090. bool MemoryInputStream::isExhausted()
  7091. {
  7092. return (position >= dataSize);
  7093. }
  7094. bool MemoryInputStream::setPosition (const int64 pos)
  7095. {
  7096. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  7097. return true;
  7098. }
  7099. int64 MemoryInputStream::getPosition()
  7100. {
  7101. return position;
  7102. }
  7103. END_JUCE_NAMESPACE
  7104. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  7105. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  7106. BEGIN_JUCE_NAMESPACE
  7107. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  7108. : data (internalBlock),
  7109. position (0),
  7110. size (0)
  7111. {
  7112. internalBlock.setSize (initialSize, false);
  7113. }
  7114. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  7115. const bool appendToExistingBlockContent)
  7116. : data (memoryBlockToWriteTo),
  7117. position (0),
  7118. size (0)
  7119. {
  7120. if (appendToExistingBlockContent)
  7121. position = size = memoryBlockToWriteTo.getSize();
  7122. }
  7123. MemoryOutputStream::~MemoryOutputStream()
  7124. {
  7125. flush();
  7126. }
  7127. void MemoryOutputStream::flush()
  7128. {
  7129. if (&data != &internalBlock)
  7130. data.setSize (size, false);
  7131. }
  7132. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  7133. {
  7134. data.ensureSize (bytesToPreallocate + 1);
  7135. }
  7136. void MemoryOutputStream::reset() throw()
  7137. {
  7138. position = 0;
  7139. size = 0;
  7140. }
  7141. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  7142. {
  7143. if (howMany > 0)
  7144. {
  7145. const size_t storageNeeded = position + howMany;
  7146. if (storageNeeded >= data.getSize())
  7147. data.ensureSize ((storageNeeded + jmin (storageNeeded / 2, (size_t) (1024 * 1024)) + 32) & ~31);
  7148. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  7149. position += howMany;
  7150. size = jmax (size, position);
  7151. }
  7152. return true;
  7153. }
  7154. const void* MemoryOutputStream::getData() const throw()
  7155. {
  7156. void* const d = data.getData();
  7157. if (data.getSize() > size)
  7158. static_cast <char*> (d) [size] = 0;
  7159. return d;
  7160. }
  7161. bool MemoryOutputStream::setPosition (int64 newPosition)
  7162. {
  7163. if (newPosition <= (int64) size)
  7164. {
  7165. // ok to seek backwards
  7166. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  7167. return true;
  7168. }
  7169. else
  7170. {
  7171. // trying to make it bigger isn't a good thing to do..
  7172. return false;
  7173. }
  7174. }
  7175. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  7176. {
  7177. // before writing from an input, see if we can preallocate to make it more efficient..
  7178. int64 availableData = source.getTotalLength() - source.getPosition();
  7179. if (availableData > 0)
  7180. {
  7181. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  7182. availableData = maxNumBytesToWrite;
  7183. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  7184. }
  7185. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  7186. }
  7187. const String MemoryOutputStream::toUTF8() const
  7188. {
  7189. return String (static_cast <const char*> (getData()), getDataSize());
  7190. }
  7191. const String MemoryOutputStream::toString() const
  7192. {
  7193. return String::createStringFromData (getData(), getDataSize());
  7194. }
  7195. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  7196. {
  7197. stream.write (streamToRead.getData(), streamToRead.getDataSize());
  7198. return stream;
  7199. }
  7200. END_JUCE_NAMESPACE
  7201. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  7202. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  7203. BEGIN_JUCE_NAMESPACE
  7204. SubregionStream::SubregionStream (InputStream* const sourceStream,
  7205. const int64 startPositionInSourceStream_,
  7206. const int64 lengthOfSourceStream_,
  7207. const bool deleteSourceWhenDestroyed)
  7208. : source (sourceStream),
  7209. startPositionInSourceStream (startPositionInSourceStream_),
  7210. lengthOfSourceStream (lengthOfSourceStream_)
  7211. {
  7212. if (deleteSourceWhenDestroyed)
  7213. sourceToDelete = source;
  7214. setPosition (0);
  7215. }
  7216. SubregionStream::~SubregionStream()
  7217. {
  7218. }
  7219. int64 SubregionStream::getTotalLength()
  7220. {
  7221. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  7222. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  7223. : srcLen;
  7224. }
  7225. int64 SubregionStream::getPosition()
  7226. {
  7227. return source->getPosition() - startPositionInSourceStream;
  7228. }
  7229. bool SubregionStream::setPosition (int64 newPosition)
  7230. {
  7231. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  7232. }
  7233. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  7234. {
  7235. if (lengthOfSourceStream < 0)
  7236. {
  7237. return source->read (destBuffer, maxBytesToRead);
  7238. }
  7239. else
  7240. {
  7241. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  7242. if (maxBytesToRead <= 0)
  7243. return 0;
  7244. return source->read (destBuffer, maxBytesToRead);
  7245. }
  7246. }
  7247. bool SubregionStream::isExhausted()
  7248. {
  7249. if (lengthOfSourceStream >= 0)
  7250. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  7251. else
  7252. return source->isExhausted();
  7253. }
  7254. END_JUCE_NAMESPACE
  7255. /*** End of inlined file: juce_SubregionStream.cpp ***/
  7256. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  7257. BEGIN_JUCE_NAMESPACE
  7258. PerformanceCounter::PerformanceCounter (const String& name_,
  7259. int runsPerPrintout,
  7260. const File& loggingFile)
  7261. : name (name_),
  7262. numRuns (0),
  7263. runsPerPrint (runsPerPrintout),
  7264. totalTime (0),
  7265. outputFile (loggingFile)
  7266. {
  7267. if (outputFile != File::nonexistent)
  7268. {
  7269. String s ("**** Counter for \"");
  7270. s << name_ << "\" started at: "
  7271. << Time::getCurrentTime().toString (true, true)
  7272. << "\r\n";
  7273. outputFile.appendText (s, false, false);
  7274. }
  7275. }
  7276. PerformanceCounter::~PerformanceCounter()
  7277. {
  7278. printStatistics();
  7279. }
  7280. void PerformanceCounter::start()
  7281. {
  7282. started = Time::getHighResolutionTicks();
  7283. }
  7284. void PerformanceCounter::stop()
  7285. {
  7286. const int64 now = Time::getHighResolutionTicks();
  7287. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  7288. if (++numRuns == runsPerPrint)
  7289. printStatistics();
  7290. }
  7291. void PerformanceCounter::printStatistics()
  7292. {
  7293. if (numRuns > 0)
  7294. {
  7295. String s ("Performance count for \"");
  7296. s << name << "\" - average over " << numRuns << " run(s) = ";
  7297. const int micros = (int) (totalTime * (1000.0 / numRuns));
  7298. if (micros > 10000)
  7299. s << (micros/1000) << " millisecs";
  7300. else
  7301. s << micros << " microsecs";
  7302. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  7303. Logger::outputDebugString (s);
  7304. s << "\r\n";
  7305. if (outputFile != File::nonexistent)
  7306. outputFile.appendText (s, false, false);
  7307. numRuns = 0;
  7308. totalTime = 0;
  7309. }
  7310. }
  7311. END_JUCE_NAMESPACE
  7312. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  7313. /*** Start of inlined file: juce_Uuid.cpp ***/
  7314. BEGIN_JUCE_NAMESPACE
  7315. Uuid::Uuid()
  7316. {
  7317. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  7318. // to make it very very unlikely that two UUIDs will ever be the same..
  7319. static int64 macAddresses[2];
  7320. static bool hasCheckedMacAddresses = false;
  7321. if (! hasCheckedMacAddresses)
  7322. {
  7323. hasCheckedMacAddresses = true;
  7324. SystemStats::getMACAddresses (macAddresses, 2);
  7325. }
  7326. value.asInt64[0] = macAddresses[0];
  7327. value.asInt64[1] = macAddresses[1];
  7328. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  7329. // whose seed will carry over between calls to this method.
  7330. Random r (macAddresses[0] ^ macAddresses[1]
  7331. ^ Random::getSystemRandom().nextInt64());
  7332. for (int i = 4; --i >= 0;)
  7333. {
  7334. r.setSeedRandomly(); // calling this repeatedly improves randomness
  7335. value.asInt[i] ^= r.nextInt();
  7336. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  7337. }
  7338. }
  7339. Uuid::~Uuid() throw()
  7340. {
  7341. }
  7342. Uuid::Uuid (const Uuid& other)
  7343. : value (other.value)
  7344. {
  7345. }
  7346. Uuid& Uuid::operator= (const Uuid& other)
  7347. {
  7348. value = other.value;
  7349. return *this;
  7350. }
  7351. bool Uuid::operator== (const Uuid& other) const
  7352. {
  7353. return value.asInt64[0] == other.value.asInt64[0]
  7354. && value.asInt64[1] == other.value.asInt64[1];
  7355. }
  7356. bool Uuid::operator!= (const Uuid& other) const
  7357. {
  7358. return ! operator== (other);
  7359. }
  7360. bool Uuid::isNull() const throw()
  7361. {
  7362. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  7363. }
  7364. const String Uuid::toString() const
  7365. {
  7366. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  7367. }
  7368. Uuid::Uuid (const String& uuidString)
  7369. {
  7370. operator= (uuidString);
  7371. }
  7372. Uuid& Uuid::operator= (const String& uuidString)
  7373. {
  7374. MemoryBlock mb;
  7375. mb.loadFromHexString (uuidString);
  7376. mb.ensureSize (sizeof (value.asBytes), true);
  7377. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  7378. return *this;
  7379. }
  7380. Uuid::Uuid (const uint8* const rawData)
  7381. {
  7382. operator= (rawData);
  7383. }
  7384. Uuid& Uuid::operator= (const uint8* const rawData)
  7385. {
  7386. if (rawData != 0)
  7387. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  7388. else
  7389. zeromem (value.asBytes, sizeof (value.asBytes));
  7390. return *this;
  7391. }
  7392. END_JUCE_NAMESPACE
  7393. /*** End of inlined file: juce_Uuid.cpp ***/
  7394. /*** Start of inlined file: juce_ZipFile.cpp ***/
  7395. BEGIN_JUCE_NAMESPACE
  7396. class ZipFile::ZipEntryInfo
  7397. {
  7398. public:
  7399. ZipFile::ZipEntry entry;
  7400. int streamOffset;
  7401. int compressedSize;
  7402. bool compressed;
  7403. };
  7404. class ZipFile::ZipInputStream : public InputStream
  7405. {
  7406. public:
  7407. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  7408. : file (file_),
  7409. zipEntryInfo (zei),
  7410. pos (0),
  7411. headerSize (0),
  7412. inputStream (0)
  7413. {
  7414. inputStream = file_.inputStream;
  7415. if (file_.inputSource != 0)
  7416. {
  7417. inputStream = file.inputSource->createInputStream();
  7418. }
  7419. else
  7420. {
  7421. #if JUCE_DEBUG
  7422. file_.numOpenStreams++;
  7423. #endif
  7424. }
  7425. char buffer [30];
  7426. if (inputStream != 0
  7427. && inputStream->setPosition (zei.streamOffset)
  7428. && inputStream->read (buffer, 30) == 30
  7429. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  7430. {
  7431. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  7432. + ByteOrder::littleEndianShort (buffer + 28);
  7433. }
  7434. }
  7435. ~ZipInputStream()
  7436. {
  7437. #if JUCE_DEBUG
  7438. if (inputStream != 0 && inputStream == file.inputStream)
  7439. file.numOpenStreams--;
  7440. #endif
  7441. if (inputStream != file.inputStream)
  7442. delete inputStream;
  7443. }
  7444. int64 getTotalLength()
  7445. {
  7446. return zipEntryInfo.compressedSize;
  7447. }
  7448. int read (void* buffer, int howMany)
  7449. {
  7450. if (headerSize <= 0)
  7451. return 0;
  7452. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  7453. if (inputStream == 0)
  7454. return 0;
  7455. int num;
  7456. if (inputStream == file.inputStream)
  7457. {
  7458. const ScopedLock sl (file.lock);
  7459. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7460. num = inputStream->read (buffer, howMany);
  7461. }
  7462. else
  7463. {
  7464. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7465. num = inputStream->read (buffer, howMany);
  7466. }
  7467. pos += num;
  7468. return num;
  7469. }
  7470. bool isExhausted()
  7471. {
  7472. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  7473. }
  7474. int64 getPosition()
  7475. {
  7476. return pos;
  7477. }
  7478. bool setPosition (int64 newPos)
  7479. {
  7480. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  7481. return true;
  7482. }
  7483. private:
  7484. ZipFile& file;
  7485. ZipEntryInfo zipEntryInfo;
  7486. int64 pos;
  7487. int headerSize;
  7488. InputStream* inputStream;
  7489. ZipInputStream (const ZipInputStream&);
  7490. ZipInputStream& operator= (const ZipInputStream&);
  7491. };
  7492. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  7493. : inputStream (source_)
  7494. #if JUCE_DEBUG
  7495. , numOpenStreams (0)
  7496. #endif
  7497. {
  7498. if (deleteStreamWhenDestroyed)
  7499. streamToDelete = inputStream;
  7500. init();
  7501. }
  7502. ZipFile::ZipFile (const File& file)
  7503. : inputStream (0)
  7504. #if JUCE_DEBUG
  7505. , numOpenStreams (0)
  7506. #endif
  7507. {
  7508. inputSource = new FileInputSource (file);
  7509. init();
  7510. }
  7511. ZipFile::ZipFile (InputSource* const inputSource_)
  7512. : inputStream (0),
  7513. inputSource (inputSource_)
  7514. #if JUCE_DEBUG
  7515. , numOpenStreams (0)
  7516. #endif
  7517. {
  7518. init();
  7519. }
  7520. ZipFile::~ZipFile()
  7521. {
  7522. #if JUCE_DEBUG
  7523. entries.clear();
  7524. // If you hit this assertion, it means you've created a stream to read
  7525. // one of the items in the zipfile, but you've forgotten to delete that
  7526. // stream object before deleting the file.. Streams can't be kept open
  7527. // after the file is deleted because they need to share the input
  7528. // stream that the file uses to read itself.
  7529. jassert (numOpenStreams == 0);
  7530. #endif
  7531. }
  7532. int ZipFile::getNumEntries() const throw()
  7533. {
  7534. return entries.size();
  7535. }
  7536. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  7537. {
  7538. ZipEntryInfo* const zei = entries [index];
  7539. return zei != 0 ? &(zei->entry) : 0;
  7540. }
  7541. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  7542. {
  7543. for (int i = 0; i < entries.size(); ++i)
  7544. if (entries.getUnchecked (i)->entry.filename == fileName)
  7545. return i;
  7546. return -1;
  7547. }
  7548. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  7549. {
  7550. return getEntry (getIndexOfFileName (fileName));
  7551. }
  7552. InputStream* ZipFile::createStreamForEntry (const int index)
  7553. {
  7554. ZipEntryInfo* const zei = entries[index];
  7555. InputStream* stream = 0;
  7556. if (zei != 0)
  7557. {
  7558. stream = new ZipInputStream (*this, *zei);
  7559. if (zei->compressed)
  7560. {
  7561. stream = new GZIPDecompressorInputStream (stream, true, true,
  7562. zei->entry.uncompressedSize);
  7563. // (much faster to unzip in big blocks using a buffer..)
  7564. stream = new BufferedInputStream (stream, 32768, true);
  7565. }
  7566. }
  7567. return stream;
  7568. }
  7569. class ZipFile::ZipFilenameComparator
  7570. {
  7571. public:
  7572. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  7573. {
  7574. return first->entry.filename.compare (second->entry.filename);
  7575. }
  7576. };
  7577. void ZipFile::sortEntriesByFilename()
  7578. {
  7579. ZipFilenameComparator sorter;
  7580. entries.sort (sorter);
  7581. }
  7582. void ZipFile::init()
  7583. {
  7584. ScopedPointer <InputStream> toDelete;
  7585. InputStream* in = inputStream;
  7586. if (inputSource != 0)
  7587. {
  7588. in = inputSource->createInputStream();
  7589. toDelete = in;
  7590. }
  7591. if (in != 0)
  7592. {
  7593. int numEntries = 0;
  7594. int pos = findEndOfZipEntryTable (in, numEntries);
  7595. if (pos >= 0 && pos < in->getTotalLength())
  7596. {
  7597. const int size = (int) (in->getTotalLength() - pos);
  7598. in->setPosition (pos);
  7599. MemoryBlock headerData;
  7600. if (in->readIntoMemoryBlock (headerData, size) == size)
  7601. {
  7602. pos = 0;
  7603. for (int i = 0; i < numEntries; ++i)
  7604. {
  7605. if (pos + 46 > size)
  7606. break;
  7607. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  7608. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  7609. if (pos + 46 + fileNameLen > size)
  7610. break;
  7611. ZipEntryInfo* const zei = new ZipEntryInfo();
  7612. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  7613. const int time = ByteOrder::littleEndianShort (buffer + 12);
  7614. const int date = ByteOrder::littleEndianShort (buffer + 14);
  7615. const int year = 1980 + (date >> 9);
  7616. const int month = ((date >> 5) & 15) - 1;
  7617. const int day = date & 31;
  7618. const int hours = time >> 11;
  7619. const int minutes = (time >> 5) & 63;
  7620. const int seconds = (time & 31) << 1;
  7621. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  7622. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  7623. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  7624. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  7625. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  7626. entries.add (zei);
  7627. pos += 46 + fileNameLen
  7628. + ByteOrder::littleEndianShort (buffer + 30)
  7629. + ByteOrder::littleEndianShort (buffer + 32);
  7630. }
  7631. }
  7632. }
  7633. }
  7634. }
  7635. int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries)
  7636. {
  7637. BufferedInputStream in (input, 8192, false);
  7638. in.setPosition (in.getTotalLength());
  7639. int64 pos = in.getPosition();
  7640. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  7641. char buffer [32];
  7642. zeromem (buffer, sizeof (buffer));
  7643. while (pos > lowestPos)
  7644. {
  7645. in.setPosition (pos - 22);
  7646. pos = in.getPosition();
  7647. memcpy (buffer + 22, buffer, 4);
  7648. if (in.read (buffer, 22) != 22)
  7649. return 0;
  7650. for (int i = 0; i < 22; ++i)
  7651. {
  7652. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  7653. {
  7654. in.setPosition (pos + i);
  7655. in.read (buffer, 22);
  7656. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  7657. return ByteOrder::littleEndianInt (buffer + 16);
  7658. }
  7659. }
  7660. }
  7661. return 0;
  7662. }
  7663. void ZipFile::uncompressTo (const File& targetDirectory,
  7664. const bool shouldOverwriteFiles)
  7665. {
  7666. for (int i = 0; i < entries.size(); ++i)
  7667. {
  7668. const ZipEntry& zei = entries.getUnchecked(i)->entry;
  7669. const File targetFile (targetDirectory.getChildFile (zei.filename));
  7670. if (zei.filename.endsWithChar ('/'))
  7671. {
  7672. targetFile.createDirectory(); // (entry is a directory, not a file)
  7673. }
  7674. else
  7675. {
  7676. ScopedPointer <InputStream> in (createStreamForEntry (i));
  7677. if (in != 0)
  7678. {
  7679. if (shouldOverwriteFiles)
  7680. targetFile.deleteFile();
  7681. if ((! targetFile.exists())
  7682. && targetFile.getParentDirectory().createDirectory())
  7683. {
  7684. ScopedPointer <FileOutputStream> out (targetFile.createOutputStream());
  7685. if (out != 0)
  7686. {
  7687. out->writeFromInputStream (*in, -1);
  7688. out = 0;
  7689. targetFile.setCreationTime (zei.fileTime);
  7690. targetFile.setLastModificationTime (zei.fileTime);
  7691. targetFile.setLastAccessTime (zei.fileTime);
  7692. }
  7693. }
  7694. }
  7695. }
  7696. }
  7697. }
  7698. END_JUCE_NAMESPACE
  7699. /*** End of inlined file: juce_ZipFile.cpp ***/
  7700. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  7701. #if JUCE_MSVC
  7702. #pragma warning (push)
  7703. #pragma warning (disable: 4514 4996)
  7704. #endif
  7705. #include <cwctype>
  7706. #include <cctype>
  7707. #include <ctime>
  7708. BEGIN_JUCE_NAMESPACE
  7709. int CharacterFunctions::length (const char* const s) throw()
  7710. {
  7711. return (int) strlen (s);
  7712. }
  7713. int CharacterFunctions::length (const juce_wchar* const s) throw()
  7714. {
  7715. return (int) wcslen (s);
  7716. }
  7717. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  7718. {
  7719. strncpy (dest, src, maxChars);
  7720. }
  7721. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  7722. {
  7723. wcsncpy (dest, src, maxChars);
  7724. }
  7725. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  7726. {
  7727. mbstowcs (dest, src, maxChars);
  7728. }
  7729. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  7730. {
  7731. wcstombs (dest, src, maxChars);
  7732. }
  7733. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  7734. {
  7735. return (int) wcstombs (0, src, 0);
  7736. }
  7737. void CharacterFunctions::append (char* dest, const char* src) throw()
  7738. {
  7739. strcat (dest, src);
  7740. }
  7741. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  7742. {
  7743. wcscat (dest, src);
  7744. }
  7745. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  7746. {
  7747. return strcmp (s1, s2);
  7748. }
  7749. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  7750. {
  7751. jassert (s1 != 0 && s2 != 0);
  7752. return wcscmp (s1, s2);
  7753. }
  7754. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  7755. {
  7756. jassert (s1 != 0 && s2 != 0);
  7757. return strncmp (s1, s2, maxChars);
  7758. }
  7759. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7760. {
  7761. jassert (s1 != 0 && s2 != 0);
  7762. return wcsncmp (s1, s2, maxChars);
  7763. }
  7764. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  7765. {
  7766. jassert (s1 != 0 && s2 != 0);
  7767. for (;;)
  7768. {
  7769. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  7770. if (diff != 0)
  7771. return diff;
  7772. else if (*s1 == 0)
  7773. break;
  7774. ++s1;
  7775. ++s2;
  7776. }
  7777. return 0;
  7778. }
  7779. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  7780. {
  7781. return -compare (s2, s1);
  7782. }
  7783. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  7784. {
  7785. jassert (s1 != 0 && s2 != 0);
  7786. #if JUCE_WINDOWS
  7787. return stricmp (s1, s2);
  7788. #else
  7789. return strcasecmp (s1, s2);
  7790. #endif
  7791. }
  7792. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  7793. {
  7794. jassert (s1 != 0 && s2 != 0);
  7795. #if JUCE_WINDOWS
  7796. return _wcsicmp (s1, s2);
  7797. #else
  7798. for (;;)
  7799. {
  7800. if (*s1 != *s2)
  7801. {
  7802. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7803. if (diff != 0)
  7804. return diff < 0 ? -1 : 1;
  7805. }
  7806. else if (*s1 == 0)
  7807. break;
  7808. ++s1;
  7809. ++s2;
  7810. }
  7811. return 0;
  7812. #endif
  7813. }
  7814. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  7815. {
  7816. jassert (s1 != 0 && s2 != 0);
  7817. for (;;)
  7818. {
  7819. if (*s1 != *s2)
  7820. {
  7821. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7822. if (diff != 0)
  7823. return diff < 0 ? -1 : 1;
  7824. }
  7825. else if (*s1 == 0)
  7826. break;
  7827. ++s1;
  7828. ++s2;
  7829. }
  7830. return 0;
  7831. }
  7832. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  7833. {
  7834. jassert (s1 != 0 && s2 != 0);
  7835. #if JUCE_WINDOWS
  7836. return strnicmp (s1, s2, maxChars);
  7837. #else
  7838. return strncasecmp (s1, s2, maxChars);
  7839. #endif
  7840. }
  7841. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7842. {
  7843. jassert (s1 != 0 && s2 != 0);
  7844. #if JUCE_WINDOWS
  7845. return _wcsnicmp (s1, s2, maxChars);
  7846. #else
  7847. while (--maxChars >= 0)
  7848. {
  7849. if (*s1 != *s2)
  7850. {
  7851. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7852. if (diff != 0)
  7853. return diff < 0 ? -1 : 1;
  7854. }
  7855. else if (*s1 == 0)
  7856. break;
  7857. ++s1;
  7858. ++s2;
  7859. }
  7860. return 0;
  7861. #endif
  7862. }
  7863. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  7864. {
  7865. return strstr (haystack, needle);
  7866. }
  7867. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  7868. {
  7869. return wcsstr (haystack, needle);
  7870. }
  7871. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  7872. {
  7873. if (haystack != 0)
  7874. {
  7875. int i = 0;
  7876. if (ignoreCase)
  7877. {
  7878. const char n1 = toLowerCase (needle);
  7879. const char n2 = toUpperCase (needle);
  7880. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7881. {
  7882. while (haystack[i] != 0)
  7883. {
  7884. if (haystack[i] == n1 || haystack[i] == n2)
  7885. return i;
  7886. ++i;
  7887. }
  7888. return -1;
  7889. }
  7890. jassert (n1 == needle);
  7891. }
  7892. while (haystack[i] != 0)
  7893. {
  7894. if (haystack[i] == needle)
  7895. return i;
  7896. ++i;
  7897. }
  7898. }
  7899. return -1;
  7900. }
  7901. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  7902. {
  7903. if (haystack != 0)
  7904. {
  7905. int i = 0;
  7906. if (ignoreCase)
  7907. {
  7908. const juce_wchar n1 = toLowerCase (needle);
  7909. const juce_wchar n2 = toUpperCase (needle);
  7910. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7911. {
  7912. while (haystack[i] != 0)
  7913. {
  7914. if (haystack[i] == n1 || haystack[i] == n2)
  7915. return i;
  7916. ++i;
  7917. }
  7918. return -1;
  7919. }
  7920. jassert (n1 == needle);
  7921. }
  7922. while (haystack[i] != 0)
  7923. {
  7924. if (haystack[i] == needle)
  7925. return i;
  7926. ++i;
  7927. }
  7928. }
  7929. return -1;
  7930. }
  7931. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  7932. {
  7933. jassert (haystack != 0);
  7934. int i = 0;
  7935. while (haystack[i] != 0)
  7936. {
  7937. if (haystack[i] == needle)
  7938. return i;
  7939. ++i;
  7940. }
  7941. return -1;
  7942. }
  7943. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  7944. {
  7945. jassert (haystack != 0);
  7946. int i = 0;
  7947. while (haystack[i] != 0)
  7948. {
  7949. if (haystack[i] == needle)
  7950. return i;
  7951. ++i;
  7952. }
  7953. return -1;
  7954. }
  7955. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  7956. {
  7957. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  7958. }
  7959. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  7960. {
  7961. if (allowedChars == 0)
  7962. return 0;
  7963. int i = 0;
  7964. for (;;)
  7965. {
  7966. if (indexOfCharFast (allowedChars, text[i]) < 0)
  7967. break;
  7968. ++i;
  7969. }
  7970. return i;
  7971. }
  7972. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  7973. {
  7974. return (int) strftime (dest, maxChars, format, tm);
  7975. }
  7976. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  7977. {
  7978. return (int) wcsftime (dest, maxChars, format, tm);
  7979. }
  7980. int CharacterFunctions::getIntValue (const char* const s) throw()
  7981. {
  7982. return atoi (s);
  7983. }
  7984. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  7985. {
  7986. #if JUCE_WINDOWS
  7987. return _wtoi (s);
  7988. #else
  7989. int v = 0;
  7990. while (isWhitespace (*s))
  7991. ++s;
  7992. const bool isNeg = *s == '-';
  7993. if (isNeg)
  7994. ++s;
  7995. for (;;)
  7996. {
  7997. const wchar_t c = *s++;
  7998. if (c >= '0' && c <= '9')
  7999. v = v * 10 + (int) (c - '0');
  8000. else
  8001. break;
  8002. }
  8003. return isNeg ? -v : v;
  8004. #endif
  8005. }
  8006. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  8007. {
  8008. #if JUCE_LINUX
  8009. return atoll (s);
  8010. #elif JUCE_WINDOWS
  8011. return _atoi64 (s);
  8012. #else
  8013. int64 v = 0;
  8014. while (isWhitespace (*s))
  8015. ++s;
  8016. const bool isNeg = *s == '-';
  8017. if (isNeg)
  8018. ++s;
  8019. for (;;)
  8020. {
  8021. const char c = *s++;
  8022. if (c >= '0' && c <= '9')
  8023. v = v * 10 + (int64) (c - '0');
  8024. else
  8025. break;
  8026. }
  8027. return isNeg ? -v : v;
  8028. #endif
  8029. }
  8030. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  8031. {
  8032. #if JUCE_WINDOWS
  8033. return _wtoi64 (s);
  8034. #else
  8035. int64 v = 0;
  8036. while (isWhitespace (*s))
  8037. ++s;
  8038. const bool isNeg = *s == '-';
  8039. if (isNeg)
  8040. ++s;
  8041. for (;;)
  8042. {
  8043. const juce_wchar c = *s++;
  8044. if (c >= '0' && c <= '9')
  8045. v = v * 10 + (int64) (c - '0');
  8046. else
  8047. break;
  8048. }
  8049. return isNeg ? -v : v;
  8050. #endif
  8051. }
  8052. static double juce_mulexp10 (const double value, int exponent) throw()
  8053. {
  8054. if (exponent == 0)
  8055. return value;
  8056. if (value == 0)
  8057. return 0;
  8058. const bool negative = (exponent < 0);
  8059. if (negative)
  8060. exponent = -exponent;
  8061. double result = 1.0, power = 10.0;
  8062. for (int bit = 1; exponent != 0; bit <<= 1)
  8063. {
  8064. if ((exponent & bit) != 0)
  8065. {
  8066. exponent ^= bit;
  8067. result *= power;
  8068. if (exponent == 0)
  8069. break;
  8070. }
  8071. power *= power;
  8072. }
  8073. return negative ? (value / result) : (value * result);
  8074. }
  8075. template <class CharType>
  8076. double juce_atof (const CharType* const original) throw()
  8077. {
  8078. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  8079. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  8080. int exponent = 0, decPointIndex = 0, digit = 0;
  8081. int lastDigit = 0, numSignificantDigits = 0;
  8082. bool isNegative = false, digitsFound = false;
  8083. const int maxSignificantDigits = 15 + 2;
  8084. const CharType* s = original;
  8085. while (CharacterFunctions::isWhitespace (*s))
  8086. ++s;
  8087. switch (*s)
  8088. {
  8089. case '-': isNegative = true; // fall-through..
  8090. case '+': ++s;
  8091. }
  8092. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  8093. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  8094. for (;;)
  8095. {
  8096. if (CharacterFunctions::isDigit (*s))
  8097. {
  8098. lastDigit = digit;
  8099. digit = *s++ - '0';
  8100. digitsFound = true;
  8101. if (decPointIndex != 0)
  8102. exponentAdjustment[1]++;
  8103. if (numSignificantDigits == 0 && digit == 0)
  8104. continue;
  8105. if (++numSignificantDigits > maxSignificantDigits)
  8106. {
  8107. if (digit > 5)
  8108. ++accumulator [decPointIndex];
  8109. else if (digit == 5 && (lastDigit & 1) != 0)
  8110. ++accumulator [decPointIndex];
  8111. if (decPointIndex > 0)
  8112. exponentAdjustment[1]--;
  8113. else
  8114. exponentAdjustment[0]++;
  8115. while (CharacterFunctions::isDigit (*s))
  8116. {
  8117. ++s;
  8118. if (decPointIndex == 0)
  8119. exponentAdjustment[0]++;
  8120. }
  8121. }
  8122. else
  8123. {
  8124. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  8125. if (accumulator [decPointIndex] > maxAccumulatorValue)
  8126. {
  8127. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  8128. + accumulator [decPointIndex];
  8129. accumulator [decPointIndex] = 0;
  8130. exponentAccumulator [decPointIndex] = 0;
  8131. }
  8132. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  8133. exponentAccumulator [decPointIndex]++;
  8134. }
  8135. }
  8136. else if (decPointIndex == 0 && *s == '.')
  8137. {
  8138. ++s;
  8139. decPointIndex = 1;
  8140. if (numSignificantDigits > maxSignificantDigits)
  8141. {
  8142. while (CharacterFunctions::isDigit (*s))
  8143. ++s;
  8144. break;
  8145. }
  8146. }
  8147. else
  8148. {
  8149. break;
  8150. }
  8151. }
  8152. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  8153. if (decPointIndex != 0)
  8154. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  8155. if ((*s == 'e' || *s == 'E') && digitsFound)
  8156. {
  8157. bool negativeExponent = false;
  8158. switch (*++s)
  8159. {
  8160. case '-': negativeExponent = true; // fall-through..
  8161. case '+': ++s;
  8162. }
  8163. while (CharacterFunctions::isDigit (*s))
  8164. exponent = (exponent * 10) + (*s++ - '0');
  8165. if (negativeExponent)
  8166. exponent = -exponent;
  8167. }
  8168. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  8169. if (decPointIndex != 0)
  8170. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  8171. return isNegative ? -r : r;
  8172. }
  8173. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  8174. {
  8175. return juce_atof <char> (s);
  8176. }
  8177. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  8178. {
  8179. return juce_atof <juce_wchar> (s);
  8180. }
  8181. char CharacterFunctions::toUpperCase (const char character) throw()
  8182. {
  8183. return (char) toupper (character);
  8184. }
  8185. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8186. {
  8187. return towupper (character);
  8188. }
  8189. void CharacterFunctions::toUpperCase (char* s) throw()
  8190. {
  8191. #if JUCE_WINDOWS
  8192. strupr (s);
  8193. #else
  8194. while (*s != 0)
  8195. {
  8196. *s = toUpperCase (*s);
  8197. ++s;
  8198. }
  8199. #endif
  8200. }
  8201. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  8202. {
  8203. #if JUCE_WINDOWS
  8204. _wcsupr (s);
  8205. #else
  8206. while (*s != 0)
  8207. {
  8208. *s = toUpperCase (*s);
  8209. ++s;
  8210. }
  8211. #endif
  8212. }
  8213. bool CharacterFunctions::isUpperCase (const char character) throw()
  8214. {
  8215. return isupper (character) != 0;
  8216. }
  8217. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8218. {
  8219. #if JUCE_WINDOWS
  8220. return iswupper (character) != 0;
  8221. #else
  8222. return toLowerCase (character) != character;
  8223. #endif
  8224. }
  8225. char CharacterFunctions::toLowerCase (const char character) throw()
  8226. {
  8227. return (char) tolower (character);
  8228. }
  8229. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8230. {
  8231. return towlower (character);
  8232. }
  8233. void CharacterFunctions::toLowerCase (char* s) throw()
  8234. {
  8235. #if JUCE_WINDOWS
  8236. strlwr (s);
  8237. #else
  8238. while (*s != 0)
  8239. {
  8240. *s = toLowerCase (*s);
  8241. ++s;
  8242. }
  8243. #endif
  8244. }
  8245. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  8246. {
  8247. #if JUCE_WINDOWS
  8248. _wcslwr (s);
  8249. #else
  8250. while (*s != 0)
  8251. {
  8252. *s = toLowerCase (*s);
  8253. ++s;
  8254. }
  8255. #endif
  8256. }
  8257. bool CharacterFunctions::isLowerCase (const char character) throw()
  8258. {
  8259. return islower (character) != 0;
  8260. }
  8261. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8262. {
  8263. #if JUCE_WINDOWS
  8264. return iswlower (character) != 0;
  8265. #else
  8266. return toUpperCase (character) != character;
  8267. #endif
  8268. }
  8269. bool CharacterFunctions::isWhitespace (const char character) throw()
  8270. {
  8271. return character == ' ' || (character <= 13 && character >= 9);
  8272. }
  8273. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8274. {
  8275. return iswspace (character) != 0;
  8276. }
  8277. bool CharacterFunctions::isDigit (const char character) throw()
  8278. {
  8279. return (character >= '0' && character <= '9');
  8280. }
  8281. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8282. {
  8283. return iswdigit (character) != 0;
  8284. }
  8285. bool CharacterFunctions::isLetter (const char character) throw()
  8286. {
  8287. return (character >= 'a' && character <= 'z')
  8288. || (character >= 'A' && character <= 'Z');
  8289. }
  8290. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8291. {
  8292. return iswalpha (character) != 0;
  8293. }
  8294. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  8295. {
  8296. return (character >= 'a' && character <= 'z')
  8297. || (character >= 'A' && character <= 'Z')
  8298. || (character >= '0' && character <= '9');
  8299. }
  8300. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  8301. {
  8302. return iswalnum (character) != 0;
  8303. }
  8304. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  8305. {
  8306. unsigned int d = digit - '0';
  8307. if (d < (unsigned int) 10)
  8308. return (int) d;
  8309. d += (unsigned int) ('0' - 'a');
  8310. if (d < (unsigned int) 6)
  8311. return (int) d + 10;
  8312. d += (unsigned int) ('a' - 'A');
  8313. if (d < (unsigned int) 6)
  8314. return (int) d + 10;
  8315. return -1;
  8316. }
  8317. #if JUCE_MSVC
  8318. #pragma warning (pop)
  8319. #endif
  8320. END_JUCE_NAMESPACE
  8321. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  8322. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  8323. BEGIN_JUCE_NAMESPACE
  8324. LocalisedStrings::LocalisedStrings (const String& fileContents)
  8325. {
  8326. loadFromText (fileContents);
  8327. }
  8328. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  8329. {
  8330. loadFromText (fileToLoad.loadFileAsString());
  8331. }
  8332. LocalisedStrings::~LocalisedStrings()
  8333. {
  8334. }
  8335. const String LocalisedStrings::translate (const String& text) const
  8336. {
  8337. return translations.getValue (text, text);
  8338. }
  8339. static int findCloseQuote (const String& text, int startPos)
  8340. {
  8341. juce_wchar lastChar = 0;
  8342. for (;;)
  8343. {
  8344. const juce_wchar c = text [startPos];
  8345. if (c == 0 || (c == '"' && lastChar != '\\'))
  8346. break;
  8347. lastChar = c;
  8348. ++startPos;
  8349. }
  8350. return startPos;
  8351. }
  8352. static const String unescapeString (const String& s)
  8353. {
  8354. return s.replace ("\\\"", "\"")
  8355. .replace ("\\\'", "\'")
  8356. .replace ("\\t", "\t")
  8357. .replace ("\\r", "\r")
  8358. .replace ("\\n", "\n");
  8359. }
  8360. void LocalisedStrings::loadFromText (const String& fileContents)
  8361. {
  8362. StringArray lines;
  8363. lines.addLines (fileContents);
  8364. for (int i = 0; i < lines.size(); ++i)
  8365. {
  8366. String line (lines[i].trim());
  8367. if (line.startsWithChar ('"'))
  8368. {
  8369. int closeQuote = findCloseQuote (line, 1);
  8370. const String originalText (unescapeString (line.substring (1, closeQuote)));
  8371. if (originalText.isNotEmpty())
  8372. {
  8373. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  8374. closeQuote = findCloseQuote (line, openingQuote + 1);
  8375. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  8376. if (newText.isNotEmpty())
  8377. translations.set (originalText, newText);
  8378. }
  8379. }
  8380. else if (line.startsWithIgnoreCase ("language:"))
  8381. {
  8382. languageName = line.substring (9).trim();
  8383. }
  8384. else if (line.startsWithIgnoreCase ("countries:"))
  8385. {
  8386. countryCodes.addTokens (line.substring (10).trim(), true);
  8387. countryCodes.trim();
  8388. countryCodes.removeEmptyStrings();
  8389. }
  8390. }
  8391. }
  8392. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  8393. {
  8394. translations.setIgnoresCase (shouldIgnoreCase);
  8395. }
  8396. static CriticalSection currentMappingsLock;
  8397. static LocalisedStrings* currentMappings = 0;
  8398. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  8399. {
  8400. const ScopedLock sl (currentMappingsLock);
  8401. delete currentMappings;
  8402. currentMappings = newTranslations;
  8403. }
  8404. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  8405. {
  8406. return currentMappings;
  8407. }
  8408. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  8409. {
  8410. const ScopedLock sl (currentMappingsLock);
  8411. if (currentMappings != 0)
  8412. return currentMappings->translate (text);
  8413. return text;
  8414. }
  8415. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  8416. {
  8417. return translateWithCurrentMappings (String (text));
  8418. }
  8419. END_JUCE_NAMESPACE
  8420. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  8421. /*** Start of inlined file: juce_String.cpp ***/
  8422. #if JUCE_MSVC
  8423. #pragma warning (push)
  8424. #pragma warning (disable: 4514)
  8425. #endif
  8426. #include <locale>
  8427. BEGIN_JUCE_NAMESPACE
  8428. #if JUCE_MSVC
  8429. #pragma warning (pop)
  8430. #endif
  8431. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  8432. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  8433. #endif
  8434. class StringHolder
  8435. {
  8436. public:
  8437. StringHolder()
  8438. : refCount (0x3fffffff), allocatedNumChars (0)
  8439. {
  8440. text[0] = 0;
  8441. }
  8442. static juce_wchar* createUninitialised (const size_t numChars)
  8443. {
  8444. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  8445. s->refCount.value = 0;
  8446. s->allocatedNumChars = numChars;
  8447. return &(s->text[0]);
  8448. }
  8449. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  8450. {
  8451. juce_wchar* const dest = createUninitialised (numChars);
  8452. copyChars (dest, src, numChars);
  8453. return dest;
  8454. }
  8455. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  8456. {
  8457. juce_wchar* const dest = createUninitialised (numChars);
  8458. CharacterFunctions::copy (dest, src, (int) numChars);
  8459. dest [numChars] = 0;
  8460. return dest;
  8461. }
  8462. static inline juce_wchar* getEmpty() throw()
  8463. {
  8464. return &(empty.text[0]);
  8465. }
  8466. static void retain (juce_wchar* const text) throw()
  8467. {
  8468. ++(bufferFromText (text)->refCount);
  8469. }
  8470. static inline void release (StringHolder* const b) throw()
  8471. {
  8472. if (--(b->refCount) == -1 && b != &empty)
  8473. delete[] reinterpret_cast <char*> (b);
  8474. }
  8475. static void release (juce_wchar* const text) throw()
  8476. {
  8477. release (bufferFromText (text));
  8478. }
  8479. static juce_wchar* makeUnique (juce_wchar* const text)
  8480. {
  8481. StringHolder* const b = bufferFromText (text);
  8482. if (b->refCount.get() <= 0)
  8483. return text;
  8484. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  8485. release (b);
  8486. return newText;
  8487. }
  8488. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  8489. {
  8490. StringHolder* const b = bufferFromText (text);
  8491. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  8492. return text;
  8493. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  8494. copyChars (newText, text, b->allocatedNumChars);
  8495. release (b);
  8496. return newText;
  8497. }
  8498. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  8499. {
  8500. return bufferFromText (text)->allocatedNumChars;
  8501. }
  8502. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  8503. {
  8504. memcpy (dest, src, numChars * sizeof (juce_wchar));
  8505. dest [numChars] = 0;
  8506. }
  8507. Atomic<int> refCount;
  8508. size_t allocatedNumChars;
  8509. juce_wchar text[1];
  8510. static StringHolder empty;
  8511. private:
  8512. static inline StringHolder* bufferFromText (void* const text) throw()
  8513. {
  8514. // (Can't use offsetof() here because of warnings about this not being a POD)
  8515. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  8516. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  8517. }
  8518. };
  8519. StringHolder StringHolder::empty;
  8520. const String String::empty;
  8521. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  8522. {
  8523. jassert (t[numChars] == 0); // must have a null terminator
  8524. text = StringHolder::createCopy (t, numChars);
  8525. }
  8526. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  8527. {
  8528. if (numExtraChars > 0)
  8529. {
  8530. const int oldLen = length();
  8531. const int newTotalLen = oldLen + numExtraChars;
  8532. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  8533. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  8534. }
  8535. }
  8536. void String::preallocateStorage (const size_t numChars)
  8537. {
  8538. text = StringHolder::makeUniqueWithSize (text, numChars);
  8539. }
  8540. String::String() throw()
  8541. : text (StringHolder::getEmpty())
  8542. {
  8543. }
  8544. String::~String() throw()
  8545. {
  8546. StringHolder::release (text);
  8547. }
  8548. String::String (const String& other) throw()
  8549. : text (other.text)
  8550. {
  8551. StringHolder::retain (text);
  8552. }
  8553. void String::swapWith (String& other) throw()
  8554. {
  8555. swapVariables (text, other.text);
  8556. }
  8557. String& String::operator= (const String& other) throw()
  8558. {
  8559. juce_wchar* const newText = other.text;
  8560. StringHolder::retain (newText);
  8561. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  8562. return *this;
  8563. }
  8564. String::String (const size_t numChars, const int /*dummyVariable*/)
  8565. : text (StringHolder::createUninitialised (numChars))
  8566. {
  8567. }
  8568. String::String (const String& stringToCopy, const size_t charsToAllocate)
  8569. {
  8570. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  8571. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  8572. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  8573. }
  8574. String::String (const char* const t)
  8575. {
  8576. if (t != 0 && *t != 0)
  8577. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8578. else
  8579. text = StringHolder::getEmpty();
  8580. }
  8581. String::String (const juce_wchar* const t)
  8582. {
  8583. if (t != 0 && *t != 0)
  8584. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8585. else
  8586. text = StringHolder::getEmpty();
  8587. }
  8588. String::String (const char* const t, const size_t maxChars)
  8589. {
  8590. int i;
  8591. for (i = 0; (size_t) i < maxChars; ++i)
  8592. if (t[i] == 0)
  8593. break;
  8594. if (i > 0)
  8595. text = StringHolder::createCopy (t, i);
  8596. else
  8597. text = StringHolder::getEmpty();
  8598. }
  8599. String::String (const juce_wchar* const t, const size_t maxChars)
  8600. {
  8601. int i;
  8602. for (i = 0; (size_t) i < maxChars; ++i)
  8603. if (t[i] == 0)
  8604. break;
  8605. if (i > 0)
  8606. text = StringHolder::createCopy (t, i);
  8607. else
  8608. text = StringHolder::getEmpty();
  8609. }
  8610. const String String::charToString (const juce_wchar character)
  8611. {
  8612. String result ((size_t) 1, (int) 0);
  8613. result.text[0] = character;
  8614. result.text[1] = 0;
  8615. return result;
  8616. }
  8617. namespace NumberToStringConverters
  8618. {
  8619. // pass in a pointer to the END of a buffer..
  8620. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  8621. {
  8622. *--t = 0;
  8623. int64 v = (n >= 0) ? n : -n;
  8624. do
  8625. {
  8626. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8627. v /= 10;
  8628. } while (v > 0);
  8629. if (n < 0)
  8630. *--t = '-';
  8631. return t;
  8632. }
  8633. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  8634. {
  8635. *--t = 0;
  8636. do
  8637. {
  8638. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8639. v /= 10;
  8640. } while (v > 0);
  8641. return t;
  8642. }
  8643. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  8644. {
  8645. if (n == (int) 0x80000000) // (would cause an overflow)
  8646. return int64ToString (t, n);
  8647. *--t = 0;
  8648. int v = abs (n);
  8649. do
  8650. {
  8651. *--t = (juce_wchar) ('0' + (v % 10));
  8652. v /= 10;
  8653. } while (v > 0);
  8654. if (n < 0)
  8655. *--t = '-';
  8656. return t;
  8657. }
  8658. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  8659. {
  8660. *--t = 0;
  8661. do
  8662. {
  8663. *--t = (juce_wchar) ('0' + (v % 10));
  8664. v /= 10;
  8665. } while (v > 0);
  8666. return t;
  8667. }
  8668. static juce_wchar getDecimalPoint()
  8669. {
  8670. #if JUCE_WINDOWS && _MSC_VER < 1400
  8671. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  8672. #else
  8673. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  8674. #endif
  8675. return dp;
  8676. }
  8677. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  8678. {
  8679. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  8680. {
  8681. juce_wchar* const end = buffer + numChars;
  8682. juce_wchar* t = end;
  8683. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  8684. *--t = (juce_wchar) 0;
  8685. while (numDecPlaces >= 0 || v > 0)
  8686. {
  8687. if (numDecPlaces == 0)
  8688. *--t = getDecimalPoint();
  8689. *--t = (juce_wchar) ('0' + (v % 10));
  8690. v /= 10;
  8691. --numDecPlaces;
  8692. }
  8693. if (n < 0)
  8694. *--t = '-';
  8695. len = end - t - 1;
  8696. return t;
  8697. }
  8698. else
  8699. {
  8700. #if JUCE_WINDOWS
  8701. #if _MSC_VER <= 1400
  8702. len = _snwprintf (buffer, numChars, L"%.9g", n);
  8703. #else
  8704. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  8705. #endif
  8706. #else
  8707. len = swprintf (buffer, numChars, L"%.9g", n);
  8708. #endif
  8709. return buffer;
  8710. }
  8711. }
  8712. }
  8713. String::String (const int number)
  8714. {
  8715. juce_wchar buffer [16];
  8716. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8717. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8718. createInternal (start, end - start - 1);
  8719. }
  8720. String::String (const unsigned int number)
  8721. {
  8722. juce_wchar buffer [16];
  8723. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8724. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8725. createInternal (start, end - start - 1);
  8726. }
  8727. String::String (const short number)
  8728. {
  8729. juce_wchar buffer [16];
  8730. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8731. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  8732. createInternal (start, end - start - 1);
  8733. }
  8734. String::String (const unsigned short number)
  8735. {
  8736. juce_wchar buffer [16];
  8737. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8738. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  8739. createInternal (start, end - start - 1);
  8740. }
  8741. String::String (const int64 number)
  8742. {
  8743. juce_wchar buffer [32];
  8744. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8745. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  8746. createInternal (start, end - start - 1);
  8747. }
  8748. String::String (const uint64 number)
  8749. {
  8750. juce_wchar buffer [32];
  8751. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8752. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  8753. createInternal (start, end - start - 1);
  8754. }
  8755. String::String (const float number, const int numberOfDecimalPlaces)
  8756. {
  8757. juce_wchar buffer [48];
  8758. size_t len;
  8759. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  8760. createInternal (start, len);
  8761. }
  8762. String::String (const double number, const int numberOfDecimalPlaces)
  8763. {
  8764. juce_wchar buffer [48];
  8765. size_t len;
  8766. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  8767. createInternal (start, len);
  8768. }
  8769. int String::length() const throw()
  8770. {
  8771. return CharacterFunctions::length (text);
  8772. }
  8773. int String::hashCode() const throw()
  8774. {
  8775. const juce_wchar* t = text;
  8776. int result = 0;
  8777. while (*t != (juce_wchar) 0)
  8778. result = 31 * result + *t++;
  8779. return result;
  8780. }
  8781. int64 String::hashCode64() const throw()
  8782. {
  8783. const juce_wchar* t = text;
  8784. int64 result = 0;
  8785. while (*t != (juce_wchar) 0)
  8786. result = 101 * result + *t++;
  8787. return result;
  8788. }
  8789. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const String& string2) throw()
  8790. {
  8791. return string1.compare (string2) == 0;
  8792. }
  8793. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const char* string2) throw()
  8794. {
  8795. return string1.compare (string2) == 0;
  8796. }
  8797. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const juce_wchar* string2) throw()
  8798. {
  8799. return string1.compare (string2) == 0;
  8800. }
  8801. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const String& string2) throw()
  8802. {
  8803. return string1.compare (string2) != 0;
  8804. }
  8805. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const char* string2) throw()
  8806. {
  8807. return string1.compare (string2) != 0;
  8808. }
  8809. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const juce_wchar* string2) throw()
  8810. {
  8811. return string1.compare (string2) != 0;
  8812. }
  8813. bool JUCE_PUBLIC_FUNCTION operator> (const String& string1, const String& string2) throw()
  8814. {
  8815. return string1.compare (string2) > 0;
  8816. }
  8817. bool JUCE_PUBLIC_FUNCTION operator< (const String& string1, const String& string2) throw()
  8818. {
  8819. return string1.compare (string2) < 0;
  8820. }
  8821. bool JUCE_PUBLIC_FUNCTION operator>= (const String& string1, const String& string2) throw()
  8822. {
  8823. return string1.compare (string2) >= 0;
  8824. }
  8825. bool JUCE_PUBLIC_FUNCTION operator<= (const String& string1, const String& string2) throw()
  8826. {
  8827. return string1.compare (string2) <= 0;
  8828. }
  8829. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  8830. {
  8831. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8832. : isEmpty();
  8833. }
  8834. bool String::equalsIgnoreCase (const char* t) const throw()
  8835. {
  8836. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8837. : isEmpty();
  8838. }
  8839. bool String::equalsIgnoreCase (const String& other) const throw()
  8840. {
  8841. return text == other.text
  8842. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  8843. }
  8844. int String::compare (const String& other) const throw()
  8845. {
  8846. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  8847. }
  8848. int String::compare (const char* other) const throw()
  8849. {
  8850. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8851. }
  8852. int String::compare (const juce_wchar* other) const throw()
  8853. {
  8854. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8855. }
  8856. int String::compareIgnoreCase (const String& other) const throw()
  8857. {
  8858. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  8859. }
  8860. int String::compareLexicographically (const String& other) const throw()
  8861. {
  8862. const juce_wchar* s1 = text;
  8863. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  8864. ++s1;
  8865. const juce_wchar* s2 = other.text;
  8866. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  8867. ++s2;
  8868. return CharacterFunctions::compareIgnoreCase (s1, s2);
  8869. }
  8870. String& String::operator+= (const juce_wchar* const t)
  8871. {
  8872. if (t != 0)
  8873. appendInternal (t, CharacterFunctions::length (t));
  8874. return *this;
  8875. }
  8876. String& String::operator+= (const String& other)
  8877. {
  8878. if (isEmpty())
  8879. operator= (other);
  8880. else
  8881. appendInternal (other.text, other.length());
  8882. return *this;
  8883. }
  8884. String& String::operator+= (const char ch)
  8885. {
  8886. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8887. return operator+= (static_cast <const juce_wchar*> (asString));
  8888. }
  8889. String& String::operator+= (const juce_wchar ch)
  8890. {
  8891. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8892. return operator+= (static_cast <const juce_wchar*> (asString));
  8893. }
  8894. String& String::operator+= (const int number)
  8895. {
  8896. juce_wchar buffer [16];
  8897. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8898. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8899. appendInternal (start, (int) (end - start));
  8900. return *this;
  8901. }
  8902. String& String::operator+= (const unsigned int number)
  8903. {
  8904. juce_wchar buffer [16];
  8905. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8906. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8907. appendInternal (start, (int) (end - start));
  8908. return *this;
  8909. }
  8910. void String::append (const juce_wchar* const other, const int howMany)
  8911. {
  8912. if (howMany > 0)
  8913. {
  8914. int i;
  8915. for (i = 0; i < howMany; ++i)
  8916. if (other[i] == 0)
  8917. break;
  8918. appendInternal (other, i);
  8919. }
  8920. }
  8921. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1, const String& string2)
  8922. {
  8923. String s (string1);
  8924. return s += string2;
  8925. }
  8926. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1, const String& string2)
  8927. {
  8928. String s (string1);
  8929. return s += string2;
  8930. }
  8931. const String JUCE_PUBLIC_FUNCTION operator+ (const char string1, const String& string2)
  8932. {
  8933. return String::charToString (string1) + string2;
  8934. }
  8935. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar string1, const String& string2)
  8936. {
  8937. return String::charToString (string1) + string2;
  8938. }
  8939. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const String& string2)
  8940. {
  8941. return string1 += string2;
  8942. }
  8943. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char* const string2)
  8944. {
  8945. return string1 += string2;
  8946. }
  8947. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar* const string2)
  8948. {
  8949. return string1 += string2;
  8950. }
  8951. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char string2)
  8952. {
  8953. return string1 += string2;
  8954. }
  8955. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar string2)
  8956. {
  8957. return string1 += string2;
  8958. }
  8959. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char characterToAppend)
  8960. {
  8961. return string1 += characterToAppend;
  8962. }
  8963. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar characterToAppend)
  8964. {
  8965. return string1 += characterToAppend;
  8966. }
  8967. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char* const string2)
  8968. {
  8969. return string1 += string2;
  8970. }
  8971. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar* const string2)
  8972. {
  8973. return string1 += string2;
  8974. }
  8975. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const String& string2)
  8976. {
  8977. return string1 += string2;
  8978. }
  8979. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const short number)
  8980. {
  8981. return string1 += (int) number;
  8982. }
  8983. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const int number)
  8984. {
  8985. return string1 += number;
  8986. }
  8987. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const unsigned int number)
  8988. {
  8989. return string1 += number;
  8990. }
  8991. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const long number)
  8992. {
  8993. return string1 += (int) number;
  8994. }
  8995. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const unsigned long number)
  8996. {
  8997. return string1 += (unsigned int) number;
  8998. }
  8999. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const float number)
  9000. {
  9001. return string1 += String (number);
  9002. }
  9003. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const double number)
  9004. {
  9005. return string1 += String (number);
  9006. }
  9007. OutputStream& JUCE_PUBLIC_FUNCTION operator<< (OutputStream& stream, const String& text)
  9008. {
  9009. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9010. // if lots of large, persistent strings were to be written to streams).
  9011. const int numBytes = text.getNumBytesAsUTF8();
  9012. HeapBlock<char> temp (numBytes + 1);
  9013. text.copyToUTF8 (temp, numBytes + 1);
  9014. stream.write (temp, numBytes);
  9015. return stream;
  9016. }
  9017. int String::indexOfChar (const juce_wchar character) const throw()
  9018. {
  9019. const juce_wchar* t = text;
  9020. for (;;)
  9021. {
  9022. if (*t == character)
  9023. return (int) (t - text);
  9024. if (*t++ == 0)
  9025. return -1;
  9026. }
  9027. }
  9028. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9029. {
  9030. for (int i = length(); --i >= 0;)
  9031. if (text[i] == character)
  9032. return i;
  9033. return -1;
  9034. }
  9035. int String::indexOf (const String& t) const throw()
  9036. {
  9037. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  9038. return r == 0 ? -1 : (int) (r - text);
  9039. }
  9040. int String::indexOfChar (const int startIndex,
  9041. const juce_wchar character) const throw()
  9042. {
  9043. if (startIndex > 0 && startIndex >= length())
  9044. return -1;
  9045. const juce_wchar* t = text + jmax (0, startIndex);
  9046. for (;;)
  9047. {
  9048. if (*t == character)
  9049. return (int) (t - text);
  9050. if (*t == 0)
  9051. return -1;
  9052. ++t;
  9053. }
  9054. }
  9055. int String::indexOfAnyOf (const String& charactersToLookFor,
  9056. const int startIndex,
  9057. const bool ignoreCase) const throw()
  9058. {
  9059. if (startIndex > 0 && startIndex >= length())
  9060. return -1;
  9061. const juce_wchar* t = text + jmax (0, startIndex);
  9062. while (*t != 0)
  9063. {
  9064. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  9065. return (int) (t - text);
  9066. ++t;
  9067. }
  9068. return -1;
  9069. }
  9070. int String::indexOf (const int startIndex, const String& other) const throw()
  9071. {
  9072. if (startIndex > 0 && startIndex >= length())
  9073. return -1;
  9074. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  9075. return found == 0 ? -1 : (int) (found - text);
  9076. }
  9077. int String::indexOfIgnoreCase (const String& other) const throw()
  9078. {
  9079. if (other.isNotEmpty())
  9080. {
  9081. const int len = other.length();
  9082. const int end = length() - len;
  9083. for (int i = 0; i <= end; ++i)
  9084. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  9085. return i;
  9086. }
  9087. return -1;
  9088. }
  9089. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  9090. {
  9091. if (other.isNotEmpty())
  9092. {
  9093. const int len = other.length();
  9094. const int end = length() - len;
  9095. for (int i = jmax (0, startIndex); i <= end; ++i)
  9096. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  9097. return i;
  9098. }
  9099. return -1;
  9100. }
  9101. int String::lastIndexOf (const String& other) const throw()
  9102. {
  9103. if (other.isNotEmpty())
  9104. {
  9105. const int len = other.length();
  9106. int i = length() - len;
  9107. if (i >= 0)
  9108. {
  9109. const juce_wchar* n = text + i;
  9110. while (i >= 0)
  9111. {
  9112. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  9113. return i;
  9114. --i;
  9115. }
  9116. }
  9117. }
  9118. return -1;
  9119. }
  9120. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  9121. {
  9122. if (other.isNotEmpty())
  9123. {
  9124. const int len = other.length();
  9125. int i = length() - len;
  9126. if (i >= 0)
  9127. {
  9128. const juce_wchar* n = text + i;
  9129. while (i >= 0)
  9130. {
  9131. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  9132. return i;
  9133. --i;
  9134. }
  9135. }
  9136. }
  9137. return -1;
  9138. }
  9139. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  9140. {
  9141. for (int i = length(); --i >= 0;)
  9142. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  9143. return i;
  9144. return -1;
  9145. }
  9146. bool String::contains (const String& other) const throw()
  9147. {
  9148. return indexOf (other) >= 0;
  9149. }
  9150. bool String::containsChar (const juce_wchar character) const throw()
  9151. {
  9152. const juce_wchar* t = text;
  9153. for (;;)
  9154. {
  9155. if (*t == 0)
  9156. return false;
  9157. if (*t == character)
  9158. return true;
  9159. ++t;
  9160. }
  9161. }
  9162. bool String::containsIgnoreCase (const String& t) const throw()
  9163. {
  9164. return indexOfIgnoreCase (t) >= 0;
  9165. }
  9166. int String::indexOfWholeWord (const String& word) const throw()
  9167. {
  9168. if (word.isNotEmpty())
  9169. {
  9170. const int wordLen = word.length();
  9171. const int end = length() - wordLen;
  9172. const juce_wchar* t = text;
  9173. for (int i = 0; i <= end; ++i)
  9174. {
  9175. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  9176. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9177. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9178. {
  9179. return i;
  9180. }
  9181. ++t;
  9182. }
  9183. }
  9184. return -1;
  9185. }
  9186. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  9187. {
  9188. if (word.isNotEmpty())
  9189. {
  9190. const int wordLen = word.length();
  9191. const int end = length() - wordLen;
  9192. const juce_wchar* t = text;
  9193. for (int i = 0; i <= end; ++i)
  9194. {
  9195. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  9196. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9197. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9198. {
  9199. return i;
  9200. }
  9201. ++t;
  9202. }
  9203. }
  9204. return -1;
  9205. }
  9206. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  9207. {
  9208. return indexOfWholeWord (wordToLookFor) >= 0;
  9209. }
  9210. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  9211. {
  9212. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9213. }
  9214. static int indexOfMatch (const juce_wchar* const wildcard,
  9215. const juce_wchar* const test,
  9216. const bool ignoreCase) throw()
  9217. {
  9218. int start = 0;
  9219. while (test [start] != 0)
  9220. {
  9221. int i = 0;
  9222. for (;;)
  9223. {
  9224. const juce_wchar wc = wildcard [i];
  9225. const juce_wchar c = test [i + start];
  9226. if (wc == c
  9227. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9228. || (wc == '?' && c != 0))
  9229. {
  9230. if (wc == 0)
  9231. return start;
  9232. ++i;
  9233. }
  9234. else
  9235. {
  9236. if (wc == '*' && (wildcard [i + 1] == 0
  9237. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  9238. {
  9239. return start;
  9240. }
  9241. break;
  9242. }
  9243. }
  9244. ++start;
  9245. }
  9246. return -1;
  9247. }
  9248. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  9249. {
  9250. int i = 0;
  9251. for (;;)
  9252. {
  9253. const juce_wchar wc = wildcard.text [i];
  9254. const juce_wchar c = text [i];
  9255. if (wc == c
  9256. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9257. || (wc == '?' && c != 0))
  9258. {
  9259. if (wc == 0)
  9260. return true;
  9261. ++i;
  9262. }
  9263. else
  9264. {
  9265. return wc == '*' && (wildcard [i + 1] == 0
  9266. || indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  9267. }
  9268. }
  9269. }
  9270. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  9271. {
  9272. const int len = stringToRepeat.length();
  9273. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  9274. juce_wchar* n = result.text;
  9275. *n = 0;
  9276. while (--numberOfTimesToRepeat >= 0)
  9277. {
  9278. StringHolder::copyChars (n, stringToRepeat.text, len);
  9279. n += len;
  9280. }
  9281. return result;
  9282. }
  9283. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  9284. {
  9285. jassert (padCharacter != 0);
  9286. const int len = length();
  9287. if (len >= minimumLength || padCharacter == 0)
  9288. return *this;
  9289. String result ((size_t) minimumLength + 1, (int) 0);
  9290. juce_wchar* n = result.text;
  9291. minimumLength -= len;
  9292. while (--minimumLength >= 0)
  9293. *n++ = padCharacter;
  9294. StringHolder::copyChars (n, text, len);
  9295. return result;
  9296. }
  9297. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  9298. {
  9299. jassert (padCharacter != 0);
  9300. const int len = length();
  9301. if (len >= minimumLength || padCharacter == 0)
  9302. return *this;
  9303. String result (*this, (size_t) minimumLength);
  9304. juce_wchar* n = result.text + len;
  9305. minimumLength -= len;
  9306. while (--minimumLength >= 0)
  9307. *n++ = padCharacter;
  9308. *n = 0;
  9309. return result;
  9310. }
  9311. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  9312. {
  9313. if (index < 0)
  9314. {
  9315. // a negative index to replace from?
  9316. jassertfalse;
  9317. index = 0;
  9318. }
  9319. if (numCharsToReplace < 0)
  9320. {
  9321. // replacing a negative number of characters?
  9322. numCharsToReplace = 0;
  9323. jassertfalse;
  9324. }
  9325. const int len = length();
  9326. if (index + numCharsToReplace > len)
  9327. {
  9328. if (index > len)
  9329. {
  9330. // replacing beyond the end of the string?
  9331. index = len;
  9332. jassertfalse;
  9333. }
  9334. numCharsToReplace = len - index;
  9335. }
  9336. const int newStringLen = stringToInsert.length();
  9337. const int newTotalLen = len + newStringLen - numCharsToReplace;
  9338. if (newTotalLen <= 0)
  9339. return String::empty;
  9340. String result ((size_t) newTotalLen, (int) 0);
  9341. StringHolder::copyChars (result.text, text, index);
  9342. if (newStringLen > 0)
  9343. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  9344. const int endStringLen = newTotalLen - (index + newStringLen);
  9345. if (endStringLen > 0)
  9346. StringHolder::copyChars (result.text + (index + newStringLen),
  9347. text + (index + numCharsToReplace),
  9348. endStringLen);
  9349. return result;
  9350. }
  9351. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  9352. {
  9353. const int stringToReplaceLen = stringToReplace.length();
  9354. const int stringToInsertLen = stringToInsert.length();
  9355. int i = 0;
  9356. String result (*this);
  9357. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  9358. : result.indexOf (i, stringToReplace))) >= 0)
  9359. {
  9360. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  9361. i += stringToInsertLen;
  9362. }
  9363. return result;
  9364. }
  9365. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  9366. {
  9367. const int index = indexOfChar (charToReplace);
  9368. if (index < 0)
  9369. return *this;
  9370. String result (*this, size_t());
  9371. juce_wchar* t = result.text + index;
  9372. while (*t != 0)
  9373. {
  9374. if (*t == charToReplace)
  9375. *t = charToInsert;
  9376. ++t;
  9377. }
  9378. return result;
  9379. }
  9380. const String String::replaceCharacters (const String& charactersToReplace,
  9381. const String& charactersToInsertInstead) const
  9382. {
  9383. String result (*this, size_t());
  9384. juce_wchar* t = result.text;
  9385. const int len2 = charactersToInsertInstead.length();
  9386. // the two strings passed in are supposed to be the same length!
  9387. jassert (len2 == charactersToReplace.length());
  9388. while (*t != 0)
  9389. {
  9390. const int index = charactersToReplace.indexOfChar (*t);
  9391. if (((unsigned int) index) < (unsigned int) len2)
  9392. *t = charactersToInsertInstead [index];
  9393. ++t;
  9394. }
  9395. return result;
  9396. }
  9397. bool String::startsWith (const String& other) const throw()
  9398. {
  9399. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  9400. }
  9401. bool String::startsWithIgnoreCase (const String& other) const throw()
  9402. {
  9403. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  9404. }
  9405. bool String::startsWithChar (const juce_wchar character) const throw()
  9406. {
  9407. jassert (character != 0); // strings can't contain a null character!
  9408. return text[0] == character;
  9409. }
  9410. bool String::endsWithChar (const juce_wchar character) const throw()
  9411. {
  9412. jassert (character != 0); // strings can't contain a null character!
  9413. return text[0] != 0
  9414. && text [length() - 1] == character;
  9415. }
  9416. bool String::endsWith (const String& other) const throw()
  9417. {
  9418. const int thisLen = length();
  9419. const int otherLen = other.length();
  9420. return thisLen >= otherLen
  9421. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  9422. }
  9423. bool String::endsWithIgnoreCase (const String& other) const throw()
  9424. {
  9425. const int thisLen = length();
  9426. const int otherLen = other.length();
  9427. return thisLen >= otherLen
  9428. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  9429. }
  9430. const String String::toUpperCase() const
  9431. {
  9432. String result (*this, size_t());
  9433. CharacterFunctions::toUpperCase (result.text);
  9434. return result;
  9435. }
  9436. const String String::toLowerCase() const
  9437. {
  9438. String result (*this, size_t());
  9439. CharacterFunctions::toLowerCase (result.text);
  9440. return result;
  9441. }
  9442. juce_wchar& String::operator[] (const int index)
  9443. {
  9444. jassert (((unsigned int) index) <= (unsigned int) length());
  9445. text = StringHolder::makeUnique (text);
  9446. return text [index];
  9447. }
  9448. juce_wchar String::getLastCharacter() const throw()
  9449. {
  9450. return isEmpty() ? juce_wchar() : text [length() - 1];
  9451. }
  9452. const String String::substring (int start, int end) const
  9453. {
  9454. if (start < 0)
  9455. start = 0;
  9456. else if (end <= start)
  9457. return empty;
  9458. int len = 0;
  9459. while (len <= end && text [len] != 0)
  9460. ++len;
  9461. if (end >= len)
  9462. {
  9463. if (start == 0)
  9464. return *this;
  9465. end = len;
  9466. }
  9467. return String (text + start, end - start);
  9468. }
  9469. const String String::substring (const int start) const
  9470. {
  9471. if (start <= 0)
  9472. return *this;
  9473. const int len = length();
  9474. if (start >= len)
  9475. return empty;
  9476. return String (text + start, len - start);
  9477. }
  9478. const String String::dropLastCharacters (const int numberToDrop) const
  9479. {
  9480. return String (text, jmax (0, length() - numberToDrop));
  9481. }
  9482. const String String::getLastCharacters (const int numCharacters) const
  9483. {
  9484. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  9485. }
  9486. const String String::fromFirstOccurrenceOf (const String& sub,
  9487. const bool includeSubString,
  9488. const bool ignoreCase) const
  9489. {
  9490. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9491. : indexOf (sub);
  9492. if (i < 0)
  9493. return empty;
  9494. return substring (includeSubString ? i : i + sub.length());
  9495. }
  9496. const String String::fromLastOccurrenceOf (const String& sub,
  9497. const bool includeSubString,
  9498. const bool ignoreCase) const
  9499. {
  9500. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9501. : lastIndexOf (sub);
  9502. if (i < 0)
  9503. return *this;
  9504. return substring (includeSubString ? i : i + sub.length());
  9505. }
  9506. const String String::upToFirstOccurrenceOf (const String& sub,
  9507. const bool includeSubString,
  9508. const bool ignoreCase) const
  9509. {
  9510. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9511. : indexOf (sub);
  9512. if (i < 0)
  9513. return *this;
  9514. return substring (0, includeSubString ? i + sub.length() : i);
  9515. }
  9516. const String String::upToLastOccurrenceOf (const String& sub,
  9517. const bool includeSubString,
  9518. const bool ignoreCase) const
  9519. {
  9520. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9521. : lastIndexOf (sub);
  9522. if (i < 0)
  9523. return *this;
  9524. return substring (0, includeSubString ? i + sub.length() : i);
  9525. }
  9526. bool String::isQuotedString() const
  9527. {
  9528. const String trimmed (trimStart());
  9529. return trimmed[0] == '"'
  9530. || trimmed[0] == '\'';
  9531. }
  9532. const String String::unquoted() const
  9533. {
  9534. String s (*this);
  9535. if (s.text[0] == '"' || s.text[0] == '\'')
  9536. s = s.substring (1);
  9537. const int lastCharIndex = s.length() - 1;
  9538. if (lastCharIndex >= 0
  9539. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  9540. s [lastCharIndex] = 0;
  9541. return s;
  9542. }
  9543. const String String::quoted (const juce_wchar quoteCharacter) const
  9544. {
  9545. if (isEmpty())
  9546. return charToString (quoteCharacter) + quoteCharacter;
  9547. String t (*this);
  9548. if (! t.startsWithChar (quoteCharacter))
  9549. t = charToString (quoteCharacter) + t;
  9550. if (! t.endsWithChar (quoteCharacter))
  9551. t += quoteCharacter;
  9552. return t;
  9553. }
  9554. const String String::trim() const
  9555. {
  9556. if (isEmpty())
  9557. return empty;
  9558. int start = 0;
  9559. while (CharacterFunctions::isWhitespace (text [start]))
  9560. ++start;
  9561. const int len = length();
  9562. int end = len - 1;
  9563. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  9564. --end;
  9565. ++end;
  9566. if (end <= start)
  9567. return empty;
  9568. else if (start > 0 || end < len)
  9569. return String (text + start, end - start);
  9570. return *this;
  9571. }
  9572. const String String::trimStart() const
  9573. {
  9574. if (isEmpty())
  9575. return empty;
  9576. const juce_wchar* t = text;
  9577. while (CharacterFunctions::isWhitespace (*t))
  9578. ++t;
  9579. if (t == text)
  9580. return *this;
  9581. return String (t);
  9582. }
  9583. const String String::trimEnd() const
  9584. {
  9585. if (isEmpty())
  9586. return empty;
  9587. const juce_wchar* endT = text + (length() - 1);
  9588. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  9589. --endT;
  9590. return String (text, (int) (++endT - text));
  9591. }
  9592. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  9593. {
  9594. const juce_wchar* t = text;
  9595. while (charactersToTrim.containsChar (*t))
  9596. ++t;
  9597. return t == text ? *this : String (t);
  9598. }
  9599. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  9600. {
  9601. if (isEmpty())
  9602. return empty;
  9603. const int len = length();
  9604. const juce_wchar* endT = text + (len - 1);
  9605. int numToRemove = 0;
  9606. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  9607. {
  9608. ++numToRemove;
  9609. --endT;
  9610. }
  9611. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  9612. }
  9613. const String String::retainCharacters (const String& charactersToRetain) const
  9614. {
  9615. if (isEmpty())
  9616. return empty;
  9617. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9618. juce_wchar* dst = result.text;
  9619. const juce_wchar* src = text;
  9620. while (*src != 0)
  9621. {
  9622. if (charactersToRetain.containsChar (*src))
  9623. *dst++ = *src;
  9624. ++src;
  9625. }
  9626. *dst = 0;
  9627. return result;
  9628. }
  9629. const String String::removeCharacters (const String& charactersToRemove) const
  9630. {
  9631. if (isEmpty())
  9632. return empty;
  9633. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9634. juce_wchar* dst = result.text;
  9635. const juce_wchar* src = text;
  9636. while (*src != 0)
  9637. {
  9638. if (! charactersToRemove.containsChar (*src))
  9639. *dst++ = *src;
  9640. ++src;
  9641. }
  9642. *dst = 0;
  9643. return result;
  9644. }
  9645. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  9646. {
  9647. int i = 0;
  9648. for (;;)
  9649. {
  9650. if (! permittedCharacters.containsChar (text[i]))
  9651. break;
  9652. ++i;
  9653. }
  9654. return substring (0, i);
  9655. }
  9656. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  9657. {
  9658. const juce_wchar* const t = text;
  9659. int i = 0;
  9660. while (t[i] != 0)
  9661. {
  9662. if (charactersToStopAt.containsChar (t[i]))
  9663. return String (text, i);
  9664. ++i;
  9665. }
  9666. return empty;
  9667. }
  9668. bool String::containsOnly (const String& chars) const throw()
  9669. {
  9670. const juce_wchar* t = text;
  9671. while (*t != 0)
  9672. if (! chars.containsChar (*t++))
  9673. return false;
  9674. return true;
  9675. }
  9676. bool String::containsAnyOf (const String& chars) const throw()
  9677. {
  9678. const juce_wchar* t = text;
  9679. while (*t != 0)
  9680. if (chars.containsChar (*t++))
  9681. return true;
  9682. return false;
  9683. }
  9684. bool String::containsNonWhitespaceChars() const throw()
  9685. {
  9686. const juce_wchar* t = text;
  9687. while (*t != 0)
  9688. if (! CharacterFunctions::isWhitespace (*t++))
  9689. return true;
  9690. return false;
  9691. }
  9692. const String String::formatted (const juce_wchar* const pf, ... )
  9693. {
  9694. jassert (pf != 0);
  9695. va_list args;
  9696. va_start (args, pf);
  9697. size_t bufferSize = 256;
  9698. String result (bufferSize, (int) 0);
  9699. result.text[0] = 0;
  9700. for (;;)
  9701. {
  9702. #if JUCE_LINUX && JUCE_64BIT
  9703. va_list tempArgs;
  9704. va_copy (tempArgs, args);
  9705. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  9706. va_end (tempArgs);
  9707. #elif JUCE_WINDOWS
  9708. #if JUCE_MSVC
  9709. #pragma warning (push)
  9710. #pragma warning (disable: 4996)
  9711. #endif
  9712. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  9713. #if JUCE_MSVC
  9714. #pragma warning (pop)
  9715. #endif
  9716. #else
  9717. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  9718. #endif
  9719. if (num > 0)
  9720. return result;
  9721. bufferSize += 256;
  9722. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  9723. break; // returns -1 because of an error rather than because it needs more space.
  9724. result.preallocateStorage (bufferSize);
  9725. }
  9726. return empty;
  9727. }
  9728. int String::getIntValue() const throw()
  9729. {
  9730. return CharacterFunctions::getIntValue (text);
  9731. }
  9732. int String::getTrailingIntValue() const throw()
  9733. {
  9734. int n = 0;
  9735. int mult = 1;
  9736. const juce_wchar* t = text + length();
  9737. while (--t >= text)
  9738. {
  9739. const juce_wchar c = *t;
  9740. if (! CharacterFunctions::isDigit (c))
  9741. {
  9742. if (c == '-')
  9743. n = -n;
  9744. break;
  9745. }
  9746. n += mult * (c - '0');
  9747. mult *= 10;
  9748. }
  9749. return n;
  9750. }
  9751. int64 String::getLargeIntValue() const throw()
  9752. {
  9753. return CharacterFunctions::getInt64Value (text);
  9754. }
  9755. float String::getFloatValue() const throw()
  9756. {
  9757. return (float) CharacterFunctions::getDoubleValue (text);
  9758. }
  9759. double String::getDoubleValue() const throw()
  9760. {
  9761. return CharacterFunctions::getDoubleValue (text);
  9762. }
  9763. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  9764. const String String::toHexString (const int number)
  9765. {
  9766. juce_wchar buffer[32];
  9767. juce_wchar* const end = buffer + 32;
  9768. juce_wchar* t = end;
  9769. *--t = 0;
  9770. unsigned int v = (unsigned int) number;
  9771. do
  9772. {
  9773. *--t = hexDigits [v & 15];
  9774. v >>= 4;
  9775. } while (v != 0);
  9776. return String (t, (int) (((char*) end) - (char*) t) - 1);
  9777. }
  9778. const String String::toHexString (const int64 number)
  9779. {
  9780. juce_wchar buffer[32];
  9781. juce_wchar* const end = buffer + 32;
  9782. juce_wchar* t = end;
  9783. *--t = 0;
  9784. uint64 v = (uint64) number;
  9785. do
  9786. {
  9787. *--t = hexDigits [(int) (v & 15)];
  9788. v >>= 4;
  9789. } while (v != 0);
  9790. return String (t, (int) (((char*) end) - (char*) t));
  9791. }
  9792. const String String::toHexString (const short number)
  9793. {
  9794. return toHexString ((int) (unsigned short) number);
  9795. }
  9796. const String String::toHexString (const unsigned char* data,
  9797. const int size,
  9798. const int groupSize)
  9799. {
  9800. if (size <= 0)
  9801. return empty;
  9802. int numChars = (size * 2) + 2;
  9803. if (groupSize > 0)
  9804. numChars += size / groupSize;
  9805. String s ((size_t) numChars, (int) 0);
  9806. juce_wchar* d = s.text;
  9807. for (int i = 0; i < size; ++i)
  9808. {
  9809. *d++ = hexDigits [(*data) >> 4];
  9810. *d++ = hexDigits [(*data) & 0xf];
  9811. ++data;
  9812. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  9813. *d++ = ' ';
  9814. }
  9815. *d = 0;
  9816. return s;
  9817. }
  9818. int String::getHexValue32() const throw()
  9819. {
  9820. int result = 0;
  9821. const juce_wchar* c = text;
  9822. for (;;)
  9823. {
  9824. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9825. if (hexValue >= 0)
  9826. result = (result << 4) | hexValue;
  9827. else if (*c == 0)
  9828. break;
  9829. ++c;
  9830. }
  9831. return result;
  9832. }
  9833. int64 String::getHexValue64() const throw()
  9834. {
  9835. int64 result = 0;
  9836. const juce_wchar* c = text;
  9837. for (;;)
  9838. {
  9839. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9840. if (hexValue >= 0)
  9841. result = (result << 4) | hexValue;
  9842. else if (*c == 0)
  9843. break;
  9844. ++c;
  9845. }
  9846. return result;
  9847. }
  9848. const String String::createStringFromData (const void* const data_, const int size)
  9849. {
  9850. const char* const data = static_cast <const char*> (data_);
  9851. if (size <= 0 || data == 0)
  9852. {
  9853. return empty;
  9854. }
  9855. else if (size < 2)
  9856. {
  9857. return charToString (data[0]);
  9858. }
  9859. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  9860. || (data[0] == (char)-1 && data[1] == (char)-2))
  9861. {
  9862. // assume it's 16-bit unicode
  9863. const bool bigEndian = (data[0] == (char)-2);
  9864. const int numChars = size / 2 - 1;
  9865. String result;
  9866. result.preallocateStorage (numChars + 2);
  9867. const uint16* const src = (const uint16*) (data + 2);
  9868. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  9869. if (bigEndian)
  9870. {
  9871. for (int i = 0; i < numChars; ++i)
  9872. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  9873. }
  9874. else
  9875. {
  9876. for (int i = 0; i < numChars; ++i)
  9877. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  9878. }
  9879. dst [numChars] = 0;
  9880. return result;
  9881. }
  9882. else
  9883. {
  9884. return String::fromUTF8 (data, size);
  9885. }
  9886. }
  9887. const char* String::toUTF8() const
  9888. {
  9889. if (isEmpty())
  9890. {
  9891. return reinterpret_cast <const char*> (text);
  9892. }
  9893. else
  9894. {
  9895. const int currentLen = length() + 1;
  9896. const int utf8BytesNeeded = getNumBytesAsUTF8();
  9897. String* const mutableThis = const_cast <String*> (this);
  9898. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  9899. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  9900. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  9901. *(juce_wchar*) (otherCopy + (utf8BytesNeeded & ~(sizeof (juce_wchar) - 1))) = 0;
  9902. #endif
  9903. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  9904. return otherCopy;
  9905. }
  9906. }
  9907. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  9908. {
  9909. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  9910. int num = 0, index = 0;
  9911. for (;;)
  9912. {
  9913. const uint32 c = (uint32) text [index++];
  9914. if (c >= 0x80)
  9915. {
  9916. int numExtraBytes = 1;
  9917. if (c >= 0x800)
  9918. {
  9919. ++numExtraBytes;
  9920. if (c >= 0x10000)
  9921. {
  9922. ++numExtraBytes;
  9923. if (c >= 0x200000)
  9924. {
  9925. ++numExtraBytes;
  9926. if (c >= 0x4000000)
  9927. ++numExtraBytes;
  9928. }
  9929. }
  9930. }
  9931. if (buffer != 0)
  9932. {
  9933. if (num + numExtraBytes >= maxBufferSizeBytes)
  9934. {
  9935. buffer [num++] = 0;
  9936. break;
  9937. }
  9938. else
  9939. {
  9940. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  9941. while (--numExtraBytes >= 0)
  9942. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  9943. }
  9944. }
  9945. else
  9946. {
  9947. num += numExtraBytes + 1;
  9948. }
  9949. }
  9950. else
  9951. {
  9952. if (buffer != 0)
  9953. {
  9954. if (num + 1 >= maxBufferSizeBytes)
  9955. {
  9956. buffer [num++] = 0;
  9957. break;
  9958. }
  9959. buffer [num] = (uint8) c;
  9960. }
  9961. ++num;
  9962. }
  9963. if (c == 0)
  9964. break;
  9965. }
  9966. return num;
  9967. }
  9968. int String::getNumBytesAsUTF8() const throw()
  9969. {
  9970. int num = 0;
  9971. const juce_wchar* t = text;
  9972. for (;;)
  9973. {
  9974. const uint32 c = (uint32) *t;
  9975. if (c >= 0x80)
  9976. {
  9977. ++num;
  9978. if (c >= 0x800)
  9979. {
  9980. ++num;
  9981. if (c >= 0x10000)
  9982. {
  9983. ++num;
  9984. if (c >= 0x200000)
  9985. {
  9986. ++num;
  9987. if (c >= 0x4000000)
  9988. ++num;
  9989. }
  9990. }
  9991. }
  9992. }
  9993. else if (c == 0)
  9994. break;
  9995. ++num;
  9996. ++t;
  9997. }
  9998. return num;
  9999. }
  10000. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10001. {
  10002. if (buffer == 0)
  10003. return empty;
  10004. if (bufferSizeBytes < 0)
  10005. bufferSizeBytes = std::numeric_limits<int>::max();
  10006. size_t numBytes;
  10007. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  10008. if (buffer [numBytes] == 0)
  10009. break;
  10010. String result ((size_t) numBytes + 1, (int) 0);
  10011. juce_wchar* dest = result.text;
  10012. size_t i = 0;
  10013. while (i < numBytes)
  10014. {
  10015. const char c = buffer [i++];
  10016. if (c < 0)
  10017. {
  10018. unsigned int mask = 0x7f;
  10019. int bit = 0x40;
  10020. int numExtraValues = 0;
  10021. while (bit != 0 && (c & bit) != 0)
  10022. {
  10023. bit >>= 1;
  10024. mask >>= 1;
  10025. ++numExtraValues;
  10026. }
  10027. int n = (mask & (unsigned char) c);
  10028. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  10029. {
  10030. const char nextByte = buffer[i];
  10031. if ((nextByte & 0xc0) != 0x80)
  10032. break;
  10033. n <<= 6;
  10034. n |= (nextByte & 0x3f);
  10035. ++i;
  10036. }
  10037. *dest++ = (juce_wchar) n;
  10038. }
  10039. else
  10040. {
  10041. *dest++ = (juce_wchar) c;
  10042. }
  10043. }
  10044. *dest = 0;
  10045. return result;
  10046. }
  10047. const char* String::toCString() const
  10048. {
  10049. if (isEmpty())
  10050. {
  10051. return reinterpret_cast <const char*> (text);
  10052. }
  10053. else
  10054. {
  10055. const int len = length();
  10056. String* const mutableThis = const_cast <String*> (this);
  10057. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  10058. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  10059. CharacterFunctions::copy (otherCopy, text, len);
  10060. otherCopy [len] = 0;
  10061. return otherCopy;
  10062. }
  10063. }
  10064. #if JUCE_MSVC
  10065. #pragma warning (push)
  10066. #pragma warning (disable: 4514 4996)
  10067. #endif
  10068. int String::getNumBytesAsCString() const throw()
  10069. {
  10070. return (int) wcstombs (0, text, 0);
  10071. }
  10072. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  10073. {
  10074. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  10075. if (destBuffer != 0 && numBytes >= 0)
  10076. destBuffer [numBytes] = 0;
  10077. return numBytes;
  10078. }
  10079. #if JUCE_MSVC
  10080. #pragma warning (pop)
  10081. #endif
  10082. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  10083. {
  10084. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  10085. }
  10086. String::Concatenator::Concatenator (String& stringToAppendTo)
  10087. : result (stringToAppendTo),
  10088. nextIndex (stringToAppendTo.length())
  10089. {
  10090. }
  10091. String::Concatenator::~Concatenator()
  10092. {
  10093. }
  10094. void String::Concatenator::append (const String& s)
  10095. {
  10096. const int len = s.length();
  10097. if (len > 0)
  10098. {
  10099. result.preallocateStorage (nextIndex + len);
  10100. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  10101. nextIndex += len;
  10102. }
  10103. }
  10104. END_JUCE_NAMESPACE
  10105. /*** End of inlined file: juce_String.cpp ***/
  10106. /*** Start of inlined file: juce_StringArray.cpp ***/
  10107. BEGIN_JUCE_NAMESPACE
  10108. StringArray::StringArray() throw()
  10109. {
  10110. }
  10111. StringArray::StringArray (const StringArray& other)
  10112. : strings (other.strings)
  10113. {
  10114. }
  10115. StringArray::StringArray (const String& firstValue)
  10116. {
  10117. strings.add (firstValue);
  10118. }
  10119. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  10120. const int numberOfStrings)
  10121. {
  10122. for (int i = 0; i < numberOfStrings; ++i)
  10123. strings.add (initialStrings [i]);
  10124. }
  10125. StringArray::StringArray (const char* const* const initialStrings,
  10126. const int numberOfStrings)
  10127. {
  10128. for (int i = 0; i < numberOfStrings; ++i)
  10129. strings.add (initialStrings [i]);
  10130. }
  10131. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  10132. {
  10133. int i = 0;
  10134. while (initialStrings[i] != 0)
  10135. strings.add (initialStrings [i++]);
  10136. }
  10137. StringArray::StringArray (const char* const* const initialStrings)
  10138. {
  10139. int i = 0;
  10140. while (initialStrings[i] != 0)
  10141. strings.add (initialStrings [i++]);
  10142. }
  10143. StringArray& StringArray::operator= (const StringArray& other)
  10144. {
  10145. strings = other.strings;
  10146. return *this;
  10147. }
  10148. StringArray::~StringArray()
  10149. {
  10150. }
  10151. bool StringArray::operator== (const StringArray& other) const throw()
  10152. {
  10153. if (other.size() != size())
  10154. return false;
  10155. for (int i = size(); --i >= 0;)
  10156. if (other.strings.getReference(i) != strings.getReference(i))
  10157. return false;
  10158. return true;
  10159. }
  10160. bool StringArray::operator!= (const StringArray& other) const throw()
  10161. {
  10162. return ! operator== (other);
  10163. }
  10164. void StringArray::clear()
  10165. {
  10166. strings.clear();
  10167. }
  10168. const String& StringArray::operator[] (const int index) const throw()
  10169. {
  10170. if (((unsigned int) index) < (unsigned int) strings.size())
  10171. return strings.getReference (index);
  10172. return String::empty;
  10173. }
  10174. String& StringArray::getReference (const int index) throw()
  10175. {
  10176. jassert (((unsigned int) index) < (unsigned int) strings.size());
  10177. return strings.getReference (index);
  10178. }
  10179. void StringArray::add (const String& newString)
  10180. {
  10181. strings.add (newString);
  10182. }
  10183. void StringArray::insert (const int index, const String& newString)
  10184. {
  10185. strings.insert (index, newString);
  10186. }
  10187. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  10188. {
  10189. if (! contains (newString, ignoreCase))
  10190. add (newString);
  10191. }
  10192. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  10193. {
  10194. if (startIndex < 0)
  10195. {
  10196. jassertfalse;
  10197. startIndex = 0;
  10198. }
  10199. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  10200. numElementsToAdd = otherArray.size() - startIndex;
  10201. while (--numElementsToAdd >= 0)
  10202. strings.add (otherArray.strings.getReference (startIndex++));
  10203. }
  10204. void StringArray::set (const int index, const String& newString)
  10205. {
  10206. strings.set (index, newString);
  10207. }
  10208. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  10209. {
  10210. if (ignoreCase)
  10211. {
  10212. for (int i = size(); --i >= 0;)
  10213. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10214. return true;
  10215. }
  10216. else
  10217. {
  10218. for (int i = size(); --i >= 0;)
  10219. if (stringToLookFor == strings.getReference(i))
  10220. return true;
  10221. }
  10222. return false;
  10223. }
  10224. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  10225. {
  10226. if (i < 0)
  10227. i = 0;
  10228. const int numElements = size();
  10229. if (ignoreCase)
  10230. {
  10231. while (i < numElements)
  10232. {
  10233. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10234. return i;
  10235. ++i;
  10236. }
  10237. }
  10238. else
  10239. {
  10240. while (i < numElements)
  10241. {
  10242. if (stringToLookFor == strings.getReference (i))
  10243. return i;
  10244. ++i;
  10245. }
  10246. }
  10247. return -1;
  10248. }
  10249. void StringArray::remove (const int index)
  10250. {
  10251. strings.remove (index);
  10252. }
  10253. void StringArray::removeString (const String& stringToRemove,
  10254. const bool ignoreCase)
  10255. {
  10256. if (ignoreCase)
  10257. {
  10258. for (int i = size(); --i >= 0;)
  10259. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  10260. strings.remove (i);
  10261. }
  10262. else
  10263. {
  10264. for (int i = size(); --i >= 0;)
  10265. if (stringToRemove == strings.getReference (i))
  10266. strings.remove (i);
  10267. }
  10268. }
  10269. void StringArray::removeRange (int startIndex, int numberToRemove)
  10270. {
  10271. strings.removeRange (startIndex, numberToRemove);
  10272. }
  10273. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  10274. {
  10275. if (removeWhitespaceStrings)
  10276. {
  10277. for (int i = size(); --i >= 0;)
  10278. if (! strings.getReference(i).containsNonWhitespaceChars())
  10279. strings.remove (i);
  10280. }
  10281. else
  10282. {
  10283. for (int i = size(); --i >= 0;)
  10284. if (strings.getReference(i).isEmpty())
  10285. strings.remove (i);
  10286. }
  10287. }
  10288. void StringArray::trim()
  10289. {
  10290. for (int i = size(); --i >= 0;)
  10291. {
  10292. String& s = strings.getReference(i);
  10293. s = s.trim();
  10294. }
  10295. }
  10296. class InternalStringArrayComparator_CaseSensitive
  10297. {
  10298. public:
  10299. static int compareElements (String& first, String& second) { return first.compare (second); }
  10300. };
  10301. class InternalStringArrayComparator_CaseInsensitive
  10302. {
  10303. public:
  10304. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  10305. };
  10306. void StringArray::sort (const bool ignoreCase)
  10307. {
  10308. if (ignoreCase)
  10309. {
  10310. InternalStringArrayComparator_CaseInsensitive comp;
  10311. strings.sort (comp);
  10312. }
  10313. else
  10314. {
  10315. InternalStringArrayComparator_CaseSensitive comp;
  10316. strings.sort (comp);
  10317. }
  10318. }
  10319. void StringArray::move (const int currentIndex, int newIndex) throw()
  10320. {
  10321. strings.move (currentIndex, newIndex);
  10322. }
  10323. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  10324. {
  10325. const int last = (numberToJoin < 0) ? size()
  10326. : jmin (size(), start + numberToJoin);
  10327. if (start < 0)
  10328. start = 0;
  10329. if (start >= last)
  10330. return String::empty;
  10331. if (start == last - 1)
  10332. return strings.getReference (start);
  10333. const int separatorLen = separator.length();
  10334. int charsNeeded = separatorLen * (last - start - 1);
  10335. for (int i = start; i < last; ++i)
  10336. charsNeeded += strings.getReference(i).length();
  10337. String result;
  10338. result.preallocateStorage (charsNeeded);
  10339. juce_wchar* dest = result;
  10340. while (start < last)
  10341. {
  10342. const String& s = strings.getReference (start);
  10343. const int len = s.length();
  10344. if (len > 0)
  10345. {
  10346. s.copyToUnicode (dest, len);
  10347. dest += len;
  10348. }
  10349. if (++start < last && separatorLen > 0)
  10350. {
  10351. separator.copyToUnicode (dest, separatorLen);
  10352. dest += separatorLen;
  10353. }
  10354. }
  10355. *dest = 0;
  10356. return result;
  10357. }
  10358. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  10359. {
  10360. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  10361. }
  10362. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  10363. {
  10364. int num = 0;
  10365. if (text.isNotEmpty())
  10366. {
  10367. bool insideQuotes = false;
  10368. juce_wchar currentQuoteChar = 0;
  10369. int i = 0;
  10370. int tokenStart = 0;
  10371. for (;;)
  10372. {
  10373. const juce_wchar c = text[i];
  10374. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  10375. if (! isBreak)
  10376. {
  10377. if (quoteCharacters.containsChar (c))
  10378. {
  10379. if (insideQuotes)
  10380. {
  10381. // only break out of quotes-mode if we find a matching quote to the
  10382. // one that we opened with..
  10383. if (currentQuoteChar == c)
  10384. insideQuotes = false;
  10385. }
  10386. else
  10387. {
  10388. insideQuotes = true;
  10389. currentQuoteChar = c;
  10390. }
  10391. }
  10392. }
  10393. else
  10394. {
  10395. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  10396. ++num;
  10397. tokenStart = i + 1;
  10398. }
  10399. if (c == 0)
  10400. break;
  10401. ++i;
  10402. }
  10403. }
  10404. return num;
  10405. }
  10406. int StringArray::addLines (const String& sourceText)
  10407. {
  10408. int numLines = 0;
  10409. const juce_wchar* text = sourceText;
  10410. while (*text != 0)
  10411. {
  10412. const juce_wchar* const startOfLine = text;
  10413. while (*text != 0)
  10414. {
  10415. if (*text == '\r')
  10416. {
  10417. ++text;
  10418. if (*text == '\n')
  10419. ++text;
  10420. break;
  10421. }
  10422. if (*text == '\n')
  10423. {
  10424. ++text;
  10425. break;
  10426. }
  10427. ++text;
  10428. }
  10429. const juce_wchar* endOfLine = text;
  10430. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10431. --endOfLine;
  10432. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10433. --endOfLine;
  10434. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  10435. ++numLines;
  10436. }
  10437. return numLines;
  10438. }
  10439. void StringArray::removeDuplicates (const bool ignoreCase)
  10440. {
  10441. for (int i = 0; i < size() - 1; ++i)
  10442. {
  10443. const String s (strings.getReference(i));
  10444. int nextIndex = i + 1;
  10445. for (;;)
  10446. {
  10447. nextIndex = indexOf (s, ignoreCase, nextIndex);
  10448. if (nextIndex < 0)
  10449. break;
  10450. strings.remove (nextIndex);
  10451. }
  10452. }
  10453. }
  10454. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  10455. const bool appendNumberToFirstInstance,
  10456. const juce_wchar* preNumberString,
  10457. const juce_wchar* postNumberString)
  10458. {
  10459. if (preNumberString == 0)
  10460. preNumberString = L" (";
  10461. if (postNumberString == 0)
  10462. postNumberString = L")";
  10463. for (int i = 0; i < size() - 1; ++i)
  10464. {
  10465. String& s = strings.getReference(i);
  10466. int nextIndex = indexOf (s, ignoreCase, i + 1);
  10467. if (nextIndex >= 0)
  10468. {
  10469. const String original (s);
  10470. int number = 0;
  10471. if (appendNumberToFirstInstance)
  10472. s = original + preNumberString + String (++number) + postNumberString;
  10473. else
  10474. ++number;
  10475. while (nextIndex >= 0)
  10476. {
  10477. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  10478. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  10479. }
  10480. }
  10481. }
  10482. }
  10483. void StringArray::minimiseStorageOverheads()
  10484. {
  10485. strings.minimiseStorageOverheads();
  10486. }
  10487. END_JUCE_NAMESPACE
  10488. /*** End of inlined file: juce_StringArray.cpp ***/
  10489. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  10490. BEGIN_JUCE_NAMESPACE
  10491. StringPairArray::StringPairArray (const bool ignoreCase_)
  10492. : ignoreCase (ignoreCase_)
  10493. {
  10494. }
  10495. StringPairArray::StringPairArray (const StringPairArray& other)
  10496. : keys (other.keys),
  10497. values (other.values),
  10498. ignoreCase (other.ignoreCase)
  10499. {
  10500. }
  10501. StringPairArray::~StringPairArray()
  10502. {
  10503. }
  10504. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  10505. {
  10506. keys = other.keys;
  10507. values = other.values;
  10508. return *this;
  10509. }
  10510. bool StringPairArray::operator== (const StringPairArray& other) const
  10511. {
  10512. for (int i = keys.size(); --i >= 0;)
  10513. if (other [keys[i]] != values[i])
  10514. return false;
  10515. return true;
  10516. }
  10517. bool StringPairArray::operator!= (const StringPairArray& other) const
  10518. {
  10519. return ! operator== (other);
  10520. }
  10521. const String& StringPairArray::operator[] (const String& key) const
  10522. {
  10523. return values [keys.indexOf (key, ignoreCase)];
  10524. }
  10525. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  10526. {
  10527. const int i = keys.indexOf (key, ignoreCase);
  10528. if (i >= 0)
  10529. return values[i];
  10530. return defaultReturnValue;
  10531. }
  10532. void StringPairArray::set (const String& key, const String& value)
  10533. {
  10534. const int i = keys.indexOf (key, ignoreCase);
  10535. if (i >= 0)
  10536. {
  10537. values.set (i, value);
  10538. }
  10539. else
  10540. {
  10541. keys.add (key);
  10542. values.add (value);
  10543. }
  10544. }
  10545. void StringPairArray::addArray (const StringPairArray& other)
  10546. {
  10547. for (int i = 0; i < other.size(); ++i)
  10548. set (other.keys[i], other.values[i]);
  10549. }
  10550. void StringPairArray::clear()
  10551. {
  10552. keys.clear();
  10553. values.clear();
  10554. }
  10555. void StringPairArray::remove (const String& key)
  10556. {
  10557. remove (keys.indexOf (key, ignoreCase));
  10558. }
  10559. void StringPairArray::remove (const int index)
  10560. {
  10561. keys.remove (index);
  10562. values.remove (index);
  10563. }
  10564. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  10565. {
  10566. ignoreCase = shouldIgnoreCase;
  10567. }
  10568. const String StringPairArray::getDescription() const
  10569. {
  10570. String s;
  10571. for (int i = 0; i < keys.size(); ++i)
  10572. {
  10573. s << keys[i] << " = " << values[i];
  10574. if (i < keys.size())
  10575. s << ", ";
  10576. }
  10577. return s;
  10578. }
  10579. void StringPairArray::minimiseStorageOverheads()
  10580. {
  10581. keys.minimiseStorageOverheads();
  10582. values.minimiseStorageOverheads();
  10583. }
  10584. END_JUCE_NAMESPACE
  10585. /*** End of inlined file: juce_StringPairArray.cpp ***/
  10586. /*** Start of inlined file: juce_StringPool.cpp ***/
  10587. BEGIN_JUCE_NAMESPACE
  10588. StringPool::StringPool() throw() {}
  10589. StringPool::~StringPool() {}
  10590. template <class StringType>
  10591. static const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  10592. {
  10593. int start = 0;
  10594. int end = strings.size();
  10595. for (;;)
  10596. {
  10597. if (start >= end)
  10598. {
  10599. jassert (start <= end);
  10600. strings.insert (start, newString);
  10601. return strings.getReference (start);
  10602. }
  10603. else
  10604. {
  10605. const String& startString = strings.getReference (start);
  10606. if (startString == newString)
  10607. return startString;
  10608. const int halfway = (start + end) >> 1;
  10609. if (halfway == start)
  10610. {
  10611. if (startString.compare (newString) < 0)
  10612. ++start;
  10613. strings.insert (start, newString);
  10614. return strings.getReference (start);
  10615. }
  10616. const int comp = strings.getReference (halfway).compare (newString);
  10617. if (comp == 0)
  10618. return strings.getReference (halfway);
  10619. else if (comp < 0)
  10620. start = halfway;
  10621. else
  10622. end = halfway;
  10623. }
  10624. }
  10625. }
  10626. const juce_wchar* StringPool::getPooledString (const String& s)
  10627. {
  10628. if (s.isEmpty())
  10629. return String::empty;
  10630. return getPooledStringFromArray (strings, s);
  10631. }
  10632. const juce_wchar* StringPool::getPooledString (const char* const s)
  10633. {
  10634. if (s == 0 || *s == 0)
  10635. return String::empty;
  10636. return getPooledStringFromArray (strings, s);
  10637. }
  10638. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  10639. {
  10640. if (s == 0 || *s == 0)
  10641. return String::empty;
  10642. return getPooledStringFromArray (strings, s);
  10643. }
  10644. int StringPool::size() const throw()
  10645. {
  10646. return strings.size();
  10647. }
  10648. const juce_wchar* StringPool::operator[] (const int index) const throw()
  10649. {
  10650. return strings [index];
  10651. }
  10652. END_JUCE_NAMESPACE
  10653. /*** End of inlined file: juce_StringPool.cpp ***/
  10654. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  10655. BEGIN_JUCE_NAMESPACE
  10656. XmlDocument::XmlDocument (const String& documentText)
  10657. : originalText (documentText),
  10658. ignoreEmptyTextElements (true)
  10659. {
  10660. }
  10661. XmlDocument::XmlDocument (const File& file)
  10662. : ignoreEmptyTextElements (true)
  10663. {
  10664. inputSource = new FileInputSource (file);
  10665. }
  10666. XmlDocument::~XmlDocument()
  10667. {
  10668. }
  10669. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  10670. {
  10671. inputSource = newSource;
  10672. }
  10673. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  10674. {
  10675. ignoreEmptyTextElements = shouldBeIgnored;
  10676. }
  10677. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  10678. {
  10679. return CharacterFunctions::isLetterOrDigit (c)
  10680. || c == '_' || c == '-' || c == ':' || c == '.';
  10681. }
  10682. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  10683. {
  10684. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  10685. : isXmlIdentifierCharSlow (c);
  10686. }
  10687. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  10688. {
  10689. String textToParse (originalText);
  10690. if (textToParse.isEmpty() && inputSource != 0)
  10691. {
  10692. ScopedPointer <InputStream> in (inputSource->createInputStream());
  10693. if (in != 0)
  10694. {
  10695. MemoryOutputStream data;
  10696. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  10697. textToParse = data.toString();
  10698. if (! onlyReadOuterDocumentElement)
  10699. originalText = textToParse;
  10700. }
  10701. }
  10702. input = textToParse;
  10703. lastError = String::empty;
  10704. errorOccurred = false;
  10705. outOfData = false;
  10706. needToLoadDTD = true;
  10707. for (int i = 0; i < 128; ++i)
  10708. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  10709. if (textToParse.isEmpty())
  10710. {
  10711. lastError = "not enough input";
  10712. }
  10713. else
  10714. {
  10715. skipHeader();
  10716. if (input != 0)
  10717. {
  10718. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  10719. if (! errorOccurred)
  10720. return result.release();
  10721. }
  10722. else
  10723. {
  10724. lastError = "incorrect xml header";
  10725. }
  10726. }
  10727. return 0;
  10728. }
  10729. const String& XmlDocument::getLastParseError() const throw()
  10730. {
  10731. return lastError;
  10732. }
  10733. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  10734. {
  10735. lastError = desc;
  10736. errorOccurred = ! carryOn;
  10737. }
  10738. const String XmlDocument::getFileContents (const String& filename) const
  10739. {
  10740. if (inputSource != 0)
  10741. {
  10742. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  10743. if (in != 0)
  10744. return in->readEntireStreamAsString();
  10745. }
  10746. return String::empty;
  10747. }
  10748. juce_wchar XmlDocument::readNextChar() throw()
  10749. {
  10750. if (*input != 0)
  10751. {
  10752. return *input++;
  10753. }
  10754. else
  10755. {
  10756. outOfData = true;
  10757. return 0;
  10758. }
  10759. }
  10760. int XmlDocument::findNextTokenLength() throw()
  10761. {
  10762. int len = 0;
  10763. juce_wchar c = *input;
  10764. while (isXmlIdentifierChar (c))
  10765. c = input [++len];
  10766. return len;
  10767. }
  10768. void XmlDocument::skipHeader()
  10769. {
  10770. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  10771. if (found != 0)
  10772. {
  10773. input = found;
  10774. input = CharacterFunctions::find (input, JUCE_T("?>"));
  10775. if (input == 0)
  10776. return;
  10777. input += 2;
  10778. }
  10779. skipNextWhiteSpace();
  10780. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  10781. if (docType == 0)
  10782. return;
  10783. input = docType + 9;
  10784. int n = 1;
  10785. while (n > 0)
  10786. {
  10787. const juce_wchar c = readNextChar();
  10788. if (outOfData)
  10789. return;
  10790. if (c == '<')
  10791. ++n;
  10792. else if (c == '>')
  10793. --n;
  10794. }
  10795. docType += 9;
  10796. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  10797. }
  10798. void XmlDocument::skipNextWhiteSpace()
  10799. {
  10800. for (;;)
  10801. {
  10802. juce_wchar c = *input;
  10803. while (CharacterFunctions::isWhitespace (c))
  10804. c = *++input;
  10805. if (c == 0)
  10806. {
  10807. outOfData = true;
  10808. break;
  10809. }
  10810. else if (c == '<')
  10811. {
  10812. if (input[1] == '!'
  10813. && input[2] == '-'
  10814. && input[3] == '-')
  10815. {
  10816. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  10817. if (closeComment == 0)
  10818. {
  10819. outOfData = true;
  10820. break;
  10821. }
  10822. input = closeComment + 3;
  10823. continue;
  10824. }
  10825. else if (input[1] == '?')
  10826. {
  10827. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  10828. if (closeBracket == 0)
  10829. {
  10830. outOfData = true;
  10831. break;
  10832. }
  10833. input = closeBracket + 2;
  10834. continue;
  10835. }
  10836. }
  10837. break;
  10838. }
  10839. }
  10840. void XmlDocument::readQuotedString (String& result)
  10841. {
  10842. const juce_wchar quote = readNextChar();
  10843. while (! outOfData)
  10844. {
  10845. const juce_wchar c = readNextChar();
  10846. if (c == quote)
  10847. break;
  10848. if (c == '&')
  10849. {
  10850. --input;
  10851. readEntity (result);
  10852. }
  10853. else
  10854. {
  10855. --input;
  10856. const juce_wchar* const start = input;
  10857. for (;;)
  10858. {
  10859. const juce_wchar character = *input;
  10860. if (character == quote)
  10861. {
  10862. result.append (start, (int) (input - start));
  10863. ++input;
  10864. return;
  10865. }
  10866. else if (character == '&')
  10867. {
  10868. result.append (start, (int) (input - start));
  10869. break;
  10870. }
  10871. else if (character == 0)
  10872. {
  10873. outOfData = true;
  10874. setLastError ("unmatched quotes", false);
  10875. break;
  10876. }
  10877. ++input;
  10878. }
  10879. }
  10880. }
  10881. }
  10882. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  10883. {
  10884. XmlElement* node = 0;
  10885. skipNextWhiteSpace();
  10886. if (outOfData)
  10887. return 0;
  10888. input = CharacterFunctions::find (input, JUCE_T("<"));
  10889. if (input != 0)
  10890. {
  10891. ++input;
  10892. int tagLen = findNextTokenLength();
  10893. if (tagLen == 0)
  10894. {
  10895. // no tag name - but allow for a gap after the '<' before giving an error
  10896. skipNextWhiteSpace();
  10897. tagLen = findNextTokenLength();
  10898. if (tagLen == 0)
  10899. {
  10900. setLastError ("tag name missing", false);
  10901. return node;
  10902. }
  10903. }
  10904. node = new XmlElement (String (input, tagLen));
  10905. input += tagLen;
  10906. XmlElement::XmlAttributeNode* lastAttribute = 0;
  10907. // look for attributes
  10908. for (;;)
  10909. {
  10910. skipNextWhiteSpace();
  10911. const juce_wchar c = *input;
  10912. // empty tag..
  10913. if (c == '/' && input[1] == '>')
  10914. {
  10915. input += 2;
  10916. break;
  10917. }
  10918. // parse the guts of the element..
  10919. if (c == '>')
  10920. {
  10921. ++input;
  10922. skipNextWhiteSpace();
  10923. if (alsoParseSubElements)
  10924. readChildElements (node);
  10925. break;
  10926. }
  10927. // get an attribute..
  10928. if (isXmlIdentifierChar (c))
  10929. {
  10930. const int attNameLen = findNextTokenLength();
  10931. if (attNameLen > 0)
  10932. {
  10933. const juce_wchar* attNameStart = input;
  10934. input += attNameLen;
  10935. skipNextWhiteSpace();
  10936. if (readNextChar() == '=')
  10937. {
  10938. skipNextWhiteSpace();
  10939. const juce_wchar nextChar = *input;
  10940. if (nextChar == '"' || nextChar == '\'')
  10941. {
  10942. XmlElement::XmlAttributeNode* const newAtt
  10943. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  10944. String::empty);
  10945. readQuotedString (newAtt->value);
  10946. if (lastAttribute == 0)
  10947. node->attributes = newAtt;
  10948. else
  10949. lastAttribute->next = newAtt;
  10950. lastAttribute = newAtt;
  10951. continue;
  10952. }
  10953. }
  10954. }
  10955. }
  10956. else
  10957. {
  10958. if (! outOfData)
  10959. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  10960. }
  10961. break;
  10962. }
  10963. }
  10964. return node;
  10965. }
  10966. void XmlDocument::readChildElements (XmlElement* parent)
  10967. {
  10968. XmlElement* lastChildNode = 0;
  10969. for (;;)
  10970. {
  10971. skipNextWhiteSpace();
  10972. if (outOfData)
  10973. {
  10974. setLastError ("unmatched tags", false);
  10975. break;
  10976. }
  10977. if (*input == '<')
  10978. {
  10979. if (input[1] == '/')
  10980. {
  10981. // our close tag..
  10982. input = CharacterFunctions::find (input, JUCE_T(">"));
  10983. ++input;
  10984. break;
  10985. }
  10986. else if (input[1] == '!'
  10987. && input[2] == '['
  10988. && input[3] == 'C'
  10989. && input[4] == 'D'
  10990. && input[5] == 'A'
  10991. && input[6] == 'T'
  10992. && input[7] == 'A'
  10993. && input[8] == '[')
  10994. {
  10995. input += 9;
  10996. const juce_wchar* const inputStart = input;
  10997. int len = 0;
  10998. for (;;)
  10999. {
  11000. if (*input == 0)
  11001. {
  11002. setLastError ("unterminated CDATA section", false);
  11003. outOfData = true;
  11004. break;
  11005. }
  11006. else if (input[0] == ']'
  11007. && input[1] == ']'
  11008. && input[2] == '>')
  11009. {
  11010. input += 3;
  11011. break;
  11012. }
  11013. ++input;
  11014. ++len;
  11015. }
  11016. XmlElement* const e = new XmlElement ((int) 0);
  11017. e->setText (String (inputStart, len));
  11018. if (lastChildNode != 0)
  11019. lastChildNode->nextElement = e;
  11020. else
  11021. parent->addChildElement (e);
  11022. lastChildNode = e;
  11023. }
  11024. else
  11025. {
  11026. // this is some other element, so parse and add it..
  11027. XmlElement* const n = readNextElement (true);
  11028. if (n != 0)
  11029. {
  11030. if (lastChildNode == 0)
  11031. parent->addChildElement (n);
  11032. else
  11033. lastChildNode->nextElement = n;
  11034. lastChildNode = n;
  11035. }
  11036. else
  11037. {
  11038. return;
  11039. }
  11040. }
  11041. }
  11042. else
  11043. {
  11044. // read character block..
  11045. XmlElement* const e = new XmlElement ((int)0);
  11046. if (lastChildNode != 0)
  11047. lastChildNode->nextElement = e;
  11048. else
  11049. parent->addChildElement (e);
  11050. lastChildNode = e;
  11051. String textElementContent;
  11052. for (;;)
  11053. {
  11054. const juce_wchar c = *input;
  11055. if (c == '<')
  11056. break;
  11057. if (c == 0)
  11058. {
  11059. setLastError ("unmatched tags", false);
  11060. outOfData = true;
  11061. return;
  11062. }
  11063. if (c == '&')
  11064. {
  11065. String entity;
  11066. readEntity (entity);
  11067. if (entity.startsWithChar ('<') && entity [1] != 0)
  11068. {
  11069. const juce_wchar* const oldInput = input;
  11070. const bool oldOutOfData = outOfData;
  11071. input = entity;
  11072. outOfData = false;
  11073. for (;;)
  11074. {
  11075. XmlElement* const n = readNextElement (true);
  11076. if (n == 0)
  11077. break;
  11078. if (lastChildNode == 0)
  11079. parent->addChildElement (n);
  11080. else
  11081. lastChildNode->nextElement = n;
  11082. lastChildNode = n;
  11083. }
  11084. input = oldInput;
  11085. outOfData = oldOutOfData;
  11086. }
  11087. else
  11088. {
  11089. textElementContent += entity;
  11090. }
  11091. }
  11092. else
  11093. {
  11094. const juce_wchar* start = input;
  11095. int len = 0;
  11096. for (;;)
  11097. {
  11098. const juce_wchar nextChar = *input;
  11099. if (nextChar == '<' || nextChar == '&')
  11100. {
  11101. break;
  11102. }
  11103. else if (nextChar == 0)
  11104. {
  11105. setLastError ("unmatched tags", false);
  11106. outOfData = true;
  11107. return;
  11108. }
  11109. ++input;
  11110. ++len;
  11111. }
  11112. textElementContent.append (start, len);
  11113. }
  11114. }
  11115. if (ignoreEmptyTextElements ? textElementContent.containsNonWhitespaceChars()
  11116. : textElementContent.isNotEmpty())
  11117. e->setText (textElementContent);
  11118. }
  11119. }
  11120. }
  11121. void XmlDocument::readEntity (String& result)
  11122. {
  11123. // skip over the ampersand
  11124. ++input;
  11125. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  11126. {
  11127. input += 4;
  11128. result += '&';
  11129. }
  11130. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  11131. {
  11132. input += 5;
  11133. result += '"';
  11134. }
  11135. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  11136. {
  11137. input += 5;
  11138. result += '\'';
  11139. }
  11140. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  11141. {
  11142. input += 3;
  11143. result += '<';
  11144. }
  11145. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  11146. {
  11147. input += 3;
  11148. result += '>';
  11149. }
  11150. else if (*input == '#')
  11151. {
  11152. int charCode = 0;
  11153. ++input;
  11154. if (*input == 'x' || *input == 'X')
  11155. {
  11156. ++input;
  11157. int numChars = 0;
  11158. while (input[0] != ';')
  11159. {
  11160. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  11161. if (hexValue < 0 || ++numChars > 8)
  11162. {
  11163. setLastError ("illegal escape sequence", true);
  11164. break;
  11165. }
  11166. charCode = (charCode << 4) | hexValue;
  11167. ++input;
  11168. }
  11169. ++input;
  11170. }
  11171. else if (input[0] >= '0' && input[0] <= '9')
  11172. {
  11173. int numChars = 0;
  11174. while (input[0] != ';')
  11175. {
  11176. if (++numChars > 12)
  11177. {
  11178. setLastError ("illegal escape sequence", true);
  11179. break;
  11180. }
  11181. charCode = charCode * 10 + (input[0] - '0');
  11182. ++input;
  11183. }
  11184. ++input;
  11185. }
  11186. else
  11187. {
  11188. setLastError ("illegal escape sequence", true);
  11189. result += '&';
  11190. return;
  11191. }
  11192. result << (juce_wchar) charCode;
  11193. }
  11194. else
  11195. {
  11196. const juce_wchar* const entityNameStart = input;
  11197. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  11198. if (closingSemiColon == 0)
  11199. {
  11200. outOfData = true;
  11201. result += '&';
  11202. }
  11203. else
  11204. {
  11205. input = closingSemiColon + 1;
  11206. result += expandExternalEntity (String (entityNameStart,
  11207. (int) (closingSemiColon - entityNameStart)));
  11208. }
  11209. }
  11210. }
  11211. const String XmlDocument::expandEntity (const String& ent)
  11212. {
  11213. if (ent.equalsIgnoreCase ("amp"))
  11214. return String::charToString ('&');
  11215. if (ent.equalsIgnoreCase ("quot"))
  11216. return String::charToString ('"');
  11217. if (ent.equalsIgnoreCase ("apos"))
  11218. return String::charToString ('\'');
  11219. if (ent.equalsIgnoreCase ("lt"))
  11220. return String::charToString ('<');
  11221. if (ent.equalsIgnoreCase ("gt"))
  11222. return String::charToString ('>');
  11223. if (ent[0] == '#')
  11224. {
  11225. if (ent[1] == 'x' || ent[1] == 'X')
  11226. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  11227. if (ent[1] >= '0' && ent[1] <= '9')
  11228. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  11229. setLastError ("illegal escape sequence", false);
  11230. return String::charToString ('&');
  11231. }
  11232. return expandExternalEntity (ent);
  11233. }
  11234. const String XmlDocument::expandExternalEntity (const String& entity)
  11235. {
  11236. if (needToLoadDTD)
  11237. {
  11238. if (dtdText.isNotEmpty())
  11239. {
  11240. dtdText = dtdText.trimCharactersAtEnd (">");
  11241. tokenisedDTD.addTokens (dtdText, true);
  11242. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  11243. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  11244. {
  11245. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  11246. tokenisedDTD.clear();
  11247. tokenisedDTD.addTokens (getFileContents (fn), true);
  11248. }
  11249. else
  11250. {
  11251. tokenisedDTD.clear();
  11252. const int openBracket = dtdText.indexOfChar ('[');
  11253. if (openBracket > 0)
  11254. {
  11255. const int closeBracket = dtdText.lastIndexOfChar (']');
  11256. if (closeBracket > openBracket)
  11257. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  11258. closeBracket), true);
  11259. }
  11260. }
  11261. for (int i = tokenisedDTD.size(); --i >= 0;)
  11262. {
  11263. if (tokenisedDTD[i].startsWithChar ('%')
  11264. && tokenisedDTD[i].endsWithChar (';'))
  11265. {
  11266. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  11267. StringArray newToks;
  11268. newToks.addTokens (parsed, true);
  11269. tokenisedDTD.remove (i);
  11270. for (int j = newToks.size(); --j >= 0;)
  11271. tokenisedDTD.insert (i, newToks[j]);
  11272. }
  11273. }
  11274. }
  11275. needToLoadDTD = false;
  11276. }
  11277. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11278. {
  11279. if (tokenisedDTD[i] == entity)
  11280. {
  11281. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  11282. {
  11283. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  11284. // check for sub-entities..
  11285. int ampersand = ent.indexOfChar ('&');
  11286. while (ampersand >= 0)
  11287. {
  11288. const int semiColon = ent.indexOf (i + 1, ";");
  11289. if (semiColon < 0)
  11290. {
  11291. setLastError ("entity without terminating semi-colon", false);
  11292. break;
  11293. }
  11294. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  11295. ent = ent.substring (0, ampersand)
  11296. + resolved
  11297. + ent.substring (semiColon + 1);
  11298. ampersand = ent.indexOfChar (semiColon + 1, '&');
  11299. }
  11300. return ent;
  11301. }
  11302. }
  11303. }
  11304. setLastError ("unknown entity", true);
  11305. return entity;
  11306. }
  11307. const String XmlDocument::getParameterEntity (const String& entity)
  11308. {
  11309. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11310. {
  11311. if (tokenisedDTD[i] == entity)
  11312. {
  11313. if (tokenisedDTD [i - 1] == "%"
  11314. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  11315. {
  11316. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  11317. if (ent.equalsIgnoreCase ("system"))
  11318. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  11319. else
  11320. return ent.trim().unquoted();
  11321. }
  11322. }
  11323. }
  11324. return entity;
  11325. }
  11326. END_JUCE_NAMESPACE
  11327. /*** End of inlined file: juce_XmlDocument.cpp ***/
  11328. /*** Start of inlined file: juce_XmlElement.cpp ***/
  11329. BEGIN_JUCE_NAMESPACE
  11330. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  11331. : name (other.name),
  11332. value (other.value),
  11333. next (0)
  11334. {
  11335. }
  11336. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  11337. : name (name_),
  11338. value (value_),
  11339. next (0)
  11340. {
  11341. }
  11342. XmlElement::XmlElement (const String& tagName_) throw()
  11343. : tagName (tagName_),
  11344. firstChildElement (0),
  11345. nextElement (0),
  11346. attributes (0)
  11347. {
  11348. // the tag name mustn't be empty, or it'll look like a text element!
  11349. jassert (tagName_.containsNonWhitespaceChars())
  11350. // The tag can't contain spaces or other characters that would create invalid XML!
  11351. jassert (! tagName_.containsAnyOf (" <>/&"));
  11352. }
  11353. XmlElement::XmlElement (int /*dummy*/) throw()
  11354. : firstChildElement (0),
  11355. nextElement (0),
  11356. attributes (0)
  11357. {
  11358. }
  11359. XmlElement::XmlElement (const XmlElement& other)
  11360. : tagName (other.tagName),
  11361. firstChildElement (0),
  11362. nextElement (0),
  11363. attributes (0)
  11364. {
  11365. copyChildrenAndAttributesFrom (other);
  11366. }
  11367. XmlElement& XmlElement::operator= (const XmlElement& other)
  11368. {
  11369. if (this != &other)
  11370. {
  11371. removeAllAttributes();
  11372. deleteAllChildElements();
  11373. tagName = other.tagName;
  11374. copyChildrenAndAttributesFrom (other);
  11375. }
  11376. return *this;
  11377. }
  11378. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  11379. {
  11380. XmlElement* child = other.firstChildElement;
  11381. XmlElement* lastChild = 0;
  11382. while (child != 0)
  11383. {
  11384. XmlElement* const copiedChild = new XmlElement (*child);
  11385. if (lastChild != 0)
  11386. lastChild->nextElement = copiedChild;
  11387. else
  11388. firstChildElement = copiedChild;
  11389. lastChild = copiedChild;
  11390. child = child->nextElement;
  11391. }
  11392. const XmlAttributeNode* att = other.attributes;
  11393. XmlAttributeNode* lastAtt = 0;
  11394. while (att != 0)
  11395. {
  11396. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  11397. if (lastAtt != 0)
  11398. lastAtt->next = newAtt;
  11399. else
  11400. attributes = newAtt;
  11401. lastAtt = newAtt;
  11402. att = att->next;
  11403. }
  11404. }
  11405. XmlElement::~XmlElement() throw()
  11406. {
  11407. XmlElement* child = firstChildElement;
  11408. while (child != 0)
  11409. {
  11410. XmlElement* const nextChild = child->nextElement;
  11411. delete child;
  11412. child = nextChild;
  11413. }
  11414. XmlAttributeNode* att = attributes;
  11415. while (att != 0)
  11416. {
  11417. XmlAttributeNode* const nextAtt = att->next;
  11418. delete att;
  11419. att = nextAtt;
  11420. }
  11421. }
  11422. namespace XmlOutputFunctions
  11423. {
  11424. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  11425. {
  11426. if ((character >= 'a' && character <= 'z')
  11427. || (character >= 'A' && character <= 'Z')
  11428. || (character >= '0' && character <= '9'))
  11429. return true;
  11430. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  11431. do
  11432. {
  11433. if (((juce_wchar) (uint8) *t) == character)
  11434. return true;
  11435. }
  11436. while (*++t != 0);
  11437. return false;
  11438. }
  11439. static void generateLegalCharConstants()
  11440. {
  11441. uint8 n[32];
  11442. zerostruct (n);
  11443. for (int i = 0; i < 256; ++i)
  11444. if (isLegalXmlCharSlow (i))
  11445. n[i >> 3] |= (1 << (i & 7));
  11446. String s;
  11447. for (int i = 0; i < 32; ++i)
  11448. s << (int) n[i] << ", ";
  11449. DBG (s);
  11450. }*/
  11451. static bool isLegalXmlChar (const uint32 c) throw()
  11452. {
  11453. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  11454. return c < sizeof (legalChars) * 8
  11455. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  11456. }
  11457. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  11458. {
  11459. const juce_wchar* t = text;
  11460. for (;;)
  11461. {
  11462. const juce_wchar character = *t++;
  11463. if (character == 0)
  11464. {
  11465. break;
  11466. }
  11467. else if (isLegalXmlChar ((uint32) character))
  11468. {
  11469. outputStream << (char) character;
  11470. }
  11471. else
  11472. {
  11473. switch (character)
  11474. {
  11475. case '&': outputStream << "&amp;"; break;
  11476. case '"': outputStream << "&quot;"; break;
  11477. case '>': outputStream << "&gt;"; break;
  11478. case '<': outputStream << "&lt;"; break;
  11479. case '\n':
  11480. if (changeNewLines)
  11481. outputStream << "&#10;";
  11482. else
  11483. outputStream << (char) character;
  11484. break;
  11485. case '\r':
  11486. if (changeNewLines)
  11487. outputStream << "&#13;";
  11488. else
  11489. outputStream << (char) character;
  11490. break;
  11491. default:
  11492. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  11493. break;
  11494. }
  11495. }
  11496. }
  11497. }
  11498. static void writeSpaces (OutputStream& out, int numSpaces)
  11499. {
  11500. if (numSpaces > 0)
  11501. {
  11502. const char* const blanks = " ";
  11503. const int blankSize = (int) sizeof (blanks) - 1;
  11504. while (numSpaces > blankSize)
  11505. {
  11506. out.write (blanks, blankSize);
  11507. numSpaces -= blankSize;
  11508. }
  11509. out.write (blanks, numSpaces);
  11510. }
  11511. }
  11512. }
  11513. void XmlElement::writeElementAsText (OutputStream& outputStream,
  11514. const int indentationLevel,
  11515. const int lineWrapLength) const
  11516. {
  11517. using namespace XmlOutputFunctions;
  11518. writeSpaces (outputStream, indentationLevel);
  11519. if (! isTextElement())
  11520. {
  11521. outputStream.writeByte ('<');
  11522. outputStream << tagName;
  11523. const int attIndent = indentationLevel + tagName.length() + 1;
  11524. int lineLen = 0;
  11525. const XmlAttributeNode* att = attributes;
  11526. while (att != 0)
  11527. {
  11528. if (lineLen > lineWrapLength && indentationLevel >= 0)
  11529. {
  11530. outputStream.write ("\r\n", 2);
  11531. writeSpaces (outputStream, attIndent);
  11532. lineLen = 0;
  11533. }
  11534. const int64 startPos = outputStream.getPosition();
  11535. outputStream.writeByte (' ');
  11536. outputStream << att->name;
  11537. outputStream.write ("=\"", 2);
  11538. escapeIllegalXmlChars (outputStream, att->value, true);
  11539. outputStream.writeByte ('"');
  11540. lineLen += (int) (outputStream.getPosition() - startPos);
  11541. att = att->next;
  11542. }
  11543. if (firstChildElement != 0)
  11544. {
  11545. XmlElement* child = firstChildElement;
  11546. if (child->nextElement == 0 && child->isTextElement())
  11547. {
  11548. outputStream.writeByte ('>');
  11549. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11550. }
  11551. else
  11552. {
  11553. if (indentationLevel >= 0)
  11554. outputStream.write (">\r\n", 3);
  11555. else
  11556. outputStream.writeByte ('>');
  11557. bool lastWasTextNode = false;
  11558. while (child != 0)
  11559. {
  11560. if (child->isTextElement())
  11561. {
  11562. if ((! lastWasTextNode) && (indentationLevel >= 0))
  11563. writeSpaces (outputStream, indentationLevel + 2);
  11564. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11565. lastWasTextNode = true;
  11566. }
  11567. else
  11568. {
  11569. if (indentationLevel >= 0)
  11570. {
  11571. if (lastWasTextNode)
  11572. outputStream.write ("\r\n", 2);
  11573. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  11574. }
  11575. else
  11576. {
  11577. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  11578. }
  11579. lastWasTextNode = false;
  11580. }
  11581. child = child->nextElement;
  11582. }
  11583. if (indentationLevel >= 0)
  11584. {
  11585. if (lastWasTextNode)
  11586. outputStream.write ("\r\n", 2);
  11587. writeSpaces (outputStream, indentationLevel);
  11588. }
  11589. }
  11590. outputStream.write ("</", 2);
  11591. outputStream << tagName;
  11592. if (indentationLevel >= 0)
  11593. outputStream.write (">\r\n", 3);
  11594. else
  11595. outputStream.writeByte ('>');
  11596. }
  11597. else
  11598. {
  11599. if (indentationLevel >= 0)
  11600. outputStream.write ("/>\r\n", 4);
  11601. else
  11602. outputStream.write ("/>", 2);
  11603. }
  11604. }
  11605. else
  11606. {
  11607. if (indentationLevel >= 0)
  11608. writeSpaces (outputStream, indentationLevel + 2);
  11609. escapeIllegalXmlChars (outputStream, getText(), false);
  11610. }
  11611. }
  11612. const String XmlElement::createDocument (const String& dtdToUse,
  11613. const bool allOnOneLine,
  11614. const bool includeXmlHeader,
  11615. const String& encodingType,
  11616. const int lineWrapLength) const
  11617. {
  11618. MemoryOutputStream mem (2048);
  11619. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  11620. return mem.toUTF8();
  11621. }
  11622. void XmlElement::writeToStream (OutputStream& output,
  11623. const String& dtdToUse,
  11624. const bool allOnOneLine,
  11625. const bool includeXmlHeader,
  11626. const String& encodingType,
  11627. const int lineWrapLength) const
  11628. {
  11629. if (includeXmlHeader)
  11630. output << "<?xml version=\"1.0\" encoding=\"" << encodingType
  11631. << (allOnOneLine ? "\"?> " : "\"?>\r\n\r\n");
  11632. if (dtdToUse.isNotEmpty())
  11633. output << dtdToUse << (allOnOneLine ? " " : "\r\n");
  11634. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  11635. }
  11636. bool XmlElement::writeToFile (const File& file,
  11637. const String& dtdToUse,
  11638. const String& encodingType,
  11639. const int lineWrapLength) const
  11640. {
  11641. if (file.hasWriteAccess())
  11642. {
  11643. TemporaryFile tempFile (file);
  11644. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  11645. if (out != 0)
  11646. {
  11647. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  11648. out = 0;
  11649. return tempFile.overwriteTargetFileWithTemporary();
  11650. }
  11651. }
  11652. return false;
  11653. }
  11654. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  11655. {
  11656. #if JUCE_DEBUG
  11657. // if debugging, check that the case is actually the same, because
  11658. // valid xml is case-sensitive, and although this lets it pass, it's
  11659. // better not to..
  11660. if (tagName.equalsIgnoreCase (tagNameWanted))
  11661. {
  11662. jassert (tagName == tagNameWanted);
  11663. return true;
  11664. }
  11665. else
  11666. {
  11667. return false;
  11668. }
  11669. #else
  11670. return tagName.equalsIgnoreCase (tagNameWanted);
  11671. #endif
  11672. }
  11673. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  11674. {
  11675. XmlElement* e = nextElement;
  11676. while (e != 0 && ! e->hasTagName (requiredTagName))
  11677. e = e->nextElement;
  11678. return e;
  11679. }
  11680. int XmlElement::getNumAttributes() const throw()
  11681. {
  11682. const XmlAttributeNode* att = attributes;
  11683. int count = 0;
  11684. while (att != 0)
  11685. {
  11686. att = att->next;
  11687. ++count;
  11688. }
  11689. return count;
  11690. }
  11691. const String& XmlElement::getAttributeName (const int index) const throw()
  11692. {
  11693. const XmlAttributeNode* att = attributes;
  11694. int count = 0;
  11695. while (att != 0)
  11696. {
  11697. if (count == index)
  11698. return att->name;
  11699. att = att->next;
  11700. ++count;
  11701. }
  11702. return String::empty;
  11703. }
  11704. const String& XmlElement::getAttributeValue (const int index) const throw()
  11705. {
  11706. const XmlAttributeNode* att = attributes;
  11707. int count = 0;
  11708. while (att != 0)
  11709. {
  11710. if (count == index)
  11711. return att->value;
  11712. att = att->next;
  11713. ++count;
  11714. }
  11715. return String::empty;
  11716. }
  11717. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  11718. {
  11719. const XmlAttributeNode* att = attributes;
  11720. while (att != 0)
  11721. {
  11722. if (att->name.equalsIgnoreCase (attributeName))
  11723. return true;
  11724. att = att->next;
  11725. }
  11726. return false;
  11727. }
  11728. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  11729. {
  11730. const XmlAttributeNode* att = attributes;
  11731. while (att != 0)
  11732. {
  11733. if (att->name.equalsIgnoreCase (attributeName))
  11734. return att->value;
  11735. att = att->next;
  11736. }
  11737. return String::empty;
  11738. }
  11739. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  11740. {
  11741. const XmlAttributeNode* att = attributes;
  11742. while (att != 0)
  11743. {
  11744. if (att->name.equalsIgnoreCase (attributeName))
  11745. return att->value;
  11746. att = att->next;
  11747. }
  11748. return defaultReturnValue;
  11749. }
  11750. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  11751. {
  11752. const XmlAttributeNode* att = attributes;
  11753. while (att != 0)
  11754. {
  11755. if (att->name.equalsIgnoreCase (attributeName))
  11756. return att->value.getIntValue();
  11757. att = att->next;
  11758. }
  11759. return defaultReturnValue;
  11760. }
  11761. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  11762. {
  11763. const XmlAttributeNode* att = attributes;
  11764. while (att != 0)
  11765. {
  11766. if (att->name.equalsIgnoreCase (attributeName))
  11767. return att->value.getDoubleValue();
  11768. att = att->next;
  11769. }
  11770. return defaultReturnValue;
  11771. }
  11772. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  11773. {
  11774. const XmlAttributeNode* att = attributes;
  11775. while (att != 0)
  11776. {
  11777. if (att->name.equalsIgnoreCase (attributeName))
  11778. {
  11779. juce_wchar firstChar = att->value[0];
  11780. if (CharacterFunctions::isWhitespace (firstChar))
  11781. firstChar = att->value.trimStart() [0];
  11782. return firstChar == '1'
  11783. || firstChar == 't'
  11784. || firstChar == 'y'
  11785. || firstChar == 'T'
  11786. || firstChar == 'Y';
  11787. }
  11788. att = att->next;
  11789. }
  11790. return defaultReturnValue;
  11791. }
  11792. bool XmlElement::compareAttribute (const String& attributeName,
  11793. const String& stringToCompareAgainst,
  11794. const bool ignoreCase) const throw()
  11795. {
  11796. const XmlAttributeNode* att = attributes;
  11797. while (att != 0)
  11798. {
  11799. if (att->name.equalsIgnoreCase (attributeName))
  11800. {
  11801. if (ignoreCase)
  11802. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  11803. else
  11804. return att->value == stringToCompareAgainst;
  11805. }
  11806. att = att->next;
  11807. }
  11808. return false;
  11809. }
  11810. void XmlElement::setAttribute (const String& attributeName, const String& value)
  11811. {
  11812. #if JUCE_DEBUG
  11813. // check the identifier being passed in is legal..
  11814. const juce_wchar* t = attributeName;
  11815. while (*t != 0)
  11816. {
  11817. jassert (CharacterFunctions::isLetterOrDigit (*t)
  11818. || *t == '_'
  11819. || *t == '-'
  11820. || *t == ':');
  11821. ++t;
  11822. }
  11823. #endif
  11824. if (attributes == 0)
  11825. {
  11826. attributes = new XmlAttributeNode (attributeName, value);
  11827. }
  11828. else
  11829. {
  11830. XmlAttributeNode* att = attributes;
  11831. for (;;)
  11832. {
  11833. if (att->name.equalsIgnoreCase (attributeName))
  11834. {
  11835. att->value = value;
  11836. break;
  11837. }
  11838. else if (att->next == 0)
  11839. {
  11840. att->next = new XmlAttributeNode (attributeName, value);
  11841. break;
  11842. }
  11843. att = att->next;
  11844. }
  11845. }
  11846. }
  11847. void XmlElement::setAttribute (const String& attributeName, const int number)
  11848. {
  11849. setAttribute (attributeName, String (number));
  11850. }
  11851. void XmlElement::setAttribute (const String& attributeName, const double number)
  11852. {
  11853. setAttribute (attributeName, String (number));
  11854. }
  11855. void XmlElement::removeAttribute (const String& attributeName) throw()
  11856. {
  11857. XmlAttributeNode* att = attributes;
  11858. XmlAttributeNode* lastAtt = 0;
  11859. while (att != 0)
  11860. {
  11861. if (att->name.equalsIgnoreCase (attributeName))
  11862. {
  11863. if (lastAtt == 0)
  11864. attributes = att->next;
  11865. else
  11866. lastAtt->next = att->next;
  11867. delete att;
  11868. break;
  11869. }
  11870. lastAtt = att;
  11871. att = att->next;
  11872. }
  11873. }
  11874. void XmlElement::removeAllAttributes() throw()
  11875. {
  11876. while (attributes != 0)
  11877. {
  11878. XmlAttributeNode* const nextAtt = attributes->next;
  11879. delete attributes;
  11880. attributes = nextAtt;
  11881. }
  11882. }
  11883. int XmlElement::getNumChildElements() const throw()
  11884. {
  11885. int count = 0;
  11886. const XmlElement* child = firstChildElement;
  11887. while (child != 0)
  11888. {
  11889. ++count;
  11890. child = child->nextElement;
  11891. }
  11892. return count;
  11893. }
  11894. XmlElement* XmlElement::getChildElement (const int index) const throw()
  11895. {
  11896. int count = 0;
  11897. XmlElement* child = firstChildElement;
  11898. while (child != 0 && count < index)
  11899. {
  11900. child = child->nextElement;
  11901. ++count;
  11902. }
  11903. return child;
  11904. }
  11905. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  11906. {
  11907. XmlElement* child = firstChildElement;
  11908. while (child != 0)
  11909. {
  11910. if (child->hasTagName (childName))
  11911. break;
  11912. child = child->nextElement;
  11913. }
  11914. return child;
  11915. }
  11916. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  11917. {
  11918. if (newNode != 0)
  11919. {
  11920. if (firstChildElement == 0)
  11921. {
  11922. firstChildElement = newNode;
  11923. }
  11924. else
  11925. {
  11926. XmlElement* child = firstChildElement;
  11927. while (child->nextElement != 0)
  11928. child = child->nextElement;
  11929. child->nextElement = newNode;
  11930. // if this is non-zero, then something's probably
  11931. // gone wrong..
  11932. jassert (newNode->nextElement == 0);
  11933. }
  11934. }
  11935. }
  11936. void XmlElement::insertChildElement (XmlElement* const newNode,
  11937. int indexToInsertAt) throw()
  11938. {
  11939. if (newNode != 0)
  11940. {
  11941. removeChildElement (newNode, false);
  11942. if (indexToInsertAt == 0)
  11943. {
  11944. newNode->nextElement = firstChildElement;
  11945. firstChildElement = newNode;
  11946. }
  11947. else
  11948. {
  11949. if (firstChildElement == 0)
  11950. {
  11951. firstChildElement = newNode;
  11952. }
  11953. else
  11954. {
  11955. if (indexToInsertAt < 0)
  11956. indexToInsertAt = std::numeric_limits<int>::max();
  11957. XmlElement* child = firstChildElement;
  11958. while (child->nextElement != 0 && --indexToInsertAt > 0)
  11959. child = child->nextElement;
  11960. newNode->nextElement = child->nextElement;
  11961. child->nextElement = newNode;
  11962. }
  11963. }
  11964. }
  11965. }
  11966. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  11967. {
  11968. XmlElement* const newElement = new XmlElement (childTagName);
  11969. addChildElement (newElement);
  11970. return newElement;
  11971. }
  11972. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  11973. XmlElement* const newNode) throw()
  11974. {
  11975. if (newNode != 0)
  11976. {
  11977. XmlElement* child = firstChildElement;
  11978. XmlElement* previousNode = 0;
  11979. while (child != 0)
  11980. {
  11981. if (child == currentChildElement)
  11982. {
  11983. if (child != newNode)
  11984. {
  11985. if (previousNode == 0)
  11986. firstChildElement = newNode;
  11987. else
  11988. previousNode->nextElement = newNode;
  11989. newNode->nextElement = child->nextElement;
  11990. delete child;
  11991. }
  11992. return true;
  11993. }
  11994. previousNode = child;
  11995. child = child->nextElement;
  11996. }
  11997. }
  11998. return false;
  11999. }
  12000. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  12001. const bool shouldDeleteTheChild) throw()
  12002. {
  12003. if (childToRemove != 0)
  12004. {
  12005. if (firstChildElement == childToRemove)
  12006. {
  12007. firstChildElement = childToRemove->nextElement;
  12008. childToRemove->nextElement = 0;
  12009. }
  12010. else
  12011. {
  12012. XmlElement* child = firstChildElement;
  12013. XmlElement* last = 0;
  12014. while (child != 0)
  12015. {
  12016. if (child == childToRemove)
  12017. {
  12018. if (last == 0)
  12019. firstChildElement = child->nextElement;
  12020. else
  12021. last->nextElement = child->nextElement;
  12022. childToRemove->nextElement = 0;
  12023. break;
  12024. }
  12025. last = child;
  12026. child = child->nextElement;
  12027. }
  12028. }
  12029. if (shouldDeleteTheChild)
  12030. delete childToRemove;
  12031. }
  12032. }
  12033. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  12034. const bool ignoreOrderOfAttributes) const throw()
  12035. {
  12036. if (this != other)
  12037. {
  12038. if (other == 0 || tagName != other->tagName)
  12039. {
  12040. return false;
  12041. }
  12042. if (ignoreOrderOfAttributes)
  12043. {
  12044. int totalAtts = 0;
  12045. const XmlAttributeNode* att = attributes;
  12046. while (att != 0)
  12047. {
  12048. if (! other->compareAttribute (att->name, att->value))
  12049. return false;
  12050. att = att->next;
  12051. ++totalAtts;
  12052. }
  12053. if (totalAtts != other->getNumAttributes())
  12054. return false;
  12055. }
  12056. else
  12057. {
  12058. const XmlAttributeNode* thisAtt = attributes;
  12059. const XmlAttributeNode* otherAtt = other->attributes;
  12060. for (;;)
  12061. {
  12062. if (thisAtt == 0 || otherAtt == 0)
  12063. {
  12064. if (thisAtt == otherAtt) // both 0, so it's a match
  12065. break;
  12066. return false;
  12067. }
  12068. if (thisAtt->name != otherAtt->name
  12069. || thisAtt->value != otherAtt->value)
  12070. {
  12071. return false;
  12072. }
  12073. thisAtt = thisAtt->next;
  12074. otherAtt = otherAtt->next;
  12075. }
  12076. }
  12077. const XmlElement* thisChild = firstChildElement;
  12078. const XmlElement* otherChild = other->firstChildElement;
  12079. for (;;)
  12080. {
  12081. if (thisChild == 0 || otherChild == 0)
  12082. {
  12083. if (thisChild == otherChild) // both 0, so it's a match
  12084. break;
  12085. return false;
  12086. }
  12087. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  12088. return false;
  12089. thisChild = thisChild->nextElement;
  12090. otherChild = otherChild->nextElement;
  12091. }
  12092. }
  12093. return true;
  12094. }
  12095. void XmlElement::deleteAllChildElements() throw()
  12096. {
  12097. while (firstChildElement != 0)
  12098. {
  12099. XmlElement* const nextChild = firstChildElement->nextElement;
  12100. delete firstChildElement;
  12101. firstChildElement = nextChild;
  12102. }
  12103. }
  12104. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  12105. {
  12106. XmlElement* child = firstChildElement;
  12107. while (child != 0)
  12108. {
  12109. if (child->hasTagName (name))
  12110. {
  12111. XmlElement* const nextChild = child->nextElement;
  12112. removeChildElement (child, true);
  12113. child = nextChild;
  12114. }
  12115. else
  12116. {
  12117. child = child->nextElement;
  12118. }
  12119. }
  12120. }
  12121. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  12122. {
  12123. const XmlElement* child = firstChildElement;
  12124. while (child != 0)
  12125. {
  12126. if (child == possibleChild)
  12127. return true;
  12128. child = child->nextElement;
  12129. }
  12130. return false;
  12131. }
  12132. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  12133. {
  12134. if (this == elementToLookFor || elementToLookFor == 0)
  12135. return 0;
  12136. XmlElement* child = firstChildElement;
  12137. while (child != 0)
  12138. {
  12139. if (elementToLookFor == child)
  12140. return this;
  12141. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  12142. if (found != 0)
  12143. return found;
  12144. child = child->nextElement;
  12145. }
  12146. return 0;
  12147. }
  12148. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  12149. {
  12150. XmlElement* e = firstChildElement;
  12151. while (e != 0)
  12152. {
  12153. *elems++ = e;
  12154. e = e->nextElement;
  12155. }
  12156. }
  12157. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  12158. {
  12159. XmlElement* e = firstChildElement = elems[0];
  12160. for (int i = 1; i < num; ++i)
  12161. {
  12162. e->nextElement = elems[i];
  12163. e = e->nextElement;
  12164. }
  12165. e->nextElement = 0;
  12166. }
  12167. bool XmlElement::isTextElement() const throw()
  12168. {
  12169. return tagName.isEmpty();
  12170. }
  12171. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  12172. const String& XmlElement::getText() const throw()
  12173. {
  12174. jassert (isTextElement()); // you're trying to get the text from an element that
  12175. // isn't actually a text element.. If this contains text sub-nodes, you
  12176. // probably want to use getAllSubText instead.
  12177. return getStringAttribute (juce_xmltextContentAttributeName);
  12178. }
  12179. void XmlElement::setText (const String& newText)
  12180. {
  12181. if (isTextElement())
  12182. setAttribute (juce_xmltextContentAttributeName, newText);
  12183. else
  12184. jassertfalse; // you can only change the text in a text element, not a normal one.
  12185. }
  12186. const String XmlElement::getAllSubText() const
  12187. {
  12188. String result;
  12189. String::Concatenator concatenator (result);
  12190. const XmlElement* child = firstChildElement;
  12191. while (child != 0)
  12192. {
  12193. if (child->isTextElement())
  12194. concatenator.append (child->getText());
  12195. child = child->nextElement;
  12196. }
  12197. return result;
  12198. }
  12199. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  12200. const String& defaultReturnValue) const
  12201. {
  12202. const XmlElement* const child = getChildByName (childTagName);
  12203. if (child != 0)
  12204. return child->getAllSubText();
  12205. return defaultReturnValue;
  12206. }
  12207. XmlElement* XmlElement::createTextElement (const String& text)
  12208. {
  12209. XmlElement* const e = new XmlElement ((int) 0);
  12210. e->setAttribute (juce_xmltextContentAttributeName, text);
  12211. return e;
  12212. }
  12213. void XmlElement::addTextElement (const String& text)
  12214. {
  12215. addChildElement (createTextElement (text));
  12216. }
  12217. void XmlElement::deleteAllTextElements() throw()
  12218. {
  12219. XmlElement* child = firstChildElement;
  12220. while (child != 0)
  12221. {
  12222. XmlElement* const next = child->nextElement;
  12223. if (child->isTextElement())
  12224. removeChildElement (child, true);
  12225. child = next;
  12226. }
  12227. }
  12228. END_JUCE_NAMESPACE
  12229. /*** End of inlined file: juce_XmlElement.cpp ***/
  12230. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  12231. BEGIN_JUCE_NAMESPACE
  12232. ReadWriteLock::ReadWriteLock() throw()
  12233. : numWaitingWriters (0),
  12234. numWriters (0),
  12235. writerThreadId (0)
  12236. {
  12237. }
  12238. ReadWriteLock::~ReadWriteLock() throw()
  12239. {
  12240. jassert (readerThreads.size() == 0);
  12241. jassert (numWriters == 0);
  12242. }
  12243. void ReadWriteLock::enterRead() const throw()
  12244. {
  12245. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12246. const ScopedLock sl (accessLock);
  12247. for (;;)
  12248. {
  12249. jassert (readerThreads.size() % 2 == 0);
  12250. int i;
  12251. for (i = 0; i < readerThreads.size(); i += 2)
  12252. if (readerThreads.getUnchecked(i) == threadId)
  12253. break;
  12254. if (i < readerThreads.size()
  12255. || numWriters + numWaitingWriters == 0
  12256. || (threadId == writerThreadId && numWriters > 0))
  12257. {
  12258. if (i < readerThreads.size())
  12259. {
  12260. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12261. }
  12262. else
  12263. {
  12264. readerThreads.add (threadId);
  12265. readerThreads.add ((Thread::ThreadID) 1);
  12266. }
  12267. return;
  12268. }
  12269. const ScopedUnlock ul (accessLock);
  12270. waitEvent.wait (100);
  12271. }
  12272. }
  12273. void ReadWriteLock::exitRead() const throw()
  12274. {
  12275. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12276. const ScopedLock sl (accessLock);
  12277. for (int i = 0; i < readerThreads.size(); i += 2)
  12278. {
  12279. if (readerThreads.getUnchecked(i) == threadId)
  12280. {
  12281. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  12282. if (newCount == 0)
  12283. {
  12284. readerThreads.removeRange (i, 2);
  12285. waitEvent.signal();
  12286. }
  12287. else
  12288. {
  12289. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  12290. }
  12291. return;
  12292. }
  12293. }
  12294. jassertfalse; // unlocking a lock that wasn't locked..
  12295. }
  12296. void ReadWriteLock::enterWrite() const throw()
  12297. {
  12298. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12299. const ScopedLock sl (accessLock);
  12300. for (;;)
  12301. {
  12302. if (readerThreads.size() + numWriters == 0
  12303. || threadId == writerThreadId
  12304. || (readerThreads.size() == 2
  12305. && readerThreads.getUnchecked(0) == threadId))
  12306. {
  12307. writerThreadId = threadId;
  12308. ++numWriters;
  12309. break;
  12310. }
  12311. ++numWaitingWriters;
  12312. accessLock.exit();
  12313. waitEvent.wait (100);
  12314. accessLock.enter();
  12315. --numWaitingWriters;
  12316. }
  12317. }
  12318. bool ReadWriteLock::tryEnterWrite() const throw()
  12319. {
  12320. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12321. const ScopedLock sl (accessLock);
  12322. if (readerThreads.size() + numWriters == 0
  12323. || threadId == writerThreadId
  12324. || (readerThreads.size() == 2
  12325. && readerThreads.getUnchecked(0) == threadId))
  12326. {
  12327. writerThreadId = threadId;
  12328. ++numWriters;
  12329. return true;
  12330. }
  12331. return false;
  12332. }
  12333. void ReadWriteLock::exitWrite() const throw()
  12334. {
  12335. const ScopedLock sl (accessLock);
  12336. // check this thread actually had the lock..
  12337. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  12338. if (--numWriters == 0)
  12339. {
  12340. writerThreadId = 0;
  12341. waitEvent.signal();
  12342. }
  12343. }
  12344. END_JUCE_NAMESPACE
  12345. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  12346. /*** Start of inlined file: juce_Thread.cpp ***/
  12347. BEGIN_JUCE_NAMESPACE
  12348. // these functions are implemented in the platform-specific code.
  12349. void* juce_createThread (void* userData);
  12350. void juce_killThread (void* handle);
  12351. bool juce_setThreadPriority (void* handle, int priority);
  12352. void juce_setCurrentThreadName (const String& name);
  12353. #if JUCE_WINDOWS
  12354. void juce_CloseThreadHandle (void* handle);
  12355. #endif
  12356. void Thread::threadEntryPoint (Thread* const thread)
  12357. {
  12358. {
  12359. const ScopedLock sl (runningThreadsLock);
  12360. runningThreads.add (thread);
  12361. }
  12362. JUCE_TRY
  12363. {
  12364. thread->threadId_ = Thread::getCurrentThreadId();
  12365. if (thread->threadName_.isNotEmpty())
  12366. juce_setCurrentThreadName (thread->threadName_);
  12367. if (thread->startSuspensionEvent_.wait (10000))
  12368. {
  12369. if (thread->affinityMask_ != 0)
  12370. setCurrentThreadAffinityMask (thread->affinityMask_);
  12371. thread->run();
  12372. }
  12373. }
  12374. JUCE_CATCH_ALL_ASSERT
  12375. {
  12376. const ScopedLock sl (runningThreadsLock);
  12377. jassert (runningThreads.contains (thread));
  12378. runningThreads.removeValue (thread);
  12379. }
  12380. #if JUCE_WINDOWS
  12381. juce_CloseThreadHandle (thread->threadHandle_);
  12382. #endif
  12383. thread->threadHandle_ = 0;
  12384. thread->threadId_ = 0;
  12385. }
  12386. // used to wrap the incoming call from the platform-specific code
  12387. void JUCE_API juce_threadEntryPoint (void* userData)
  12388. {
  12389. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  12390. }
  12391. Thread::Thread (const String& threadName)
  12392. : threadName_ (threadName),
  12393. threadHandle_ (0),
  12394. threadPriority_ (5),
  12395. threadId_ (0),
  12396. affinityMask_ (0),
  12397. threadShouldExit_ (false)
  12398. {
  12399. }
  12400. Thread::~Thread()
  12401. {
  12402. stopThread (100);
  12403. }
  12404. void Thread::startThread()
  12405. {
  12406. const ScopedLock sl (startStopLock);
  12407. threadShouldExit_ = false;
  12408. if (threadHandle_ == 0)
  12409. {
  12410. threadHandle_ = juce_createThread (this);
  12411. juce_setThreadPriority (threadHandle_, threadPriority_);
  12412. startSuspensionEvent_.signal();
  12413. }
  12414. }
  12415. void Thread::startThread (const int priority)
  12416. {
  12417. const ScopedLock sl (startStopLock);
  12418. if (threadHandle_ == 0)
  12419. {
  12420. threadPriority_ = priority;
  12421. startThread();
  12422. }
  12423. else
  12424. {
  12425. setPriority (priority);
  12426. }
  12427. }
  12428. bool Thread::isThreadRunning() const
  12429. {
  12430. return threadHandle_ != 0;
  12431. }
  12432. void Thread::signalThreadShouldExit()
  12433. {
  12434. threadShouldExit_ = true;
  12435. }
  12436. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  12437. {
  12438. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  12439. jassert (getThreadId() != getCurrentThreadId());
  12440. const int sleepMsPerIteration = 5;
  12441. int count = timeOutMilliseconds / sleepMsPerIteration;
  12442. while (isThreadRunning())
  12443. {
  12444. if (timeOutMilliseconds > 0 && --count < 0)
  12445. return false;
  12446. sleep (sleepMsPerIteration);
  12447. }
  12448. return true;
  12449. }
  12450. void Thread::stopThread (const int timeOutMilliseconds)
  12451. {
  12452. // agh! You can't stop the thread that's calling this method! How on earth
  12453. // would that work??
  12454. jassert (getCurrentThreadId() != getThreadId());
  12455. const ScopedLock sl (startStopLock);
  12456. if (isThreadRunning())
  12457. {
  12458. signalThreadShouldExit();
  12459. notify();
  12460. if (timeOutMilliseconds != 0)
  12461. waitForThreadToExit (timeOutMilliseconds);
  12462. if (isThreadRunning())
  12463. {
  12464. // very bad karma if this point is reached, as
  12465. // there are bound to be locks and events left in
  12466. // silly states when a thread is killed by force..
  12467. jassertfalse;
  12468. Logger::writeToLog ("!! killing thread by force !!");
  12469. juce_killThread (threadHandle_);
  12470. threadHandle_ = 0;
  12471. threadId_ = 0;
  12472. const ScopedLock sl2 (runningThreadsLock);
  12473. runningThreads.removeValue (this);
  12474. }
  12475. }
  12476. }
  12477. bool Thread::setPriority (const int priority)
  12478. {
  12479. const ScopedLock sl (startStopLock);
  12480. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  12481. if (worked)
  12482. threadPriority_ = priority;
  12483. return worked;
  12484. }
  12485. bool Thread::setCurrentThreadPriority (const int priority)
  12486. {
  12487. return juce_setThreadPriority (0, priority);
  12488. }
  12489. void Thread::setAffinityMask (const uint32 affinityMask)
  12490. {
  12491. affinityMask_ = affinityMask;
  12492. }
  12493. bool Thread::wait (const int timeOutMilliseconds) const
  12494. {
  12495. return defaultEvent_.wait (timeOutMilliseconds);
  12496. }
  12497. void Thread::notify() const
  12498. {
  12499. defaultEvent_.signal();
  12500. }
  12501. int Thread::getNumRunningThreads()
  12502. {
  12503. return runningThreads.size();
  12504. }
  12505. Thread* Thread::getCurrentThread()
  12506. {
  12507. const ThreadID thisId = getCurrentThreadId();
  12508. const ScopedLock sl (runningThreadsLock);
  12509. for (int i = runningThreads.size(); --i >= 0;)
  12510. {
  12511. Thread* const t = runningThreads.getUnchecked(i);
  12512. if (t->threadId_ == thisId)
  12513. return t;
  12514. }
  12515. return 0;
  12516. }
  12517. void Thread::stopAllThreads (const int timeOutMilliseconds)
  12518. {
  12519. {
  12520. const ScopedLock sl (runningThreadsLock);
  12521. for (int i = runningThreads.size(); --i >= 0;)
  12522. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  12523. }
  12524. for (;;)
  12525. {
  12526. Thread* firstThread;
  12527. {
  12528. const ScopedLock sl (runningThreadsLock);
  12529. firstThread = runningThreads.getFirst();
  12530. }
  12531. if (firstThread == 0)
  12532. break;
  12533. firstThread->stopThread (timeOutMilliseconds);
  12534. }
  12535. }
  12536. Array<Thread*> Thread::runningThreads;
  12537. CriticalSection Thread::runningThreadsLock;
  12538. END_JUCE_NAMESPACE
  12539. /*** End of inlined file: juce_Thread.cpp ***/
  12540. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  12541. BEGIN_JUCE_NAMESPACE
  12542. ThreadPoolJob::ThreadPoolJob (const String& name)
  12543. : jobName (name),
  12544. pool (0),
  12545. shouldStop (false),
  12546. isActive (false),
  12547. shouldBeDeleted (false)
  12548. {
  12549. }
  12550. ThreadPoolJob::~ThreadPoolJob()
  12551. {
  12552. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  12553. // to remove it first!
  12554. jassert (pool == 0 || ! pool->contains (this));
  12555. }
  12556. const String ThreadPoolJob::getJobName() const
  12557. {
  12558. return jobName;
  12559. }
  12560. void ThreadPoolJob::setJobName (const String& newName)
  12561. {
  12562. jobName = newName;
  12563. }
  12564. void ThreadPoolJob::signalJobShouldExit()
  12565. {
  12566. shouldStop = true;
  12567. }
  12568. class ThreadPool::ThreadPoolThread : public Thread
  12569. {
  12570. public:
  12571. ThreadPoolThread (ThreadPool& pool_)
  12572. : Thread ("Pool"),
  12573. pool (pool_),
  12574. busy (false)
  12575. {
  12576. }
  12577. ~ThreadPoolThread()
  12578. {
  12579. }
  12580. void run()
  12581. {
  12582. while (! threadShouldExit())
  12583. {
  12584. if (! pool.runNextJob())
  12585. wait (500);
  12586. }
  12587. }
  12588. private:
  12589. ThreadPool& pool;
  12590. bool volatile busy;
  12591. ThreadPoolThread (const ThreadPoolThread&);
  12592. ThreadPoolThread& operator= (const ThreadPoolThread&);
  12593. };
  12594. ThreadPool::ThreadPool (const int numThreads,
  12595. const bool startThreadsOnlyWhenNeeded,
  12596. const int stopThreadsWhenNotUsedTimeoutMs)
  12597. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  12598. priority (5)
  12599. {
  12600. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  12601. for (int i = jmax (1, numThreads); --i >= 0;)
  12602. threads.add (new ThreadPoolThread (*this));
  12603. if (! startThreadsOnlyWhenNeeded)
  12604. for (int i = threads.size(); --i >= 0;)
  12605. threads.getUnchecked(i)->startThread (priority);
  12606. }
  12607. ThreadPool::~ThreadPool()
  12608. {
  12609. removeAllJobs (true, 4000);
  12610. int i;
  12611. for (i = threads.size(); --i >= 0;)
  12612. threads.getUnchecked(i)->signalThreadShouldExit();
  12613. for (i = threads.size(); --i >= 0;)
  12614. threads.getUnchecked(i)->stopThread (500);
  12615. }
  12616. void ThreadPool::addJob (ThreadPoolJob* const job)
  12617. {
  12618. jassert (job != 0);
  12619. jassert (job->pool == 0);
  12620. if (job->pool == 0)
  12621. {
  12622. job->pool = this;
  12623. job->shouldStop = false;
  12624. job->isActive = false;
  12625. {
  12626. const ScopedLock sl (lock);
  12627. jobs.add (job);
  12628. int numRunning = 0;
  12629. for (int i = threads.size(); --i >= 0;)
  12630. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  12631. ++numRunning;
  12632. if (numRunning < threads.size())
  12633. {
  12634. bool startedOne = false;
  12635. int n = 1000;
  12636. while (--n >= 0 && ! startedOne)
  12637. {
  12638. for (int i = threads.size(); --i >= 0;)
  12639. {
  12640. if (! threads.getUnchecked(i)->isThreadRunning())
  12641. {
  12642. threads.getUnchecked(i)->startThread (priority);
  12643. startedOne = true;
  12644. break;
  12645. }
  12646. }
  12647. if (! startedOne)
  12648. Thread::sleep (2);
  12649. }
  12650. }
  12651. }
  12652. for (int i = threads.size(); --i >= 0;)
  12653. threads.getUnchecked(i)->notify();
  12654. }
  12655. }
  12656. int ThreadPool::getNumJobs() const
  12657. {
  12658. return jobs.size();
  12659. }
  12660. ThreadPoolJob* ThreadPool::getJob (const int index) const
  12661. {
  12662. const ScopedLock sl (lock);
  12663. return jobs [index];
  12664. }
  12665. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  12666. {
  12667. const ScopedLock sl (lock);
  12668. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  12669. }
  12670. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  12671. {
  12672. const ScopedLock sl (lock);
  12673. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  12674. }
  12675. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  12676. const int timeOutMs) const
  12677. {
  12678. if (job != 0)
  12679. {
  12680. const uint32 start = Time::getMillisecondCounter();
  12681. while (contains (job))
  12682. {
  12683. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12684. return false;
  12685. jobFinishedSignal.wait (2);
  12686. }
  12687. }
  12688. return true;
  12689. }
  12690. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  12691. const bool interruptIfRunning,
  12692. const int timeOutMs)
  12693. {
  12694. bool dontWait = true;
  12695. if (job != 0)
  12696. {
  12697. const ScopedLock sl (lock);
  12698. if (jobs.contains (job))
  12699. {
  12700. if (job->isActive)
  12701. {
  12702. if (interruptIfRunning)
  12703. job->signalJobShouldExit();
  12704. dontWait = false;
  12705. }
  12706. else
  12707. {
  12708. jobs.removeValue (job);
  12709. job->pool = 0;
  12710. }
  12711. }
  12712. }
  12713. return dontWait || waitForJobToFinish (job, timeOutMs);
  12714. }
  12715. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  12716. const int timeOutMs,
  12717. const bool deleteInactiveJobs,
  12718. ThreadPool::JobSelector* selectedJobsToRemove)
  12719. {
  12720. Array <ThreadPoolJob*> jobsToWaitFor;
  12721. {
  12722. const ScopedLock sl (lock);
  12723. for (int i = jobs.size(); --i >= 0;)
  12724. {
  12725. ThreadPoolJob* const job = jobs.getUnchecked(i);
  12726. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  12727. {
  12728. if (job->isActive)
  12729. {
  12730. jobsToWaitFor.add (job);
  12731. if (interruptRunningJobs)
  12732. job->signalJobShouldExit();
  12733. }
  12734. else
  12735. {
  12736. jobs.remove (i);
  12737. if (deleteInactiveJobs)
  12738. delete job;
  12739. else
  12740. job->pool = 0;
  12741. }
  12742. }
  12743. }
  12744. }
  12745. const uint32 start = Time::getMillisecondCounter();
  12746. for (;;)
  12747. {
  12748. for (int i = jobsToWaitFor.size(); --i >= 0;)
  12749. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  12750. jobsToWaitFor.remove (i);
  12751. if (jobsToWaitFor.size() == 0)
  12752. break;
  12753. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12754. return false;
  12755. jobFinishedSignal.wait (20);
  12756. }
  12757. return true;
  12758. }
  12759. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  12760. {
  12761. StringArray s;
  12762. const ScopedLock sl (lock);
  12763. for (int i = 0; i < jobs.size(); ++i)
  12764. {
  12765. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  12766. if (job->isActive || ! onlyReturnActiveJobs)
  12767. s.add (job->getJobName());
  12768. }
  12769. return s;
  12770. }
  12771. bool ThreadPool::setThreadPriorities (const int newPriority)
  12772. {
  12773. bool ok = true;
  12774. if (priority != newPriority)
  12775. {
  12776. priority = newPriority;
  12777. for (int i = threads.size(); --i >= 0;)
  12778. if (! threads.getUnchecked(i)->setPriority (newPriority))
  12779. ok = false;
  12780. }
  12781. return ok;
  12782. }
  12783. bool ThreadPool::runNextJob()
  12784. {
  12785. ThreadPoolJob* job = 0;
  12786. {
  12787. const ScopedLock sl (lock);
  12788. for (int i = 0; i < jobs.size(); ++i)
  12789. {
  12790. job = jobs[i];
  12791. if (job != 0 && ! (job->isActive || job->shouldStop))
  12792. break;
  12793. job = 0;
  12794. }
  12795. if (job != 0)
  12796. job->isActive = true;
  12797. }
  12798. if (job != 0)
  12799. {
  12800. JUCE_TRY
  12801. {
  12802. ThreadPoolJob::JobStatus result = job->runJob();
  12803. lastJobEndTime = Time::getApproximateMillisecondCounter();
  12804. const ScopedLock sl (lock);
  12805. if (jobs.contains (job))
  12806. {
  12807. job->isActive = false;
  12808. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  12809. {
  12810. job->pool = 0;
  12811. job->shouldStop = true;
  12812. jobs.removeValue (job);
  12813. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  12814. delete job;
  12815. jobFinishedSignal.signal();
  12816. }
  12817. else
  12818. {
  12819. // move the job to the end of the queue if it wants another go
  12820. jobs.move (jobs.indexOf (job), -1);
  12821. }
  12822. }
  12823. }
  12824. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12825. catch (...)
  12826. {
  12827. const ScopedLock sl (lock);
  12828. jobs.removeValue (job);
  12829. }
  12830. #endif
  12831. }
  12832. else
  12833. {
  12834. if (threadStopTimeout > 0
  12835. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  12836. {
  12837. const ScopedLock sl (lock);
  12838. if (jobs.size() == 0)
  12839. for (int i = threads.size(); --i >= 0;)
  12840. threads.getUnchecked(i)->signalThreadShouldExit();
  12841. }
  12842. else
  12843. {
  12844. return false;
  12845. }
  12846. }
  12847. return true;
  12848. }
  12849. END_JUCE_NAMESPACE
  12850. /*** End of inlined file: juce_ThreadPool.cpp ***/
  12851. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  12852. BEGIN_JUCE_NAMESPACE
  12853. TimeSliceThread::TimeSliceThread (const String& threadName)
  12854. : Thread (threadName),
  12855. index (0),
  12856. clientBeingCalled (0),
  12857. clientsChanged (false)
  12858. {
  12859. }
  12860. TimeSliceThread::~TimeSliceThread()
  12861. {
  12862. stopThread (2000);
  12863. }
  12864. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  12865. {
  12866. const ScopedLock sl (listLock);
  12867. clients.addIfNotAlreadyThere (client);
  12868. clientsChanged = true;
  12869. notify();
  12870. }
  12871. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  12872. {
  12873. const ScopedLock sl1 (listLock);
  12874. clientsChanged = true;
  12875. // if there's a chance we're in the middle of calling this client, we need to
  12876. // also lock the outer lock..
  12877. if (clientBeingCalled == client)
  12878. {
  12879. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  12880. const ScopedLock sl2 (callbackLock);
  12881. const ScopedLock sl3 (listLock);
  12882. clients.removeValue (client);
  12883. }
  12884. else
  12885. {
  12886. clients.removeValue (client);
  12887. }
  12888. }
  12889. int TimeSliceThread::getNumClients() const
  12890. {
  12891. return clients.size();
  12892. }
  12893. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  12894. {
  12895. const ScopedLock sl (listLock);
  12896. return clients [i];
  12897. }
  12898. void TimeSliceThread::run()
  12899. {
  12900. int numCallsSinceBusy = 0;
  12901. while (! threadShouldExit())
  12902. {
  12903. int timeToWait = 500;
  12904. {
  12905. const ScopedLock sl (callbackLock);
  12906. {
  12907. const ScopedLock sl2 (listLock);
  12908. if (clients.size() > 0)
  12909. {
  12910. index = (index + 1) % clients.size();
  12911. clientBeingCalled = clients [index];
  12912. }
  12913. else
  12914. {
  12915. index = 0;
  12916. clientBeingCalled = 0;
  12917. }
  12918. if (clientsChanged)
  12919. {
  12920. clientsChanged = false;
  12921. numCallsSinceBusy = 0;
  12922. }
  12923. }
  12924. if (clientBeingCalled != 0)
  12925. {
  12926. if (clientBeingCalled->useTimeSlice())
  12927. numCallsSinceBusy = 0;
  12928. else
  12929. ++numCallsSinceBusy;
  12930. if (numCallsSinceBusy >= clients.size())
  12931. timeToWait = 500;
  12932. else if (index == 0)
  12933. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  12934. else
  12935. timeToWait = 0;
  12936. }
  12937. }
  12938. if (timeToWait > 0)
  12939. wait (timeToWait);
  12940. }
  12941. }
  12942. END_JUCE_NAMESPACE
  12943. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  12944. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  12945. BEGIN_JUCE_NAMESPACE
  12946. DeletedAtShutdown::DeletedAtShutdown()
  12947. {
  12948. const ScopedLock sl (getLock());
  12949. getObjects().add (this);
  12950. }
  12951. DeletedAtShutdown::~DeletedAtShutdown()
  12952. {
  12953. const ScopedLock sl (getLock());
  12954. getObjects().removeValue (this);
  12955. }
  12956. void DeletedAtShutdown::deleteAll()
  12957. {
  12958. // make a local copy of the array, so it can't get into a loop if something
  12959. // creates another DeletedAtShutdown object during its destructor.
  12960. Array <DeletedAtShutdown*> localCopy;
  12961. {
  12962. const ScopedLock sl (getLock());
  12963. localCopy = getObjects();
  12964. }
  12965. for (int i = localCopy.size(); --i >= 0;)
  12966. {
  12967. JUCE_TRY
  12968. {
  12969. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  12970. // double-check that it's not already been deleted during another object's destructor.
  12971. {
  12972. const ScopedLock sl (getLock());
  12973. if (! getObjects().contains (deletee))
  12974. deletee = 0;
  12975. }
  12976. delete deletee;
  12977. }
  12978. JUCE_CATCH_EXCEPTION
  12979. }
  12980. // if no objects got re-created during shutdown, this should have been emptied by their
  12981. // destructors
  12982. jassert (getObjects().size() == 0);
  12983. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  12984. }
  12985. CriticalSection& DeletedAtShutdown::getLock()
  12986. {
  12987. static CriticalSection lock;
  12988. return lock;
  12989. }
  12990. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  12991. {
  12992. static Array <DeletedAtShutdown*> objects;
  12993. return objects;
  12994. }
  12995. END_JUCE_NAMESPACE
  12996. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  12997. #endif
  12998. #if JUCE_BUILD_MISC
  12999. /*** Start of inlined file: juce_ValueTree.cpp ***/
  13000. BEGIN_JUCE_NAMESPACE
  13001. class ValueTree::SetPropertyAction : public UndoableAction
  13002. {
  13003. public:
  13004. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  13005. const var& newValue_, const var& oldValue_,
  13006. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  13007. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  13008. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  13009. {
  13010. }
  13011. ~SetPropertyAction() {}
  13012. bool perform()
  13013. {
  13014. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  13015. if (isDeletingProperty)
  13016. target->removeProperty (name, 0);
  13017. else
  13018. target->setProperty (name, newValue, 0);
  13019. return true;
  13020. }
  13021. bool undo()
  13022. {
  13023. if (isAddingNewProperty)
  13024. target->removeProperty (name, 0);
  13025. else
  13026. target->setProperty (name, oldValue, 0);
  13027. return true;
  13028. }
  13029. int getSizeInUnits()
  13030. {
  13031. return (int) sizeof (*this); //xxx should be more accurate
  13032. }
  13033. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13034. {
  13035. if (! (isAddingNewProperty || isDeletingProperty))
  13036. {
  13037. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  13038. if (next != 0 && next->target == target && next->name == name
  13039. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  13040. {
  13041. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  13042. }
  13043. }
  13044. return 0;
  13045. }
  13046. private:
  13047. const SharedObjectPtr target;
  13048. const Identifier name;
  13049. const var newValue;
  13050. var oldValue;
  13051. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  13052. SetPropertyAction (const SetPropertyAction&);
  13053. SetPropertyAction& operator= (const SetPropertyAction&);
  13054. };
  13055. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  13056. {
  13057. public:
  13058. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  13059. const SharedObjectPtr& newChild_)
  13060. : target (target_),
  13061. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  13062. childIndex (childIndex_),
  13063. isDeleting (newChild_ == 0)
  13064. {
  13065. jassert (child != 0);
  13066. }
  13067. ~AddOrRemoveChildAction() {}
  13068. bool perform()
  13069. {
  13070. if (isDeleting)
  13071. target->removeChild (childIndex, 0);
  13072. else
  13073. target->addChild (child, childIndex, 0);
  13074. return true;
  13075. }
  13076. bool undo()
  13077. {
  13078. if (isDeleting)
  13079. {
  13080. target->addChild (child, childIndex, 0);
  13081. }
  13082. else
  13083. {
  13084. // If you hit this, it seems that your object's state is getting confused - probably
  13085. // because you've interleaved some undoable and non-undoable operations?
  13086. jassert (childIndex < target->children.size());
  13087. target->removeChild (childIndex, 0);
  13088. }
  13089. return true;
  13090. }
  13091. int getSizeInUnits()
  13092. {
  13093. return (int) sizeof (*this); //xxx should be more accurate
  13094. }
  13095. private:
  13096. const SharedObjectPtr target, child;
  13097. const int childIndex;
  13098. const bool isDeleting;
  13099. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  13100. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  13101. };
  13102. class ValueTree::MoveChildAction : public UndoableAction
  13103. {
  13104. public:
  13105. MoveChildAction (const SharedObjectPtr& parent_,
  13106. const int startIndex_, const int endIndex_)
  13107. : parent (parent_),
  13108. startIndex (startIndex_),
  13109. endIndex (endIndex_)
  13110. {
  13111. }
  13112. ~MoveChildAction() {}
  13113. bool perform()
  13114. {
  13115. parent->moveChild (startIndex, endIndex, 0);
  13116. return true;
  13117. }
  13118. bool undo()
  13119. {
  13120. parent->moveChild (endIndex, startIndex, 0);
  13121. return true;
  13122. }
  13123. int getSizeInUnits()
  13124. {
  13125. return (int) sizeof (*this); //xxx should be more accurate
  13126. }
  13127. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13128. {
  13129. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  13130. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  13131. return new MoveChildAction (parent, startIndex, next->endIndex);
  13132. return 0;
  13133. }
  13134. private:
  13135. const SharedObjectPtr parent;
  13136. const int startIndex, endIndex;
  13137. MoveChildAction (const MoveChildAction&);
  13138. MoveChildAction& operator= (const MoveChildAction&);
  13139. };
  13140. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  13141. : type (type_), parent (0)
  13142. {
  13143. }
  13144. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  13145. : type (other.type), properties (other.properties), parent (0)
  13146. {
  13147. for (int i = 0; i < other.children.size(); ++i)
  13148. {
  13149. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  13150. child->parent = this;
  13151. children.add (child);
  13152. }
  13153. }
  13154. ValueTree::SharedObject::~SharedObject()
  13155. {
  13156. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  13157. for (int i = children.size(); --i >= 0;)
  13158. {
  13159. const SharedObjectPtr c (children.getUnchecked(i));
  13160. c->parent = 0;
  13161. children.remove (i);
  13162. c->sendParentChangeMessage();
  13163. }
  13164. }
  13165. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  13166. {
  13167. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13168. {
  13169. ValueTree* const v = valueTreesWithListeners[i];
  13170. if (v != 0)
  13171. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  13172. }
  13173. }
  13174. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  13175. {
  13176. ValueTree tree (this);
  13177. ValueTree::SharedObject* t = this;
  13178. while (t != 0)
  13179. {
  13180. t->sendPropertyChangeMessage (tree, property);
  13181. t = t->parent;
  13182. }
  13183. }
  13184. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  13185. {
  13186. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13187. {
  13188. ValueTree* const v = valueTreesWithListeners[i];
  13189. if (v != 0)
  13190. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  13191. }
  13192. }
  13193. void ValueTree::SharedObject::sendChildChangeMessage()
  13194. {
  13195. ValueTree tree (this);
  13196. ValueTree::SharedObject* t = this;
  13197. while (t != 0)
  13198. {
  13199. t->sendChildChangeMessage (tree);
  13200. t = t->parent;
  13201. }
  13202. }
  13203. void ValueTree::SharedObject::sendParentChangeMessage()
  13204. {
  13205. ValueTree tree (this);
  13206. int i;
  13207. for (i = children.size(); --i >= 0;)
  13208. {
  13209. SharedObject* const t = children[i];
  13210. if (t != 0)
  13211. t->sendParentChangeMessage();
  13212. }
  13213. for (i = valueTreesWithListeners.size(); --i >= 0;)
  13214. {
  13215. ValueTree* const v = valueTreesWithListeners[i];
  13216. if (v != 0)
  13217. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  13218. }
  13219. }
  13220. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  13221. {
  13222. return properties [name];
  13223. }
  13224. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  13225. {
  13226. return properties.getWithDefault (name, defaultReturnValue);
  13227. }
  13228. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  13229. {
  13230. if (undoManager == 0)
  13231. {
  13232. if (properties.set (name, newValue))
  13233. sendPropertyChangeMessage (name);
  13234. }
  13235. else
  13236. {
  13237. var* const existingValue = properties.getItem (name);
  13238. if (existingValue != 0)
  13239. {
  13240. if (*existingValue != newValue)
  13241. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  13242. }
  13243. else
  13244. {
  13245. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  13246. }
  13247. }
  13248. }
  13249. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  13250. {
  13251. return properties.contains (name);
  13252. }
  13253. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  13254. {
  13255. if (undoManager == 0)
  13256. {
  13257. if (properties.remove (name))
  13258. sendPropertyChangeMessage (name);
  13259. }
  13260. else
  13261. {
  13262. if (properties.contains (name))
  13263. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  13264. }
  13265. }
  13266. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  13267. {
  13268. if (undoManager == 0)
  13269. {
  13270. while (properties.size() > 0)
  13271. {
  13272. const Identifier name (properties.getName (properties.size() - 1));
  13273. properties.remove (name);
  13274. sendPropertyChangeMessage (name);
  13275. }
  13276. }
  13277. else
  13278. {
  13279. for (int i = properties.size(); --i >= 0;)
  13280. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  13281. }
  13282. }
  13283. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  13284. {
  13285. for (int i = 0; i < children.size(); ++i)
  13286. if (children.getUnchecked(i)->type == typeToMatch)
  13287. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13288. return ValueTree::invalid;
  13289. }
  13290. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  13291. {
  13292. for (int i = 0; i < children.size(); ++i)
  13293. if (children.getUnchecked(i)->type == typeToMatch)
  13294. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13295. SharedObject* const newObject = new SharedObject (typeToMatch);
  13296. addChild (newObject, -1, undoManager);
  13297. return ValueTree (newObject);
  13298. }
  13299. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  13300. {
  13301. for (int i = 0; i < children.size(); ++i)
  13302. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  13303. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13304. return ValueTree::invalid;
  13305. }
  13306. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  13307. {
  13308. const SharedObject* p = parent;
  13309. while (p != 0)
  13310. {
  13311. if (p == possibleParent)
  13312. return true;
  13313. p = p->parent;
  13314. }
  13315. return false;
  13316. }
  13317. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  13318. {
  13319. return children.indexOf (child.object);
  13320. }
  13321. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  13322. {
  13323. if (child != 0 && child->parent != this)
  13324. {
  13325. if (child != this && ! isAChildOf (child))
  13326. {
  13327. // You should always make sure that a child is removed from its previous parent before
  13328. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  13329. // undomanager should be used when removing it from its current parent..
  13330. jassert (child->parent == 0);
  13331. if (child->parent != 0)
  13332. {
  13333. jassert (child->parent->children.indexOf (child) >= 0);
  13334. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  13335. }
  13336. if (undoManager == 0)
  13337. {
  13338. children.insert (index, child);
  13339. child->parent = this;
  13340. sendChildChangeMessage();
  13341. child->sendParentChangeMessage();
  13342. }
  13343. else
  13344. {
  13345. if (index < 0)
  13346. index = children.size();
  13347. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  13348. }
  13349. }
  13350. else
  13351. {
  13352. // You're attempting to create a recursive loop! A node
  13353. // can't be a child of one of its own children!
  13354. jassertfalse;
  13355. }
  13356. }
  13357. }
  13358. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  13359. {
  13360. const SharedObjectPtr child (children [childIndex]);
  13361. if (child != 0)
  13362. {
  13363. if (undoManager == 0)
  13364. {
  13365. children.remove (childIndex);
  13366. child->parent = 0;
  13367. sendChildChangeMessage();
  13368. child->sendParentChangeMessage();
  13369. }
  13370. else
  13371. {
  13372. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  13373. }
  13374. }
  13375. }
  13376. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  13377. {
  13378. while (children.size() > 0)
  13379. removeChild (children.size() - 1, undoManager);
  13380. }
  13381. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13382. {
  13383. // The source index must be a valid index!
  13384. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  13385. if (currentIndex != newIndex
  13386. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  13387. {
  13388. if (undoManager == 0)
  13389. {
  13390. children.move (currentIndex, newIndex);
  13391. sendChildChangeMessage();
  13392. }
  13393. else
  13394. {
  13395. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  13396. newIndex = children.size() - 1;
  13397. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  13398. }
  13399. }
  13400. }
  13401. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  13402. {
  13403. if (type != other.type
  13404. || properties.size() != other.properties.size()
  13405. || children.size() != other.children.size()
  13406. || properties != other.properties)
  13407. return false;
  13408. for (int i = 0; i < children.size(); ++i)
  13409. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  13410. return false;
  13411. return true;
  13412. }
  13413. ValueTree::ValueTree() throw()
  13414. : object (0)
  13415. {
  13416. }
  13417. const ValueTree ValueTree::invalid;
  13418. ValueTree::ValueTree (const Identifier& type_)
  13419. : object (new ValueTree::SharedObject (type_))
  13420. {
  13421. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  13422. }
  13423. ValueTree::ValueTree (SharedObject* const object_)
  13424. : object (object_)
  13425. {
  13426. }
  13427. ValueTree::ValueTree (const ValueTree& other)
  13428. : object (other.object)
  13429. {
  13430. }
  13431. ValueTree& ValueTree::operator= (const ValueTree& other)
  13432. {
  13433. if (listeners.size() > 0)
  13434. {
  13435. if (object != 0)
  13436. object->valueTreesWithListeners.removeValue (this);
  13437. if (other.object != 0)
  13438. other.object->valueTreesWithListeners.add (this);
  13439. }
  13440. object = other.object;
  13441. return *this;
  13442. }
  13443. ValueTree::~ValueTree()
  13444. {
  13445. if (listeners.size() > 0 && object != 0)
  13446. object->valueTreesWithListeners.removeValue (this);
  13447. }
  13448. bool ValueTree::operator== (const ValueTree& other) const throw()
  13449. {
  13450. return object == other.object;
  13451. }
  13452. bool ValueTree::operator!= (const ValueTree& other) const throw()
  13453. {
  13454. return object != other.object;
  13455. }
  13456. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  13457. {
  13458. return object == other.object
  13459. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  13460. }
  13461. ValueTree ValueTree::createCopy() const
  13462. {
  13463. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  13464. }
  13465. bool ValueTree::hasType (const Identifier& typeName) const
  13466. {
  13467. return object != 0 && object->type == typeName;
  13468. }
  13469. const Identifier ValueTree::getType() const
  13470. {
  13471. return object != 0 ? object->type : Identifier();
  13472. }
  13473. ValueTree ValueTree::getParent() const
  13474. {
  13475. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  13476. }
  13477. ValueTree ValueTree::getSibling (const int delta) const
  13478. {
  13479. if (object == 0 || object->parent == 0)
  13480. return invalid;
  13481. const int index = object->parent->indexOf (*this) + delta;
  13482. return ValueTree (static_cast <SharedObject*> (object->parent->children [index]));
  13483. }
  13484. const var& ValueTree::operator[] (const Identifier& name) const
  13485. {
  13486. return object == 0 ? var::null : object->getProperty (name);
  13487. }
  13488. const var& ValueTree::getProperty (const Identifier& name) const
  13489. {
  13490. return object == 0 ? var::null : object->getProperty (name);
  13491. }
  13492. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  13493. {
  13494. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  13495. }
  13496. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  13497. {
  13498. jassert (name.toString().isNotEmpty());
  13499. if (object != 0 && name.toString().isNotEmpty())
  13500. object->setProperty (name, newValue, undoManager);
  13501. }
  13502. bool ValueTree::hasProperty (const Identifier& name) const
  13503. {
  13504. return object != 0 && object->hasProperty (name);
  13505. }
  13506. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  13507. {
  13508. if (object != 0)
  13509. object->removeProperty (name, undoManager);
  13510. }
  13511. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  13512. {
  13513. if (object != 0)
  13514. object->removeAllProperties (undoManager);
  13515. }
  13516. int ValueTree::getNumProperties() const
  13517. {
  13518. return object == 0 ? 0 : object->properties.size();
  13519. }
  13520. const Identifier ValueTree::getPropertyName (const int index) const
  13521. {
  13522. return object == 0 ? Identifier()
  13523. : object->properties.getName (index);
  13524. }
  13525. class ValueTreePropertyValueSource : public Value::ValueSource,
  13526. public ValueTree::Listener
  13527. {
  13528. public:
  13529. ValueTreePropertyValueSource (const ValueTree& tree_,
  13530. const Identifier& property_,
  13531. UndoManager* const undoManager_)
  13532. : tree (tree_),
  13533. property (property_),
  13534. undoManager (undoManager_)
  13535. {
  13536. tree.addListener (this);
  13537. }
  13538. ~ValueTreePropertyValueSource()
  13539. {
  13540. tree.removeListener (this);
  13541. }
  13542. const var getValue() const
  13543. {
  13544. return tree [property];
  13545. }
  13546. void setValue (const var& newValue)
  13547. {
  13548. tree.setProperty (property, newValue, undoManager);
  13549. }
  13550. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  13551. {
  13552. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  13553. sendChangeMessage (false);
  13554. }
  13555. void valueTreeChildrenChanged (ValueTree&) {}
  13556. void valueTreeParentChanged (ValueTree&) {}
  13557. private:
  13558. ValueTree tree;
  13559. const Identifier property;
  13560. UndoManager* const undoManager;
  13561. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  13562. };
  13563. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  13564. {
  13565. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  13566. }
  13567. int ValueTree::getNumChildren() const
  13568. {
  13569. return object == 0 ? 0 : object->children.size();
  13570. }
  13571. ValueTree ValueTree::getChild (int index) const
  13572. {
  13573. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  13574. }
  13575. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  13576. {
  13577. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  13578. }
  13579. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  13580. {
  13581. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  13582. }
  13583. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  13584. {
  13585. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  13586. }
  13587. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  13588. {
  13589. return object != 0 && object->isAChildOf (possibleParent.object);
  13590. }
  13591. int ValueTree::indexOf (const ValueTree& child) const
  13592. {
  13593. return object != 0 ? object->indexOf (child) : -1;
  13594. }
  13595. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  13596. {
  13597. if (object != 0)
  13598. object->addChild (child.object, index, undoManager);
  13599. }
  13600. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  13601. {
  13602. if (object != 0)
  13603. object->removeChild (childIndex, undoManager);
  13604. }
  13605. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  13606. {
  13607. if (object != 0)
  13608. object->removeChild (object->children.indexOf (child.object), undoManager);
  13609. }
  13610. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  13611. {
  13612. if (object != 0)
  13613. object->removeAllChildren (undoManager);
  13614. }
  13615. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13616. {
  13617. if (object != 0)
  13618. object->moveChild (currentIndex, newIndex, undoManager);
  13619. }
  13620. void ValueTree::addListener (Listener* listener)
  13621. {
  13622. if (listener != 0)
  13623. {
  13624. if (listeners.size() == 0 && object != 0)
  13625. object->valueTreesWithListeners.add (this);
  13626. listeners.add (listener);
  13627. }
  13628. }
  13629. void ValueTree::removeListener (Listener* listener)
  13630. {
  13631. listeners.remove (listener);
  13632. if (listeners.size() == 0 && object != 0)
  13633. object->valueTreesWithListeners.removeValue (this);
  13634. }
  13635. XmlElement* ValueTree::SharedObject::createXml() const
  13636. {
  13637. XmlElement* xml = new XmlElement (type.toString());
  13638. int i;
  13639. for (i = 0; i < properties.size(); ++i)
  13640. {
  13641. Identifier name (properties.getName(i));
  13642. const var& v = properties [name];
  13643. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  13644. xml->setAttribute (name.toString(), v.toString());
  13645. }
  13646. for (i = 0; i < children.size(); ++i)
  13647. xml->addChildElement (children.getUnchecked(i)->createXml());
  13648. return xml;
  13649. }
  13650. XmlElement* ValueTree::createXml() const
  13651. {
  13652. return object != 0 ? object->createXml() : 0;
  13653. }
  13654. ValueTree ValueTree::fromXml (const XmlElement& xml)
  13655. {
  13656. ValueTree v (xml.getTagName());
  13657. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  13658. for (int i = 0; i < numAtts; ++i)
  13659. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  13660. forEachXmlChildElement (xml, e)
  13661. {
  13662. v.addChild (fromXml (*e), -1, 0);
  13663. }
  13664. return v;
  13665. }
  13666. void ValueTree::writeToStream (OutputStream& output)
  13667. {
  13668. output.writeString (getType().toString());
  13669. const int numProps = getNumProperties();
  13670. output.writeCompressedInt (numProps);
  13671. int i;
  13672. for (i = 0; i < numProps; ++i)
  13673. {
  13674. const Identifier name (getPropertyName(i));
  13675. output.writeString (name.toString());
  13676. getProperty(name).writeToStream (output);
  13677. }
  13678. const int numChildren = getNumChildren();
  13679. output.writeCompressedInt (numChildren);
  13680. for (i = 0; i < numChildren; ++i)
  13681. getChild (i).writeToStream (output);
  13682. }
  13683. ValueTree ValueTree::readFromStream (InputStream& input)
  13684. {
  13685. const String type (input.readString());
  13686. if (type.isEmpty())
  13687. return ValueTree::invalid;
  13688. ValueTree v (type);
  13689. const int numProps = input.readCompressedInt();
  13690. if (numProps < 0)
  13691. {
  13692. jassertfalse; // trying to read corrupted data!
  13693. return v;
  13694. }
  13695. int i;
  13696. for (i = 0; i < numProps; ++i)
  13697. {
  13698. const String name (input.readString());
  13699. jassert (name.isNotEmpty());
  13700. const var value (var::readFromStream (input));
  13701. v.setProperty (name, value, 0);
  13702. }
  13703. const int numChildren = input.readCompressedInt();
  13704. for (i = 0; i < numChildren; ++i)
  13705. v.addChild (readFromStream (input), -1, 0);
  13706. return v;
  13707. }
  13708. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  13709. {
  13710. MemoryInputStream in (data, numBytes, false);
  13711. return readFromStream (in);
  13712. }
  13713. END_JUCE_NAMESPACE
  13714. /*** End of inlined file: juce_ValueTree.cpp ***/
  13715. /*** Start of inlined file: juce_Value.cpp ***/
  13716. BEGIN_JUCE_NAMESPACE
  13717. Value::ValueSource::ValueSource()
  13718. {
  13719. }
  13720. Value::ValueSource::~ValueSource()
  13721. {
  13722. }
  13723. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  13724. {
  13725. if (synchronous)
  13726. {
  13727. for (int i = valuesWithListeners.size(); --i >= 0;)
  13728. {
  13729. Value* const v = valuesWithListeners[i];
  13730. if (v != 0)
  13731. v->callListeners();
  13732. }
  13733. }
  13734. else
  13735. {
  13736. triggerAsyncUpdate();
  13737. }
  13738. }
  13739. void Value::ValueSource::handleAsyncUpdate()
  13740. {
  13741. sendChangeMessage (true);
  13742. }
  13743. class SimpleValueSource : public Value::ValueSource
  13744. {
  13745. public:
  13746. SimpleValueSource()
  13747. {
  13748. }
  13749. SimpleValueSource (const var& initialValue)
  13750. : value (initialValue)
  13751. {
  13752. }
  13753. ~SimpleValueSource()
  13754. {
  13755. }
  13756. const var getValue() const
  13757. {
  13758. return value;
  13759. }
  13760. void setValue (const var& newValue)
  13761. {
  13762. if (newValue != value)
  13763. {
  13764. value = newValue;
  13765. sendChangeMessage (false);
  13766. }
  13767. }
  13768. private:
  13769. var value;
  13770. SimpleValueSource (const SimpleValueSource&);
  13771. SimpleValueSource& operator= (const SimpleValueSource&);
  13772. };
  13773. Value::Value()
  13774. : value (new SimpleValueSource())
  13775. {
  13776. }
  13777. Value::Value (ValueSource* const value_)
  13778. : value (value_)
  13779. {
  13780. jassert (value_ != 0);
  13781. }
  13782. Value::Value (const var& initialValue)
  13783. : value (new SimpleValueSource (initialValue))
  13784. {
  13785. }
  13786. Value::Value (const Value& other)
  13787. : value (other.value)
  13788. {
  13789. }
  13790. Value& Value::operator= (const Value& other)
  13791. {
  13792. value = other.value;
  13793. return *this;
  13794. }
  13795. Value::~Value()
  13796. {
  13797. if (listeners.size() > 0)
  13798. value->valuesWithListeners.removeValue (this);
  13799. }
  13800. const var Value::getValue() const
  13801. {
  13802. return value->getValue();
  13803. }
  13804. Value::operator const var() const
  13805. {
  13806. return getValue();
  13807. }
  13808. void Value::setValue (const var& newValue)
  13809. {
  13810. value->setValue (newValue);
  13811. }
  13812. const String Value::toString() const
  13813. {
  13814. return value->getValue().toString();
  13815. }
  13816. Value& Value::operator= (const var& newValue)
  13817. {
  13818. value->setValue (newValue);
  13819. return *this;
  13820. }
  13821. void Value::referTo (const Value& valueToReferTo)
  13822. {
  13823. if (valueToReferTo.value != value)
  13824. {
  13825. if (listeners.size() > 0)
  13826. {
  13827. value->valuesWithListeners.removeValue (this);
  13828. valueToReferTo.value->valuesWithListeners.add (this);
  13829. }
  13830. value = valueToReferTo.value;
  13831. callListeners();
  13832. }
  13833. }
  13834. bool Value::refersToSameSourceAs (const Value& other) const
  13835. {
  13836. return value == other.value;
  13837. }
  13838. bool Value::operator== (const Value& other) const
  13839. {
  13840. return value == other.value || value->getValue() == other.getValue();
  13841. }
  13842. bool Value::operator!= (const Value& other) const
  13843. {
  13844. return value != other.value && value->getValue() != other.getValue();
  13845. }
  13846. void Value::addListener (Listener* const listener)
  13847. {
  13848. if (listener != 0)
  13849. {
  13850. if (listeners.size() == 0)
  13851. value->valuesWithListeners.add (this);
  13852. listeners.add (listener);
  13853. }
  13854. }
  13855. void Value::removeListener (Listener* const listener)
  13856. {
  13857. listeners.remove (listener);
  13858. if (listeners.size() == 0)
  13859. value->valuesWithListeners.removeValue (this);
  13860. }
  13861. void Value::callListeners()
  13862. {
  13863. Value v (*this); // (create a copy in case this gets deleted by a callback)
  13864. listeners.call (&Listener::valueChanged, v);
  13865. }
  13866. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  13867. {
  13868. return stream << value.toString();
  13869. }
  13870. END_JUCE_NAMESPACE
  13871. /*** End of inlined file: juce_Value.cpp ***/
  13872. /*** Start of inlined file: juce_Application.cpp ***/
  13873. BEGIN_JUCE_NAMESPACE
  13874. #if JUCE_MAC
  13875. extern void juce_initialiseMacMainMenu();
  13876. #endif
  13877. JUCEApplication::JUCEApplication()
  13878. : appReturnValue (0),
  13879. stillInitialising (true)
  13880. {
  13881. jassert (isStandaloneApp && appInstance == 0);
  13882. appInstance = this;
  13883. }
  13884. JUCEApplication::~JUCEApplication()
  13885. {
  13886. if (appLock != 0)
  13887. {
  13888. appLock->exit();
  13889. appLock = 0;
  13890. }
  13891. jassert (appInstance == this);
  13892. appInstance = 0;
  13893. }
  13894. bool JUCEApplication::isStandaloneApp = false;
  13895. JUCEApplication* JUCEApplication::appInstance = 0;
  13896. bool JUCEApplication::moreThanOneInstanceAllowed()
  13897. {
  13898. return true;
  13899. }
  13900. void JUCEApplication::anotherInstanceStarted (const String&)
  13901. {
  13902. }
  13903. void JUCEApplication::systemRequestedQuit()
  13904. {
  13905. quit();
  13906. }
  13907. void JUCEApplication::quit()
  13908. {
  13909. MessageManager::getInstance()->stopDispatchLoop();
  13910. }
  13911. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  13912. {
  13913. appReturnValue = newReturnValue;
  13914. }
  13915. void JUCEApplication::actionListenerCallback (const String& message)
  13916. {
  13917. if (message.startsWith (getApplicationName() + "/"))
  13918. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  13919. }
  13920. void JUCEApplication::unhandledException (const std::exception*,
  13921. const String&,
  13922. const int)
  13923. {
  13924. jassertfalse;
  13925. }
  13926. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  13927. const char* const sourceFile,
  13928. const int lineNumber)
  13929. {
  13930. if (appInstance != 0)
  13931. appInstance->unhandledException (e, sourceFile, lineNumber);
  13932. }
  13933. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  13934. {
  13935. return 0;
  13936. }
  13937. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  13938. {
  13939. commands.add (StandardApplicationCommandIDs::quit);
  13940. }
  13941. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  13942. {
  13943. if (commandID == StandardApplicationCommandIDs::quit)
  13944. {
  13945. result.setInfo (TRANS("Quit"),
  13946. TRANS("Quits the application"),
  13947. "Application",
  13948. 0);
  13949. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  13950. }
  13951. }
  13952. bool JUCEApplication::perform (const InvocationInfo& info)
  13953. {
  13954. if (info.commandID == StandardApplicationCommandIDs::quit)
  13955. {
  13956. systemRequestedQuit();
  13957. return true;
  13958. }
  13959. return false;
  13960. }
  13961. bool JUCEApplication::initialiseApp (const String& commandLine)
  13962. {
  13963. commandLineParameters = commandLine.trim();
  13964. #if ! JUCE_IOS
  13965. jassert (appLock == 0); // initialiseApp must only be called once!
  13966. if (! moreThanOneInstanceAllowed())
  13967. {
  13968. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  13969. if (! appLock->enter(0))
  13970. {
  13971. appLock = 0;
  13972. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  13973. DBG ("Another instance is running - quitting...");
  13974. return false;
  13975. }
  13976. }
  13977. #endif
  13978. // let the app do its setting-up..
  13979. initialise (commandLineParameters);
  13980. #if JUCE_MAC
  13981. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  13982. #endif
  13983. // register for broadcast new app messages
  13984. MessageManager::getInstance()->registerBroadcastListener (this);
  13985. stillInitialising = false;
  13986. return true;
  13987. }
  13988. int JUCEApplication::shutdownApp()
  13989. {
  13990. jassert (appInstance == this);
  13991. MessageManager::getInstance()->deregisterBroadcastListener (this);
  13992. JUCE_TRY
  13993. {
  13994. // give the app a chance to clean up..
  13995. shutdown();
  13996. }
  13997. JUCE_CATCH_EXCEPTION
  13998. return getApplicationReturnValue();
  13999. }
  14000. int JUCEApplication::main (const String& commandLine, JUCEApplication* const app)
  14001. {
  14002. const ScopedPointer<JUCEApplication> appDeleter (app);
  14003. if (! app->initialiseApp (commandLine))
  14004. return 0;
  14005. JUCE_TRY
  14006. {
  14007. // loop until a quit message is received..
  14008. MessageManager::getInstance()->runDispatchLoop();
  14009. }
  14010. JUCE_CATCH_EXCEPTION
  14011. return app->shutdownApp();
  14012. }
  14013. #if JUCE_IOS
  14014. extern int juce_iOSMain (int argc, const char* argv[]);
  14015. #endif
  14016. #if ! JUCE_WINDOWS
  14017. extern const char* juce_Argv0;
  14018. #endif
  14019. int JUCEApplication::main (int argc, const char* argv[], JUCEApplication* const newApp)
  14020. {
  14021. JUCE_AUTORELEASEPOOL
  14022. #if ! JUCE_WINDOWS
  14023. juce_Argv0 = argv[0];
  14024. #endif
  14025. #if JUCE_IOS
  14026. const ScopedPointer<JUCEApplication> appDeleter (newApp);
  14027. return juce_iOSMain (argc, argv);
  14028. #else
  14029. String cmd;
  14030. for (int i = 1; i < argc; ++i)
  14031. cmd << argv[i] << ' ';
  14032. return JUCEApplication::main (cmd, newApp);
  14033. #endif
  14034. }
  14035. END_JUCE_NAMESPACE
  14036. /*** End of inlined file: juce_Application.cpp ***/
  14037. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14038. BEGIN_JUCE_NAMESPACE
  14039. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  14040. : commandID (commandID_),
  14041. flags (0)
  14042. {
  14043. }
  14044. void ApplicationCommandInfo::setInfo (const String& shortName_,
  14045. const String& description_,
  14046. const String& categoryName_,
  14047. const int flags_) throw()
  14048. {
  14049. shortName = shortName_;
  14050. description = description_;
  14051. categoryName = categoryName_;
  14052. flags = flags_;
  14053. }
  14054. void ApplicationCommandInfo::setActive (const bool b) throw()
  14055. {
  14056. if (b)
  14057. flags &= ~isDisabled;
  14058. else
  14059. flags |= isDisabled;
  14060. }
  14061. void ApplicationCommandInfo::setTicked (const bool b) throw()
  14062. {
  14063. if (b)
  14064. flags |= isTicked;
  14065. else
  14066. flags &= ~isTicked;
  14067. }
  14068. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  14069. {
  14070. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  14071. }
  14072. END_JUCE_NAMESPACE
  14073. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14074. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  14075. BEGIN_JUCE_NAMESPACE
  14076. ApplicationCommandManager::ApplicationCommandManager()
  14077. : firstTarget (0)
  14078. {
  14079. keyMappings = new KeyPressMappingSet (this);
  14080. Desktop::getInstance().addFocusChangeListener (this);
  14081. }
  14082. ApplicationCommandManager::~ApplicationCommandManager()
  14083. {
  14084. Desktop::getInstance().removeFocusChangeListener (this);
  14085. keyMappings = 0;
  14086. }
  14087. void ApplicationCommandManager::clearCommands()
  14088. {
  14089. commands.clear();
  14090. keyMappings->clearAllKeyPresses();
  14091. triggerAsyncUpdate();
  14092. }
  14093. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  14094. {
  14095. // zero isn't a valid command ID!
  14096. jassert (newCommand.commandID != 0);
  14097. // the name isn't optional!
  14098. jassert (newCommand.shortName.isNotEmpty());
  14099. if (getCommandForID (newCommand.commandID) == 0)
  14100. {
  14101. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  14102. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  14103. commands.add (newInfo);
  14104. keyMappings->resetToDefaultMapping (newCommand.commandID);
  14105. triggerAsyncUpdate();
  14106. }
  14107. else
  14108. {
  14109. // trying to re-register the same command with different parameters?
  14110. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  14111. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  14112. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  14113. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  14114. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  14115. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  14116. }
  14117. }
  14118. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  14119. {
  14120. if (target != 0)
  14121. {
  14122. Array <CommandID> commandIDs;
  14123. target->getAllCommands (commandIDs);
  14124. for (int i = 0; i < commandIDs.size(); ++i)
  14125. {
  14126. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  14127. target->getCommandInfo (info.commandID, info);
  14128. registerCommand (info);
  14129. }
  14130. }
  14131. }
  14132. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  14133. {
  14134. for (int i = commands.size(); --i >= 0;)
  14135. {
  14136. if (commands.getUnchecked (i)->commandID == commandID)
  14137. {
  14138. commands.remove (i);
  14139. triggerAsyncUpdate();
  14140. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  14141. for (int j = keys.size(); --j >= 0;)
  14142. keyMappings->removeKeyPress (keys.getReference (j));
  14143. }
  14144. }
  14145. }
  14146. void ApplicationCommandManager::commandStatusChanged()
  14147. {
  14148. triggerAsyncUpdate();
  14149. }
  14150. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  14151. {
  14152. for (int i = commands.size(); --i >= 0;)
  14153. if (commands.getUnchecked(i)->commandID == commandID)
  14154. return commands.getUnchecked(i);
  14155. return 0;
  14156. }
  14157. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  14158. {
  14159. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14160. return (ci != 0) ? ci->shortName : String::empty;
  14161. }
  14162. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  14163. {
  14164. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14165. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  14166. : String::empty;
  14167. }
  14168. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  14169. {
  14170. StringArray s;
  14171. for (int i = 0; i < commands.size(); ++i)
  14172. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  14173. return s;
  14174. }
  14175. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  14176. {
  14177. Array <CommandID> results;
  14178. for (int i = 0; i < commands.size(); ++i)
  14179. if (commands.getUnchecked(i)->categoryName == categoryName)
  14180. results.add (commands.getUnchecked(i)->commandID);
  14181. return results;
  14182. }
  14183. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14184. {
  14185. ApplicationCommandTarget::InvocationInfo info (commandID);
  14186. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14187. return invoke (info, asynchronously);
  14188. }
  14189. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  14190. {
  14191. // This call isn't thread-safe for use from a non-UI thread without locking the message
  14192. // manager first..
  14193. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  14194. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  14195. if (target == 0)
  14196. return false;
  14197. ApplicationCommandInfo commandInfo (0);
  14198. target->getCommandInfo (info_.commandID, commandInfo);
  14199. ApplicationCommandTarget::InvocationInfo info (info_);
  14200. info.commandFlags = commandInfo.flags;
  14201. sendListenerInvokeCallback (info);
  14202. const bool ok = target->invoke (info, asynchronously);
  14203. commandStatusChanged();
  14204. return ok;
  14205. }
  14206. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  14207. {
  14208. return firstTarget != 0 ? firstTarget
  14209. : findDefaultComponentTarget();
  14210. }
  14211. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  14212. {
  14213. firstTarget = newTarget;
  14214. }
  14215. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  14216. ApplicationCommandInfo& upToDateInfo)
  14217. {
  14218. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  14219. if (target == 0)
  14220. target = JUCEApplication::getInstance();
  14221. if (target != 0)
  14222. target = target->getTargetForCommand (commandID);
  14223. if (target != 0)
  14224. target->getCommandInfo (commandID, upToDateInfo);
  14225. return target;
  14226. }
  14227. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  14228. {
  14229. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  14230. if (target == 0 && c != 0)
  14231. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14232. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14233. return target;
  14234. }
  14235. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  14236. {
  14237. Component* c = Component::getCurrentlyFocusedComponent();
  14238. if (c == 0)
  14239. {
  14240. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  14241. if (activeWindow != 0)
  14242. {
  14243. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  14244. if (c == 0)
  14245. c = activeWindow;
  14246. }
  14247. }
  14248. if (c == 0 && Process::isForegroundProcess())
  14249. {
  14250. // getting a bit desperate now - try all desktop comps..
  14251. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  14252. {
  14253. ApplicationCommandTarget* const target
  14254. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  14255. ->getPeer()->getLastFocusedSubcomponent());
  14256. if (target != 0)
  14257. return target;
  14258. }
  14259. }
  14260. if (c != 0)
  14261. {
  14262. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  14263. // if we're focused on a ResizableWindow, chances are that it's the content
  14264. // component that really should get the event. And if not, the event will
  14265. // still be passed up to the top level window anyway, so let's send it to the
  14266. // content comp.
  14267. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  14268. c = resizableWindow->getContentComponent();
  14269. ApplicationCommandTarget* const target = findTargetForComponent (c);
  14270. if (target != 0)
  14271. return target;
  14272. }
  14273. return JUCEApplication::getInstance();
  14274. }
  14275. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  14276. {
  14277. listeners.add (listener);
  14278. }
  14279. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  14280. {
  14281. listeners.remove (listener);
  14282. }
  14283. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  14284. {
  14285. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  14286. }
  14287. void ApplicationCommandManager::handleAsyncUpdate()
  14288. {
  14289. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  14290. }
  14291. void ApplicationCommandManager::globalFocusChanged (Component*)
  14292. {
  14293. commandStatusChanged();
  14294. }
  14295. END_JUCE_NAMESPACE
  14296. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  14297. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14298. BEGIN_JUCE_NAMESPACE
  14299. ApplicationCommandTarget::ApplicationCommandTarget()
  14300. {
  14301. }
  14302. ApplicationCommandTarget::~ApplicationCommandTarget()
  14303. {
  14304. messageInvoker = 0;
  14305. }
  14306. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  14307. {
  14308. if (isCommandActive (info.commandID))
  14309. {
  14310. if (async)
  14311. {
  14312. if (messageInvoker == 0)
  14313. messageInvoker = new CommandTargetMessageInvoker (this);
  14314. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  14315. return true;
  14316. }
  14317. else
  14318. {
  14319. const bool success = perform (info);
  14320. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  14321. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  14322. // returns the command's info.
  14323. return success;
  14324. }
  14325. }
  14326. return false;
  14327. }
  14328. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  14329. {
  14330. Component* c = dynamic_cast <Component*> (this);
  14331. if (c != 0)
  14332. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14333. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14334. return 0;
  14335. }
  14336. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  14337. {
  14338. ApplicationCommandTarget* target = this;
  14339. int depth = 0;
  14340. while (target != 0)
  14341. {
  14342. Array <CommandID> commandIDs;
  14343. target->getAllCommands (commandIDs);
  14344. if (commandIDs.contains (commandID))
  14345. return target;
  14346. target = target->getNextCommandTarget();
  14347. ++depth;
  14348. jassert (depth < 100); // could be a recursive command chain??
  14349. jassert (target != this); // definitely a recursive command chain!
  14350. if (depth > 100 || target == this)
  14351. break;
  14352. }
  14353. if (target == 0)
  14354. {
  14355. target = JUCEApplication::getInstance();
  14356. if (target != 0)
  14357. {
  14358. Array <CommandID> commandIDs;
  14359. target->getAllCommands (commandIDs);
  14360. if (commandIDs.contains (commandID))
  14361. return target;
  14362. }
  14363. }
  14364. return 0;
  14365. }
  14366. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  14367. {
  14368. ApplicationCommandInfo info (commandID);
  14369. info.flags = ApplicationCommandInfo::isDisabled;
  14370. getCommandInfo (commandID, info);
  14371. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  14372. }
  14373. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  14374. {
  14375. ApplicationCommandTarget* target = this;
  14376. int depth = 0;
  14377. while (target != 0)
  14378. {
  14379. if (target->tryToInvoke (info, async))
  14380. return true;
  14381. target = target->getNextCommandTarget();
  14382. ++depth;
  14383. jassert (depth < 100); // could be a recursive command chain??
  14384. jassert (target != this); // definitely a recursive command chain!
  14385. if (depth > 100 || target == this)
  14386. break;
  14387. }
  14388. if (target == 0)
  14389. {
  14390. target = JUCEApplication::getInstance();
  14391. if (target != 0)
  14392. return target->tryToInvoke (info, async);
  14393. }
  14394. return false;
  14395. }
  14396. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14397. {
  14398. ApplicationCommandTarget::InvocationInfo info (commandID);
  14399. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14400. return invoke (info, asynchronously);
  14401. }
  14402. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  14403. : commandID (commandID_),
  14404. commandFlags (0),
  14405. invocationMethod (direct),
  14406. originatingComponent (0),
  14407. isKeyDown (false),
  14408. millisecsSinceKeyPressed (0)
  14409. {
  14410. }
  14411. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  14412. : owner (owner_)
  14413. {
  14414. }
  14415. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  14416. {
  14417. }
  14418. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  14419. {
  14420. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  14421. owner->tryToInvoke (*info, false);
  14422. }
  14423. END_JUCE_NAMESPACE
  14424. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14425. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  14426. BEGIN_JUCE_NAMESPACE
  14427. juce_ImplementSingleton (ApplicationProperties)
  14428. ApplicationProperties::ApplicationProperties() throw()
  14429. : msBeforeSaving (3000),
  14430. options (PropertiesFile::storeAsBinary),
  14431. commonSettingsAreReadOnly (0)
  14432. {
  14433. }
  14434. ApplicationProperties::~ApplicationProperties()
  14435. {
  14436. closeFiles();
  14437. clearSingletonInstance();
  14438. }
  14439. void ApplicationProperties::setStorageParameters (const String& applicationName,
  14440. const String& fileNameSuffix,
  14441. const String& folderName_,
  14442. const int millisecondsBeforeSaving,
  14443. const int propertiesFileOptions) throw()
  14444. {
  14445. appName = applicationName;
  14446. fileSuffix = fileNameSuffix;
  14447. folderName = folderName_;
  14448. msBeforeSaving = millisecondsBeforeSaving;
  14449. options = propertiesFileOptions;
  14450. }
  14451. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  14452. const bool testCommonSettings,
  14453. const bool showWarningDialogOnFailure)
  14454. {
  14455. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  14456. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  14457. if (! (userOk && commonOk))
  14458. {
  14459. if (showWarningDialogOnFailure)
  14460. {
  14461. String filenames;
  14462. if (userProps != 0 && ! userOk)
  14463. filenames << '\n' << userProps->getFile().getFullPathName();
  14464. if (commonProps != 0 && ! commonOk)
  14465. filenames << '\n' << commonProps->getFile().getFullPathName();
  14466. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14467. appName + TRANS(" - Unable to save settings"),
  14468. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  14469. + appName + TRANS(" needs to be able to write to the following files:\n")
  14470. + filenames
  14471. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  14472. }
  14473. return false;
  14474. }
  14475. return true;
  14476. }
  14477. void ApplicationProperties::openFiles() throw()
  14478. {
  14479. // You need to call setStorageParameters() before trying to get hold of the
  14480. // properties!
  14481. jassert (appName.isNotEmpty());
  14482. if (appName.isNotEmpty())
  14483. {
  14484. if (userProps == 0)
  14485. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14486. false, msBeforeSaving, options);
  14487. if (commonProps == 0)
  14488. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14489. true, msBeforeSaving, options);
  14490. userProps->setFallbackPropertySet (commonProps);
  14491. }
  14492. }
  14493. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  14494. {
  14495. if (userProps == 0)
  14496. openFiles();
  14497. return userProps;
  14498. }
  14499. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  14500. {
  14501. if (commonProps == 0)
  14502. openFiles();
  14503. if (returnUserPropsIfReadOnly)
  14504. {
  14505. if (commonSettingsAreReadOnly == 0)
  14506. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  14507. if (commonSettingsAreReadOnly > 0)
  14508. return userProps;
  14509. }
  14510. return commonProps;
  14511. }
  14512. bool ApplicationProperties::saveIfNeeded()
  14513. {
  14514. return (userProps == 0 || userProps->saveIfNeeded())
  14515. && (commonProps == 0 || commonProps->saveIfNeeded());
  14516. }
  14517. void ApplicationProperties::closeFiles()
  14518. {
  14519. userProps = 0;
  14520. commonProps = 0;
  14521. }
  14522. END_JUCE_NAMESPACE
  14523. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  14524. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  14525. BEGIN_JUCE_NAMESPACE
  14526. namespace PropertyFileConstants
  14527. {
  14528. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  14529. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  14530. static const char* const fileTag = "PROPERTIES";
  14531. static const char* const valueTag = "VALUE";
  14532. static const char* const nameAttribute = "name";
  14533. static const char* const valueAttribute = "val";
  14534. }
  14535. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  14536. const int options_, InterProcessLock* const processLock_)
  14537. : PropertySet (ignoreCaseOfKeyNames),
  14538. file (f),
  14539. timerInterval (millisecondsBeforeSaving),
  14540. options (options_),
  14541. loadedOk (false),
  14542. needsWriting (false),
  14543. processLock (processLock_)
  14544. {
  14545. // You need to correctly specify just one storage format for the file
  14546. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  14547. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  14548. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  14549. ProcessScopedLock pl (createProcessLock());
  14550. if (pl != 0 && ! pl->isLocked())
  14551. return; // locking failure..
  14552. ScopedPointer<InputStream> fileStream (f.createInputStream());
  14553. if (fileStream != 0)
  14554. {
  14555. int magicNumber = fileStream->readInt();
  14556. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  14557. {
  14558. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  14559. magicNumber = PropertyFileConstants::magicNumber;
  14560. }
  14561. if (magicNumber == PropertyFileConstants::magicNumber)
  14562. {
  14563. loadedOk = true;
  14564. BufferedInputStream in (fileStream.release(), 2048, true);
  14565. int numValues = in.readInt();
  14566. while (--numValues >= 0 && ! in.isExhausted())
  14567. {
  14568. const String key (in.readString());
  14569. const String value (in.readString());
  14570. jassert (key.isNotEmpty());
  14571. if (key.isNotEmpty())
  14572. getAllProperties().set (key, value);
  14573. }
  14574. }
  14575. else
  14576. {
  14577. // Not a binary props file - let's see if it's XML..
  14578. fileStream = 0;
  14579. XmlDocument parser (f);
  14580. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  14581. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  14582. {
  14583. doc = parser.getDocumentElement();
  14584. if (doc != 0)
  14585. {
  14586. loadedOk = true;
  14587. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  14588. {
  14589. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  14590. if (name.isNotEmpty())
  14591. {
  14592. getAllProperties().set (name,
  14593. e->getFirstChildElement() != 0
  14594. ? e->getFirstChildElement()->createDocument (String::empty, true)
  14595. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  14596. }
  14597. }
  14598. }
  14599. else
  14600. {
  14601. // must be a pretty broken XML file we're trying to parse here,
  14602. // or a sign that this object needs an InterProcessLock,
  14603. // or just a failure reading the file. This last reason is why
  14604. // we don't jassertfalse here.
  14605. }
  14606. }
  14607. }
  14608. }
  14609. else
  14610. {
  14611. loadedOk = ! f.exists();
  14612. }
  14613. }
  14614. PropertiesFile::~PropertiesFile()
  14615. {
  14616. if (! saveIfNeeded())
  14617. jassertfalse;
  14618. }
  14619. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  14620. {
  14621. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  14622. }
  14623. bool PropertiesFile::saveIfNeeded()
  14624. {
  14625. const ScopedLock sl (getLock());
  14626. return (! needsWriting) || save();
  14627. }
  14628. bool PropertiesFile::needsToBeSaved() const
  14629. {
  14630. const ScopedLock sl (getLock());
  14631. return needsWriting;
  14632. }
  14633. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  14634. {
  14635. const ScopedLock sl (getLock());
  14636. needsWriting = needsToBeSaved_;
  14637. }
  14638. bool PropertiesFile::save()
  14639. {
  14640. const ScopedLock sl (getLock());
  14641. stopTimer();
  14642. if (file == File::nonexistent
  14643. || file.isDirectory()
  14644. || ! file.getParentDirectory().createDirectory())
  14645. return false;
  14646. if ((options & storeAsXML) != 0)
  14647. {
  14648. XmlElement doc (PropertyFileConstants::fileTag);
  14649. for (int i = 0; i < getAllProperties().size(); ++i)
  14650. {
  14651. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  14652. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  14653. // if the value seems to contain xml, store it as such..
  14654. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  14655. XmlElement* const childElement = xmlContent.getDocumentElement();
  14656. if (childElement != 0)
  14657. e->addChildElement (childElement);
  14658. else
  14659. e->setAttribute (PropertyFileConstants::valueAttribute,
  14660. getAllProperties().getAllValues() [i]);
  14661. }
  14662. ProcessScopedLock pl (createProcessLock());
  14663. if (pl != 0 && ! pl->isLocked())
  14664. return false; // locking failure..
  14665. if (doc.writeToFile (file, String::empty))
  14666. {
  14667. needsWriting = false;
  14668. return true;
  14669. }
  14670. }
  14671. else
  14672. {
  14673. ProcessScopedLock pl (createProcessLock());
  14674. if (pl != 0 && ! pl->isLocked())
  14675. return false; // locking failure..
  14676. TemporaryFile tempFile (file);
  14677. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  14678. if (out != 0)
  14679. {
  14680. if ((options & storeAsCompressedBinary) != 0)
  14681. {
  14682. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  14683. out->flush();
  14684. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  14685. }
  14686. else
  14687. {
  14688. // have you set up the storage option flags correctly?
  14689. jassert ((options & storeAsBinary) != 0);
  14690. out->writeInt (PropertyFileConstants::magicNumber);
  14691. }
  14692. const int numProperties = getAllProperties().size();
  14693. out->writeInt (numProperties);
  14694. for (int i = 0; i < numProperties; ++i)
  14695. {
  14696. out->writeString (getAllProperties().getAllKeys() [i]);
  14697. out->writeString (getAllProperties().getAllValues() [i]);
  14698. }
  14699. out = 0;
  14700. if (tempFile.overwriteTargetFileWithTemporary())
  14701. {
  14702. needsWriting = false;
  14703. return true;
  14704. }
  14705. }
  14706. }
  14707. return false;
  14708. }
  14709. void PropertiesFile::timerCallback()
  14710. {
  14711. saveIfNeeded();
  14712. }
  14713. void PropertiesFile::propertyChanged()
  14714. {
  14715. sendChangeMessage (this);
  14716. needsWriting = true;
  14717. if (timerInterval > 0)
  14718. startTimer (timerInterval);
  14719. else if (timerInterval == 0)
  14720. saveIfNeeded();
  14721. }
  14722. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  14723. const String& fileNameSuffix,
  14724. const String& folderName,
  14725. const bool commonToAllUsers)
  14726. {
  14727. // mustn't have illegal characters in this name..
  14728. jassert (applicationName == File::createLegalFileName (applicationName));
  14729. #if JUCE_MAC || JUCE_IOS
  14730. File dir (commonToAllUsers ? "/Library/Preferences"
  14731. : "~/Library/Preferences");
  14732. if (folderName.isNotEmpty())
  14733. dir = dir.getChildFile (folderName);
  14734. #endif
  14735. #ifdef JUCE_LINUX
  14736. const File dir ((commonToAllUsers ? "/var/" : "~/")
  14737. + (folderName.isNotEmpty() ? folderName
  14738. : ("." + applicationName)));
  14739. #endif
  14740. #if JUCE_WINDOWS
  14741. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  14742. : File::userApplicationDataDirectory));
  14743. if (dir == File::nonexistent)
  14744. return File::nonexistent;
  14745. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  14746. : applicationName);
  14747. #endif
  14748. return dir.getChildFile (applicationName)
  14749. .withFileExtension (fileNameSuffix);
  14750. }
  14751. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  14752. const String& fileNameSuffix,
  14753. const String& folderName,
  14754. const bool commonToAllUsers,
  14755. const int millisecondsBeforeSaving,
  14756. const int propertiesFileOptions,
  14757. InterProcessLock* processLock_)
  14758. {
  14759. const File file (getDefaultAppSettingsFile (applicationName,
  14760. fileNameSuffix,
  14761. folderName,
  14762. commonToAllUsers));
  14763. jassert (file != File::nonexistent);
  14764. if (file == File::nonexistent)
  14765. return 0;
  14766. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  14767. }
  14768. END_JUCE_NAMESPACE
  14769. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  14770. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  14771. BEGIN_JUCE_NAMESPACE
  14772. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  14773. const String& fileWildcard_,
  14774. const String& openFileDialogTitle_,
  14775. const String& saveFileDialogTitle_)
  14776. : changedSinceSave (false),
  14777. fileExtension (fileExtension_),
  14778. fileWildcard (fileWildcard_),
  14779. openFileDialogTitle (openFileDialogTitle_),
  14780. saveFileDialogTitle (saveFileDialogTitle_)
  14781. {
  14782. }
  14783. FileBasedDocument::~FileBasedDocument()
  14784. {
  14785. }
  14786. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  14787. {
  14788. if (changedSinceSave != hasChanged)
  14789. {
  14790. changedSinceSave = hasChanged;
  14791. sendChangeMessage (this);
  14792. }
  14793. }
  14794. void FileBasedDocument::changed()
  14795. {
  14796. changedSinceSave = true;
  14797. sendChangeMessage (this);
  14798. }
  14799. void FileBasedDocument::setFile (const File& newFile)
  14800. {
  14801. if (documentFile != newFile)
  14802. {
  14803. documentFile = newFile;
  14804. changed();
  14805. }
  14806. }
  14807. bool FileBasedDocument::loadFrom (const File& newFile,
  14808. const bool showMessageOnFailure)
  14809. {
  14810. MouseCursor::showWaitCursor();
  14811. const File oldFile (documentFile);
  14812. documentFile = newFile;
  14813. String error;
  14814. if (newFile.existsAsFile())
  14815. {
  14816. error = loadDocument (newFile);
  14817. if (error.isEmpty())
  14818. {
  14819. setChangedFlag (false);
  14820. MouseCursor::hideWaitCursor();
  14821. setLastDocumentOpened (newFile);
  14822. return true;
  14823. }
  14824. }
  14825. else
  14826. {
  14827. error = "The file doesn't exist";
  14828. }
  14829. documentFile = oldFile;
  14830. MouseCursor::hideWaitCursor();
  14831. if (showMessageOnFailure)
  14832. {
  14833. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14834. TRANS("Failed to open file..."),
  14835. TRANS("There was an error while trying to load the file:\n\n")
  14836. + newFile.getFullPathName()
  14837. + "\n\n"
  14838. + error);
  14839. }
  14840. return false;
  14841. }
  14842. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  14843. {
  14844. FileChooser fc (openFileDialogTitle,
  14845. getLastDocumentOpened(),
  14846. fileWildcard);
  14847. if (fc.browseForFileToOpen())
  14848. return loadFrom (fc.getResult(), showMessageOnFailure);
  14849. return false;
  14850. }
  14851. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  14852. const bool showMessageOnFailure)
  14853. {
  14854. return saveAs (documentFile,
  14855. false,
  14856. askUserForFileIfNotSpecified,
  14857. showMessageOnFailure);
  14858. }
  14859. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  14860. const bool warnAboutOverwritingExistingFiles,
  14861. const bool askUserForFileIfNotSpecified,
  14862. const bool showMessageOnFailure)
  14863. {
  14864. if (newFile == File::nonexistent)
  14865. {
  14866. if (askUserForFileIfNotSpecified)
  14867. {
  14868. return saveAsInteractive (true);
  14869. }
  14870. else
  14871. {
  14872. // can't save to an unspecified file
  14873. jassertfalse;
  14874. return failedToWriteToFile;
  14875. }
  14876. }
  14877. if (warnAboutOverwritingExistingFiles && newFile.exists())
  14878. {
  14879. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14880. TRANS("File already exists"),
  14881. TRANS("There's already a file called:\n\n")
  14882. + newFile.getFullPathName()
  14883. + TRANS("\n\nAre you sure you want to overwrite it?"),
  14884. TRANS("overwrite"),
  14885. TRANS("cancel")))
  14886. {
  14887. return userCancelledSave;
  14888. }
  14889. }
  14890. MouseCursor::showWaitCursor();
  14891. const File oldFile (documentFile);
  14892. documentFile = newFile;
  14893. String error (saveDocument (newFile));
  14894. if (error.isEmpty())
  14895. {
  14896. setChangedFlag (false);
  14897. MouseCursor::hideWaitCursor();
  14898. return savedOk;
  14899. }
  14900. documentFile = oldFile;
  14901. MouseCursor::hideWaitCursor();
  14902. if (showMessageOnFailure)
  14903. {
  14904. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14905. TRANS("Error writing to file..."),
  14906. TRANS("An error occurred while trying to save \"")
  14907. + getDocumentTitle()
  14908. + TRANS("\" to the file:\n\n")
  14909. + newFile.getFullPathName()
  14910. + "\n\n"
  14911. + error);
  14912. }
  14913. return failedToWriteToFile;
  14914. }
  14915. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  14916. {
  14917. if (! hasChangedSinceSaved())
  14918. return savedOk;
  14919. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  14920. TRANS("Closing document..."),
  14921. TRANS("Do you want to save the changes to \"")
  14922. + getDocumentTitle() + "\"?",
  14923. TRANS("save"),
  14924. TRANS("discard changes"),
  14925. TRANS("cancel"));
  14926. if (r == 1)
  14927. {
  14928. // save changes
  14929. return save (true, true);
  14930. }
  14931. else if (r == 2)
  14932. {
  14933. // discard changes
  14934. return savedOk;
  14935. }
  14936. return userCancelledSave;
  14937. }
  14938. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  14939. {
  14940. File f;
  14941. if (documentFile.existsAsFile())
  14942. f = documentFile;
  14943. else
  14944. f = getLastDocumentOpened();
  14945. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  14946. if (legalFilename.isEmpty())
  14947. legalFilename = "unnamed";
  14948. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  14949. f = f.getSiblingFile (legalFilename);
  14950. else
  14951. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  14952. f = f.withFileExtension (fileExtension)
  14953. .getNonexistentSibling (true);
  14954. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  14955. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  14956. {
  14957. setLastDocumentOpened (fc.getResult());
  14958. File chosen (fc.getResult());
  14959. if (chosen.getFileExtension().isEmpty())
  14960. {
  14961. chosen = chosen.withFileExtension (fileExtension);
  14962. if (chosen.exists())
  14963. {
  14964. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14965. TRANS("File already exists"),
  14966. TRANS("There's already a file called:")
  14967. + "\n\n" + chosen.getFullPathName()
  14968. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  14969. TRANS("overwrite"),
  14970. TRANS("cancel")))
  14971. {
  14972. return userCancelledSave;
  14973. }
  14974. }
  14975. }
  14976. return saveAs (chosen, false, false, true);
  14977. }
  14978. return userCancelledSave;
  14979. }
  14980. END_JUCE_NAMESPACE
  14981. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  14982. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  14983. BEGIN_JUCE_NAMESPACE
  14984. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  14985. : maxNumberOfItems (10)
  14986. {
  14987. }
  14988. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  14989. {
  14990. }
  14991. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  14992. {
  14993. maxNumberOfItems = jmax (1, newMaxNumber);
  14994. while (getNumFiles() > maxNumberOfItems)
  14995. files.remove (getNumFiles() - 1);
  14996. }
  14997. int RecentlyOpenedFilesList::getNumFiles() const
  14998. {
  14999. return files.size();
  15000. }
  15001. const File RecentlyOpenedFilesList::getFile (const int index) const
  15002. {
  15003. return File (files [index]);
  15004. }
  15005. void RecentlyOpenedFilesList::clear()
  15006. {
  15007. files.clear();
  15008. }
  15009. void RecentlyOpenedFilesList::addFile (const File& file)
  15010. {
  15011. const String path (file.getFullPathName());
  15012. files.removeString (path, true);
  15013. files.insert (0, path);
  15014. setMaxNumberOfItems (maxNumberOfItems);
  15015. }
  15016. void RecentlyOpenedFilesList::removeNonExistentFiles()
  15017. {
  15018. for (int i = getNumFiles(); --i >= 0;)
  15019. if (! getFile(i).exists())
  15020. files.remove (i);
  15021. }
  15022. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  15023. const int baseItemId,
  15024. const bool showFullPaths,
  15025. const bool dontAddNonExistentFiles,
  15026. const File** filesToAvoid)
  15027. {
  15028. int num = 0;
  15029. for (int i = 0; i < getNumFiles(); ++i)
  15030. {
  15031. const File f (getFile(i));
  15032. if ((! dontAddNonExistentFiles) || f.exists())
  15033. {
  15034. bool needsAvoiding = false;
  15035. if (filesToAvoid != 0)
  15036. {
  15037. const File** avoid = filesToAvoid;
  15038. while (*avoid != 0)
  15039. {
  15040. if (f == **avoid)
  15041. {
  15042. needsAvoiding = true;
  15043. break;
  15044. }
  15045. ++avoid;
  15046. }
  15047. }
  15048. if (! needsAvoiding)
  15049. {
  15050. menuToAddTo.addItem (baseItemId + i,
  15051. showFullPaths ? f.getFullPathName()
  15052. : f.getFileName());
  15053. ++num;
  15054. }
  15055. }
  15056. }
  15057. return num;
  15058. }
  15059. const String RecentlyOpenedFilesList::toString() const
  15060. {
  15061. return files.joinIntoString ("\n");
  15062. }
  15063. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  15064. {
  15065. clear();
  15066. files.addLines (stringifiedVersion);
  15067. setMaxNumberOfItems (maxNumberOfItems);
  15068. }
  15069. END_JUCE_NAMESPACE
  15070. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15071. /*** Start of inlined file: juce_UndoManager.cpp ***/
  15072. BEGIN_JUCE_NAMESPACE
  15073. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  15074. const int minimumTransactions)
  15075. : totalUnitsStored (0),
  15076. nextIndex (0),
  15077. newTransaction (true),
  15078. reentrancyCheck (false)
  15079. {
  15080. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  15081. minimumTransactions);
  15082. }
  15083. UndoManager::~UndoManager()
  15084. {
  15085. clearUndoHistory();
  15086. }
  15087. void UndoManager::clearUndoHistory()
  15088. {
  15089. transactions.clear();
  15090. transactionNames.clear();
  15091. totalUnitsStored = 0;
  15092. nextIndex = 0;
  15093. sendChangeMessage (this);
  15094. }
  15095. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  15096. {
  15097. return totalUnitsStored;
  15098. }
  15099. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  15100. const int minimumTransactions)
  15101. {
  15102. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  15103. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  15104. }
  15105. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  15106. {
  15107. if (command_ != 0)
  15108. {
  15109. ScopedPointer<UndoableAction> command (command_);
  15110. if (actionName.isNotEmpty())
  15111. currentTransactionName = actionName;
  15112. if (reentrancyCheck)
  15113. {
  15114. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  15115. // undo() methods, or else these actions won't actually get done.
  15116. return false;
  15117. }
  15118. else if (command->perform())
  15119. {
  15120. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  15121. if (commandSet != 0 && ! newTransaction)
  15122. {
  15123. UndoableAction* lastAction = commandSet->getLast();
  15124. if (lastAction != 0)
  15125. {
  15126. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  15127. if (coalescedAction != 0)
  15128. {
  15129. command = coalescedAction;
  15130. totalUnitsStored -= lastAction->getSizeInUnits();
  15131. commandSet->removeLast();
  15132. }
  15133. }
  15134. }
  15135. else
  15136. {
  15137. commandSet = new OwnedArray<UndoableAction>();
  15138. transactions.insert (nextIndex, commandSet);
  15139. transactionNames.insert (nextIndex, currentTransactionName);
  15140. ++nextIndex;
  15141. }
  15142. totalUnitsStored += command->getSizeInUnits();
  15143. commandSet->add (command.release());
  15144. newTransaction = false;
  15145. while (nextIndex < transactions.size())
  15146. {
  15147. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  15148. for (int i = lastSet->size(); --i >= 0;)
  15149. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  15150. transactions.removeLast();
  15151. transactionNames.remove (transactionNames.size() - 1);
  15152. }
  15153. while (nextIndex > 0
  15154. && totalUnitsStored > maxNumUnitsToKeep
  15155. && transactions.size() > minimumTransactionsToKeep)
  15156. {
  15157. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  15158. for (int i = firstSet->size(); --i >= 0;)
  15159. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  15160. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  15161. transactions.remove (0);
  15162. transactionNames.remove (0);
  15163. --nextIndex;
  15164. }
  15165. sendChangeMessage (this);
  15166. return true;
  15167. }
  15168. }
  15169. return false;
  15170. }
  15171. void UndoManager::beginNewTransaction (const String& actionName)
  15172. {
  15173. newTransaction = true;
  15174. currentTransactionName = actionName;
  15175. }
  15176. void UndoManager::setCurrentTransactionName (const String& newName)
  15177. {
  15178. currentTransactionName = newName;
  15179. }
  15180. bool UndoManager::canUndo() const
  15181. {
  15182. return nextIndex > 0;
  15183. }
  15184. bool UndoManager::canRedo() const
  15185. {
  15186. return nextIndex < transactions.size();
  15187. }
  15188. const String UndoManager::getUndoDescription() const
  15189. {
  15190. return transactionNames [nextIndex - 1];
  15191. }
  15192. const String UndoManager::getRedoDescription() const
  15193. {
  15194. return transactionNames [nextIndex];
  15195. }
  15196. bool UndoManager::undo()
  15197. {
  15198. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15199. if (commandSet == 0)
  15200. return false;
  15201. reentrancyCheck = true;
  15202. bool failed = false;
  15203. for (int i = commandSet->size(); --i >= 0;)
  15204. {
  15205. if (! commandSet->getUnchecked(i)->undo())
  15206. {
  15207. jassertfalse;
  15208. failed = true;
  15209. break;
  15210. }
  15211. }
  15212. reentrancyCheck = false;
  15213. if (failed)
  15214. clearUndoHistory();
  15215. else
  15216. --nextIndex;
  15217. beginNewTransaction();
  15218. sendChangeMessage (this);
  15219. return true;
  15220. }
  15221. bool UndoManager::redo()
  15222. {
  15223. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  15224. if (commandSet == 0)
  15225. return false;
  15226. reentrancyCheck = true;
  15227. bool failed = false;
  15228. for (int i = 0; i < commandSet->size(); ++i)
  15229. {
  15230. if (! commandSet->getUnchecked(i)->perform())
  15231. {
  15232. jassertfalse;
  15233. failed = true;
  15234. break;
  15235. }
  15236. }
  15237. reentrancyCheck = false;
  15238. if (failed)
  15239. clearUndoHistory();
  15240. else
  15241. ++nextIndex;
  15242. beginNewTransaction();
  15243. sendChangeMessage (this);
  15244. return true;
  15245. }
  15246. bool UndoManager::undoCurrentTransactionOnly()
  15247. {
  15248. return newTransaction ? false : undo();
  15249. }
  15250. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  15251. {
  15252. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15253. if (commandSet != 0 && ! newTransaction)
  15254. {
  15255. for (int i = 0; i < commandSet->size(); ++i)
  15256. actionsFound.add (commandSet->getUnchecked(i));
  15257. }
  15258. }
  15259. int UndoManager::getNumActionsInCurrentTransaction() const
  15260. {
  15261. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15262. if (commandSet != 0 && ! newTransaction)
  15263. return commandSet->size();
  15264. return 0;
  15265. }
  15266. END_JUCE_NAMESPACE
  15267. /*** End of inlined file: juce_UndoManager.cpp ***/
  15268. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  15269. BEGIN_JUCE_NAMESPACE
  15270. static const char* const aiffFormatName = "AIFF file";
  15271. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  15272. class AiffAudioFormatReader : public AudioFormatReader
  15273. {
  15274. public:
  15275. int bytesPerFrame;
  15276. int64 dataChunkStart;
  15277. bool littleEndian;
  15278. AiffAudioFormatReader (InputStream* in)
  15279. : AudioFormatReader (in, TRANS (aiffFormatName))
  15280. {
  15281. if (input->readInt() == chunkName ("FORM"))
  15282. {
  15283. const int len = input->readIntBigEndian();
  15284. const int64 end = input->getPosition() + len;
  15285. const int nextType = input->readInt();
  15286. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  15287. {
  15288. bool hasGotVer = false;
  15289. bool hasGotData = false;
  15290. bool hasGotType = false;
  15291. while (input->getPosition() < end)
  15292. {
  15293. const int type = input->readInt();
  15294. const uint32 length = (uint32) input->readIntBigEndian();
  15295. const int64 chunkEnd = input->getPosition() + length;
  15296. if (type == chunkName ("FVER"))
  15297. {
  15298. hasGotVer = true;
  15299. const int ver = input->readIntBigEndian();
  15300. if (ver != 0 && ver != (int)0xa2805140)
  15301. break;
  15302. }
  15303. else if (type == chunkName ("COMM"))
  15304. {
  15305. hasGotType = true;
  15306. numChannels = (unsigned int)input->readShortBigEndian();
  15307. lengthInSamples = input->readIntBigEndian();
  15308. bitsPerSample = input->readShortBigEndian();
  15309. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  15310. unsigned char sampleRateBytes[10];
  15311. input->read (sampleRateBytes, 10);
  15312. const int byte0 = sampleRateBytes[0];
  15313. if ((byte0 & 0x80) != 0
  15314. || byte0 <= 0x3F || byte0 > 0x40
  15315. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  15316. break;
  15317. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  15318. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  15319. sampleRate = (int) sampRate;
  15320. if (length <= 18)
  15321. {
  15322. // some types don't have a chunk large enough to include a compression
  15323. // type, so assume it's just big-endian pcm
  15324. littleEndian = false;
  15325. }
  15326. else
  15327. {
  15328. const int compType = input->readInt();
  15329. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  15330. {
  15331. littleEndian = false;
  15332. }
  15333. else if (compType == chunkName ("sowt"))
  15334. {
  15335. littleEndian = true;
  15336. }
  15337. else
  15338. {
  15339. sampleRate = 0;
  15340. break;
  15341. }
  15342. }
  15343. }
  15344. else if (type == chunkName ("SSND"))
  15345. {
  15346. hasGotData = true;
  15347. const int offset = input->readIntBigEndian();
  15348. dataChunkStart = input->getPosition() + 4 + offset;
  15349. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  15350. }
  15351. else if ((hasGotVer && hasGotData && hasGotType)
  15352. || chunkEnd < input->getPosition()
  15353. || input->isExhausted())
  15354. {
  15355. break;
  15356. }
  15357. input->setPosition (chunkEnd);
  15358. }
  15359. }
  15360. }
  15361. }
  15362. ~AiffAudioFormatReader()
  15363. {
  15364. }
  15365. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15366. int64 startSampleInFile, int numSamples)
  15367. {
  15368. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  15369. if (samplesAvailable < numSamples)
  15370. {
  15371. for (int i = numDestChannels; --i >= 0;)
  15372. if (destSamples[i] != 0)
  15373. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  15374. numSamples = (int) samplesAvailable;
  15375. }
  15376. if (numSamples <= 0)
  15377. return true;
  15378. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  15379. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  15380. char tempBuffer [tempBufSize];
  15381. while (numSamples > 0)
  15382. {
  15383. int* left = destSamples[0];
  15384. if (left != 0)
  15385. left += startOffsetInDestBuffer;
  15386. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  15387. if (right != 0)
  15388. right += startOffsetInDestBuffer;
  15389. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  15390. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  15391. if (bytesRead < numThisTime * bytesPerFrame)
  15392. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  15393. if (bitsPerSample == 16)
  15394. {
  15395. if (littleEndian)
  15396. {
  15397. const short* src = reinterpret_cast <const short*> (tempBuffer);
  15398. if (numChannels > 1)
  15399. {
  15400. if (left == 0)
  15401. {
  15402. for (int i = numThisTime; --i >= 0;)
  15403. {
  15404. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15405. ++src;
  15406. }
  15407. }
  15408. else if (right == 0)
  15409. {
  15410. for (int i = numThisTime; --i >= 0;)
  15411. {
  15412. ++src;
  15413. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15414. }
  15415. }
  15416. else
  15417. {
  15418. for (int i = numThisTime; --i >= 0;)
  15419. {
  15420. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15421. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15422. }
  15423. }
  15424. }
  15425. else
  15426. {
  15427. for (int i = numThisTime; --i >= 0;)
  15428. {
  15429. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15430. }
  15431. }
  15432. }
  15433. else
  15434. {
  15435. const char* src = tempBuffer;
  15436. if (numChannels > 1)
  15437. {
  15438. if (left == 0)
  15439. {
  15440. for (int i = numThisTime; --i >= 0;)
  15441. {
  15442. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15443. src += 4;
  15444. }
  15445. }
  15446. else if (right == 0)
  15447. {
  15448. for (int i = numThisTime; --i >= 0;)
  15449. {
  15450. src += 2;
  15451. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15452. src += 2;
  15453. }
  15454. }
  15455. else
  15456. {
  15457. for (int i = numThisTime; --i >= 0;)
  15458. {
  15459. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15460. src += 2;
  15461. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15462. src += 2;
  15463. }
  15464. }
  15465. }
  15466. else
  15467. {
  15468. for (int i = numThisTime; --i >= 0;)
  15469. {
  15470. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15471. src += 2;
  15472. }
  15473. }
  15474. }
  15475. }
  15476. else if (bitsPerSample == 24)
  15477. {
  15478. const char* src = (const char*)tempBuffer;
  15479. if (littleEndian)
  15480. {
  15481. if (numChannels > 1)
  15482. {
  15483. if (left == 0)
  15484. {
  15485. for (int i = numThisTime; --i >= 0;)
  15486. {
  15487. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15488. src += 6;
  15489. }
  15490. }
  15491. else if (right == 0)
  15492. {
  15493. for (int i = numThisTime; --i >= 0;)
  15494. {
  15495. src += 3;
  15496. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15497. src += 3;
  15498. }
  15499. }
  15500. else
  15501. {
  15502. for (int i = numThisTime; --i >= 0;)
  15503. {
  15504. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15505. src += 3;
  15506. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15507. src += 3;
  15508. }
  15509. }
  15510. }
  15511. else
  15512. {
  15513. for (int i = numThisTime; --i >= 0;)
  15514. {
  15515. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15516. src += 3;
  15517. }
  15518. }
  15519. }
  15520. else
  15521. {
  15522. if (numChannels > 1)
  15523. {
  15524. if (left == 0)
  15525. {
  15526. for (int i = numThisTime; --i >= 0;)
  15527. {
  15528. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15529. src += 6;
  15530. }
  15531. }
  15532. else if (right == 0)
  15533. {
  15534. for (int i = numThisTime; --i >= 0;)
  15535. {
  15536. src += 3;
  15537. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15538. src += 3;
  15539. }
  15540. }
  15541. else
  15542. {
  15543. for (int i = numThisTime; --i >= 0;)
  15544. {
  15545. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15546. src += 3;
  15547. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15548. src += 3;
  15549. }
  15550. }
  15551. }
  15552. else
  15553. {
  15554. for (int i = numThisTime; --i >= 0;)
  15555. {
  15556. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15557. src += 3;
  15558. }
  15559. }
  15560. }
  15561. }
  15562. else if (bitsPerSample == 32)
  15563. {
  15564. const unsigned int* src = reinterpret_cast <const unsigned int*> (tempBuffer);
  15565. unsigned int* l = reinterpret_cast <unsigned int*> (left);
  15566. unsigned int* r = reinterpret_cast <unsigned int*> (right);
  15567. if (littleEndian)
  15568. {
  15569. if (numChannels > 1)
  15570. {
  15571. if (l == 0)
  15572. {
  15573. for (int i = numThisTime; --i >= 0;)
  15574. {
  15575. ++src;
  15576. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15577. }
  15578. }
  15579. else if (r == 0)
  15580. {
  15581. for (int i = numThisTime; --i >= 0;)
  15582. {
  15583. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15584. ++src;
  15585. }
  15586. }
  15587. else
  15588. {
  15589. for (int i = numThisTime; --i >= 0;)
  15590. {
  15591. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15592. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15593. }
  15594. }
  15595. }
  15596. else
  15597. {
  15598. for (int i = numThisTime; --i >= 0;)
  15599. {
  15600. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15601. }
  15602. }
  15603. }
  15604. else
  15605. {
  15606. if (numChannels > 1)
  15607. {
  15608. if (l == 0)
  15609. {
  15610. for (int i = numThisTime; --i >= 0;)
  15611. {
  15612. ++src;
  15613. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15614. }
  15615. }
  15616. else if (r == 0)
  15617. {
  15618. for (int i = numThisTime; --i >= 0;)
  15619. {
  15620. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15621. ++src;
  15622. }
  15623. }
  15624. else
  15625. {
  15626. for (int i = numThisTime; --i >= 0;)
  15627. {
  15628. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15629. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15630. }
  15631. }
  15632. }
  15633. else
  15634. {
  15635. for (int i = numThisTime; --i >= 0;)
  15636. {
  15637. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15638. }
  15639. }
  15640. }
  15641. left = reinterpret_cast <int*> (l);
  15642. right = reinterpret_cast <int*> (r);
  15643. }
  15644. else if (bitsPerSample == 8)
  15645. {
  15646. const char* src = tempBuffer;
  15647. if (numChannels > 1)
  15648. {
  15649. if (left == 0)
  15650. {
  15651. for (int i = numThisTime; --i >= 0;)
  15652. {
  15653. *right++ = ((int) *src++) << 24;
  15654. ++src;
  15655. }
  15656. }
  15657. else if (right == 0)
  15658. {
  15659. for (int i = numThisTime; --i >= 0;)
  15660. {
  15661. ++src;
  15662. *left++ = ((int) *src++) << 24;
  15663. }
  15664. }
  15665. else
  15666. {
  15667. for (int i = numThisTime; --i >= 0;)
  15668. {
  15669. *left++ = ((int) *src++) << 24;
  15670. *right++ = ((int) *src++) << 24;
  15671. }
  15672. }
  15673. }
  15674. else
  15675. {
  15676. for (int i = numThisTime; --i >= 0;)
  15677. {
  15678. *left++ = ((int) *src++) << 24;
  15679. }
  15680. }
  15681. }
  15682. startOffsetInDestBuffer += numThisTime;
  15683. numSamples -= numThisTime;
  15684. }
  15685. if (numSamples > 0)
  15686. {
  15687. for (int i = numDestChannels; --i >= 0;)
  15688. if (destSamples[i] != 0)
  15689. zeromem (destSamples[i] + startOffsetInDestBuffer,
  15690. sizeof (int) * numSamples);
  15691. }
  15692. return true;
  15693. }
  15694. juce_UseDebuggingNewOperator
  15695. private:
  15696. AiffAudioFormatReader (const AiffAudioFormatReader&);
  15697. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  15698. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15699. };
  15700. class AiffAudioFormatWriter : public AudioFormatWriter
  15701. {
  15702. MemoryBlock tempBlock;
  15703. uint32 lengthInSamples, bytesWritten;
  15704. int64 headerPosition;
  15705. bool writeFailed;
  15706. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15707. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  15708. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  15709. void writeHeader()
  15710. {
  15711. const bool couldSeekOk = output->setPosition (headerPosition);
  15712. (void) couldSeekOk;
  15713. // if this fails, you've given it an output stream that can't seek! It needs
  15714. // to be able to seek back to write the header
  15715. jassert (couldSeekOk);
  15716. const int headerLen = 54;
  15717. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  15718. audioBytes += (audioBytes & 1);
  15719. output->writeInt (chunkName ("FORM"));
  15720. output->writeIntBigEndian (headerLen + audioBytes - 8);
  15721. output->writeInt (chunkName ("AIFF"));
  15722. output->writeInt (chunkName ("COMM"));
  15723. output->writeIntBigEndian (18);
  15724. output->writeShortBigEndian ((short) numChannels);
  15725. output->writeIntBigEndian (lengthInSamples);
  15726. output->writeShortBigEndian ((short) bitsPerSample);
  15727. uint8 sampleRateBytes[10];
  15728. zeromem (sampleRateBytes, 10);
  15729. if (sampleRate <= 1)
  15730. {
  15731. sampleRateBytes[0] = 0x3f;
  15732. sampleRateBytes[1] = 0xff;
  15733. sampleRateBytes[2] = 0x80;
  15734. }
  15735. else
  15736. {
  15737. int mask = 0x40000000;
  15738. sampleRateBytes[0] = 0x40;
  15739. if (sampleRate >= mask)
  15740. {
  15741. jassertfalse;
  15742. sampleRateBytes[1] = 0x1d;
  15743. }
  15744. else
  15745. {
  15746. int n = (int) sampleRate;
  15747. int i;
  15748. for (i = 0; i <= 32 ; ++i)
  15749. {
  15750. if ((n & mask) != 0)
  15751. break;
  15752. mask >>= 1;
  15753. }
  15754. n = n << (i + 1);
  15755. sampleRateBytes[1] = (uint8) (29 - i);
  15756. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  15757. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  15758. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  15759. sampleRateBytes[5] = (uint8) (n & 0xff);
  15760. }
  15761. }
  15762. output->write (sampleRateBytes, 10);
  15763. output->writeInt (chunkName ("SSND"));
  15764. output->writeIntBigEndian (audioBytes + 8);
  15765. output->writeInt (0);
  15766. output->writeInt (0);
  15767. jassert (output->getPosition() == headerLen);
  15768. }
  15769. public:
  15770. AiffAudioFormatWriter (OutputStream* out,
  15771. const double sampleRate_,
  15772. const unsigned int chans,
  15773. const int bits)
  15774. : AudioFormatWriter (out,
  15775. TRANS (aiffFormatName),
  15776. sampleRate_,
  15777. chans,
  15778. bits),
  15779. lengthInSamples (0),
  15780. bytesWritten (0),
  15781. writeFailed (false)
  15782. {
  15783. headerPosition = out->getPosition();
  15784. writeHeader();
  15785. }
  15786. ~AiffAudioFormatWriter()
  15787. {
  15788. if ((bytesWritten & 1) != 0)
  15789. output->writeByte (0);
  15790. writeHeader();
  15791. }
  15792. bool write (const int** data, int numSamples)
  15793. {
  15794. if (writeFailed)
  15795. return false;
  15796. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  15797. tempBlock.ensureSize (bytes, false);
  15798. char* buffer = static_cast <char*> (tempBlock.getData());
  15799. const int* left = data[0];
  15800. const int* right = data[1];
  15801. if (right == 0)
  15802. right = left;
  15803. if (bitsPerSample == 16)
  15804. {
  15805. short* b = reinterpret_cast <short*> (buffer);
  15806. if (numChannels > 1)
  15807. {
  15808. for (int i = numSamples; --i >= 0;)
  15809. {
  15810. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15811. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*right++ >> 16));
  15812. }
  15813. }
  15814. else
  15815. {
  15816. for (int i = numSamples; --i >= 0;)
  15817. {
  15818. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15819. }
  15820. }
  15821. }
  15822. else if (bitsPerSample == 24)
  15823. {
  15824. char* b = buffer;
  15825. if (numChannels > 1)
  15826. {
  15827. for (int i = numSamples; --i >= 0;)
  15828. {
  15829. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15830. b += 3;
  15831. ByteOrder::bigEndian24BitToChars (*right++ >> 8, b);
  15832. b += 3;
  15833. }
  15834. }
  15835. else
  15836. {
  15837. for (int i = numSamples; --i >= 0;)
  15838. {
  15839. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15840. b += 3;
  15841. }
  15842. }
  15843. }
  15844. else if (bitsPerSample == 32)
  15845. {
  15846. uint32* b = reinterpret_cast <uint32*> (buffer);
  15847. if (numChannels > 1)
  15848. {
  15849. for (int i = numSamples; --i >= 0;)
  15850. {
  15851. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15852. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *right++);
  15853. }
  15854. }
  15855. else
  15856. {
  15857. for (int i = numSamples; --i >= 0;)
  15858. {
  15859. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15860. }
  15861. }
  15862. }
  15863. else if (bitsPerSample == 8)
  15864. {
  15865. char* b = buffer;
  15866. if (numChannels > 1)
  15867. {
  15868. for (int i = numSamples; --i >= 0;)
  15869. {
  15870. *b++ = (char) (*left++ >> 24);
  15871. *b++ = (char) (*right++ >> 24);
  15872. }
  15873. }
  15874. else
  15875. {
  15876. for (int i = numSamples; --i >= 0;)
  15877. {
  15878. *b++ = (char) (*left++ >> 24);
  15879. }
  15880. }
  15881. }
  15882. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15883. || ! output->write (buffer, bytes))
  15884. {
  15885. // failed to write to disk, so let's try writing the header.
  15886. // If it's just run out of disk space, then if it does manage
  15887. // to write the header, we'll still have a useable file..
  15888. writeHeader();
  15889. writeFailed = true;
  15890. return false;
  15891. }
  15892. else
  15893. {
  15894. bytesWritten += bytes;
  15895. lengthInSamples += numSamples;
  15896. return true;
  15897. }
  15898. }
  15899. juce_UseDebuggingNewOperator
  15900. };
  15901. AiffAudioFormat::AiffAudioFormat()
  15902. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  15903. {
  15904. }
  15905. AiffAudioFormat::~AiffAudioFormat()
  15906. {
  15907. }
  15908. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  15909. {
  15910. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15911. return Array <int> (rates);
  15912. }
  15913. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  15914. {
  15915. const int depths[] = { 8, 16, 24, 0 };
  15916. return Array <int> (depths);
  15917. }
  15918. bool AiffAudioFormat::canDoStereo()
  15919. {
  15920. return true;
  15921. }
  15922. bool AiffAudioFormat::canDoMono()
  15923. {
  15924. return true;
  15925. }
  15926. #if JUCE_MAC
  15927. bool AiffAudioFormat::canHandleFile (const File& f)
  15928. {
  15929. if (AudioFormat::canHandleFile (f))
  15930. return true;
  15931. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  15932. return type == 'AIFF' || type == 'AIFC'
  15933. || type == 'aiff' || type == 'aifc';
  15934. }
  15935. #endif
  15936. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  15937. const bool deleteStreamIfOpeningFails)
  15938. {
  15939. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  15940. if (w->sampleRate != 0)
  15941. return w.release();
  15942. if (! deleteStreamIfOpeningFails)
  15943. w->input = 0;
  15944. return 0;
  15945. }
  15946. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  15947. double sampleRate,
  15948. unsigned int chans,
  15949. int bitsPerSample,
  15950. const StringPairArray& /*metadataValues*/,
  15951. int /*qualityOptionIndex*/)
  15952. {
  15953. if (getPossibleBitDepths().contains (bitsPerSample))
  15954. {
  15955. return new AiffAudioFormatWriter (out,
  15956. sampleRate,
  15957. chans,
  15958. bitsPerSample);
  15959. }
  15960. return 0;
  15961. }
  15962. END_JUCE_NAMESPACE
  15963. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  15964. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  15965. BEGIN_JUCE_NAMESPACE
  15966. AudioFormatReader::AudioFormatReader (InputStream* const in,
  15967. const String& formatName_)
  15968. : sampleRate (0),
  15969. bitsPerSample (0),
  15970. lengthInSamples (0),
  15971. numChannels (0),
  15972. usesFloatingPointData (false),
  15973. input (in),
  15974. formatName (formatName_)
  15975. {
  15976. }
  15977. AudioFormatReader::~AudioFormatReader()
  15978. {
  15979. delete input;
  15980. }
  15981. bool AudioFormatReader::read (int** destSamples,
  15982. int numDestChannels,
  15983. int64 startSampleInSource,
  15984. int numSamplesToRead,
  15985. const bool fillLeftoverChannelsWithCopies)
  15986. {
  15987. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  15988. int startOffsetInDestBuffer = 0;
  15989. if (startSampleInSource < 0)
  15990. {
  15991. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  15992. for (int i = numDestChannels; --i >= 0;)
  15993. if (destSamples[i] != 0)
  15994. zeromem (destSamples[i], sizeof (int) * silence);
  15995. startOffsetInDestBuffer += silence;
  15996. numSamplesToRead -= silence;
  15997. startSampleInSource = 0;
  15998. }
  15999. if (numSamplesToRead <= 0)
  16000. return true;
  16001. if (! readSamples (destSamples, jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  16002. startSampleInSource, numSamplesToRead))
  16003. return false;
  16004. if (numDestChannels > (int) numChannels)
  16005. {
  16006. if (fillLeftoverChannelsWithCopies)
  16007. {
  16008. int* lastFullChannel = destSamples[0];
  16009. for (int i = (int) numChannels; --i > 0;)
  16010. {
  16011. if (destSamples[i] != 0)
  16012. {
  16013. lastFullChannel = destSamples[i];
  16014. break;
  16015. }
  16016. }
  16017. if (lastFullChannel != 0)
  16018. for (int i = numChannels; i < numDestChannels; ++i)
  16019. if (destSamples[i] != 0)
  16020. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  16021. }
  16022. else
  16023. {
  16024. for (int i = numChannels; i < numDestChannels; ++i)
  16025. if (destSamples[i] != 0)
  16026. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  16027. }
  16028. }
  16029. return true;
  16030. }
  16031. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  16032. {
  16033. float mn = buffer[0];
  16034. float mx = mn;
  16035. for (int i = 1; i < num; ++i)
  16036. {
  16037. const float s = buffer[i];
  16038. if (s > mx) mx = s;
  16039. if (s < mn) mn = s;
  16040. }
  16041. maxVal = mx;
  16042. minVal = mn;
  16043. }
  16044. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16045. int64 numSamples,
  16046. float& lowestLeft, float& highestLeft,
  16047. float& lowestRight, float& highestRight)
  16048. {
  16049. if (numSamples <= 0)
  16050. {
  16051. lowestLeft = 0;
  16052. lowestRight = 0;
  16053. highestLeft = 0;
  16054. highestRight = 0;
  16055. return;
  16056. }
  16057. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16058. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16059. int* tempBuffer[3];
  16060. tempBuffer[0] = (int*) tempSpace.getData();
  16061. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16062. tempBuffer[2] = 0;
  16063. if (usesFloatingPointData)
  16064. {
  16065. float lmin = 1.0e6f;
  16066. float lmax = -lmin;
  16067. float rmin = lmin;
  16068. float rmax = lmax;
  16069. while (numSamples > 0)
  16070. {
  16071. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16072. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16073. numSamples -= numToDo;
  16074. startSampleInFile += numToDo;
  16075. float bufmin, bufmax;
  16076. findAudioBufferMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  16077. lmin = jmin (lmin, bufmin);
  16078. lmax = jmax (lmax, bufmax);
  16079. if (numChannels > 1)
  16080. {
  16081. findAudioBufferMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  16082. rmin = jmin (rmin, bufmin);
  16083. rmax = jmax (rmax, bufmax);
  16084. }
  16085. }
  16086. if (numChannels <= 1)
  16087. {
  16088. rmax = lmax;
  16089. rmin = lmin;
  16090. }
  16091. lowestLeft = lmin;
  16092. highestLeft = lmax;
  16093. lowestRight = rmin;
  16094. highestRight = rmax;
  16095. }
  16096. else
  16097. {
  16098. int lmax = std::numeric_limits<int>::min();
  16099. int lmin = std::numeric_limits<int>::max();
  16100. int rmax = std::numeric_limits<int>::min();
  16101. int rmin = std::numeric_limits<int>::max();
  16102. while (numSamples > 0)
  16103. {
  16104. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16105. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16106. numSamples -= numToDo;
  16107. startSampleInFile += numToDo;
  16108. for (int j = numChannels; --j >= 0;)
  16109. {
  16110. int bufMax = std::numeric_limits<int>::min();
  16111. int bufMin = std::numeric_limits<int>::max();
  16112. const int* const b = tempBuffer[j];
  16113. for (int i = 0; i < numToDo; ++i)
  16114. {
  16115. const int samp = b[i];
  16116. if (samp < bufMin)
  16117. bufMin = samp;
  16118. if (samp > bufMax)
  16119. bufMax = samp;
  16120. }
  16121. if (j == 0)
  16122. {
  16123. lmax = jmax (lmax, bufMax);
  16124. lmin = jmin (lmin, bufMin);
  16125. }
  16126. else
  16127. {
  16128. rmax = jmax (rmax, bufMax);
  16129. rmin = jmin (rmin, bufMin);
  16130. }
  16131. }
  16132. }
  16133. if (numChannels <= 1)
  16134. {
  16135. rmax = lmax;
  16136. rmin = lmin;
  16137. }
  16138. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16139. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16140. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16141. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16142. }
  16143. }
  16144. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16145. int64 numSamplesToSearch,
  16146. const double magnitudeRangeMinimum,
  16147. const double magnitudeRangeMaximum,
  16148. const int minimumConsecutiveSamples)
  16149. {
  16150. if (numSamplesToSearch == 0)
  16151. return -1;
  16152. const int bufferSize = 4096;
  16153. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16154. int* tempBuffer[3];
  16155. tempBuffer[0] = (int*) tempSpace.getData();
  16156. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16157. tempBuffer[2] = 0;
  16158. int consecutive = 0;
  16159. int64 firstMatchPos = -1;
  16160. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16161. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16162. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16163. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16164. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16165. while (numSamplesToSearch != 0)
  16166. {
  16167. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16168. int64 bufferStart = startSample;
  16169. if (numSamplesToSearch < 0)
  16170. bufferStart -= numThisTime;
  16171. if (bufferStart >= (int) lengthInSamples)
  16172. break;
  16173. read ((int**) tempBuffer, 2, bufferStart, numThisTime, false);
  16174. int num = numThisTime;
  16175. while (--num >= 0)
  16176. {
  16177. if (numSamplesToSearch < 0)
  16178. --startSample;
  16179. bool matches = false;
  16180. const int index = (int) (startSample - bufferStart);
  16181. if (usesFloatingPointData)
  16182. {
  16183. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16184. if (sample1 >= magnitudeRangeMinimum
  16185. && sample1 <= magnitudeRangeMaximum)
  16186. {
  16187. matches = true;
  16188. }
  16189. else if (numChannels > 1)
  16190. {
  16191. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16192. matches = (sample2 >= magnitudeRangeMinimum
  16193. && sample2 <= magnitudeRangeMaximum);
  16194. }
  16195. }
  16196. else
  16197. {
  16198. const int sample1 = abs (tempBuffer[0] [index]);
  16199. if (sample1 >= intMagnitudeRangeMinimum
  16200. && sample1 <= intMagnitudeRangeMaximum)
  16201. {
  16202. matches = true;
  16203. }
  16204. else if (numChannels > 1)
  16205. {
  16206. const int sample2 = abs (tempBuffer[1][index]);
  16207. matches = (sample2 >= intMagnitudeRangeMinimum
  16208. && sample2 <= intMagnitudeRangeMaximum);
  16209. }
  16210. }
  16211. if (matches)
  16212. {
  16213. if (firstMatchPos < 0)
  16214. firstMatchPos = startSample;
  16215. if (++consecutive >= minimumConsecutiveSamples)
  16216. {
  16217. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16218. return -1;
  16219. return firstMatchPos;
  16220. }
  16221. }
  16222. else
  16223. {
  16224. consecutive = 0;
  16225. firstMatchPos = -1;
  16226. }
  16227. if (numSamplesToSearch > 0)
  16228. ++startSample;
  16229. }
  16230. if (numSamplesToSearch > 0)
  16231. numSamplesToSearch -= numThisTime;
  16232. else
  16233. numSamplesToSearch += numThisTime;
  16234. }
  16235. return -1;
  16236. }
  16237. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  16238. const String& formatName_,
  16239. const double rate,
  16240. const unsigned int numChannels_,
  16241. const unsigned int bitsPerSample_)
  16242. : sampleRate (rate),
  16243. numChannels (numChannels_),
  16244. bitsPerSample (bitsPerSample_),
  16245. usesFloatingPointData (false),
  16246. output (out),
  16247. formatName (formatName_)
  16248. {
  16249. }
  16250. AudioFormatWriter::~AudioFormatWriter()
  16251. {
  16252. delete output;
  16253. }
  16254. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  16255. int64 startSample,
  16256. int64 numSamplesToRead)
  16257. {
  16258. const int bufferSize = 16384;
  16259. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  16260. int* buffers [128];
  16261. zerostruct (buffers);
  16262. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16263. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16264. if (numSamplesToRead < 0)
  16265. numSamplesToRead = reader.lengthInSamples;
  16266. while (numSamplesToRead > 0)
  16267. {
  16268. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  16269. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  16270. return false;
  16271. if (reader.usesFloatingPointData != isFloatingPoint())
  16272. {
  16273. int** bufferChan = buffers;
  16274. while (*bufferChan != 0)
  16275. {
  16276. int* b = *bufferChan++;
  16277. if (isFloatingPoint())
  16278. {
  16279. // int -> float
  16280. const double factor = 1.0 / std::numeric_limits<int>::max();
  16281. for (int i = 0; i < numToDo; ++i)
  16282. ((float*) b)[i] = (float) (factor * b[i]);
  16283. }
  16284. else
  16285. {
  16286. // float -> int
  16287. for (int i = 0; i < numToDo; ++i)
  16288. {
  16289. const double samp = *(const float*) b;
  16290. if (samp <= -1.0)
  16291. *b++ = std::numeric_limits<int>::min();
  16292. else if (samp >= 1.0)
  16293. *b++ = std::numeric_limits<int>::max();
  16294. else
  16295. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16296. }
  16297. }
  16298. }
  16299. }
  16300. if (! write ((const int**) buffers, numToDo))
  16301. return false;
  16302. numSamplesToRead -= numToDo;
  16303. startSample += numToDo;
  16304. }
  16305. return true;
  16306. }
  16307. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  16308. int numSamplesToRead,
  16309. const int samplesPerBlock)
  16310. {
  16311. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  16312. int* buffers [128];
  16313. zerostruct (buffers);
  16314. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16315. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16316. while (numSamplesToRead > 0)
  16317. {
  16318. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  16319. AudioSourceChannelInfo info;
  16320. info.buffer = &tempBuffer;
  16321. info.startSample = 0;
  16322. info.numSamples = numToDo;
  16323. info.clearActiveBufferRegion();
  16324. source.getNextAudioBlock (info);
  16325. if (! isFloatingPoint())
  16326. {
  16327. int** bufferChan = buffers;
  16328. while (*bufferChan != 0)
  16329. {
  16330. int* b = *bufferChan++;
  16331. // float -> int
  16332. for (int j = numToDo; --j >= 0;)
  16333. {
  16334. const double samp = *(const float*) b;
  16335. if (samp <= -1.0)
  16336. *b++ = std::numeric_limits<int>::min();
  16337. else if (samp >= 1.0)
  16338. *b++ = std::numeric_limits<int>::max();
  16339. else
  16340. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16341. }
  16342. }
  16343. }
  16344. if (! write ((const int**) buffers, numToDo))
  16345. return false;
  16346. numSamplesToRead -= numToDo;
  16347. }
  16348. return true;
  16349. }
  16350. AudioFormat::AudioFormat (const String& name,
  16351. const StringArray& extensions)
  16352. : formatName (name),
  16353. fileExtensions (extensions)
  16354. {
  16355. }
  16356. AudioFormat::~AudioFormat()
  16357. {
  16358. }
  16359. const String& AudioFormat::getFormatName() const
  16360. {
  16361. return formatName;
  16362. }
  16363. const StringArray& AudioFormat::getFileExtensions() const
  16364. {
  16365. return fileExtensions;
  16366. }
  16367. bool AudioFormat::canHandleFile (const File& f)
  16368. {
  16369. for (int i = 0; i < fileExtensions.size(); ++i)
  16370. if (f.hasFileExtension (fileExtensions[i]))
  16371. return true;
  16372. return false;
  16373. }
  16374. bool AudioFormat::isCompressed()
  16375. {
  16376. return false;
  16377. }
  16378. const StringArray AudioFormat::getQualityOptions()
  16379. {
  16380. return StringArray();
  16381. }
  16382. END_JUCE_NAMESPACE
  16383. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16384. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  16385. BEGIN_JUCE_NAMESPACE
  16386. AudioFormatManager::AudioFormatManager()
  16387. : defaultFormatIndex (0)
  16388. {
  16389. }
  16390. AudioFormatManager::~AudioFormatManager()
  16391. {
  16392. clearFormats();
  16393. clearSingletonInstance();
  16394. }
  16395. juce_ImplementSingleton (AudioFormatManager);
  16396. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  16397. const bool makeThisTheDefaultFormat)
  16398. {
  16399. jassert (newFormat != 0);
  16400. if (newFormat != 0)
  16401. {
  16402. #if JUCE_DEBUG
  16403. for (int i = getNumKnownFormats(); --i >= 0;)
  16404. {
  16405. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  16406. {
  16407. jassertfalse; // trying to add the same format twice!
  16408. }
  16409. }
  16410. #endif
  16411. if (makeThisTheDefaultFormat)
  16412. defaultFormatIndex = getNumKnownFormats();
  16413. knownFormats.add (newFormat);
  16414. }
  16415. }
  16416. void AudioFormatManager::registerBasicFormats()
  16417. {
  16418. #if JUCE_MAC
  16419. registerFormat (new AiffAudioFormat(), true);
  16420. registerFormat (new WavAudioFormat(), false);
  16421. #else
  16422. registerFormat (new WavAudioFormat(), true);
  16423. registerFormat (new AiffAudioFormat(), false);
  16424. #endif
  16425. #if JUCE_USE_FLAC
  16426. registerFormat (new FlacAudioFormat(), false);
  16427. #endif
  16428. #if JUCE_USE_OGGVORBIS
  16429. registerFormat (new OggVorbisAudioFormat(), false);
  16430. #endif
  16431. }
  16432. void AudioFormatManager::clearFormats()
  16433. {
  16434. knownFormats.clear();
  16435. defaultFormatIndex = 0;
  16436. }
  16437. int AudioFormatManager::getNumKnownFormats() const
  16438. {
  16439. return knownFormats.size();
  16440. }
  16441. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  16442. {
  16443. return knownFormats [index];
  16444. }
  16445. AudioFormat* AudioFormatManager::getDefaultFormat() const
  16446. {
  16447. return getKnownFormat (defaultFormatIndex);
  16448. }
  16449. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  16450. {
  16451. String e (fileExtension);
  16452. if (! e.startsWithChar ('.'))
  16453. e = "." + e;
  16454. for (int i = 0; i < getNumKnownFormats(); ++i)
  16455. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  16456. return getKnownFormat(i);
  16457. return 0;
  16458. }
  16459. const String AudioFormatManager::getWildcardForAllFormats() const
  16460. {
  16461. StringArray allExtensions;
  16462. int i;
  16463. for (i = 0; i < getNumKnownFormats(); ++i)
  16464. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  16465. allExtensions.trim();
  16466. allExtensions.removeEmptyStrings();
  16467. String s;
  16468. for (i = 0; i < allExtensions.size(); ++i)
  16469. {
  16470. s << '*';
  16471. if (! allExtensions[i].startsWithChar ('.'))
  16472. s << '.';
  16473. s << allExtensions[i];
  16474. if (i < allExtensions.size() - 1)
  16475. s << ';';
  16476. }
  16477. return s;
  16478. }
  16479. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  16480. {
  16481. // you need to actually register some formats before the manager can
  16482. // use them to open a file!
  16483. jassert (getNumKnownFormats() > 0);
  16484. for (int i = 0; i < getNumKnownFormats(); ++i)
  16485. {
  16486. AudioFormat* const af = getKnownFormat(i);
  16487. if (af->canHandleFile (file))
  16488. {
  16489. InputStream* const in = file.createInputStream();
  16490. if (in != 0)
  16491. {
  16492. AudioFormatReader* const r = af->createReaderFor (in, true);
  16493. if (r != 0)
  16494. return r;
  16495. }
  16496. }
  16497. }
  16498. return 0;
  16499. }
  16500. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  16501. {
  16502. // you need to actually register some formats before the manager can
  16503. // use them to open a file!
  16504. jassert (getNumKnownFormats() > 0);
  16505. ScopedPointer <InputStream> in (audioFileStream);
  16506. if (in != 0)
  16507. {
  16508. const int64 originalStreamPos = in->getPosition();
  16509. for (int i = 0; i < getNumKnownFormats(); ++i)
  16510. {
  16511. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  16512. if (r != 0)
  16513. {
  16514. in.release();
  16515. return r;
  16516. }
  16517. in->setPosition (originalStreamPos);
  16518. // the stream that is passed-in must be capable of being repositioned so
  16519. // that all the formats can have a go at opening it.
  16520. jassert (in->getPosition() == originalStreamPos);
  16521. }
  16522. }
  16523. return 0;
  16524. }
  16525. END_JUCE_NAMESPACE
  16526. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  16527. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  16528. BEGIN_JUCE_NAMESPACE
  16529. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  16530. const int64 startSample_,
  16531. const int64 length_,
  16532. const bool deleteSourceWhenDeleted_)
  16533. : AudioFormatReader (0, source_->getFormatName()),
  16534. source (source_),
  16535. startSample (startSample_),
  16536. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  16537. {
  16538. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  16539. sampleRate = source->sampleRate;
  16540. bitsPerSample = source->bitsPerSample;
  16541. lengthInSamples = length;
  16542. numChannels = source->numChannels;
  16543. usesFloatingPointData = source->usesFloatingPointData;
  16544. }
  16545. AudioSubsectionReader::~AudioSubsectionReader()
  16546. {
  16547. if (deleteSourceWhenDeleted)
  16548. delete source;
  16549. }
  16550. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16551. int64 startSampleInFile, int numSamples)
  16552. {
  16553. if (startSampleInFile + numSamples > length)
  16554. {
  16555. for (int i = numDestChannels; --i >= 0;)
  16556. if (destSamples[i] != 0)
  16557. zeromem (destSamples[i], sizeof (int) * numSamples);
  16558. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  16559. if (numSamples <= 0)
  16560. return true;
  16561. }
  16562. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  16563. startSampleInFile + startSample, numSamples);
  16564. }
  16565. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  16566. int64 numSamples,
  16567. float& lowestLeft,
  16568. float& highestLeft,
  16569. float& lowestRight,
  16570. float& highestRight)
  16571. {
  16572. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  16573. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  16574. source->readMaxLevels (startSampleInFile + startSample,
  16575. numSamples,
  16576. lowestLeft,
  16577. highestLeft,
  16578. lowestRight,
  16579. highestRight);
  16580. }
  16581. END_JUCE_NAMESPACE
  16582. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  16583. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  16584. BEGIN_JUCE_NAMESPACE
  16585. const int timeBeforeDeletingReader = 2000;
  16586. struct AudioThumbnailDataFormat
  16587. {
  16588. char thumbnailMagic[4];
  16589. int samplesPerThumbSample;
  16590. int64 totalSamples; // source samples
  16591. int64 numFinishedSamples; // source samples
  16592. int numThumbnailSamples;
  16593. int numChannels;
  16594. int sampleRate;
  16595. char future[16];
  16596. char data[1];
  16597. void swapEndiannessIfNeeded() throw()
  16598. {
  16599. #if JUCE_BIG_ENDIAN
  16600. flip (samplesPerThumbSample);
  16601. flip (totalSamples);
  16602. flip (numFinishedSamples);
  16603. flip (numThumbnailSamples);
  16604. flip (numChannels);
  16605. flip (sampleRate);
  16606. #endif
  16607. }
  16608. private:
  16609. #if JUCE_BIG_ENDIAN
  16610. static void flip (int& n) { n = (int) ByteOrder::swap ((uint32) n); }
  16611. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  16612. #endif
  16613. };
  16614. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  16615. AudioFormatManager& formatManagerToUse_,
  16616. AudioThumbnailCache& cacheToUse)
  16617. : formatManagerToUse (formatManagerToUse_),
  16618. cache (cacheToUse),
  16619. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  16620. {
  16621. clear();
  16622. }
  16623. AudioThumbnail::~AudioThumbnail()
  16624. {
  16625. cache.removeThumbnail (this);
  16626. const ScopedLock sl (readerLock);
  16627. reader = 0;
  16628. }
  16629. void AudioThumbnail::setSource (InputSource* const newSource)
  16630. {
  16631. cache.removeThumbnail (this);
  16632. timerCallback(); // stops the timer and deletes the reader
  16633. source = newSource;
  16634. clear();
  16635. if (newSource != 0
  16636. && ! (cache.loadThumb (*this, newSource->hashCode())
  16637. && isFullyLoaded()))
  16638. {
  16639. {
  16640. const ScopedLock sl (readerLock);
  16641. reader = createReader();
  16642. }
  16643. if (reader != 0)
  16644. {
  16645. initialiseFromAudioFile (*reader);
  16646. cache.addThumbnail (this);
  16647. }
  16648. }
  16649. sendChangeMessage (this);
  16650. }
  16651. bool AudioThumbnail::useTimeSlice()
  16652. {
  16653. const ScopedLock sl (readerLock);
  16654. if (isFullyLoaded())
  16655. {
  16656. if (reader != 0)
  16657. startTimer (timeBeforeDeletingReader);
  16658. cache.removeThumbnail (this);
  16659. return false;
  16660. }
  16661. if (reader == 0)
  16662. reader = createReader();
  16663. if (reader != 0)
  16664. {
  16665. readNextBlockFromAudioFile (*reader);
  16666. stopTimer();
  16667. sendChangeMessage (this);
  16668. const bool justFinished = isFullyLoaded();
  16669. if (justFinished)
  16670. cache.storeThumb (*this, source->hashCode());
  16671. return ! justFinished;
  16672. }
  16673. return false;
  16674. }
  16675. AudioFormatReader* AudioThumbnail::createReader() const
  16676. {
  16677. if (source != 0)
  16678. {
  16679. InputStream* const audioFileStream = source->createInputStream();
  16680. if (audioFileStream != 0)
  16681. return formatManagerToUse.createReaderFor (audioFileStream);
  16682. }
  16683. return 0;
  16684. }
  16685. void AudioThumbnail::timerCallback()
  16686. {
  16687. stopTimer();
  16688. const ScopedLock sl (readerLock);
  16689. reader = 0;
  16690. }
  16691. void AudioThumbnail::clear()
  16692. {
  16693. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  16694. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16695. d->thumbnailMagic[0] = 'j';
  16696. d->thumbnailMagic[1] = 'a';
  16697. d->thumbnailMagic[2] = 't';
  16698. d->thumbnailMagic[3] = 'm';
  16699. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  16700. d->totalSamples = 0;
  16701. d->numFinishedSamples = 0;
  16702. d->numThumbnailSamples = 0;
  16703. d->numChannels = 0;
  16704. d->sampleRate = 0;
  16705. numSamplesCached = 0;
  16706. cacheNeedsRefilling = true;
  16707. }
  16708. void AudioThumbnail::loadFrom (InputStream& input)
  16709. {
  16710. const ScopedLock sl (readerLock);
  16711. data.setSize (0);
  16712. input.readIntoMemoryBlock (data);
  16713. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16714. d->swapEndiannessIfNeeded();
  16715. if (! (d->thumbnailMagic[0] == 'j'
  16716. && d->thumbnailMagic[1] == 'a'
  16717. && d->thumbnailMagic[2] == 't'
  16718. && d->thumbnailMagic[3] == 'm'))
  16719. {
  16720. clear();
  16721. }
  16722. numSamplesCached = 0;
  16723. cacheNeedsRefilling = true;
  16724. }
  16725. void AudioThumbnail::saveTo (OutputStream& output) const
  16726. {
  16727. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16728. d->swapEndiannessIfNeeded();
  16729. output.write (data.getData(), (int) data.getSize());
  16730. d->swapEndiannessIfNeeded();
  16731. }
  16732. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  16733. {
  16734. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  16735. d->totalSamples = fileReader.lengthInSamples;
  16736. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  16737. d->numFinishedSamples = 0;
  16738. d->sampleRate = roundToInt (fileReader.sampleRate);
  16739. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  16740. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  16741. d = (AudioThumbnailDataFormat*) data.getData();
  16742. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  16743. return d->totalSamples > 0;
  16744. }
  16745. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  16746. {
  16747. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16748. if (d->numFinishedSamples < d->totalSamples)
  16749. {
  16750. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  16751. generateSection (fileReader,
  16752. d->numFinishedSamples,
  16753. numToDo);
  16754. d->numFinishedSamples += numToDo;
  16755. }
  16756. cacheNeedsRefilling = true;
  16757. return (d->numFinishedSamples < d->totalSamples);
  16758. }
  16759. int AudioThumbnail::getNumChannels() const throw()
  16760. {
  16761. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16762. jassert (d != 0);
  16763. return d->numChannels;
  16764. }
  16765. double AudioThumbnail::getTotalLength() const throw()
  16766. {
  16767. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16768. jassert (d != 0);
  16769. if (d->sampleRate > 0)
  16770. return d->totalSamples / (double)d->sampleRate;
  16771. else
  16772. return 0.0;
  16773. }
  16774. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  16775. int64 startSample,
  16776. int numSamples)
  16777. {
  16778. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16779. jassert (d != 0);
  16780. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  16781. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  16782. char* l = getChannelData (0);
  16783. char* r = getChannelData (1);
  16784. for (int i = firstDataPos; i < lastDataPos; ++i)
  16785. {
  16786. const int sourceStart = i * d->samplesPerThumbSample;
  16787. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  16788. float lowestLeft, highestLeft, lowestRight, highestRight;
  16789. fileReader.readMaxLevels (sourceStart,
  16790. sourceEnd - sourceStart,
  16791. lowestLeft,
  16792. highestLeft,
  16793. lowestRight,
  16794. highestRight);
  16795. int n = i * 2;
  16796. if (r != 0)
  16797. {
  16798. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16799. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  16800. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16801. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  16802. }
  16803. else
  16804. {
  16805. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16806. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16807. }
  16808. }
  16809. }
  16810. char* AudioThumbnail::getChannelData (int channel) const
  16811. {
  16812. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16813. jassert (d != 0);
  16814. if (channel >= 0 && channel < d->numChannels)
  16815. return d->data + (channel * 2 * d->numThumbnailSamples);
  16816. return 0;
  16817. }
  16818. bool AudioThumbnail::isFullyLoaded() const throw()
  16819. {
  16820. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16821. jassert (d != 0);
  16822. return d->numFinishedSamples >= d->totalSamples;
  16823. }
  16824. void AudioThumbnail::refillCache (const int numSamples,
  16825. double startTime,
  16826. const double timePerPixel)
  16827. {
  16828. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16829. jassert (d != 0);
  16830. if (numSamples <= 0
  16831. || timePerPixel <= 0.0
  16832. || d->sampleRate <= 0)
  16833. {
  16834. numSamplesCached = 0;
  16835. cacheNeedsRefilling = true;
  16836. return;
  16837. }
  16838. if (numSamples == numSamplesCached
  16839. && numChannelsCached == d->numChannels
  16840. && startTime == cachedStart
  16841. && timePerPixel == cachedTimePerPixel
  16842. && ! cacheNeedsRefilling)
  16843. {
  16844. return;
  16845. }
  16846. numSamplesCached = numSamples;
  16847. numChannelsCached = d->numChannels;
  16848. cachedStart = startTime;
  16849. cachedTimePerPixel = timePerPixel;
  16850. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  16851. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  16852. const ScopedLock sl (readerLock);
  16853. cacheNeedsRefilling = false;
  16854. if (needExtraDetail && reader == 0)
  16855. reader = createReader();
  16856. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  16857. {
  16858. startTimer (timeBeforeDeletingReader);
  16859. char* cacheData = static_cast <char*> (cachedLevels.getData());
  16860. int sample = roundToInt (startTime * d->sampleRate);
  16861. for (int i = numSamples; --i >= 0;)
  16862. {
  16863. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  16864. if (sample >= 0)
  16865. {
  16866. if (sample >= reader->lengthInSamples)
  16867. break;
  16868. float lmin, lmax, rmin, rmax;
  16869. reader->readMaxLevels (sample,
  16870. jmax (1, nextSample - sample),
  16871. lmin, lmax, rmin, rmax);
  16872. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  16873. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  16874. if (numChannelsCached > 1)
  16875. {
  16876. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  16877. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  16878. }
  16879. cacheData += 2 * numChannelsCached;
  16880. }
  16881. startTime += timePerPixel;
  16882. sample = nextSample;
  16883. }
  16884. }
  16885. else
  16886. {
  16887. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  16888. {
  16889. char* const channelData = getChannelData (channelNum);
  16890. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  16891. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  16892. startTime = cachedStart;
  16893. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  16894. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  16895. for (int i = numSamples; --i >= 0;)
  16896. {
  16897. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  16898. if (sample >= 0 && channelData != 0)
  16899. {
  16900. char mx = -128;
  16901. char mn = 127;
  16902. while (sample <= nextSample)
  16903. {
  16904. if (sample >= numFinished)
  16905. break;
  16906. const int n = sample << 1;
  16907. const char sampMin = channelData [n];
  16908. const char sampMax = channelData [n + 1];
  16909. if (sampMin < mn)
  16910. mn = sampMin;
  16911. if (sampMax > mx)
  16912. mx = sampMax;
  16913. ++sample;
  16914. }
  16915. if (mn <= mx)
  16916. {
  16917. cacheData[0] = mn;
  16918. cacheData[1] = mx;
  16919. }
  16920. else
  16921. {
  16922. cacheData[0] = 1;
  16923. cacheData[1] = 0;
  16924. }
  16925. }
  16926. else
  16927. {
  16928. cacheData[0] = 1;
  16929. cacheData[1] = 0;
  16930. }
  16931. cacheData += numChannelsCached * 2;
  16932. startTime += timePerPixel;
  16933. sample = nextSample;
  16934. }
  16935. }
  16936. }
  16937. }
  16938. void AudioThumbnail::drawChannel (Graphics& g,
  16939. int x, int y, int w, int h,
  16940. double startTime,
  16941. double endTime,
  16942. int channelNum,
  16943. const float verticalZoomFactor)
  16944. {
  16945. refillCache (w, startTime, (endTime - startTime) / w);
  16946. if (numSamplesCached >= w
  16947. && channelNum >= 0
  16948. && channelNum < numChannelsCached)
  16949. {
  16950. const float topY = (float) y;
  16951. const float bottomY = topY + h;
  16952. const float midY = topY + h * 0.5f;
  16953. const float vscale = verticalZoomFactor * h / 256.0f;
  16954. const Rectangle<int> clip (g.getClipBounds());
  16955. const int skipLeft = jlimit (0, w, clip.getX() - x);
  16956. w -= skipLeft;
  16957. x += skipLeft;
  16958. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  16959. + (channelNum << 1)
  16960. + skipLeft * (numChannelsCached << 1);
  16961. while (--w >= 0)
  16962. {
  16963. const char mn = cacheData[0];
  16964. const char mx = cacheData[1];
  16965. cacheData += numChannelsCached << 1;
  16966. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  16967. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  16968. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  16969. ++x;
  16970. if (x >= clip.getRight())
  16971. break;
  16972. }
  16973. }
  16974. }
  16975. END_JUCE_NAMESPACE
  16976. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  16977. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  16978. BEGIN_JUCE_NAMESPACE
  16979. struct ThumbnailCacheEntry
  16980. {
  16981. int64 hash;
  16982. uint32 lastUsed;
  16983. MemoryBlock data;
  16984. juce_UseDebuggingNewOperator
  16985. };
  16986. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  16987. : TimeSliceThread ("thumb cache"),
  16988. maxNumThumbsToStore (maxNumThumbsToStore_)
  16989. {
  16990. startThread (2);
  16991. }
  16992. AudioThumbnailCache::~AudioThumbnailCache()
  16993. {
  16994. }
  16995. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  16996. {
  16997. for (int i = thumbs.size(); --i >= 0;)
  16998. {
  16999. if (thumbs[i]->hash == hashCode)
  17000. {
  17001. MemoryInputStream in (thumbs[i]->data, false);
  17002. thumb.loadFrom (in);
  17003. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  17004. return true;
  17005. }
  17006. }
  17007. return false;
  17008. }
  17009. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  17010. const int64 hashCode)
  17011. {
  17012. MemoryOutputStream out;
  17013. thumb.saveTo (out);
  17014. ThumbnailCacheEntry* te = 0;
  17015. for (int i = thumbs.size(); --i >= 0;)
  17016. {
  17017. if (thumbs[i]->hash == hashCode)
  17018. {
  17019. te = thumbs[i];
  17020. break;
  17021. }
  17022. }
  17023. if (te == 0)
  17024. {
  17025. te = new ThumbnailCacheEntry();
  17026. te->hash = hashCode;
  17027. if (thumbs.size() < maxNumThumbsToStore)
  17028. {
  17029. thumbs.add (te);
  17030. }
  17031. else
  17032. {
  17033. int oldest = 0;
  17034. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  17035. int i;
  17036. for (i = thumbs.size(); --i >= 0;)
  17037. if (thumbs[i]->lastUsed < oldestTime)
  17038. oldest = i;
  17039. thumbs.set (i, te);
  17040. }
  17041. }
  17042. te->lastUsed = Time::getMillisecondCounter();
  17043. te->data.setSize (0);
  17044. te->data.append (out.getData(), out.getDataSize());
  17045. }
  17046. void AudioThumbnailCache::clear()
  17047. {
  17048. thumbs.clear();
  17049. }
  17050. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  17051. {
  17052. addTimeSliceClient (thumb);
  17053. }
  17054. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  17055. {
  17056. removeTimeSliceClient (thumb);
  17057. }
  17058. END_JUCE_NAMESPACE
  17059. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  17060. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17061. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  17062. #if ! JUCE_WINDOWS
  17063. #include <QuickTime/Movies.h>
  17064. #include <QuickTime/QTML.h>
  17065. #include <QuickTime/QuickTimeComponents.h>
  17066. #include <QuickTime/MediaHandlers.h>
  17067. #include <QuickTime/ImageCodec.h>
  17068. #else
  17069. #if JUCE_MSVC
  17070. #pragma warning (push)
  17071. #pragma warning (disable : 4100)
  17072. #endif
  17073. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  17074. add its header directory to your include path.
  17075. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  17076. flag in juce_Config.h
  17077. */
  17078. #include <Movies.h>
  17079. #include <QTML.h>
  17080. #include <QuickTimeComponents.h>
  17081. #include <MediaHandlers.h>
  17082. #include <ImageCodec.h>
  17083. #if JUCE_MSVC
  17084. #pragma warning (pop)
  17085. #endif
  17086. #endif
  17087. BEGIN_JUCE_NAMESPACE
  17088. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  17089. static const char* const quickTimeFormatName = "QuickTime file";
  17090. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", 0 };
  17091. class QTAudioReader : public AudioFormatReader
  17092. {
  17093. public:
  17094. QTAudioReader (InputStream* const input_, const int trackNum_)
  17095. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  17096. ok (false),
  17097. movie (0),
  17098. trackNum (trackNum_),
  17099. lastSampleRead (0),
  17100. lastThreadId (0),
  17101. extractor (0),
  17102. dataHandle (0)
  17103. {
  17104. bufferList.calloc (256, 1);
  17105. #if JUCE_WINDOWS
  17106. if (InitializeQTML (0) != noErr)
  17107. return;
  17108. #endif
  17109. if (EnterMovies() != noErr)
  17110. return;
  17111. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  17112. if (! opened)
  17113. return;
  17114. {
  17115. const int numTracks = GetMovieTrackCount (movie);
  17116. int trackCount = 0;
  17117. for (int i = 1; i <= numTracks; ++i)
  17118. {
  17119. track = GetMovieIndTrack (movie, i);
  17120. media = GetTrackMedia (track);
  17121. OSType mediaType;
  17122. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  17123. if (mediaType == SoundMediaType
  17124. && trackCount++ == trackNum_)
  17125. {
  17126. ok = true;
  17127. break;
  17128. }
  17129. }
  17130. }
  17131. if (! ok)
  17132. return;
  17133. ok = false;
  17134. lengthInSamples = GetMediaDecodeDuration (media);
  17135. usesFloatingPointData = false;
  17136. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  17137. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  17138. / GetMediaTimeScale (media);
  17139. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  17140. unsigned long output_layout_size;
  17141. err = MovieAudioExtractionGetPropertyInfo (extractor,
  17142. kQTPropertyClass_MovieAudioExtraction_Audio,
  17143. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17144. 0, &output_layout_size, 0);
  17145. if (err != noErr)
  17146. return;
  17147. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  17148. qt_audio_channel_layout.calloc (output_layout_size, 1);
  17149. err = MovieAudioExtractionGetProperty (extractor,
  17150. kQTPropertyClass_MovieAudioExtraction_Audio,
  17151. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17152. output_layout_size, qt_audio_channel_layout, 0);
  17153. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  17154. err = MovieAudioExtractionSetProperty (extractor,
  17155. kQTPropertyClass_MovieAudioExtraction_Audio,
  17156. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17157. output_layout_size,
  17158. qt_audio_channel_layout);
  17159. err = MovieAudioExtractionGetProperty (extractor,
  17160. kQTPropertyClass_MovieAudioExtraction_Audio,
  17161. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17162. sizeof (inputStreamDesc),
  17163. &inputStreamDesc, 0);
  17164. if (err != noErr)
  17165. return;
  17166. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  17167. | kAudioFormatFlagIsPacked
  17168. | kAudioFormatFlagsNativeEndian;
  17169. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  17170. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  17171. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  17172. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  17173. err = MovieAudioExtractionSetProperty (extractor,
  17174. kQTPropertyClass_MovieAudioExtraction_Audio,
  17175. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17176. sizeof (inputStreamDesc),
  17177. &inputStreamDesc);
  17178. if (err != noErr)
  17179. return;
  17180. Boolean allChannelsDiscrete = false;
  17181. err = MovieAudioExtractionSetProperty (extractor,
  17182. kQTPropertyClass_MovieAudioExtraction_Movie,
  17183. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  17184. sizeof (allChannelsDiscrete),
  17185. &allChannelsDiscrete);
  17186. if (err != noErr)
  17187. return;
  17188. bufferList->mNumberBuffers = 1;
  17189. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  17190. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  17191. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  17192. bufferList->mBuffers[0].mData = dataBuffer;
  17193. sampleRate = inputStreamDesc.mSampleRate;
  17194. bitsPerSample = 16;
  17195. numChannels = inputStreamDesc.mChannelsPerFrame;
  17196. detachThread();
  17197. ok = true;
  17198. }
  17199. ~QTAudioReader()
  17200. {
  17201. if (dataHandle != 0)
  17202. DisposeHandle (dataHandle);
  17203. if (extractor != 0)
  17204. {
  17205. MovieAudioExtractionEnd (extractor);
  17206. extractor = 0;
  17207. }
  17208. checkThreadIsAttached();
  17209. DisposeMovie (movie);
  17210. #if JUCE_MAC
  17211. ExitMoviesOnThread ();
  17212. #endif
  17213. }
  17214. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17215. int64 startSampleInFile, int numSamples)
  17216. {
  17217. checkThreadIsAttached();
  17218. while (numSamples > 0)
  17219. {
  17220. if (! loadFrame ((int) startSampleInFile))
  17221. return false;
  17222. const int numToDo = jmin (numSamples, samplesPerFrame);
  17223. for (int j = numDestChannels; --j >= 0;)
  17224. {
  17225. if (destSamples[j] != 0)
  17226. {
  17227. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  17228. for (int i = 0; i < numToDo; ++i)
  17229. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  17230. }
  17231. }
  17232. startOffsetInDestBuffer += numToDo;
  17233. startSampleInFile += numToDo;
  17234. numSamples -= numToDo;
  17235. }
  17236. detachThread();
  17237. return true;
  17238. }
  17239. bool loadFrame (const int sampleNum)
  17240. {
  17241. if (lastSampleRead != sampleNum)
  17242. {
  17243. TimeRecord time;
  17244. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  17245. time.base = 0;
  17246. time.value.hi = 0;
  17247. time.value.lo = (UInt32) sampleNum;
  17248. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  17249. kQTPropertyClass_MovieAudioExtraction_Movie,
  17250. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  17251. sizeof (time), &time);
  17252. if (err != noErr)
  17253. return false;
  17254. }
  17255. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  17256. UInt32 outFlags = 0;
  17257. UInt32 actualNumSamples = samplesPerFrame;
  17258. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  17259. bufferList, &outFlags);
  17260. lastSampleRead = sampleNum + samplesPerFrame;
  17261. return err == noErr;
  17262. }
  17263. juce_UseDebuggingNewOperator
  17264. bool ok;
  17265. private:
  17266. Movie movie;
  17267. Media media;
  17268. Track track;
  17269. const int trackNum;
  17270. double trackUnitsPerFrame;
  17271. int samplesPerFrame;
  17272. int lastSampleRead;
  17273. Thread::ThreadID lastThreadId;
  17274. MovieAudioExtractionRef extractor;
  17275. AudioStreamBasicDescription inputStreamDesc;
  17276. HeapBlock <AudioBufferList> bufferList;
  17277. HeapBlock <char> dataBuffer;
  17278. Handle dataHandle;
  17279. void checkThreadIsAttached()
  17280. {
  17281. #if JUCE_MAC
  17282. if (Thread::getCurrentThreadId() != lastThreadId)
  17283. EnterMoviesOnThread (0);
  17284. AttachMovieToCurrentThread (movie);
  17285. #endif
  17286. }
  17287. void detachThread()
  17288. {
  17289. #if JUCE_MAC
  17290. DetachMovieFromCurrentThread (movie);
  17291. #endif
  17292. }
  17293. QTAudioReader (const QTAudioReader&);
  17294. QTAudioReader& operator= (const QTAudioReader&);
  17295. };
  17296. QuickTimeAudioFormat::QuickTimeAudioFormat()
  17297. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  17298. {
  17299. }
  17300. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  17301. {
  17302. }
  17303. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  17304. {
  17305. return Array<int>();
  17306. }
  17307. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  17308. {
  17309. return Array<int>();
  17310. }
  17311. bool QuickTimeAudioFormat::canDoStereo()
  17312. {
  17313. return true;
  17314. }
  17315. bool QuickTimeAudioFormat::canDoMono()
  17316. {
  17317. return true;
  17318. }
  17319. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  17320. const bool deleteStreamIfOpeningFails)
  17321. {
  17322. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  17323. if (r->ok)
  17324. return r.release();
  17325. if (! deleteStreamIfOpeningFails)
  17326. r->input = 0;
  17327. return 0;
  17328. }
  17329. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  17330. double /*sampleRateToUse*/,
  17331. unsigned int /*numberOfChannels*/,
  17332. int /*bitsPerSample*/,
  17333. const StringPairArray& /*metadataValues*/,
  17334. int /*qualityOptionIndex*/)
  17335. {
  17336. jassertfalse; // not yet implemented!
  17337. return 0;
  17338. }
  17339. END_JUCE_NAMESPACE
  17340. #endif
  17341. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17342. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  17343. BEGIN_JUCE_NAMESPACE
  17344. static const char* const wavFormatName = "WAV file";
  17345. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  17346. const char* const WavAudioFormat::bwavDescription = "bwav description";
  17347. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  17348. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  17349. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  17350. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  17351. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  17352. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  17353. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  17354. const String& originator,
  17355. const String& originatorRef,
  17356. const Time& date,
  17357. const int64 timeReferenceSamples,
  17358. const String& codingHistory)
  17359. {
  17360. StringPairArray m;
  17361. m.set (bwavDescription, description);
  17362. m.set (bwavOriginator, originator);
  17363. m.set (bwavOriginatorRef, originatorRef);
  17364. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  17365. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  17366. m.set (bwavTimeReference, String (timeReferenceSamples));
  17367. m.set (bwavCodingHistory, codingHistory);
  17368. return m;
  17369. }
  17370. #if JUCE_MSVC
  17371. #pragma pack (push, 1)
  17372. #define PACKED
  17373. #elif JUCE_GCC
  17374. #define PACKED __attribute__((packed))
  17375. #else
  17376. #define PACKED
  17377. #endif
  17378. struct BWAVChunk
  17379. {
  17380. char description [256];
  17381. char originator [32];
  17382. char originatorRef [32];
  17383. char originationDate [10];
  17384. char originationTime [8];
  17385. uint32 timeRefLow;
  17386. uint32 timeRefHigh;
  17387. uint16 version;
  17388. uint8 umid[64];
  17389. uint8 reserved[190];
  17390. char codingHistory[1];
  17391. void copyTo (StringPairArray& values) const
  17392. {
  17393. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  17394. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  17395. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  17396. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  17397. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  17398. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  17399. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  17400. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  17401. values.set (WavAudioFormat::bwavTimeReference, String (time));
  17402. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  17403. }
  17404. static MemoryBlock createFrom (const StringPairArray& values)
  17405. {
  17406. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  17407. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17408. data.fillWith (0);
  17409. BWAVChunk* b = (BWAVChunk*) data.getData();
  17410. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17411. // as they get called in the right order..
  17412. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  17413. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  17414. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  17415. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  17416. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  17417. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  17418. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  17419. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  17420. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  17421. if (b->description[0] != 0
  17422. || b->originator[0] != 0
  17423. || b->originationDate[0] != 0
  17424. || b->originationTime[0] != 0
  17425. || b->codingHistory[0] != 0
  17426. || time != 0)
  17427. {
  17428. return data;
  17429. }
  17430. return MemoryBlock();
  17431. }
  17432. } PACKED;
  17433. struct SMPLChunk
  17434. {
  17435. struct SampleLoop
  17436. {
  17437. uint32 identifier;
  17438. uint32 type;
  17439. uint32 start;
  17440. uint32 end;
  17441. uint32 fraction;
  17442. uint32 playCount;
  17443. } PACKED;
  17444. uint32 manufacturer;
  17445. uint32 product;
  17446. uint32 samplePeriod;
  17447. uint32 midiUnityNote;
  17448. uint32 midiPitchFraction;
  17449. uint32 smpteFormat;
  17450. uint32 smpteOffset;
  17451. uint32 numSampleLoops;
  17452. uint32 samplerData;
  17453. SampleLoop loops[1];
  17454. void copyTo (StringPairArray& values, const int totalSize) const
  17455. {
  17456. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  17457. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  17458. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  17459. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  17460. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  17461. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  17462. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  17463. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  17464. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  17465. for (uint32 i = 0; i < numSampleLoops; ++i)
  17466. {
  17467. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  17468. break;
  17469. const String prefix ("Loop" + String(i));
  17470. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  17471. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  17472. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  17473. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  17474. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  17475. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  17476. }
  17477. }
  17478. static MemoryBlock createFrom (const StringPairArray& values)
  17479. {
  17480. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  17481. if (numLoops <= 0)
  17482. return MemoryBlock();
  17483. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  17484. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17485. data.fillWith (0);
  17486. SMPLChunk* s = (SMPLChunk*) data.getData();
  17487. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17488. // as they get called in the right order..
  17489. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  17490. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  17491. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  17492. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  17493. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  17494. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  17495. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  17496. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  17497. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  17498. for (int i = 0; i < numLoops; ++i)
  17499. {
  17500. const String prefix ("Loop" + String(i));
  17501. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  17502. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  17503. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  17504. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  17505. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  17506. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  17507. }
  17508. return data;
  17509. }
  17510. } PACKED;
  17511. struct ExtensibleWavSubFormat
  17512. {
  17513. uint32 data1;
  17514. uint16 data2;
  17515. uint16 data3;
  17516. uint8 data4[8];
  17517. } PACKED;
  17518. #if JUCE_MSVC
  17519. #pragma pack (pop)
  17520. #endif
  17521. #undef PACKED
  17522. class WavAudioFormatReader : public AudioFormatReader
  17523. {
  17524. int bytesPerFrame;
  17525. int64 dataChunkStart, dataLength;
  17526. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17527. WavAudioFormatReader (const WavAudioFormatReader&);
  17528. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  17529. public:
  17530. int64 bwavChunkStart, bwavSize;
  17531. WavAudioFormatReader (InputStream* const in)
  17532. : AudioFormatReader (in, TRANS (wavFormatName)),
  17533. dataLength (0),
  17534. bwavChunkStart (0),
  17535. bwavSize (0)
  17536. {
  17537. if (input->readInt() == chunkName ("RIFF"))
  17538. {
  17539. const uint32 len = (uint32) input->readInt();
  17540. const int64 end = input->getPosition() + len;
  17541. bool hasGotType = false;
  17542. bool hasGotData = false;
  17543. if (input->readInt() == chunkName ("WAVE"))
  17544. {
  17545. while (input->getPosition() < end
  17546. && ! input->isExhausted())
  17547. {
  17548. const int chunkType = input->readInt();
  17549. uint32 length = (uint32) input->readInt();
  17550. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  17551. if (chunkType == chunkName ("fmt "))
  17552. {
  17553. // read the format chunk
  17554. const unsigned short format = input->readShort();
  17555. const short numChans = input->readShort();
  17556. sampleRate = input->readInt();
  17557. const int bytesPerSec = input->readInt();
  17558. numChannels = numChans;
  17559. bytesPerFrame = bytesPerSec / (int)sampleRate;
  17560. bitsPerSample = 8 * bytesPerFrame / numChans;
  17561. if (format == 3)
  17562. {
  17563. usesFloatingPointData = true;
  17564. }
  17565. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  17566. {
  17567. if (length < 40) // too short
  17568. {
  17569. bytesPerFrame = 0;
  17570. }
  17571. else
  17572. {
  17573. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  17574. ExtensibleWavSubFormat subFormat;
  17575. subFormat.data1 = input->readInt();
  17576. subFormat.data2 = input->readShort();
  17577. subFormat.data3 = input->readShort();
  17578. input->read (subFormat.data4, sizeof (subFormat.data4));
  17579. const ExtensibleWavSubFormat pcmFormat
  17580. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  17581. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  17582. {
  17583. const ExtensibleWavSubFormat ambisonicFormat
  17584. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  17585. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  17586. bytesPerFrame = 0;
  17587. }
  17588. }
  17589. }
  17590. else if (format != 1)
  17591. {
  17592. bytesPerFrame = 0;
  17593. }
  17594. hasGotType = true;
  17595. }
  17596. else if (chunkType == chunkName ("data"))
  17597. {
  17598. // get the data chunk's position
  17599. dataLength = length;
  17600. dataChunkStart = input->getPosition();
  17601. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  17602. hasGotData = true;
  17603. }
  17604. else if (chunkType == chunkName ("bext"))
  17605. {
  17606. bwavChunkStart = input->getPosition();
  17607. bwavSize = length;
  17608. // Broadcast-wav extension chunk..
  17609. HeapBlock <BWAVChunk> bwav;
  17610. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  17611. input->read (bwav, length);
  17612. bwav->copyTo (metadataValues);
  17613. }
  17614. else if (chunkType == chunkName ("smpl"))
  17615. {
  17616. HeapBlock <SMPLChunk> smpl;
  17617. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  17618. input->read (smpl, length);
  17619. smpl->copyTo (metadataValues, length);
  17620. }
  17621. else if (chunkEnd <= input->getPosition())
  17622. {
  17623. break;
  17624. }
  17625. input->setPosition (chunkEnd);
  17626. }
  17627. }
  17628. }
  17629. }
  17630. ~WavAudioFormatReader()
  17631. {
  17632. }
  17633. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17634. int64 startSampleInFile, int numSamples)
  17635. {
  17636. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  17637. if (samplesAvailable < numSamples)
  17638. {
  17639. for (int i = numDestChannels; --i >= 0;)
  17640. if (destSamples[i] != 0)
  17641. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  17642. numSamples = (int) samplesAvailable;
  17643. }
  17644. if (numSamples <= 0)
  17645. return true;
  17646. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  17647. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  17648. char tempBuffer [tempBufSize];
  17649. while (numSamples > 0)
  17650. {
  17651. int* left = destSamples[0];
  17652. if (left != 0)
  17653. left += startOffsetInDestBuffer;
  17654. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  17655. if (right != 0)
  17656. right += startOffsetInDestBuffer;
  17657. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  17658. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  17659. if (bytesRead < numThisTime * bytesPerFrame)
  17660. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  17661. if (bitsPerSample == 16)
  17662. {
  17663. const short* src = reinterpret_cast <const short*> (tempBuffer);
  17664. if (numChannels > 1)
  17665. {
  17666. if (left == 0)
  17667. {
  17668. for (int i = numThisTime; --i >= 0;)
  17669. {
  17670. ++src;
  17671. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17672. }
  17673. }
  17674. else if (right == 0)
  17675. {
  17676. for (int i = numThisTime; --i >= 0;)
  17677. {
  17678. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17679. ++src;
  17680. }
  17681. }
  17682. else
  17683. {
  17684. for (int i = numThisTime; --i >= 0;)
  17685. {
  17686. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17687. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17688. }
  17689. }
  17690. }
  17691. else
  17692. {
  17693. for (int i = numThisTime; --i >= 0;)
  17694. {
  17695. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17696. }
  17697. }
  17698. }
  17699. else if (bitsPerSample == 24)
  17700. {
  17701. const char* src = tempBuffer;
  17702. if (numChannels > 1)
  17703. {
  17704. if (left == 0)
  17705. {
  17706. for (int i = numThisTime; --i >= 0;)
  17707. {
  17708. src += 3;
  17709. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17710. src += 3;
  17711. }
  17712. }
  17713. else if (right == 0)
  17714. {
  17715. for (int i = numThisTime; --i >= 0;)
  17716. {
  17717. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17718. src += 6;
  17719. }
  17720. }
  17721. else
  17722. {
  17723. for (int i = 0; i < numThisTime; ++i)
  17724. {
  17725. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17726. src += 3;
  17727. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17728. src += 3;
  17729. }
  17730. }
  17731. }
  17732. else
  17733. {
  17734. for (int i = 0; i < numThisTime; ++i)
  17735. {
  17736. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17737. src += 3;
  17738. }
  17739. }
  17740. }
  17741. else if (bitsPerSample == 32)
  17742. {
  17743. const unsigned int* src = (const unsigned int*) tempBuffer;
  17744. unsigned int* l = (unsigned int*) left;
  17745. unsigned int* r = (unsigned int*) right;
  17746. if (numChannels > 1)
  17747. {
  17748. if (l == 0)
  17749. {
  17750. for (int i = numThisTime; --i >= 0;)
  17751. {
  17752. ++src;
  17753. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17754. }
  17755. }
  17756. else if (r == 0)
  17757. {
  17758. for (int i = numThisTime; --i >= 0;)
  17759. {
  17760. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17761. ++src;
  17762. }
  17763. }
  17764. else
  17765. {
  17766. for (int i = numThisTime; --i >= 0;)
  17767. {
  17768. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17769. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17770. }
  17771. }
  17772. }
  17773. else
  17774. {
  17775. for (int i = numThisTime; --i >= 0;)
  17776. {
  17777. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17778. }
  17779. }
  17780. left = (int*)l;
  17781. right = (int*)r;
  17782. }
  17783. else if (bitsPerSample == 8)
  17784. {
  17785. const unsigned char* src = (const unsigned char*) tempBuffer;
  17786. if (numChannels > 1)
  17787. {
  17788. if (left == 0)
  17789. {
  17790. for (int i = numThisTime; --i >= 0;)
  17791. {
  17792. ++src;
  17793. *right++ = ((int) *src++ - 128) << 24;
  17794. }
  17795. }
  17796. else if (right == 0)
  17797. {
  17798. for (int i = numThisTime; --i >= 0;)
  17799. {
  17800. *left++ = ((int) *src++ - 128) << 24;
  17801. ++src;
  17802. }
  17803. }
  17804. else
  17805. {
  17806. for (int i = numThisTime; --i >= 0;)
  17807. {
  17808. *left++ = ((int) *src++ - 128) << 24;
  17809. *right++ = ((int) *src++ - 128) << 24;
  17810. }
  17811. }
  17812. }
  17813. else
  17814. {
  17815. for (int i = numThisTime; --i >= 0;)
  17816. {
  17817. *left++ = ((int)*src++ - 128) << 24;
  17818. }
  17819. }
  17820. }
  17821. startOffsetInDestBuffer += numThisTime;
  17822. numSamples -= numThisTime;
  17823. }
  17824. if (numSamples > 0)
  17825. {
  17826. for (int i = numDestChannels; --i >= 0;)
  17827. if (destSamples[i] != 0)
  17828. zeromem (destSamples[i] + startOffsetInDestBuffer,
  17829. sizeof (int) * numSamples);
  17830. }
  17831. return true;
  17832. }
  17833. juce_UseDebuggingNewOperator
  17834. };
  17835. class WavAudioFormatWriter : public AudioFormatWriter
  17836. {
  17837. MemoryBlock tempBlock, bwavChunk, smplChunk;
  17838. uint32 lengthInSamples, bytesWritten;
  17839. int64 headerPosition;
  17840. bool writeFailed;
  17841. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17842. WavAudioFormatWriter (const WavAudioFormatWriter&);
  17843. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  17844. void writeHeader()
  17845. {
  17846. const bool seekedOk = output->setPosition (headerPosition);
  17847. (void) seekedOk;
  17848. // if this fails, you've given it an output stream that can't seek! It needs
  17849. // to be able to seek back to write the header
  17850. jassert (seekedOk);
  17851. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  17852. output->writeInt (chunkName ("RIFF"));
  17853. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  17854. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  17855. output->writeInt (chunkName ("WAVE"));
  17856. output->writeInt (chunkName ("fmt "));
  17857. output->writeInt (16);
  17858. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  17859. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  17860. output->writeShort ((short) numChannels);
  17861. output->writeInt ((int) sampleRate);
  17862. output->writeInt (bytesPerFrame * (int) sampleRate);
  17863. output->writeShort ((short) bytesPerFrame);
  17864. output->writeShort ((short) bitsPerSample);
  17865. if (bwavChunk.getSize() > 0)
  17866. {
  17867. output->writeInt (chunkName ("bext"));
  17868. output->writeInt ((int) bwavChunk.getSize());
  17869. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  17870. }
  17871. if (smplChunk.getSize() > 0)
  17872. {
  17873. output->writeInt (chunkName ("smpl"));
  17874. output->writeInt ((int) smplChunk.getSize());
  17875. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  17876. }
  17877. output->writeInt (chunkName ("data"));
  17878. output->writeInt (lengthInSamples * bytesPerFrame);
  17879. usesFloatingPointData = (bitsPerSample == 32);
  17880. }
  17881. public:
  17882. WavAudioFormatWriter (OutputStream* const out,
  17883. const double sampleRate_,
  17884. const unsigned int numChannels_,
  17885. const int bits,
  17886. const StringPairArray& metadataValues)
  17887. : AudioFormatWriter (out,
  17888. TRANS (wavFormatName),
  17889. sampleRate_,
  17890. numChannels_,
  17891. bits),
  17892. lengthInSamples (0),
  17893. bytesWritten (0),
  17894. writeFailed (false)
  17895. {
  17896. if (metadataValues.size() > 0)
  17897. {
  17898. bwavChunk = BWAVChunk::createFrom (metadataValues);
  17899. smplChunk = SMPLChunk::createFrom (metadataValues);
  17900. }
  17901. headerPosition = out->getPosition();
  17902. writeHeader();
  17903. }
  17904. ~WavAudioFormatWriter()
  17905. {
  17906. writeHeader();
  17907. }
  17908. bool write (const int** data, int numSamples)
  17909. {
  17910. if (writeFailed)
  17911. return false;
  17912. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  17913. tempBlock.ensureSize (bytes, false);
  17914. char* buffer = static_cast <char*> (tempBlock.getData());
  17915. const int* left = data[0];
  17916. const int* right = data[1];
  17917. if (right == 0)
  17918. right = left;
  17919. if (bitsPerSample == 16)
  17920. {
  17921. short* b = (short*) buffer;
  17922. if (numChannels > 1)
  17923. {
  17924. for (int i = numSamples; --i >= 0;)
  17925. {
  17926. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17927. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*right++ >> 16));
  17928. }
  17929. }
  17930. else
  17931. {
  17932. for (int i = numSamples; --i >= 0;)
  17933. {
  17934. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17935. }
  17936. }
  17937. }
  17938. else if (bitsPerSample == 24)
  17939. {
  17940. char* b = buffer;
  17941. if (numChannels > 1)
  17942. {
  17943. for (int i = numSamples; --i >= 0;)
  17944. {
  17945. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17946. b += 3;
  17947. ByteOrder::littleEndian24BitToChars ((*right++) >> 8, b);
  17948. b += 3;
  17949. }
  17950. }
  17951. else
  17952. {
  17953. for (int i = numSamples; --i >= 0;)
  17954. {
  17955. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17956. b += 3;
  17957. }
  17958. }
  17959. }
  17960. else if (bitsPerSample == 32)
  17961. {
  17962. unsigned int* b = (unsigned int*) buffer;
  17963. if (numChannels > 1)
  17964. {
  17965. for (int i = numSamples; --i >= 0;)
  17966. {
  17967. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17968. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *right++);
  17969. }
  17970. }
  17971. else
  17972. {
  17973. for (int i = numSamples; --i >= 0;)
  17974. {
  17975. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17976. }
  17977. }
  17978. }
  17979. else if (bitsPerSample == 8)
  17980. {
  17981. unsigned char* b = (unsigned char*) buffer;
  17982. if (numChannels > 1)
  17983. {
  17984. for (int i = numSamples; --i >= 0;)
  17985. {
  17986. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17987. *b++ = (unsigned char) (128 + (*right++ >> 24));
  17988. }
  17989. }
  17990. else
  17991. {
  17992. for (int i = numSamples; --i >= 0;)
  17993. {
  17994. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17995. }
  17996. }
  17997. }
  17998. if (bytesWritten + bytes >= (uint32) 0xfff00000
  17999. || ! output->write (buffer, bytes))
  18000. {
  18001. // failed to write to disk, so let's try writing the header.
  18002. // If it's just run out of disk space, then if it does manage
  18003. // to write the header, we'll still have a useable file..
  18004. writeHeader();
  18005. writeFailed = true;
  18006. return false;
  18007. }
  18008. else
  18009. {
  18010. bytesWritten += bytes;
  18011. lengthInSamples += numSamples;
  18012. return true;
  18013. }
  18014. }
  18015. juce_UseDebuggingNewOperator
  18016. };
  18017. WavAudioFormat::WavAudioFormat()
  18018. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18019. {
  18020. }
  18021. WavAudioFormat::~WavAudioFormat()
  18022. {
  18023. }
  18024. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18025. {
  18026. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18027. return Array <int> (rates);
  18028. }
  18029. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18030. {
  18031. const int depths[] = { 8, 16, 24, 32, 0 };
  18032. return Array <int> (depths);
  18033. }
  18034. bool WavAudioFormat::canDoStereo()
  18035. {
  18036. return true;
  18037. }
  18038. bool WavAudioFormat::canDoMono()
  18039. {
  18040. return true;
  18041. }
  18042. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18043. const bool deleteStreamIfOpeningFails)
  18044. {
  18045. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18046. if (r->sampleRate != 0)
  18047. return r.release();
  18048. if (! deleteStreamIfOpeningFails)
  18049. r->input = 0;
  18050. return 0;
  18051. }
  18052. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18053. double sampleRate,
  18054. unsigned int numChannels,
  18055. int bitsPerSample,
  18056. const StringPairArray& metadataValues,
  18057. int /*qualityOptionIndex*/)
  18058. {
  18059. if (getPossibleBitDepths().contains (bitsPerSample))
  18060. {
  18061. return new WavAudioFormatWriter (out,
  18062. sampleRate,
  18063. numChannels,
  18064. bitsPerSample,
  18065. metadataValues);
  18066. }
  18067. return 0;
  18068. }
  18069. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18070. {
  18071. TemporaryFile tempFile (file);
  18072. WavAudioFormat wav;
  18073. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18074. if (reader != 0)
  18075. {
  18076. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18077. if (outStream != 0)
  18078. {
  18079. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18080. reader->numChannels, reader->bitsPerSample,
  18081. metadata, 0));
  18082. if (writer != 0)
  18083. {
  18084. outStream.release();
  18085. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18086. writer = 0;
  18087. reader = 0;
  18088. return ok && tempFile.overwriteTargetFileWithTemporary();
  18089. }
  18090. }
  18091. }
  18092. return false;
  18093. }
  18094. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18095. {
  18096. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18097. if (reader != 0)
  18098. {
  18099. const int64 bwavPos = reader->bwavChunkStart;
  18100. const int64 bwavSize = reader->bwavSize;
  18101. reader = 0;
  18102. if (bwavSize > 0)
  18103. {
  18104. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18105. if (chunk.getSize() <= (size_t) bwavSize)
  18106. {
  18107. // the new one will fit in the space available, so write it directly..
  18108. const int64 oldSize = wavFile.getSize();
  18109. {
  18110. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18111. out->setPosition (bwavPos);
  18112. out->write (chunk.getData(), (int) chunk.getSize());
  18113. out->setPosition (oldSize);
  18114. }
  18115. jassert (wavFile.getSize() == oldSize);
  18116. return true;
  18117. }
  18118. }
  18119. }
  18120. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18121. }
  18122. END_JUCE_NAMESPACE
  18123. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18124. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18125. BEGIN_JUCE_NAMESPACE
  18126. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18127. const bool deleteReaderWhenThisIsDeleted)
  18128. : reader (reader_),
  18129. deleteReader (deleteReaderWhenThisIsDeleted),
  18130. nextPlayPos (0),
  18131. looping (false)
  18132. {
  18133. jassert (reader != 0);
  18134. }
  18135. AudioFormatReaderSource::~AudioFormatReaderSource()
  18136. {
  18137. releaseResources();
  18138. if (deleteReader)
  18139. delete reader;
  18140. }
  18141. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  18142. {
  18143. nextPlayPos = newPosition;
  18144. }
  18145. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  18146. {
  18147. looping = shouldLoop;
  18148. }
  18149. int AudioFormatReaderSource::getNextReadPosition() const
  18150. {
  18151. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  18152. : nextPlayPos;
  18153. }
  18154. int AudioFormatReaderSource::getTotalLength() const
  18155. {
  18156. return (int) reader->lengthInSamples;
  18157. }
  18158. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18159. double /*sampleRate*/)
  18160. {
  18161. }
  18162. void AudioFormatReaderSource::releaseResources()
  18163. {
  18164. }
  18165. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18166. {
  18167. if (info.numSamples > 0)
  18168. {
  18169. const int start = nextPlayPos;
  18170. if (looping)
  18171. {
  18172. const int newStart = start % (int) reader->lengthInSamples;
  18173. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18174. if (newEnd > newStart)
  18175. {
  18176. info.buffer->readFromAudioReader (reader,
  18177. info.startSample,
  18178. newEnd - newStart,
  18179. newStart,
  18180. true, true);
  18181. }
  18182. else
  18183. {
  18184. const int endSamps = (int) reader->lengthInSamples - newStart;
  18185. info.buffer->readFromAudioReader (reader,
  18186. info.startSample,
  18187. endSamps,
  18188. newStart,
  18189. true, true);
  18190. info.buffer->readFromAudioReader (reader,
  18191. info.startSample + endSamps,
  18192. newEnd,
  18193. 0,
  18194. true, true);
  18195. }
  18196. nextPlayPos = newEnd;
  18197. }
  18198. else
  18199. {
  18200. info.buffer->readFromAudioReader (reader,
  18201. info.startSample,
  18202. info.numSamples,
  18203. start,
  18204. true, true);
  18205. nextPlayPos += info.numSamples;
  18206. }
  18207. }
  18208. }
  18209. END_JUCE_NAMESPACE
  18210. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18211. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  18212. BEGIN_JUCE_NAMESPACE
  18213. AudioSourcePlayer::AudioSourcePlayer()
  18214. : source (0),
  18215. sampleRate (0),
  18216. bufferSize (0),
  18217. tempBuffer (2, 8),
  18218. lastGain (1.0f),
  18219. gain (1.0f)
  18220. {
  18221. }
  18222. AudioSourcePlayer::~AudioSourcePlayer()
  18223. {
  18224. setSource (0);
  18225. }
  18226. void AudioSourcePlayer::setSource (AudioSource* newSource)
  18227. {
  18228. if (source != newSource)
  18229. {
  18230. AudioSource* const oldSource = source;
  18231. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  18232. newSource->prepareToPlay (bufferSize, sampleRate);
  18233. {
  18234. const ScopedLock sl (readLock);
  18235. source = newSource;
  18236. }
  18237. if (oldSource != 0)
  18238. oldSource->releaseResources();
  18239. }
  18240. }
  18241. void AudioSourcePlayer::setGain (const float newGain) throw()
  18242. {
  18243. gain = newGain;
  18244. }
  18245. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  18246. int totalNumInputChannels,
  18247. float** outputChannelData,
  18248. int totalNumOutputChannels,
  18249. int numSamples)
  18250. {
  18251. // these should have been prepared by audioDeviceAboutToStart()...
  18252. jassert (sampleRate > 0 && bufferSize > 0);
  18253. const ScopedLock sl (readLock);
  18254. if (source != 0)
  18255. {
  18256. AudioSourceChannelInfo info;
  18257. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  18258. // messy stuff needed to compact the channels down into an array
  18259. // of non-zero pointers..
  18260. for (i = 0; i < totalNumInputChannels; ++i)
  18261. {
  18262. if (inputChannelData[i] != 0)
  18263. {
  18264. inputChans [numInputs++] = inputChannelData[i];
  18265. if (numInputs >= numElementsInArray (inputChans))
  18266. break;
  18267. }
  18268. }
  18269. for (i = 0; i < totalNumOutputChannels; ++i)
  18270. {
  18271. if (outputChannelData[i] != 0)
  18272. {
  18273. outputChans [numOutputs++] = outputChannelData[i];
  18274. if (numOutputs >= numElementsInArray (outputChans))
  18275. break;
  18276. }
  18277. }
  18278. if (numInputs > numOutputs)
  18279. {
  18280. // if there aren't enough output channels for the number of
  18281. // inputs, we need to create some temporary extra ones (can't
  18282. // use the input data in case it gets written to)
  18283. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  18284. false, false, true);
  18285. for (i = 0; i < numOutputs; ++i)
  18286. {
  18287. channels[numActiveChans] = outputChans[i];
  18288. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18289. ++numActiveChans;
  18290. }
  18291. for (i = numOutputs; i < numInputs; ++i)
  18292. {
  18293. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  18294. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18295. ++numActiveChans;
  18296. }
  18297. }
  18298. else
  18299. {
  18300. for (i = 0; i < numInputs; ++i)
  18301. {
  18302. channels[numActiveChans] = outputChans[i];
  18303. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18304. ++numActiveChans;
  18305. }
  18306. for (i = numInputs; i < numOutputs; ++i)
  18307. {
  18308. channels[numActiveChans] = outputChans[i];
  18309. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  18310. ++numActiveChans;
  18311. }
  18312. }
  18313. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  18314. info.buffer = &buffer;
  18315. info.startSample = 0;
  18316. info.numSamples = numSamples;
  18317. source->getNextAudioBlock (info);
  18318. for (i = info.buffer->getNumChannels(); --i >= 0;)
  18319. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  18320. lastGain = gain;
  18321. }
  18322. else
  18323. {
  18324. for (int i = 0; i < totalNumOutputChannels; ++i)
  18325. if (outputChannelData[i] != 0)
  18326. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  18327. }
  18328. }
  18329. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  18330. {
  18331. sampleRate = device->getCurrentSampleRate();
  18332. bufferSize = device->getCurrentBufferSizeSamples();
  18333. zeromem (channels, sizeof (channels));
  18334. if (source != 0)
  18335. source->prepareToPlay (bufferSize, sampleRate);
  18336. }
  18337. void AudioSourcePlayer::audioDeviceStopped()
  18338. {
  18339. if (source != 0)
  18340. source->releaseResources();
  18341. sampleRate = 0.0;
  18342. bufferSize = 0;
  18343. tempBuffer.setSize (2, 8);
  18344. }
  18345. END_JUCE_NAMESPACE
  18346. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  18347. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  18348. BEGIN_JUCE_NAMESPACE
  18349. AudioTransportSource::AudioTransportSource()
  18350. : source (0),
  18351. resamplerSource (0),
  18352. bufferingSource (0),
  18353. positionableSource (0),
  18354. masterSource (0),
  18355. gain (1.0f),
  18356. lastGain (1.0f),
  18357. playing (false),
  18358. stopped (true),
  18359. sampleRate (44100.0),
  18360. sourceSampleRate (0.0),
  18361. blockSize (128),
  18362. readAheadBufferSize (0),
  18363. isPrepared (false),
  18364. inputStreamEOF (false)
  18365. {
  18366. }
  18367. AudioTransportSource::~AudioTransportSource()
  18368. {
  18369. setSource (0);
  18370. releaseResources();
  18371. }
  18372. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  18373. int readAheadBufferSize_,
  18374. double sourceSampleRateToCorrectFor)
  18375. {
  18376. if (source == newSource)
  18377. {
  18378. if (source == 0)
  18379. return;
  18380. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  18381. }
  18382. readAheadBufferSize = readAheadBufferSize_;
  18383. sourceSampleRate = sourceSampleRateToCorrectFor;
  18384. ResamplingAudioSource* newResamplerSource = 0;
  18385. BufferingAudioSource* newBufferingSource = 0;
  18386. PositionableAudioSource* newPositionableSource = 0;
  18387. AudioSource* newMasterSource = 0;
  18388. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  18389. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  18390. AudioSource* oldMasterSource = masterSource;
  18391. if (newSource != 0)
  18392. {
  18393. newPositionableSource = newSource;
  18394. if (readAheadBufferSize_ > 0)
  18395. newPositionableSource = newBufferingSource
  18396. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  18397. newPositionableSource->setNextReadPosition (0);
  18398. if (sourceSampleRateToCorrectFor != 0)
  18399. newMasterSource = newResamplerSource
  18400. = new ResamplingAudioSource (newPositionableSource, false);
  18401. else
  18402. newMasterSource = newPositionableSource;
  18403. if (isPrepared)
  18404. {
  18405. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  18406. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18407. newMasterSource->prepareToPlay (blockSize, sampleRate);
  18408. }
  18409. }
  18410. {
  18411. const ScopedLock sl (callbackLock);
  18412. source = newSource;
  18413. resamplerSource = newResamplerSource;
  18414. bufferingSource = newBufferingSource;
  18415. masterSource = newMasterSource;
  18416. positionableSource = newPositionableSource;
  18417. playing = false;
  18418. }
  18419. if (oldMasterSource != 0)
  18420. oldMasterSource->releaseResources();
  18421. }
  18422. void AudioTransportSource::start()
  18423. {
  18424. if ((! playing) && masterSource != 0)
  18425. {
  18426. {
  18427. const ScopedLock sl (callbackLock);
  18428. playing = true;
  18429. stopped = false;
  18430. inputStreamEOF = false;
  18431. }
  18432. sendChangeMessage (this);
  18433. }
  18434. }
  18435. void AudioTransportSource::stop()
  18436. {
  18437. if (playing)
  18438. {
  18439. {
  18440. const ScopedLock sl (callbackLock);
  18441. playing = false;
  18442. }
  18443. int n = 500;
  18444. while (--n >= 0 && ! stopped)
  18445. Thread::sleep (2);
  18446. sendChangeMessage (this);
  18447. }
  18448. }
  18449. void AudioTransportSource::setPosition (double newPosition)
  18450. {
  18451. if (sampleRate > 0.0)
  18452. setNextReadPosition (roundToInt (newPosition * sampleRate));
  18453. }
  18454. double AudioTransportSource::getCurrentPosition() const
  18455. {
  18456. if (sampleRate > 0.0)
  18457. return getNextReadPosition() / sampleRate;
  18458. else
  18459. return 0.0;
  18460. }
  18461. void AudioTransportSource::setNextReadPosition (int newPosition)
  18462. {
  18463. if (positionableSource != 0)
  18464. {
  18465. if (sampleRate > 0 && sourceSampleRate > 0)
  18466. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  18467. positionableSource->setNextReadPosition (newPosition);
  18468. }
  18469. }
  18470. int AudioTransportSource::getNextReadPosition() const
  18471. {
  18472. if (positionableSource != 0)
  18473. {
  18474. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18475. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  18476. }
  18477. return 0;
  18478. }
  18479. int AudioTransportSource::getTotalLength() const
  18480. {
  18481. const ScopedLock sl (callbackLock);
  18482. if (positionableSource != 0)
  18483. {
  18484. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18485. return roundToInt (positionableSource->getTotalLength() * ratio);
  18486. }
  18487. return 0;
  18488. }
  18489. bool AudioTransportSource::isLooping() const
  18490. {
  18491. const ScopedLock sl (callbackLock);
  18492. return positionableSource != 0
  18493. && positionableSource->isLooping();
  18494. }
  18495. void AudioTransportSource::setGain (const float newGain) throw()
  18496. {
  18497. gain = newGain;
  18498. }
  18499. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  18500. double sampleRate_)
  18501. {
  18502. const ScopedLock sl (callbackLock);
  18503. sampleRate = sampleRate_;
  18504. blockSize = samplesPerBlockExpected;
  18505. if (masterSource != 0)
  18506. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18507. if (resamplerSource != 0 && sourceSampleRate != 0)
  18508. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18509. isPrepared = true;
  18510. }
  18511. void AudioTransportSource::releaseResources()
  18512. {
  18513. const ScopedLock sl (callbackLock);
  18514. if (masterSource != 0)
  18515. masterSource->releaseResources();
  18516. isPrepared = false;
  18517. }
  18518. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18519. {
  18520. const ScopedLock sl (callbackLock);
  18521. inputStreamEOF = false;
  18522. if (masterSource != 0 && ! stopped)
  18523. {
  18524. masterSource->getNextAudioBlock (info);
  18525. if (! playing)
  18526. {
  18527. // just stopped playing, so fade out the last block..
  18528. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18529. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  18530. if (info.numSamples > 256)
  18531. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  18532. }
  18533. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  18534. && ! positionableSource->isLooping())
  18535. {
  18536. playing = false;
  18537. inputStreamEOF = true;
  18538. sendChangeMessage (this);
  18539. }
  18540. stopped = ! playing;
  18541. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18542. {
  18543. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  18544. lastGain, gain);
  18545. }
  18546. }
  18547. else
  18548. {
  18549. info.clearActiveBufferRegion();
  18550. stopped = true;
  18551. }
  18552. lastGain = gain;
  18553. }
  18554. END_JUCE_NAMESPACE
  18555. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  18556. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  18557. BEGIN_JUCE_NAMESPACE
  18558. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  18559. public Thread,
  18560. private Timer
  18561. {
  18562. public:
  18563. SharedBufferingAudioSourceThread()
  18564. : Thread ("Audio Buffer")
  18565. {
  18566. }
  18567. ~SharedBufferingAudioSourceThread()
  18568. {
  18569. stopThread (10000);
  18570. clearSingletonInstance();
  18571. }
  18572. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  18573. void addSource (BufferingAudioSource* source)
  18574. {
  18575. const ScopedLock sl (lock);
  18576. if (! sources.contains (source))
  18577. {
  18578. sources.add (source);
  18579. startThread();
  18580. stopTimer();
  18581. }
  18582. notify();
  18583. }
  18584. void removeSource (BufferingAudioSource* source)
  18585. {
  18586. const ScopedLock sl (lock);
  18587. sources.removeValue (source);
  18588. if (sources.size() == 0)
  18589. startTimer (5000);
  18590. }
  18591. private:
  18592. Array <BufferingAudioSource*> sources;
  18593. CriticalSection lock;
  18594. void run()
  18595. {
  18596. while (! threadShouldExit())
  18597. {
  18598. bool busy = false;
  18599. for (int i = sources.size(); --i >= 0;)
  18600. {
  18601. if (threadShouldExit())
  18602. return;
  18603. const ScopedLock sl (lock);
  18604. BufferingAudioSource* const b = sources[i];
  18605. if (b != 0 && b->readNextBufferChunk())
  18606. busy = true;
  18607. }
  18608. if (! busy)
  18609. wait (500);
  18610. }
  18611. }
  18612. void timerCallback()
  18613. {
  18614. stopTimer();
  18615. if (sources.size() == 0)
  18616. deleteInstance();
  18617. }
  18618. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  18619. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  18620. };
  18621. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  18622. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  18623. const bool deleteSourceWhenDeleted_,
  18624. int numberOfSamplesToBuffer_)
  18625. : source (source_),
  18626. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18627. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  18628. buffer (2, 0),
  18629. bufferValidStart (0),
  18630. bufferValidEnd (0),
  18631. nextPlayPos (0),
  18632. wasSourceLooping (false)
  18633. {
  18634. jassert (source_ != 0);
  18635. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  18636. // not using a larger buffer..
  18637. }
  18638. BufferingAudioSource::~BufferingAudioSource()
  18639. {
  18640. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18641. if (thread != 0)
  18642. thread->removeSource (this);
  18643. if (deleteSourceWhenDeleted)
  18644. delete source;
  18645. }
  18646. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  18647. {
  18648. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  18649. sampleRate = sampleRate_;
  18650. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  18651. buffer.clear();
  18652. bufferValidStart = 0;
  18653. bufferValidEnd = 0;
  18654. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  18655. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  18656. buffer.getNumSamples() / 2))
  18657. {
  18658. SharedBufferingAudioSourceThread::getInstance()->notify();
  18659. Thread::sleep (5);
  18660. }
  18661. }
  18662. void BufferingAudioSource::releaseResources()
  18663. {
  18664. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18665. if (thread != 0)
  18666. thread->removeSource (this);
  18667. buffer.setSize (2, 0);
  18668. source->releaseResources();
  18669. }
  18670. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18671. {
  18672. const ScopedLock sl (bufferStartPosLock);
  18673. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  18674. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  18675. if (validStart == validEnd)
  18676. {
  18677. // total cache miss
  18678. info.clearActiveBufferRegion();
  18679. }
  18680. else
  18681. {
  18682. if (validStart > 0)
  18683. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  18684. if (validEnd < info.numSamples)
  18685. info.buffer->clear (info.startSample + validEnd,
  18686. info.numSamples - validEnd); // partial cache miss at end
  18687. if (validStart < validEnd)
  18688. {
  18689. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  18690. {
  18691. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  18692. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  18693. if (startBufferIndex < endBufferIndex)
  18694. {
  18695. info.buffer->copyFrom (chan, info.startSample + validStart,
  18696. buffer,
  18697. chan, startBufferIndex,
  18698. validEnd - validStart);
  18699. }
  18700. else
  18701. {
  18702. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  18703. info.buffer->copyFrom (chan, info.startSample + validStart,
  18704. buffer,
  18705. chan, startBufferIndex,
  18706. initialSize);
  18707. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  18708. buffer,
  18709. chan, 0,
  18710. (validEnd - validStart) - initialSize);
  18711. }
  18712. }
  18713. }
  18714. nextPlayPos += info.numSamples;
  18715. if (source->isLooping() && nextPlayPos > 0)
  18716. nextPlayPos %= source->getTotalLength();
  18717. }
  18718. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18719. if (thread != 0)
  18720. thread->notify();
  18721. }
  18722. int BufferingAudioSource::getNextReadPosition() const
  18723. {
  18724. return (source->isLooping() && nextPlayPos > 0)
  18725. ? nextPlayPos % source->getTotalLength()
  18726. : nextPlayPos;
  18727. }
  18728. void BufferingAudioSource::setNextReadPosition (int newPosition)
  18729. {
  18730. const ScopedLock sl (bufferStartPosLock);
  18731. nextPlayPos = newPosition;
  18732. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18733. if (thread != 0)
  18734. thread->notify();
  18735. }
  18736. bool BufferingAudioSource::readNextBufferChunk()
  18737. {
  18738. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  18739. {
  18740. const ScopedLock sl (bufferStartPosLock);
  18741. if (wasSourceLooping != isLooping())
  18742. {
  18743. wasSourceLooping = isLooping();
  18744. bufferValidStart = 0;
  18745. bufferValidEnd = 0;
  18746. }
  18747. newBVS = jmax (0, nextPlayPos);
  18748. newBVE = newBVS + buffer.getNumSamples() - 4;
  18749. sectionToReadStart = 0;
  18750. sectionToReadEnd = 0;
  18751. const int maxChunkSize = 2048;
  18752. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  18753. {
  18754. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  18755. sectionToReadStart = newBVS;
  18756. sectionToReadEnd = newBVE;
  18757. bufferValidStart = 0;
  18758. bufferValidEnd = 0;
  18759. }
  18760. else if (abs (newBVS - bufferValidStart) > 512
  18761. || abs (newBVE - bufferValidEnd) > 512)
  18762. {
  18763. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  18764. sectionToReadStart = bufferValidEnd;
  18765. sectionToReadEnd = newBVE;
  18766. bufferValidStart = newBVS;
  18767. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  18768. }
  18769. }
  18770. if (sectionToReadStart != sectionToReadEnd)
  18771. {
  18772. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  18773. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  18774. if (bufferIndexStart < bufferIndexEnd)
  18775. {
  18776. readBufferSection (sectionToReadStart,
  18777. sectionToReadEnd - sectionToReadStart,
  18778. bufferIndexStart);
  18779. }
  18780. else
  18781. {
  18782. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  18783. readBufferSection (sectionToReadStart,
  18784. initialSize,
  18785. bufferIndexStart);
  18786. readBufferSection (sectionToReadStart + initialSize,
  18787. (sectionToReadEnd - sectionToReadStart) - initialSize,
  18788. 0);
  18789. }
  18790. const ScopedLock sl2 (bufferStartPosLock);
  18791. bufferValidStart = newBVS;
  18792. bufferValidEnd = newBVE;
  18793. return true;
  18794. }
  18795. else
  18796. {
  18797. return false;
  18798. }
  18799. }
  18800. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  18801. {
  18802. if (source->getNextReadPosition() != start)
  18803. source->setNextReadPosition (start);
  18804. AudioSourceChannelInfo info;
  18805. info.buffer = &buffer;
  18806. info.startSample = bufferOffset;
  18807. info.numSamples = length;
  18808. source->getNextAudioBlock (info);
  18809. }
  18810. END_JUCE_NAMESPACE
  18811. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  18812. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18813. BEGIN_JUCE_NAMESPACE
  18814. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  18815. const bool deleteSourceWhenDeleted_)
  18816. : requiredNumberOfChannels (2),
  18817. source (source_),
  18818. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18819. buffer (2, 16)
  18820. {
  18821. remappedInfo.buffer = &buffer;
  18822. remappedInfo.startSample = 0;
  18823. }
  18824. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  18825. {
  18826. if (deleteSourceWhenDeleted)
  18827. delete source;
  18828. }
  18829. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  18830. {
  18831. const ScopedLock sl (lock);
  18832. requiredNumberOfChannels = requiredNumberOfChannels_;
  18833. }
  18834. void ChannelRemappingAudioSource::clearAllMappings() throw()
  18835. {
  18836. const ScopedLock sl (lock);
  18837. remappedInputs.clear();
  18838. remappedOutputs.clear();
  18839. }
  18840. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  18841. {
  18842. const ScopedLock sl (lock);
  18843. while (remappedInputs.size() < destIndex)
  18844. remappedInputs.add (-1);
  18845. remappedInputs.set (destIndex, sourceIndex);
  18846. }
  18847. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  18848. {
  18849. const ScopedLock sl (lock);
  18850. while (remappedOutputs.size() < sourceIndex)
  18851. remappedOutputs.add (-1);
  18852. remappedOutputs.set (sourceIndex, destIndex);
  18853. }
  18854. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  18855. {
  18856. const ScopedLock sl (lock);
  18857. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  18858. return remappedInputs.getUnchecked (inputChannelIndex);
  18859. return -1;
  18860. }
  18861. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  18862. {
  18863. const ScopedLock sl (lock);
  18864. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  18865. return remappedOutputs .getUnchecked (outputChannelIndex);
  18866. return -1;
  18867. }
  18868. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18869. {
  18870. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18871. }
  18872. void ChannelRemappingAudioSource::releaseResources()
  18873. {
  18874. source->releaseResources();
  18875. }
  18876. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18877. {
  18878. const ScopedLock sl (lock);
  18879. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  18880. const int numChans = bufferToFill.buffer->getNumChannels();
  18881. int i;
  18882. for (i = 0; i < buffer.getNumChannels(); ++i)
  18883. {
  18884. const int remappedChan = getRemappedInputChannel (i);
  18885. if (remappedChan >= 0 && remappedChan < numChans)
  18886. {
  18887. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  18888. remappedChan,
  18889. bufferToFill.startSample,
  18890. bufferToFill.numSamples);
  18891. }
  18892. else
  18893. {
  18894. buffer.clear (i, 0, bufferToFill.numSamples);
  18895. }
  18896. }
  18897. remappedInfo.numSamples = bufferToFill.numSamples;
  18898. source->getNextAudioBlock (remappedInfo);
  18899. bufferToFill.clearActiveBufferRegion();
  18900. for (i = 0; i < requiredNumberOfChannels; ++i)
  18901. {
  18902. const int remappedChan = getRemappedOutputChannel (i);
  18903. if (remappedChan >= 0 && remappedChan < numChans)
  18904. {
  18905. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  18906. buffer, i, 0, bufferToFill.numSamples);
  18907. }
  18908. }
  18909. }
  18910. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  18911. {
  18912. XmlElement* e = new XmlElement ("MAPPINGS");
  18913. String ins, outs;
  18914. int i;
  18915. const ScopedLock sl (lock);
  18916. for (i = 0; i < remappedInputs.size(); ++i)
  18917. ins << remappedInputs.getUnchecked(i) << ' ';
  18918. for (i = 0; i < remappedOutputs.size(); ++i)
  18919. outs << remappedOutputs.getUnchecked(i) << ' ';
  18920. e->setAttribute ("inputs", ins.trimEnd());
  18921. e->setAttribute ("outputs", outs.trimEnd());
  18922. return e;
  18923. }
  18924. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  18925. {
  18926. if (e.hasTagName ("MAPPINGS"))
  18927. {
  18928. const ScopedLock sl (lock);
  18929. clearAllMappings();
  18930. StringArray ins, outs;
  18931. ins.addTokens (e.getStringAttribute ("inputs"), false);
  18932. outs.addTokens (e.getStringAttribute ("outputs"), false);
  18933. int i;
  18934. for (i = 0; i < ins.size(); ++i)
  18935. remappedInputs.add (ins[i].getIntValue());
  18936. for (i = 0; i < outs.size(); ++i)
  18937. remappedOutputs.add (outs[i].getIntValue());
  18938. }
  18939. }
  18940. END_JUCE_NAMESPACE
  18941. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18942. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18943. BEGIN_JUCE_NAMESPACE
  18944. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  18945. const bool deleteInputWhenDeleted_)
  18946. : input (inputSource),
  18947. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  18948. {
  18949. jassert (inputSource != 0);
  18950. for (int i = 2; --i >= 0;)
  18951. iirFilters.add (new IIRFilter());
  18952. }
  18953. IIRFilterAudioSource::~IIRFilterAudioSource()
  18954. {
  18955. if (deleteInputWhenDeleted)
  18956. delete input;
  18957. }
  18958. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  18959. {
  18960. for (int i = iirFilters.size(); --i >= 0;)
  18961. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  18962. }
  18963. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18964. {
  18965. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18966. for (int i = iirFilters.size(); --i >= 0;)
  18967. iirFilters.getUnchecked(i)->reset();
  18968. }
  18969. void IIRFilterAudioSource::releaseResources()
  18970. {
  18971. input->releaseResources();
  18972. }
  18973. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18974. {
  18975. input->getNextAudioBlock (bufferToFill);
  18976. const int numChannels = bufferToFill.buffer->getNumChannels();
  18977. while (numChannels > iirFilters.size())
  18978. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  18979. for (int i = 0; i < numChannels; ++i)
  18980. iirFilters.getUnchecked(i)
  18981. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  18982. bufferToFill.numSamples);
  18983. }
  18984. END_JUCE_NAMESPACE
  18985. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18986. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  18987. BEGIN_JUCE_NAMESPACE
  18988. MixerAudioSource::MixerAudioSource()
  18989. : tempBuffer (2, 0),
  18990. currentSampleRate (0.0),
  18991. bufferSizeExpected (0)
  18992. {
  18993. }
  18994. MixerAudioSource::~MixerAudioSource()
  18995. {
  18996. removeAllInputs();
  18997. }
  18998. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  18999. {
  19000. if (input != 0 && ! inputs.contains (input))
  19001. {
  19002. double localRate;
  19003. int localBufferSize;
  19004. {
  19005. const ScopedLock sl (lock);
  19006. localRate = currentSampleRate;
  19007. localBufferSize = bufferSizeExpected;
  19008. }
  19009. if (localRate != 0.0)
  19010. input->prepareToPlay (localBufferSize, localRate);
  19011. const ScopedLock sl (lock);
  19012. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19013. inputs.add (input);
  19014. }
  19015. }
  19016. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19017. {
  19018. if (input != 0)
  19019. {
  19020. int index;
  19021. {
  19022. const ScopedLock sl (lock);
  19023. index = inputs.indexOf (input);
  19024. if (index >= 0)
  19025. {
  19026. inputsToDelete.shiftBits (index, 1);
  19027. inputs.remove (index);
  19028. }
  19029. }
  19030. if (index >= 0)
  19031. {
  19032. input->releaseResources();
  19033. if (deleteInput)
  19034. delete input;
  19035. }
  19036. }
  19037. }
  19038. void MixerAudioSource::removeAllInputs()
  19039. {
  19040. OwnedArray<AudioSource> toDelete;
  19041. {
  19042. const ScopedLock sl (lock);
  19043. for (int i = inputs.size(); --i >= 0;)
  19044. if (inputsToDelete[i])
  19045. toDelete.add (inputs.getUnchecked(i));
  19046. }
  19047. }
  19048. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19049. {
  19050. tempBuffer.setSize (2, samplesPerBlockExpected);
  19051. const ScopedLock sl (lock);
  19052. currentSampleRate = sampleRate;
  19053. bufferSizeExpected = samplesPerBlockExpected;
  19054. for (int i = inputs.size(); --i >= 0;)
  19055. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19056. }
  19057. void MixerAudioSource::releaseResources()
  19058. {
  19059. const ScopedLock sl (lock);
  19060. for (int i = inputs.size(); --i >= 0;)
  19061. inputs.getUnchecked(i)->releaseResources();
  19062. tempBuffer.setSize (2, 0);
  19063. currentSampleRate = 0;
  19064. bufferSizeExpected = 0;
  19065. }
  19066. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19067. {
  19068. const ScopedLock sl (lock);
  19069. if (inputs.size() > 0)
  19070. {
  19071. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19072. if (inputs.size() > 1)
  19073. {
  19074. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19075. info.buffer->getNumSamples());
  19076. AudioSourceChannelInfo info2;
  19077. info2.buffer = &tempBuffer;
  19078. info2.numSamples = info.numSamples;
  19079. info2.startSample = 0;
  19080. for (int i = 1; i < inputs.size(); ++i)
  19081. {
  19082. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19083. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19084. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19085. }
  19086. }
  19087. }
  19088. else
  19089. {
  19090. info.clearActiveBufferRegion();
  19091. }
  19092. }
  19093. END_JUCE_NAMESPACE
  19094. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19095. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19096. BEGIN_JUCE_NAMESPACE
  19097. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19098. const bool deleteInputWhenDeleted_,
  19099. const int numChannels_)
  19100. : input (inputSource),
  19101. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19102. ratio (1.0),
  19103. lastRatio (1.0),
  19104. buffer (numChannels_, 0),
  19105. sampsInBuffer (0),
  19106. numChannels (numChannels_)
  19107. {
  19108. jassert (input != 0);
  19109. }
  19110. ResamplingAudioSource::~ResamplingAudioSource()
  19111. {
  19112. if (deleteInputWhenDeleted)
  19113. delete input;
  19114. }
  19115. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19116. {
  19117. jassert (samplesInPerOutputSample > 0);
  19118. const ScopedLock sl (ratioLock);
  19119. ratio = jmax (0.0, samplesInPerOutputSample);
  19120. }
  19121. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19122. double sampleRate)
  19123. {
  19124. const ScopedLock sl (ratioLock);
  19125. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19126. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19127. buffer.clear();
  19128. sampsInBuffer = 0;
  19129. bufferPos = 0;
  19130. subSampleOffset = 0.0;
  19131. filterStates.calloc (numChannels);
  19132. srcBuffers.calloc (numChannels);
  19133. destBuffers.calloc (numChannels);
  19134. createLowPass (ratio);
  19135. resetFilters();
  19136. }
  19137. void ResamplingAudioSource::releaseResources()
  19138. {
  19139. input->releaseResources();
  19140. buffer.setSize (numChannels, 0);
  19141. }
  19142. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19143. {
  19144. const ScopedLock sl (ratioLock);
  19145. if (lastRatio != ratio)
  19146. {
  19147. createLowPass (ratio);
  19148. lastRatio = ratio;
  19149. }
  19150. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  19151. int bufferSize = buffer.getNumSamples();
  19152. if (bufferSize < sampsNeeded + 8)
  19153. {
  19154. bufferPos %= bufferSize;
  19155. bufferSize = sampsNeeded + 32;
  19156. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19157. }
  19158. bufferPos %= bufferSize;
  19159. int endOfBufferPos = bufferPos + sampsInBuffer;
  19160. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  19161. while (sampsNeeded > sampsInBuffer)
  19162. {
  19163. endOfBufferPos %= bufferSize;
  19164. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19165. bufferSize - endOfBufferPos);
  19166. AudioSourceChannelInfo readInfo;
  19167. readInfo.buffer = &buffer;
  19168. readInfo.numSamples = numToDo;
  19169. readInfo.startSample = endOfBufferPos;
  19170. input->getNextAudioBlock (readInfo);
  19171. if (ratio > 1.0001)
  19172. {
  19173. // for down-sampling, pre-apply the filter..
  19174. for (int i = channelsToProcess; --i >= 0;)
  19175. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19176. }
  19177. sampsInBuffer += numToDo;
  19178. endOfBufferPos += numToDo;
  19179. }
  19180. for (int channel = 0; channel < channelsToProcess; ++channel)
  19181. {
  19182. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  19183. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  19184. }
  19185. int nextPos = (bufferPos + 1) % bufferSize;
  19186. for (int m = info.numSamples; --m >= 0;)
  19187. {
  19188. const float alpha = (float) subSampleOffset;
  19189. const float invAlpha = 1.0f - alpha;
  19190. for (int channel = 0; channel < channelsToProcess; ++channel)
  19191. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  19192. subSampleOffset += ratio;
  19193. jassert (sampsInBuffer > 0);
  19194. while (subSampleOffset >= 1.0)
  19195. {
  19196. if (++bufferPos >= bufferSize)
  19197. bufferPos = 0;
  19198. --sampsInBuffer;
  19199. nextPos = (bufferPos + 1) % bufferSize;
  19200. subSampleOffset -= 1.0;
  19201. }
  19202. }
  19203. if (ratio < 0.9999)
  19204. {
  19205. // for up-sampling, apply the filter after transposing..
  19206. for (int i = channelsToProcess; --i >= 0;)
  19207. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  19208. }
  19209. else if (ratio <= 1.0001)
  19210. {
  19211. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  19212. for (int i = channelsToProcess; --i >= 0;)
  19213. {
  19214. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  19215. FilterState& fs = filterStates[i];
  19216. if (info.numSamples > 1)
  19217. {
  19218. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  19219. }
  19220. else
  19221. {
  19222. fs.y2 = fs.y1;
  19223. fs.x2 = fs.x1;
  19224. }
  19225. fs.y1 = fs.x1 = *endOfBuffer;
  19226. }
  19227. }
  19228. jassert (sampsInBuffer >= 0);
  19229. }
  19230. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  19231. {
  19232. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  19233. : 0.5 * frequencyRatio;
  19234. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  19235. const double nSquared = n * n;
  19236. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  19237. setFilterCoefficients (c1,
  19238. c1 * 2.0f,
  19239. c1,
  19240. 1.0,
  19241. c1 * 2.0 * (1.0 - nSquared),
  19242. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  19243. }
  19244. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  19245. {
  19246. const double a = 1.0 / c4;
  19247. c1 *= a;
  19248. c2 *= a;
  19249. c3 *= a;
  19250. c5 *= a;
  19251. c6 *= a;
  19252. coefficients[0] = c1;
  19253. coefficients[1] = c2;
  19254. coefficients[2] = c3;
  19255. coefficients[3] = c4;
  19256. coefficients[4] = c5;
  19257. coefficients[5] = c6;
  19258. }
  19259. void ResamplingAudioSource::resetFilters()
  19260. {
  19261. zeromem (filterStates, sizeof (FilterState) * numChannels);
  19262. }
  19263. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  19264. {
  19265. while (--num >= 0)
  19266. {
  19267. const double in = *samples;
  19268. double out = coefficients[0] * in
  19269. + coefficients[1] * fs.x1
  19270. + coefficients[2] * fs.x2
  19271. - coefficients[4] * fs.y1
  19272. - coefficients[5] * fs.y2;
  19273. #if JUCE_INTEL
  19274. if (! (out < -1.0e-8 || out > 1.0e-8))
  19275. out = 0;
  19276. #endif
  19277. fs.x2 = fs.x1;
  19278. fs.x1 = in;
  19279. fs.y2 = fs.y1;
  19280. fs.y1 = out;
  19281. *samples++ = (float) out;
  19282. }
  19283. }
  19284. END_JUCE_NAMESPACE
  19285. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  19286. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19287. BEGIN_JUCE_NAMESPACE
  19288. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  19289. : frequency (1000.0),
  19290. sampleRate (44100.0),
  19291. currentPhase (0.0),
  19292. phasePerSample (0.0),
  19293. amplitude (0.5f)
  19294. {
  19295. }
  19296. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  19297. {
  19298. }
  19299. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  19300. {
  19301. amplitude = newAmplitude;
  19302. }
  19303. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  19304. {
  19305. frequency = newFrequencyHz;
  19306. phasePerSample = 0.0;
  19307. }
  19308. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19309. double sampleRate_)
  19310. {
  19311. currentPhase = 0.0;
  19312. phasePerSample = 0.0;
  19313. sampleRate = sampleRate_;
  19314. }
  19315. void ToneGeneratorAudioSource::releaseResources()
  19316. {
  19317. }
  19318. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19319. {
  19320. if (phasePerSample == 0.0)
  19321. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19322. for (int i = 0; i < info.numSamples; ++i)
  19323. {
  19324. const float sample = amplitude * (float) std::sin (currentPhase);
  19325. currentPhase += phasePerSample;
  19326. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  19327. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  19328. }
  19329. }
  19330. END_JUCE_NAMESPACE
  19331. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19332. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  19333. BEGIN_JUCE_NAMESPACE
  19334. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  19335. : sampleRate (0),
  19336. bufferSize (0),
  19337. useDefaultInputChannels (true),
  19338. useDefaultOutputChannels (true)
  19339. {
  19340. }
  19341. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  19342. {
  19343. return outputDeviceName == other.outputDeviceName
  19344. && inputDeviceName == other.inputDeviceName
  19345. && sampleRate == other.sampleRate
  19346. && bufferSize == other.bufferSize
  19347. && inputChannels == other.inputChannels
  19348. && useDefaultInputChannels == other.useDefaultInputChannels
  19349. && outputChannels == other.outputChannels
  19350. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  19351. }
  19352. AudioDeviceManager::AudioDeviceManager()
  19353. : currentAudioDevice (0),
  19354. numInputChansNeeded (0),
  19355. numOutputChansNeeded (2),
  19356. listNeedsScanning (true),
  19357. useInputNames (false),
  19358. inputLevelMeasurementEnabledCount (0),
  19359. inputLevel (0),
  19360. tempBuffer (2, 2),
  19361. defaultMidiOutput (0),
  19362. cpuUsageMs (0),
  19363. timeToCpuScale (0)
  19364. {
  19365. callbackHandler.owner = this;
  19366. }
  19367. AudioDeviceManager::~AudioDeviceManager()
  19368. {
  19369. currentAudioDevice = 0;
  19370. defaultMidiOutput = 0;
  19371. }
  19372. void AudioDeviceManager::createDeviceTypesIfNeeded()
  19373. {
  19374. if (availableDeviceTypes.size() == 0)
  19375. {
  19376. createAudioDeviceTypes (availableDeviceTypes);
  19377. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  19378. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  19379. if (availableDeviceTypes.size() > 0)
  19380. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  19381. }
  19382. }
  19383. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  19384. {
  19385. scanDevicesIfNeeded();
  19386. return availableDeviceTypes;
  19387. }
  19388. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  19389. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  19390. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  19391. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  19392. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  19393. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  19394. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  19395. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  19396. {
  19397. (void) list; // (to avoid 'unused param' warnings)
  19398. #if JUCE_WINDOWS
  19399. #if JUCE_WASAPI
  19400. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  19401. list.add (juce_createAudioIODeviceType_WASAPI());
  19402. #endif
  19403. #if JUCE_DIRECTSOUND
  19404. list.add (juce_createAudioIODeviceType_DirectSound());
  19405. #endif
  19406. #if JUCE_ASIO
  19407. list.add (juce_createAudioIODeviceType_ASIO());
  19408. #endif
  19409. #endif
  19410. #if JUCE_MAC
  19411. list.add (juce_createAudioIODeviceType_CoreAudio());
  19412. #endif
  19413. #if JUCE_IOS
  19414. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  19415. #endif
  19416. #if JUCE_LINUX && JUCE_ALSA
  19417. list.add (juce_createAudioIODeviceType_ALSA());
  19418. #endif
  19419. #if JUCE_LINUX && JUCE_JACK
  19420. list.add (juce_createAudioIODeviceType_JACK());
  19421. #endif
  19422. }
  19423. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  19424. const int numOutputChannelsNeeded,
  19425. const XmlElement* const e,
  19426. const bool selectDefaultDeviceOnFailure,
  19427. const String& preferredDefaultDeviceName,
  19428. const AudioDeviceSetup* preferredSetupOptions)
  19429. {
  19430. scanDevicesIfNeeded();
  19431. numInputChansNeeded = numInputChannelsNeeded;
  19432. numOutputChansNeeded = numOutputChannelsNeeded;
  19433. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  19434. {
  19435. lastExplicitSettings = new XmlElement (*e);
  19436. String error;
  19437. AudioDeviceSetup setup;
  19438. if (preferredSetupOptions != 0)
  19439. setup = *preferredSetupOptions;
  19440. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  19441. {
  19442. setup.inputDeviceName = setup.outputDeviceName
  19443. = e->getStringAttribute ("audioDeviceName");
  19444. }
  19445. else
  19446. {
  19447. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  19448. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  19449. }
  19450. currentDeviceType = e->getStringAttribute ("deviceType");
  19451. if (currentDeviceType.isEmpty())
  19452. {
  19453. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  19454. if (type != 0)
  19455. currentDeviceType = type->getTypeName();
  19456. else if (availableDeviceTypes.size() > 0)
  19457. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  19458. }
  19459. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  19460. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  19461. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  19462. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  19463. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  19464. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  19465. error = setAudioDeviceSetup (setup, true);
  19466. midiInsFromXml.clear();
  19467. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  19468. midiInsFromXml.add (c->getStringAttribute ("name"));
  19469. const StringArray allMidiIns (MidiInput::getDevices());
  19470. for (int i = allMidiIns.size(); --i >= 0;)
  19471. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  19472. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  19473. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  19474. false, preferredDefaultDeviceName);
  19475. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  19476. return error;
  19477. }
  19478. else
  19479. {
  19480. AudioDeviceSetup setup;
  19481. if (preferredSetupOptions != 0)
  19482. {
  19483. setup = *preferredSetupOptions;
  19484. }
  19485. else if (preferredDefaultDeviceName.isNotEmpty())
  19486. {
  19487. for (int j = availableDeviceTypes.size(); --j >= 0;)
  19488. {
  19489. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  19490. StringArray outs (type->getDeviceNames (false));
  19491. int i;
  19492. for (i = 0; i < outs.size(); ++i)
  19493. {
  19494. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  19495. {
  19496. setup.outputDeviceName = outs[i];
  19497. break;
  19498. }
  19499. }
  19500. StringArray ins (type->getDeviceNames (true));
  19501. for (i = 0; i < ins.size(); ++i)
  19502. {
  19503. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  19504. {
  19505. setup.inputDeviceName = ins[i];
  19506. break;
  19507. }
  19508. }
  19509. }
  19510. }
  19511. insertDefaultDeviceNames (setup);
  19512. return setAudioDeviceSetup (setup, false);
  19513. }
  19514. }
  19515. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  19516. {
  19517. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19518. if (type != 0)
  19519. {
  19520. if (setup.outputDeviceName.isEmpty())
  19521. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  19522. if (setup.inputDeviceName.isEmpty())
  19523. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  19524. }
  19525. }
  19526. XmlElement* AudioDeviceManager::createStateXml() const
  19527. {
  19528. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  19529. }
  19530. void AudioDeviceManager::scanDevicesIfNeeded()
  19531. {
  19532. if (listNeedsScanning)
  19533. {
  19534. listNeedsScanning = false;
  19535. createDeviceTypesIfNeeded();
  19536. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19537. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  19538. }
  19539. }
  19540. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  19541. {
  19542. scanDevicesIfNeeded();
  19543. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19544. {
  19545. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  19546. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  19547. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  19548. {
  19549. return type;
  19550. }
  19551. }
  19552. return 0;
  19553. }
  19554. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  19555. {
  19556. setup = currentSetup;
  19557. }
  19558. void AudioDeviceManager::deleteCurrentDevice()
  19559. {
  19560. currentAudioDevice = 0;
  19561. currentSetup.inputDeviceName = String::empty;
  19562. currentSetup.outputDeviceName = String::empty;
  19563. }
  19564. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  19565. const bool treatAsChosenDevice)
  19566. {
  19567. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19568. {
  19569. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  19570. && currentDeviceType != type)
  19571. {
  19572. currentDeviceType = type;
  19573. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  19574. insertDefaultDeviceNames (s);
  19575. setAudioDeviceSetup (s, treatAsChosenDevice);
  19576. sendChangeMessage (this);
  19577. break;
  19578. }
  19579. }
  19580. }
  19581. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  19582. {
  19583. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19584. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  19585. return availableDeviceTypes[i];
  19586. return availableDeviceTypes[0];
  19587. }
  19588. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  19589. const bool treatAsChosenDevice)
  19590. {
  19591. jassert (&newSetup != &currentSetup); // this will have no effect
  19592. if (newSetup == currentSetup && currentAudioDevice != 0)
  19593. return String::empty;
  19594. if (! (newSetup == currentSetup))
  19595. sendChangeMessage (this);
  19596. stopDevice();
  19597. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  19598. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  19599. String error;
  19600. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19601. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  19602. {
  19603. deleteCurrentDevice();
  19604. if (treatAsChosenDevice)
  19605. updateXml();
  19606. return String::empty;
  19607. }
  19608. if (currentSetup.inputDeviceName != newInputDeviceName
  19609. || currentSetup.outputDeviceName != newOutputDeviceName
  19610. || currentAudioDevice == 0)
  19611. {
  19612. deleteCurrentDevice();
  19613. scanDevicesIfNeeded();
  19614. if (newOutputDeviceName.isNotEmpty()
  19615. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  19616. {
  19617. return "No such device: " + newOutputDeviceName;
  19618. }
  19619. if (newInputDeviceName.isNotEmpty()
  19620. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  19621. {
  19622. return "No such device: " + newInputDeviceName;
  19623. }
  19624. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  19625. if (currentAudioDevice == 0)
  19626. 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!";
  19627. else
  19628. error = currentAudioDevice->getLastError();
  19629. if (error.isNotEmpty())
  19630. {
  19631. deleteCurrentDevice();
  19632. return error;
  19633. }
  19634. if (newSetup.useDefaultInputChannels)
  19635. {
  19636. inputChannels.clear();
  19637. inputChannels.setRange (0, numInputChansNeeded, true);
  19638. }
  19639. if (newSetup.useDefaultOutputChannels)
  19640. {
  19641. outputChannels.clear();
  19642. outputChannels.setRange (0, numOutputChansNeeded, true);
  19643. }
  19644. if (newInputDeviceName.isEmpty())
  19645. inputChannels.clear();
  19646. if (newOutputDeviceName.isEmpty())
  19647. outputChannels.clear();
  19648. }
  19649. if (! newSetup.useDefaultInputChannels)
  19650. inputChannels = newSetup.inputChannels;
  19651. if (! newSetup.useDefaultOutputChannels)
  19652. outputChannels = newSetup.outputChannels;
  19653. currentSetup = newSetup;
  19654. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  19655. error = currentAudioDevice->open (inputChannels,
  19656. outputChannels,
  19657. currentSetup.sampleRate,
  19658. currentSetup.bufferSize);
  19659. if (error.isEmpty())
  19660. {
  19661. currentDeviceType = currentAudioDevice->getTypeName();
  19662. currentAudioDevice->start (&callbackHandler);
  19663. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  19664. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  19665. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  19666. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  19667. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19668. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  19669. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  19670. if (treatAsChosenDevice)
  19671. updateXml();
  19672. }
  19673. else
  19674. {
  19675. deleteCurrentDevice();
  19676. }
  19677. return error;
  19678. }
  19679. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  19680. {
  19681. jassert (currentAudioDevice != 0);
  19682. if (rate > 0)
  19683. {
  19684. bool ok = false;
  19685. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19686. {
  19687. const double sr = currentAudioDevice->getSampleRate (i);
  19688. if (sr == rate)
  19689. ok = true;
  19690. }
  19691. if (! ok)
  19692. rate = 0;
  19693. }
  19694. if (rate == 0)
  19695. {
  19696. double lowestAbove44 = 0.0;
  19697. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19698. {
  19699. const double sr = currentAudioDevice->getSampleRate (i);
  19700. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  19701. lowestAbove44 = sr;
  19702. }
  19703. if (lowestAbove44 == 0.0)
  19704. rate = currentAudioDevice->getSampleRate (0);
  19705. else
  19706. rate = lowestAbove44;
  19707. }
  19708. return rate;
  19709. }
  19710. void AudioDeviceManager::stopDevice()
  19711. {
  19712. if (currentAudioDevice != 0)
  19713. currentAudioDevice->stop();
  19714. testSound = 0;
  19715. }
  19716. void AudioDeviceManager::closeAudioDevice()
  19717. {
  19718. stopDevice();
  19719. currentAudioDevice = 0;
  19720. }
  19721. void AudioDeviceManager::restartLastAudioDevice()
  19722. {
  19723. if (currentAudioDevice == 0)
  19724. {
  19725. if (currentSetup.inputDeviceName.isEmpty()
  19726. && currentSetup.outputDeviceName.isEmpty())
  19727. {
  19728. // This method will only reload the last device that was running
  19729. // before closeAudioDevice() was called - you need to actually open
  19730. // one first, with setAudioDevice().
  19731. jassertfalse;
  19732. return;
  19733. }
  19734. AudioDeviceSetup s (currentSetup);
  19735. setAudioDeviceSetup (s, false);
  19736. }
  19737. }
  19738. void AudioDeviceManager::updateXml()
  19739. {
  19740. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  19741. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  19742. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  19743. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  19744. if (currentAudioDevice != 0)
  19745. {
  19746. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  19747. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  19748. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  19749. if (! currentSetup.useDefaultInputChannels)
  19750. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  19751. if (! currentSetup.useDefaultOutputChannels)
  19752. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  19753. }
  19754. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  19755. {
  19756. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19757. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  19758. }
  19759. if (midiInsFromXml.size() > 0)
  19760. {
  19761. // Add any midi devices that have been enabled before, but which aren't currently
  19762. // open because the device has been disconnected.
  19763. const StringArray availableMidiDevices (MidiInput::getDevices());
  19764. for (int i = 0; i < midiInsFromXml.size(); ++i)
  19765. {
  19766. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  19767. {
  19768. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19769. m->setAttribute ("name", midiInsFromXml[i]);
  19770. }
  19771. }
  19772. }
  19773. if (defaultMidiOutputName.isNotEmpty())
  19774. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  19775. }
  19776. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  19777. {
  19778. {
  19779. const ScopedLock sl (audioCallbackLock);
  19780. if (callbacks.contains (newCallback))
  19781. return;
  19782. }
  19783. if (currentAudioDevice != 0 && newCallback != 0)
  19784. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  19785. const ScopedLock sl (audioCallbackLock);
  19786. callbacks.add (newCallback);
  19787. }
  19788. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  19789. {
  19790. if (callback != 0)
  19791. {
  19792. bool needsDeinitialising = currentAudioDevice != 0;
  19793. {
  19794. const ScopedLock sl (audioCallbackLock);
  19795. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  19796. callbacks.removeValue (callback);
  19797. }
  19798. if (needsDeinitialising)
  19799. callback->audioDeviceStopped();
  19800. }
  19801. }
  19802. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  19803. int numInputChannels,
  19804. float** outputChannelData,
  19805. int numOutputChannels,
  19806. int numSamples)
  19807. {
  19808. const ScopedLock sl (audioCallbackLock);
  19809. if (inputLevelMeasurementEnabledCount > 0)
  19810. {
  19811. for (int j = 0; j < numSamples; ++j)
  19812. {
  19813. float s = 0;
  19814. for (int i = 0; i < numInputChannels; ++i)
  19815. s += std::abs (inputChannelData[i][j]);
  19816. s /= numInputChannels;
  19817. const double decayFactor = 0.99992;
  19818. if (s > inputLevel)
  19819. inputLevel = s;
  19820. else if (inputLevel > 0.001f)
  19821. inputLevel *= decayFactor;
  19822. else
  19823. inputLevel = 0;
  19824. }
  19825. }
  19826. if (callbacks.size() > 0)
  19827. {
  19828. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  19829. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  19830. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19831. outputChannelData, numOutputChannels, numSamples);
  19832. float** const tempChans = tempBuffer.getArrayOfChannels();
  19833. for (int i = callbacks.size(); --i > 0;)
  19834. {
  19835. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19836. tempChans, numOutputChannels, numSamples);
  19837. for (int chan = 0; chan < numOutputChannels; ++chan)
  19838. {
  19839. const float* const src = tempChans [chan];
  19840. float* const dst = outputChannelData [chan];
  19841. if (src != 0 && dst != 0)
  19842. for (int j = 0; j < numSamples; ++j)
  19843. dst[j] += src[j];
  19844. }
  19845. }
  19846. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  19847. const double filterAmount = 0.2;
  19848. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  19849. }
  19850. else
  19851. {
  19852. for (int i = 0; i < numOutputChannels; ++i)
  19853. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19854. }
  19855. if (testSound != 0)
  19856. {
  19857. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  19858. const float* const src = testSound->getSampleData (0, testSoundPosition);
  19859. for (int i = 0; i < numOutputChannels; ++i)
  19860. for (int j = 0; j < numSamps; ++j)
  19861. outputChannelData [i][j] += src[j];
  19862. testSoundPosition += numSamps;
  19863. if (testSoundPosition >= testSound->getNumSamples())
  19864. testSound = 0;
  19865. }
  19866. }
  19867. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  19868. {
  19869. cpuUsageMs = 0;
  19870. const double sampleRate = device->getCurrentSampleRate();
  19871. const int blockSize = device->getCurrentBufferSizeSamples();
  19872. if (sampleRate > 0.0 && blockSize > 0)
  19873. {
  19874. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  19875. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  19876. }
  19877. {
  19878. const ScopedLock sl (audioCallbackLock);
  19879. for (int i = callbacks.size(); --i >= 0;)
  19880. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  19881. }
  19882. sendChangeMessage (this);
  19883. }
  19884. void AudioDeviceManager::audioDeviceStoppedInt()
  19885. {
  19886. cpuUsageMs = 0;
  19887. timeToCpuScale = 0;
  19888. sendChangeMessage (this);
  19889. const ScopedLock sl (audioCallbackLock);
  19890. for (int i = callbacks.size(); --i >= 0;)
  19891. callbacks.getUnchecked(i)->audioDeviceStopped();
  19892. }
  19893. double AudioDeviceManager::getCpuUsage() const
  19894. {
  19895. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  19896. }
  19897. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  19898. const bool enabled)
  19899. {
  19900. if (enabled != isMidiInputEnabled (name))
  19901. {
  19902. if (enabled)
  19903. {
  19904. const int index = MidiInput::getDevices().indexOf (name);
  19905. if (index >= 0)
  19906. {
  19907. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  19908. if (min != 0)
  19909. {
  19910. enabledMidiInputs.add (min);
  19911. min->start();
  19912. }
  19913. }
  19914. }
  19915. else
  19916. {
  19917. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19918. if (enabledMidiInputs[i]->getName() == name)
  19919. enabledMidiInputs.remove (i);
  19920. }
  19921. updateXml();
  19922. sendChangeMessage (this);
  19923. }
  19924. }
  19925. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  19926. {
  19927. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19928. if (enabledMidiInputs[i]->getName() == name)
  19929. return true;
  19930. return false;
  19931. }
  19932. void AudioDeviceManager::addMidiInputCallback (const String& name,
  19933. MidiInputCallback* callback)
  19934. {
  19935. removeMidiInputCallback (name, callback);
  19936. if (name.isEmpty())
  19937. {
  19938. midiCallbacks.add (callback);
  19939. midiCallbackDevices.add (0);
  19940. }
  19941. else
  19942. {
  19943. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19944. {
  19945. if (enabledMidiInputs[i]->getName() == name)
  19946. {
  19947. const ScopedLock sl (midiCallbackLock);
  19948. midiCallbacks.add (callback);
  19949. midiCallbackDevices.add (enabledMidiInputs[i]);
  19950. break;
  19951. }
  19952. }
  19953. }
  19954. }
  19955. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  19956. MidiInputCallback* /*callback*/)
  19957. {
  19958. const ScopedLock sl (midiCallbackLock);
  19959. for (int i = midiCallbacks.size(); --i >= 0;)
  19960. {
  19961. String devName;
  19962. if (midiCallbackDevices.getUnchecked(i) != 0)
  19963. devName = midiCallbackDevices.getUnchecked(i)->getName();
  19964. if (devName == name)
  19965. {
  19966. midiCallbacks.remove (i);
  19967. midiCallbackDevices.remove (i);
  19968. }
  19969. }
  19970. }
  19971. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  19972. const MidiMessage& message)
  19973. {
  19974. if (! message.isActiveSense())
  19975. {
  19976. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  19977. const ScopedLock sl (midiCallbackLock);
  19978. for (int i = midiCallbackDevices.size(); --i >= 0;)
  19979. {
  19980. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  19981. if (md == source || (md == 0 && isDefaultSource))
  19982. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  19983. }
  19984. }
  19985. }
  19986. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  19987. {
  19988. if (defaultMidiOutputName != deviceName)
  19989. {
  19990. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  19991. {
  19992. const ScopedLock sl (audioCallbackLock);
  19993. oldCallbacks = callbacks;
  19994. callbacks.clear();
  19995. }
  19996. if (currentAudioDevice != 0)
  19997. for (int i = oldCallbacks.size(); --i >= 0;)
  19998. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  19999. defaultMidiOutput = 0;
  20000. defaultMidiOutputName = deviceName;
  20001. if (deviceName.isNotEmpty())
  20002. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20003. if (currentAudioDevice != 0)
  20004. for (int i = oldCallbacks.size(); --i >= 0;)
  20005. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20006. {
  20007. const ScopedLock sl (audioCallbackLock);
  20008. callbacks = oldCallbacks;
  20009. }
  20010. updateXml();
  20011. sendChangeMessage (this);
  20012. }
  20013. }
  20014. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20015. int numInputChannels,
  20016. float** outputChannelData,
  20017. int numOutputChannels,
  20018. int numSamples)
  20019. {
  20020. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20021. }
  20022. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20023. {
  20024. owner->audioDeviceAboutToStartInt (device);
  20025. }
  20026. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20027. {
  20028. owner->audioDeviceStoppedInt();
  20029. }
  20030. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20031. {
  20032. owner->handleIncomingMidiMessageInt (source, message);
  20033. }
  20034. void AudioDeviceManager::playTestSound()
  20035. {
  20036. { // cunningly nested to swap, unlock and delete in that order.
  20037. ScopedPointer <AudioSampleBuffer> oldSound;
  20038. {
  20039. const ScopedLock sl (audioCallbackLock);
  20040. oldSound = testSound;
  20041. }
  20042. }
  20043. testSoundPosition = 0;
  20044. if (currentAudioDevice != 0)
  20045. {
  20046. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20047. const int soundLength = (int) sampleRate;
  20048. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20049. float* samples = newSound->getSampleData (0);
  20050. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20051. const float amplitude = 0.5f;
  20052. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20053. for (int i = 0; i < soundLength; ++i)
  20054. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20055. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20056. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20057. const ScopedLock sl (audioCallbackLock);
  20058. testSound = newSound;
  20059. }
  20060. }
  20061. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20062. {
  20063. const ScopedLock sl (audioCallbackLock);
  20064. if (enableMeasurement)
  20065. ++inputLevelMeasurementEnabledCount;
  20066. else
  20067. --inputLevelMeasurementEnabledCount;
  20068. inputLevel = 0;
  20069. }
  20070. double AudioDeviceManager::getCurrentInputLevel() const
  20071. {
  20072. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20073. return inputLevel;
  20074. }
  20075. END_JUCE_NAMESPACE
  20076. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20077. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20078. BEGIN_JUCE_NAMESPACE
  20079. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20080. : name (deviceName),
  20081. typeName (typeName_)
  20082. {
  20083. }
  20084. AudioIODevice::~AudioIODevice()
  20085. {
  20086. }
  20087. bool AudioIODevice::hasControlPanel() const
  20088. {
  20089. return false;
  20090. }
  20091. bool AudioIODevice::showControlPanel()
  20092. {
  20093. jassertfalse; // this should only be called for devices which return true from
  20094. // their hasControlPanel() method.
  20095. return false;
  20096. }
  20097. END_JUCE_NAMESPACE
  20098. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20099. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20100. BEGIN_JUCE_NAMESPACE
  20101. AudioIODeviceType::AudioIODeviceType (const String& name)
  20102. : typeName (name)
  20103. {
  20104. }
  20105. AudioIODeviceType::~AudioIODeviceType()
  20106. {
  20107. }
  20108. END_JUCE_NAMESPACE
  20109. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20110. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20111. BEGIN_JUCE_NAMESPACE
  20112. MidiOutput::MidiOutput()
  20113. : Thread ("midi out"),
  20114. internal (0),
  20115. firstMessage (0)
  20116. {
  20117. }
  20118. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20119. const double sampleNumber)
  20120. : message (data, len, sampleNumber)
  20121. {
  20122. }
  20123. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20124. const double millisecondCounterToStartAt,
  20125. double samplesPerSecondForBuffer)
  20126. {
  20127. // You've got to call startBackgroundThread() for this to actually work..
  20128. jassert (isThreadRunning());
  20129. // this needs to be a value in the future - RTFM for this method!
  20130. jassert (millisecondCounterToStartAt > 0);
  20131. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20132. MidiBuffer::Iterator i (buffer);
  20133. const uint8* data;
  20134. int len, time;
  20135. while (i.getNextEvent (data, len, time))
  20136. {
  20137. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20138. PendingMessage* const m
  20139. = new PendingMessage (data, len, eventTime);
  20140. const ScopedLock sl (lock);
  20141. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20142. {
  20143. m->next = firstMessage;
  20144. firstMessage = m;
  20145. }
  20146. else
  20147. {
  20148. PendingMessage* mm = firstMessage;
  20149. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20150. mm = mm->next;
  20151. m->next = mm->next;
  20152. mm->next = m;
  20153. }
  20154. }
  20155. notify();
  20156. }
  20157. void MidiOutput::clearAllPendingMessages()
  20158. {
  20159. const ScopedLock sl (lock);
  20160. while (firstMessage != 0)
  20161. {
  20162. PendingMessage* const m = firstMessage;
  20163. firstMessage = firstMessage->next;
  20164. delete m;
  20165. }
  20166. }
  20167. void MidiOutput::startBackgroundThread()
  20168. {
  20169. startThread (9);
  20170. }
  20171. void MidiOutput::stopBackgroundThread()
  20172. {
  20173. stopThread (5000);
  20174. }
  20175. void MidiOutput::run()
  20176. {
  20177. while (! threadShouldExit())
  20178. {
  20179. uint32 now = Time::getMillisecondCounter();
  20180. uint32 eventTime = 0;
  20181. uint32 timeToWait = 500;
  20182. PendingMessage* message;
  20183. {
  20184. const ScopedLock sl (lock);
  20185. message = firstMessage;
  20186. if (message != 0)
  20187. {
  20188. eventTime = roundToInt (message->message.getTimeStamp());
  20189. if (eventTime > now + 20)
  20190. {
  20191. timeToWait = eventTime - (now + 20);
  20192. message = 0;
  20193. }
  20194. else
  20195. {
  20196. firstMessage = message->next;
  20197. }
  20198. }
  20199. }
  20200. if (message != 0)
  20201. {
  20202. if (eventTime > now)
  20203. {
  20204. Time::waitForMillisecondCounter (eventTime);
  20205. if (threadShouldExit())
  20206. break;
  20207. }
  20208. if (eventTime > now - 200)
  20209. sendMessageNow (message->message);
  20210. delete message;
  20211. }
  20212. else
  20213. {
  20214. jassert (timeToWait < 1000 * 30);
  20215. wait (timeToWait);
  20216. }
  20217. }
  20218. clearAllPendingMessages();
  20219. }
  20220. END_JUCE_NAMESPACE
  20221. /*** End of inlined file: juce_MidiOutput.cpp ***/
  20222. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  20223. BEGIN_JUCE_NAMESPACE
  20224. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20225. {
  20226. const double maxVal = (double) 0x7fff;
  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. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20233. intData += destBytesPerSample;
  20234. }
  20235. }
  20236. else
  20237. {
  20238. intData += destBytesPerSample * numSamples;
  20239. for (int i = numSamples; --i >= 0;)
  20240. {
  20241. intData -= destBytesPerSample;
  20242. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20243. }
  20244. }
  20245. }
  20246. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20247. {
  20248. const double maxVal = (double) 0x7fff;
  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. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20255. intData += destBytesPerSample;
  20256. }
  20257. }
  20258. else
  20259. {
  20260. intData += destBytesPerSample * numSamples;
  20261. for (int i = numSamples; --i >= 0;)
  20262. {
  20263. intData -= destBytesPerSample;
  20264. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20265. }
  20266. }
  20267. }
  20268. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20269. {
  20270. const double maxVal = (double) 0x7fffff;
  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. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20277. intData += destBytesPerSample;
  20278. }
  20279. }
  20280. else
  20281. {
  20282. intData += destBytesPerSample * numSamples;
  20283. for (int i = numSamples; --i >= 0;)
  20284. {
  20285. intData -= destBytesPerSample;
  20286. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20287. }
  20288. }
  20289. }
  20290. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20291. {
  20292. const double maxVal = (double) 0x7fffff;
  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. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20299. intData += destBytesPerSample;
  20300. }
  20301. }
  20302. else
  20303. {
  20304. intData += destBytesPerSample * numSamples;
  20305. for (int i = numSamples; --i >= 0;)
  20306. {
  20307. intData -= destBytesPerSample;
  20308. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20309. }
  20310. }
  20311. }
  20312. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20313. {
  20314. const double maxVal = (double) 0x7fffffff;
  20315. char* intData = static_cast <char*> (dest);
  20316. if (dest != (void*) source || destBytesPerSample <= 4)
  20317. {
  20318. for (int i = 0; i < numSamples; ++i)
  20319. {
  20320. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20321. intData += destBytesPerSample;
  20322. }
  20323. }
  20324. else
  20325. {
  20326. intData += destBytesPerSample * numSamples;
  20327. for (int i = numSamples; --i >= 0;)
  20328. {
  20329. intData -= destBytesPerSample;
  20330. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20331. }
  20332. }
  20333. }
  20334. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20335. {
  20336. const double maxVal = (double) 0x7fffffff;
  20337. char* intData = static_cast <char*> (dest);
  20338. if (dest != (void*) source || destBytesPerSample <= 4)
  20339. {
  20340. for (int i = 0; i < numSamples; ++i)
  20341. {
  20342. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20343. intData += destBytesPerSample;
  20344. }
  20345. }
  20346. else
  20347. {
  20348. intData += destBytesPerSample * numSamples;
  20349. for (int i = numSamples; --i >= 0;)
  20350. {
  20351. intData -= destBytesPerSample;
  20352. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20353. }
  20354. }
  20355. }
  20356. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20357. {
  20358. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20359. char* d = static_cast <char*> (dest);
  20360. for (int i = 0; i < numSamples; ++i)
  20361. {
  20362. *(float*) d = source[i];
  20363. #if JUCE_BIG_ENDIAN
  20364. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20365. #endif
  20366. d += destBytesPerSample;
  20367. }
  20368. }
  20369. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20370. {
  20371. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20372. char* d = static_cast <char*> (dest);
  20373. for (int i = 0; i < numSamples; ++i)
  20374. {
  20375. *(float*) d = source[i];
  20376. #if JUCE_LITTLE_ENDIAN
  20377. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20378. #endif
  20379. d += destBytesPerSample;
  20380. }
  20381. }
  20382. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20383. {
  20384. const float scale = 1.0f / 0x7fff;
  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::swapIfBigEndian (*(uint16*)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::swapIfBigEndian (*(uint16*)intData);
  20401. }
  20402. }
  20403. }
  20404. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20405. {
  20406. const float scale = 1.0f / 0x7fff;
  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::swapIfLittleEndian (*(uint16*)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::swapIfLittleEndian (*(uint16*)intData);
  20423. }
  20424. }
  20425. }
  20426. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20427. {
  20428. const float scale = 1.0f / 0x7fffff;
  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 * (short) ByteOrder::littleEndian24Bit (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 * (short) ByteOrder::littleEndian24Bit (intData);
  20445. }
  20446. }
  20447. }
  20448. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20449. {
  20450. const float scale = 1.0f / 0x7fffff;
  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 * (short) ByteOrder::bigEndian24Bit (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 * (short) ByteOrder::bigEndian24Bit (intData);
  20467. }
  20468. }
  20469. }
  20470. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20471. {
  20472. const float scale = 1.0f / 0x7fffffff;
  20473. const char* intData = static_cast <const char*> (source);
  20474. if (source != (void*) dest || srcBytesPerSample >= 4)
  20475. {
  20476. for (int i = 0; i < numSamples; ++i)
  20477. {
  20478. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20479. intData += srcBytesPerSample;
  20480. }
  20481. }
  20482. else
  20483. {
  20484. intData += srcBytesPerSample * numSamples;
  20485. for (int i = numSamples; --i >= 0;)
  20486. {
  20487. intData -= srcBytesPerSample;
  20488. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20489. }
  20490. }
  20491. }
  20492. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20493. {
  20494. const float scale = 1.0f / 0x7fffffff;
  20495. const char* intData = static_cast <const char*> (source);
  20496. if (source != (void*) dest || srcBytesPerSample >= 4)
  20497. {
  20498. for (int i = 0; i < numSamples; ++i)
  20499. {
  20500. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20501. intData += srcBytesPerSample;
  20502. }
  20503. }
  20504. else
  20505. {
  20506. intData += srcBytesPerSample * numSamples;
  20507. for (int i = numSamples; --i >= 0;)
  20508. {
  20509. intData -= srcBytesPerSample;
  20510. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20511. }
  20512. }
  20513. }
  20514. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20515. {
  20516. const char* s = static_cast <const char*> (source);
  20517. for (int i = 0; i < numSamples; ++i)
  20518. {
  20519. dest[i] = *(float*)s;
  20520. #if JUCE_BIG_ENDIAN
  20521. uint32* const d = (uint32*) (dest + i);
  20522. *d = ByteOrder::swap (*d);
  20523. #endif
  20524. s += srcBytesPerSample;
  20525. }
  20526. }
  20527. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20528. {
  20529. const char* s = static_cast <const char*> (source);
  20530. for (int i = 0; i < numSamples; ++i)
  20531. {
  20532. dest[i] = *(float*)s;
  20533. #if JUCE_LITTLE_ENDIAN
  20534. uint32* const d = (uint32*) (dest + i);
  20535. *d = ByteOrder::swap (*d);
  20536. #endif
  20537. s += srcBytesPerSample;
  20538. }
  20539. }
  20540. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  20541. const float* const source,
  20542. void* const dest,
  20543. const int numSamples)
  20544. {
  20545. switch (destFormat)
  20546. {
  20547. case int16LE:
  20548. convertFloatToInt16LE (source, dest, numSamples);
  20549. break;
  20550. case int16BE:
  20551. convertFloatToInt16BE (source, dest, numSamples);
  20552. break;
  20553. case int24LE:
  20554. convertFloatToInt24LE (source, dest, numSamples);
  20555. break;
  20556. case int24BE:
  20557. convertFloatToInt24BE (source, dest, numSamples);
  20558. break;
  20559. case int32LE:
  20560. convertFloatToInt32LE (source, dest, numSamples);
  20561. break;
  20562. case int32BE:
  20563. convertFloatToInt32BE (source, dest, numSamples);
  20564. break;
  20565. case float32LE:
  20566. convertFloatToFloat32LE (source, dest, numSamples);
  20567. break;
  20568. case float32BE:
  20569. convertFloatToFloat32BE (source, dest, numSamples);
  20570. break;
  20571. default:
  20572. jassertfalse;
  20573. break;
  20574. }
  20575. }
  20576. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  20577. const void* const source,
  20578. float* const dest,
  20579. const int numSamples)
  20580. {
  20581. switch (sourceFormat)
  20582. {
  20583. case int16LE:
  20584. convertInt16LEToFloat (source, dest, numSamples);
  20585. break;
  20586. case int16BE:
  20587. convertInt16BEToFloat (source, dest, numSamples);
  20588. break;
  20589. case int24LE:
  20590. convertInt24LEToFloat (source, dest, numSamples);
  20591. break;
  20592. case int24BE:
  20593. convertInt24BEToFloat (source, dest, numSamples);
  20594. break;
  20595. case int32LE:
  20596. convertInt32LEToFloat (source, dest, numSamples);
  20597. break;
  20598. case int32BE:
  20599. convertInt32BEToFloat (source, dest, numSamples);
  20600. break;
  20601. case float32LE:
  20602. convertFloat32LEToFloat (source, dest, numSamples);
  20603. break;
  20604. case float32BE:
  20605. convertFloat32BEToFloat (source, dest, numSamples);
  20606. break;
  20607. default:
  20608. jassertfalse;
  20609. break;
  20610. }
  20611. }
  20612. void AudioDataConverters::interleaveSamples (const float** const source,
  20613. float* const dest,
  20614. const int numSamples,
  20615. const int numChannels)
  20616. {
  20617. for (int chan = 0; chan < numChannels; ++chan)
  20618. {
  20619. int i = chan;
  20620. const float* src = source [chan];
  20621. for (int j = 0; j < numSamples; ++j)
  20622. {
  20623. dest [i] = src [j];
  20624. i += numChannels;
  20625. }
  20626. }
  20627. }
  20628. void AudioDataConverters::deinterleaveSamples (const float* const source,
  20629. float** const dest,
  20630. const int numSamples,
  20631. const int numChannels)
  20632. {
  20633. for (int chan = 0; chan < numChannels; ++chan)
  20634. {
  20635. int i = chan;
  20636. float* dst = dest [chan];
  20637. for (int j = 0; j < numSamples; ++j)
  20638. {
  20639. dst [j] = source [i];
  20640. i += numChannels;
  20641. }
  20642. }
  20643. }
  20644. END_JUCE_NAMESPACE
  20645. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  20646. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  20647. BEGIN_JUCE_NAMESPACE
  20648. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  20649. const int numSamples) throw()
  20650. : numChannels (numChannels_),
  20651. size (numSamples)
  20652. {
  20653. jassert (numSamples >= 0);
  20654. jassert (numChannels_ > 0);
  20655. allocateData();
  20656. }
  20657. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  20658. : numChannels (other.numChannels),
  20659. size (other.size)
  20660. {
  20661. allocateData();
  20662. const size_t numBytes = size * sizeof (float);
  20663. for (int i = 0; i < numChannels; ++i)
  20664. memcpy (channels[i], other.channels[i], numBytes);
  20665. }
  20666. void AudioSampleBuffer::allocateData()
  20667. {
  20668. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  20669. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  20670. allocatedData.malloc (allocatedBytes);
  20671. channels = reinterpret_cast <float**> (allocatedData.getData());
  20672. float* chan = (float*) (allocatedData + channelListSize);
  20673. for (int i = 0; i < numChannels; ++i)
  20674. {
  20675. channels[i] = chan;
  20676. chan += size;
  20677. }
  20678. channels [numChannels] = 0;
  20679. }
  20680. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  20681. const int numChannels_,
  20682. const int numSamples) throw()
  20683. : numChannels (numChannels_),
  20684. size (numSamples),
  20685. allocatedBytes (0)
  20686. {
  20687. jassert (numChannels_ > 0);
  20688. allocateChannels (dataToReferTo);
  20689. }
  20690. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  20691. const int newNumChannels,
  20692. const int newNumSamples) throw()
  20693. {
  20694. jassert (newNumChannels > 0);
  20695. allocatedBytes = 0;
  20696. allocatedData.free();
  20697. numChannels = newNumChannels;
  20698. size = newNumSamples;
  20699. allocateChannels (dataToReferTo);
  20700. }
  20701. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  20702. {
  20703. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  20704. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  20705. {
  20706. channels = static_cast <float**> (preallocatedChannelSpace);
  20707. }
  20708. else
  20709. {
  20710. allocatedData.malloc (numChannels + 1, sizeof (float*));
  20711. channels = reinterpret_cast <float**> (allocatedData.getData());
  20712. }
  20713. for (int i = 0; i < numChannels; ++i)
  20714. {
  20715. // you have to pass in the same number of valid pointers as numChannels
  20716. jassert (dataToReferTo[i] != 0);
  20717. channels[i] = dataToReferTo[i];
  20718. }
  20719. channels [numChannels] = 0;
  20720. }
  20721. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  20722. {
  20723. if (this != &other)
  20724. {
  20725. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  20726. const size_t numBytes = size * sizeof (float);
  20727. for (int i = 0; i < numChannels; ++i)
  20728. memcpy (channels[i], other.channels[i], numBytes);
  20729. }
  20730. return *this;
  20731. }
  20732. AudioSampleBuffer::~AudioSampleBuffer() throw()
  20733. {
  20734. }
  20735. void AudioSampleBuffer::setSize (const int newNumChannels,
  20736. const int newNumSamples,
  20737. const bool keepExistingContent,
  20738. const bool clearExtraSpace,
  20739. const bool avoidReallocating) throw()
  20740. {
  20741. jassert (newNumChannels > 0);
  20742. if (newNumSamples != size || newNumChannels != numChannels)
  20743. {
  20744. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  20745. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  20746. if (keepExistingContent)
  20747. {
  20748. HeapBlock <char> newData;
  20749. newData.allocate (newTotalBytes, clearExtraSpace);
  20750. const int numChansToCopy = jmin (numChannels, newNumChannels);
  20751. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  20752. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  20753. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  20754. for (int i = 0; i < numChansToCopy; ++i)
  20755. {
  20756. memcpy (newChan, channels[i], numBytesToCopy);
  20757. newChannels[i] = newChan;
  20758. newChan += newNumSamples;
  20759. }
  20760. allocatedData.swapWith (newData);
  20761. allocatedBytes = (int) newTotalBytes;
  20762. channels = newChannels;
  20763. }
  20764. else
  20765. {
  20766. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  20767. {
  20768. if (clearExtraSpace)
  20769. zeromem (allocatedData, newTotalBytes);
  20770. }
  20771. else
  20772. {
  20773. allocatedBytes = newTotalBytes;
  20774. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  20775. channels = reinterpret_cast <float**> (allocatedData.getData());
  20776. }
  20777. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  20778. for (int i = 0; i < newNumChannels; ++i)
  20779. {
  20780. channels[i] = chan;
  20781. chan += newNumSamples;
  20782. }
  20783. }
  20784. channels [newNumChannels] = 0;
  20785. size = newNumSamples;
  20786. numChannels = newNumChannels;
  20787. }
  20788. }
  20789. void AudioSampleBuffer::clear() throw()
  20790. {
  20791. for (int i = 0; i < numChannels; ++i)
  20792. zeromem (channels[i], size * sizeof (float));
  20793. }
  20794. void AudioSampleBuffer::clear (const int startSample,
  20795. const int numSamples) throw()
  20796. {
  20797. jassert (startSample >= 0 && startSample + numSamples <= size);
  20798. for (int i = 0; i < numChannels; ++i)
  20799. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  20800. }
  20801. void AudioSampleBuffer::clear (const int channel,
  20802. const int startSample,
  20803. const int numSamples) throw()
  20804. {
  20805. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20806. jassert (startSample >= 0 && startSample + numSamples <= size);
  20807. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  20808. }
  20809. void AudioSampleBuffer::applyGain (const int channel,
  20810. const int startSample,
  20811. int numSamples,
  20812. const float gain) throw()
  20813. {
  20814. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20815. jassert (startSample >= 0 && startSample + numSamples <= size);
  20816. if (gain != 1.0f)
  20817. {
  20818. float* d = channels [channel] + startSample;
  20819. if (gain == 0.0f)
  20820. {
  20821. zeromem (d, sizeof (float) * numSamples);
  20822. }
  20823. else
  20824. {
  20825. while (--numSamples >= 0)
  20826. *d++ *= gain;
  20827. }
  20828. }
  20829. }
  20830. void AudioSampleBuffer::applyGainRamp (const int channel,
  20831. const int startSample,
  20832. int numSamples,
  20833. float startGain,
  20834. float endGain) throw()
  20835. {
  20836. if (startGain == endGain)
  20837. {
  20838. applyGain (channel, startSample, numSamples, startGain);
  20839. }
  20840. else
  20841. {
  20842. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20843. jassert (startSample >= 0 && startSample + numSamples <= size);
  20844. const float increment = (endGain - startGain) / numSamples;
  20845. float* d = channels [channel] + startSample;
  20846. while (--numSamples >= 0)
  20847. {
  20848. *d++ *= startGain;
  20849. startGain += increment;
  20850. }
  20851. }
  20852. }
  20853. void AudioSampleBuffer::applyGain (const int startSample,
  20854. const int numSamples,
  20855. const float gain) throw()
  20856. {
  20857. for (int i = 0; i < numChannels; ++i)
  20858. applyGain (i, startSample, numSamples, gain);
  20859. }
  20860. void AudioSampleBuffer::addFrom (const int destChannel,
  20861. const int destStartSample,
  20862. const AudioSampleBuffer& source,
  20863. const int sourceChannel,
  20864. const int sourceStartSample,
  20865. int numSamples,
  20866. const float gain) throw()
  20867. {
  20868. jassert (&source != this || sourceChannel != destChannel);
  20869. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20870. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20871. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20872. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20873. if (gain != 0.0f && numSamples > 0)
  20874. {
  20875. float* d = channels [destChannel] + destStartSample;
  20876. const float* s = source.channels [sourceChannel] + sourceStartSample;
  20877. if (gain != 1.0f)
  20878. {
  20879. while (--numSamples >= 0)
  20880. *d++ += gain * *s++;
  20881. }
  20882. else
  20883. {
  20884. while (--numSamples >= 0)
  20885. *d++ += *s++;
  20886. }
  20887. }
  20888. }
  20889. void AudioSampleBuffer::addFrom (const int destChannel,
  20890. const int destStartSample,
  20891. const float* source,
  20892. int numSamples,
  20893. const float gain) throw()
  20894. {
  20895. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20896. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20897. jassert (source != 0);
  20898. if (gain != 0.0f && numSamples > 0)
  20899. {
  20900. float* d = channels [destChannel] + destStartSample;
  20901. if (gain != 1.0f)
  20902. {
  20903. while (--numSamples >= 0)
  20904. *d++ += gain * *source++;
  20905. }
  20906. else
  20907. {
  20908. while (--numSamples >= 0)
  20909. *d++ += *source++;
  20910. }
  20911. }
  20912. }
  20913. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  20914. const int destStartSample,
  20915. const float* source,
  20916. int numSamples,
  20917. float startGain,
  20918. const float endGain) throw()
  20919. {
  20920. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20921. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20922. jassert (source != 0);
  20923. if (startGain == endGain)
  20924. {
  20925. addFrom (destChannel,
  20926. destStartSample,
  20927. source,
  20928. numSamples,
  20929. startGain);
  20930. }
  20931. else
  20932. {
  20933. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20934. {
  20935. const float increment = (endGain - startGain) / numSamples;
  20936. float* d = channels [destChannel] + destStartSample;
  20937. while (--numSamples >= 0)
  20938. {
  20939. *d++ += startGain * *source++;
  20940. startGain += increment;
  20941. }
  20942. }
  20943. }
  20944. }
  20945. void AudioSampleBuffer::copyFrom (const int destChannel,
  20946. const int destStartSample,
  20947. const AudioSampleBuffer& source,
  20948. const int sourceChannel,
  20949. const int sourceStartSample,
  20950. int numSamples) throw()
  20951. {
  20952. jassert (&source != this || sourceChannel != destChannel);
  20953. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20954. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20955. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20956. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20957. if (numSamples > 0)
  20958. {
  20959. memcpy (channels [destChannel] + destStartSample,
  20960. source.channels [sourceChannel] + sourceStartSample,
  20961. sizeof (float) * numSamples);
  20962. }
  20963. }
  20964. void AudioSampleBuffer::copyFrom (const int destChannel,
  20965. const int destStartSample,
  20966. const float* source,
  20967. int numSamples) throw()
  20968. {
  20969. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20970. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20971. jassert (source != 0);
  20972. if (numSamples > 0)
  20973. {
  20974. memcpy (channels [destChannel] + destStartSample,
  20975. source,
  20976. sizeof (float) * numSamples);
  20977. }
  20978. }
  20979. void AudioSampleBuffer::copyFrom (const int destChannel,
  20980. const int destStartSample,
  20981. const float* source,
  20982. int numSamples,
  20983. const float gain) throw()
  20984. {
  20985. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20986. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20987. jassert (source != 0);
  20988. if (numSamples > 0)
  20989. {
  20990. float* d = channels [destChannel] + destStartSample;
  20991. if (gain != 1.0f)
  20992. {
  20993. if (gain == 0)
  20994. {
  20995. zeromem (d, sizeof (float) * numSamples);
  20996. }
  20997. else
  20998. {
  20999. while (--numSamples >= 0)
  21000. *d++ = gain * *source++;
  21001. }
  21002. }
  21003. else
  21004. {
  21005. memcpy (d, source, sizeof (float) * numSamples);
  21006. }
  21007. }
  21008. }
  21009. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21010. const int destStartSample,
  21011. const float* source,
  21012. int numSamples,
  21013. float startGain,
  21014. float endGain) throw()
  21015. {
  21016. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21017. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21018. jassert (source != 0);
  21019. if (startGain == endGain)
  21020. {
  21021. copyFrom (destChannel,
  21022. destStartSample,
  21023. source,
  21024. numSamples,
  21025. startGain);
  21026. }
  21027. else
  21028. {
  21029. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21030. {
  21031. const float increment = (endGain - startGain) / numSamples;
  21032. float* d = channels [destChannel] + destStartSample;
  21033. while (--numSamples >= 0)
  21034. {
  21035. *d++ = startGain * *source++;
  21036. startGain += increment;
  21037. }
  21038. }
  21039. }
  21040. }
  21041. void AudioSampleBuffer::findMinMax (const int channel,
  21042. const int startSample,
  21043. int numSamples,
  21044. float& minVal,
  21045. float& maxVal) const throw()
  21046. {
  21047. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21048. jassert (startSample >= 0 && startSample + numSamples <= size);
  21049. if (numSamples <= 0)
  21050. {
  21051. minVal = 0.0f;
  21052. maxVal = 0.0f;
  21053. }
  21054. else
  21055. {
  21056. const float* d = channels [channel] + startSample;
  21057. float mn = *d++;
  21058. float mx = mn;
  21059. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  21060. {
  21061. const float samp = *d++;
  21062. if (samp > mx)
  21063. mx = samp;
  21064. if (samp < mn)
  21065. mn = samp;
  21066. }
  21067. maxVal = mx;
  21068. minVal = mn;
  21069. }
  21070. }
  21071. float AudioSampleBuffer::getMagnitude (const int channel,
  21072. const int startSample,
  21073. const int numSamples) const throw()
  21074. {
  21075. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21076. jassert (startSample >= 0 && startSample + numSamples <= size);
  21077. float mn, mx;
  21078. findMinMax (channel, startSample, numSamples, mn, mx);
  21079. return jmax (mn, -mn, mx, -mx);
  21080. }
  21081. float AudioSampleBuffer::getMagnitude (const int startSample,
  21082. const int numSamples) const throw()
  21083. {
  21084. float mag = 0.0f;
  21085. for (int i = 0; i < numChannels; ++i)
  21086. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21087. return mag;
  21088. }
  21089. float AudioSampleBuffer::getRMSLevel (const int channel,
  21090. const int startSample,
  21091. const int numSamples) const throw()
  21092. {
  21093. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21094. jassert (startSample >= 0 && startSample + numSamples <= size);
  21095. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21096. return 0.0f;
  21097. const float* const data = channels [channel] + startSample;
  21098. double sum = 0.0;
  21099. for (int i = 0; i < numSamples; ++i)
  21100. {
  21101. const float sample = data [i];
  21102. sum += sample * sample;
  21103. }
  21104. return (float) std::sqrt (sum / numSamples);
  21105. }
  21106. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21107. const int startSample,
  21108. const int numSamples,
  21109. const int readerStartSample,
  21110. const bool useLeftChan,
  21111. const bool useRightChan)
  21112. {
  21113. jassert (reader != 0);
  21114. jassert (startSample >= 0 && startSample + numSamples <= size);
  21115. if (numSamples > 0)
  21116. {
  21117. int* chans[3];
  21118. if (useLeftChan == useRightChan)
  21119. {
  21120. chans[0] = (int*) getSampleData (0, startSample);
  21121. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  21122. }
  21123. else if (useLeftChan || (reader->numChannels == 1))
  21124. {
  21125. chans[0] = (int*) getSampleData (0, startSample);
  21126. chans[1] = 0;
  21127. }
  21128. else if (useRightChan)
  21129. {
  21130. chans[0] = 0;
  21131. chans[1] = (int*) getSampleData (0, startSample);
  21132. }
  21133. chans[2] = 0;
  21134. reader->read (chans, 2, readerStartSample, numSamples, true);
  21135. if (! reader->usesFloatingPointData)
  21136. {
  21137. for (int j = 0; j < 2; ++j)
  21138. {
  21139. float* const d = reinterpret_cast <float*> (chans[j]);
  21140. if (d != 0)
  21141. {
  21142. const float multiplier = 1.0f / 0x7fffffff;
  21143. for (int i = 0; i < numSamples; ++i)
  21144. d[i] = *(int*)(d + i) * multiplier;
  21145. }
  21146. }
  21147. }
  21148. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  21149. {
  21150. // if this is a stereo buffer and the source was mono, dupe the first channel..
  21151. memcpy (getSampleData (1, startSample),
  21152. getSampleData (0, startSample),
  21153. sizeof (float) * numSamples);
  21154. }
  21155. }
  21156. }
  21157. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  21158. const int startSample,
  21159. const int numSamples) const
  21160. {
  21161. jassert (startSample >= 0 && startSample + numSamples <= size && numChannels > 0);
  21162. if (numSamples > 0)
  21163. {
  21164. HeapBlock<int> tempBuffer;
  21165. HeapBlock<int*> chans (numChannels + 1);
  21166. chans [numChannels] = 0;
  21167. if (writer->isFloatingPoint())
  21168. {
  21169. for (int i = numChannels; --i >= 0;)
  21170. chans[i] = (int*) channels[i] + startSample;
  21171. }
  21172. else
  21173. {
  21174. tempBuffer.malloc (numSamples * numChannels);
  21175. for (int j = 0; j < numChannels; ++j)
  21176. {
  21177. int* const dest = tempBuffer + j * numSamples;
  21178. const float* const src = channels[j] + startSample;
  21179. chans[j] = dest;
  21180. for (int i = 0; i < numSamples; ++i)
  21181. {
  21182. const double samp = src[i];
  21183. if (samp <= -1.0)
  21184. dest[i] = std::numeric_limits<int>::min();
  21185. else if (samp >= 1.0)
  21186. dest[i] = std::numeric_limits<int>::max();
  21187. else
  21188. dest[i] = roundToInt (std::numeric_limits<int>::max() * samp);
  21189. }
  21190. }
  21191. }
  21192. writer->write ((const int**) chans.getData(), numSamples);
  21193. }
  21194. }
  21195. END_JUCE_NAMESPACE
  21196. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  21197. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  21198. BEGIN_JUCE_NAMESPACE
  21199. IIRFilter::IIRFilter()
  21200. : active (false)
  21201. {
  21202. reset();
  21203. }
  21204. IIRFilter::IIRFilter (const IIRFilter& other)
  21205. : active (other.active)
  21206. {
  21207. const ScopedLock sl (other.processLock);
  21208. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21209. reset();
  21210. }
  21211. IIRFilter::~IIRFilter()
  21212. {
  21213. }
  21214. void IIRFilter::reset() throw()
  21215. {
  21216. const ScopedLock sl (processLock);
  21217. x1 = 0;
  21218. x2 = 0;
  21219. y1 = 0;
  21220. y2 = 0;
  21221. }
  21222. float IIRFilter::processSingleSampleRaw (const float in) throw()
  21223. {
  21224. float out = coefficients[0] * in
  21225. + coefficients[1] * x1
  21226. + coefficients[2] * x2
  21227. - coefficients[4] * y1
  21228. - coefficients[5] * y2;
  21229. #if JUCE_INTEL
  21230. if (! (out < -1.0e-8 || out > 1.0e-8))
  21231. out = 0;
  21232. #endif
  21233. x2 = x1;
  21234. x1 = in;
  21235. y2 = y1;
  21236. y1 = out;
  21237. return out;
  21238. }
  21239. void IIRFilter::processSamples (float* const samples,
  21240. const int numSamples) throw()
  21241. {
  21242. const ScopedLock sl (processLock);
  21243. if (active)
  21244. {
  21245. for (int i = 0; i < numSamples; ++i)
  21246. {
  21247. const float in = samples[i];
  21248. float out = coefficients[0] * in
  21249. + coefficients[1] * x1
  21250. + coefficients[2] * x2
  21251. - coefficients[4] * y1
  21252. - coefficients[5] * y2;
  21253. #if JUCE_INTEL
  21254. if (! (out < -1.0e-8 || out > 1.0e-8))
  21255. out = 0;
  21256. #endif
  21257. x2 = x1;
  21258. x1 = in;
  21259. y2 = y1;
  21260. y1 = out;
  21261. samples[i] = out;
  21262. }
  21263. }
  21264. }
  21265. void IIRFilter::makeLowPass (const double sampleRate,
  21266. const double frequency) throw()
  21267. {
  21268. jassert (sampleRate > 0);
  21269. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  21270. const double nSquared = n * n;
  21271. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21272. setCoefficients (c1,
  21273. c1 * 2.0f,
  21274. c1,
  21275. 1.0,
  21276. c1 * 2.0 * (1.0 - nSquared),
  21277. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21278. }
  21279. void IIRFilter::makeHighPass (const double sampleRate,
  21280. const double frequency) throw()
  21281. {
  21282. const double n = tan (double_Pi * frequency / sampleRate);
  21283. const double nSquared = n * n;
  21284. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21285. setCoefficients (c1,
  21286. c1 * -2.0f,
  21287. c1,
  21288. 1.0,
  21289. c1 * 2.0 * (nSquared - 1.0),
  21290. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21291. }
  21292. void IIRFilter::makeLowShelf (const double sampleRate,
  21293. const double cutOffFrequency,
  21294. const double Q,
  21295. const float gainFactor) throw()
  21296. {
  21297. jassert (sampleRate > 0);
  21298. jassert (Q > 0);
  21299. const double A = jmax (0.0f, gainFactor);
  21300. const double aminus1 = A - 1.0;
  21301. const double aplus1 = A + 1.0;
  21302. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21303. const double coso = std::cos (omega);
  21304. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21305. const double aminus1TimesCoso = aminus1 * coso;
  21306. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  21307. A * 2.0 * (aminus1 - aplus1 * coso),
  21308. A * (aplus1 - aminus1TimesCoso - beta),
  21309. aplus1 + aminus1TimesCoso + beta,
  21310. -2.0 * (aminus1 + aplus1 * coso),
  21311. aplus1 + aminus1TimesCoso - beta);
  21312. }
  21313. void IIRFilter::makeHighShelf (const double sampleRate,
  21314. const double cutOffFrequency,
  21315. const double Q,
  21316. const float gainFactor) throw()
  21317. {
  21318. jassert (sampleRate > 0);
  21319. jassert (Q > 0);
  21320. const double A = jmax (0.0f, gainFactor);
  21321. const double aminus1 = A - 1.0;
  21322. const double aplus1 = A + 1.0;
  21323. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21324. const double coso = std::cos (omega);
  21325. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21326. const double aminus1TimesCoso = aminus1 * coso;
  21327. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  21328. A * -2.0 * (aminus1 + aplus1 * coso),
  21329. A * (aplus1 + aminus1TimesCoso - beta),
  21330. aplus1 - aminus1TimesCoso + beta,
  21331. 2.0 * (aminus1 - aplus1 * coso),
  21332. aplus1 - aminus1TimesCoso - beta);
  21333. }
  21334. void IIRFilter::makeBandPass (const double sampleRate,
  21335. const double centreFrequency,
  21336. const double Q,
  21337. const float gainFactor) throw()
  21338. {
  21339. jassert (sampleRate > 0);
  21340. jassert (Q > 0);
  21341. const double A = jmax (0.0f, gainFactor);
  21342. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  21343. const double alpha = 0.5 * std::sin (omega) / Q;
  21344. const double c2 = -2.0 * std::cos (omega);
  21345. const double alphaTimesA = alpha * A;
  21346. const double alphaOverA = alpha / A;
  21347. setCoefficients (1.0 + alphaTimesA,
  21348. c2,
  21349. 1.0 - alphaTimesA,
  21350. 1.0 + alphaOverA,
  21351. c2,
  21352. 1.0 - alphaOverA);
  21353. }
  21354. void IIRFilter::makeInactive() throw()
  21355. {
  21356. const ScopedLock sl (processLock);
  21357. active = false;
  21358. }
  21359. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  21360. {
  21361. const ScopedLock sl (processLock);
  21362. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21363. active = other.active;
  21364. }
  21365. void IIRFilter::setCoefficients (double c1,
  21366. double c2,
  21367. double c3,
  21368. double c4,
  21369. double c5,
  21370. double c6) throw()
  21371. {
  21372. const double a = 1.0 / c4;
  21373. c1 *= a;
  21374. c2 *= a;
  21375. c3 *= a;
  21376. c5 *= a;
  21377. c6 *= a;
  21378. const ScopedLock sl (processLock);
  21379. coefficients[0] = (float) c1;
  21380. coefficients[1] = (float) c2;
  21381. coefficients[2] = (float) c3;
  21382. coefficients[3] = (float) c4;
  21383. coefficients[4] = (float) c5;
  21384. coefficients[5] = (float) c6;
  21385. active = true;
  21386. }
  21387. END_JUCE_NAMESPACE
  21388. /*** End of inlined file: juce_IIRFilter.cpp ***/
  21389. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  21390. BEGIN_JUCE_NAMESPACE
  21391. MidiBuffer::MidiBuffer() throw()
  21392. : bytesUsed (0)
  21393. {
  21394. }
  21395. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  21396. : bytesUsed (0)
  21397. {
  21398. addEvent (message, 0);
  21399. }
  21400. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  21401. : data (other.data),
  21402. bytesUsed (other.bytesUsed)
  21403. {
  21404. }
  21405. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  21406. {
  21407. bytesUsed = other.bytesUsed;
  21408. data = other.data;
  21409. return *this;
  21410. }
  21411. void MidiBuffer::swapWith (MidiBuffer& other)
  21412. {
  21413. data.swapWith (other.data);
  21414. swapVariables <int> (bytesUsed, other.bytesUsed);
  21415. }
  21416. MidiBuffer::~MidiBuffer() throw()
  21417. {
  21418. }
  21419. inline uint8* MidiBuffer::getData() const throw()
  21420. {
  21421. return static_cast <uint8*> (data.getData());
  21422. }
  21423. inline int MidiBuffer::getEventTime (const void* const d) throw()
  21424. {
  21425. return *static_cast <const int*> (d);
  21426. }
  21427. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  21428. {
  21429. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  21430. }
  21431. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  21432. {
  21433. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  21434. }
  21435. void MidiBuffer::clear() throw()
  21436. {
  21437. bytesUsed = 0;
  21438. }
  21439. void MidiBuffer::clear (const int startSample,
  21440. const int numSamples) throw()
  21441. {
  21442. uint8* const start = findEventAfter (getData(), startSample - 1);
  21443. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  21444. if (end > start)
  21445. {
  21446. const int bytesToMove = bytesUsed - (int) (end - getData());
  21447. if (bytesToMove > 0)
  21448. memmove (start, end, bytesToMove);
  21449. bytesUsed -= (int) (end - start);
  21450. }
  21451. }
  21452. void MidiBuffer::addEvent (const MidiMessage& m,
  21453. const int sampleNumber) throw()
  21454. {
  21455. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  21456. }
  21457. static int findActualEventLength (const uint8* const data,
  21458. const int maxBytes) throw()
  21459. {
  21460. unsigned int byte = (unsigned int) *data;
  21461. int size = 0;
  21462. if (byte == 0xf0 || byte == 0xf7)
  21463. {
  21464. const uint8* d = data + 1;
  21465. while (d < data + maxBytes)
  21466. if (*d++ == 0xf7)
  21467. break;
  21468. size = (int) (d - data);
  21469. }
  21470. else if (byte == 0xff)
  21471. {
  21472. int n;
  21473. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  21474. size = jmin (maxBytes, n + 2 + bytesLeft);
  21475. }
  21476. else if (byte >= 0x80)
  21477. {
  21478. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  21479. }
  21480. return size;
  21481. }
  21482. void MidiBuffer::addEvent (const uint8* const newData,
  21483. const int maxBytes,
  21484. const int sampleNumber) throw()
  21485. {
  21486. const int numBytes = findActualEventLength (newData, maxBytes);
  21487. if (numBytes > 0)
  21488. {
  21489. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  21490. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  21491. uint8* d = findEventAfter (getData(), sampleNumber);
  21492. const int bytesToMove = bytesUsed - (int) (d - getData());
  21493. if (bytesToMove > 0)
  21494. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  21495. *reinterpret_cast <int*> (d) = sampleNumber;
  21496. d += sizeof (int);
  21497. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  21498. d += sizeof (uint16);
  21499. memcpy (d, newData, numBytes);
  21500. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  21501. }
  21502. }
  21503. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  21504. const int startSample,
  21505. const int numSamples,
  21506. const int sampleDeltaToAdd) throw()
  21507. {
  21508. Iterator i (otherBuffer);
  21509. i.setNextSamplePosition (startSample);
  21510. const uint8* eventData;
  21511. int eventSize, position;
  21512. while (i.getNextEvent (eventData, eventSize, position)
  21513. && (position < startSample + numSamples || numSamples < 0))
  21514. {
  21515. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  21516. }
  21517. }
  21518. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  21519. {
  21520. data.ensureSize (minimumNumBytes);
  21521. }
  21522. bool MidiBuffer::isEmpty() const throw()
  21523. {
  21524. return bytesUsed == 0;
  21525. }
  21526. int MidiBuffer::getNumEvents() const throw()
  21527. {
  21528. int n = 0;
  21529. const uint8* d = getData();
  21530. const uint8* const end = d + bytesUsed;
  21531. while (d < end)
  21532. {
  21533. d += getEventTotalSize (d);
  21534. ++n;
  21535. }
  21536. return n;
  21537. }
  21538. int MidiBuffer::getFirstEventTime() const throw()
  21539. {
  21540. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  21541. }
  21542. int MidiBuffer::getLastEventTime() const throw()
  21543. {
  21544. if (bytesUsed == 0)
  21545. return 0;
  21546. const uint8* d = getData();
  21547. const uint8* const endData = d + bytesUsed;
  21548. for (;;)
  21549. {
  21550. const uint8* const nextOne = d + getEventTotalSize (d);
  21551. if (nextOne >= endData)
  21552. return getEventTime (d);
  21553. d = nextOne;
  21554. }
  21555. }
  21556. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  21557. {
  21558. const uint8* const endData = getData() + bytesUsed;
  21559. while (d < endData && getEventTime (d) <= samplePosition)
  21560. d += getEventTotalSize (d);
  21561. return d;
  21562. }
  21563. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  21564. : buffer (buffer_),
  21565. data (buffer_.getData())
  21566. {
  21567. }
  21568. MidiBuffer::Iterator::~Iterator() throw()
  21569. {
  21570. }
  21571. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  21572. {
  21573. data = buffer.getData();
  21574. const uint8* dataEnd = data + buffer.bytesUsed;
  21575. while (data < dataEnd && getEventTime (data) < samplePosition)
  21576. data += getEventTotalSize (data);
  21577. }
  21578. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  21579. {
  21580. if (data >= buffer.getData() + buffer.bytesUsed)
  21581. return false;
  21582. samplePosition = getEventTime (data);
  21583. numBytes = getEventDataSize (data);
  21584. data += sizeof (int) + sizeof (uint16);
  21585. midiData = data;
  21586. data += numBytes;
  21587. return true;
  21588. }
  21589. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  21590. {
  21591. if (data >= buffer.getData() + buffer.bytesUsed)
  21592. return false;
  21593. samplePosition = getEventTime (data);
  21594. const int numBytes = getEventDataSize (data);
  21595. data += sizeof (int) + sizeof (uint16);
  21596. result = MidiMessage (data, numBytes, samplePosition);
  21597. data += numBytes;
  21598. return true;
  21599. }
  21600. END_JUCE_NAMESPACE
  21601. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  21602. /*** Start of inlined file: juce_MidiFile.cpp ***/
  21603. BEGIN_JUCE_NAMESPACE
  21604. namespace MidiFileHelpers
  21605. {
  21606. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  21607. {
  21608. unsigned int buffer = v & 0x7F;
  21609. while ((v >>= 7) != 0)
  21610. {
  21611. buffer <<= 8;
  21612. buffer |= ((v & 0x7F) | 0x80);
  21613. }
  21614. for (;;)
  21615. {
  21616. out.writeByte ((char) buffer);
  21617. if (buffer & 0x80)
  21618. buffer >>= 8;
  21619. else
  21620. break;
  21621. }
  21622. }
  21623. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  21624. {
  21625. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  21626. data += 4;
  21627. if (ch != ByteOrder::bigEndianInt ("MThd"))
  21628. {
  21629. bool ok = false;
  21630. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  21631. {
  21632. for (int i = 0; i < 8; ++i)
  21633. {
  21634. ch = ByteOrder::bigEndianInt (data);
  21635. data += 4;
  21636. if (ch == ByteOrder::bigEndianInt ("MThd"))
  21637. {
  21638. ok = true;
  21639. break;
  21640. }
  21641. }
  21642. }
  21643. if (! ok)
  21644. return false;
  21645. }
  21646. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  21647. data += 4;
  21648. fileType = (short) ByteOrder::bigEndianShort (data);
  21649. data += 2;
  21650. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  21651. data += 2;
  21652. timeFormat = (short) ByteOrder::bigEndianShort (data);
  21653. data += 2;
  21654. bytesRemaining -= 6;
  21655. data += bytesRemaining;
  21656. return true;
  21657. }
  21658. static double convertTicksToSeconds (const double time,
  21659. const MidiMessageSequence& tempoEvents,
  21660. const int timeFormat)
  21661. {
  21662. if (timeFormat > 0)
  21663. {
  21664. int numer = 4, denom = 4;
  21665. double tempoTime = 0.0, correctedTempoTime = 0.0;
  21666. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  21667. double secsPerTick = 0.5 * tickLen;
  21668. const int numEvents = tempoEvents.getNumEvents();
  21669. for (int i = 0; i < numEvents; ++i)
  21670. {
  21671. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  21672. if (time <= m.getTimeStamp())
  21673. break;
  21674. if (timeFormat > 0)
  21675. {
  21676. correctedTempoTime = correctedTempoTime
  21677. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  21678. }
  21679. else
  21680. {
  21681. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21682. }
  21683. tempoTime = m.getTimeStamp();
  21684. if (m.isTempoMetaEvent())
  21685. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  21686. else if (m.isTimeSignatureMetaEvent())
  21687. m.getTimeSignatureInfo (numer, denom);
  21688. while (i + 1 < numEvents)
  21689. {
  21690. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  21691. if (m2.getTimeStamp() == tempoTime)
  21692. {
  21693. ++i;
  21694. if (m2.isTempoMetaEvent())
  21695. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  21696. else if (m2.isTimeSignatureMetaEvent())
  21697. m2.getTimeSignatureInfo (numer, denom);
  21698. }
  21699. else
  21700. {
  21701. break;
  21702. }
  21703. }
  21704. }
  21705. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  21706. }
  21707. else
  21708. {
  21709. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21710. }
  21711. }
  21712. }
  21713. MidiFile::MidiFile()
  21714. : timeFormat ((short) (unsigned short) 0xe728)
  21715. {
  21716. }
  21717. MidiFile::~MidiFile()
  21718. {
  21719. clear();
  21720. }
  21721. void MidiFile::clear()
  21722. {
  21723. tracks.clear();
  21724. }
  21725. int MidiFile::getNumTracks() const throw()
  21726. {
  21727. return tracks.size();
  21728. }
  21729. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  21730. {
  21731. return tracks [index];
  21732. }
  21733. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  21734. {
  21735. tracks.add (new MidiMessageSequence (trackSequence));
  21736. }
  21737. short MidiFile::getTimeFormat() const throw()
  21738. {
  21739. return timeFormat;
  21740. }
  21741. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  21742. {
  21743. timeFormat = (short) ticks;
  21744. }
  21745. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  21746. const int subframeResolution) throw()
  21747. {
  21748. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  21749. }
  21750. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  21751. {
  21752. for (int i = tracks.size(); --i >= 0;)
  21753. {
  21754. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21755. for (int j = 0; j < numEvents; ++j)
  21756. {
  21757. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21758. if (m.isTempoMetaEvent())
  21759. tempoChangeEvents.addEvent (m);
  21760. }
  21761. }
  21762. }
  21763. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  21764. {
  21765. for (int i = tracks.size(); --i >= 0;)
  21766. {
  21767. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21768. for (int j = 0; j < numEvents; ++j)
  21769. {
  21770. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21771. if (m.isTimeSignatureMetaEvent())
  21772. timeSigEvents.addEvent (m);
  21773. }
  21774. }
  21775. }
  21776. double MidiFile::getLastTimestamp() const
  21777. {
  21778. double t = 0.0;
  21779. for (int i = tracks.size(); --i >= 0;)
  21780. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  21781. return t;
  21782. }
  21783. bool MidiFile::readFrom (InputStream& sourceStream)
  21784. {
  21785. clear();
  21786. MemoryBlock data;
  21787. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  21788. // (put a sanity-check on the file size, as midi files are generally small)
  21789. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  21790. {
  21791. size_t size = data.getSize();
  21792. const uint8* d = static_cast <const uint8*> (data.getData());
  21793. short fileType, expectedTracks;
  21794. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  21795. {
  21796. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  21797. int track = 0;
  21798. while (size > 0 && track < expectedTracks)
  21799. {
  21800. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  21801. d += 4;
  21802. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  21803. d += 4;
  21804. if (chunkSize <= 0)
  21805. break;
  21806. if (size < 0)
  21807. return false;
  21808. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  21809. {
  21810. readNextTrack (d, chunkSize);
  21811. }
  21812. size -= chunkSize + 8;
  21813. d += chunkSize;
  21814. ++track;
  21815. }
  21816. return true;
  21817. }
  21818. }
  21819. return false;
  21820. }
  21821. // a comparator that puts all the note-offs before note-ons that have the same time
  21822. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  21823. const MidiMessageSequence::MidiEventHolder* const second)
  21824. {
  21825. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  21826. if (diff == 0)
  21827. {
  21828. if (first->message.isNoteOff() && second->message.isNoteOn())
  21829. return -1;
  21830. else if (first->message.isNoteOn() && second->message.isNoteOff())
  21831. return 1;
  21832. else
  21833. return 0;
  21834. }
  21835. else
  21836. {
  21837. return (diff > 0) ? 1 : -1;
  21838. }
  21839. }
  21840. void MidiFile::readNextTrack (const uint8* data, int size)
  21841. {
  21842. double time = 0;
  21843. char lastStatusByte = 0;
  21844. MidiMessageSequence result;
  21845. while (size > 0)
  21846. {
  21847. int bytesUsed;
  21848. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  21849. data += bytesUsed;
  21850. size -= bytesUsed;
  21851. time += delay;
  21852. int messSize = 0;
  21853. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  21854. if (messSize <= 0)
  21855. break;
  21856. size -= messSize;
  21857. data += messSize;
  21858. result.addEvent (mm);
  21859. const char firstByte = *(mm.getRawData());
  21860. if ((firstByte & 0xf0) != 0xf0)
  21861. lastStatusByte = firstByte;
  21862. }
  21863. // use a sort that puts all the note-offs before note-ons that have the same time
  21864. result.list.sort (*this, true);
  21865. result.updateMatchedPairs();
  21866. addTrack (result);
  21867. }
  21868. void MidiFile::convertTimestampTicksToSeconds()
  21869. {
  21870. MidiMessageSequence tempoEvents;
  21871. findAllTempoEvents (tempoEvents);
  21872. findAllTimeSigEvents (tempoEvents);
  21873. for (int i = 0; i < tracks.size(); ++i)
  21874. {
  21875. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  21876. for (int j = ms.getNumEvents(); --j >= 0;)
  21877. {
  21878. MidiMessage& m = ms.getEventPointer(j)->message;
  21879. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  21880. tempoEvents,
  21881. timeFormat));
  21882. }
  21883. }
  21884. }
  21885. bool MidiFile::writeTo (OutputStream& out)
  21886. {
  21887. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  21888. out.writeIntBigEndian (6);
  21889. out.writeShortBigEndian (1); // type
  21890. out.writeShortBigEndian ((short) tracks.size());
  21891. out.writeShortBigEndian (timeFormat);
  21892. for (int i = 0; i < tracks.size(); ++i)
  21893. writeTrack (out, i);
  21894. out.flush();
  21895. return true;
  21896. }
  21897. void MidiFile::writeTrack (OutputStream& mainOut,
  21898. const int trackNum)
  21899. {
  21900. MemoryOutputStream out;
  21901. const MidiMessageSequence& ms = *tracks[trackNum];
  21902. int lastTick = 0;
  21903. char lastStatusByte = 0;
  21904. for (int i = 0; i < ms.getNumEvents(); ++i)
  21905. {
  21906. const MidiMessage& mm = ms.getEventPointer(i)->message;
  21907. const int tick = roundToInt (mm.getTimeStamp());
  21908. const int delta = jmax (0, tick - lastTick);
  21909. MidiFileHelpers::writeVariableLengthInt (out, delta);
  21910. lastTick = tick;
  21911. const char statusByte = *(mm.getRawData());
  21912. if ((statusByte == lastStatusByte)
  21913. && ((statusByte & 0xf0) != 0xf0)
  21914. && i > 0
  21915. && mm.getRawDataSize() > 1)
  21916. {
  21917. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  21918. }
  21919. else
  21920. {
  21921. out.write (mm.getRawData(), mm.getRawDataSize());
  21922. }
  21923. lastStatusByte = statusByte;
  21924. }
  21925. out.writeByte (0);
  21926. const MidiMessage m (MidiMessage::endOfTrack());
  21927. out.write (m.getRawData(),
  21928. m.getRawDataSize());
  21929. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  21930. mainOut.writeIntBigEndian ((int) out.getDataSize());
  21931. mainOut.write (out.getData(), (int) out.getDataSize());
  21932. }
  21933. END_JUCE_NAMESPACE
  21934. /*** End of inlined file: juce_MidiFile.cpp ***/
  21935. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  21936. BEGIN_JUCE_NAMESPACE
  21937. MidiKeyboardState::MidiKeyboardState()
  21938. {
  21939. zerostruct (noteStates);
  21940. }
  21941. MidiKeyboardState::~MidiKeyboardState()
  21942. {
  21943. }
  21944. void MidiKeyboardState::reset()
  21945. {
  21946. const ScopedLock sl (lock);
  21947. zerostruct (noteStates);
  21948. eventsToAdd.clear();
  21949. }
  21950. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  21951. {
  21952. jassert (midiChannel >= 0 && midiChannel <= 16);
  21953. return ((unsigned int) n) < 128
  21954. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  21955. }
  21956. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  21957. {
  21958. return ((unsigned int) n) < 128
  21959. && (noteStates[n] & midiChannelMask) != 0;
  21960. }
  21961. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  21962. {
  21963. jassert (midiChannel >= 0 && midiChannel <= 16);
  21964. jassert (((unsigned int) midiNoteNumber) < 128);
  21965. const ScopedLock sl (lock);
  21966. if (((unsigned int) midiNoteNumber) < 128)
  21967. {
  21968. const int timeNow = (int) Time::getMillisecondCounter();
  21969. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  21970. eventsToAdd.clear (0, timeNow - 500);
  21971. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  21972. }
  21973. }
  21974. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  21975. {
  21976. if (((unsigned int) midiNoteNumber) < 128)
  21977. {
  21978. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  21979. for (int i = listeners.size(); --i >= 0;)
  21980. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  21981. }
  21982. }
  21983. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  21984. {
  21985. const ScopedLock sl (lock);
  21986. if (isNoteOn (midiChannel, midiNoteNumber))
  21987. {
  21988. const int timeNow = (int) Time::getMillisecondCounter();
  21989. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  21990. eventsToAdd.clear (0, timeNow - 500);
  21991. noteOffInternal (midiChannel, midiNoteNumber);
  21992. }
  21993. }
  21994. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  21995. {
  21996. if (isNoteOn (midiChannel, midiNoteNumber))
  21997. {
  21998. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  21999. for (int i = listeners.size(); --i >= 0;)
  22000. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22001. }
  22002. }
  22003. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22004. {
  22005. const ScopedLock sl (lock);
  22006. if (midiChannel <= 0)
  22007. {
  22008. for (int i = 1; i <= 16; ++i)
  22009. allNotesOff (i);
  22010. }
  22011. else
  22012. {
  22013. for (int i = 0; i < 128; ++i)
  22014. noteOff (midiChannel, i);
  22015. }
  22016. }
  22017. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22018. {
  22019. if (message.isNoteOn())
  22020. {
  22021. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22022. }
  22023. else if (message.isNoteOff())
  22024. {
  22025. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22026. }
  22027. else if (message.isAllNotesOff())
  22028. {
  22029. for (int i = 0; i < 128; ++i)
  22030. noteOffInternal (message.getChannel(), i);
  22031. }
  22032. }
  22033. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22034. const int startSample,
  22035. const int numSamples,
  22036. const bool injectIndirectEvents)
  22037. {
  22038. MidiBuffer::Iterator i (buffer);
  22039. MidiMessage message (0xf4, 0.0);
  22040. int time;
  22041. const ScopedLock sl (lock);
  22042. while (i.getNextEvent (message, time))
  22043. processNextMidiEvent (message);
  22044. if (injectIndirectEvents)
  22045. {
  22046. MidiBuffer::Iterator i2 (eventsToAdd);
  22047. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22048. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22049. while (i2.getNextEvent (message, time))
  22050. {
  22051. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22052. buffer.addEvent (message, startSample + pos);
  22053. }
  22054. }
  22055. eventsToAdd.clear();
  22056. }
  22057. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  22058. {
  22059. const ScopedLock sl (lock);
  22060. listeners.addIfNotAlreadyThere (listener);
  22061. }
  22062. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  22063. {
  22064. const ScopedLock sl (lock);
  22065. listeners.removeValue (listener);
  22066. }
  22067. END_JUCE_NAMESPACE
  22068. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22069. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22070. BEGIN_JUCE_NAMESPACE
  22071. int MidiMessage::readVariableLengthVal (const uint8* data,
  22072. int& numBytesUsed) throw()
  22073. {
  22074. numBytesUsed = 0;
  22075. int v = 0;
  22076. int i;
  22077. do
  22078. {
  22079. i = (int) *data++;
  22080. if (++numBytesUsed > 6)
  22081. break;
  22082. v = (v << 7) + (i & 0x7f);
  22083. } while (i & 0x80);
  22084. return v;
  22085. }
  22086. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22087. {
  22088. // this method only works for valid starting bytes of a short midi message
  22089. jassert (firstByte >= 0x80
  22090. && firstByte != 0xf0
  22091. && firstByte != 0xf7);
  22092. static const char messageLengths[] =
  22093. {
  22094. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22095. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22096. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22097. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22098. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22099. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22100. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22101. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22102. };
  22103. return messageLengths [firstByte & 0x7f];
  22104. }
  22105. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22106. : timeStamp (t),
  22107. size (dataSize)
  22108. {
  22109. jassert (dataSize > 0);
  22110. if (dataSize <= 4)
  22111. data = static_cast<uint8*> (preallocatedData.asBytes);
  22112. else
  22113. data = new uint8 [dataSize];
  22114. memcpy (data, d, dataSize);
  22115. // check that the length matches the data..
  22116. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22117. }
  22118. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22119. : timeStamp (t),
  22120. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22121. size (1)
  22122. {
  22123. data[0] = (uint8) byte1;
  22124. // check that the length matches the data..
  22125. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22126. }
  22127. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22128. : timeStamp (t),
  22129. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22130. size (2)
  22131. {
  22132. data[0] = (uint8) byte1;
  22133. data[1] = (uint8) byte2;
  22134. // check that the length matches the data..
  22135. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22136. }
  22137. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22138. : timeStamp (t),
  22139. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22140. size (3)
  22141. {
  22142. data[0] = (uint8) byte1;
  22143. data[1] = (uint8) byte2;
  22144. data[2] = (uint8) byte3;
  22145. // check that the length matches the data..
  22146. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  22147. }
  22148. MidiMessage::MidiMessage (const MidiMessage& other)
  22149. : timeStamp (other.timeStamp),
  22150. size (other.size)
  22151. {
  22152. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22153. {
  22154. data = new uint8 [size];
  22155. memcpy (data, other.data, size);
  22156. }
  22157. else
  22158. {
  22159. data = static_cast<uint8*> (preallocatedData.asBytes);
  22160. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22161. }
  22162. }
  22163. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  22164. : timeStamp (newTimeStamp),
  22165. size (other.size)
  22166. {
  22167. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22168. {
  22169. data = new uint8 [size];
  22170. memcpy (data, other.data, size);
  22171. }
  22172. else
  22173. {
  22174. data = static_cast<uint8*> (preallocatedData.asBytes);
  22175. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22176. }
  22177. }
  22178. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  22179. : timeStamp (t),
  22180. data (static_cast<uint8*> (preallocatedData.asBytes))
  22181. {
  22182. const uint8* src = static_cast <const uint8*> (src_);
  22183. unsigned int byte = (unsigned int) *src;
  22184. if (byte < 0x80)
  22185. {
  22186. byte = (unsigned int) (uint8) lastStatusByte;
  22187. numBytesUsed = -1;
  22188. }
  22189. else
  22190. {
  22191. numBytesUsed = 0;
  22192. --sz;
  22193. ++src;
  22194. }
  22195. if (byte >= 0x80)
  22196. {
  22197. if (byte == 0xf0)
  22198. {
  22199. const uint8* d = src;
  22200. while (d < src + sz)
  22201. {
  22202. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  22203. {
  22204. if (*d == 0xf7) // include an 0xf7 if we hit one
  22205. ++d;
  22206. break;
  22207. }
  22208. ++d;
  22209. }
  22210. size = 1 + (int) (d - src);
  22211. data = new uint8 [size];
  22212. *data = (uint8) byte;
  22213. memcpy (data + 1, src, size - 1);
  22214. }
  22215. else if (byte == 0xff)
  22216. {
  22217. int n;
  22218. const int bytesLeft = readVariableLengthVal (src + 1, n);
  22219. size = jmin (sz + 1, n + 2 + bytesLeft);
  22220. data = new uint8 [size];
  22221. *data = (uint8) byte;
  22222. memcpy (data + 1, src, size - 1);
  22223. }
  22224. else
  22225. {
  22226. preallocatedData.asInt32 = 0;
  22227. size = getMessageLengthFromFirstByte ((uint8) byte);
  22228. data[0] = (uint8) byte;
  22229. if (size > 1)
  22230. {
  22231. data[1] = src[0];
  22232. if (size > 2)
  22233. data[2] = src[1];
  22234. }
  22235. }
  22236. numBytesUsed += size;
  22237. }
  22238. else
  22239. {
  22240. preallocatedData.asInt32 = 0;
  22241. size = 0;
  22242. }
  22243. }
  22244. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  22245. {
  22246. if (this != &other)
  22247. {
  22248. timeStamp = other.timeStamp;
  22249. size = other.size;
  22250. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22251. delete[] data;
  22252. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22253. {
  22254. data = new uint8 [size];
  22255. memcpy (data, other.data, size);
  22256. }
  22257. else
  22258. {
  22259. data = static_cast<uint8*> (preallocatedData.asBytes);
  22260. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22261. }
  22262. }
  22263. return *this;
  22264. }
  22265. MidiMessage::~MidiMessage()
  22266. {
  22267. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22268. delete[] data;
  22269. }
  22270. int MidiMessage::getChannel() const throw()
  22271. {
  22272. if ((data[0] & 0xf0) != 0xf0)
  22273. return (data[0] & 0xf) + 1;
  22274. else
  22275. return 0;
  22276. }
  22277. bool MidiMessage::isForChannel (const int channel) const throw()
  22278. {
  22279. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22280. return ((data[0] & 0xf) == channel - 1)
  22281. && ((data[0] & 0xf0) != 0xf0);
  22282. }
  22283. void MidiMessage::setChannel (const int channel) throw()
  22284. {
  22285. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22286. if ((data[0] & 0xf0) != (uint8) 0xf0)
  22287. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  22288. | (uint8)(channel - 1));
  22289. }
  22290. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  22291. {
  22292. return ((data[0] & 0xf0) == 0x90)
  22293. && (returnTrueForVelocity0 || data[2] != 0);
  22294. }
  22295. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  22296. {
  22297. return ((data[0] & 0xf0) == 0x80)
  22298. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  22299. }
  22300. bool MidiMessage::isNoteOnOrOff() const throw()
  22301. {
  22302. const int d = data[0] & 0xf0;
  22303. return (d == 0x90) || (d == 0x80);
  22304. }
  22305. int MidiMessage::getNoteNumber() const throw()
  22306. {
  22307. return data[1];
  22308. }
  22309. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  22310. {
  22311. if (isNoteOnOrOff())
  22312. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  22313. }
  22314. uint8 MidiMessage::getVelocity() const throw()
  22315. {
  22316. if (isNoteOnOrOff())
  22317. return data[2];
  22318. else
  22319. return 0;
  22320. }
  22321. float MidiMessage::getFloatVelocity() const throw()
  22322. {
  22323. return getVelocity() * (1.0f / 127.0f);
  22324. }
  22325. void MidiMessage::setVelocity (const float newVelocity) throw()
  22326. {
  22327. if (isNoteOnOrOff())
  22328. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  22329. }
  22330. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  22331. {
  22332. if (isNoteOnOrOff())
  22333. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  22334. }
  22335. bool MidiMessage::isAftertouch() const throw()
  22336. {
  22337. return (data[0] & 0xf0) == 0xa0;
  22338. }
  22339. int MidiMessage::getAfterTouchValue() const throw()
  22340. {
  22341. return data[2];
  22342. }
  22343. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  22344. const int noteNum,
  22345. const int aftertouchValue) throw()
  22346. {
  22347. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22348. jassert (((unsigned int) noteNum) <= 127);
  22349. jassert (((unsigned int) aftertouchValue) <= 127);
  22350. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  22351. noteNum & 0x7f,
  22352. aftertouchValue & 0x7f);
  22353. }
  22354. bool MidiMessage::isChannelPressure() const throw()
  22355. {
  22356. return (data[0] & 0xf0) == 0xd0;
  22357. }
  22358. int MidiMessage::getChannelPressureValue() const throw()
  22359. {
  22360. jassert (isChannelPressure());
  22361. return data[1];
  22362. }
  22363. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  22364. const int pressure) throw()
  22365. {
  22366. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22367. jassert (((unsigned int) pressure) <= 127);
  22368. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  22369. pressure & 0x7f);
  22370. }
  22371. bool MidiMessage::isProgramChange() const throw()
  22372. {
  22373. return (data[0] & 0xf0) == 0xc0;
  22374. }
  22375. int MidiMessage::getProgramChangeNumber() const throw()
  22376. {
  22377. return data[1];
  22378. }
  22379. const MidiMessage MidiMessage::programChange (const int channel,
  22380. const int programNumber) throw()
  22381. {
  22382. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22383. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  22384. programNumber & 0x7f);
  22385. }
  22386. bool MidiMessage::isPitchWheel() const throw()
  22387. {
  22388. return (data[0] & 0xf0) == 0xe0;
  22389. }
  22390. int MidiMessage::getPitchWheelValue() const throw()
  22391. {
  22392. return data[1] | (data[2] << 7);
  22393. }
  22394. const MidiMessage MidiMessage::pitchWheel (const int channel,
  22395. const int position) throw()
  22396. {
  22397. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22398. jassert (((unsigned int) position) <= 0x3fff);
  22399. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  22400. position & 127,
  22401. (position >> 7) & 127);
  22402. }
  22403. bool MidiMessage::isController() const throw()
  22404. {
  22405. return (data[0] & 0xf0) == 0xb0;
  22406. }
  22407. int MidiMessage::getControllerNumber() const throw()
  22408. {
  22409. jassert (isController());
  22410. return data[1];
  22411. }
  22412. int MidiMessage::getControllerValue() const throw()
  22413. {
  22414. jassert (isController());
  22415. return data[2];
  22416. }
  22417. const MidiMessage MidiMessage::controllerEvent (const int channel,
  22418. const int controllerType,
  22419. const int value) throw()
  22420. {
  22421. // the channel must be between 1 and 16 inclusive
  22422. jassert (channel > 0 && channel <= 16);
  22423. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  22424. controllerType & 127,
  22425. value & 127);
  22426. }
  22427. const MidiMessage MidiMessage::noteOn (const int channel,
  22428. const int noteNumber,
  22429. const float velocity) throw()
  22430. {
  22431. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  22432. }
  22433. const MidiMessage MidiMessage::noteOn (const int channel,
  22434. const int noteNumber,
  22435. const uint8 velocity) throw()
  22436. {
  22437. jassert (channel > 0 && channel <= 16);
  22438. jassert (((unsigned int) noteNumber) <= 127);
  22439. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  22440. noteNumber & 127,
  22441. jlimit (0, 127, roundToInt (velocity)));
  22442. }
  22443. const MidiMessage MidiMessage::noteOff (const int channel,
  22444. const int noteNumber) throw()
  22445. {
  22446. jassert (channel > 0 && channel <= 16);
  22447. jassert (((unsigned int) noteNumber) <= 127);
  22448. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  22449. }
  22450. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  22451. {
  22452. jassert (channel > 0 && channel <= 16);
  22453. return controllerEvent (channel, 123, 0);
  22454. }
  22455. bool MidiMessage::isAllNotesOff() const throw()
  22456. {
  22457. return (data[0] & 0xf0) == 0xb0
  22458. && data[1] == 123;
  22459. }
  22460. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  22461. {
  22462. return controllerEvent (channel, 120, 0);
  22463. }
  22464. bool MidiMessage::isAllSoundOff() const throw()
  22465. {
  22466. return (data[0] & 0xf0) == 0xb0
  22467. && data[1] == 120;
  22468. }
  22469. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  22470. {
  22471. return controllerEvent (channel, 121, 0);
  22472. }
  22473. const MidiMessage MidiMessage::masterVolume (const float volume)
  22474. {
  22475. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  22476. uint8 buf[8];
  22477. buf[0] = 0xf0;
  22478. buf[1] = 0x7f;
  22479. buf[2] = 0x7f;
  22480. buf[3] = 0x04;
  22481. buf[4] = 0x01;
  22482. buf[5] = (uint8) (vol & 0x7f);
  22483. buf[6] = (uint8) (vol >> 7);
  22484. buf[7] = 0xf7;
  22485. return MidiMessage (buf, 8);
  22486. }
  22487. bool MidiMessage::isSysEx() const throw()
  22488. {
  22489. return *data == 0xf0;
  22490. }
  22491. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  22492. {
  22493. MemoryBlock mm (dataSize + 2);
  22494. uint8* const m = static_cast <uint8*> (mm.getData());
  22495. m[0] = 0xf0;
  22496. memcpy (m + 1, sysexData, dataSize);
  22497. m[dataSize + 1] = 0xf7;
  22498. return MidiMessage (m, dataSize + 2);
  22499. }
  22500. const uint8* MidiMessage::getSysExData() const throw()
  22501. {
  22502. return (isSysEx()) ? getRawData() + 1 : 0;
  22503. }
  22504. int MidiMessage::getSysExDataSize() const throw()
  22505. {
  22506. return (isSysEx()) ? size - 2 : 0;
  22507. }
  22508. bool MidiMessage::isMetaEvent() const throw()
  22509. {
  22510. return *data == 0xff;
  22511. }
  22512. bool MidiMessage::isActiveSense() const throw()
  22513. {
  22514. return *data == 0xfe;
  22515. }
  22516. int MidiMessage::getMetaEventType() const throw()
  22517. {
  22518. if (*data != 0xff)
  22519. return -1;
  22520. else
  22521. return data[1];
  22522. }
  22523. int MidiMessage::getMetaEventLength() const throw()
  22524. {
  22525. if (*data == 0xff)
  22526. {
  22527. int n;
  22528. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  22529. }
  22530. return 0;
  22531. }
  22532. const uint8* MidiMessage::getMetaEventData() const throw()
  22533. {
  22534. int n;
  22535. const uint8* d = data + 2;
  22536. readVariableLengthVal (d, n);
  22537. return d + n;
  22538. }
  22539. bool MidiMessage::isTrackMetaEvent() const throw()
  22540. {
  22541. return getMetaEventType() == 0;
  22542. }
  22543. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  22544. {
  22545. return getMetaEventType() == 47;
  22546. }
  22547. bool MidiMessage::isTextMetaEvent() const throw()
  22548. {
  22549. const int t = getMetaEventType();
  22550. return t > 0 && t < 16;
  22551. }
  22552. const String MidiMessage::getTextFromTextMetaEvent() const
  22553. {
  22554. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  22555. }
  22556. bool MidiMessage::isTrackNameEvent() const throw()
  22557. {
  22558. return (data[1] == 3)
  22559. && (*data == 0xff);
  22560. }
  22561. bool MidiMessage::isTempoMetaEvent() const throw()
  22562. {
  22563. return (data[1] == 81)
  22564. && (*data == 0xff);
  22565. }
  22566. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  22567. {
  22568. return (data[1] == 0x20)
  22569. && (*data == 0xff)
  22570. && (data[2] == 1);
  22571. }
  22572. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  22573. {
  22574. return data[3] + 1;
  22575. }
  22576. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  22577. {
  22578. if (! isTempoMetaEvent())
  22579. return 0.0;
  22580. const uint8* const d = getMetaEventData();
  22581. return (((unsigned int) d[0] << 16)
  22582. | ((unsigned int) d[1] << 8)
  22583. | d[2])
  22584. / 1000000.0;
  22585. }
  22586. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  22587. {
  22588. if (timeFormat > 0)
  22589. {
  22590. if (! isTempoMetaEvent())
  22591. return 0.5 / timeFormat;
  22592. return getTempoSecondsPerQuarterNote() / timeFormat;
  22593. }
  22594. else
  22595. {
  22596. const int frameCode = (-timeFormat) >> 8;
  22597. double framesPerSecond;
  22598. switch (frameCode)
  22599. {
  22600. case 24: framesPerSecond = 24.0; break;
  22601. case 25: framesPerSecond = 25.0; break;
  22602. case 29: framesPerSecond = 29.97; break;
  22603. case 30: framesPerSecond = 30.0; break;
  22604. default: framesPerSecond = 30.0; break;
  22605. }
  22606. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  22607. }
  22608. }
  22609. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  22610. {
  22611. uint8 d[8];
  22612. d[0] = 0xff;
  22613. d[1] = 81;
  22614. d[2] = 3;
  22615. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  22616. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  22617. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  22618. return MidiMessage (d, 6, 0.0);
  22619. }
  22620. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  22621. {
  22622. return (data[1] == 0x58)
  22623. && (*data == (uint8) 0xff);
  22624. }
  22625. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  22626. {
  22627. if (isTimeSignatureMetaEvent())
  22628. {
  22629. const uint8* const d = getMetaEventData();
  22630. numerator = d[0];
  22631. denominator = 1 << d[1];
  22632. }
  22633. else
  22634. {
  22635. numerator = 4;
  22636. denominator = 4;
  22637. }
  22638. }
  22639. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  22640. {
  22641. uint8 d[8];
  22642. d[0] = 0xff;
  22643. d[1] = 0x58;
  22644. d[2] = 0x04;
  22645. d[3] = (uint8) numerator;
  22646. int n = 1;
  22647. int powerOfTwo = 0;
  22648. while (n < denominator)
  22649. {
  22650. n <<= 1;
  22651. ++powerOfTwo;
  22652. }
  22653. d[4] = (uint8) powerOfTwo;
  22654. d[5] = 0x01;
  22655. d[6] = 96;
  22656. return MidiMessage (d, 7, 0.0);
  22657. }
  22658. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  22659. {
  22660. uint8 d[8];
  22661. d[0] = 0xff;
  22662. d[1] = 0x20;
  22663. d[2] = 0x01;
  22664. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  22665. return MidiMessage (d, 4, 0.0);
  22666. }
  22667. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  22668. {
  22669. return getMetaEventType() == 89;
  22670. }
  22671. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  22672. {
  22673. return (int) *getMetaEventData();
  22674. }
  22675. const MidiMessage MidiMessage::endOfTrack() throw()
  22676. {
  22677. return MidiMessage (0xff, 0x2f, 0, 0.0);
  22678. }
  22679. bool MidiMessage::isSongPositionPointer() const throw()
  22680. {
  22681. return *data == 0xf2;
  22682. }
  22683. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  22684. {
  22685. return data[1] | (data[2] << 7);
  22686. }
  22687. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  22688. {
  22689. return MidiMessage (0xf2,
  22690. positionInMidiBeats & 127,
  22691. (positionInMidiBeats >> 7) & 127);
  22692. }
  22693. bool MidiMessage::isMidiStart() const throw()
  22694. {
  22695. return *data == 0xfa;
  22696. }
  22697. const MidiMessage MidiMessage::midiStart() throw()
  22698. {
  22699. return MidiMessage (0xfa);
  22700. }
  22701. bool MidiMessage::isMidiContinue() const throw()
  22702. {
  22703. return *data == 0xfb;
  22704. }
  22705. const MidiMessage MidiMessage::midiContinue() throw()
  22706. {
  22707. return MidiMessage (0xfb);
  22708. }
  22709. bool MidiMessage::isMidiStop() const throw()
  22710. {
  22711. return *data == 0xfc;
  22712. }
  22713. const MidiMessage MidiMessage::midiStop() throw()
  22714. {
  22715. return MidiMessage (0xfc);
  22716. }
  22717. bool MidiMessage::isMidiClock() const throw()
  22718. {
  22719. return *data == 0xf8;
  22720. }
  22721. const MidiMessage MidiMessage::midiClock() throw()
  22722. {
  22723. return MidiMessage (0xf8);
  22724. }
  22725. bool MidiMessage::isQuarterFrame() const throw()
  22726. {
  22727. return *data == 0xf1;
  22728. }
  22729. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  22730. {
  22731. return ((int) data[1]) >> 4;
  22732. }
  22733. int MidiMessage::getQuarterFrameValue() const throw()
  22734. {
  22735. return ((int) data[1]) & 0x0f;
  22736. }
  22737. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  22738. const int value) throw()
  22739. {
  22740. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  22741. }
  22742. bool MidiMessage::isFullFrame() const throw()
  22743. {
  22744. return data[0] == 0xf0
  22745. && data[1] == 0x7f
  22746. && size >= 10
  22747. && data[3] == 0x01
  22748. && data[4] == 0x01;
  22749. }
  22750. void MidiMessage::getFullFrameParameters (int& hours,
  22751. int& minutes,
  22752. int& seconds,
  22753. int& frames,
  22754. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  22755. {
  22756. jassert (isFullFrame());
  22757. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  22758. hours = data[5] & 0x1f;
  22759. minutes = data[6];
  22760. seconds = data[7];
  22761. frames = data[8];
  22762. }
  22763. const MidiMessage MidiMessage::fullFrame (const int hours,
  22764. const int minutes,
  22765. const int seconds,
  22766. const int frames,
  22767. MidiMessage::SmpteTimecodeType timecodeType)
  22768. {
  22769. uint8 d[10];
  22770. d[0] = 0xf0;
  22771. d[1] = 0x7f;
  22772. d[2] = 0x7f;
  22773. d[3] = 0x01;
  22774. d[4] = 0x01;
  22775. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  22776. d[6] = (uint8) minutes;
  22777. d[7] = (uint8) seconds;
  22778. d[8] = (uint8) frames;
  22779. d[9] = 0xf7;
  22780. return MidiMessage (d, 10, 0.0);
  22781. }
  22782. bool MidiMessage::isMidiMachineControlMessage() const throw()
  22783. {
  22784. return data[0] == 0xf0
  22785. && data[1] == 0x7f
  22786. && data[3] == 0x06
  22787. && size > 5;
  22788. }
  22789. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  22790. {
  22791. jassert (isMidiMachineControlMessage());
  22792. return (MidiMachineControlCommand) data[4];
  22793. }
  22794. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  22795. {
  22796. uint8 d[6];
  22797. d[0] = 0xf0;
  22798. d[1] = 0x7f;
  22799. d[2] = 0x00;
  22800. d[3] = 0x06;
  22801. d[4] = (uint8) command;
  22802. d[5] = 0xf7;
  22803. return MidiMessage (d, 6, 0.0);
  22804. }
  22805. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  22806. int& minutes,
  22807. int& seconds,
  22808. int& frames) const throw()
  22809. {
  22810. if (size >= 12
  22811. && data[0] == 0xf0
  22812. && data[1] == 0x7f
  22813. && data[3] == 0x06
  22814. && data[4] == 0x44
  22815. && data[5] == 0x06
  22816. && data[6] == 0x01)
  22817. {
  22818. hours = data[7] % 24; // (that some machines send out hours > 24)
  22819. minutes = data[8];
  22820. seconds = data[9];
  22821. frames = data[10];
  22822. return true;
  22823. }
  22824. return false;
  22825. }
  22826. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  22827. int minutes,
  22828. int seconds,
  22829. int frames)
  22830. {
  22831. uint8 d[12];
  22832. d[0] = 0xf0;
  22833. d[1] = 0x7f;
  22834. d[2] = 0x00;
  22835. d[3] = 0x06;
  22836. d[4] = 0x44;
  22837. d[5] = 0x06;
  22838. d[6] = 0x01;
  22839. d[7] = (uint8) hours;
  22840. d[8] = (uint8) minutes;
  22841. d[9] = (uint8) seconds;
  22842. d[10] = (uint8) frames;
  22843. d[11] = 0xf7;
  22844. return MidiMessage (d, 12, 0.0);
  22845. }
  22846. const String MidiMessage::getMidiNoteName (int note,
  22847. bool useSharps,
  22848. bool includeOctaveNumber,
  22849. int octaveNumForMiddleC) throw()
  22850. {
  22851. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  22852. "F", "F#", "G", "G#", "A",
  22853. "A#", "B" };
  22854. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  22855. "F", "Gb", "G", "Ab", "A",
  22856. "Bb", "B" };
  22857. if (((unsigned int) note) < 128)
  22858. {
  22859. const String s ((useSharps) ? sharpNoteNames [note % 12]
  22860. : flatNoteNames [note % 12]);
  22861. if (includeOctaveNumber)
  22862. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  22863. else
  22864. return s;
  22865. }
  22866. return String::empty;
  22867. }
  22868. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  22869. {
  22870. noteNumber -= 12 * 6 + 9; // now 0 = A440
  22871. return 440.0 * pow (2.0, noteNumber / 12.0);
  22872. }
  22873. const String MidiMessage::getGMInstrumentName (int n) throw()
  22874. {
  22875. const char *names[] =
  22876. {
  22877. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  22878. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  22879. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  22880. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  22881. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  22882. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  22883. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  22884. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  22885. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  22886. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  22887. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  22888. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  22889. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  22890. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  22891. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  22892. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  22893. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  22894. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  22895. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  22896. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  22897. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  22898. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  22899. "Applause", "Gunshot"
  22900. };
  22901. return (((unsigned int) n) < 128) ? names[n]
  22902. : (const char*)0;
  22903. }
  22904. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  22905. {
  22906. const char* names[] =
  22907. {
  22908. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  22909. "Bass", "Strings", "Ensemble", "Brass",
  22910. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  22911. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  22912. };
  22913. return (((unsigned int) n) <= 15) ? names[n]
  22914. : (const char*)0;
  22915. }
  22916. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  22917. {
  22918. const char* names[] =
  22919. {
  22920. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  22921. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  22922. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  22923. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  22924. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  22925. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  22926. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  22927. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  22928. "Mute Triangle", "Open Triangle"
  22929. };
  22930. return (n >= 35 && n <= 81) ? names [n - 35]
  22931. : (const char*)0;
  22932. }
  22933. const String MidiMessage::getControllerName (int n) throw()
  22934. {
  22935. const char* names[] =
  22936. {
  22937. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  22938. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  22939. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  22940. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  22941. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  22942. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  22943. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  22944. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  22945. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  22946. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22947. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  22948. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  22949. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  22950. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  22951. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  22952. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  22953. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  22954. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  22955. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  22956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  22957. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  22958. "Poly Operation"
  22959. };
  22960. return (((unsigned int) n) < 128) ? names[n]
  22961. : (const char*)0;
  22962. }
  22963. END_JUCE_NAMESPACE
  22964. /*** End of inlined file: juce_MidiMessage.cpp ***/
  22965. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  22966. BEGIN_JUCE_NAMESPACE
  22967. MidiMessageCollector::MidiMessageCollector()
  22968. : lastCallbackTime (0),
  22969. sampleRate (44100.0001)
  22970. {
  22971. }
  22972. MidiMessageCollector::~MidiMessageCollector()
  22973. {
  22974. }
  22975. void MidiMessageCollector::reset (const double sampleRate_)
  22976. {
  22977. jassert (sampleRate_ > 0);
  22978. const ScopedLock sl (midiCallbackLock);
  22979. sampleRate = sampleRate_;
  22980. incomingMessages.clear();
  22981. lastCallbackTime = Time::getMillisecondCounterHiRes();
  22982. }
  22983. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  22984. {
  22985. // you need to call reset() to set the correct sample rate before using this object
  22986. jassert (sampleRate != 44100.0001);
  22987. // the messages that come in here need to be time-stamped correctly - see MidiInput
  22988. // for details of what the number should be.
  22989. jassert (message.getTimeStamp() != 0);
  22990. const ScopedLock sl (midiCallbackLock);
  22991. const int sampleNumber
  22992. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  22993. incomingMessages.addEvent (message, sampleNumber);
  22994. // if the messages don't get used for over a second, we'd better
  22995. // get rid of any old ones to avoid the queue getting too big
  22996. if (sampleNumber > sampleRate)
  22997. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  22998. }
  22999. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23000. const int numSamples)
  23001. {
  23002. // you need to call reset() to set the correct sample rate before using this object
  23003. jassert (sampleRate != 44100.0001);
  23004. const double timeNow = Time::getMillisecondCounterHiRes();
  23005. const double msElapsed = timeNow - lastCallbackTime;
  23006. const ScopedLock sl (midiCallbackLock);
  23007. lastCallbackTime = timeNow;
  23008. if (! incomingMessages.isEmpty())
  23009. {
  23010. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23011. int startSample = 0;
  23012. int scale = 1 << 16;
  23013. const uint8* midiData;
  23014. int numBytes, samplePosition;
  23015. MidiBuffer::Iterator iter (incomingMessages);
  23016. if (numSourceSamples > numSamples)
  23017. {
  23018. // if our list of events is longer than the buffer we're being
  23019. // asked for, scale them down to squeeze them all in..
  23020. const int maxBlockLengthToUse = numSamples << 5;
  23021. if (numSourceSamples > maxBlockLengthToUse)
  23022. {
  23023. startSample = numSourceSamples - maxBlockLengthToUse;
  23024. numSourceSamples = maxBlockLengthToUse;
  23025. iter.setNextSamplePosition (startSample);
  23026. }
  23027. scale = (numSamples << 10) / numSourceSamples;
  23028. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23029. {
  23030. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23031. destBuffer.addEvent (midiData, numBytes,
  23032. jlimit (0, numSamples - 1, samplePosition));
  23033. }
  23034. }
  23035. else
  23036. {
  23037. // if our event list is shorter than the number we need, put them
  23038. // towards the end of the buffer
  23039. startSample = numSamples - numSourceSamples;
  23040. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23041. {
  23042. destBuffer.addEvent (midiData, numBytes,
  23043. jlimit (0, numSamples - 1, samplePosition + startSample));
  23044. }
  23045. }
  23046. incomingMessages.clear();
  23047. }
  23048. }
  23049. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23050. {
  23051. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23052. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23053. addMessageToQueue (m);
  23054. }
  23055. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23056. {
  23057. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23058. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23059. addMessageToQueue (m);
  23060. }
  23061. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23062. {
  23063. addMessageToQueue (message);
  23064. }
  23065. END_JUCE_NAMESPACE
  23066. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23067. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23068. BEGIN_JUCE_NAMESPACE
  23069. MidiMessageSequence::MidiMessageSequence()
  23070. {
  23071. }
  23072. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23073. {
  23074. list.ensureStorageAllocated (other.list.size());
  23075. for (int i = 0; i < other.list.size(); ++i)
  23076. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23077. }
  23078. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23079. {
  23080. MidiMessageSequence otherCopy (other);
  23081. swapWith (otherCopy);
  23082. return *this;
  23083. }
  23084. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23085. {
  23086. list.swapWithArray (other.list);
  23087. }
  23088. MidiMessageSequence::~MidiMessageSequence()
  23089. {
  23090. }
  23091. void MidiMessageSequence::clear()
  23092. {
  23093. list.clear();
  23094. }
  23095. int MidiMessageSequence::getNumEvents() const
  23096. {
  23097. return list.size();
  23098. }
  23099. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23100. {
  23101. return list [index];
  23102. }
  23103. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23104. {
  23105. const MidiEventHolder* const meh = list [index];
  23106. if (meh != 0 && meh->noteOffObject != 0)
  23107. return meh->noteOffObject->message.getTimeStamp();
  23108. else
  23109. return 0.0;
  23110. }
  23111. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23112. {
  23113. const MidiEventHolder* const meh = list [index];
  23114. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23115. }
  23116. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23117. {
  23118. return list.indexOf (event);
  23119. }
  23120. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23121. {
  23122. const int numEvents = list.size();
  23123. int i;
  23124. for (i = 0; i < numEvents; ++i)
  23125. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23126. break;
  23127. return i;
  23128. }
  23129. double MidiMessageSequence::getStartTime() const
  23130. {
  23131. if (list.size() > 0)
  23132. return list.getUnchecked(0)->message.getTimeStamp();
  23133. else
  23134. return 0;
  23135. }
  23136. double MidiMessageSequence::getEndTime() const
  23137. {
  23138. if (list.size() > 0)
  23139. return list.getLast()->message.getTimeStamp();
  23140. else
  23141. return 0;
  23142. }
  23143. double MidiMessageSequence::getEventTime (const int index) const
  23144. {
  23145. if (((unsigned int) index) < (unsigned int) list.size())
  23146. return list.getUnchecked (index)->message.getTimeStamp();
  23147. return 0.0;
  23148. }
  23149. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23150. double timeAdjustment)
  23151. {
  23152. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23153. timeAdjustment += newMessage.getTimeStamp();
  23154. newOne->message.setTimeStamp (timeAdjustment);
  23155. int i;
  23156. for (i = list.size(); --i >= 0;)
  23157. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  23158. break;
  23159. list.insert (i + 1, newOne);
  23160. }
  23161. void MidiMessageSequence::deleteEvent (const int index,
  23162. const bool deleteMatchingNoteUp)
  23163. {
  23164. if (((unsigned int) index) < (unsigned int) list.size())
  23165. {
  23166. if (deleteMatchingNoteUp)
  23167. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  23168. list.remove (index);
  23169. }
  23170. }
  23171. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  23172. double timeAdjustment,
  23173. double firstAllowableTime,
  23174. double endOfAllowableDestTimes)
  23175. {
  23176. firstAllowableTime -= timeAdjustment;
  23177. endOfAllowableDestTimes -= timeAdjustment;
  23178. for (int i = 0; i < other.list.size(); ++i)
  23179. {
  23180. const MidiMessage& m = other.list.getUnchecked(i)->message;
  23181. const double t = m.getTimeStamp();
  23182. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  23183. {
  23184. MidiEventHolder* const newOne = new MidiEventHolder (m);
  23185. newOne->message.setTimeStamp (timeAdjustment + t);
  23186. list.add (newOne);
  23187. }
  23188. }
  23189. sort();
  23190. }
  23191. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  23192. const MidiMessageSequence::MidiEventHolder* const second) throw()
  23193. {
  23194. const double diff = first->message.getTimeStamp()
  23195. - second->message.getTimeStamp();
  23196. return (diff > 0) - (diff < 0);
  23197. }
  23198. void MidiMessageSequence::sort()
  23199. {
  23200. list.sort (*this, true);
  23201. }
  23202. void MidiMessageSequence::updateMatchedPairs()
  23203. {
  23204. for (int i = 0; i < list.size(); ++i)
  23205. {
  23206. const MidiMessage& m1 = list.getUnchecked(i)->message;
  23207. if (m1.isNoteOn())
  23208. {
  23209. list.getUnchecked(i)->noteOffObject = 0;
  23210. const int note = m1.getNoteNumber();
  23211. const int chan = m1.getChannel();
  23212. const int len = list.size();
  23213. for (int j = i + 1; j < len; ++j)
  23214. {
  23215. const MidiMessage& m = list.getUnchecked(j)->message;
  23216. if (m.getNoteNumber() == note && m.getChannel() == chan)
  23217. {
  23218. if (m.isNoteOff())
  23219. {
  23220. list.getUnchecked(i)->noteOffObject = list[j];
  23221. break;
  23222. }
  23223. else if (m.isNoteOn())
  23224. {
  23225. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  23226. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  23227. list.getUnchecked(i)->noteOffObject = list[j];
  23228. break;
  23229. }
  23230. }
  23231. }
  23232. }
  23233. }
  23234. }
  23235. void MidiMessageSequence::addTimeToMessages (const double delta)
  23236. {
  23237. for (int i = list.size(); --i >= 0;)
  23238. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  23239. + delta);
  23240. }
  23241. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  23242. MidiMessageSequence& destSequence,
  23243. const bool alsoIncludeMetaEvents) const
  23244. {
  23245. for (int i = 0; i < list.size(); ++i)
  23246. {
  23247. const MidiMessage& mm = list.getUnchecked(i)->message;
  23248. if (mm.isForChannel (channelNumberToExtract)
  23249. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  23250. {
  23251. destSequence.addEvent (mm);
  23252. }
  23253. }
  23254. }
  23255. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  23256. {
  23257. for (int i = 0; i < list.size(); ++i)
  23258. {
  23259. const MidiMessage& mm = list.getUnchecked(i)->message;
  23260. if (mm.isSysEx())
  23261. destSequence.addEvent (mm);
  23262. }
  23263. }
  23264. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  23265. {
  23266. for (int i = list.size(); --i >= 0;)
  23267. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  23268. list.remove(i);
  23269. }
  23270. void MidiMessageSequence::deleteSysExMessages()
  23271. {
  23272. for (int i = list.size(); --i >= 0;)
  23273. if (list.getUnchecked(i)->message.isSysEx())
  23274. list.remove(i);
  23275. }
  23276. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  23277. const double time,
  23278. OwnedArray<MidiMessage>& dest)
  23279. {
  23280. bool doneProg = false;
  23281. bool donePitchWheel = false;
  23282. Array <int> doneControllers;
  23283. doneControllers.ensureStorageAllocated (32);
  23284. for (int i = list.size(); --i >= 0;)
  23285. {
  23286. const MidiMessage& mm = list.getUnchecked(i)->message;
  23287. if (mm.isForChannel (channelNumber)
  23288. && mm.getTimeStamp() <= time)
  23289. {
  23290. if (mm.isProgramChange())
  23291. {
  23292. if (! doneProg)
  23293. {
  23294. dest.add (new MidiMessage (mm, 0.0));
  23295. doneProg = true;
  23296. }
  23297. }
  23298. else if (mm.isController())
  23299. {
  23300. if (! doneControllers.contains (mm.getControllerNumber()))
  23301. {
  23302. dest.add (new MidiMessage (mm, 0.0));
  23303. doneControllers.add (mm.getControllerNumber());
  23304. }
  23305. }
  23306. else if (mm.isPitchWheel())
  23307. {
  23308. if (! donePitchWheel)
  23309. {
  23310. dest.add (new MidiMessage (mm, 0.0));
  23311. donePitchWheel = true;
  23312. }
  23313. }
  23314. }
  23315. }
  23316. }
  23317. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  23318. : message (message_),
  23319. noteOffObject (0)
  23320. {
  23321. }
  23322. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  23323. {
  23324. }
  23325. END_JUCE_NAMESPACE
  23326. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  23327. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  23328. BEGIN_JUCE_NAMESPACE
  23329. AudioPluginFormat::AudioPluginFormat() throw()
  23330. {
  23331. }
  23332. AudioPluginFormat::~AudioPluginFormat()
  23333. {
  23334. }
  23335. END_JUCE_NAMESPACE
  23336. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  23337. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23338. BEGIN_JUCE_NAMESPACE
  23339. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  23340. {
  23341. }
  23342. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  23343. {
  23344. clearSingletonInstance();
  23345. }
  23346. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  23347. void AudioPluginFormatManager::addDefaultFormats()
  23348. {
  23349. #if JUCE_DEBUG
  23350. // you should only call this method once!
  23351. for (int i = formats.size(); --i >= 0;)
  23352. {
  23353. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23354. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  23355. #endif
  23356. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23357. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  23358. #endif
  23359. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  23360. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  23361. #endif
  23362. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23363. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  23364. #endif
  23365. }
  23366. #endif
  23367. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23368. formats.add (new AudioUnitPluginFormat());
  23369. #endif
  23370. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23371. formats.add (new VSTPluginFormat());
  23372. #endif
  23373. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  23374. formats.add (new DirectXPluginFormat());
  23375. #endif
  23376. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23377. formats.add (new LADSPAPluginFormat());
  23378. #endif
  23379. }
  23380. int AudioPluginFormatManager::getNumFormats() throw()
  23381. {
  23382. return formats.size();
  23383. }
  23384. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  23385. {
  23386. return formats [index];
  23387. }
  23388. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  23389. {
  23390. formats.add (format);
  23391. }
  23392. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  23393. String& errorMessage) const
  23394. {
  23395. AudioPluginInstance* result = 0;
  23396. for (int i = 0; i < formats.size(); ++i)
  23397. {
  23398. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  23399. if (result != 0)
  23400. break;
  23401. }
  23402. if (result == 0)
  23403. {
  23404. if (! doesPluginStillExist (description))
  23405. errorMessage = TRANS ("This plug-in file no longer exists");
  23406. else
  23407. errorMessage = TRANS ("This plug-in failed to load correctly");
  23408. }
  23409. return result;
  23410. }
  23411. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  23412. {
  23413. for (int i = 0; i < formats.size(); ++i)
  23414. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  23415. return formats.getUnchecked(i)->doesPluginStillExist (description);
  23416. return false;
  23417. }
  23418. END_JUCE_NAMESPACE
  23419. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23420. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  23421. #define JUCE_PLUGIN_HOST 1
  23422. BEGIN_JUCE_NAMESPACE
  23423. AudioPluginInstance::AudioPluginInstance()
  23424. {
  23425. }
  23426. AudioPluginInstance::~AudioPluginInstance()
  23427. {
  23428. }
  23429. END_JUCE_NAMESPACE
  23430. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  23431. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  23432. BEGIN_JUCE_NAMESPACE
  23433. KnownPluginList::KnownPluginList()
  23434. {
  23435. }
  23436. KnownPluginList::~KnownPluginList()
  23437. {
  23438. }
  23439. void KnownPluginList::clear()
  23440. {
  23441. if (types.size() > 0)
  23442. {
  23443. types.clear();
  23444. sendChangeMessage (this);
  23445. }
  23446. }
  23447. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const throw()
  23448. {
  23449. for (int i = 0; i < types.size(); ++i)
  23450. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  23451. return types.getUnchecked(i);
  23452. return 0;
  23453. }
  23454. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  23455. {
  23456. for (int i = 0; i < types.size(); ++i)
  23457. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  23458. return types.getUnchecked(i);
  23459. return 0;
  23460. }
  23461. bool KnownPluginList::addType (const PluginDescription& type)
  23462. {
  23463. for (int i = types.size(); --i >= 0;)
  23464. {
  23465. if (types.getUnchecked(i)->isDuplicateOf (type))
  23466. {
  23467. // strange - found a duplicate plugin with different info..
  23468. jassert (types.getUnchecked(i)->name == type.name);
  23469. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  23470. *types.getUnchecked(i) = type;
  23471. return false;
  23472. }
  23473. }
  23474. types.add (new PluginDescription (type));
  23475. sendChangeMessage (this);
  23476. return true;
  23477. }
  23478. void KnownPluginList::removeType (const int index) throw()
  23479. {
  23480. types.remove (index);
  23481. sendChangeMessage (this);
  23482. }
  23483. static Time getFileModTime (const String& fileOrIdentifier) throw()
  23484. {
  23485. if (fileOrIdentifier.startsWithChar ('/')
  23486. || fileOrIdentifier[1] == ':')
  23487. {
  23488. return File (fileOrIdentifier).getLastModificationTime();
  23489. }
  23490. return Time (0);
  23491. }
  23492. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  23493. {
  23494. return t1 != t2 || t1 == Time (0);
  23495. }
  23496. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const throw()
  23497. {
  23498. if (getTypeForFile (fileOrIdentifier) == 0)
  23499. return false;
  23500. for (int i = types.size(); --i >= 0;)
  23501. {
  23502. const PluginDescription* const d = types.getUnchecked(i);
  23503. if (d->fileOrIdentifier == fileOrIdentifier
  23504. && timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23505. {
  23506. return false;
  23507. }
  23508. }
  23509. return true;
  23510. }
  23511. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  23512. const bool dontRescanIfAlreadyInList,
  23513. OwnedArray <PluginDescription>& typesFound,
  23514. AudioPluginFormat& format)
  23515. {
  23516. bool addedOne = false;
  23517. if (dontRescanIfAlreadyInList
  23518. && getTypeForFile (fileOrIdentifier) != 0)
  23519. {
  23520. bool needsRescanning = false;
  23521. for (int i = types.size(); --i >= 0;)
  23522. {
  23523. const PluginDescription* const d = types.getUnchecked(i);
  23524. if (d->fileOrIdentifier == fileOrIdentifier)
  23525. {
  23526. if (timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23527. needsRescanning = true;
  23528. else
  23529. typesFound.add (new PluginDescription (*d));
  23530. }
  23531. }
  23532. if (! needsRescanning)
  23533. return false;
  23534. }
  23535. OwnedArray <PluginDescription> found;
  23536. format.findAllTypesForFile (found, fileOrIdentifier);
  23537. for (int i = 0; i < found.size(); ++i)
  23538. {
  23539. PluginDescription* const desc = found.getUnchecked(i);
  23540. jassert (desc != 0);
  23541. if (addType (*desc))
  23542. addedOne = true;
  23543. typesFound.add (new PluginDescription (*desc));
  23544. }
  23545. return addedOne;
  23546. }
  23547. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  23548. OwnedArray <PluginDescription>& typesFound)
  23549. {
  23550. for (int i = 0; i < files.size(); ++i)
  23551. {
  23552. bool loaded = false;
  23553. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  23554. {
  23555. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  23556. if (scanAndAddFile (files[i], true, typesFound, *format))
  23557. loaded = true;
  23558. }
  23559. if (! loaded)
  23560. {
  23561. const File f (files[i]);
  23562. if (f.isDirectory())
  23563. {
  23564. StringArray s;
  23565. {
  23566. Array<File> subFiles;
  23567. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  23568. for (int j = 0; j < subFiles.size(); ++j)
  23569. s.add (subFiles.getReference(j).getFullPathName());
  23570. }
  23571. scanAndAddDragAndDroppedFiles (s, typesFound);
  23572. }
  23573. }
  23574. }
  23575. }
  23576. class PluginSorter
  23577. {
  23578. public:
  23579. KnownPluginList::SortMethod method;
  23580. PluginSorter() throw() {}
  23581. int compareElements (const PluginDescription* const first,
  23582. const PluginDescription* const second) const throw()
  23583. {
  23584. int diff = 0;
  23585. if (method == KnownPluginList::sortByCategory)
  23586. diff = first->category.compareLexicographically (second->category);
  23587. else if (method == KnownPluginList::sortByManufacturer)
  23588. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  23589. else if (method == KnownPluginList::sortByFileSystemLocation)
  23590. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  23591. .upToLastOccurrenceOf ("/", false, false)
  23592. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  23593. .upToLastOccurrenceOf ("/", false, false));
  23594. if (diff == 0)
  23595. diff = first->name.compareLexicographically (second->name);
  23596. return diff;
  23597. }
  23598. };
  23599. void KnownPluginList::sort (const SortMethod method)
  23600. {
  23601. if (method != defaultOrder)
  23602. {
  23603. PluginSorter sorter;
  23604. sorter.method = method;
  23605. types.sort (sorter, true);
  23606. sendChangeMessage (this);
  23607. }
  23608. }
  23609. XmlElement* KnownPluginList::createXml() const
  23610. {
  23611. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  23612. for (int i = 0; i < types.size(); ++i)
  23613. e->addChildElement (types.getUnchecked(i)->createXml());
  23614. return e;
  23615. }
  23616. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  23617. {
  23618. clear();
  23619. if (xml.hasTagName ("KNOWNPLUGINS"))
  23620. {
  23621. forEachXmlChildElement (xml, e)
  23622. {
  23623. PluginDescription info;
  23624. if (info.loadFromXml (*e))
  23625. addType (info);
  23626. }
  23627. }
  23628. }
  23629. const int menuIdBase = 0x324503f4;
  23630. // This is used to turn a bunch of paths into a nested menu structure.
  23631. struct PluginFilesystemTree
  23632. {
  23633. private:
  23634. String folder;
  23635. OwnedArray <PluginFilesystemTree> subFolders;
  23636. Array <PluginDescription*> plugins;
  23637. void addPlugin (PluginDescription* const pd, const String& path)
  23638. {
  23639. if (path.isEmpty())
  23640. {
  23641. plugins.add (pd);
  23642. }
  23643. else
  23644. {
  23645. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  23646. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  23647. for (int i = subFolders.size(); --i >= 0;)
  23648. {
  23649. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  23650. {
  23651. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  23652. return;
  23653. }
  23654. }
  23655. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  23656. newFolder->folder = firstSubFolder;
  23657. subFolders.add (newFolder);
  23658. newFolder->addPlugin (pd, remainingPath);
  23659. }
  23660. }
  23661. // removes any deeply nested folders that don't contain any actual plugins
  23662. void optimise()
  23663. {
  23664. for (int i = subFolders.size(); --i >= 0;)
  23665. {
  23666. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23667. sub->optimise();
  23668. if (sub->plugins.size() == 0)
  23669. {
  23670. for (int j = 0; j < sub->subFolders.size(); ++j)
  23671. subFolders.add (sub->subFolders.getUnchecked(j));
  23672. sub->subFolders.clear (false);
  23673. subFolders.remove (i);
  23674. }
  23675. }
  23676. }
  23677. public:
  23678. void buildTree (const Array <PluginDescription*>& allPlugins)
  23679. {
  23680. for (int i = 0; i < allPlugins.size(); ++i)
  23681. {
  23682. String path (allPlugins.getUnchecked(i)
  23683. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  23684. .upToLastOccurrenceOf ("/", false, false));
  23685. if (path.substring (1, 2) == ":")
  23686. path = path.substring (2);
  23687. addPlugin (allPlugins.getUnchecked(i), path);
  23688. }
  23689. optimise();
  23690. }
  23691. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  23692. {
  23693. int i;
  23694. for (i = 0; i < subFolders.size(); ++i)
  23695. {
  23696. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23697. PopupMenu subMenu;
  23698. sub->addToMenu (subMenu, allPlugins);
  23699. #if JUCE_MAC
  23700. // avoid the special AU formatting nonsense on Mac..
  23701. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  23702. #else
  23703. m.addSubMenu (sub->folder, subMenu);
  23704. #endif
  23705. }
  23706. for (i = 0; i < plugins.size(); ++i)
  23707. {
  23708. PluginDescription* const plugin = plugins.getUnchecked(i);
  23709. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  23710. plugin->name, true, false);
  23711. }
  23712. }
  23713. };
  23714. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  23715. {
  23716. Array <PluginDescription*> sorted;
  23717. {
  23718. PluginSorter sorter;
  23719. sorter.method = sortMethod;
  23720. for (int i = 0; i < types.size(); ++i)
  23721. sorted.addSorted (sorter, types.getUnchecked(i));
  23722. }
  23723. if (sortMethod == sortByCategory
  23724. || sortMethod == sortByManufacturer)
  23725. {
  23726. String lastSubMenuName;
  23727. PopupMenu sub;
  23728. for (int i = 0; i < sorted.size(); ++i)
  23729. {
  23730. const PluginDescription* const pd = sorted.getUnchecked(i);
  23731. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  23732. : pd->manufacturerName);
  23733. if (! thisSubMenuName.containsNonWhitespaceChars())
  23734. thisSubMenuName = "Other";
  23735. if (thisSubMenuName != lastSubMenuName)
  23736. {
  23737. if (sub.getNumItems() > 0)
  23738. {
  23739. menu.addSubMenu (lastSubMenuName, sub);
  23740. sub.clear();
  23741. }
  23742. lastSubMenuName = thisSubMenuName;
  23743. }
  23744. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23745. }
  23746. if (sub.getNumItems() > 0)
  23747. menu.addSubMenu (lastSubMenuName, sub);
  23748. }
  23749. else if (sortMethod == sortByFileSystemLocation)
  23750. {
  23751. PluginFilesystemTree root;
  23752. root.buildTree (sorted);
  23753. root.addToMenu (menu, types);
  23754. }
  23755. else
  23756. {
  23757. for (int i = 0; i < sorted.size(); ++i)
  23758. {
  23759. const PluginDescription* const pd = sorted.getUnchecked(i);
  23760. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23761. }
  23762. }
  23763. }
  23764. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  23765. {
  23766. const int i = menuResultCode - menuIdBase;
  23767. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  23768. }
  23769. END_JUCE_NAMESPACE
  23770. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  23771. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  23772. BEGIN_JUCE_NAMESPACE
  23773. PluginDescription::PluginDescription() throw()
  23774. : uid (0),
  23775. isInstrument (false),
  23776. numInputChannels (0),
  23777. numOutputChannels (0)
  23778. {
  23779. }
  23780. PluginDescription::~PluginDescription() throw()
  23781. {
  23782. }
  23783. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  23784. : name (other.name),
  23785. pluginFormatName (other.pluginFormatName),
  23786. category (other.category),
  23787. manufacturerName (other.manufacturerName),
  23788. version (other.version),
  23789. fileOrIdentifier (other.fileOrIdentifier),
  23790. lastFileModTime (other.lastFileModTime),
  23791. uid (other.uid),
  23792. isInstrument (other.isInstrument),
  23793. numInputChannels (other.numInputChannels),
  23794. numOutputChannels (other.numOutputChannels)
  23795. {
  23796. }
  23797. PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  23798. {
  23799. name = other.name;
  23800. pluginFormatName = other.pluginFormatName;
  23801. category = other.category;
  23802. manufacturerName = other.manufacturerName;
  23803. version = other.version;
  23804. fileOrIdentifier = other.fileOrIdentifier;
  23805. uid = other.uid;
  23806. isInstrument = other.isInstrument;
  23807. lastFileModTime = other.lastFileModTime;
  23808. numInputChannels = other.numInputChannels;
  23809. numOutputChannels = other.numOutputChannels;
  23810. return *this;
  23811. }
  23812. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  23813. {
  23814. return fileOrIdentifier == other.fileOrIdentifier
  23815. && uid == other.uid;
  23816. }
  23817. const String PluginDescription::createIdentifierString() const throw()
  23818. {
  23819. return pluginFormatName
  23820. + "-" + name
  23821. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  23822. + "-" + String::toHexString (uid);
  23823. }
  23824. XmlElement* PluginDescription::createXml() const
  23825. {
  23826. XmlElement* const e = new XmlElement ("PLUGIN");
  23827. e->setAttribute ("name", name);
  23828. e->setAttribute ("format", pluginFormatName);
  23829. e->setAttribute ("category", category);
  23830. e->setAttribute ("manufacturer", manufacturerName);
  23831. e->setAttribute ("version", version);
  23832. e->setAttribute ("file", fileOrIdentifier);
  23833. e->setAttribute ("uid", String::toHexString (uid));
  23834. e->setAttribute ("isInstrument", isInstrument);
  23835. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  23836. e->setAttribute ("numInputs", numInputChannels);
  23837. e->setAttribute ("numOutputs", numOutputChannels);
  23838. return e;
  23839. }
  23840. bool PluginDescription::loadFromXml (const XmlElement& xml)
  23841. {
  23842. if (xml.hasTagName ("PLUGIN"))
  23843. {
  23844. name = xml.getStringAttribute ("name");
  23845. pluginFormatName = xml.getStringAttribute ("format");
  23846. category = xml.getStringAttribute ("category");
  23847. manufacturerName = xml.getStringAttribute ("manufacturer");
  23848. version = xml.getStringAttribute ("version");
  23849. fileOrIdentifier = xml.getStringAttribute ("file");
  23850. uid = xml.getStringAttribute ("uid").getHexValue32();
  23851. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  23852. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  23853. numInputChannels = xml.getIntAttribute ("numInputs");
  23854. numOutputChannels = xml.getIntAttribute ("numOutputs");
  23855. return true;
  23856. }
  23857. return false;
  23858. }
  23859. END_JUCE_NAMESPACE
  23860. /*** End of inlined file: juce_PluginDescription.cpp ***/
  23861. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23862. BEGIN_JUCE_NAMESPACE
  23863. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  23864. AudioPluginFormat& formatToLookFor,
  23865. FileSearchPath directoriesToSearch,
  23866. const bool recursive,
  23867. const File& deadMansPedalFile_)
  23868. : list (listToAddTo),
  23869. format (formatToLookFor),
  23870. deadMansPedalFile (deadMansPedalFile_),
  23871. nextIndex (0),
  23872. progress (0)
  23873. {
  23874. directoriesToSearch.removeRedundantPaths();
  23875. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  23876. // If any plugins have crashed recently when being loaded, move them to the
  23877. // end of the list to give the others a chance to load correctly..
  23878. const StringArray crashedPlugins (getDeadMansPedalFile());
  23879. for (int i = 0; i < crashedPlugins.size(); ++i)
  23880. {
  23881. const String f = crashedPlugins[i];
  23882. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  23883. if (f == filesOrIdentifiersToScan[j])
  23884. filesOrIdentifiersToScan.move (j, -1);
  23885. }
  23886. }
  23887. PluginDirectoryScanner::~PluginDirectoryScanner()
  23888. {
  23889. }
  23890. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  23891. {
  23892. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  23893. }
  23894. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  23895. {
  23896. String file (filesOrIdentifiersToScan [nextIndex]);
  23897. if (file.isNotEmpty())
  23898. {
  23899. if (! list.isListingUpToDate (file))
  23900. {
  23901. OwnedArray <PluginDescription> typesFound;
  23902. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  23903. StringArray crashedPlugins (getDeadMansPedalFile());
  23904. crashedPlugins.removeString (file);
  23905. crashedPlugins.add (file);
  23906. setDeadMansPedalFile (crashedPlugins);
  23907. list.scanAndAddFile (file,
  23908. dontRescanIfAlreadyInList,
  23909. typesFound,
  23910. format);
  23911. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  23912. crashedPlugins.removeString (file);
  23913. setDeadMansPedalFile (crashedPlugins);
  23914. if (typesFound.size() == 0)
  23915. failedFiles.add (file);
  23916. }
  23917. ++nextIndex;
  23918. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  23919. }
  23920. return nextIndex < filesOrIdentifiersToScan.size();
  23921. }
  23922. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  23923. {
  23924. StringArray lines;
  23925. if (deadMansPedalFile != File::nonexistent)
  23926. {
  23927. lines.addLines (deadMansPedalFile.loadFileAsString());
  23928. lines.removeEmptyStrings();
  23929. }
  23930. return lines;
  23931. }
  23932. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  23933. {
  23934. if (deadMansPedalFile != File::nonexistent)
  23935. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  23936. }
  23937. END_JUCE_NAMESPACE
  23938. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23939. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  23940. BEGIN_JUCE_NAMESPACE
  23941. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  23942. const File& deadMansPedalFile_,
  23943. PropertiesFile* const propertiesToUse_)
  23944. : list (listToEdit),
  23945. deadMansPedalFile (deadMansPedalFile_),
  23946. propertiesToUse (propertiesToUse_)
  23947. {
  23948. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  23949. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  23950. optionsButton->addButtonListener (this);
  23951. optionsButton->setTriggeredOnMouseDown (true);
  23952. setSize (400, 600);
  23953. list.addChangeListener (this);
  23954. changeListenerCallback (0);
  23955. }
  23956. PluginListComponent::~PluginListComponent()
  23957. {
  23958. list.removeChangeListener (this);
  23959. deleteAllChildren();
  23960. }
  23961. void PluginListComponent::resized()
  23962. {
  23963. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  23964. optionsButton->changeWidthToFitText (24);
  23965. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  23966. }
  23967. void PluginListComponent::changeListenerCallback (void*)
  23968. {
  23969. listBox->updateContent();
  23970. listBox->repaint();
  23971. }
  23972. int PluginListComponent::getNumRows()
  23973. {
  23974. return list.getNumTypes();
  23975. }
  23976. void PluginListComponent::paintListBoxItem (int row,
  23977. Graphics& g,
  23978. int width, int height,
  23979. bool rowIsSelected)
  23980. {
  23981. if (rowIsSelected)
  23982. g.fillAll (findColour (TextEditor::highlightColourId));
  23983. const PluginDescription* const pd = list.getType (row);
  23984. if (pd != 0)
  23985. {
  23986. GlyphArrangement ga;
  23987. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  23988. g.setColour (Colours::black);
  23989. ga.draw (g);
  23990. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  23991. String desc;
  23992. desc << pd->pluginFormatName
  23993. << (pd->isInstrument ? " instrument" : " effect")
  23994. << " - "
  23995. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  23996. << " / "
  23997. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  23998. if (pd->manufacturerName.isNotEmpty())
  23999. desc << " - " << pd->manufacturerName;
  24000. if (pd->version.isNotEmpty())
  24001. desc << " - " << pd->version;
  24002. if (pd->category.isNotEmpty())
  24003. desc << " - category: '" << pd->category << '\'';
  24004. g.setColour (Colours::grey);
  24005. ga.clear();
  24006. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24007. ga.draw (g);
  24008. }
  24009. }
  24010. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24011. {
  24012. list.removeType (lastRowSelected);
  24013. }
  24014. void PluginListComponent::buttonClicked (Button* b)
  24015. {
  24016. if (optionsButton == b)
  24017. {
  24018. PopupMenu menu;
  24019. menu.addItem (1, TRANS("Clear list"));
  24020. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  24021. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  24022. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24023. menu.addSeparator();
  24024. menu.addItem (2, TRANS("Sort alphabetically"));
  24025. menu.addItem (3, TRANS("Sort by category"));
  24026. menu.addItem (4, TRANS("Sort by manufacturer"));
  24027. menu.addSeparator();
  24028. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24029. {
  24030. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24031. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24032. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24033. }
  24034. const int r = menu.showAt (optionsButton);
  24035. if (r == 1)
  24036. {
  24037. list.clear();
  24038. }
  24039. else if (r == 2)
  24040. {
  24041. list.sort (KnownPluginList::sortAlphabetically);
  24042. }
  24043. else if (r == 3)
  24044. {
  24045. list.sort (KnownPluginList::sortByCategory);
  24046. }
  24047. else if (r == 4)
  24048. {
  24049. list.sort (KnownPluginList::sortByManufacturer);
  24050. }
  24051. else if (r == 5)
  24052. {
  24053. const SparseSet <int> selected (listBox->getSelectedRows());
  24054. for (int i = list.getNumTypes(); --i >= 0;)
  24055. if (selected.contains (i))
  24056. list.removeType (i);
  24057. }
  24058. else if (r == 6)
  24059. {
  24060. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  24061. if (desc != 0)
  24062. {
  24063. if (File (desc->fileOrIdentifier).existsAsFile())
  24064. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24065. }
  24066. }
  24067. else if (r == 7)
  24068. {
  24069. for (int i = list.getNumTypes(); --i >= 0;)
  24070. {
  24071. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24072. {
  24073. list.removeType (i);
  24074. }
  24075. }
  24076. }
  24077. else if (r != 0)
  24078. {
  24079. typeToScan = r - 10;
  24080. startTimer (1);
  24081. }
  24082. }
  24083. }
  24084. void PluginListComponent::timerCallback()
  24085. {
  24086. stopTimer();
  24087. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24088. }
  24089. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24090. {
  24091. return true;
  24092. }
  24093. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24094. {
  24095. OwnedArray <PluginDescription> typesFound;
  24096. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24097. }
  24098. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24099. {
  24100. if (format == 0)
  24101. return;
  24102. FileSearchPath path (format->getDefaultLocationsToSearch());
  24103. if (propertiesToUse != 0)
  24104. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24105. {
  24106. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24107. FileSearchPathListComponent pathList;
  24108. pathList.setSize (500, 300);
  24109. pathList.setPath (path);
  24110. aw.addCustomComponent (&pathList);
  24111. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24112. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24113. if (aw.runModalLoop() == 0)
  24114. return;
  24115. path = pathList.getPath();
  24116. }
  24117. if (propertiesToUse != 0)
  24118. {
  24119. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24120. propertiesToUse->saveIfNeeded();
  24121. }
  24122. double progress = 0.0;
  24123. AlertWindow aw (TRANS("Scanning for plugins..."),
  24124. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24125. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24126. aw.addProgressBarComponent (progress);
  24127. aw.enterModalState();
  24128. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24129. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24130. for (;;)
  24131. {
  24132. aw.setMessage (TRANS("Testing:\n\n")
  24133. + scanner.getNextPluginFileThatWillBeScanned());
  24134. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24135. if (! scanner.scanNextFile (true))
  24136. break;
  24137. if (! aw.isCurrentlyModal())
  24138. break;
  24139. progress = scanner.getProgress();
  24140. }
  24141. if (scanner.getFailedFiles().size() > 0)
  24142. {
  24143. StringArray shortNames;
  24144. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  24145. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  24146. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  24147. TRANS("Scan complete"),
  24148. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  24149. + shortNames.joinIntoString (", "));
  24150. }
  24151. }
  24152. END_JUCE_NAMESPACE
  24153. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  24154. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  24155. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  24156. #include <AudioUnit/AudioUnit.h>
  24157. #include <AudioUnit/AUCocoaUIView.h>
  24158. #include <CoreAudioKit/AUGenericView.h>
  24159. #if JUCE_SUPPORT_CARBON
  24160. #include <AudioToolbox/AudioUnitUtilities.h>
  24161. #include <AudioUnit/AudioUnitCarbonView.h>
  24162. #endif
  24163. BEGIN_JUCE_NAMESPACE
  24164. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24165. #endif
  24166. #if JUCE_MAC
  24167. // Change this to disable logging of various activities
  24168. #ifndef AU_LOGGING
  24169. #define AU_LOGGING 1
  24170. #endif
  24171. #if AU_LOGGING
  24172. #define log(a) Logger::writeToLog(a);
  24173. #else
  24174. #define log(a)
  24175. #endif
  24176. namespace AudioUnitFormatHelpers
  24177. {
  24178. static int insideCallback = 0;
  24179. static const String osTypeToString (OSType type)
  24180. {
  24181. char s[4];
  24182. s[0] = (char) (((uint32) type) >> 24);
  24183. s[1] = (char) (((uint32) type) >> 16);
  24184. s[2] = (char) (((uint32) type) >> 8);
  24185. s[3] = (char) ((uint32) type);
  24186. return String (s, 4);
  24187. }
  24188. static OSType stringToOSType (const String& s1)
  24189. {
  24190. const String s (s1 + " ");
  24191. return (((OSType) (unsigned char) s[0]) << 24)
  24192. | (((OSType) (unsigned char) s[1]) << 16)
  24193. | (((OSType) (unsigned char) s[2]) << 8)
  24194. | ((OSType) (unsigned char) s[3]);
  24195. }
  24196. static const char* auIdentifierPrefix = "AudioUnit:";
  24197. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  24198. {
  24199. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  24200. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  24201. String s (auIdentifierPrefix);
  24202. if (desc.componentType == kAudioUnitType_MusicDevice)
  24203. s << "Synths/";
  24204. else if (desc.componentType == kAudioUnitType_MusicEffect
  24205. || desc.componentType == kAudioUnitType_Effect)
  24206. s << "Effects/";
  24207. else if (desc.componentType == kAudioUnitType_Generator)
  24208. s << "Generators/";
  24209. else if (desc.componentType == kAudioUnitType_Panner)
  24210. s << "Panners/";
  24211. s << osTypeToString (desc.componentType) << ","
  24212. << osTypeToString (desc.componentSubType) << ","
  24213. << osTypeToString (desc.componentManufacturer);
  24214. return s;
  24215. }
  24216. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  24217. {
  24218. Handle componentNameHandle = NewHandle (sizeof (void*));
  24219. Handle componentInfoHandle = NewHandle (sizeof (void*));
  24220. if (componentNameHandle != 0 && componentInfoHandle != 0)
  24221. {
  24222. ComponentDescription desc;
  24223. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  24224. {
  24225. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  24226. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  24227. if (nameString != 0 && nameString[0] != 0)
  24228. {
  24229. const String all ((const char*) nameString + 1, nameString[0]);
  24230. DBG ("name: "+ all);
  24231. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  24232. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  24233. }
  24234. if (infoString != 0 && infoString[0] != 0)
  24235. {
  24236. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  24237. }
  24238. if (name.isEmpty())
  24239. name = "<Unknown>";
  24240. }
  24241. DisposeHandle (componentNameHandle);
  24242. DisposeHandle (componentInfoHandle);
  24243. }
  24244. }
  24245. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  24246. String& name, String& version, String& manufacturer)
  24247. {
  24248. zerostruct (desc);
  24249. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  24250. {
  24251. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  24252. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  24253. StringArray tokens;
  24254. tokens.addTokens (s, ",", String::empty);
  24255. tokens.trim();
  24256. tokens.removeEmptyStrings();
  24257. if (tokens.size() == 3)
  24258. {
  24259. desc.componentType = stringToOSType (tokens[0]);
  24260. desc.componentSubType = stringToOSType (tokens[1]);
  24261. desc.componentManufacturer = stringToOSType (tokens[2]);
  24262. ComponentRecord* comp = FindNextComponent (0, &desc);
  24263. if (comp != 0)
  24264. {
  24265. getAUDetails (comp, name, manufacturer);
  24266. return true;
  24267. }
  24268. }
  24269. }
  24270. return false;
  24271. }
  24272. }
  24273. class AudioUnitPluginWindowCarbon;
  24274. class AudioUnitPluginWindowCocoa;
  24275. class AudioUnitPluginInstance : public AudioPluginInstance
  24276. {
  24277. public:
  24278. ~AudioUnitPluginInstance();
  24279. // AudioPluginInstance methods:
  24280. void fillInPluginDescription (PluginDescription& desc) const
  24281. {
  24282. desc.name = pluginName;
  24283. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  24284. desc.uid = ((int) componentDesc.componentType)
  24285. ^ ((int) componentDesc.componentSubType)
  24286. ^ ((int) componentDesc.componentManufacturer);
  24287. desc.lastFileModTime = 0;
  24288. desc.pluginFormatName = "AudioUnit";
  24289. desc.category = getCategory();
  24290. desc.manufacturerName = manufacturer;
  24291. desc.version = version;
  24292. desc.numInputChannels = getNumInputChannels();
  24293. desc.numOutputChannels = getNumOutputChannels();
  24294. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  24295. }
  24296. const String getName() const { return pluginName; }
  24297. bool acceptsMidi() const { return wantsMidiMessages; }
  24298. bool producesMidi() const { return false; }
  24299. // AudioProcessor methods:
  24300. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  24301. void releaseResources();
  24302. void processBlock (AudioSampleBuffer& buffer,
  24303. MidiBuffer& midiMessages);
  24304. AudioProcessorEditor* createEditor();
  24305. const String getInputChannelName (const int index) const;
  24306. bool isInputChannelStereoPair (int index) const;
  24307. const String getOutputChannelName (const int index) const;
  24308. bool isOutputChannelStereoPair (int index) const;
  24309. int getNumParameters();
  24310. float getParameter (int index);
  24311. void setParameter (int index, float newValue);
  24312. const String getParameterName (int index);
  24313. const String getParameterText (int index);
  24314. bool isParameterAutomatable (int index) const;
  24315. int getNumPrograms();
  24316. int getCurrentProgram();
  24317. void setCurrentProgram (int index);
  24318. const String getProgramName (int index);
  24319. void changeProgramName (int index, const String& newName);
  24320. void getStateInformation (MemoryBlock& destData);
  24321. void getCurrentProgramStateInformation (MemoryBlock& destData);
  24322. void setStateInformation (const void* data, int sizeInBytes);
  24323. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  24324. juce_UseDebuggingNewOperator
  24325. private:
  24326. friend class AudioUnitPluginWindowCarbon;
  24327. friend class AudioUnitPluginWindowCocoa;
  24328. friend class AudioUnitPluginFormat;
  24329. ComponentDescription componentDesc;
  24330. String pluginName, manufacturer, version;
  24331. String fileOrIdentifier;
  24332. CriticalSection lock;
  24333. bool initialised, wantsMidiMessages, wasPlaying;
  24334. HeapBlock <AudioBufferList> outputBufferList;
  24335. AudioTimeStamp timeStamp;
  24336. AudioSampleBuffer* currentBuffer;
  24337. AudioUnit audioUnit;
  24338. Array <int> parameterIds;
  24339. bool getComponentDescFromFile (const String& fileOrIdentifier);
  24340. void initialise();
  24341. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24342. const AudioTimeStamp* inTimeStamp,
  24343. UInt32 inBusNumber,
  24344. UInt32 inNumberFrames,
  24345. AudioBufferList* ioData) const;
  24346. static OSStatus renderGetInputCallback (void* inRefCon,
  24347. AudioUnitRenderActionFlags* ioActionFlags,
  24348. const AudioTimeStamp* inTimeStamp,
  24349. UInt32 inBusNumber,
  24350. UInt32 inNumberFrames,
  24351. AudioBufferList* ioData)
  24352. {
  24353. return ((AudioUnitPluginInstance*) inRefCon)
  24354. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  24355. }
  24356. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  24357. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  24358. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  24359. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24360. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24361. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  24362. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  24363. {
  24364. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  24365. }
  24366. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  24367. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  24368. Float64* outCurrentMeasureDownBeat)
  24369. {
  24370. return ((AudioUnitPluginInstance*) inHostUserData)
  24371. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  24372. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  24373. }
  24374. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24375. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24376. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  24377. {
  24378. return ((AudioUnitPluginInstance*) inHostUserData)
  24379. ->getTransportState (outIsPlaying, outTransportStateChanged,
  24380. outCurrentSampleInTimeLine, outIsCycling,
  24381. outCycleStartBeat, outCycleEndBeat);
  24382. }
  24383. void getNumChannels (int& numIns, int& numOuts)
  24384. {
  24385. numIns = 0;
  24386. numOuts = 0;
  24387. AUChannelInfo supportedChannels [128];
  24388. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  24389. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  24390. 0, supportedChannels, &supportedChannelsSize) == noErr
  24391. && supportedChannelsSize > 0)
  24392. {
  24393. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  24394. {
  24395. numIns = jmax (numIns, (int) supportedChannels[i].inChannels);
  24396. numOuts = jmax (numOuts, (int) supportedChannels[i].outChannels);
  24397. }
  24398. }
  24399. else
  24400. {
  24401. // (this really means the plugin will take any number of ins/outs as long
  24402. // as they are the same)
  24403. numIns = numOuts = 2;
  24404. }
  24405. }
  24406. const String getCategory() const;
  24407. AudioUnitPluginInstance (const String& fileOrIdentifier);
  24408. };
  24409. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  24410. : fileOrIdentifier (fileOrIdentifier),
  24411. initialised (false),
  24412. wantsMidiMessages (false),
  24413. audioUnit (0),
  24414. currentBuffer (0)
  24415. {
  24416. using namespace AudioUnitFormatHelpers;
  24417. try
  24418. {
  24419. ++insideCallback;
  24420. log ("Opening AU: " + fileOrIdentifier);
  24421. if (getComponentDescFromFile (fileOrIdentifier))
  24422. {
  24423. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  24424. if (comp != 0)
  24425. {
  24426. audioUnit = (AudioUnit) OpenComponent (comp);
  24427. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  24428. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  24429. }
  24430. }
  24431. --insideCallback;
  24432. }
  24433. catch (...)
  24434. {
  24435. --insideCallback;
  24436. }
  24437. }
  24438. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  24439. {
  24440. const ScopedLock sl (lock);
  24441. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  24442. if (audioUnit != 0)
  24443. {
  24444. AudioUnitUninitialize (audioUnit);
  24445. CloseComponent (audioUnit);
  24446. audioUnit = 0;
  24447. }
  24448. }
  24449. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  24450. {
  24451. zerostruct (componentDesc);
  24452. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  24453. return true;
  24454. const File file (fileOrIdentifier);
  24455. if (! file.hasFileExtension (".component"))
  24456. return false;
  24457. const char* const utf8 = fileOrIdentifier.toUTF8();
  24458. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  24459. strlen (utf8), file.isDirectory());
  24460. if (url != 0)
  24461. {
  24462. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  24463. CFRelease (url);
  24464. if (bundleRef != 0)
  24465. {
  24466. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  24467. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  24468. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  24469. if (pluginName.isEmpty())
  24470. pluginName = file.getFileNameWithoutExtension();
  24471. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  24472. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  24473. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  24474. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  24475. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  24476. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  24477. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  24478. UseResFile (resFileId);
  24479. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  24480. {
  24481. Handle h = Get1IndResource ('thng', i);
  24482. if (h != 0)
  24483. {
  24484. HLock (h);
  24485. const uint32* const types = (const uint32*) *h;
  24486. if (types[0] == kAudioUnitType_MusicDevice
  24487. || types[0] == kAudioUnitType_MusicEffect
  24488. || types[0] == kAudioUnitType_Effect
  24489. || types[0] == kAudioUnitType_Generator
  24490. || types[0] == kAudioUnitType_Panner)
  24491. {
  24492. componentDesc.componentType = types[0];
  24493. componentDesc.componentSubType = types[1];
  24494. componentDesc.componentManufacturer = types[2];
  24495. break;
  24496. }
  24497. HUnlock (h);
  24498. ReleaseResource (h);
  24499. }
  24500. }
  24501. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  24502. CFRelease (bundleRef);
  24503. }
  24504. }
  24505. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  24506. }
  24507. void AudioUnitPluginInstance::initialise()
  24508. {
  24509. if (initialised || audioUnit == 0)
  24510. return;
  24511. log ("Initialising AU: " + pluginName);
  24512. parameterIds.clear();
  24513. {
  24514. UInt32 paramListSize = 0;
  24515. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24516. 0, 0, &paramListSize);
  24517. if (paramListSize > 0)
  24518. {
  24519. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  24520. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24521. 0, &parameterIds.getReference(0), &paramListSize);
  24522. }
  24523. }
  24524. {
  24525. AURenderCallbackStruct info;
  24526. zerostruct (info);
  24527. info.inputProcRefCon = this;
  24528. info.inputProc = renderGetInputCallback;
  24529. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  24530. 0, &info, sizeof (info));
  24531. }
  24532. {
  24533. HostCallbackInfo info;
  24534. zerostruct (info);
  24535. info.hostUserData = this;
  24536. info.beatAndTempoProc = getBeatAndTempoCallback;
  24537. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  24538. info.transportStateProc = getTransportStateCallback;
  24539. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  24540. 0, &info, sizeof (info));
  24541. }
  24542. int numIns, numOuts;
  24543. getNumChannels (numIns, numOuts);
  24544. setPlayConfigDetails (numIns, numOuts, 0, 0);
  24545. initialised = AudioUnitInitialize (audioUnit) == noErr;
  24546. setLatencySamples (0);
  24547. }
  24548. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  24549. int samplesPerBlockExpected)
  24550. {
  24551. if (audioUnit != 0)
  24552. {
  24553. Float64 sampleRateIn = 0, sampleRateOut = 0;
  24554. UInt32 sampleRateSize = sizeof (sampleRateIn);
  24555. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  24556. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  24557. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  24558. {
  24559. if (initialised)
  24560. {
  24561. AudioUnitUninitialize (audioUnit);
  24562. initialised = false;
  24563. }
  24564. Float64 sr = sampleRate_;
  24565. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  24566. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  24567. }
  24568. }
  24569. initialise();
  24570. if (initialised)
  24571. {
  24572. int numIns, numOuts;
  24573. getNumChannels (numIns, numOuts);
  24574. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  24575. Float64 latencySecs = 0.0;
  24576. UInt32 latencySize = sizeof (latencySecs);
  24577. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  24578. 0, &latencySecs, &latencySize);
  24579. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  24580. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24581. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24582. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24583. AudioStreamBasicDescription stream;
  24584. zerostruct (stream);
  24585. stream.mSampleRate = sampleRate_;
  24586. stream.mFormatID = kAudioFormatLinearPCM;
  24587. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  24588. stream.mFramesPerPacket = 1;
  24589. stream.mBytesPerPacket = 4;
  24590. stream.mBytesPerFrame = 4;
  24591. stream.mBitsPerChannel = 32;
  24592. stream.mChannelsPerFrame = numIns;
  24593. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  24594. 0, &stream, sizeof (stream));
  24595. stream.mChannelsPerFrame = numOuts;
  24596. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  24597. 0, &stream, sizeof (stream));
  24598. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  24599. outputBufferList->mNumberBuffers = numOuts;
  24600. for (int i = numOuts; --i >= 0;)
  24601. outputBufferList->mBuffers[i].mNumberChannels = 1;
  24602. zerostruct (timeStamp);
  24603. timeStamp.mSampleTime = 0;
  24604. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24605. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  24606. currentBuffer = 0;
  24607. wasPlaying = false;
  24608. }
  24609. }
  24610. void AudioUnitPluginInstance::releaseResources()
  24611. {
  24612. if (initialised)
  24613. {
  24614. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24615. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24616. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24617. outputBufferList.free();
  24618. currentBuffer = 0;
  24619. }
  24620. }
  24621. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24622. const AudioTimeStamp* inTimeStamp,
  24623. UInt32 inBusNumber,
  24624. UInt32 inNumberFrames,
  24625. AudioBufferList* ioData) const
  24626. {
  24627. if (inBusNumber == 0
  24628. && currentBuffer != 0)
  24629. {
  24630. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  24631. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  24632. {
  24633. if (i < currentBuffer->getNumChannels())
  24634. {
  24635. memcpy (ioData->mBuffers[i].mData,
  24636. currentBuffer->getSampleData (i, 0),
  24637. sizeof (float) * inNumberFrames);
  24638. }
  24639. else
  24640. {
  24641. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  24642. }
  24643. }
  24644. }
  24645. return noErr;
  24646. }
  24647. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  24648. MidiBuffer& midiMessages)
  24649. {
  24650. const int numSamples = buffer.getNumSamples();
  24651. if (initialised)
  24652. {
  24653. AudioUnitRenderActionFlags flags = 0;
  24654. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24655. for (int i = getNumOutputChannels(); --i >= 0;)
  24656. {
  24657. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  24658. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  24659. }
  24660. currentBuffer = &buffer;
  24661. if (wantsMidiMessages)
  24662. {
  24663. const uint8* midiEventData;
  24664. int midiEventSize, midiEventPosition;
  24665. MidiBuffer::Iterator i (midiMessages);
  24666. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  24667. {
  24668. if (midiEventSize <= 3)
  24669. MusicDeviceMIDIEvent (audioUnit,
  24670. midiEventData[0], midiEventData[1], midiEventData[2],
  24671. midiEventPosition);
  24672. else
  24673. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  24674. }
  24675. midiMessages.clear();
  24676. }
  24677. AudioUnitRender (audioUnit, &flags, &timeStamp,
  24678. 0, numSamples, outputBufferList);
  24679. timeStamp.mSampleTime += numSamples;
  24680. }
  24681. else
  24682. {
  24683. // Not initialised, so just bypass..
  24684. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  24685. buffer.clear (i, 0, buffer.getNumSamples());
  24686. }
  24687. }
  24688. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  24689. {
  24690. AudioPlayHead* const ph = getPlayHead();
  24691. AudioPlayHead::CurrentPositionInfo result;
  24692. if (ph != 0 && ph->getCurrentPosition (result))
  24693. {
  24694. if (outCurrentBeat != 0)
  24695. *outCurrentBeat = result.ppqPosition;
  24696. if (outCurrentTempo != 0)
  24697. *outCurrentTempo = result.bpm;
  24698. }
  24699. else
  24700. {
  24701. if (outCurrentBeat != 0)
  24702. *outCurrentBeat = 0;
  24703. if (outCurrentTempo != 0)
  24704. *outCurrentTempo = 120.0;
  24705. }
  24706. return noErr;
  24707. }
  24708. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  24709. Float32* outTimeSig_Numerator,
  24710. UInt32* outTimeSig_Denominator,
  24711. Float64* outCurrentMeasureDownBeat) const
  24712. {
  24713. AudioPlayHead* const ph = getPlayHead();
  24714. AudioPlayHead::CurrentPositionInfo result;
  24715. if (ph != 0 && ph->getCurrentPosition (result))
  24716. {
  24717. if (outTimeSig_Numerator != 0)
  24718. *outTimeSig_Numerator = result.timeSigNumerator;
  24719. if (outTimeSig_Denominator != 0)
  24720. *outTimeSig_Denominator = result.timeSigDenominator;
  24721. if (outDeltaSampleOffsetToNextBeat != 0)
  24722. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  24723. if (outCurrentMeasureDownBeat != 0)
  24724. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  24725. }
  24726. else
  24727. {
  24728. if (outDeltaSampleOffsetToNextBeat != 0)
  24729. *outDeltaSampleOffsetToNextBeat = 0;
  24730. if (outTimeSig_Numerator != 0)
  24731. *outTimeSig_Numerator = 4;
  24732. if (outTimeSig_Denominator != 0)
  24733. *outTimeSig_Denominator = 4;
  24734. if (outCurrentMeasureDownBeat != 0)
  24735. *outCurrentMeasureDownBeat = 0;
  24736. }
  24737. return noErr;
  24738. }
  24739. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  24740. Boolean* outTransportStateChanged,
  24741. Float64* outCurrentSampleInTimeLine,
  24742. Boolean* outIsCycling,
  24743. Float64* outCycleStartBeat,
  24744. Float64* outCycleEndBeat)
  24745. {
  24746. AudioPlayHead* const ph = getPlayHead();
  24747. AudioPlayHead::CurrentPositionInfo result;
  24748. if (ph != 0 && ph->getCurrentPosition (result))
  24749. {
  24750. if (outIsPlaying != 0)
  24751. *outIsPlaying = result.isPlaying;
  24752. if (outTransportStateChanged != 0)
  24753. {
  24754. *outTransportStateChanged = result.isPlaying != wasPlaying;
  24755. wasPlaying = result.isPlaying;
  24756. }
  24757. if (outCurrentSampleInTimeLine != 0)
  24758. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  24759. if (outIsCycling != 0)
  24760. *outIsCycling = false;
  24761. if (outCycleStartBeat != 0)
  24762. *outCycleStartBeat = 0;
  24763. if (outCycleEndBeat != 0)
  24764. *outCycleEndBeat = 0;
  24765. }
  24766. else
  24767. {
  24768. if (outIsPlaying != 0)
  24769. *outIsPlaying = false;
  24770. if (outTransportStateChanged != 0)
  24771. *outTransportStateChanged = false;
  24772. if (outCurrentSampleInTimeLine != 0)
  24773. *outCurrentSampleInTimeLine = 0;
  24774. if (outIsCycling != 0)
  24775. *outIsCycling = false;
  24776. if (outCycleStartBeat != 0)
  24777. *outCycleStartBeat = 0;
  24778. if (outCycleEndBeat != 0)
  24779. *outCycleEndBeat = 0;
  24780. }
  24781. return noErr;
  24782. }
  24783. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  24784. {
  24785. public:
  24786. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  24787. : AudioProcessorEditor (&plugin_),
  24788. plugin (plugin_),
  24789. wrapper (0)
  24790. {
  24791. addAndMakeVisible (wrapper = new NSViewComponent());
  24792. setOpaque (true);
  24793. setVisible (true);
  24794. setSize (100, 100);
  24795. createView (createGenericViewIfNeeded);
  24796. }
  24797. ~AudioUnitPluginWindowCocoa()
  24798. {
  24799. const bool wasValid = isValid();
  24800. wrapper->setView (0);
  24801. if (wasValid)
  24802. plugin.editorBeingDeleted (this);
  24803. delete wrapper;
  24804. }
  24805. bool isValid() const { return wrapper->getView() != 0; }
  24806. void paint (Graphics& g)
  24807. {
  24808. g.fillAll (Colours::white);
  24809. }
  24810. void resized()
  24811. {
  24812. wrapper->setSize (getWidth(), getHeight());
  24813. }
  24814. private:
  24815. AudioUnitPluginInstance& plugin;
  24816. NSViewComponent* wrapper;
  24817. bool createView (const bool createGenericViewIfNeeded)
  24818. {
  24819. NSView* pluginView = 0;
  24820. UInt32 dataSize = 0;
  24821. Boolean isWritable = false;
  24822. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24823. 0, &dataSize, &isWritable) == noErr
  24824. && dataSize != 0
  24825. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24826. 0, &dataSize, &isWritable) == noErr)
  24827. {
  24828. HeapBlock <AudioUnitCocoaViewInfo> info;
  24829. info.calloc (dataSize, 1);
  24830. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24831. 0, info, &dataSize) == noErr)
  24832. {
  24833. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  24834. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  24835. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  24836. Class viewClass = [viewBundle classNamed: viewClassName];
  24837. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  24838. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  24839. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  24840. {
  24841. id factory = [[[viewClass alloc] init] autorelease];
  24842. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  24843. withSize: NSMakeSize (getWidth(), getHeight())];
  24844. }
  24845. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  24846. {
  24847. CFRelease (info->mCocoaAUViewClass[i]);
  24848. CFRelease (info->mCocoaAUViewBundleLocation);
  24849. }
  24850. }
  24851. }
  24852. if (createGenericViewIfNeeded && (pluginView == 0))
  24853. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  24854. wrapper->setView (pluginView);
  24855. if (pluginView != 0)
  24856. setSize ([pluginView frame].size.width,
  24857. [pluginView frame].size.height);
  24858. return pluginView != 0;
  24859. }
  24860. };
  24861. #if JUCE_SUPPORT_CARBON
  24862. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  24863. {
  24864. public:
  24865. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  24866. : AudioProcessorEditor (&plugin_),
  24867. plugin (plugin_),
  24868. viewComponent (0)
  24869. {
  24870. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  24871. setOpaque (true);
  24872. setVisible (true);
  24873. setSize (400, 300);
  24874. ComponentDescription viewList [16];
  24875. UInt32 viewListSize = sizeof (viewList);
  24876. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  24877. 0, &viewList, &viewListSize);
  24878. componentRecord = FindNextComponent (0, &viewList[0]);
  24879. }
  24880. ~AudioUnitPluginWindowCarbon()
  24881. {
  24882. innerWrapper = 0;
  24883. if (isValid())
  24884. plugin.editorBeingDeleted (this);
  24885. }
  24886. bool isValid() const throw() { return componentRecord != 0; }
  24887. void paint (Graphics& g)
  24888. {
  24889. g.fillAll (Colours::black);
  24890. }
  24891. void resized()
  24892. {
  24893. innerWrapper->setSize (getWidth(), getHeight());
  24894. }
  24895. bool keyStateChanged (bool)
  24896. {
  24897. return false;
  24898. }
  24899. bool keyPressed (const KeyPress&)
  24900. {
  24901. return false;
  24902. }
  24903. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  24904. AudioUnitCarbonView getViewComponent()
  24905. {
  24906. if (viewComponent == 0 && componentRecord != 0)
  24907. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  24908. return viewComponent;
  24909. }
  24910. void closeViewComponent()
  24911. {
  24912. if (viewComponent != 0)
  24913. {
  24914. CloseComponent (viewComponent);
  24915. viewComponent = 0;
  24916. }
  24917. }
  24918. juce_UseDebuggingNewOperator
  24919. private:
  24920. AudioUnitPluginInstance& plugin;
  24921. ComponentRecord* componentRecord;
  24922. AudioUnitCarbonView viewComponent;
  24923. class InnerWrapperComponent : public CarbonViewWrapperComponent
  24924. {
  24925. public:
  24926. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  24927. : owner (owner_)
  24928. {
  24929. }
  24930. ~InnerWrapperComponent()
  24931. {
  24932. deleteWindow();
  24933. }
  24934. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  24935. {
  24936. log ("Opening AU GUI: " + owner->plugin.getName());
  24937. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  24938. if (viewComponent == 0)
  24939. return 0;
  24940. Float32Point pos = { 0, 0 };
  24941. Float32Point size = { 250, 200 };
  24942. HIViewRef pluginView = 0;
  24943. AudioUnitCarbonViewCreate (viewComponent,
  24944. owner->getAudioUnit(),
  24945. windowRef,
  24946. rootView,
  24947. &pos,
  24948. &size,
  24949. (ControlRef*) &pluginView);
  24950. return pluginView;
  24951. }
  24952. void removeView (HIViewRef)
  24953. {
  24954. log ("Closing AU GUI: " + owner->plugin.getName());
  24955. owner->closeViewComponent();
  24956. }
  24957. private:
  24958. AudioUnitPluginWindowCarbon* const owner;
  24959. };
  24960. friend class InnerWrapperComponent;
  24961. ScopedPointer<InnerWrapperComponent> innerWrapper;
  24962. };
  24963. #endif
  24964. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  24965. {
  24966. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  24967. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24968. w = 0;
  24969. #if JUCE_SUPPORT_CARBON
  24970. if (w == 0)
  24971. {
  24972. w = new AudioUnitPluginWindowCarbon (*this);
  24973. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24974. w = 0;
  24975. }
  24976. #endif
  24977. if (w == 0)
  24978. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  24979. return w.release();
  24980. }
  24981. const String AudioUnitPluginInstance::getCategory() const
  24982. {
  24983. const char* result = 0;
  24984. switch (componentDesc.componentType)
  24985. {
  24986. case kAudioUnitType_Effect:
  24987. case kAudioUnitType_MusicEffect:
  24988. result = "Effect";
  24989. break;
  24990. case kAudioUnitType_MusicDevice:
  24991. result = "Synth";
  24992. break;
  24993. case kAudioUnitType_Generator:
  24994. result = "Generator";
  24995. break;
  24996. case kAudioUnitType_Panner:
  24997. result = "Panner";
  24998. break;
  24999. default:
  25000. break;
  25001. }
  25002. return result;
  25003. }
  25004. int AudioUnitPluginInstance::getNumParameters()
  25005. {
  25006. return parameterIds.size();
  25007. }
  25008. float AudioUnitPluginInstance::getParameter (int index)
  25009. {
  25010. const ScopedLock sl (lock);
  25011. Float32 value = 0.0f;
  25012. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25013. {
  25014. AudioUnitGetParameter (audioUnit,
  25015. (UInt32) parameterIds.getUnchecked (index),
  25016. kAudioUnitScope_Global, 0,
  25017. &value);
  25018. }
  25019. return value;
  25020. }
  25021. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25022. {
  25023. const ScopedLock sl (lock);
  25024. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25025. {
  25026. AudioUnitSetParameter (audioUnit,
  25027. (UInt32) parameterIds.getUnchecked (index),
  25028. kAudioUnitScope_Global, 0,
  25029. newValue, 0);
  25030. }
  25031. }
  25032. const String AudioUnitPluginInstance::getParameterName (int index)
  25033. {
  25034. AudioUnitParameterInfo info;
  25035. zerostruct (info);
  25036. UInt32 sz = sizeof (info);
  25037. String name;
  25038. if (AudioUnitGetProperty (audioUnit,
  25039. kAudioUnitProperty_ParameterInfo,
  25040. kAudioUnitScope_Global,
  25041. parameterIds [index], &info, &sz) == noErr)
  25042. {
  25043. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25044. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25045. else
  25046. name = String (info.name, sizeof (info.name));
  25047. }
  25048. return name;
  25049. }
  25050. const String AudioUnitPluginInstance::getParameterText (int index)
  25051. {
  25052. return String (getParameter (index));
  25053. }
  25054. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25055. {
  25056. AudioUnitParameterInfo info;
  25057. UInt32 sz = sizeof (info);
  25058. if (AudioUnitGetProperty (audioUnit,
  25059. kAudioUnitProperty_ParameterInfo,
  25060. kAudioUnitScope_Global,
  25061. parameterIds [index], &info, &sz) == noErr)
  25062. {
  25063. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25064. }
  25065. return true;
  25066. }
  25067. int AudioUnitPluginInstance::getNumPrograms()
  25068. {
  25069. CFArrayRef presets;
  25070. UInt32 sz = sizeof (CFArrayRef);
  25071. int num = 0;
  25072. if (AudioUnitGetProperty (audioUnit,
  25073. kAudioUnitProperty_FactoryPresets,
  25074. kAudioUnitScope_Global,
  25075. 0, &presets, &sz) == noErr)
  25076. {
  25077. num = (int) CFArrayGetCount (presets);
  25078. CFRelease (presets);
  25079. }
  25080. return num;
  25081. }
  25082. int AudioUnitPluginInstance::getCurrentProgram()
  25083. {
  25084. AUPreset current;
  25085. current.presetNumber = 0;
  25086. UInt32 sz = sizeof (AUPreset);
  25087. AudioUnitGetProperty (audioUnit,
  25088. kAudioUnitProperty_FactoryPresets,
  25089. kAudioUnitScope_Global,
  25090. 0, &current, &sz);
  25091. return current.presetNumber;
  25092. }
  25093. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25094. {
  25095. AUPreset current;
  25096. current.presetNumber = newIndex;
  25097. current.presetName = 0;
  25098. AudioUnitSetProperty (audioUnit,
  25099. kAudioUnitProperty_FactoryPresets,
  25100. kAudioUnitScope_Global,
  25101. 0, &current, sizeof (AUPreset));
  25102. }
  25103. const String AudioUnitPluginInstance::getProgramName (int index)
  25104. {
  25105. String s;
  25106. CFArrayRef presets;
  25107. UInt32 sz = sizeof (CFArrayRef);
  25108. if (AudioUnitGetProperty (audioUnit,
  25109. kAudioUnitProperty_FactoryPresets,
  25110. kAudioUnitScope_Global,
  25111. 0, &presets, &sz) == noErr)
  25112. {
  25113. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  25114. {
  25115. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  25116. if (p != 0 && p->presetNumber == index)
  25117. {
  25118. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  25119. break;
  25120. }
  25121. }
  25122. CFRelease (presets);
  25123. }
  25124. return s;
  25125. }
  25126. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  25127. {
  25128. jassertfalse; // xxx not implemented!
  25129. }
  25130. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  25131. {
  25132. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  25133. return "Input " + String (index + 1);
  25134. return String::empty;
  25135. }
  25136. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  25137. {
  25138. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  25139. return false;
  25140. return true;
  25141. }
  25142. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  25143. {
  25144. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  25145. return "Output " + String (index + 1);
  25146. return String::empty;
  25147. }
  25148. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  25149. {
  25150. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  25151. return false;
  25152. return true;
  25153. }
  25154. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  25155. {
  25156. getCurrentProgramStateInformation (destData);
  25157. }
  25158. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  25159. {
  25160. CFPropertyListRef propertyList = 0;
  25161. UInt32 sz = sizeof (CFPropertyListRef);
  25162. if (AudioUnitGetProperty (audioUnit,
  25163. kAudioUnitProperty_ClassInfo,
  25164. kAudioUnitScope_Global,
  25165. 0, &propertyList, &sz) == noErr)
  25166. {
  25167. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  25168. CFWriteStreamOpen (stream);
  25169. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  25170. CFWriteStreamClose (stream);
  25171. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  25172. destData.setSize (bytesWritten);
  25173. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  25174. CFRelease (data);
  25175. CFRelease (stream);
  25176. CFRelease (propertyList);
  25177. }
  25178. }
  25179. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  25180. {
  25181. setCurrentProgramStateInformation (data, sizeInBytes);
  25182. }
  25183. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  25184. {
  25185. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  25186. (const UInt8*) data,
  25187. sizeInBytes,
  25188. kCFAllocatorNull);
  25189. CFReadStreamOpen (stream);
  25190. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  25191. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  25192. stream,
  25193. 0,
  25194. kCFPropertyListImmutable,
  25195. &format,
  25196. 0);
  25197. CFRelease (stream);
  25198. if (propertyList != 0)
  25199. AudioUnitSetProperty (audioUnit,
  25200. kAudioUnitProperty_ClassInfo,
  25201. kAudioUnitScope_Global,
  25202. 0, &propertyList, sizeof (propertyList));
  25203. }
  25204. AudioUnitPluginFormat::AudioUnitPluginFormat()
  25205. {
  25206. }
  25207. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  25208. {
  25209. }
  25210. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  25211. const String& fileOrIdentifier)
  25212. {
  25213. if (! fileMightContainThisPluginType (fileOrIdentifier))
  25214. return;
  25215. PluginDescription desc;
  25216. desc.fileOrIdentifier = fileOrIdentifier;
  25217. desc.uid = 0;
  25218. try
  25219. {
  25220. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  25221. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  25222. if (auInstance != 0)
  25223. {
  25224. auInstance->fillInPluginDescription (desc);
  25225. results.add (new PluginDescription (desc));
  25226. }
  25227. }
  25228. catch (...)
  25229. {
  25230. // crashed while loading...
  25231. }
  25232. }
  25233. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  25234. {
  25235. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  25236. {
  25237. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  25238. if (result->audioUnit != 0)
  25239. {
  25240. result->initialise();
  25241. return result.release();
  25242. }
  25243. }
  25244. return 0;
  25245. }
  25246. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  25247. const bool /*recursive*/)
  25248. {
  25249. StringArray result;
  25250. ComponentRecord* comp = 0;
  25251. ComponentDescription desc;
  25252. zerostruct (desc);
  25253. for (;;)
  25254. {
  25255. zerostruct (desc);
  25256. comp = FindNextComponent (comp, &desc);
  25257. if (comp == 0)
  25258. break;
  25259. GetComponentInfo (comp, &desc, 0, 0, 0);
  25260. if (desc.componentType == kAudioUnitType_MusicDevice
  25261. || desc.componentType == kAudioUnitType_MusicEffect
  25262. || desc.componentType == kAudioUnitType_Effect
  25263. || desc.componentType == kAudioUnitType_Generator
  25264. || desc.componentType == kAudioUnitType_Panner)
  25265. {
  25266. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  25267. DBG (s);
  25268. result.add (s);
  25269. }
  25270. }
  25271. return result;
  25272. }
  25273. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  25274. {
  25275. ComponentDescription desc;
  25276. String name, version, manufacturer;
  25277. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  25278. return FindNextComponent (0, &desc) != 0;
  25279. const File f (fileOrIdentifier);
  25280. return f.hasFileExtension (".component")
  25281. && f.isDirectory();
  25282. }
  25283. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  25284. {
  25285. ComponentDescription desc;
  25286. String name, version, manufacturer;
  25287. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  25288. if (name.isEmpty())
  25289. name = fileOrIdentifier;
  25290. return name;
  25291. }
  25292. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  25293. {
  25294. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  25295. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  25296. else
  25297. return File (desc.fileOrIdentifier).exists();
  25298. }
  25299. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  25300. {
  25301. return FileSearchPath ("/(Default AudioUnit locations)");
  25302. }
  25303. #endif
  25304. END_JUCE_NAMESPACE
  25305. #undef log
  25306. #endif
  25307. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25308. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  25309. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  25310. #define JUCE_MAC_VST_INCLUDED 1
  25311. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  25312. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  25313. #if JUCE_WINDOWS
  25314. #undef _WIN32_WINNT
  25315. #define _WIN32_WINNT 0x500
  25316. #undef STRICT
  25317. #define STRICT
  25318. #include <windows.h>
  25319. #include <float.h>
  25320. #pragma warning (disable : 4312 4355)
  25321. #elif JUCE_LINUX
  25322. #include <float.h>
  25323. #include <sys/time.h>
  25324. #include <X11/Xlib.h>
  25325. #include <X11/Xutil.h>
  25326. #include <X11/Xatom.h>
  25327. #undef Font
  25328. #undef KeyPress
  25329. #undef Drawable
  25330. #undef Time
  25331. #else
  25332. #include <Cocoa/Cocoa.h>
  25333. #include <Carbon/Carbon.h>
  25334. #endif
  25335. #if ! (JUCE_MAC && JUCE_64BIT)
  25336. BEGIN_JUCE_NAMESPACE
  25337. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25338. #endif
  25339. #undef PRAGMA_ALIGN_SUPPORTED
  25340. #define VST_FORCE_DEPRECATED 0
  25341. #if JUCE_MSVC
  25342. #pragma warning (push)
  25343. #pragma warning (disable: 4996)
  25344. #endif
  25345. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  25346. your include path if you want to add VST support.
  25347. If you're not interested in VSTs, you can disable them by changing the
  25348. JUCE_PLUGINHOST_VST flag in juce_Config.h
  25349. */
  25350. #include "pluginterfaces/vst2.x/aeffectx.h"
  25351. #if JUCE_MSVC
  25352. #pragma warning (pop)
  25353. #endif
  25354. #if JUCE_LINUX
  25355. #define Font JUCE_NAMESPACE::Font
  25356. #define KeyPress JUCE_NAMESPACE::KeyPress
  25357. #define Drawable JUCE_NAMESPACE::Drawable
  25358. #define Time JUCE_NAMESPACE::Time
  25359. #endif
  25360. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  25361. #ifdef __aeffect__
  25362. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25363. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25364. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  25365. events to the list.
  25366. This is used by both the VST hosting code and the plugin wrapper.
  25367. */
  25368. class VSTMidiEventList
  25369. {
  25370. public:
  25371. VSTMidiEventList()
  25372. : numEventsUsed (0), numEventsAllocated (0)
  25373. {
  25374. }
  25375. ~VSTMidiEventList()
  25376. {
  25377. freeEvents();
  25378. }
  25379. void clear()
  25380. {
  25381. numEventsUsed = 0;
  25382. if (events != 0)
  25383. events->numEvents = 0;
  25384. }
  25385. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  25386. {
  25387. ensureSize (numEventsUsed + 1);
  25388. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  25389. events->numEvents = ++numEventsUsed;
  25390. if (numBytes <= 4)
  25391. {
  25392. if (e->type == kVstSysExType)
  25393. {
  25394. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25395. e->type = kVstMidiType;
  25396. e->byteSize = sizeof (VstMidiEvent);
  25397. e->noteLength = 0;
  25398. e->noteOffset = 0;
  25399. e->detune = 0;
  25400. e->noteOffVelocity = 0;
  25401. }
  25402. e->deltaFrames = frameOffset;
  25403. memcpy (e->midiData, midiData, numBytes);
  25404. }
  25405. else
  25406. {
  25407. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  25408. if (se->type == kVstSysExType)
  25409. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  25410. else
  25411. se->sysexDump = (char*) juce_malloc (numBytes);
  25412. memcpy (se->sysexDump, midiData, numBytes);
  25413. se->type = kVstSysExType;
  25414. se->byteSize = sizeof (VstMidiSysexEvent);
  25415. se->deltaFrames = frameOffset;
  25416. se->flags = 0;
  25417. se->dumpBytes = numBytes;
  25418. se->resvd1 = 0;
  25419. se->resvd2 = 0;
  25420. }
  25421. }
  25422. // Handy method to pull the events out of an event buffer supplied by the host
  25423. // or plugin.
  25424. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  25425. {
  25426. for (int i = 0; i < events->numEvents; ++i)
  25427. {
  25428. const VstEvent* const e = events->events[i];
  25429. if (e != 0)
  25430. {
  25431. if (e->type == kVstMidiType)
  25432. {
  25433. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  25434. 4, e->deltaFrames);
  25435. }
  25436. else if (e->type == kVstSysExType)
  25437. {
  25438. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  25439. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  25440. e->deltaFrames);
  25441. }
  25442. }
  25443. }
  25444. }
  25445. void ensureSize (int numEventsNeeded)
  25446. {
  25447. if (numEventsNeeded > numEventsAllocated)
  25448. {
  25449. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  25450. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  25451. if (events == 0)
  25452. events.calloc (size, 1);
  25453. else
  25454. events.realloc (size, 1);
  25455. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  25456. {
  25457. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  25458. (int) sizeof (VstMidiSysexEvent)));
  25459. e->type = kVstMidiType;
  25460. e->byteSize = sizeof (VstMidiEvent);
  25461. events->events[i] = (VstEvent*) e;
  25462. }
  25463. numEventsAllocated = numEventsNeeded;
  25464. }
  25465. }
  25466. void freeEvents()
  25467. {
  25468. if (events != 0)
  25469. {
  25470. for (int i = numEventsAllocated; --i >= 0;)
  25471. {
  25472. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  25473. if (e->type == kVstSysExType)
  25474. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25475. juce_free (e);
  25476. }
  25477. events.free();
  25478. numEventsUsed = 0;
  25479. numEventsAllocated = 0;
  25480. }
  25481. }
  25482. HeapBlock <VstEvents> events;
  25483. private:
  25484. int numEventsUsed, numEventsAllocated;
  25485. };
  25486. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25487. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25488. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  25489. #if ! JUCE_WINDOWS
  25490. static void _fpreset() {}
  25491. static void _clearfp() {}
  25492. #endif
  25493. extern void juce_callAnyTimersSynchronously();
  25494. const int fxbVersionNum = 1;
  25495. struct fxProgram
  25496. {
  25497. long chunkMagic; // 'CcnK'
  25498. long byteSize; // of this chunk, excl. magic + byteSize
  25499. long fxMagic; // 'FxCk'
  25500. long version;
  25501. long fxID; // fx unique id
  25502. long fxVersion;
  25503. long numParams;
  25504. char prgName[28];
  25505. float params[1]; // variable no. of parameters
  25506. };
  25507. struct fxSet
  25508. {
  25509. long chunkMagic; // 'CcnK'
  25510. long byteSize; // of this chunk, excl. magic + byteSize
  25511. long fxMagic; // 'FxBk'
  25512. long version;
  25513. long fxID; // fx unique id
  25514. long fxVersion;
  25515. long numPrograms;
  25516. char future[128];
  25517. fxProgram programs[1]; // variable no. of programs
  25518. };
  25519. struct fxChunkSet
  25520. {
  25521. long chunkMagic; // 'CcnK'
  25522. long byteSize; // of this chunk, excl. magic + byteSize
  25523. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25524. long version;
  25525. long fxID; // fx unique id
  25526. long fxVersion;
  25527. long numPrograms;
  25528. char future[128];
  25529. long chunkSize;
  25530. char chunk[8]; // variable
  25531. };
  25532. struct fxProgramSet
  25533. {
  25534. long chunkMagic; // 'CcnK'
  25535. long byteSize; // of this chunk, excl. magic + byteSize
  25536. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25537. long version;
  25538. long fxID; // fx unique id
  25539. long fxVersion;
  25540. long numPrograms;
  25541. char name[28];
  25542. long chunkSize;
  25543. char chunk[8]; // variable
  25544. };
  25545. static long vst_swap (const long x) throw()
  25546. {
  25547. #ifdef JUCE_LITTLE_ENDIAN
  25548. return (long) ByteOrder::swap ((uint32) x);
  25549. #else
  25550. return x;
  25551. #endif
  25552. }
  25553. static float vst_swapFloat (const float x) throw()
  25554. {
  25555. #ifdef JUCE_LITTLE_ENDIAN
  25556. union { uint32 asInt; float asFloat; } n;
  25557. n.asFloat = x;
  25558. n.asInt = ByteOrder::swap (n.asInt);
  25559. return n.asFloat;
  25560. #else
  25561. return x;
  25562. #endif
  25563. }
  25564. typedef AEffect* (*MainCall) (audioMasterCallback);
  25565. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  25566. static int shellUIDToCreate = 0;
  25567. static int insideVSTCallback = 0;
  25568. class VSTPluginWindow;
  25569. // Change this to disable logging of various VST activities
  25570. #ifndef VST_LOGGING
  25571. #define VST_LOGGING 1
  25572. #endif
  25573. #if VST_LOGGING
  25574. #define log(a) Logger::writeToLog(a);
  25575. #else
  25576. #define log(a)
  25577. #endif
  25578. #if JUCE_MAC && JUCE_PPC
  25579. static void* NewCFMFromMachO (void* const machofp) throw()
  25580. {
  25581. void* result = juce_malloc (8);
  25582. ((void**) result)[0] = machofp;
  25583. ((void**) result)[1] = result;
  25584. return result;
  25585. }
  25586. #endif
  25587. #if JUCE_LINUX
  25588. extern Display* display;
  25589. extern XContext windowHandleXContext;
  25590. typedef void (*EventProcPtr) (XEvent* ev);
  25591. static bool xErrorTriggered;
  25592. static int temporaryErrorHandler (Display*, XErrorEvent*)
  25593. {
  25594. xErrorTriggered = true;
  25595. return 0;
  25596. }
  25597. static int getPropertyFromXWindow (Window handle, Atom atom)
  25598. {
  25599. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  25600. xErrorTriggered = false;
  25601. int userSize;
  25602. unsigned long bytes, userCount;
  25603. unsigned char* data;
  25604. Atom userType;
  25605. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  25606. &userType, &userSize, &userCount, &bytes, &data);
  25607. XSetErrorHandler (oldErrorHandler);
  25608. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  25609. : 0;
  25610. }
  25611. static Window getChildWindow (Window windowToCheck)
  25612. {
  25613. Window rootWindow, parentWindow;
  25614. Window* childWindows;
  25615. unsigned int numChildren;
  25616. XQueryTree (display,
  25617. windowToCheck,
  25618. &rootWindow,
  25619. &parentWindow,
  25620. &childWindows,
  25621. &numChildren);
  25622. if (numChildren > 0)
  25623. return childWindows [0];
  25624. return 0;
  25625. }
  25626. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  25627. {
  25628. if (e.mods.isLeftButtonDown())
  25629. {
  25630. ev.xbutton.button = Button1;
  25631. ev.xbutton.state |= Button1Mask;
  25632. }
  25633. else if (e.mods.isRightButtonDown())
  25634. {
  25635. ev.xbutton.button = Button3;
  25636. ev.xbutton.state |= Button3Mask;
  25637. }
  25638. else if (e.mods.isMiddleButtonDown())
  25639. {
  25640. ev.xbutton.button = Button2;
  25641. ev.xbutton.state |= Button2Mask;
  25642. }
  25643. }
  25644. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  25645. {
  25646. if (e.mods.isLeftButtonDown())
  25647. ev.xmotion.state |= Button1Mask;
  25648. else if (e.mods.isRightButtonDown())
  25649. ev.xmotion.state |= Button3Mask;
  25650. else if (e.mods.isMiddleButtonDown())
  25651. ev.xmotion.state |= Button2Mask;
  25652. }
  25653. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  25654. {
  25655. if (e.mods.isLeftButtonDown())
  25656. ev.xcrossing.state |= Button1Mask;
  25657. else if (e.mods.isRightButtonDown())
  25658. ev.xcrossing.state |= Button3Mask;
  25659. else if (e.mods.isMiddleButtonDown())
  25660. ev.xcrossing.state |= Button2Mask;
  25661. }
  25662. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  25663. {
  25664. if (increment < 0)
  25665. {
  25666. ev.xbutton.button = Button5;
  25667. ev.xbutton.state |= Button5Mask;
  25668. }
  25669. else if (increment > 0)
  25670. {
  25671. ev.xbutton.button = Button4;
  25672. ev.xbutton.state |= Button4Mask;
  25673. }
  25674. }
  25675. #endif
  25676. class ModuleHandle : public ReferenceCountedObject
  25677. {
  25678. public:
  25679. File file;
  25680. MainCall moduleMain;
  25681. String pluginName;
  25682. static Array <ModuleHandle*>& getActiveModules()
  25683. {
  25684. static Array <ModuleHandle*> activeModules;
  25685. return activeModules;
  25686. }
  25687. static ModuleHandle* findOrCreateModule (const File& file)
  25688. {
  25689. for (int i = getActiveModules().size(); --i >= 0;)
  25690. {
  25691. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  25692. if (module->file == file)
  25693. return module;
  25694. }
  25695. _fpreset(); // (doesn't do any harm)
  25696. ++insideVSTCallback;
  25697. shellUIDToCreate = 0;
  25698. log ("Attempting to load VST: " + file.getFullPathName());
  25699. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  25700. if (! m->open())
  25701. m = 0;
  25702. --insideVSTCallback;
  25703. _fpreset(); // (doesn't do any harm)
  25704. return m.release();
  25705. }
  25706. ModuleHandle (const File& file_)
  25707. : file (file_),
  25708. moduleMain (0),
  25709. #if JUCE_WINDOWS || JUCE_LINUX
  25710. hModule (0)
  25711. #elif JUCE_MAC
  25712. fragId (0),
  25713. resHandle (0),
  25714. bundleRef (0),
  25715. resFileId (0)
  25716. #endif
  25717. {
  25718. getActiveModules().add (this);
  25719. #if JUCE_WINDOWS || JUCE_LINUX
  25720. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  25721. #elif JUCE_MAC
  25722. FSRef ref;
  25723. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  25724. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  25725. #endif
  25726. }
  25727. ~ModuleHandle()
  25728. {
  25729. getActiveModules().removeValue (this);
  25730. close();
  25731. }
  25732. juce_UseDebuggingNewOperator
  25733. #if JUCE_WINDOWS || JUCE_LINUX
  25734. void* hModule;
  25735. String fullParentDirectoryPathName;
  25736. bool open()
  25737. {
  25738. #if JUCE_WINDOWS
  25739. static bool timePeriodSet = false;
  25740. if (! timePeriodSet)
  25741. {
  25742. timePeriodSet = true;
  25743. timeBeginPeriod (2);
  25744. }
  25745. #endif
  25746. pluginName = file.getFileNameWithoutExtension();
  25747. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  25748. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  25749. if (moduleMain == 0)
  25750. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  25751. return moduleMain != 0;
  25752. }
  25753. void close()
  25754. {
  25755. _fpreset(); // (doesn't do any harm)
  25756. PlatformUtilities::freeDynamicLibrary (hModule);
  25757. }
  25758. void closeEffect (AEffect* eff)
  25759. {
  25760. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25761. }
  25762. #else
  25763. CFragConnectionID fragId;
  25764. Handle resHandle;
  25765. CFBundleRef bundleRef;
  25766. FSSpec parentDirFSSpec;
  25767. short resFileId;
  25768. bool open()
  25769. {
  25770. bool ok = false;
  25771. const String filename (file.getFullPathName());
  25772. if (file.hasFileExtension (".vst"))
  25773. {
  25774. const char* const utf8 = filename.toUTF8();
  25775. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25776. strlen (utf8), file.isDirectory());
  25777. if (url != 0)
  25778. {
  25779. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25780. CFRelease (url);
  25781. if (bundleRef != 0)
  25782. {
  25783. if (CFBundleLoadExecutable (bundleRef))
  25784. {
  25785. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  25786. if (moduleMain == 0)
  25787. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  25788. if (moduleMain != 0)
  25789. {
  25790. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25791. if (name != 0)
  25792. {
  25793. if (CFGetTypeID (name) == CFStringGetTypeID())
  25794. {
  25795. char buffer[1024];
  25796. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  25797. pluginName = buffer;
  25798. }
  25799. }
  25800. if (pluginName.isEmpty())
  25801. pluginName = file.getFileNameWithoutExtension();
  25802. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25803. ok = true;
  25804. }
  25805. }
  25806. if (! ok)
  25807. {
  25808. CFBundleUnloadExecutable (bundleRef);
  25809. CFRelease (bundleRef);
  25810. bundleRef = 0;
  25811. }
  25812. }
  25813. }
  25814. }
  25815. #if JUCE_PPC
  25816. else
  25817. {
  25818. FSRef fn;
  25819. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  25820. {
  25821. resFileId = FSOpenResFile (&fn, fsRdPerm);
  25822. if (resFileId != -1)
  25823. {
  25824. const int numEffs = Count1Resources ('aEff');
  25825. for (int i = 0; i < numEffs; ++i)
  25826. {
  25827. resHandle = Get1IndResource ('aEff', i + 1);
  25828. if (resHandle != 0)
  25829. {
  25830. OSType type;
  25831. Str255 name;
  25832. SInt16 id;
  25833. GetResInfo (resHandle, &id, &type, name);
  25834. pluginName = String ((const char*) name + 1, name[0]);
  25835. DetachResource (resHandle);
  25836. HLock (resHandle);
  25837. Ptr ptr;
  25838. Str255 errorText;
  25839. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  25840. name, kPrivateCFragCopy,
  25841. &fragId, &ptr, errorText);
  25842. if (err == noErr)
  25843. {
  25844. moduleMain = (MainCall) newMachOFromCFM (ptr);
  25845. ok = true;
  25846. }
  25847. else
  25848. {
  25849. HUnlock (resHandle);
  25850. }
  25851. break;
  25852. }
  25853. }
  25854. if (! ok)
  25855. CloseResFile (resFileId);
  25856. }
  25857. }
  25858. }
  25859. #endif
  25860. return ok;
  25861. }
  25862. void close()
  25863. {
  25864. #if JUCE_PPC
  25865. if (fragId != 0)
  25866. {
  25867. if (moduleMain != 0)
  25868. disposeMachOFromCFM ((void*) moduleMain);
  25869. CloseConnection (&fragId);
  25870. HUnlock (resHandle);
  25871. if (resFileId != 0)
  25872. CloseResFile (resFileId);
  25873. }
  25874. else
  25875. #endif
  25876. if (bundleRef != 0)
  25877. {
  25878. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25879. if (CFGetRetainCount (bundleRef) == 1)
  25880. CFBundleUnloadExecutable (bundleRef);
  25881. if (CFGetRetainCount (bundleRef) > 0)
  25882. CFRelease (bundleRef);
  25883. }
  25884. }
  25885. void closeEffect (AEffect* eff)
  25886. {
  25887. #if JUCE_PPC
  25888. if (fragId != 0)
  25889. {
  25890. Array<void*> thingsToDelete;
  25891. thingsToDelete.add ((void*) eff->dispatcher);
  25892. thingsToDelete.add ((void*) eff->process);
  25893. thingsToDelete.add ((void*) eff->setParameter);
  25894. thingsToDelete.add ((void*) eff->getParameter);
  25895. thingsToDelete.add ((void*) eff->processReplacing);
  25896. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25897. for (int i = thingsToDelete.size(); --i >= 0;)
  25898. disposeMachOFromCFM (thingsToDelete[i]);
  25899. }
  25900. else
  25901. #endif
  25902. {
  25903. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25904. }
  25905. }
  25906. #if JUCE_PPC
  25907. static void* newMachOFromCFM (void* cfmfp)
  25908. {
  25909. if (cfmfp == 0)
  25910. return 0;
  25911. UInt32* const mfp = new UInt32[6];
  25912. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  25913. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  25914. mfp[2] = 0x800c0000;
  25915. mfp[3] = 0x804c0004;
  25916. mfp[4] = 0x7c0903a6;
  25917. mfp[5] = 0x4e800420;
  25918. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  25919. return mfp;
  25920. }
  25921. static void disposeMachOFromCFM (void* ptr)
  25922. {
  25923. delete[] static_cast <UInt32*> (ptr);
  25924. }
  25925. void coerceAEffectFunctionCalls (AEffect* eff)
  25926. {
  25927. if (fragId != 0)
  25928. {
  25929. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  25930. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  25931. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  25932. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  25933. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  25934. }
  25935. }
  25936. #endif
  25937. #endif
  25938. };
  25939. /**
  25940. An instance of a plugin, created by a VSTPluginFormat.
  25941. */
  25942. class VSTPluginInstance : public AudioPluginInstance,
  25943. private Timer,
  25944. private AsyncUpdater
  25945. {
  25946. public:
  25947. ~VSTPluginInstance();
  25948. // AudioPluginInstance methods:
  25949. void fillInPluginDescription (PluginDescription& desc) const
  25950. {
  25951. desc.name = name;
  25952. desc.fileOrIdentifier = module->file.getFullPathName();
  25953. desc.uid = getUID();
  25954. desc.lastFileModTime = module->file.getLastModificationTime();
  25955. desc.pluginFormatName = "VST";
  25956. desc.category = getCategory();
  25957. {
  25958. char buffer [kVstMaxVendorStrLen + 8];
  25959. zerostruct (buffer);
  25960. dispatch (effGetVendorString, 0, 0, buffer, 0);
  25961. desc.manufacturerName = buffer;
  25962. }
  25963. desc.version = getVersion();
  25964. desc.numInputChannels = getNumInputChannels();
  25965. desc.numOutputChannels = getNumOutputChannels();
  25966. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  25967. }
  25968. const String getName() const { return name; }
  25969. int getUID() const throw();
  25970. bool acceptsMidi() const { return wantsMidiMessages; }
  25971. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  25972. // AudioProcessor methods:
  25973. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25974. void releaseResources();
  25975. void processBlock (AudioSampleBuffer& buffer,
  25976. MidiBuffer& midiMessages);
  25977. AudioProcessorEditor* createEditor();
  25978. const String getInputChannelName (const int index) const;
  25979. bool isInputChannelStereoPair (int index) const;
  25980. const String getOutputChannelName (const int index) const;
  25981. bool isOutputChannelStereoPair (int index) const;
  25982. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  25983. float getParameter (int index);
  25984. void setParameter (int index, float newValue);
  25985. const String getParameterName (int index);
  25986. const String getParameterText (int index);
  25987. bool isParameterAutomatable (int index) const;
  25988. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  25989. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  25990. void setCurrentProgram (int index);
  25991. const String getProgramName (int index);
  25992. void changeProgramName (int index, const String& newName);
  25993. void getStateInformation (MemoryBlock& destData);
  25994. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25995. void setStateInformation (const void* data, int sizeInBytes);
  25996. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25997. void timerCallback();
  25998. void handleAsyncUpdate();
  25999. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26000. juce_UseDebuggingNewOperator
  26001. private:
  26002. friend class VSTPluginWindow;
  26003. friend class VSTPluginFormat;
  26004. AEffect* effect;
  26005. String name;
  26006. CriticalSection lock;
  26007. bool wantsMidiMessages, initialised, isPowerOn;
  26008. mutable StringArray programNames;
  26009. AudioSampleBuffer tempBuffer;
  26010. CriticalSection midiInLock;
  26011. MidiBuffer incomingMidi;
  26012. VSTMidiEventList midiEventsToSend;
  26013. VstTimeInfo vstHostTime;
  26014. HeapBlock <float*> channels;
  26015. ReferenceCountedObjectPtr <ModuleHandle> module;
  26016. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26017. bool restoreProgramSettings (const fxProgram* const prog);
  26018. const String getCurrentProgramName();
  26019. void setParamsInProgramBlock (fxProgram* const prog) throw();
  26020. void updateStoredProgramNames();
  26021. void initialise();
  26022. void handleMidiFromPlugin (const VstEvents* const events);
  26023. void createTempParameterStore (MemoryBlock& dest);
  26024. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26025. const String getParameterLabel (int index) const;
  26026. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26027. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26028. void setChunkData (const char* data, int size, bool isPreset);
  26029. bool loadFromFXBFile (const void* data, int numBytes);
  26030. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26031. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26032. const String getVersion() const throw();
  26033. const String getCategory() const throw();
  26034. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26035. void setPower (const bool on);
  26036. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26037. };
  26038. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26039. : effect (0),
  26040. wantsMidiMessages (false),
  26041. initialised (false),
  26042. isPowerOn (false),
  26043. tempBuffer (1, 1),
  26044. module (module_)
  26045. {
  26046. try
  26047. {
  26048. _fpreset();
  26049. ++insideVSTCallback;
  26050. name = module->pluginName;
  26051. log ("Creating VST instance: " + name);
  26052. #if JUCE_MAC
  26053. if (module->resFileId != 0)
  26054. UseResFile (module->resFileId);
  26055. #if JUCE_PPC
  26056. if (module->fragId != 0)
  26057. {
  26058. static void* audioMasterCoerced = 0;
  26059. if (audioMasterCoerced == 0)
  26060. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26061. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26062. }
  26063. else
  26064. #endif
  26065. #endif
  26066. {
  26067. effect = module->moduleMain (&audioMaster);
  26068. }
  26069. --insideVSTCallback;
  26070. if (effect != 0 && effect->magic == kEffectMagic)
  26071. {
  26072. #if JUCE_PPC
  26073. module->coerceAEffectFunctionCalls (effect);
  26074. #endif
  26075. jassert (effect->resvd2 == 0);
  26076. jassert (effect->object != 0);
  26077. _fpreset(); // some dodgy plugs fuck around with this
  26078. }
  26079. else
  26080. {
  26081. effect = 0;
  26082. }
  26083. }
  26084. catch (...)
  26085. {
  26086. --insideVSTCallback;
  26087. }
  26088. }
  26089. VSTPluginInstance::~VSTPluginInstance()
  26090. {
  26091. {
  26092. const ScopedLock sl (lock);
  26093. jassert (insideVSTCallback == 0);
  26094. if (effect != 0 && effect->magic == kEffectMagic)
  26095. {
  26096. try
  26097. {
  26098. #if JUCE_MAC
  26099. if (module->resFileId != 0)
  26100. UseResFile (module->resFileId);
  26101. #endif
  26102. // Must delete any editors before deleting the plugin instance!
  26103. jassert (getActiveEditor() == 0);
  26104. _fpreset(); // some dodgy plugs fuck around with this
  26105. module->closeEffect (effect);
  26106. }
  26107. catch (...)
  26108. {}
  26109. }
  26110. module = 0;
  26111. effect = 0;
  26112. }
  26113. }
  26114. void VSTPluginInstance::initialise()
  26115. {
  26116. if (initialised || effect == 0)
  26117. return;
  26118. log ("Initialising VST: " + module->pluginName);
  26119. initialised = true;
  26120. dispatch (effIdentify, 0, 0, 0, 0);
  26121. // this code would ask the plugin for its name, but so few plugins
  26122. // actually bother implementing this correctly, that it's better to
  26123. // just ignore it and use the file name instead.
  26124. /* {
  26125. char buffer [256];
  26126. zerostruct (buffer);
  26127. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26128. name = String (buffer).trim();
  26129. if (name.isEmpty())
  26130. name = module->pluginName;
  26131. }
  26132. */
  26133. if (getSampleRate() > 0)
  26134. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  26135. if (getBlockSize() > 0)
  26136. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  26137. dispatch (effOpen, 0, 0, 0, 0);
  26138. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26139. getSampleRate(), getBlockSize());
  26140. if (getNumPrograms() > 1)
  26141. setCurrentProgram (0);
  26142. else
  26143. dispatch (effSetProgram, 0, 0, 0, 0);
  26144. int i;
  26145. for (i = effect->numInputs; --i >= 0;)
  26146. dispatch (effConnectInput, i, 1, 0, 0);
  26147. for (i = effect->numOutputs; --i >= 0;)
  26148. dispatch (effConnectOutput, i, 1, 0, 0);
  26149. updateStoredProgramNames();
  26150. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  26151. setLatencySamples (effect->initialDelay);
  26152. }
  26153. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  26154. int samplesPerBlockExpected)
  26155. {
  26156. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26157. sampleRate_, samplesPerBlockExpected);
  26158. setLatencySamples (effect->initialDelay);
  26159. channels.calloc (jmax (16, getNumOutputChannels(), getNumInputChannels()) + 2);
  26160. vstHostTime.tempo = 120.0;
  26161. vstHostTime.timeSigNumerator = 4;
  26162. vstHostTime.timeSigDenominator = 4;
  26163. vstHostTime.sampleRate = sampleRate_;
  26164. vstHostTime.samplePos = 0;
  26165. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  26166. initialise();
  26167. if (initialised)
  26168. {
  26169. wantsMidiMessages = wantsMidiMessages
  26170. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  26171. if (wantsMidiMessages)
  26172. midiEventsToSend.ensureSize (256);
  26173. else
  26174. midiEventsToSend.freeEvents();
  26175. incomingMidi.clear();
  26176. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  26177. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  26178. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  26179. if (! isPowerOn)
  26180. setPower (true);
  26181. // dodgy hack to force some plugins to initialise the sample rate..
  26182. if ((! hasEditor()) && getNumParameters() > 0)
  26183. {
  26184. const float old = getParameter (0);
  26185. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  26186. setParameter (0, old);
  26187. }
  26188. dispatch (effStartProcess, 0, 0, 0, 0);
  26189. }
  26190. }
  26191. void VSTPluginInstance::releaseResources()
  26192. {
  26193. if (initialised)
  26194. {
  26195. dispatch (effStopProcess, 0, 0, 0, 0);
  26196. setPower (false);
  26197. }
  26198. tempBuffer.setSize (1, 1);
  26199. incomingMidi.clear();
  26200. midiEventsToSend.freeEvents();
  26201. channels.free();
  26202. }
  26203. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  26204. MidiBuffer& midiMessages)
  26205. {
  26206. const int numSamples = buffer.getNumSamples();
  26207. if (initialised)
  26208. {
  26209. AudioPlayHead* playHead = getPlayHead();
  26210. if (playHead != 0)
  26211. {
  26212. AudioPlayHead::CurrentPositionInfo position;
  26213. playHead->getCurrentPosition (position);
  26214. vstHostTime.tempo = position.bpm;
  26215. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  26216. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  26217. vstHostTime.ppqPos = position.ppqPosition;
  26218. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  26219. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  26220. if (position.isPlaying)
  26221. vstHostTime.flags |= kVstTransportPlaying;
  26222. else
  26223. vstHostTime.flags &= ~kVstTransportPlaying;
  26224. }
  26225. #if JUCE_WINDOWS
  26226. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  26227. #elif JUCE_LINUX
  26228. timeval micro;
  26229. gettimeofday (&micro, 0);
  26230. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  26231. #elif JUCE_MAC
  26232. UnsignedWide micro;
  26233. Microseconds (&micro);
  26234. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  26235. #endif
  26236. if (wantsMidiMessages)
  26237. {
  26238. midiEventsToSend.clear();
  26239. midiEventsToSend.ensureSize (1);
  26240. MidiBuffer::Iterator iter (midiMessages);
  26241. const uint8* midiData;
  26242. int numBytesOfMidiData, samplePosition;
  26243. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  26244. {
  26245. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  26246. jlimit (0, numSamples - 1, samplePosition));
  26247. }
  26248. try
  26249. {
  26250. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  26251. }
  26252. catch (...)
  26253. {}
  26254. }
  26255. int i;
  26256. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  26257. for (i = 0; i < maxChans; ++i)
  26258. channels[i] = buffer.getSampleData (i);
  26259. channels [maxChans] = 0;
  26260. _clearfp();
  26261. if ((effect->flags & effFlagsCanReplacing) != 0)
  26262. {
  26263. try
  26264. {
  26265. effect->processReplacing (effect, channels, channels, numSamples);
  26266. }
  26267. catch (...)
  26268. {}
  26269. }
  26270. else
  26271. {
  26272. tempBuffer.setSize (effect->numOutputs, numSamples);
  26273. tempBuffer.clear();
  26274. float* outs [64];
  26275. for (i = effect->numOutputs; --i >= 0;)
  26276. outs[i] = tempBuffer.getSampleData (i);
  26277. outs [effect->numOutputs] = 0;
  26278. try
  26279. {
  26280. effect->process (effect, channels, outs, numSamples);
  26281. }
  26282. catch (...)
  26283. {}
  26284. for (i = effect->numOutputs; --i >= 0;)
  26285. buffer.copyFrom (i, 0, outs[i], numSamples);
  26286. }
  26287. }
  26288. else
  26289. {
  26290. // Not initialised, so just bypass..
  26291. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  26292. buffer.clear (i, 0, buffer.getNumSamples());
  26293. }
  26294. {
  26295. // copy any incoming midi..
  26296. const ScopedLock sl (midiInLock);
  26297. midiMessages.swapWith (incomingMidi);
  26298. incomingMidi.clear();
  26299. }
  26300. }
  26301. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  26302. {
  26303. if (events != 0)
  26304. {
  26305. const ScopedLock sl (midiInLock);
  26306. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  26307. }
  26308. }
  26309. static Array <VSTPluginWindow*> activeVSTWindows;
  26310. class VSTPluginWindow : public AudioProcessorEditor,
  26311. #if ! JUCE_MAC
  26312. public ComponentMovementWatcher,
  26313. #endif
  26314. public Timer
  26315. {
  26316. public:
  26317. VSTPluginWindow (VSTPluginInstance& plugin_)
  26318. : AudioProcessorEditor (&plugin_),
  26319. #if ! JUCE_MAC
  26320. ComponentMovementWatcher (this),
  26321. #endif
  26322. plugin (plugin_),
  26323. isOpen (false),
  26324. wasShowing (false),
  26325. pluginRefusesToResize (false),
  26326. pluginWantsKeys (false),
  26327. alreadyInside (false),
  26328. recursiveResize (false)
  26329. {
  26330. #if JUCE_WINDOWS
  26331. sizeCheckCount = 0;
  26332. pluginHWND = 0;
  26333. #elif JUCE_LINUX
  26334. pluginWindow = None;
  26335. pluginProc = None;
  26336. #else
  26337. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  26338. #endif
  26339. activeVSTWindows.add (this);
  26340. setSize (1, 1);
  26341. setOpaque (true);
  26342. setVisible (true);
  26343. }
  26344. ~VSTPluginWindow()
  26345. {
  26346. #if JUCE_MAC
  26347. innerWrapper = 0;
  26348. #else
  26349. closePluginWindow();
  26350. #endif
  26351. activeVSTWindows.removeValue (this);
  26352. plugin.editorBeingDeleted (this);
  26353. }
  26354. #if ! JUCE_MAC
  26355. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  26356. {
  26357. if (recursiveResize)
  26358. return;
  26359. Component* const topComp = getTopLevelComponent();
  26360. if (topComp->getPeer() != 0)
  26361. {
  26362. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  26363. recursiveResize = true;
  26364. #if JUCE_WINDOWS
  26365. if (pluginHWND != 0)
  26366. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  26367. #elif JUCE_LINUX
  26368. if (pluginWindow != 0)
  26369. {
  26370. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  26371. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  26372. XMapRaised (display, pluginWindow);
  26373. }
  26374. #endif
  26375. recursiveResize = false;
  26376. }
  26377. }
  26378. void componentVisibilityChanged (Component&)
  26379. {
  26380. const bool isShowingNow = isShowing();
  26381. if (wasShowing != isShowingNow)
  26382. {
  26383. wasShowing = isShowingNow;
  26384. if (isShowingNow)
  26385. openPluginWindow();
  26386. else
  26387. closePluginWindow();
  26388. }
  26389. componentMovedOrResized (true, true);
  26390. }
  26391. void componentPeerChanged()
  26392. {
  26393. closePluginWindow();
  26394. openPluginWindow();
  26395. }
  26396. #endif
  26397. bool keyStateChanged (bool)
  26398. {
  26399. return pluginWantsKeys;
  26400. }
  26401. bool keyPressed (const KeyPress&)
  26402. {
  26403. return pluginWantsKeys;
  26404. }
  26405. #if JUCE_MAC
  26406. void paint (Graphics& g)
  26407. {
  26408. g.fillAll (Colours::black);
  26409. }
  26410. #else
  26411. void paint (Graphics& g)
  26412. {
  26413. if (isOpen)
  26414. {
  26415. ComponentPeer* const peer = getPeer();
  26416. if (peer != 0)
  26417. {
  26418. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26419. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  26420. #if JUCE_LINUX
  26421. if (pluginWindow != 0)
  26422. {
  26423. const Rectangle<int> clip (g.getClipBounds());
  26424. XEvent ev;
  26425. zerostruct (ev);
  26426. ev.xexpose.type = Expose;
  26427. ev.xexpose.display = display;
  26428. ev.xexpose.window = pluginWindow;
  26429. ev.xexpose.x = clip.getX();
  26430. ev.xexpose.y = clip.getY();
  26431. ev.xexpose.width = clip.getWidth();
  26432. ev.xexpose.height = clip.getHeight();
  26433. sendEventToChild (&ev);
  26434. }
  26435. #endif
  26436. }
  26437. }
  26438. else
  26439. {
  26440. g.fillAll (Colours::black);
  26441. }
  26442. }
  26443. #endif
  26444. void timerCallback()
  26445. {
  26446. #if JUCE_WINDOWS
  26447. if (--sizeCheckCount <= 0)
  26448. {
  26449. sizeCheckCount = 10;
  26450. checkPluginWindowSize();
  26451. }
  26452. #endif
  26453. try
  26454. {
  26455. static bool reentrant = false;
  26456. if (! reentrant)
  26457. {
  26458. reentrant = true;
  26459. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  26460. reentrant = false;
  26461. }
  26462. }
  26463. catch (...)
  26464. {}
  26465. }
  26466. void mouseDown (const MouseEvent& e)
  26467. {
  26468. #if JUCE_LINUX
  26469. if (pluginWindow == 0)
  26470. return;
  26471. toFront (true);
  26472. XEvent ev;
  26473. zerostruct (ev);
  26474. ev.xbutton.display = display;
  26475. ev.xbutton.type = ButtonPress;
  26476. ev.xbutton.window = pluginWindow;
  26477. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26478. ev.xbutton.time = CurrentTime;
  26479. ev.xbutton.x = e.x;
  26480. ev.xbutton.y = e.y;
  26481. ev.xbutton.x_root = e.getScreenX();
  26482. ev.xbutton.y_root = e.getScreenY();
  26483. translateJuceToXButtonModifiers (e, ev);
  26484. sendEventToChild (&ev);
  26485. #elif JUCE_WINDOWS
  26486. (void) e;
  26487. toFront (true);
  26488. #endif
  26489. }
  26490. void broughtToFront()
  26491. {
  26492. activeVSTWindows.removeValue (this);
  26493. activeVSTWindows.add (this);
  26494. #if JUCE_MAC
  26495. dispatch (effEditTop, 0, 0, 0, 0);
  26496. #endif
  26497. }
  26498. juce_UseDebuggingNewOperator
  26499. private:
  26500. VSTPluginInstance& plugin;
  26501. bool isOpen, wasShowing, recursiveResize;
  26502. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  26503. #if JUCE_WINDOWS
  26504. HWND pluginHWND;
  26505. void* originalWndProc;
  26506. int sizeCheckCount;
  26507. #elif JUCE_LINUX
  26508. Window pluginWindow;
  26509. EventProcPtr pluginProc;
  26510. #endif
  26511. #if JUCE_MAC
  26512. void openPluginWindow (WindowRef parentWindow)
  26513. {
  26514. if (isOpen || parentWindow == 0)
  26515. return;
  26516. isOpen = true;
  26517. ERect* rect = 0;
  26518. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26519. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  26520. // do this before and after like in the steinberg example
  26521. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26522. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26523. // Install keyboard hooks
  26524. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26525. // double-check it's not too tiny
  26526. int w = 250, h = 150;
  26527. if (rect != 0)
  26528. {
  26529. w = rect->right - rect->left;
  26530. h = rect->bottom - rect->top;
  26531. if (w == 0 || h == 0)
  26532. {
  26533. w = 250;
  26534. h = 150;
  26535. }
  26536. }
  26537. w = jmax (w, 32);
  26538. h = jmax (h, 32);
  26539. setSize (w, h);
  26540. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26541. repaint();
  26542. }
  26543. #else
  26544. void openPluginWindow()
  26545. {
  26546. if (isOpen || getWindowHandle() == 0)
  26547. return;
  26548. log ("Opening VST UI: " + plugin.name);
  26549. isOpen = true;
  26550. ERect* rect = 0;
  26551. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26552. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  26553. // do this before and after like in the steinberg example
  26554. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26555. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26556. // Install keyboard hooks
  26557. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26558. #if JUCE_WINDOWS
  26559. originalWndProc = 0;
  26560. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  26561. if (pluginHWND == 0)
  26562. {
  26563. isOpen = false;
  26564. setSize (300, 150);
  26565. return;
  26566. }
  26567. #pragma warning (push)
  26568. #pragma warning (disable: 4244)
  26569. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  26570. if (! pluginWantsKeys)
  26571. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  26572. #pragma warning (pop)
  26573. int w, h;
  26574. RECT r;
  26575. GetWindowRect (pluginHWND, &r);
  26576. w = r.right - r.left;
  26577. h = r.bottom - r.top;
  26578. if (rect != 0)
  26579. {
  26580. const int rw = rect->right - rect->left;
  26581. const int rh = rect->bottom - rect->top;
  26582. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  26583. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  26584. {
  26585. // very dodgy logic to decide which size is right.
  26586. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  26587. {
  26588. SetWindowPos (pluginHWND, 0,
  26589. 0, 0, rw, rh,
  26590. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  26591. GetWindowRect (pluginHWND, &r);
  26592. w = r.right - r.left;
  26593. h = r.bottom - r.top;
  26594. pluginRefusesToResize = (w != rw) || (h != rh);
  26595. w = rw;
  26596. h = rh;
  26597. }
  26598. }
  26599. }
  26600. #elif JUCE_LINUX
  26601. pluginWindow = getChildWindow ((Window) getWindowHandle());
  26602. if (pluginWindow != 0)
  26603. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  26604. XInternAtom (display, "_XEventProc", False));
  26605. int w = 250, h = 150;
  26606. if (rect != 0)
  26607. {
  26608. w = rect->right - rect->left;
  26609. h = rect->bottom - rect->top;
  26610. if (w == 0 || h == 0)
  26611. {
  26612. w = 250;
  26613. h = 150;
  26614. }
  26615. }
  26616. if (pluginWindow != 0)
  26617. XMapRaised (display, pluginWindow);
  26618. #endif
  26619. // double-check it's not too tiny
  26620. w = jmax (w, 32);
  26621. h = jmax (h, 32);
  26622. setSize (w, h);
  26623. #if JUCE_WINDOWS
  26624. checkPluginWindowSize();
  26625. #endif
  26626. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26627. repaint();
  26628. }
  26629. #endif
  26630. #if ! JUCE_MAC
  26631. void closePluginWindow()
  26632. {
  26633. if (isOpen)
  26634. {
  26635. log ("Closing VST UI: " + plugin.getName());
  26636. isOpen = false;
  26637. dispatch (effEditClose, 0, 0, 0, 0);
  26638. #if JUCE_WINDOWS
  26639. #pragma warning (push)
  26640. #pragma warning (disable: 4244)
  26641. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26642. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  26643. #pragma warning (pop)
  26644. stopTimer();
  26645. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26646. DestroyWindow (pluginHWND);
  26647. pluginHWND = 0;
  26648. #elif JUCE_LINUX
  26649. stopTimer();
  26650. pluginWindow = 0;
  26651. pluginProc = 0;
  26652. #endif
  26653. }
  26654. }
  26655. #endif
  26656. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  26657. {
  26658. return plugin.dispatch (opcode, index, value, ptr, opt);
  26659. }
  26660. #if JUCE_WINDOWS
  26661. void checkPluginWindowSize() throw()
  26662. {
  26663. RECT r;
  26664. GetWindowRect (pluginHWND, &r);
  26665. const int w = r.right - r.left;
  26666. const int h = r.bottom - r.top;
  26667. if (isShowing() && w > 0 && h > 0
  26668. && (w != getWidth() || h != getHeight())
  26669. && ! pluginRefusesToResize)
  26670. {
  26671. setSize (w, h);
  26672. sizeCheckCount = 0;
  26673. }
  26674. }
  26675. // hooks to get keyboard events from VST windows..
  26676. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  26677. {
  26678. for (int i = activeVSTWindows.size(); --i >= 0;)
  26679. {
  26680. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  26681. if (w->pluginHWND == hW)
  26682. {
  26683. if (message == WM_CHAR
  26684. || message == WM_KEYDOWN
  26685. || message == WM_SYSKEYDOWN
  26686. || message == WM_KEYUP
  26687. || message == WM_SYSKEYUP
  26688. || message == WM_APPCOMMAND)
  26689. {
  26690. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  26691. message, wParam, lParam);
  26692. }
  26693. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  26694. (HWND) w->pluginHWND,
  26695. message,
  26696. wParam,
  26697. lParam);
  26698. }
  26699. }
  26700. return DefWindowProc (hW, message, wParam, lParam);
  26701. }
  26702. #endif
  26703. #if JUCE_LINUX
  26704. // overload mouse/keyboard events to forward them to the plugin's inner window..
  26705. void sendEventToChild (XEvent* event)
  26706. {
  26707. if (pluginProc != 0)
  26708. {
  26709. // if the plugin publishes an event procedure, pass the event directly..
  26710. pluginProc (event);
  26711. }
  26712. else if (pluginWindow != 0)
  26713. {
  26714. // if the plugin has a window, then send the event to the window so that
  26715. // its message thread will pick it up..
  26716. XSendEvent (display, pluginWindow, False, 0L, event);
  26717. XFlush (display);
  26718. }
  26719. }
  26720. void mouseEnter (const MouseEvent& e)
  26721. {
  26722. if (pluginWindow != 0)
  26723. {
  26724. XEvent ev;
  26725. zerostruct (ev);
  26726. ev.xcrossing.display = display;
  26727. ev.xcrossing.type = EnterNotify;
  26728. ev.xcrossing.window = pluginWindow;
  26729. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26730. ev.xcrossing.time = CurrentTime;
  26731. ev.xcrossing.x = e.x;
  26732. ev.xcrossing.y = e.y;
  26733. ev.xcrossing.x_root = e.getScreenX();
  26734. ev.xcrossing.y_root = e.getScreenY();
  26735. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26736. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26737. translateJuceToXCrossingModifiers (e, ev);
  26738. sendEventToChild (&ev);
  26739. }
  26740. }
  26741. void mouseExit (const MouseEvent& e)
  26742. {
  26743. if (pluginWindow != 0)
  26744. {
  26745. XEvent ev;
  26746. zerostruct (ev);
  26747. ev.xcrossing.display = display;
  26748. ev.xcrossing.type = LeaveNotify;
  26749. ev.xcrossing.window = pluginWindow;
  26750. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26751. ev.xcrossing.time = CurrentTime;
  26752. ev.xcrossing.x = e.x;
  26753. ev.xcrossing.y = e.y;
  26754. ev.xcrossing.x_root = e.getScreenX();
  26755. ev.xcrossing.y_root = e.getScreenY();
  26756. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26757. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26758. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  26759. translateJuceToXCrossingModifiers (e, ev);
  26760. sendEventToChild (&ev);
  26761. }
  26762. }
  26763. void mouseMove (const MouseEvent& e)
  26764. {
  26765. if (pluginWindow != 0)
  26766. {
  26767. XEvent ev;
  26768. zerostruct (ev);
  26769. ev.xmotion.display = display;
  26770. ev.xmotion.type = MotionNotify;
  26771. ev.xmotion.window = pluginWindow;
  26772. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26773. ev.xmotion.time = CurrentTime;
  26774. ev.xmotion.is_hint = NotifyNormal;
  26775. ev.xmotion.x = e.x;
  26776. ev.xmotion.y = e.y;
  26777. ev.xmotion.x_root = e.getScreenX();
  26778. ev.xmotion.y_root = e.getScreenY();
  26779. sendEventToChild (&ev);
  26780. }
  26781. }
  26782. void mouseDrag (const MouseEvent& e)
  26783. {
  26784. if (pluginWindow != 0)
  26785. {
  26786. XEvent ev;
  26787. zerostruct (ev);
  26788. ev.xmotion.display = display;
  26789. ev.xmotion.type = MotionNotify;
  26790. ev.xmotion.window = pluginWindow;
  26791. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26792. ev.xmotion.time = CurrentTime;
  26793. ev.xmotion.x = e.x ;
  26794. ev.xmotion.y = e.y;
  26795. ev.xmotion.x_root = e.getScreenX();
  26796. ev.xmotion.y_root = e.getScreenY();
  26797. ev.xmotion.is_hint = NotifyNormal;
  26798. translateJuceToXMotionModifiers (e, ev);
  26799. sendEventToChild (&ev);
  26800. }
  26801. }
  26802. void mouseUp (const MouseEvent& e)
  26803. {
  26804. if (pluginWindow != 0)
  26805. {
  26806. XEvent ev;
  26807. zerostruct (ev);
  26808. ev.xbutton.display = display;
  26809. ev.xbutton.type = ButtonRelease;
  26810. ev.xbutton.window = pluginWindow;
  26811. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26812. ev.xbutton.time = CurrentTime;
  26813. ev.xbutton.x = e.x;
  26814. ev.xbutton.y = e.y;
  26815. ev.xbutton.x_root = e.getScreenX();
  26816. ev.xbutton.y_root = e.getScreenY();
  26817. translateJuceToXButtonModifiers (e, ev);
  26818. sendEventToChild (&ev);
  26819. }
  26820. }
  26821. void mouseWheelMove (const MouseEvent& e,
  26822. float incrementX,
  26823. float incrementY)
  26824. {
  26825. if (pluginWindow != 0)
  26826. {
  26827. XEvent ev;
  26828. zerostruct (ev);
  26829. ev.xbutton.display = display;
  26830. ev.xbutton.type = ButtonPress;
  26831. ev.xbutton.window = pluginWindow;
  26832. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26833. ev.xbutton.time = CurrentTime;
  26834. ev.xbutton.x = e.x;
  26835. ev.xbutton.y = e.y;
  26836. ev.xbutton.x_root = e.getScreenX();
  26837. ev.xbutton.y_root = e.getScreenY();
  26838. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  26839. sendEventToChild (&ev);
  26840. // TODO - put a usleep here ?
  26841. ev.xbutton.type = ButtonRelease;
  26842. sendEventToChild (&ev);
  26843. }
  26844. }
  26845. #endif
  26846. #if JUCE_MAC
  26847. #if ! JUCE_SUPPORT_CARBON
  26848. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  26849. #endif
  26850. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26851. {
  26852. public:
  26853. InnerWrapperComponent (VSTPluginWindow* const owner_)
  26854. : owner (owner_),
  26855. alreadyInside (false)
  26856. {
  26857. }
  26858. ~InnerWrapperComponent()
  26859. {
  26860. deleteWindow();
  26861. }
  26862. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26863. {
  26864. owner->openPluginWindow (windowRef);
  26865. return 0;
  26866. }
  26867. void removeView (HIViewRef)
  26868. {
  26869. owner->dispatch (effEditClose, 0, 0, 0, 0);
  26870. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  26871. }
  26872. bool getEmbeddedViewSize (int& w, int& h)
  26873. {
  26874. ERect* rect = 0;
  26875. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  26876. w = rect->right - rect->left;
  26877. h = rect->bottom - rect->top;
  26878. return true;
  26879. }
  26880. void mouseDown (int x, int y)
  26881. {
  26882. if (! alreadyInside)
  26883. {
  26884. alreadyInside = true;
  26885. getTopLevelComponent()->toFront (true);
  26886. owner->dispatch (effEditMouse, x, y, 0, 0);
  26887. alreadyInside = false;
  26888. }
  26889. else
  26890. {
  26891. PostEvent (::mouseDown, 0);
  26892. }
  26893. }
  26894. void paint()
  26895. {
  26896. ComponentPeer* const peer = getPeer();
  26897. if (peer != 0)
  26898. {
  26899. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26900. ERect r;
  26901. r.left = pos.getX();
  26902. r.right = r.left + getWidth();
  26903. r.top = pos.getY();
  26904. r.bottom = r.top + getHeight();
  26905. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  26906. }
  26907. }
  26908. private:
  26909. VSTPluginWindow* const owner;
  26910. bool alreadyInside;
  26911. };
  26912. friend class InnerWrapperComponent;
  26913. ScopedPointer <InnerWrapperComponent> innerWrapper;
  26914. void resized()
  26915. {
  26916. innerWrapper->setSize (getWidth(), getHeight());
  26917. }
  26918. #endif
  26919. };
  26920. AudioProcessorEditor* VSTPluginInstance::createEditor()
  26921. {
  26922. if (hasEditor())
  26923. return new VSTPluginWindow (*this);
  26924. return 0;
  26925. }
  26926. void VSTPluginInstance::handleAsyncUpdate()
  26927. {
  26928. // indicates that something about the plugin has changed..
  26929. updateHostDisplay();
  26930. }
  26931. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  26932. {
  26933. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  26934. {
  26935. changeProgramName (getCurrentProgram(), prog->prgName);
  26936. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26937. setParameter (i, vst_swapFloat (prog->params[i]));
  26938. return true;
  26939. }
  26940. return false;
  26941. }
  26942. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  26943. const int dataSize)
  26944. {
  26945. if (dataSize < 28)
  26946. return false;
  26947. const fxSet* const set = (const fxSet*) data;
  26948. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  26949. || vst_swap (set->version) > fxbVersionNum)
  26950. return false;
  26951. if (vst_swap (set->fxMagic) == 'FxBk')
  26952. {
  26953. // bank of programs
  26954. if (vst_swap (set->numPrograms) >= 0)
  26955. {
  26956. const int oldProg = getCurrentProgram();
  26957. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  26958. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26959. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  26960. {
  26961. if (i != oldProg)
  26962. {
  26963. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  26964. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26965. return false;
  26966. if (vst_swap (set->numPrograms) > 0)
  26967. setCurrentProgram (i);
  26968. if (! restoreProgramSettings (prog))
  26969. return false;
  26970. }
  26971. }
  26972. if (vst_swap (set->numPrograms) > 0)
  26973. setCurrentProgram (oldProg);
  26974. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  26975. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26976. return false;
  26977. if (! restoreProgramSettings (prog))
  26978. return false;
  26979. }
  26980. }
  26981. else if (vst_swap (set->fxMagic) == 'FxCk')
  26982. {
  26983. // single program
  26984. const fxProgram* const prog = (const fxProgram*) data;
  26985. if (vst_swap (prog->chunkMagic) != 'CcnK')
  26986. return false;
  26987. changeProgramName (getCurrentProgram(), prog->prgName);
  26988. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26989. setParameter (i, vst_swapFloat (prog->params[i]));
  26990. }
  26991. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  26992. {
  26993. // non-preset chunk
  26994. const fxChunkSet* const cset = (const fxChunkSet*) data;
  26995. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  26996. return false;
  26997. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  26998. }
  26999. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27000. {
  27001. // preset chunk
  27002. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27003. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27004. return false;
  27005. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27006. changeProgramName (getCurrentProgram(), cset->name);
  27007. }
  27008. else
  27009. {
  27010. return false;
  27011. }
  27012. return true;
  27013. }
  27014. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  27015. {
  27016. const int numParams = getNumParameters();
  27017. prog->chunkMagic = vst_swap ('CcnK');
  27018. prog->byteSize = 0;
  27019. prog->fxMagic = vst_swap ('FxCk');
  27020. prog->version = vst_swap (fxbVersionNum);
  27021. prog->fxID = vst_swap (getUID());
  27022. prog->fxVersion = vst_swap (getVersionNumber());
  27023. prog->numParams = vst_swap (numParams);
  27024. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27025. for (int i = 0; i < numParams; ++i)
  27026. prog->params[i] = vst_swapFloat (getParameter (i));
  27027. }
  27028. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27029. {
  27030. const int numPrograms = getNumPrograms();
  27031. const int numParams = getNumParameters();
  27032. if (usesChunks())
  27033. {
  27034. if (isFXB)
  27035. {
  27036. MemoryBlock chunk;
  27037. getChunkData (chunk, false, maxSizeMB);
  27038. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27039. dest.setSize (totalLen, true);
  27040. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27041. set->chunkMagic = vst_swap ('CcnK');
  27042. set->byteSize = 0;
  27043. set->fxMagic = vst_swap ('FBCh');
  27044. set->version = vst_swap (fxbVersionNum);
  27045. set->fxID = vst_swap (getUID());
  27046. set->fxVersion = vst_swap (getVersionNumber());
  27047. set->numPrograms = vst_swap (numPrograms);
  27048. set->chunkSize = vst_swap ((long) chunk.getSize());
  27049. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27050. }
  27051. else
  27052. {
  27053. MemoryBlock chunk;
  27054. getChunkData (chunk, true, maxSizeMB);
  27055. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27056. dest.setSize (totalLen, true);
  27057. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27058. set->chunkMagic = vst_swap ('CcnK');
  27059. set->byteSize = 0;
  27060. set->fxMagic = vst_swap ('FPCh');
  27061. set->version = vst_swap (fxbVersionNum);
  27062. set->fxID = vst_swap (getUID());
  27063. set->fxVersion = vst_swap (getVersionNumber());
  27064. set->numPrograms = vst_swap (numPrograms);
  27065. set->chunkSize = vst_swap ((long) chunk.getSize());
  27066. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27067. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27068. }
  27069. }
  27070. else
  27071. {
  27072. if (isFXB)
  27073. {
  27074. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27075. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27076. dest.setSize (len, true);
  27077. fxSet* const set = (fxSet*) dest.getData();
  27078. set->chunkMagic = vst_swap ('CcnK');
  27079. set->byteSize = 0;
  27080. set->fxMagic = vst_swap ('FxBk');
  27081. set->version = vst_swap (fxbVersionNum);
  27082. set->fxID = vst_swap (getUID());
  27083. set->fxVersion = vst_swap (getVersionNumber());
  27084. set->numPrograms = vst_swap (numPrograms);
  27085. const int oldProgram = getCurrentProgram();
  27086. MemoryBlock oldSettings;
  27087. createTempParameterStore (oldSettings);
  27088. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27089. for (int i = 0; i < numPrograms; ++i)
  27090. {
  27091. if (i != oldProgram)
  27092. {
  27093. setCurrentProgram (i);
  27094. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27095. }
  27096. }
  27097. setCurrentProgram (oldProgram);
  27098. restoreFromTempParameterStore (oldSettings);
  27099. }
  27100. else
  27101. {
  27102. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27103. dest.setSize (totalLen, true);
  27104. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27105. }
  27106. }
  27107. return true;
  27108. }
  27109. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27110. {
  27111. if (usesChunks())
  27112. {
  27113. void* data = 0;
  27114. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27115. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27116. {
  27117. mb.setSize (bytes);
  27118. mb.copyFrom (data, 0, bytes);
  27119. }
  27120. }
  27121. }
  27122. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  27123. {
  27124. if (size > 0 && usesChunks())
  27125. {
  27126. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  27127. if (! isPreset)
  27128. updateStoredProgramNames();
  27129. }
  27130. }
  27131. void VSTPluginInstance::timerCallback()
  27132. {
  27133. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  27134. stopTimer();
  27135. }
  27136. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  27137. {
  27138. const ScopedLock sl (lock);
  27139. ++insideVSTCallback;
  27140. int result = 0;
  27141. try
  27142. {
  27143. if (effect != 0)
  27144. {
  27145. #if JUCE_MAC
  27146. if (module->resFileId != 0)
  27147. UseResFile (module->resFileId);
  27148. CGrafPtr oldPort;
  27149. if (getActiveEditor() != 0)
  27150. {
  27151. const Point<int> pos (getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), Point<int>()));
  27152. GetPort (&oldPort);
  27153. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  27154. SetOrigin (-pos.getX(), -pos.getY());
  27155. }
  27156. #endif
  27157. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  27158. #if JUCE_MAC
  27159. if (getActiveEditor() != 0)
  27160. SetPort (oldPort);
  27161. module->resFileId = CurResFile();
  27162. #endif
  27163. --insideVSTCallback;
  27164. return result;
  27165. }
  27166. }
  27167. catch (...)
  27168. {
  27169. }
  27170. --insideVSTCallback;
  27171. return result;
  27172. }
  27173. // handles non plugin-specific callbacks..
  27174. static const int defaultVSTSampleRateValue = 16384;
  27175. static const int defaultVSTBlockSizeValue = 512;
  27176. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27177. {
  27178. (void) index;
  27179. (void) value;
  27180. (void) opt;
  27181. switch (opcode)
  27182. {
  27183. case audioMasterCanDo:
  27184. {
  27185. static const char* canDos[] = { "supplyIdle",
  27186. "sendVstEvents",
  27187. "sendVstMidiEvent",
  27188. "sendVstTimeInfo",
  27189. "receiveVstEvents",
  27190. "receiveVstMidiEvent",
  27191. "supportShell",
  27192. "shellCategory" };
  27193. for (int i = 0; i < numElementsInArray (canDos); ++i)
  27194. if (strcmp (canDos[i], (const char*) ptr) == 0)
  27195. return 1;
  27196. return 0;
  27197. }
  27198. case audioMasterVersion:
  27199. return 0x2400;
  27200. case audioMasterCurrentId:
  27201. return shellUIDToCreate;
  27202. case audioMasterGetNumAutomatableParameters:
  27203. return 0;
  27204. case audioMasterGetAutomationState:
  27205. return 1;
  27206. case audioMasterGetVendorVersion:
  27207. return 0x0101;
  27208. case audioMasterGetVendorString:
  27209. case audioMasterGetProductString:
  27210. {
  27211. String hostName ("Juce VST Host");
  27212. if (JUCEApplication::getInstance() != 0)
  27213. hostName = JUCEApplication::getInstance()->getApplicationName();
  27214. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  27215. }
  27216. break;
  27217. case audioMasterGetSampleRate:
  27218. return (VstIntPtr) defaultVSTSampleRateValue;
  27219. case audioMasterGetBlockSize:
  27220. return (VstIntPtr) defaultVSTBlockSizeValue;
  27221. case audioMasterSetOutputSampleRate:
  27222. return 0;
  27223. default:
  27224. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  27225. break;
  27226. }
  27227. return 0;
  27228. }
  27229. // handles callbacks for a specific plugin
  27230. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27231. {
  27232. switch (opcode)
  27233. {
  27234. case audioMasterAutomate:
  27235. sendParamChangeMessageToListeners (index, opt);
  27236. break;
  27237. case audioMasterProcessEvents:
  27238. handleMidiFromPlugin ((const VstEvents*) ptr);
  27239. break;
  27240. case audioMasterGetTime:
  27241. #if JUCE_MSVC
  27242. #pragma warning (push)
  27243. #pragma warning (disable: 4311)
  27244. #endif
  27245. return (VstIntPtr) &vstHostTime;
  27246. #if JUCE_MSVC
  27247. #pragma warning (pop)
  27248. #endif
  27249. break;
  27250. case audioMasterIdle:
  27251. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  27252. {
  27253. ++insideVSTCallback;
  27254. #if JUCE_MAC
  27255. if (getActiveEditor() != 0)
  27256. dispatch (effEditIdle, 0, 0, 0, 0);
  27257. #endif
  27258. juce_callAnyTimersSynchronously();
  27259. handleUpdateNowIfNeeded();
  27260. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  27261. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  27262. --insideVSTCallback;
  27263. }
  27264. break;
  27265. case audioMasterUpdateDisplay:
  27266. triggerAsyncUpdate();
  27267. break;
  27268. case audioMasterTempoAt:
  27269. // returns (10000 * bpm)
  27270. break;
  27271. case audioMasterNeedIdle:
  27272. startTimer (50);
  27273. break;
  27274. case audioMasterSizeWindow:
  27275. if (getActiveEditor() != 0)
  27276. getActiveEditor()->setSize (index, value);
  27277. return 1;
  27278. case audioMasterGetSampleRate:
  27279. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  27280. case audioMasterGetBlockSize:
  27281. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  27282. case audioMasterWantMidi:
  27283. wantsMidiMessages = true;
  27284. break;
  27285. case audioMasterGetDirectory:
  27286. #if JUCE_MAC
  27287. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  27288. #else
  27289. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  27290. #endif
  27291. case audioMasterGetAutomationState:
  27292. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  27293. break;
  27294. // none of these are handled (yet)..
  27295. case audioMasterBeginEdit:
  27296. case audioMasterEndEdit:
  27297. case audioMasterSetTime:
  27298. case audioMasterPinConnected:
  27299. case audioMasterGetParameterQuantization:
  27300. case audioMasterIOChanged:
  27301. case audioMasterGetInputLatency:
  27302. case audioMasterGetOutputLatency:
  27303. case audioMasterGetPreviousPlug:
  27304. case audioMasterGetNextPlug:
  27305. case audioMasterWillReplaceOrAccumulate:
  27306. case audioMasterGetCurrentProcessLevel:
  27307. case audioMasterOfflineStart:
  27308. case audioMasterOfflineRead:
  27309. case audioMasterOfflineWrite:
  27310. case audioMasterOfflineGetCurrentPass:
  27311. case audioMasterOfflineGetCurrentMetaPass:
  27312. case audioMasterVendorSpecific:
  27313. case audioMasterSetIcon:
  27314. case audioMasterGetLanguage:
  27315. case audioMasterOpenWindow:
  27316. case audioMasterCloseWindow:
  27317. break;
  27318. default:
  27319. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27320. }
  27321. return 0;
  27322. }
  27323. // entry point for all callbacks from the plugin
  27324. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  27325. {
  27326. try
  27327. {
  27328. if (effect != 0 && effect->resvd2 != 0)
  27329. {
  27330. return ((VSTPluginInstance*)(effect->resvd2))
  27331. ->handleCallback (opcode, index, value, ptr, opt);
  27332. }
  27333. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27334. }
  27335. catch (...)
  27336. {
  27337. return 0;
  27338. }
  27339. }
  27340. const String VSTPluginInstance::getVersion() const throw()
  27341. {
  27342. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  27343. String s;
  27344. if (v == 0 || v == -1)
  27345. v = getVersionNumber();
  27346. if (v != 0)
  27347. {
  27348. int versionBits[4];
  27349. int n = 0;
  27350. while (v != 0)
  27351. {
  27352. versionBits [n++] = (v & 0xff);
  27353. v >>= 8;
  27354. }
  27355. s << 'V';
  27356. while (n > 0)
  27357. {
  27358. s << versionBits [--n];
  27359. if (n > 0)
  27360. s << '.';
  27361. }
  27362. }
  27363. return s;
  27364. }
  27365. int VSTPluginInstance::getUID() const throw()
  27366. {
  27367. int uid = effect != 0 ? effect->uniqueID : 0;
  27368. if (uid == 0)
  27369. uid = module->file.hashCode();
  27370. return uid;
  27371. }
  27372. const String VSTPluginInstance::getCategory() const throw()
  27373. {
  27374. const char* result = 0;
  27375. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  27376. {
  27377. case kPlugCategEffect:
  27378. result = "Effect";
  27379. break;
  27380. case kPlugCategSynth:
  27381. result = "Synth";
  27382. break;
  27383. case kPlugCategAnalysis:
  27384. result = "Anaylsis";
  27385. break;
  27386. case kPlugCategMastering:
  27387. result = "Mastering";
  27388. break;
  27389. case kPlugCategSpacializer:
  27390. result = "Spacial";
  27391. break;
  27392. case kPlugCategRoomFx:
  27393. result = "Reverb";
  27394. break;
  27395. case kPlugSurroundFx:
  27396. result = "Surround";
  27397. break;
  27398. case kPlugCategRestoration:
  27399. result = "Restoration";
  27400. break;
  27401. case kPlugCategGenerator:
  27402. result = "Tone generation";
  27403. break;
  27404. default:
  27405. break;
  27406. }
  27407. return result;
  27408. }
  27409. float VSTPluginInstance::getParameter (int index)
  27410. {
  27411. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27412. {
  27413. try
  27414. {
  27415. const ScopedLock sl (lock);
  27416. return effect->getParameter (effect, index);
  27417. }
  27418. catch (...)
  27419. {
  27420. }
  27421. }
  27422. return 0.0f;
  27423. }
  27424. void VSTPluginInstance::setParameter (int index, float newValue)
  27425. {
  27426. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27427. {
  27428. try
  27429. {
  27430. const ScopedLock sl (lock);
  27431. if (effect->getParameter (effect, index) != newValue)
  27432. effect->setParameter (effect, index, newValue);
  27433. }
  27434. catch (...)
  27435. {
  27436. }
  27437. }
  27438. }
  27439. const String VSTPluginInstance::getParameterName (int index)
  27440. {
  27441. if (effect != 0)
  27442. {
  27443. jassert (index >= 0 && index < effect->numParams);
  27444. char nm [256];
  27445. zerostruct (nm);
  27446. dispatch (effGetParamName, index, 0, nm, 0);
  27447. return String (nm).trim();
  27448. }
  27449. return String::empty;
  27450. }
  27451. const String VSTPluginInstance::getParameterLabel (int index) const
  27452. {
  27453. if (effect != 0)
  27454. {
  27455. jassert (index >= 0 && index < effect->numParams);
  27456. char nm [256];
  27457. zerostruct (nm);
  27458. dispatch (effGetParamLabel, index, 0, nm, 0);
  27459. return String (nm).trim();
  27460. }
  27461. return String::empty;
  27462. }
  27463. const String VSTPluginInstance::getParameterText (int index)
  27464. {
  27465. if (effect != 0)
  27466. {
  27467. jassert (index >= 0 && index < effect->numParams);
  27468. char nm [256];
  27469. zerostruct (nm);
  27470. dispatch (effGetParamDisplay, index, 0, nm, 0);
  27471. return String (nm).trim();
  27472. }
  27473. return String::empty;
  27474. }
  27475. bool VSTPluginInstance::isParameterAutomatable (int index) const
  27476. {
  27477. if (effect != 0)
  27478. {
  27479. jassert (index >= 0 && index < effect->numParams);
  27480. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  27481. }
  27482. return false;
  27483. }
  27484. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  27485. {
  27486. dest.setSize (64 + 4 * getNumParameters());
  27487. dest.fillWith (0);
  27488. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  27489. float* const p = (float*) (((char*) dest.getData()) + 64);
  27490. for (int i = 0; i < getNumParameters(); ++i)
  27491. p[i] = getParameter(i);
  27492. }
  27493. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  27494. {
  27495. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  27496. float* p = (float*) (((char*) m.getData()) + 64);
  27497. for (int i = 0; i < getNumParameters(); ++i)
  27498. setParameter (i, p[i]);
  27499. }
  27500. void VSTPluginInstance::setCurrentProgram (int newIndex)
  27501. {
  27502. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  27503. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  27504. }
  27505. const String VSTPluginInstance::getProgramName (int index)
  27506. {
  27507. if (index == getCurrentProgram())
  27508. {
  27509. return getCurrentProgramName();
  27510. }
  27511. else if (effect != 0)
  27512. {
  27513. char nm [256];
  27514. zerostruct (nm);
  27515. if (dispatch (effGetProgramNameIndexed,
  27516. jlimit (0, getNumPrograms(), index),
  27517. -1, nm, 0) != 0)
  27518. {
  27519. return String (nm).trim();
  27520. }
  27521. }
  27522. return programNames [index];
  27523. }
  27524. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  27525. {
  27526. if (index == getCurrentProgram())
  27527. {
  27528. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  27529. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  27530. }
  27531. else
  27532. {
  27533. jassertfalse; // xxx not implemented!
  27534. }
  27535. }
  27536. void VSTPluginInstance::updateStoredProgramNames()
  27537. {
  27538. if (effect != 0 && getNumPrograms() > 0)
  27539. {
  27540. char nm [256];
  27541. zerostruct (nm);
  27542. // only do this if the plugin can't use indexed names..
  27543. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  27544. {
  27545. const int oldProgram = getCurrentProgram();
  27546. MemoryBlock oldSettings;
  27547. createTempParameterStore (oldSettings);
  27548. for (int i = 0; i < getNumPrograms(); ++i)
  27549. {
  27550. setCurrentProgram (i);
  27551. getCurrentProgramName(); // (this updates the list)
  27552. }
  27553. setCurrentProgram (oldProgram);
  27554. restoreFromTempParameterStore (oldSettings);
  27555. }
  27556. }
  27557. }
  27558. const String VSTPluginInstance::getCurrentProgramName()
  27559. {
  27560. if (effect != 0)
  27561. {
  27562. char nm [256];
  27563. zerostruct (nm);
  27564. dispatch (effGetProgramName, 0, 0, nm, 0);
  27565. const int index = getCurrentProgram();
  27566. if (programNames[index].isEmpty())
  27567. {
  27568. while (programNames.size() < index)
  27569. programNames.add (String::empty);
  27570. programNames.set (index, String (nm).trim());
  27571. }
  27572. return String (nm).trim();
  27573. }
  27574. return String::empty;
  27575. }
  27576. const String VSTPluginInstance::getInputChannelName (const int index) const
  27577. {
  27578. if (index >= 0 && index < getNumInputChannels())
  27579. {
  27580. VstPinProperties pinProps;
  27581. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27582. return String (pinProps.label, sizeof (pinProps.label));
  27583. }
  27584. return String::empty;
  27585. }
  27586. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  27587. {
  27588. if (index < 0 || index >= getNumInputChannels())
  27589. return false;
  27590. VstPinProperties pinProps;
  27591. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27592. return (pinProps.flags & kVstPinIsStereo) != 0;
  27593. return true;
  27594. }
  27595. const String VSTPluginInstance::getOutputChannelName (const int index) const
  27596. {
  27597. if (index >= 0 && index < getNumOutputChannels())
  27598. {
  27599. VstPinProperties pinProps;
  27600. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27601. return String (pinProps.label, sizeof (pinProps.label));
  27602. }
  27603. return String::empty;
  27604. }
  27605. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  27606. {
  27607. if (index < 0 || index >= getNumOutputChannels())
  27608. return false;
  27609. VstPinProperties pinProps;
  27610. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27611. return (pinProps.flags & kVstPinIsStereo) != 0;
  27612. return true;
  27613. }
  27614. void VSTPluginInstance::setPower (const bool on)
  27615. {
  27616. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  27617. isPowerOn = on;
  27618. }
  27619. const int defaultMaxSizeMB = 64;
  27620. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  27621. {
  27622. saveToFXBFile (destData, true, defaultMaxSizeMB);
  27623. }
  27624. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  27625. {
  27626. saveToFXBFile (destData, false, defaultMaxSizeMB);
  27627. }
  27628. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  27629. {
  27630. loadFromFXBFile (data, sizeInBytes);
  27631. }
  27632. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27633. {
  27634. loadFromFXBFile (data, sizeInBytes);
  27635. }
  27636. VSTPluginFormat::VSTPluginFormat()
  27637. {
  27638. }
  27639. VSTPluginFormat::~VSTPluginFormat()
  27640. {
  27641. }
  27642. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  27643. const String& fileOrIdentifier)
  27644. {
  27645. if (! fileMightContainThisPluginType (fileOrIdentifier))
  27646. return;
  27647. PluginDescription desc;
  27648. desc.fileOrIdentifier = fileOrIdentifier;
  27649. desc.uid = 0;
  27650. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  27651. if (instance == 0)
  27652. return;
  27653. try
  27654. {
  27655. #if JUCE_MAC
  27656. if (instance->module->resFileId != 0)
  27657. UseResFile (instance->module->resFileId);
  27658. #endif
  27659. instance->fillInPluginDescription (desc);
  27660. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  27661. if (category != kPlugCategShell)
  27662. {
  27663. // Normal plugin...
  27664. results.add (new PluginDescription (desc));
  27665. ++insideVSTCallback;
  27666. instance->dispatch (effOpen, 0, 0, 0, 0);
  27667. --insideVSTCallback;
  27668. }
  27669. else
  27670. {
  27671. // It's a shell plugin, so iterate all the subtypes...
  27672. char shellEffectName [64];
  27673. for (;;)
  27674. {
  27675. zerostruct (shellEffectName);
  27676. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  27677. if (uid == 0)
  27678. {
  27679. break;
  27680. }
  27681. else
  27682. {
  27683. desc.uid = uid;
  27684. desc.name = shellEffectName;
  27685. bool alreadyThere = false;
  27686. for (int i = results.size(); --i >= 0;)
  27687. {
  27688. PluginDescription* const d = results.getUnchecked(i);
  27689. if (d->isDuplicateOf (desc))
  27690. {
  27691. alreadyThere = true;
  27692. break;
  27693. }
  27694. }
  27695. if (! alreadyThere)
  27696. results.add (new PluginDescription (desc));
  27697. }
  27698. }
  27699. }
  27700. }
  27701. catch (...)
  27702. {
  27703. // crashed while loading...
  27704. }
  27705. }
  27706. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  27707. {
  27708. ScopedPointer <VSTPluginInstance> result;
  27709. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  27710. {
  27711. File file (desc.fileOrIdentifier);
  27712. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  27713. file.getParentDirectory().setAsCurrentWorkingDirectory();
  27714. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  27715. if (module != 0)
  27716. {
  27717. shellUIDToCreate = desc.uid;
  27718. result = new VSTPluginInstance (module);
  27719. if (result->effect != 0)
  27720. {
  27721. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  27722. result->initialise();
  27723. }
  27724. else
  27725. {
  27726. result = 0;
  27727. }
  27728. }
  27729. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  27730. }
  27731. return result.release();
  27732. }
  27733. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  27734. {
  27735. const File f (fileOrIdentifier);
  27736. #if JUCE_MAC
  27737. if (f.isDirectory() && f.hasFileExtension (".vst"))
  27738. return true;
  27739. #if JUCE_PPC
  27740. FSRef fileRef;
  27741. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  27742. {
  27743. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  27744. if (resFileId != -1)
  27745. {
  27746. const int numEffects = Count1Resources ('aEff');
  27747. CloseResFile (resFileId);
  27748. if (numEffects > 0)
  27749. return true;
  27750. }
  27751. }
  27752. #endif
  27753. return false;
  27754. #elif JUCE_WINDOWS
  27755. return f.existsAsFile()
  27756. && f.hasFileExtension (".dll");
  27757. #elif JUCE_LINUX
  27758. return f.existsAsFile()
  27759. && f.hasFileExtension (".so");
  27760. #endif
  27761. }
  27762. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  27763. {
  27764. return fileOrIdentifier;
  27765. }
  27766. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  27767. {
  27768. return File (desc.fileOrIdentifier).exists();
  27769. }
  27770. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  27771. {
  27772. StringArray results;
  27773. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  27774. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  27775. return results;
  27776. }
  27777. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  27778. {
  27779. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  27780. // .component or .vst directories.
  27781. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  27782. while (iter.next())
  27783. {
  27784. const File f (iter.getFile());
  27785. bool isPlugin = false;
  27786. if (fileMightContainThisPluginType (f.getFullPathName()))
  27787. {
  27788. isPlugin = true;
  27789. results.add (f.getFullPathName());
  27790. }
  27791. if (recursive && (! isPlugin) && f.isDirectory())
  27792. recursiveFileSearch (results, f, true);
  27793. }
  27794. }
  27795. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  27796. {
  27797. #if JUCE_MAC
  27798. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  27799. #elif JUCE_WINDOWS
  27800. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  27801. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  27802. #elif JUCE_LINUX
  27803. return FileSearchPath ("/usr/lib/vst");
  27804. #endif
  27805. }
  27806. END_JUCE_NAMESPACE
  27807. #endif
  27808. #undef log
  27809. #endif
  27810. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  27811. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  27812. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  27813. BEGIN_JUCE_NAMESPACE
  27814. AudioProcessor::AudioProcessor()
  27815. : playHead (0),
  27816. activeEditor (0),
  27817. sampleRate (0),
  27818. blockSize (0),
  27819. numInputChannels (0),
  27820. numOutputChannels (0),
  27821. latencySamples (0),
  27822. suspended (false),
  27823. nonRealtime (false)
  27824. {
  27825. }
  27826. AudioProcessor::~AudioProcessor()
  27827. {
  27828. // ooh, nasty - the editor should have been deleted before the filter
  27829. // that it refers to is deleted..
  27830. jassert (activeEditor == 0);
  27831. #if JUCE_DEBUG
  27832. // This will fail if you've called beginParameterChangeGesture() for one
  27833. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  27834. jassert (changingParams.countNumberOfSetBits() == 0);
  27835. #endif
  27836. }
  27837. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  27838. {
  27839. playHead = newPlayHead;
  27840. }
  27841. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  27842. {
  27843. const ScopedLock sl (listenerLock);
  27844. listeners.addIfNotAlreadyThere (newListener);
  27845. }
  27846. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  27847. {
  27848. const ScopedLock sl (listenerLock);
  27849. listeners.removeValue (listenerToRemove);
  27850. }
  27851. void AudioProcessor::setPlayConfigDetails (const int numIns,
  27852. const int numOuts,
  27853. const double sampleRate_,
  27854. const int blockSize_) throw()
  27855. {
  27856. numInputChannels = numIns;
  27857. numOutputChannels = numOuts;
  27858. sampleRate = sampleRate_;
  27859. blockSize = blockSize_;
  27860. }
  27861. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  27862. {
  27863. nonRealtime = nonRealtime_;
  27864. }
  27865. void AudioProcessor::setLatencySamples (const int newLatency)
  27866. {
  27867. if (latencySamples != newLatency)
  27868. {
  27869. latencySamples = newLatency;
  27870. updateHostDisplay();
  27871. }
  27872. }
  27873. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  27874. const float newValue)
  27875. {
  27876. setParameter (parameterIndex, newValue);
  27877. sendParamChangeMessageToListeners (parameterIndex, newValue);
  27878. }
  27879. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  27880. {
  27881. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27882. for (int i = listeners.size(); --i >= 0;)
  27883. {
  27884. AudioProcessorListener* l;
  27885. {
  27886. const ScopedLock sl (listenerLock);
  27887. l = listeners [i];
  27888. }
  27889. if (l != 0)
  27890. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  27891. }
  27892. }
  27893. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  27894. {
  27895. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27896. #if JUCE_DEBUG
  27897. // This means you've called beginParameterChangeGesture twice in succession without a matching
  27898. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  27899. jassert (! changingParams [parameterIndex]);
  27900. changingParams.setBit (parameterIndex);
  27901. #endif
  27902. for (int i = listeners.size(); --i >= 0;)
  27903. {
  27904. AudioProcessorListener* l;
  27905. {
  27906. const ScopedLock sl (listenerLock);
  27907. l = listeners [i];
  27908. }
  27909. if (l != 0)
  27910. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  27911. }
  27912. }
  27913. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  27914. {
  27915. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27916. #if JUCE_DEBUG
  27917. // This means you've called endParameterChangeGesture without having previously called
  27918. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  27919. // calls matched correctly.
  27920. jassert (changingParams [parameterIndex]);
  27921. changingParams.clearBit (parameterIndex);
  27922. #endif
  27923. for (int i = listeners.size(); --i >= 0;)
  27924. {
  27925. AudioProcessorListener* l;
  27926. {
  27927. const ScopedLock sl (listenerLock);
  27928. l = listeners [i];
  27929. }
  27930. if (l != 0)
  27931. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  27932. }
  27933. }
  27934. void AudioProcessor::updateHostDisplay()
  27935. {
  27936. for (int i = listeners.size(); --i >= 0;)
  27937. {
  27938. AudioProcessorListener* l;
  27939. {
  27940. const ScopedLock sl (listenerLock);
  27941. l = listeners [i];
  27942. }
  27943. if (l != 0)
  27944. l->audioProcessorChanged (this);
  27945. }
  27946. }
  27947. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  27948. {
  27949. return true;
  27950. }
  27951. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  27952. {
  27953. return false;
  27954. }
  27955. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  27956. {
  27957. const ScopedLock sl (callbackLock);
  27958. suspended = shouldBeSuspended;
  27959. }
  27960. void AudioProcessor::reset()
  27961. {
  27962. }
  27963. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  27964. {
  27965. const ScopedLock sl (callbackLock);
  27966. jassert (activeEditor == editor);
  27967. if (activeEditor == editor)
  27968. activeEditor = 0;
  27969. }
  27970. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  27971. {
  27972. if (activeEditor != 0)
  27973. return activeEditor;
  27974. AudioProcessorEditor* const ed = createEditor();
  27975. if (ed != 0)
  27976. {
  27977. // you must give your editor comp a size before returning it..
  27978. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  27979. const ScopedLock sl (callbackLock);
  27980. activeEditor = ed;
  27981. }
  27982. return ed;
  27983. }
  27984. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  27985. {
  27986. getStateInformation (destData);
  27987. }
  27988. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27989. {
  27990. setStateInformation (data, sizeInBytes);
  27991. }
  27992. // magic number to identify memory blocks that we've stored as XML
  27993. const uint32 magicXmlNumber = 0x21324356;
  27994. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  27995. JUCE_NAMESPACE::MemoryBlock& destData)
  27996. {
  27997. const String xmlString (xml.createDocument (String::empty, true, false));
  27998. const int stringLength = xmlString.getNumBytesAsUTF8();
  27999. destData.setSize (stringLength + 10);
  28000. char* const d = (char*) destData.getData();
  28001. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28002. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28003. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28004. }
  28005. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28006. const int sizeInBytes)
  28007. {
  28008. if (sizeInBytes > 8
  28009. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28010. {
  28011. const int stringLength = (int) ByteOrder::littleEndianInt (((const char*) data) + 4);
  28012. if (stringLength > 0)
  28013. {
  28014. XmlDocument doc (String::fromUTF8 (((const char*) data) + 8,
  28015. jmin ((sizeInBytes - 8), stringLength)));
  28016. return doc.getDocumentElement();
  28017. }
  28018. }
  28019. return 0;
  28020. }
  28021. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  28022. {
  28023. }
  28024. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  28025. {
  28026. }
  28027. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28028. {
  28029. return timeInSeconds == other.timeInSeconds
  28030. && ppqPosition == other.ppqPosition
  28031. && editOriginTime == other.editOriginTime
  28032. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28033. && frameRate == other.frameRate
  28034. && isPlaying == other.isPlaying
  28035. && isRecording == other.isRecording
  28036. && bpm == other.bpm
  28037. && timeSigNumerator == other.timeSigNumerator
  28038. && timeSigDenominator == other.timeSigDenominator;
  28039. }
  28040. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28041. {
  28042. return ! operator== (other);
  28043. }
  28044. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28045. {
  28046. zerostruct (*this);
  28047. timeSigNumerator = 4;
  28048. timeSigDenominator = 4;
  28049. bpm = 120;
  28050. }
  28051. END_JUCE_NAMESPACE
  28052. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28053. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28054. BEGIN_JUCE_NAMESPACE
  28055. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28056. : owner (owner_)
  28057. {
  28058. // the filter must be valid..
  28059. jassert (owner != 0);
  28060. }
  28061. AudioProcessorEditor::~AudioProcessorEditor()
  28062. {
  28063. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28064. // filter for some reason..
  28065. jassert (owner->getActiveEditor() != this);
  28066. }
  28067. END_JUCE_NAMESPACE
  28068. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28069. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28070. BEGIN_JUCE_NAMESPACE
  28071. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28072. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28073. : id (id_),
  28074. processor (processor_),
  28075. isPrepared (false)
  28076. {
  28077. jassert (processor_ != 0);
  28078. }
  28079. AudioProcessorGraph::Node::~Node()
  28080. {
  28081. delete processor;
  28082. }
  28083. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28084. AudioProcessorGraph* const graph)
  28085. {
  28086. if (! isPrepared)
  28087. {
  28088. isPrepared = true;
  28089. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28090. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  28091. if (ioProc != 0)
  28092. ioProc->setParentGraph (graph);
  28093. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28094. processor->getNumOutputChannels(),
  28095. sampleRate, blockSize);
  28096. processor->prepareToPlay (sampleRate, blockSize);
  28097. }
  28098. }
  28099. void AudioProcessorGraph::Node::unprepare()
  28100. {
  28101. if (isPrepared)
  28102. {
  28103. isPrepared = false;
  28104. processor->releaseResources();
  28105. }
  28106. }
  28107. AudioProcessorGraph::AudioProcessorGraph()
  28108. : lastNodeId (0),
  28109. renderingBuffers (1, 1),
  28110. currentAudioOutputBuffer (1, 1)
  28111. {
  28112. }
  28113. AudioProcessorGraph::~AudioProcessorGraph()
  28114. {
  28115. clearRenderingSequence();
  28116. clear();
  28117. }
  28118. const String AudioProcessorGraph::getName() const
  28119. {
  28120. return "Audio Graph";
  28121. }
  28122. void AudioProcessorGraph::clear()
  28123. {
  28124. nodes.clear();
  28125. connections.clear();
  28126. triggerAsyncUpdate();
  28127. }
  28128. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28129. {
  28130. for (int i = nodes.size(); --i >= 0;)
  28131. if (nodes.getUnchecked(i)->id == nodeId)
  28132. return nodes.getUnchecked(i);
  28133. return 0;
  28134. }
  28135. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28136. uint32 nodeId)
  28137. {
  28138. if (newProcessor == 0)
  28139. {
  28140. jassertfalse;
  28141. return 0;
  28142. }
  28143. if (nodeId == 0)
  28144. {
  28145. nodeId = ++lastNodeId;
  28146. }
  28147. else
  28148. {
  28149. // you can't add a node with an id that already exists in the graph..
  28150. jassert (getNodeForId (nodeId) == 0);
  28151. removeNode (nodeId);
  28152. }
  28153. lastNodeId = nodeId;
  28154. Node* const n = new Node (nodeId, newProcessor);
  28155. nodes.add (n);
  28156. triggerAsyncUpdate();
  28157. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28158. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  28159. if (ioProc != 0)
  28160. ioProc->setParentGraph (this);
  28161. return n;
  28162. }
  28163. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  28164. {
  28165. disconnectNode (nodeId);
  28166. for (int i = nodes.size(); --i >= 0;)
  28167. {
  28168. if (nodes.getUnchecked(i)->id == nodeId)
  28169. {
  28170. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28171. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  28172. if (ioProc != 0)
  28173. ioProc->setParentGraph (0);
  28174. nodes.remove (i);
  28175. triggerAsyncUpdate();
  28176. return true;
  28177. }
  28178. }
  28179. return false;
  28180. }
  28181. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  28182. const int sourceChannelIndex,
  28183. const uint32 destNodeId,
  28184. const int destChannelIndex) const
  28185. {
  28186. for (int i = connections.size(); --i >= 0;)
  28187. {
  28188. const Connection* const c = connections.getUnchecked(i);
  28189. if (c->sourceNodeId == sourceNodeId
  28190. && c->destNodeId == destNodeId
  28191. && c->sourceChannelIndex == sourceChannelIndex
  28192. && c->destChannelIndex == destChannelIndex)
  28193. {
  28194. return c;
  28195. }
  28196. }
  28197. return 0;
  28198. }
  28199. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  28200. const uint32 possibleDestNodeId) const
  28201. {
  28202. for (int i = connections.size(); --i >= 0;)
  28203. {
  28204. const Connection* const c = connections.getUnchecked(i);
  28205. if (c->sourceNodeId == possibleSourceNodeId
  28206. && c->destNodeId == possibleDestNodeId)
  28207. {
  28208. return true;
  28209. }
  28210. }
  28211. return false;
  28212. }
  28213. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  28214. const int sourceChannelIndex,
  28215. const uint32 destNodeId,
  28216. const int destChannelIndex) const
  28217. {
  28218. if (sourceChannelIndex < 0
  28219. || destChannelIndex < 0
  28220. || sourceNodeId == destNodeId
  28221. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  28222. return false;
  28223. const Node* const source = getNodeForId (sourceNodeId);
  28224. if (source == 0
  28225. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  28226. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  28227. return false;
  28228. const Node* const dest = getNodeForId (destNodeId);
  28229. if (dest == 0
  28230. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  28231. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  28232. return false;
  28233. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  28234. destNodeId, destChannelIndex) == 0;
  28235. }
  28236. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  28237. const int sourceChannelIndex,
  28238. const uint32 destNodeId,
  28239. const int destChannelIndex)
  28240. {
  28241. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  28242. return false;
  28243. Connection* const c = new Connection();
  28244. c->sourceNodeId = sourceNodeId;
  28245. c->sourceChannelIndex = sourceChannelIndex;
  28246. c->destNodeId = destNodeId;
  28247. c->destChannelIndex = destChannelIndex;
  28248. connections.add (c);
  28249. triggerAsyncUpdate();
  28250. return true;
  28251. }
  28252. void AudioProcessorGraph::removeConnection (const int index)
  28253. {
  28254. connections.remove (index);
  28255. triggerAsyncUpdate();
  28256. }
  28257. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  28258. const uint32 destNodeId, const int destChannelIndex)
  28259. {
  28260. bool doneAnything = false;
  28261. for (int i = connections.size(); --i >= 0;)
  28262. {
  28263. const Connection* const c = connections.getUnchecked(i);
  28264. if (c->sourceNodeId == sourceNodeId
  28265. && c->destNodeId == destNodeId
  28266. && c->sourceChannelIndex == sourceChannelIndex
  28267. && c->destChannelIndex == destChannelIndex)
  28268. {
  28269. removeConnection (i);
  28270. doneAnything = true;
  28271. triggerAsyncUpdate();
  28272. }
  28273. }
  28274. return doneAnything;
  28275. }
  28276. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  28277. {
  28278. bool doneAnything = false;
  28279. for (int i = connections.size(); --i >= 0;)
  28280. {
  28281. const Connection* const c = connections.getUnchecked(i);
  28282. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  28283. {
  28284. removeConnection (i);
  28285. doneAnything = true;
  28286. triggerAsyncUpdate();
  28287. }
  28288. }
  28289. return doneAnything;
  28290. }
  28291. bool AudioProcessorGraph::removeIllegalConnections()
  28292. {
  28293. bool doneAnything = false;
  28294. for (int i = connections.size(); --i >= 0;)
  28295. {
  28296. const Connection* const c = connections.getUnchecked(i);
  28297. const Node* const source = getNodeForId (c->sourceNodeId);
  28298. const Node* const dest = getNodeForId (c->destNodeId);
  28299. if (source == 0 || dest == 0
  28300. || (c->sourceChannelIndex != midiChannelIndex
  28301. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  28302. || (c->sourceChannelIndex == midiChannelIndex
  28303. && ! source->processor->producesMidi())
  28304. || (c->destChannelIndex != midiChannelIndex
  28305. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  28306. || (c->destChannelIndex == midiChannelIndex
  28307. && ! dest->processor->acceptsMidi()))
  28308. {
  28309. removeConnection (i);
  28310. doneAnything = true;
  28311. triggerAsyncUpdate();
  28312. }
  28313. }
  28314. return doneAnything;
  28315. }
  28316. namespace GraphRenderingOps
  28317. {
  28318. class AudioGraphRenderingOp
  28319. {
  28320. public:
  28321. AudioGraphRenderingOp() {}
  28322. virtual ~AudioGraphRenderingOp() {}
  28323. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  28324. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  28325. const int numSamples) = 0;
  28326. juce_UseDebuggingNewOperator
  28327. };
  28328. class ClearChannelOp : public AudioGraphRenderingOp
  28329. {
  28330. public:
  28331. ClearChannelOp (const int channelNum_)
  28332. : channelNum (channelNum_)
  28333. {}
  28334. ~ClearChannelOp() {}
  28335. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28336. {
  28337. sharedBufferChans.clear (channelNum, 0, numSamples);
  28338. }
  28339. private:
  28340. const int channelNum;
  28341. ClearChannelOp (const ClearChannelOp&);
  28342. ClearChannelOp& operator= (const ClearChannelOp&);
  28343. };
  28344. class CopyChannelOp : public AudioGraphRenderingOp
  28345. {
  28346. public:
  28347. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28348. : srcChannelNum (srcChannelNum_),
  28349. dstChannelNum (dstChannelNum_)
  28350. {}
  28351. ~CopyChannelOp() {}
  28352. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28353. {
  28354. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28355. }
  28356. private:
  28357. const int srcChannelNum, dstChannelNum;
  28358. CopyChannelOp (const CopyChannelOp&);
  28359. CopyChannelOp& operator= (const CopyChannelOp&);
  28360. };
  28361. class AddChannelOp : public AudioGraphRenderingOp
  28362. {
  28363. public:
  28364. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28365. : srcChannelNum (srcChannelNum_),
  28366. dstChannelNum (dstChannelNum_)
  28367. {}
  28368. ~AddChannelOp() {}
  28369. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28370. {
  28371. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28372. }
  28373. private:
  28374. const int srcChannelNum, dstChannelNum;
  28375. AddChannelOp (const AddChannelOp&);
  28376. AddChannelOp& operator= (const AddChannelOp&);
  28377. };
  28378. class ClearMidiBufferOp : public AudioGraphRenderingOp
  28379. {
  28380. public:
  28381. ClearMidiBufferOp (const int bufferNum_)
  28382. : bufferNum (bufferNum_)
  28383. {}
  28384. ~ClearMidiBufferOp() {}
  28385. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28386. {
  28387. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  28388. }
  28389. private:
  28390. const int bufferNum;
  28391. ClearMidiBufferOp (const ClearMidiBufferOp&);
  28392. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  28393. };
  28394. class CopyMidiBufferOp : public AudioGraphRenderingOp
  28395. {
  28396. public:
  28397. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28398. : srcBufferNum (srcBufferNum_),
  28399. dstBufferNum (dstBufferNum_)
  28400. {}
  28401. ~CopyMidiBufferOp() {}
  28402. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28403. {
  28404. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  28405. }
  28406. private:
  28407. const int srcBufferNum, dstBufferNum;
  28408. CopyMidiBufferOp (const CopyMidiBufferOp&);
  28409. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  28410. };
  28411. class AddMidiBufferOp : public AudioGraphRenderingOp
  28412. {
  28413. public:
  28414. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28415. : srcBufferNum (srcBufferNum_),
  28416. dstBufferNum (dstBufferNum_)
  28417. {}
  28418. ~AddMidiBufferOp() {}
  28419. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28420. {
  28421. sharedMidiBuffers.getUnchecked (dstBufferNum)
  28422. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  28423. }
  28424. private:
  28425. const int srcBufferNum, dstBufferNum;
  28426. AddMidiBufferOp (const AddMidiBufferOp&);
  28427. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  28428. };
  28429. class ProcessBufferOp : public AudioGraphRenderingOp
  28430. {
  28431. public:
  28432. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  28433. const Array <int>& audioChannelsToUse_,
  28434. const int totalChans_,
  28435. const int midiBufferToUse_)
  28436. : node (node_),
  28437. processor (node_->processor),
  28438. audioChannelsToUse (audioChannelsToUse_),
  28439. totalChans (jmax (1, totalChans_)),
  28440. midiBufferToUse (midiBufferToUse_)
  28441. {
  28442. channels.calloc (totalChans);
  28443. while (audioChannelsToUse.size() < totalChans)
  28444. audioChannelsToUse.add (0);
  28445. }
  28446. ~ProcessBufferOp()
  28447. {
  28448. }
  28449. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28450. {
  28451. for (int i = totalChans; --i >= 0;)
  28452. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  28453. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  28454. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  28455. }
  28456. const AudioProcessorGraph::Node::Ptr node;
  28457. AudioProcessor* const processor;
  28458. private:
  28459. Array <int> audioChannelsToUse;
  28460. HeapBlock <float*> channels;
  28461. int totalChans;
  28462. int midiBufferToUse;
  28463. ProcessBufferOp (const ProcessBufferOp&);
  28464. ProcessBufferOp& operator= (const ProcessBufferOp&);
  28465. };
  28466. /** Used to calculate the correct sequence of rendering ops needed, based on
  28467. the best re-use of shared buffers at each stage.
  28468. */
  28469. class RenderingOpSequenceCalculator
  28470. {
  28471. public:
  28472. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  28473. const Array<void*>& orderedNodes_,
  28474. Array<void*>& renderingOps)
  28475. : graph (graph_),
  28476. orderedNodes (orderedNodes_)
  28477. {
  28478. nodeIds.add (-2); // first buffer is read-only zeros
  28479. channels.add (0);
  28480. midiNodeIds.add (-2);
  28481. for (int i = 0; i < orderedNodes.size(); ++i)
  28482. {
  28483. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  28484. renderingOps, i);
  28485. markAnyUnusedBuffersAsFree (i);
  28486. }
  28487. }
  28488. int getNumBuffersNeeded() const { return nodeIds.size(); }
  28489. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  28490. juce_UseDebuggingNewOperator
  28491. private:
  28492. AudioProcessorGraph& graph;
  28493. const Array<void*>& orderedNodes;
  28494. Array <int> nodeIds, channels, midiNodeIds;
  28495. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  28496. Array<void*>& renderingOps,
  28497. const int ourRenderingIndex)
  28498. {
  28499. const int numIns = node->processor->getNumInputChannels();
  28500. const int numOuts = node->processor->getNumOutputChannels();
  28501. const int totalChans = jmax (numIns, numOuts);
  28502. Array <int> audioChannelsToUse;
  28503. int midiBufferToUse = -1;
  28504. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  28505. {
  28506. // get a list of all the inputs to this node
  28507. Array <int> sourceNodes, sourceOutputChans;
  28508. for (int i = graph.getNumConnections(); --i >= 0;)
  28509. {
  28510. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28511. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  28512. {
  28513. sourceNodes.add (c->sourceNodeId);
  28514. sourceOutputChans.add (c->sourceChannelIndex);
  28515. }
  28516. }
  28517. int bufIndex = -1;
  28518. if (sourceNodes.size() == 0)
  28519. {
  28520. // unconnected input channel
  28521. if (inputChan >= numOuts)
  28522. {
  28523. bufIndex = getReadOnlyEmptyBuffer();
  28524. jassert (bufIndex >= 0);
  28525. }
  28526. else
  28527. {
  28528. bufIndex = getFreeBuffer (false);
  28529. renderingOps.add (new ClearChannelOp (bufIndex));
  28530. }
  28531. }
  28532. else if (sourceNodes.size() == 1)
  28533. {
  28534. // channel with a straightforward single input..
  28535. const int srcNode = sourceNodes.getUnchecked(0);
  28536. const int srcChan = sourceOutputChans.getUnchecked(0);
  28537. bufIndex = getBufferContaining (srcNode, srcChan);
  28538. if (bufIndex < 0)
  28539. {
  28540. // if not found, this is probably a feedback loop
  28541. bufIndex = getReadOnlyEmptyBuffer();
  28542. jassert (bufIndex >= 0);
  28543. }
  28544. if (inputChan < numOuts
  28545. && isBufferNeededLater (ourRenderingIndex,
  28546. inputChan,
  28547. srcNode, srcChan))
  28548. {
  28549. // can't mess up this channel because it's needed later by another node, so we
  28550. // need to use a copy of it..
  28551. const int newFreeBuffer = getFreeBuffer (false);
  28552. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  28553. bufIndex = newFreeBuffer;
  28554. }
  28555. }
  28556. else
  28557. {
  28558. // channel with a mix of several inputs..
  28559. // try to find a re-usable channel from our inputs..
  28560. int reusableInputIndex = -1;
  28561. for (int i = 0; i < sourceNodes.size(); ++i)
  28562. {
  28563. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  28564. sourceOutputChans.getUnchecked(i));
  28565. if (sourceBufIndex >= 0
  28566. && ! isBufferNeededLater (ourRenderingIndex,
  28567. inputChan,
  28568. sourceNodes.getUnchecked(i),
  28569. sourceOutputChans.getUnchecked(i)))
  28570. {
  28571. // we've found one of our input chans that can be re-used..
  28572. reusableInputIndex = i;
  28573. bufIndex = sourceBufIndex;
  28574. break;
  28575. }
  28576. }
  28577. if (reusableInputIndex < 0)
  28578. {
  28579. // can't re-use any of our input chans, so get a new one and copy everything into it..
  28580. bufIndex = getFreeBuffer (false);
  28581. jassert (bufIndex != 0);
  28582. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  28583. sourceOutputChans.getUnchecked (0));
  28584. if (srcIndex < 0)
  28585. {
  28586. // if not found, this is probably a feedback loop
  28587. renderingOps.add (new ClearChannelOp (bufIndex));
  28588. }
  28589. else
  28590. {
  28591. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  28592. }
  28593. reusableInputIndex = 0;
  28594. }
  28595. for (int j = 0; j < sourceNodes.size(); ++j)
  28596. {
  28597. if (j != reusableInputIndex)
  28598. {
  28599. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  28600. sourceOutputChans.getUnchecked(j));
  28601. if (srcIndex >= 0)
  28602. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  28603. }
  28604. }
  28605. }
  28606. jassert (bufIndex >= 0);
  28607. audioChannelsToUse.add (bufIndex);
  28608. if (inputChan < numOuts)
  28609. markBufferAsContaining (bufIndex, node->id, inputChan);
  28610. }
  28611. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  28612. {
  28613. const int bufIndex = getFreeBuffer (false);
  28614. jassert (bufIndex != 0);
  28615. audioChannelsToUse.add (bufIndex);
  28616. markBufferAsContaining (bufIndex, node->id, outputChan);
  28617. }
  28618. // Now the same thing for midi..
  28619. Array <int> midiSourceNodes;
  28620. for (int i = graph.getNumConnections(); --i >= 0;)
  28621. {
  28622. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28623. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  28624. midiSourceNodes.add (c->sourceNodeId);
  28625. }
  28626. if (midiSourceNodes.size() == 0)
  28627. {
  28628. // No midi inputs..
  28629. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28630. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  28631. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28632. }
  28633. else if (midiSourceNodes.size() == 1)
  28634. {
  28635. // One midi input..
  28636. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28637. AudioProcessorGraph::midiChannelIndex);
  28638. if (midiBufferToUse >= 0)
  28639. {
  28640. if (isBufferNeededLater (ourRenderingIndex,
  28641. AudioProcessorGraph::midiChannelIndex,
  28642. midiSourceNodes.getUnchecked(0),
  28643. AudioProcessorGraph::midiChannelIndex))
  28644. {
  28645. // can't mess up this channel because it's needed later by another node, so we
  28646. // need to use a copy of it..
  28647. const int newFreeBuffer = getFreeBuffer (true);
  28648. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  28649. midiBufferToUse = newFreeBuffer;
  28650. }
  28651. }
  28652. else
  28653. {
  28654. // probably a feedback loop, so just use an empty one..
  28655. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28656. }
  28657. }
  28658. else
  28659. {
  28660. // More than one midi input being mixed..
  28661. int reusableInputIndex = -1;
  28662. for (int i = 0; i < midiSourceNodes.size(); ++i)
  28663. {
  28664. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  28665. AudioProcessorGraph::midiChannelIndex);
  28666. if (sourceBufIndex >= 0
  28667. && ! isBufferNeededLater (ourRenderingIndex,
  28668. AudioProcessorGraph::midiChannelIndex,
  28669. midiSourceNodes.getUnchecked(i),
  28670. AudioProcessorGraph::midiChannelIndex))
  28671. {
  28672. // we've found one of our input buffers that can be re-used..
  28673. reusableInputIndex = i;
  28674. midiBufferToUse = sourceBufIndex;
  28675. break;
  28676. }
  28677. }
  28678. if (reusableInputIndex < 0)
  28679. {
  28680. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  28681. midiBufferToUse = getFreeBuffer (true);
  28682. jassert (midiBufferToUse >= 0);
  28683. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28684. AudioProcessorGraph::midiChannelIndex);
  28685. if (srcIndex >= 0)
  28686. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  28687. else
  28688. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28689. reusableInputIndex = 0;
  28690. }
  28691. for (int j = 0; j < midiSourceNodes.size(); ++j)
  28692. {
  28693. if (j != reusableInputIndex)
  28694. {
  28695. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  28696. AudioProcessorGraph::midiChannelIndex);
  28697. if (srcIndex >= 0)
  28698. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  28699. }
  28700. }
  28701. }
  28702. if (node->processor->producesMidi())
  28703. markBufferAsContaining (midiBufferToUse, node->id,
  28704. AudioProcessorGraph::midiChannelIndex);
  28705. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  28706. totalChans, midiBufferToUse));
  28707. }
  28708. int getFreeBuffer (const bool forMidi)
  28709. {
  28710. if (forMidi)
  28711. {
  28712. for (int i = 1; i < midiNodeIds.size(); ++i)
  28713. if (midiNodeIds.getUnchecked(i) < 0)
  28714. return i;
  28715. midiNodeIds.add (-1);
  28716. return midiNodeIds.size() - 1;
  28717. }
  28718. else
  28719. {
  28720. for (int i = 1; i < nodeIds.size(); ++i)
  28721. if (nodeIds.getUnchecked(i) < 0)
  28722. return i;
  28723. nodeIds.add (-1);
  28724. channels.add (0);
  28725. return nodeIds.size() - 1;
  28726. }
  28727. }
  28728. int getReadOnlyEmptyBuffer() const
  28729. {
  28730. return 0;
  28731. }
  28732. int getBufferContaining (const int nodeId, const int outputChannel) const
  28733. {
  28734. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  28735. {
  28736. for (int i = midiNodeIds.size(); --i >= 0;)
  28737. if (midiNodeIds.getUnchecked(i) == nodeId)
  28738. return i;
  28739. }
  28740. else
  28741. {
  28742. for (int i = nodeIds.size(); --i >= 0;)
  28743. if (nodeIds.getUnchecked(i) == nodeId
  28744. && channels.getUnchecked(i) == outputChannel)
  28745. return i;
  28746. }
  28747. return -1;
  28748. }
  28749. void markAnyUnusedBuffersAsFree (const int stepIndex)
  28750. {
  28751. int i;
  28752. for (i = 0; i < nodeIds.size(); ++i)
  28753. {
  28754. if (nodeIds.getUnchecked(i) >= 0
  28755. && ! isBufferNeededLater (stepIndex, -1,
  28756. nodeIds.getUnchecked(i),
  28757. channels.getUnchecked(i)))
  28758. {
  28759. nodeIds.set (i, -1);
  28760. }
  28761. }
  28762. for (i = 0; i < midiNodeIds.size(); ++i)
  28763. {
  28764. if (midiNodeIds.getUnchecked(i) >= 0
  28765. && ! isBufferNeededLater (stepIndex, -1,
  28766. midiNodeIds.getUnchecked(i),
  28767. AudioProcessorGraph::midiChannelIndex))
  28768. {
  28769. midiNodeIds.set (i, -1);
  28770. }
  28771. }
  28772. }
  28773. bool isBufferNeededLater (int stepIndexToSearchFrom,
  28774. int inputChannelOfIndexToIgnore,
  28775. const int nodeId,
  28776. const int outputChanIndex) const
  28777. {
  28778. while (stepIndexToSearchFrom < orderedNodes.size())
  28779. {
  28780. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  28781. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  28782. {
  28783. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  28784. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  28785. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  28786. return true;
  28787. }
  28788. else
  28789. {
  28790. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  28791. if (i != inputChannelOfIndexToIgnore
  28792. && graph.getConnectionBetween (nodeId, outputChanIndex,
  28793. node->id, i) != 0)
  28794. return true;
  28795. }
  28796. inputChannelOfIndexToIgnore = -1;
  28797. ++stepIndexToSearchFrom;
  28798. }
  28799. return false;
  28800. }
  28801. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  28802. {
  28803. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  28804. {
  28805. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  28806. midiNodeIds.set (bufferNum, nodeId);
  28807. }
  28808. else
  28809. {
  28810. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  28811. nodeIds.set (bufferNum, nodeId);
  28812. channels.set (bufferNum, outputIndex);
  28813. }
  28814. }
  28815. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  28816. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  28817. };
  28818. }
  28819. void AudioProcessorGraph::clearRenderingSequence()
  28820. {
  28821. const ScopedLock sl (renderLock);
  28822. for (int i = renderingOps.size(); --i >= 0;)
  28823. {
  28824. GraphRenderingOps::AudioGraphRenderingOp* const r
  28825. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28826. renderingOps.remove (i);
  28827. delete r;
  28828. }
  28829. }
  28830. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  28831. const uint32 possibleDestinationId,
  28832. const int recursionCheck) const
  28833. {
  28834. if (recursionCheck > 0)
  28835. {
  28836. for (int i = connections.size(); --i >= 0;)
  28837. {
  28838. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  28839. if (c->destNodeId == possibleDestinationId
  28840. && (c->sourceNodeId == possibleInputId
  28841. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  28842. return true;
  28843. }
  28844. }
  28845. return false;
  28846. }
  28847. void AudioProcessorGraph::buildRenderingSequence()
  28848. {
  28849. Array<void*> newRenderingOps;
  28850. int numRenderingBuffersNeeded = 2;
  28851. int numMidiBuffersNeeded = 1;
  28852. {
  28853. MessageManagerLock mml;
  28854. Array<void*> orderedNodes;
  28855. int i;
  28856. for (i = 0; i < nodes.size(); ++i)
  28857. {
  28858. Node* const node = nodes.getUnchecked(i);
  28859. node->prepare (getSampleRate(), getBlockSize(), this);
  28860. int j = 0;
  28861. for (; j < orderedNodes.size(); ++j)
  28862. if (isAnInputTo (node->id,
  28863. ((Node*) orderedNodes.getUnchecked (j))->id,
  28864. nodes.size() + 1))
  28865. break;
  28866. orderedNodes.insert (j, node);
  28867. }
  28868. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  28869. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  28870. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  28871. }
  28872. Array<void*> oldRenderingOps (renderingOps);
  28873. {
  28874. // swap over to the new rendering sequence..
  28875. const ScopedLock sl (renderLock);
  28876. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  28877. renderingBuffers.clear();
  28878. for (int i = midiBuffers.size(); --i >= 0;)
  28879. midiBuffers.getUnchecked(i)->clear();
  28880. while (midiBuffers.size() < numMidiBuffersNeeded)
  28881. midiBuffers.add (new MidiBuffer());
  28882. renderingOps = newRenderingOps;
  28883. }
  28884. for (int i = oldRenderingOps.size(); --i >= 0;)
  28885. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  28886. }
  28887. void AudioProcessorGraph::handleAsyncUpdate()
  28888. {
  28889. buildRenderingSequence();
  28890. }
  28891. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  28892. {
  28893. currentAudioInputBuffer = 0;
  28894. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  28895. currentMidiInputBuffer = 0;
  28896. currentMidiOutputBuffer.clear();
  28897. clearRenderingSequence();
  28898. buildRenderingSequence();
  28899. }
  28900. void AudioProcessorGraph::releaseResources()
  28901. {
  28902. for (int i = 0; i < nodes.size(); ++i)
  28903. nodes.getUnchecked(i)->unprepare();
  28904. renderingBuffers.setSize (1, 1);
  28905. midiBuffers.clear();
  28906. currentAudioInputBuffer = 0;
  28907. currentAudioOutputBuffer.setSize (1, 1);
  28908. currentMidiInputBuffer = 0;
  28909. currentMidiOutputBuffer.clear();
  28910. }
  28911. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  28912. {
  28913. const int numSamples = buffer.getNumSamples();
  28914. const ScopedLock sl (renderLock);
  28915. currentAudioInputBuffer = &buffer;
  28916. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  28917. currentAudioOutputBuffer.clear();
  28918. currentMidiInputBuffer = &midiMessages;
  28919. currentMidiOutputBuffer.clear();
  28920. int i;
  28921. for (i = 0; i < renderingOps.size(); ++i)
  28922. {
  28923. GraphRenderingOps::AudioGraphRenderingOp* const op
  28924. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28925. op->perform (renderingBuffers, midiBuffers, numSamples);
  28926. }
  28927. for (i = 0; i < buffer.getNumChannels(); ++i)
  28928. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  28929. midiMessages.clear();
  28930. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  28931. }
  28932. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  28933. {
  28934. return "Input " + String (channelIndex + 1);
  28935. }
  28936. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  28937. {
  28938. return "Output " + String (channelIndex + 1);
  28939. }
  28940. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  28941. {
  28942. return true;
  28943. }
  28944. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  28945. {
  28946. return true;
  28947. }
  28948. bool AudioProcessorGraph::acceptsMidi() const
  28949. {
  28950. return true;
  28951. }
  28952. bool AudioProcessorGraph::producesMidi() const
  28953. {
  28954. return true;
  28955. }
  28956. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  28957. {
  28958. }
  28959. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  28960. {
  28961. }
  28962. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  28963. : type (type_),
  28964. graph (0)
  28965. {
  28966. }
  28967. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  28968. {
  28969. }
  28970. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  28971. {
  28972. switch (type)
  28973. {
  28974. case audioOutputNode:
  28975. return "Audio Output";
  28976. case audioInputNode:
  28977. return "Audio Input";
  28978. case midiOutputNode:
  28979. return "Midi Output";
  28980. case midiInputNode:
  28981. return "Midi Input";
  28982. default:
  28983. break;
  28984. }
  28985. return String::empty;
  28986. }
  28987. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  28988. {
  28989. d.name = getName();
  28990. d.uid = d.name.hashCode();
  28991. d.category = "I/O devices";
  28992. d.pluginFormatName = "Internal";
  28993. d.manufacturerName = "Raw Material Software";
  28994. d.version = "1.0";
  28995. d.isInstrument = false;
  28996. d.numInputChannels = getNumInputChannels();
  28997. if (type == audioOutputNode && graph != 0)
  28998. d.numInputChannels = graph->getNumInputChannels();
  28999. d.numOutputChannels = getNumOutputChannels();
  29000. if (type == audioInputNode && graph != 0)
  29001. d.numOutputChannels = graph->getNumOutputChannels();
  29002. }
  29003. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29004. {
  29005. jassert (graph != 0);
  29006. }
  29007. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29008. {
  29009. }
  29010. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29011. MidiBuffer& midiMessages)
  29012. {
  29013. jassert (graph != 0);
  29014. switch (type)
  29015. {
  29016. case audioOutputNode:
  29017. {
  29018. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29019. buffer.getNumChannels()); --i >= 0;)
  29020. {
  29021. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29022. }
  29023. break;
  29024. }
  29025. case audioInputNode:
  29026. {
  29027. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29028. buffer.getNumChannels()); --i >= 0;)
  29029. {
  29030. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29031. }
  29032. break;
  29033. }
  29034. case midiOutputNode:
  29035. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29036. break;
  29037. case midiInputNode:
  29038. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29039. break;
  29040. default:
  29041. break;
  29042. }
  29043. }
  29044. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29045. {
  29046. return type == midiOutputNode;
  29047. }
  29048. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29049. {
  29050. return type == midiInputNode;
  29051. }
  29052. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  29053. {
  29054. switch (type)
  29055. {
  29056. case audioOutputNode:
  29057. return "Output " + String (channelIndex + 1);
  29058. case midiOutputNode:
  29059. return "Midi Output";
  29060. default:
  29061. break;
  29062. }
  29063. return String::empty;
  29064. }
  29065. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  29066. {
  29067. switch (type)
  29068. {
  29069. case audioInputNode:
  29070. return "Input " + String (channelIndex + 1);
  29071. case midiInputNode:
  29072. return "Midi Input";
  29073. default:
  29074. break;
  29075. }
  29076. return String::empty;
  29077. }
  29078. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29079. {
  29080. return type == audioInputNode || type == audioOutputNode;
  29081. }
  29082. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29083. {
  29084. return isInputChannelStereoPair (index);
  29085. }
  29086. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29087. {
  29088. return type == audioInputNode || type == midiInputNode;
  29089. }
  29090. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29091. {
  29092. return type == audioOutputNode || type == midiOutputNode;
  29093. }
  29094. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  29095. {
  29096. return 0;
  29097. }
  29098. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29099. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29100. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29101. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29102. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29103. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29104. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29105. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29106. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29107. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29108. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29109. {
  29110. }
  29111. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29112. {
  29113. }
  29114. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29115. {
  29116. graph = newGraph;
  29117. if (graph != 0)
  29118. {
  29119. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29120. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29121. getSampleRate(),
  29122. getBlockSize());
  29123. updateHostDisplay();
  29124. }
  29125. }
  29126. END_JUCE_NAMESPACE
  29127. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29128. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29129. BEGIN_JUCE_NAMESPACE
  29130. AudioProcessorPlayer::AudioProcessorPlayer()
  29131. : processor (0),
  29132. sampleRate (0),
  29133. blockSize (0),
  29134. isPrepared (false),
  29135. numInputChans (0),
  29136. numOutputChans (0),
  29137. tempBuffer (1, 1)
  29138. {
  29139. }
  29140. AudioProcessorPlayer::~AudioProcessorPlayer()
  29141. {
  29142. setProcessor (0);
  29143. }
  29144. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29145. {
  29146. if (processor != processorToPlay)
  29147. {
  29148. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29149. {
  29150. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29151. sampleRate, blockSize);
  29152. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29153. }
  29154. AudioProcessor* oldOne;
  29155. {
  29156. const ScopedLock sl (lock);
  29157. oldOne = isPrepared ? processor : 0;
  29158. processor = processorToPlay;
  29159. isPrepared = true;
  29160. }
  29161. if (oldOne != 0)
  29162. oldOne->releaseResources();
  29163. }
  29164. }
  29165. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  29166. const int numInputChannels,
  29167. float** const outputChannelData,
  29168. const int numOutputChannels,
  29169. const int numSamples)
  29170. {
  29171. // these should have been prepared by audioDeviceAboutToStart()...
  29172. jassert (sampleRate > 0 && blockSize > 0);
  29173. incomingMidi.clear();
  29174. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29175. int i, totalNumChans = 0;
  29176. if (numInputChannels > numOutputChannels)
  29177. {
  29178. // if there aren't enough output channels for the number of
  29179. // inputs, we need to create some temporary extra ones (can't
  29180. // use the input data in case it gets written to)
  29181. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29182. false, false, true);
  29183. for (i = 0; i < numOutputChannels; ++i)
  29184. {
  29185. channels[totalNumChans] = outputChannelData[i];
  29186. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29187. ++totalNumChans;
  29188. }
  29189. for (i = numOutputChannels; i < numInputChannels; ++i)
  29190. {
  29191. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29192. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29193. ++totalNumChans;
  29194. }
  29195. }
  29196. else
  29197. {
  29198. for (i = 0; i < numInputChannels; ++i)
  29199. {
  29200. channels[totalNumChans] = outputChannelData[i];
  29201. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29202. ++totalNumChans;
  29203. }
  29204. for (i = numInputChannels; i < numOutputChannels; ++i)
  29205. {
  29206. channels[totalNumChans] = outputChannelData[i];
  29207. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  29208. ++totalNumChans;
  29209. }
  29210. }
  29211. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  29212. const ScopedLock sl (lock);
  29213. if (processor != 0)
  29214. {
  29215. const ScopedLock sl (processor->getCallbackLock());
  29216. if (processor->isSuspended())
  29217. {
  29218. for (i = 0; i < numOutputChannels; ++i)
  29219. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  29220. }
  29221. else
  29222. {
  29223. processor->processBlock (buffer, incomingMidi);
  29224. }
  29225. }
  29226. }
  29227. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  29228. {
  29229. const ScopedLock sl (lock);
  29230. sampleRate = device->getCurrentSampleRate();
  29231. blockSize = device->getCurrentBufferSizeSamples();
  29232. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  29233. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  29234. messageCollector.reset (sampleRate);
  29235. zeromem (channels, sizeof (channels));
  29236. if (processor != 0)
  29237. {
  29238. if (isPrepared)
  29239. processor->releaseResources();
  29240. AudioProcessor* const oldProcessor = processor;
  29241. setProcessor (0);
  29242. setProcessor (oldProcessor);
  29243. }
  29244. }
  29245. void AudioProcessorPlayer::audioDeviceStopped()
  29246. {
  29247. const ScopedLock sl (lock);
  29248. if (processor != 0 && isPrepared)
  29249. processor->releaseResources();
  29250. sampleRate = 0.0;
  29251. blockSize = 0;
  29252. isPrepared = false;
  29253. tempBuffer.setSize (1, 1);
  29254. }
  29255. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  29256. {
  29257. messageCollector.addMessageToQueue (message);
  29258. }
  29259. END_JUCE_NAMESPACE
  29260. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29261. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29262. BEGIN_JUCE_NAMESPACE
  29263. class ProcessorParameterPropertyComp : public PropertyComponent,
  29264. public AudioProcessorListener,
  29265. public AsyncUpdater
  29266. {
  29267. public:
  29268. ProcessorParameterPropertyComp (const String& name,
  29269. AudioProcessor* const owner_,
  29270. const int index_)
  29271. : PropertyComponent (name),
  29272. owner (owner_),
  29273. index (index_)
  29274. {
  29275. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  29276. owner_->addListener (this);
  29277. }
  29278. ~ProcessorParameterPropertyComp()
  29279. {
  29280. owner->removeListener (this);
  29281. deleteAllChildren();
  29282. }
  29283. void refresh()
  29284. {
  29285. slider->setValue (owner->getParameter (index), false);
  29286. }
  29287. void audioProcessorChanged (AudioProcessor*) {}
  29288. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  29289. {
  29290. if (parameterIndex == index)
  29291. triggerAsyncUpdate();
  29292. }
  29293. void handleAsyncUpdate()
  29294. {
  29295. refresh();
  29296. }
  29297. juce_UseDebuggingNewOperator
  29298. private:
  29299. AudioProcessor* const owner;
  29300. const int index;
  29301. Slider* slider;
  29302. class ParamSlider : public Slider
  29303. {
  29304. public:
  29305. ParamSlider (AudioProcessor* const owner_, const int index_)
  29306. : Slider (String::empty),
  29307. owner (owner_),
  29308. index (index_)
  29309. {
  29310. setRange (0.0, 1.0, 0.0);
  29311. setSliderStyle (Slider::LinearBar);
  29312. setTextBoxIsEditable (false);
  29313. setScrollWheelEnabled (false);
  29314. }
  29315. ~ParamSlider()
  29316. {
  29317. }
  29318. void valueChanged()
  29319. {
  29320. const float newVal = (float) getValue();
  29321. if (owner->getParameter (index) != newVal)
  29322. owner->setParameter (index, newVal);
  29323. }
  29324. const String getTextFromValue (double /*value*/)
  29325. {
  29326. return owner->getParameterText (index);
  29327. }
  29328. juce_UseDebuggingNewOperator
  29329. private:
  29330. AudioProcessor* const owner;
  29331. const int index;
  29332. ParamSlider (const ParamSlider&);
  29333. ParamSlider& operator= (const ParamSlider&);
  29334. };
  29335. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  29336. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  29337. };
  29338. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  29339. : AudioProcessorEditor (owner_)
  29340. {
  29341. setOpaque (true);
  29342. addAndMakeVisible (panel = new PropertyPanel());
  29343. Array <PropertyComponent*> params;
  29344. const int numParams = owner_->getNumParameters();
  29345. int totalHeight = 0;
  29346. for (int i = 0; i < numParams; ++i)
  29347. {
  29348. String name (owner_->getParameterName (i));
  29349. if (name.trim().isEmpty())
  29350. name = "Unnamed";
  29351. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner_, i);
  29352. params.add (pc);
  29353. totalHeight += pc->getPreferredHeight();
  29354. }
  29355. panel->addProperties (params);
  29356. setSize (400, jlimit (25, 400, totalHeight));
  29357. }
  29358. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  29359. {
  29360. deleteAllChildren();
  29361. }
  29362. void GenericAudioProcessorEditor::paint (Graphics& g)
  29363. {
  29364. g.fillAll (Colours::white);
  29365. }
  29366. void GenericAudioProcessorEditor::resized()
  29367. {
  29368. panel->setSize (getWidth(), getHeight());
  29369. }
  29370. END_JUCE_NAMESPACE
  29371. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29372. /*** Start of inlined file: juce_Sampler.cpp ***/
  29373. BEGIN_JUCE_NAMESPACE
  29374. SamplerSound::SamplerSound (const String& name_,
  29375. AudioFormatReader& source,
  29376. const BigInteger& midiNotes_,
  29377. const int midiNoteForNormalPitch,
  29378. const double attackTimeSecs,
  29379. const double releaseTimeSecs,
  29380. const double maxSampleLengthSeconds)
  29381. : name (name_),
  29382. midiNotes (midiNotes_),
  29383. midiRootNote (midiNoteForNormalPitch)
  29384. {
  29385. sourceSampleRate = source.sampleRate;
  29386. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  29387. {
  29388. length = 0;
  29389. attackSamples = 0;
  29390. releaseSamples = 0;
  29391. }
  29392. else
  29393. {
  29394. length = jmin ((int) source.lengthInSamples,
  29395. (int) (maxSampleLengthSeconds * sourceSampleRate));
  29396. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  29397. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  29398. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  29399. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  29400. }
  29401. }
  29402. SamplerSound::~SamplerSound()
  29403. {
  29404. }
  29405. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  29406. {
  29407. return midiNotes [midiNoteNumber];
  29408. }
  29409. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  29410. {
  29411. return true;
  29412. }
  29413. SamplerVoice::SamplerVoice()
  29414. : pitchRatio (0.0),
  29415. sourceSamplePosition (0.0),
  29416. lgain (0.0f),
  29417. rgain (0.0f),
  29418. isInAttack (false),
  29419. isInRelease (false)
  29420. {
  29421. }
  29422. SamplerVoice::~SamplerVoice()
  29423. {
  29424. }
  29425. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  29426. {
  29427. return dynamic_cast <const SamplerSound*> (sound) != 0;
  29428. }
  29429. void SamplerVoice::startNote (const int midiNoteNumber,
  29430. const float velocity,
  29431. SynthesiserSound* s,
  29432. const int /*currentPitchWheelPosition*/)
  29433. {
  29434. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  29435. jassert (sound != 0); // this object can only play SamplerSounds!
  29436. if (sound != 0)
  29437. {
  29438. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  29439. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  29440. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  29441. sourceSamplePosition = 0.0;
  29442. lgain = velocity;
  29443. rgain = velocity;
  29444. isInAttack = (sound->attackSamples > 0);
  29445. isInRelease = false;
  29446. if (isInAttack)
  29447. {
  29448. attackReleaseLevel = 0.0f;
  29449. attackDelta = (float) (pitchRatio / sound->attackSamples);
  29450. }
  29451. else
  29452. {
  29453. attackReleaseLevel = 1.0f;
  29454. attackDelta = 0.0f;
  29455. }
  29456. if (sound->releaseSamples > 0)
  29457. {
  29458. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  29459. }
  29460. else
  29461. {
  29462. releaseDelta = 0.0f;
  29463. }
  29464. }
  29465. }
  29466. void SamplerVoice::stopNote (const bool allowTailOff)
  29467. {
  29468. if (allowTailOff)
  29469. {
  29470. isInAttack = false;
  29471. isInRelease = true;
  29472. }
  29473. else
  29474. {
  29475. clearCurrentNote();
  29476. }
  29477. }
  29478. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  29479. {
  29480. }
  29481. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  29482. const int /*newValue*/)
  29483. {
  29484. }
  29485. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  29486. {
  29487. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  29488. if (playingSound != 0)
  29489. {
  29490. const float* const inL = playingSound->data->getSampleData (0, 0);
  29491. const float* const inR = playingSound->data->getNumChannels() > 1
  29492. ? playingSound->data->getSampleData (1, 0) : 0;
  29493. float* outL = outputBuffer.getSampleData (0, startSample);
  29494. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  29495. while (--numSamples >= 0)
  29496. {
  29497. const int pos = (int) sourceSamplePosition;
  29498. const float alpha = (float) (sourceSamplePosition - pos);
  29499. const float invAlpha = 1.0f - alpha;
  29500. // just using a very simple linear interpolation here..
  29501. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  29502. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  29503. : l;
  29504. l *= lgain;
  29505. r *= rgain;
  29506. if (isInAttack)
  29507. {
  29508. l *= attackReleaseLevel;
  29509. r *= attackReleaseLevel;
  29510. attackReleaseLevel += attackDelta;
  29511. if (attackReleaseLevel >= 1.0f)
  29512. {
  29513. attackReleaseLevel = 1.0f;
  29514. isInAttack = false;
  29515. }
  29516. }
  29517. else if (isInRelease)
  29518. {
  29519. l *= attackReleaseLevel;
  29520. r *= attackReleaseLevel;
  29521. attackReleaseLevel += releaseDelta;
  29522. if (attackReleaseLevel <= 0.0f)
  29523. {
  29524. stopNote (false);
  29525. break;
  29526. }
  29527. }
  29528. if (outR != 0)
  29529. {
  29530. *outL++ += l;
  29531. *outR++ += r;
  29532. }
  29533. else
  29534. {
  29535. *outL++ += (l + r) * 0.5f;
  29536. }
  29537. sourceSamplePosition += pitchRatio;
  29538. if (sourceSamplePosition > playingSound->length)
  29539. {
  29540. stopNote (false);
  29541. break;
  29542. }
  29543. }
  29544. }
  29545. }
  29546. END_JUCE_NAMESPACE
  29547. /*** End of inlined file: juce_Sampler.cpp ***/
  29548. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  29549. BEGIN_JUCE_NAMESPACE
  29550. SynthesiserSound::SynthesiserSound()
  29551. {
  29552. }
  29553. SynthesiserSound::~SynthesiserSound()
  29554. {
  29555. }
  29556. SynthesiserVoice::SynthesiserVoice()
  29557. : currentSampleRate (44100.0),
  29558. currentlyPlayingNote (-1),
  29559. noteOnTime (0),
  29560. currentlyPlayingSound (0)
  29561. {
  29562. }
  29563. SynthesiserVoice::~SynthesiserVoice()
  29564. {
  29565. }
  29566. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  29567. {
  29568. return currentlyPlayingSound != 0
  29569. && currentlyPlayingSound->appliesToChannel (midiChannel);
  29570. }
  29571. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  29572. {
  29573. currentSampleRate = newRate;
  29574. }
  29575. void SynthesiserVoice::clearCurrentNote()
  29576. {
  29577. currentlyPlayingNote = -1;
  29578. currentlyPlayingSound = 0;
  29579. }
  29580. Synthesiser::Synthesiser()
  29581. : sampleRate (0),
  29582. lastNoteOnCounter (0),
  29583. shouldStealNotes (true)
  29584. {
  29585. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  29586. lastPitchWheelValues[i] = 0x2000;
  29587. }
  29588. Synthesiser::~Synthesiser()
  29589. {
  29590. }
  29591. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  29592. {
  29593. const ScopedLock sl (lock);
  29594. return voices [index];
  29595. }
  29596. void Synthesiser::clearVoices()
  29597. {
  29598. const ScopedLock sl (lock);
  29599. voices.clear();
  29600. }
  29601. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  29602. {
  29603. const ScopedLock sl (lock);
  29604. voices.add (newVoice);
  29605. }
  29606. void Synthesiser::removeVoice (const int index)
  29607. {
  29608. const ScopedLock sl (lock);
  29609. voices.remove (index);
  29610. }
  29611. void Synthesiser::clearSounds()
  29612. {
  29613. const ScopedLock sl (lock);
  29614. sounds.clear();
  29615. }
  29616. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  29617. {
  29618. const ScopedLock sl (lock);
  29619. sounds.add (newSound);
  29620. }
  29621. void Synthesiser::removeSound (const int index)
  29622. {
  29623. const ScopedLock sl (lock);
  29624. sounds.remove (index);
  29625. }
  29626. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  29627. {
  29628. shouldStealNotes = shouldStealNotes_;
  29629. }
  29630. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  29631. {
  29632. if (sampleRate != newRate)
  29633. {
  29634. const ScopedLock sl (lock);
  29635. allNotesOff (0, false);
  29636. sampleRate = newRate;
  29637. for (int i = voices.size(); --i >= 0;)
  29638. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  29639. }
  29640. }
  29641. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  29642. const MidiBuffer& midiData,
  29643. int startSample,
  29644. int numSamples)
  29645. {
  29646. // must set the sample rate before using this!
  29647. jassert (sampleRate != 0);
  29648. const ScopedLock sl (lock);
  29649. MidiBuffer::Iterator midiIterator (midiData);
  29650. midiIterator.setNextSamplePosition (startSample);
  29651. MidiMessage m (0xf4, 0.0);
  29652. while (numSamples > 0)
  29653. {
  29654. int midiEventPos;
  29655. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  29656. && midiEventPos < startSample + numSamples;
  29657. const int numThisTime = useEvent ? midiEventPos - startSample
  29658. : numSamples;
  29659. if (numThisTime > 0)
  29660. {
  29661. for (int i = voices.size(); --i >= 0;)
  29662. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  29663. }
  29664. if (useEvent)
  29665. {
  29666. if (m.isNoteOn())
  29667. {
  29668. const int channel = m.getChannel();
  29669. noteOn (channel,
  29670. m.getNoteNumber(),
  29671. m.getFloatVelocity());
  29672. }
  29673. else if (m.isNoteOff())
  29674. {
  29675. noteOff (m.getChannel(),
  29676. m.getNoteNumber(),
  29677. true);
  29678. }
  29679. else if (m.isAllNotesOff() || m.isAllSoundOff())
  29680. {
  29681. allNotesOff (m.getChannel(), true);
  29682. }
  29683. else if (m.isPitchWheel())
  29684. {
  29685. const int channel = m.getChannel();
  29686. const int wheelPos = m.getPitchWheelValue();
  29687. lastPitchWheelValues [channel - 1] = wheelPos;
  29688. handlePitchWheel (channel, wheelPos);
  29689. }
  29690. else if (m.isController())
  29691. {
  29692. handleController (m.getChannel(),
  29693. m.getControllerNumber(),
  29694. m.getControllerValue());
  29695. }
  29696. }
  29697. startSample += numThisTime;
  29698. numSamples -= numThisTime;
  29699. }
  29700. }
  29701. void Synthesiser::noteOn (const int midiChannel,
  29702. const int midiNoteNumber,
  29703. const float velocity)
  29704. {
  29705. const ScopedLock sl (lock);
  29706. for (int i = sounds.size(); --i >= 0;)
  29707. {
  29708. SynthesiserSound* const sound = sounds.getUnchecked(i);
  29709. if (sound->appliesToNote (midiNoteNumber)
  29710. && sound->appliesToChannel (midiChannel))
  29711. {
  29712. startVoice (findFreeVoice (sound, shouldStealNotes),
  29713. sound, midiChannel, midiNoteNumber, velocity);
  29714. }
  29715. }
  29716. }
  29717. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  29718. SynthesiserSound* const sound,
  29719. const int midiChannel,
  29720. const int midiNoteNumber,
  29721. const float velocity)
  29722. {
  29723. if (voice != 0 && sound != 0)
  29724. {
  29725. if (voice->currentlyPlayingSound != 0)
  29726. voice->stopNote (false);
  29727. voice->startNote (midiNoteNumber,
  29728. velocity,
  29729. sound,
  29730. lastPitchWheelValues [midiChannel - 1]);
  29731. voice->currentlyPlayingNote = midiNoteNumber;
  29732. voice->noteOnTime = ++lastNoteOnCounter;
  29733. voice->currentlyPlayingSound = sound;
  29734. }
  29735. }
  29736. void Synthesiser::noteOff (const int midiChannel,
  29737. const int midiNoteNumber,
  29738. const bool allowTailOff)
  29739. {
  29740. const ScopedLock sl (lock);
  29741. for (int i = voices.size(); --i >= 0;)
  29742. {
  29743. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29744. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  29745. {
  29746. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  29747. if (sound != 0
  29748. && sound->appliesToNote (midiNoteNumber)
  29749. && sound->appliesToChannel (midiChannel))
  29750. {
  29751. voice->stopNote (allowTailOff);
  29752. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  29753. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  29754. }
  29755. }
  29756. }
  29757. }
  29758. void Synthesiser::allNotesOff (const int midiChannel,
  29759. const bool allowTailOff)
  29760. {
  29761. const ScopedLock sl (lock);
  29762. for (int i = voices.size(); --i >= 0;)
  29763. {
  29764. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29765. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29766. voice->stopNote (allowTailOff);
  29767. }
  29768. }
  29769. void Synthesiser::handlePitchWheel (const int midiChannel,
  29770. const int wheelValue)
  29771. {
  29772. const ScopedLock sl (lock);
  29773. for (int i = voices.size(); --i >= 0;)
  29774. {
  29775. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29776. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29777. {
  29778. voice->pitchWheelMoved (wheelValue);
  29779. }
  29780. }
  29781. }
  29782. void Synthesiser::handleController (const int midiChannel,
  29783. const int controllerNumber,
  29784. const int controllerValue)
  29785. {
  29786. const ScopedLock sl (lock);
  29787. for (int i = voices.size(); --i >= 0;)
  29788. {
  29789. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29790. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29791. voice->controllerMoved (controllerNumber, controllerValue);
  29792. }
  29793. }
  29794. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  29795. const bool stealIfNoneAvailable) const
  29796. {
  29797. const ScopedLock sl (lock);
  29798. for (int i = voices.size(); --i >= 0;)
  29799. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  29800. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  29801. return voices.getUnchecked (i);
  29802. if (stealIfNoneAvailable)
  29803. {
  29804. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  29805. SynthesiserVoice* oldest = 0;
  29806. for (int i = voices.size(); --i >= 0;)
  29807. {
  29808. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29809. if (voice->canPlaySound (soundToPlay)
  29810. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  29811. oldest = voice;
  29812. }
  29813. jassert (oldest != 0);
  29814. return oldest;
  29815. }
  29816. return 0;
  29817. }
  29818. END_JUCE_NAMESPACE
  29819. /*** End of inlined file: juce_Synthesiser.cpp ***/
  29820. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  29821. BEGIN_JUCE_NAMESPACE
  29822. ActionBroadcaster::ActionBroadcaster() throw()
  29823. {
  29824. // are you trying to create this object before or after juce has been intialised??
  29825. jassert (MessageManager::instance != 0);
  29826. }
  29827. ActionBroadcaster::~ActionBroadcaster()
  29828. {
  29829. // all event-based objects must be deleted BEFORE juce is shut down!
  29830. jassert (MessageManager::instance != 0);
  29831. }
  29832. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  29833. {
  29834. actionListenerList.addActionListener (listener);
  29835. }
  29836. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  29837. {
  29838. jassert (actionListenerList.isValidMessageListener());
  29839. if (actionListenerList.isValidMessageListener())
  29840. actionListenerList.removeActionListener (listener);
  29841. }
  29842. void ActionBroadcaster::removeAllActionListeners()
  29843. {
  29844. actionListenerList.removeAllActionListeners();
  29845. }
  29846. void ActionBroadcaster::sendActionMessage (const String& message) const
  29847. {
  29848. actionListenerList.sendActionMessage (message);
  29849. }
  29850. END_JUCE_NAMESPACE
  29851. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  29852. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  29853. BEGIN_JUCE_NAMESPACE
  29854. // special message of our own with a string in it
  29855. class ActionMessage : public Message
  29856. {
  29857. public:
  29858. const String message;
  29859. ActionMessage (const String& messageText,
  29860. void* const listener_) throw()
  29861. : message (messageText)
  29862. {
  29863. pointerParameter = listener_;
  29864. }
  29865. ~ActionMessage() throw()
  29866. {
  29867. }
  29868. private:
  29869. ActionMessage (const ActionMessage&);
  29870. ActionMessage& operator= (const ActionMessage&);
  29871. };
  29872. ActionListenerList::ActionListenerList() throw()
  29873. {
  29874. }
  29875. ActionListenerList::~ActionListenerList() throw()
  29876. {
  29877. }
  29878. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  29879. {
  29880. const ScopedLock sl (actionListenerLock_);
  29881. jassert (listener != 0);
  29882. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  29883. if (listener != 0)
  29884. actionListeners_.add (listener);
  29885. }
  29886. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  29887. {
  29888. const ScopedLock sl (actionListenerLock_);
  29889. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  29890. actionListeners_.removeValue (listener);
  29891. }
  29892. void ActionListenerList::removeAllActionListeners() throw()
  29893. {
  29894. const ScopedLock sl (actionListenerLock_);
  29895. actionListeners_.clear();
  29896. }
  29897. void ActionListenerList::sendActionMessage (const String& message) const
  29898. {
  29899. const ScopedLock sl (actionListenerLock_);
  29900. for (int i = actionListeners_.size(); --i >= 0;)
  29901. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  29902. }
  29903. void ActionListenerList::handleMessage (const Message& message)
  29904. {
  29905. const ActionMessage& am = (const ActionMessage&) message;
  29906. if (actionListeners_.contains (am.pointerParameter))
  29907. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  29908. }
  29909. END_JUCE_NAMESPACE
  29910. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  29911. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  29912. BEGIN_JUCE_NAMESPACE
  29913. AsyncUpdater::AsyncUpdater() throw()
  29914. : asyncMessagePending (false)
  29915. {
  29916. internalAsyncHandler.owner = this;
  29917. }
  29918. AsyncUpdater::~AsyncUpdater()
  29919. {
  29920. }
  29921. void AsyncUpdater::triggerAsyncUpdate() throw()
  29922. {
  29923. if (! asyncMessagePending)
  29924. {
  29925. asyncMessagePending = true;
  29926. internalAsyncHandler.postMessage (new Message());
  29927. }
  29928. }
  29929. void AsyncUpdater::cancelPendingUpdate() throw()
  29930. {
  29931. asyncMessagePending = false;
  29932. }
  29933. void AsyncUpdater::handleUpdateNowIfNeeded()
  29934. {
  29935. if (asyncMessagePending)
  29936. {
  29937. asyncMessagePending = false;
  29938. handleAsyncUpdate();
  29939. }
  29940. }
  29941. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  29942. {
  29943. owner->handleUpdateNowIfNeeded();
  29944. }
  29945. END_JUCE_NAMESPACE
  29946. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  29947. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  29948. BEGIN_JUCE_NAMESPACE
  29949. ChangeBroadcaster::ChangeBroadcaster() throw()
  29950. {
  29951. // are you trying to create this object before or after juce has been intialised??
  29952. jassert (MessageManager::instance != 0);
  29953. }
  29954. ChangeBroadcaster::~ChangeBroadcaster()
  29955. {
  29956. // all event-based objects must be deleted BEFORE juce is shut down!
  29957. jassert (MessageManager::instance != 0);
  29958. }
  29959. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  29960. {
  29961. changeListenerList.addChangeListener (listener);
  29962. }
  29963. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  29964. {
  29965. jassert (changeListenerList.isValidMessageListener());
  29966. if (changeListenerList.isValidMessageListener())
  29967. changeListenerList.removeChangeListener (listener);
  29968. }
  29969. void ChangeBroadcaster::removeAllChangeListeners() throw()
  29970. {
  29971. changeListenerList.removeAllChangeListeners();
  29972. }
  29973. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  29974. {
  29975. changeListenerList.sendChangeMessage (objectThatHasChanged);
  29976. }
  29977. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  29978. {
  29979. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  29980. }
  29981. void ChangeBroadcaster::dispatchPendingMessages()
  29982. {
  29983. changeListenerList.dispatchPendingMessages();
  29984. }
  29985. END_JUCE_NAMESPACE
  29986. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  29987. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  29988. BEGIN_JUCE_NAMESPACE
  29989. ChangeListenerList::ChangeListenerList() throw()
  29990. : lastChangedObject (0),
  29991. messagePending (false)
  29992. {
  29993. }
  29994. ChangeListenerList::~ChangeListenerList() throw()
  29995. {
  29996. }
  29997. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  29998. {
  29999. const ScopedLock sl (lock);
  30000. jassert (listener != 0);
  30001. if (listener != 0)
  30002. listeners.add (listener);
  30003. }
  30004. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  30005. {
  30006. const ScopedLock sl (lock);
  30007. listeners.removeValue (listener);
  30008. }
  30009. void ChangeListenerList::removeAllChangeListeners() throw()
  30010. {
  30011. const ScopedLock sl (lock);
  30012. listeners.clear();
  30013. }
  30014. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  30015. {
  30016. const ScopedLock sl (lock);
  30017. if ((! messagePending) && (listeners.size() > 0))
  30018. {
  30019. lastChangedObject = objectThatHasChanged;
  30020. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  30021. messagePending = true;
  30022. }
  30023. }
  30024. void ChangeListenerList::handleMessage (const Message& message)
  30025. {
  30026. sendSynchronousChangeMessage (message.pointerParameter);
  30027. }
  30028. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  30029. {
  30030. const ScopedLock sl (lock);
  30031. messagePending = false;
  30032. for (int i = listeners.size(); --i >= 0;)
  30033. {
  30034. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  30035. {
  30036. const ScopedUnlock tempUnlocker (lock);
  30037. l->changeListenerCallback (objectThatHasChanged);
  30038. }
  30039. i = jmin (i, listeners.size());
  30040. }
  30041. }
  30042. void ChangeListenerList::dispatchPendingMessages()
  30043. {
  30044. if (messagePending)
  30045. sendSynchronousChangeMessage (lastChangedObject);
  30046. }
  30047. END_JUCE_NAMESPACE
  30048. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  30049. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30050. BEGIN_JUCE_NAMESPACE
  30051. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30052. const uint32 magicMessageHeaderNumber)
  30053. : Thread ("Juce IPC connection"),
  30054. callbackConnectionState (false),
  30055. useMessageThread (callbacksOnMessageThread),
  30056. magicMessageHeader (magicMessageHeaderNumber),
  30057. pipeReceiveMessageTimeout (-1)
  30058. {
  30059. }
  30060. InterprocessConnection::~InterprocessConnection()
  30061. {
  30062. callbackConnectionState = false;
  30063. disconnect();
  30064. }
  30065. bool InterprocessConnection::connectToSocket (const String& hostName,
  30066. const int portNumber,
  30067. const int timeOutMillisecs)
  30068. {
  30069. disconnect();
  30070. const ScopedLock sl (pipeAndSocketLock);
  30071. socket = new StreamingSocket();
  30072. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30073. {
  30074. connectionMadeInt();
  30075. startThread();
  30076. return true;
  30077. }
  30078. else
  30079. {
  30080. socket = 0;
  30081. return false;
  30082. }
  30083. }
  30084. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30085. const int pipeReceiveMessageTimeoutMs)
  30086. {
  30087. disconnect();
  30088. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30089. if (newPipe->openExisting (pipeName))
  30090. {
  30091. const ScopedLock sl (pipeAndSocketLock);
  30092. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30093. initialiseWithPipe (newPipe.release());
  30094. return true;
  30095. }
  30096. return false;
  30097. }
  30098. bool InterprocessConnection::createPipe (const String& pipeName,
  30099. const int pipeReceiveMessageTimeoutMs)
  30100. {
  30101. disconnect();
  30102. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30103. if (newPipe->createNewPipe (pipeName))
  30104. {
  30105. const ScopedLock sl (pipeAndSocketLock);
  30106. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30107. initialiseWithPipe (newPipe.release());
  30108. return true;
  30109. }
  30110. return false;
  30111. }
  30112. void InterprocessConnection::disconnect()
  30113. {
  30114. if (socket != 0)
  30115. socket->close();
  30116. if (pipe != 0)
  30117. {
  30118. pipe->cancelPendingReads();
  30119. pipe->close();
  30120. }
  30121. stopThread (4000);
  30122. {
  30123. const ScopedLock sl (pipeAndSocketLock);
  30124. socket = 0;
  30125. pipe = 0;
  30126. }
  30127. connectionLostInt();
  30128. }
  30129. bool InterprocessConnection::isConnected() const
  30130. {
  30131. const ScopedLock sl (pipeAndSocketLock);
  30132. return ((socket != 0 && socket->isConnected())
  30133. || (pipe != 0 && pipe->isOpen()))
  30134. && isThreadRunning();
  30135. }
  30136. const String InterprocessConnection::getConnectedHostName() const
  30137. {
  30138. if (pipe != 0)
  30139. {
  30140. return "localhost";
  30141. }
  30142. else if (socket != 0)
  30143. {
  30144. if (! socket->isLocal())
  30145. return socket->getHostName();
  30146. return "localhost";
  30147. }
  30148. return String::empty;
  30149. }
  30150. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30151. {
  30152. uint32 messageHeader[2];
  30153. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30154. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30155. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30156. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30157. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30158. size_t bytesWritten = 0;
  30159. const ScopedLock sl (pipeAndSocketLock);
  30160. if (socket != 0)
  30161. {
  30162. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30163. }
  30164. else if (pipe != 0)
  30165. {
  30166. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30167. }
  30168. if (bytesWritten < 0)
  30169. {
  30170. // error..
  30171. return false;
  30172. }
  30173. return (bytesWritten == messageData.getSize());
  30174. }
  30175. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30176. {
  30177. jassert (socket == 0);
  30178. socket = socket_;
  30179. connectionMadeInt();
  30180. startThread();
  30181. }
  30182. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30183. {
  30184. jassert (pipe == 0);
  30185. pipe = pipe_;
  30186. connectionMadeInt();
  30187. startThread();
  30188. }
  30189. const int messageMagicNumber = 0xb734128b;
  30190. void InterprocessConnection::handleMessage (const Message& message)
  30191. {
  30192. if (message.intParameter1 == messageMagicNumber)
  30193. {
  30194. switch (message.intParameter2)
  30195. {
  30196. case 0:
  30197. {
  30198. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30199. messageReceived (*data);
  30200. break;
  30201. }
  30202. case 1:
  30203. connectionMade();
  30204. break;
  30205. case 2:
  30206. connectionLost();
  30207. break;
  30208. }
  30209. }
  30210. }
  30211. void InterprocessConnection::connectionMadeInt()
  30212. {
  30213. if (! callbackConnectionState)
  30214. {
  30215. callbackConnectionState = true;
  30216. if (useMessageThread)
  30217. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30218. else
  30219. connectionMade();
  30220. }
  30221. }
  30222. void InterprocessConnection::connectionLostInt()
  30223. {
  30224. if (callbackConnectionState)
  30225. {
  30226. callbackConnectionState = false;
  30227. if (useMessageThread)
  30228. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30229. else
  30230. connectionLost();
  30231. }
  30232. }
  30233. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30234. {
  30235. jassert (callbackConnectionState);
  30236. if (useMessageThread)
  30237. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30238. else
  30239. messageReceived (data);
  30240. }
  30241. bool InterprocessConnection::readNextMessageInt()
  30242. {
  30243. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30244. uint32 messageHeader[2];
  30245. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  30246. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  30247. if (bytes == sizeof (messageHeader)
  30248. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  30249. {
  30250. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  30251. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  30252. {
  30253. MemoryBlock messageData (bytesInMessage, true);
  30254. int bytesRead = 0;
  30255. while (bytesInMessage > 0)
  30256. {
  30257. if (threadShouldExit())
  30258. return false;
  30259. const int numThisTime = jmin (bytesInMessage, 65536);
  30260. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  30261. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  30262. if (bytesIn <= 0)
  30263. break;
  30264. bytesRead += bytesIn;
  30265. bytesInMessage -= bytesIn;
  30266. }
  30267. if (bytesRead >= 0)
  30268. deliverDataInt (messageData);
  30269. }
  30270. }
  30271. else if (bytes < 0)
  30272. {
  30273. {
  30274. const ScopedLock sl (pipeAndSocketLock);
  30275. socket = 0;
  30276. }
  30277. connectionLostInt();
  30278. return false;
  30279. }
  30280. return true;
  30281. }
  30282. void InterprocessConnection::run()
  30283. {
  30284. while (! threadShouldExit())
  30285. {
  30286. if (socket != 0)
  30287. {
  30288. const int ready = socket->waitUntilReady (true, 0);
  30289. if (ready < 0)
  30290. {
  30291. {
  30292. const ScopedLock sl (pipeAndSocketLock);
  30293. socket = 0;
  30294. }
  30295. connectionLostInt();
  30296. break;
  30297. }
  30298. else if (ready > 0)
  30299. {
  30300. if (! readNextMessageInt())
  30301. break;
  30302. }
  30303. else
  30304. {
  30305. Thread::sleep (2);
  30306. }
  30307. }
  30308. else if (pipe != 0)
  30309. {
  30310. if (! pipe->isOpen())
  30311. {
  30312. {
  30313. const ScopedLock sl (pipeAndSocketLock);
  30314. pipe = 0;
  30315. }
  30316. connectionLostInt();
  30317. break;
  30318. }
  30319. else
  30320. {
  30321. if (! readNextMessageInt())
  30322. break;
  30323. }
  30324. }
  30325. else
  30326. {
  30327. break;
  30328. }
  30329. }
  30330. }
  30331. END_JUCE_NAMESPACE
  30332. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  30333. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30334. BEGIN_JUCE_NAMESPACE
  30335. InterprocessConnectionServer::InterprocessConnectionServer()
  30336. : Thread ("Juce IPC server")
  30337. {
  30338. }
  30339. InterprocessConnectionServer::~InterprocessConnectionServer()
  30340. {
  30341. stop();
  30342. }
  30343. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  30344. {
  30345. stop();
  30346. socket = new StreamingSocket();
  30347. if (socket->createListener (portNumber))
  30348. {
  30349. startThread();
  30350. return true;
  30351. }
  30352. socket = 0;
  30353. return false;
  30354. }
  30355. void InterprocessConnectionServer::stop()
  30356. {
  30357. signalThreadShouldExit();
  30358. if (socket != 0)
  30359. socket->close();
  30360. stopThread (4000);
  30361. socket = 0;
  30362. }
  30363. void InterprocessConnectionServer::run()
  30364. {
  30365. while ((! threadShouldExit()) && socket != 0)
  30366. {
  30367. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  30368. if (clientSocket != 0)
  30369. {
  30370. InterprocessConnection* newConnection = createConnectionObject();
  30371. if (newConnection != 0)
  30372. newConnection->initialiseWithSocket (clientSocket.release());
  30373. }
  30374. }
  30375. }
  30376. END_JUCE_NAMESPACE
  30377. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30378. /*** Start of inlined file: juce_Message.cpp ***/
  30379. BEGIN_JUCE_NAMESPACE
  30380. Message::Message() throw()
  30381. : intParameter1 (0),
  30382. intParameter2 (0),
  30383. intParameter3 (0),
  30384. pointerParameter (0)
  30385. {
  30386. }
  30387. Message::Message (const int intParameter1_,
  30388. const int intParameter2_,
  30389. const int intParameter3_,
  30390. void* const pointerParameter_) throw()
  30391. : intParameter1 (intParameter1_),
  30392. intParameter2 (intParameter2_),
  30393. intParameter3 (intParameter3_),
  30394. pointerParameter (pointerParameter_)
  30395. {
  30396. }
  30397. Message::~Message() throw()
  30398. {
  30399. }
  30400. END_JUCE_NAMESPACE
  30401. /*** End of inlined file: juce_Message.cpp ***/
  30402. /*** Start of inlined file: juce_MessageListener.cpp ***/
  30403. BEGIN_JUCE_NAMESPACE
  30404. MessageListener::MessageListener() throw()
  30405. {
  30406. // are you trying to create a messagelistener before or after juce has been intialised??
  30407. jassert (MessageManager::instance != 0);
  30408. if (MessageManager::instance != 0)
  30409. MessageManager::instance->messageListeners.add (this);
  30410. }
  30411. MessageListener::~MessageListener()
  30412. {
  30413. if (MessageManager::instance != 0)
  30414. MessageManager::instance->messageListeners.removeValue (this);
  30415. }
  30416. void MessageListener::postMessage (Message* const message) const throw()
  30417. {
  30418. message->messageRecipient = const_cast <MessageListener*> (this);
  30419. if (MessageManager::instance == 0)
  30420. MessageManager::getInstance();
  30421. MessageManager::instance->postMessageToQueue (message);
  30422. }
  30423. bool MessageListener::isValidMessageListener() const throw()
  30424. {
  30425. return (MessageManager::instance != 0)
  30426. && MessageManager::instance->messageListeners.contains (this);
  30427. }
  30428. END_JUCE_NAMESPACE
  30429. /*** End of inlined file: juce_MessageListener.cpp ***/
  30430. /*** Start of inlined file: juce_MessageManager.cpp ***/
  30431. BEGIN_JUCE_NAMESPACE
  30432. // platform-specific functions..
  30433. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  30434. bool juce_postMessageToSystemQueue (Message* message);
  30435. MessageManager* MessageManager::instance = 0;
  30436. static const int quitMessageId = 0xfffff321;
  30437. MessageManager::MessageManager() throw()
  30438. : quitMessagePosted (false),
  30439. quitMessageReceived (false),
  30440. threadWithLock (0)
  30441. {
  30442. messageThreadId = Thread::getCurrentThreadId();
  30443. }
  30444. MessageManager::~MessageManager() throw()
  30445. {
  30446. broadcastListeners = 0;
  30447. doPlatformSpecificShutdown();
  30448. // If you hit this assertion, then you've probably leaked a Component or some other
  30449. // kind of MessageListener object...
  30450. jassert (messageListeners.size() == 0);
  30451. jassert (instance == this);
  30452. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  30453. }
  30454. MessageManager* MessageManager::getInstance() throw()
  30455. {
  30456. if (instance == 0)
  30457. {
  30458. instance = new MessageManager();
  30459. doPlatformSpecificInitialisation();
  30460. }
  30461. return instance;
  30462. }
  30463. void MessageManager::postMessageToQueue (Message* const message)
  30464. {
  30465. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  30466. delete message;
  30467. }
  30468. CallbackMessage::CallbackMessage() throw() {}
  30469. CallbackMessage::~CallbackMessage() throw() {}
  30470. void CallbackMessage::post()
  30471. {
  30472. if (MessageManager::instance != 0)
  30473. MessageManager::instance->postCallbackMessage (this);
  30474. }
  30475. void MessageManager::postCallbackMessage (Message* const message)
  30476. {
  30477. message->messageRecipient = 0;
  30478. postMessageToQueue (message);
  30479. }
  30480. // not for public use..
  30481. void MessageManager::deliverMessage (Message* const message)
  30482. {
  30483. const ScopedPointer <Message> messageDeleter (message);
  30484. MessageListener* const recipient = message->messageRecipient;
  30485. JUCE_TRY
  30486. {
  30487. if (messageListeners.contains (recipient))
  30488. {
  30489. recipient->handleMessage (*message);
  30490. }
  30491. else if (recipient == 0)
  30492. {
  30493. if (message->intParameter1 == quitMessageId)
  30494. {
  30495. quitMessageReceived = true;
  30496. }
  30497. else
  30498. {
  30499. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (message);
  30500. if (cm != 0)
  30501. cm->messageCallback();
  30502. }
  30503. }
  30504. }
  30505. JUCE_CATCH_EXCEPTION
  30506. }
  30507. #if ! (JUCE_MAC || JUCE_IOS)
  30508. void MessageManager::runDispatchLoop()
  30509. {
  30510. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30511. runDispatchLoopUntil (-1);
  30512. }
  30513. void MessageManager::stopDispatchLoop()
  30514. {
  30515. Message* const m = new Message (quitMessageId, 0, 0, 0);
  30516. m->messageRecipient = 0;
  30517. postMessageToQueue (m);
  30518. quitMessagePosted = true;
  30519. }
  30520. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  30521. {
  30522. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30523. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  30524. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  30525. && ! quitMessageReceived)
  30526. {
  30527. JUCE_TRY
  30528. {
  30529. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  30530. {
  30531. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  30532. if (msToWait > 0)
  30533. Thread::sleep (jmin (5, msToWait));
  30534. }
  30535. }
  30536. JUCE_CATCH_EXCEPTION
  30537. }
  30538. return ! quitMessageReceived;
  30539. }
  30540. #endif
  30541. void MessageManager::deliverBroadcastMessage (const String& value)
  30542. {
  30543. if (broadcastListeners != 0)
  30544. broadcastListeners->sendActionMessage (value);
  30545. }
  30546. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  30547. {
  30548. if (broadcastListeners == 0)
  30549. broadcastListeners = new ActionListenerList();
  30550. broadcastListeners->addActionListener (listener);
  30551. }
  30552. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  30553. {
  30554. if (broadcastListeners != 0)
  30555. broadcastListeners->removeActionListener (listener);
  30556. }
  30557. bool MessageManager::isThisTheMessageThread() const throw()
  30558. {
  30559. return Thread::getCurrentThreadId() == messageThreadId;
  30560. }
  30561. void MessageManager::setCurrentThreadAsMessageThread()
  30562. {
  30563. if (messageThreadId != Thread::getCurrentThreadId())
  30564. {
  30565. messageThreadId = Thread::getCurrentThreadId();
  30566. // This is needed on windows to make sure the message window is created by this thread
  30567. doPlatformSpecificShutdown();
  30568. doPlatformSpecificInitialisation();
  30569. }
  30570. }
  30571. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  30572. {
  30573. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  30574. return thisThread == messageThreadId || thisThread == threadWithLock;
  30575. }
  30576. /* The only safe way to lock the message thread while another thread does
  30577. some work is by posting a special message, whose purpose is to tie up the event
  30578. loop until the other thread has finished its business.
  30579. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  30580. get locked before making an event callback, because if the same OS lock gets indirectly
  30581. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  30582. in Cocoa).
  30583. */
  30584. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  30585. {
  30586. public:
  30587. SharedEvents() {}
  30588. ~SharedEvents() {}
  30589. /* This class just holds a couple of events to communicate between the BlockingMessage
  30590. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  30591. this shared data must be kept in a separate, ref-counted container. */
  30592. WaitableEvent lockedEvent, releaseEvent;
  30593. private:
  30594. SharedEvents (const SharedEvents&);
  30595. SharedEvents& operator= (const SharedEvents&);
  30596. };
  30597. class MessageManagerLock::BlockingMessage : public CallbackMessage
  30598. {
  30599. public:
  30600. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  30601. ~BlockingMessage() throw() {}
  30602. void messageCallback()
  30603. {
  30604. events->lockedEvent.signal();
  30605. events->releaseEvent.wait();
  30606. }
  30607. juce_UseDebuggingNewOperator
  30608. private:
  30609. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  30610. BlockingMessage (const BlockingMessage&);
  30611. BlockingMessage& operator= (const BlockingMessage&);
  30612. };
  30613. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck) throw()
  30614. : sharedEvents (0),
  30615. locked (false)
  30616. {
  30617. init (threadToCheck, 0);
  30618. }
  30619. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw()
  30620. : sharedEvents (0),
  30621. locked (false)
  30622. {
  30623. init (0, jobToCheckForExitSignal);
  30624. }
  30625. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job) throw()
  30626. {
  30627. if (MessageManager::instance != 0)
  30628. {
  30629. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  30630. {
  30631. locked = true; // either we're on the message thread, or this is a re-entrant call.
  30632. }
  30633. else
  30634. {
  30635. if (threadToCheck == 0 && job == 0)
  30636. {
  30637. MessageManager::instance->lockingLock.enter();
  30638. }
  30639. else
  30640. {
  30641. while (! MessageManager::instance->lockingLock.tryEnter())
  30642. {
  30643. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30644. || (job != 0 && job->shouldExit()))
  30645. return;
  30646. Thread::sleep (1);
  30647. }
  30648. }
  30649. sharedEvents = new SharedEvents();
  30650. sharedEvents->incReferenceCount();
  30651. (new BlockingMessage (sharedEvents))->post();
  30652. while (! sharedEvents->lockedEvent.wait (50))
  30653. {
  30654. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30655. || (job != 0 && job->shouldExit()))
  30656. {
  30657. sharedEvents->releaseEvent.signal();
  30658. sharedEvents->decReferenceCount();
  30659. sharedEvents = 0;
  30660. MessageManager::instance->lockingLock.exit();
  30661. return;
  30662. }
  30663. }
  30664. jassert (MessageManager::instance->threadWithLock == 0);
  30665. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  30666. locked = true;
  30667. }
  30668. }
  30669. }
  30670. MessageManagerLock::~MessageManagerLock() throw()
  30671. {
  30672. if (sharedEvents != 0)
  30673. {
  30674. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  30675. sharedEvents->releaseEvent.signal();
  30676. sharedEvents->decReferenceCount();
  30677. if (MessageManager::instance != 0)
  30678. {
  30679. MessageManager::instance->threadWithLock = 0;
  30680. MessageManager::instance->lockingLock.exit();
  30681. }
  30682. }
  30683. }
  30684. END_JUCE_NAMESPACE
  30685. /*** End of inlined file: juce_MessageManager.cpp ***/
  30686. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  30687. BEGIN_JUCE_NAMESPACE
  30688. class MultiTimer::MultiTimerCallback : public Timer
  30689. {
  30690. public:
  30691. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  30692. : timerId (timerId_),
  30693. owner (owner_)
  30694. {
  30695. }
  30696. ~MultiTimerCallback()
  30697. {
  30698. }
  30699. void timerCallback()
  30700. {
  30701. owner.timerCallback (timerId);
  30702. }
  30703. const int timerId;
  30704. private:
  30705. MultiTimer& owner;
  30706. };
  30707. MultiTimer::MultiTimer() throw()
  30708. {
  30709. }
  30710. MultiTimer::MultiTimer (const MultiTimer&) throw()
  30711. {
  30712. }
  30713. MultiTimer::~MultiTimer()
  30714. {
  30715. const ScopedLock sl (timerListLock);
  30716. timers.clear();
  30717. }
  30718. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  30719. {
  30720. const ScopedLock sl (timerListLock);
  30721. for (int i = timers.size(); --i >= 0;)
  30722. {
  30723. MultiTimerCallback* const t = timers.getUnchecked(i);
  30724. if (t->timerId == timerId)
  30725. {
  30726. t->startTimer (intervalInMilliseconds);
  30727. return;
  30728. }
  30729. }
  30730. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  30731. timers.add (newTimer);
  30732. newTimer->startTimer (intervalInMilliseconds);
  30733. }
  30734. void MultiTimer::stopTimer (const int timerId) throw()
  30735. {
  30736. const ScopedLock sl (timerListLock);
  30737. for (int i = timers.size(); --i >= 0;)
  30738. {
  30739. MultiTimerCallback* const t = timers.getUnchecked(i);
  30740. if (t->timerId == timerId)
  30741. t->stopTimer();
  30742. }
  30743. }
  30744. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  30745. {
  30746. const ScopedLock sl (timerListLock);
  30747. for (int i = timers.size(); --i >= 0;)
  30748. {
  30749. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30750. if (t->timerId == timerId)
  30751. return t->isTimerRunning();
  30752. }
  30753. return false;
  30754. }
  30755. int MultiTimer::getTimerInterval (const int timerId) const throw()
  30756. {
  30757. const ScopedLock sl (timerListLock);
  30758. for (int i = timers.size(); --i >= 0;)
  30759. {
  30760. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30761. if (t->timerId == timerId)
  30762. return t->getTimerInterval();
  30763. }
  30764. return 0;
  30765. }
  30766. END_JUCE_NAMESPACE
  30767. /*** End of inlined file: juce_MultiTimer.cpp ***/
  30768. /*** Start of inlined file: juce_Timer.cpp ***/
  30769. BEGIN_JUCE_NAMESPACE
  30770. class InternalTimerThread : private Thread,
  30771. private MessageListener,
  30772. private DeletedAtShutdown,
  30773. private AsyncUpdater
  30774. {
  30775. public:
  30776. InternalTimerThread()
  30777. : Thread ("Juce Timer"),
  30778. firstTimer (0),
  30779. callbackNeeded (0)
  30780. {
  30781. triggerAsyncUpdate();
  30782. }
  30783. ~InternalTimerThread() throw()
  30784. {
  30785. stopThread (4000);
  30786. jassert (instance == this || instance == 0);
  30787. if (instance == this)
  30788. instance = 0;
  30789. }
  30790. void run()
  30791. {
  30792. uint32 lastTime = Time::getMillisecondCounter();
  30793. while (! threadShouldExit())
  30794. {
  30795. const uint32 now = Time::getMillisecondCounter();
  30796. if (now <= lastTime)
  30797. {
  30798. wait (2);
  30799. continue;
  30800. }
  30801. const int elapsed = now - lastTime;
  30802. lastTime = now;
  30803. int timeUntilFirstTimer = 1000;
  30804. {
  30805. const ScopedLock sl (lock);
  30806. decrementAllCounters (elapsed);
  30807. if (firstTimer != 0)
  30808. timeUntilFirstTimer = firstTimer->countdownMs;
  30809. }
  30810. if (timeUntilFirstTimer <= 0)
  30811. {
  30812. /* If we managed to set the atomic boolean to true then send a message, this is needed
  30813. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  30814. but if it fails it means the message-thread changed the value from under us so at least
  30815. some processing is happenening and we can just loop around and try again
  30816. */
  30817. if (callbackNeeded.compareAndSetBool (1, 0))
  30818. {
  30819. postMessage (new Message());
  30820. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  30821. when the app has a modal loop), so this is how long to wait before assuming the
  30822. message has been lost and trying again.
  30823. */
  30824. const uint32 messageDeliveryTimeout = now + 2000;
  30825. while (callbackNeeded.get() != 0)
  30826. {
  30827. wait (4);
  30828. if (threadShouldExit())
  30829. return;
  30830. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  30831. break;
  30832. }
  30833. }
  30834. }
  30835. else
  30836. {
  30837. // don't wait for too long because running this loop also helps keep the
  30838. // Time::getApproximateMillisecondTimer value stay up-to-date
  30839. wait (jlimit (1, 50, timeUntilFirstTimer));
  30840. }
  30841. }
  30842. }
  30843. void callTimers()
  30844. {
  30845. const ScopedLock sl (lock);
  30846. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  30847. {
  30848. Timer* const t = firstTimer;
  30849. t->countdownMs = t->periodMs;
  30850. removeTimer (t);
  30851. addTimer (t);
  30852. const ScopedUnlock ul (lock);
  30853. JUCE_TRY
  30854. {
  30855. t->timerCallback();
  30856. }
  30857. JUCE_CATCH_EXCEPTION
  30858. }
  30859. /* This is needed as a memory barrier to make sure all processing of current timers is done
  30860. before the boolean is set. This set should never fail since if it was false in the first place,
  30861. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  30862. get a message then the value is true and the other thread can only set it to true again and
  30863. we will get another callback to set it to false.
  30864. */
  30865. callbackNeeded.set (0);
  30866. }
  30867. void handleMessage (const Message&)
  30868. {
  30869. callTimers();
  30870. }
  30871. void callTimersSynchronously()
  30872. {
  30873. if (! isThreadRunning())
  30874. {
  30875. // (This is relied on by some plugins in cases where the MM has
  30876. // had to restart and the async callback never started)
  30877. cancelPendingUpdate();
  30878. triggerAsyncUpdate();
  30879. }
  30880. callTimers();
  30881. }
  30882. static void callAnyTimersSynchronously()
  30883. {
  30884. if (InternalTimerThread::instance != 0)
  30885. InternalTimerThread::instance->callTimersSynchronously();
  30886. }
  30887. static inline void add (Timer* const tim) throw()
  30888. {
  30889. if (instance == 0)
  30890. instance = new InternalTimerThread();
  30891. const ScopedLock sl (instance->lock);
  30892. instance->addTimer (tim);
  30893. }
  30894. static inline void remove (Timer* const tim) throw()
  30895. {
  30896. if (instance != 0)
  30897. {
  30898. const ScopedLock sl (instance->lock);
  30899. instance->removeTimer (tim);
  30900. }
  30901. }
  30902. static inline void resetCounter (Timer* const tim,
  30903. const int newCounter) throw()
  30904. {
  30905. if (instance != 0)
  30906. {
  30907. tim->countdownMs = newCounter;
  30908. tim->periodMs = newCounter;
  30909. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  30910. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  30911. {
  30912. const ScopedLock sl (instance->lock);
  30913. instance->removeTimer (tim);
  30914. instance->addTimer (tim);
  30915. }
  30916. }
  30917. }
  30918. private:
  30919. friend class Timer;
  30920. static InternalTimerThread* instance;
  30921. static CriticalSection lock;
  30922. Timer* volatile firstTimer;
  30923. Atomic <int> callbackNeeded;
  30924. void addTimer (Timer* const t) throw()
  30925. {
  30926. #if JUCE_DEBUG
  30927. Timer* tt = firstTimer;
  30928. while (tt != 0)
  30929. {
  30930. // trying to add a timer that's already here - shouldn't get to this point,
  30931. // so if you get this assertion, let me know!
  30932. jassert (tt != t);
  30933. tt = tt->next;
  30934. }
  30935. jassert (t->previous == 0 && t->next == 0);
  30936. #endif
  30937. Timer* i = firstTimer;
  30938. if (i == 0 || i->countdownMs > t->countdownMs)
  30939. {
  30940. t->next = firstTimer;
  30941. firstTimer = t;
  30942. }
  30943. else
  30944. {
  30945. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  30946. i = i->next;
  30947. jassert (i != 0);
  30948. t->next = i->next;
  30949. t->previous = i;
  30950. i->next = t;
  30951. }
  30952. if (t->next != 0)
  30953. t->next->previous = t;
  30954. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  30955. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  30956. notify();
  30957. }
  30958. void removeTimer (Timer* const t) throw()
  30959. {
  30960. #if JUCE_DEBUG
  30961. Timer* tt = firstTimer;
  30962. bool found = false;
  30963. while (tt != 0)
  30964. {
  30965. if (tt == t)
  30966. {
  30967. found = true;
  30968. break;
  30969. }
  30970. tt = tt->next;
  30971. }
  30972. // trying to remove a timer that's not here - shouldn't get to this point,
  30973. // so if you get this assertion, let me know!
  30974. jassert (found);
  30975. #endif
  30976. if (t->previous != 0)
  30977. {
  30978. jassert (firstTimer != t);
  30979. t->previous->next = t->next;
  30980. }
  30981. else
  30982. {
  30983. jassert (firstTimer == t);
  30984. firstTimer = t->next;
  30985. }
  30986. if (t->next != 0)
  30987. t->next->previous = t->previous;
  30988. t->next = 0;
  30989. t->previous = 0;
  30990. }
  30991. void decrementAllCounters (const int numMillisecs) const
  30992. {
  30993. Timer* t = firstTimer;
  30994. while (t != 0)
  30995. {
  30996. t->countdownMs -= numMillisecs;
  30997. t = t->next;
  30998. }
  30999. }
  31000. void handleAsyncUpdate()
  31001. {
  31002. startThread (7);
  31003. }
  31004. InternalTimerThread (const InternalTimerThread&);
  31005. InternalTimerThread& operator= (const InternalTimerThread&);
  31006. };
  31007. InternalTimerThread* InternalTimerThread::instance = 0;
  31008. CriticalSection InternalTimerThread::lock;
  31009. void juce_callAnyTimersSynchronously()
  31010. {
  31011. InternalTimerThread::callAnyTimersSynchronously();
  31012. }
  31013. #if JUCE_DEBUG
  31014. static SortedSet <Timer*> activeTimers;
  31015. #endif
  31016. Timer::Timer() throw()
  31017. : countdownMs (0),
  31018. periodMs (0),
  31019. previous (0),
  31020. next (0)
  31021. {
  31022. #if JUCE_DEBUG
  31023. activeTimers.add (this);
  31024. #endif
  31025. }
  31026. Timer::Timer (const Timer&) throw()
  31027. : countdownMs (0),
  31028. periodMs (0),
  31029. previous (0),
  31030. next (0)
  31031. {
  31032. #if JUCE_DEBUG
  31033. activeTimers.add (this);
  31034. #endif
  31035. }
  31036. Timer::~Timer()
  31037. {
  31038. stopTimer();
  31039. #if JUCE_DEBUG
  31040. activeTimers.removeValue (this);
  31041. #endif
  31042. }
  31043. void Timer::startTimer (const int interval) throw()
  31044. {
  31045. const ScopedLock sl (InternalTimerThread::lock);
  31046. #if JUCE_DEBUG
  31047. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31048. jassert (activeTimers.contains (this));
  31049. #endif
  31050. if (periodMs == 0)
  31051. {
  31052. countdownMs = interval;
  31053. periodMs = jmax (1, interval);
  31054. InternalTimerThread::add (this);
  31055. }
  31056. else
  31057. {
  31058. InternalTimerThread::resetCounter (this, interval);
  31059. }
  31060. }
  31061. void Timer::stopTimer() throw()
  31062. {
  31063. const ScopedLock sl (InternalTimerThread::lock);
  31064. #if JUCE_DEBUG
  31065. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31066. jassert (activeTimers.contains (this));
  31067. #endif
  31068. if (periodMs > 0)
  31069. {
  31070. InternalTimerThread::remove (this);
  31071. periodMs = 0;
  31072. }
  31073. }
  31074. END_JUCE_NAMESPACE
  31075. /*** End of inlined file: juce_Timer.cpp ***/
  31076. #endif
  31077. #if JUCE_BUILD_GUI
  31078. /*** Start of inlined file: juce_Component.cpp ***/
  31079. BEGIN_JUCE_NAMESPACE
  31080. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31081. enum ComponentMessageNumbers
  31082. {
  31083. customCommandMessage = 0x7fff0001,
  31084. exitModalStateMessage = 0x7fff0002
  31085. };
  31086. static uint32 nextComponentUID = 0;
  31087. Component* Component::currentlyFocusedComponent = 0;
  31088. Component::Component()
  31089. : parentComponent_ (0),
  31090. componentUID (++nextComponentUID),
  31091. numDeepMouseListeners (0),
  31092. lookAndFeel_ (0),
  31093. effect_ (0),
  31094. bufferedImage_ (0),
  31095. mouseListeners_ (0),
  31096. keyListeners_ (0),
  31097. componentFlags_ (0)
  31098. {
  31099. }
  31100. Component::Component (const String& name)
  31101. : componentName_ (name),
  31102. parentComponent_ (0),
  31103. componentUID (++nextComponentUID),
  31104. numDeepMouseListeners (0),
  31105. lookAndFeel_ (0),
  31106. effect_ (0),
  31107. bufferedImage_ (0),
  31108. mouseListeners_ (0),
  31109. keyListeners_ (0),
  31110. componentFlags_ (0)
  31111. {
  31112. }
  31113. Component::~Component()
  31114. {
  31115. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31116. if (parentComponent_ != 0)
  31117. {
  31118. parentComponent_->removeChildComponent (this);
  31119. }
  31120. else if ((currentlyFocusedComponent == this)
  31121. || isParentOf (currentlyFocusedComponent))
  31122. {
  31123. giveAwayFocus();
  31124. }
  31125. if (flags.hasHeavyweightPeerFlag)
  31126. removeFromDesktop();
  31127. for (int i = childComponentList_.size(); --i >= 0;)
  31128. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  31129. delete mouseListeners_;
  31130. delete keyListeners_;
  31131. }
  31132. void Component::setName (const String& name)
  31133. {
  31134. // if component methods are being called from threads other than the message
  31135. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31136. checkMessageManagerIsLocked
  31137. if (componentName_ != name)
  31138. {
  31139. componentName_ = name;
  31140. if (flags.hasHeavyweightPeerFlag)
  31141. {
  31142. ComponentPeer* const peer = getPeer();
  31143. jassert (peer != 0);
  31144. if (peer != 0)
  31145. peer->setTitle (name);
  31146. }
  31147. BailOutChecker checker (this);
  31148. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31149. }
  31150. }
  31151. void Component::setVisible (bool shouldBeVisible)
  31152. {
  31153. if (flags.visibleFlag != shouldBeVisible)
  31154. {
  31155. // if component methods are being called from threads other than the message
  31156. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31157. checkMessageManagerIsLocked
  31158. SafePointer<Component> safePointer (this);
  31159. flags.visibleFlag = shouldBeVisible;
  31160. internalRepaint (0, 0, getWidth(), getHeight());
  31161. sendFakeMouseMove();
  31162. if (! shouldBeVisible)
  31163. {
  31164. if (currentlyFocusedComponent == this
  31165. || isParentOf (currentlyFocusedComponent))
  31166. {
  31167. if (parentComponent_ != 0)
  31168. parentComponent_->grabKeyboardFocus();
  31169. else
  31170. giveAwayFocus();
  31171. }
  31172. }
  31173. if (safePointer != 0)
  31174. {
  31175. sendVisibilityChangeMessage();
  31176. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  31177. {
  31178. ComponentPeer* const peer = getPeer();
  31179. jassert (peer != 0);
  31180. if (peer != 0)
  31181. {
  31182. peer->setVisible (shouldBeVisible);
  31183. internalHierarchyChanged();
  31184. }
  31185. }
  31186. }
  31187. }
  31188. }
  31189. void Component::visibilityChanged()
  31190. {
  31191. }
  31192. void Component::sendVisibilityChangeMessage()
  31193. {
  31194. BailOutChecker checker (this);
  31195. visibilityChanged();
  31196. if (! checker.shouldBailOut())
  31197. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  31198. }
  31199. bool Component::isShowing() const
  31200. {
  31201. if (flags.visibleFlag)
  31202. {
  31203. if (parentComponent_ != 0)
  31204. {
  31205. return parentComponent_->isShowing();
  31206. }
  31207. else
  31208. {
  31209. const ComponentPeer* const peer = getPeer();
  31210. return peer != 0 && ! peer->isMinimised();
  31211. }
  31212. }
  31213. return false;
  31214. }
  31215. class FadeOutProxyComponent : public Component,
  31216. public Timer
  31217. {
  31218. public:
  31219. FadeOutProxyComponent (Component* comp,
  31220. const int fadeLengthMs,
  31221. const int deltaXToMove,
  31222. const int deltaYToMove,
  31223. const float scaleFactorAtEnd)
  31224. : lastTime (0),
  31225. alpha (1.0f),
  31226. scale (1.0f)
  31227. {
  31228. image = comp->createComponentSnapshot (comp->getLocalBounds());
  31229. setBounds (comp->getBounds());
  31230. comp->getParentComponent()->addAndMakeVisible (this);
  31231. toBehind (comp);
  31232. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  31233. centreX = comp->getX() + comp->getWidth() * 0.5f;
  31234. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  31235. centreY = comp->getY() + comp->getHeight() * 0.5f;
  31236. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  31237. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  31238. setInterceptsMouseClicks (false, false);
  31239. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  31240. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  31241. }
  31242. ~FadeOutProxyComponent()
  31243. {
  31244. }
  31245. void paint (Graphics& g)
  31246. {
  31247. g.setOpacity (alpha);
  31248. g.drawImage (image,
  31249. 0, 0, getWidth(), getHeight(),
  31250. 0, 0, image.getWidth(), image.getHeight());
  31251. }
  31252. void timerCallback()
  31253. {
  31254. const uint32 now = Time::getMillisecondCounter();
  31255. if (lastTime == 0)
  31256. lastTime = now;
  31257. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  31258. lastTime = now;
  31259. alpha += alphaChangePerMs * msPassed;
  31260. if (alpha > 0)
  31261. {
  31262. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  31263. {
  31264. centreX += xChangePerMs * msPassed;
  31265. centreY += yChangePerMs * msPassed;
  31266. scale += scaleChangePerMs * msPassed;
  31267. const int w = roundToInt (image.getWidth() * scale);
  31268. const int h = roundToInt (image.getHeight() * scale);
  31269. setBounds (roundToInt (centreX) - w / 2,
  31270. roundToInt (centreY) - h / 2,
  31271. w, h);
  31272. }
  31273. repaint();
  31274. }
  31275. else
  31276. {
  31277. delete this;
  31278. }
  31279. }
  31280. juce_UseDebuggingNewOperator
  31281. private:
  31282. Image image;
  31283. uint32 lastTime;
  31284. float alpha, alphaChangePerMs;
  31285. float centreX, xChangePerMs;
  31286. float centreY, yChangePerMs;
  31287. float scale, scaleChangePerMs;
  31288. FadeOutProxyComponent (const FadeOutProxyComponent&);
  31289. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  31290. };
  31291. void Component::fadeOutComponent (const int millisecondsToFade,
  31292. const int deltaXToMove,
  31293. const int deltaYToMove,
  31294. const float scaleFactorAtEnd)
  31295. {
  31296. //xxx won't work for comps without parents
  31297. if (isShowing() && millisecondsToFade > 0)
  31298. new FadeOutProxyComponent (this, millisecondsToFade,
  31299. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  31300. setVisible (false);
  31301. }
  31302. bool Component::isValidComponent() const
  31303. {
  31304. return (this != 0) && isValidMessageListener();
  31305. }
  31306. void* Component::getWindowHandle() const
  31307. {
  31308. const ComponentPeer* const peer = getPeer();
  31309. if (peer != 0)
  31310. return peer->getNativeHandle();
  31311. return 0;
  31312. }
  31313. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  31314. {
  31315. // if component methods are being called from threads other than the message
  31316. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31317. checkMessageManagerIsLocked
  31318. if (isOpaque())
  31319. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  31320. else
  31321. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  31322. int currentStyleFlags = 0;
  31323. // don't use getPeer(), so that we only get the peer that's specifically
  31324. // for this comp, and not for one of its parents.
  31325. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  31326. if (peer != 0)
  31327. currentStyleFlags = peer->getStyleFlags();
  31328. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  31329. {
  31330. SafePointer<Component> safePointer (this);
  31331. #if JUCE_LINUX
  31332. // it's wise to give the component a non-zero size before
  31333. // putting it on the desktop, as X windows get confused by this, and
  31334. // a (1, 1) minimum size is enforced here.
  31335. setSize (jmax (1, getWidth()),
  31336. jmax (1, getHeight()));
  31337. #endif
  31338. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  31339. bool wasFullscreen = false;
  31340. bool wasMinimised = false;
  31341. ComponentBoundsConstrainer* currentConstainer = 0;
  31342. Rectangle<int> oldNonFullScreenBounds;
  31343. if (peer != 0)
  31344. {
  31345. wasFullscreen = peer->isFullScreen();
  31346. wasMinimised = peer->isMinimised();
  31347. currentConstainer = peer->getConstrainer();
  31348. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  31349. removeFromDesktop();
  31350. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  31351. }
  31352. if (parentComponent_ != 0)
  31353. parentComponent_->removeChildComponent (this);
  31354. if (safePointer != 0)
  31355. {
  31356. flags.hasHeavyweightPeerFlag = true;
  31357. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  31358. Desktop::getInstance().addDesktopComponent (this);
  31359. bounds_.setPosition (topLeft);
  31360. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  31361. peer->setVisible (isVisible());
  31362. if (wasFullscreen)
  31363. {
  31364. peer->setFullScreen (true);
  31365. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  31366. }
  31367. if (wasMinimised)
  31368. peer->setMinimised (true);
  31369. if (isAlwaysOnTop())
  31370. peer->setAlwaysOnTop (true);
  31371. peer->setConstrainer (currentConstainer);
  31372. repaint();
  31373. }
  31374. internalHierarchyChanged();
  31375. }
  31376. }
  31377. void Component::removeFromDesktop()
  31378. {
  31379. // if component methods are being called from threads other than the message
  31380. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31381. checkMessageManagerIsLocked
  31382. if (flags.hasHeavyweightPeerFlag)
  31383. {
  31384. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31385. flags.hasHeavyweightPeerFlag = false;
  31386. jassert (peer != 0);
  31387. delete peer;
  31388. Desktop::getInstance().removeDesktopComponent (this);
  31389. }
  31390. }
  31391. bool Component::isOnDesktop() const throw()
  31392. {
  31393. return flags.hasHeavyweightPeerFlag;
  31394. }
  31395. void Component::userTriedToCloseWindow()
  31396. {
  31397. /* This means that the user's trying to get rid of your window with the 'close window' system
  31398. menu option (on windows) or possibly the task manager - you should really handle this
  31399. and delete or hide your component in an appropriate way.
  31400. If you want to ignore the event and don't want to trigger this assertion, just override
  31401. this method and do nothing.
  31402. */
  31403. jassertfalse;
  31404. }
  31405. void Component::minimisationStateChanged (bool)
  31406. {
  31407. }
  31408. void Component::setOpaque (const bool shouldBeOpaque)
  31409. {
  31410. if (shouldBeOpaque != flags.opaqueFlag)
  31411. {
  31412. flags.opaqueFlag = shouldBeOpaque;
  31413. if (flags.hasHeavyweightPeerFlag)
  31414. {
  31415. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31416. if (peer != 0)
  31417. {
  31418. // to make it recreate the heavyweight window
  31419. addToDesktop (peer->getStyleFlags());
  31420. }
  31421. }
  31422. repaint();
  31423. }
  31424. }
  31425. bool Component::isOpaque() const throw()
  31426. {
  31427. return flags.opaqueFlag;
  31428. }
  31429. void Component::setBufferedToImage (const bool shouldBeBuffered)
  31430. {
  31431. if (shouldBeBuffered != flags.bufferToImageFlag)
  31432. {
  31433. bufferedImage_ = Image::null;
  31434. flags.bufferToImageFlag = shouldBeBuffered;
  31435. }
  31436. }
  31437. void Component::toFront (const bool setAsForeground)
  31438. {
  31439. // if component methods are being called from threads other than the message
  31440. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31441. checkMessageManagerIsLocked
  31442. if (flags.hasHeavyweightPeerFlag)
  31443. {
  31444. ComponentPeer* const peer = getPeer();
  31445. if (peer != 0)
  31446. {
  31447. peer->toFront (setAsForeground);
  31448. if (setAsForeground && ! hasKeyboardFocus (true))
  31449. grabKeyboardFocus();
  31450. }
  31451. }
  31452. else if (parentComponent_ != 0)
  31453. {
  31454. Array<Component*>& childList = parentComponent_->childComponentList_;
  31455. if (childList.getLast() != this)
  31456. {
  31457. const int index = childList.indexOf (this);
  31458. if (index >= 0)
  31459. {
  31460. int insertIndex = -1;
  31461. if (! flags.alwaysOnTopFlag)
  31462. {
  31463. insertIndex = childList.size() - 1;
  31464. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31465. --insertIndex;
  31466. }
  31467. if (index != insertIndex)
  31468. {
  31469. childList.move (index, insertIndex);
  31470. sendFakeMouseMove();
  31471. repaintParent();
  31472. }
  31473. }
  31474. }
  31475. if (setAsForeground)
  31476. {
  31477. internalBroughtToFront();
  31478. grabKeyboardFocus();
  31479. }
  31480. }
  31481. }
  31482. void Component::toBehind (Component* const other)
  31483. {
  31484. if (other != 0 && other != this)
  31485. {
  31486. // the two components must belong to the same parent..
  31487. jassert (parentComponent_ == other->parentComponent_);
  31488. if (parentComponent_ != 0)
  31489. {
  31490. Array<Component*>& childList = parentComponent_->childComponentList_;
  31491. const int index = childList.indexOf (this);
  31492. if (index >= 0 && childList [index + 1] != other)
  31493. {
  31494. int otherIndex = childList.indexOf (other);
  31495. if (otherIndex >= 0)
  31496. {
  31497. if (index < otherIndex)
  31498. --otherIndex;
  31499. childList.move (index, otherIndex);
  31500. sendFakeMouseMove();
  31501. repaintParent();
  31502. }
  31503. }
  31504. }
  31505. else if (isOnDesktop())
  31506. {
  31507. jassert (other->isOnDesktop());
  31508. if (other->isOnDesktop())
  31509. {
  31510. ComponentPeer* const us = getPeer();
  31511. ComponentPeer* const them = other->getPeer();
  31512. jassert (us != 0 && them != 0);
  31513. if (us != 0 && them != 0)
  31514. us->toBehind (them);
  31515. }
  31516. }
  31517. }
  31518. }
  31519. void Component::toBack()
  31520. {
  31521. Array<Component*>& childList = parentComponent_->childComponentList_;
  31522. if (isOnDesktop())
  31523. {
  31524. jassertfalse; //xxx need to add this to native window
  31525. }
  31526. else if (parentComponent_ != 0 && childList.getFirst() != this)
  31527. {
  31528. const int index = childList.indexOf (this);
  31529. if (index > 0)
  31530. {
  31531. int insertIndex = 0;
  31532. if (flags.alwaysOnTopFlag)
  31533. {
  31534. while (insertIndex < childList.size()
  31535. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31536. {
  31537. ++insertIndex;
  31538. }
  31539. }
  31540. if (index != insertIndex)
  31541. {
  31542. childList.move (index, insertIndex);
  31543. sendFakeMouseMove();
  31544. repaintParent();
  31545. }
  31546. }
  31547. }
  31548. }
  31549. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  31550. {
  31551. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  31552. {
  31553. flags.alwaysOnTopFlag = shouldStayOnTop;
  31554. if (isOnDesktop())
  31555. {
  31556. ComponentPeer* const peer = getPeer();
  31557. jassert (peer != 0);
  31558. if (peer != 0)
  31559. {
  31560. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  31561. {
  31562. // some kinds of peer can't change their always-on-top status, so
  31563. // for these, we'll need to create a new window
  31564. const int oldFlags = peer->getStyleFlags();
  31565. removeFromDesktop();
  31566. addToDesktop (oldFlags);
  31567. }
  31568. }
  31569. }
  31570. if (shouldStayOnTop)
  31571. toFront (false);
  31572. internalHierarchyChanged();
  31573. }
  31574. }
  31575. bool Component::isAlwaysOnTop() const throw()
  31576. {
  31577. return flags.alwaysOnTopFlag;
  31578. }
  31579. int Component::proportionOfWidth (const float proportion) const throw()
  31580. {
  31581. return roundToInt (proportion * bounds_.getWidth());
  31582. }
  31583. int Component::proportionOfHeight (const float proportion) const throw()
  31584. {
  31585. return roundToInt (proportion * bounds_.getHeight());
  31586. }
  31587. int Component::getParentWidth() const throw()
  31588. {
  31589. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  31590. : getParentMonitorArea().getWidth();
  31591. }
  31592. int Component::getParentHeight() const throw()
  31593. {
  31594. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  31595. : getParentMonitorArea().getHeight();
  31596. }
  31597. int Component::getScreenX() const
  31598. {
  31599. return getScreenPosition().getX();
  31600. }
  31601. int Component::getScreenY() const
  31602. {
  31603. return getScreenPosition().getY();
  31604. }
  31605. const Point<int> Component::getScreenPosition() const
  31606. {
  31607. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  31608. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  31609. : getPosition());
  31610. }
  31611. const Rectangle<int> Component::getScreenBounds() const
  31612. {
  31613. return bounds_.withPosition (getScreenPosition());
  31614. }
  31615. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  31616. {
  31617. const Component* c = this;
  31618. Point<int> p (relativePosition);
  31619. do
  31620. {
  31621. if (c->flags.hasHeavyweightPeerFlag)
  31622. return c->getPeer()->relativePositionToGlobal (p);
  31623. p += c->getPosition();
  31624. c = c->parentComponent_;
  31625. }
  31626. while (c != 0);
  31627. return p;
  31628. }
  31629. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  31630. {
  31631. if (flags.hasHeavyweightPeerFlag)
  31632. {
  31633. return getPeer()->globalPositionToRelative (screenPosition);
  31634. }
  31635. else
  31636. {
  31637. if (parentComponent_ != 0)
  31638. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  31639. return screenPosition - getPosition();
  31640. }
  31641. }
  31642. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  31643. {
  31644. Point<int> p (positionRelativeToThis);
  31645. if (targetComponent != 0)
  31646. {
  31647. const Component* c = this;
  31648. do
  31649. {
  31650. if (c == targetComponent)
  31651. return p;
  31652. if (c->flags.hasHeavyweightPeerFlag)
  31653. {
  31654. p = c->getPeer()->relativePositionToGlobal (p);
  31655. break;
  31656. }
  31657. p += c->getPosition();
  31658. c = c->parentComponent_;
  31659. }
  31660. while (c != 0);
  31661. p = targetComponent->globalPositionToRelative (p);
  31662. }
  31663. return p;
  31664. }
  31665. void Component::setBounds (const int x, const int y, int w, int h)
  31666. {
  31667. // if component methods are being called from threads other than the message
  31668. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31669. checkMessageManagerIsLocked
  31670. if (w < 0) w = 0;
  31671. if (h < 0) h = 0;
  31672. const bool wasResized = (getWidth() != w || getHeight() != h);
  31673. const bool wasMoved = (getX() != x || getY() != y);
  31674. #if JUCE_DEBUG
  31675. // It's a very bad idea to try to resize a window during its paint() method!
  31676. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  31677. #endif
  31678. if (wasMoved || wasResized)
  31679. {
  31680. if (flags.visibleFlag)
  31681. {
  31682. // send a fake mouse move to trigger enter/exit messages if needed..
  31683. sendFakeMouseMove();
  31684. if (! flags.hasHeavyweightPeerFlag)
  31685. repaintParent();
  31686. }
  31687. bounds_.setBounds (x, y, w, h);
  31688. if (wasResized)
  31689. repaint();
  31690. else if (! flags.hasHeavyweightPeerFlag)
  31691. repaintParent();
  31692. if (flags.hasHeavyweightPeerFlag)
  31693. {
  31694. ComponentPeer* const peer = getPeer();
  31695. if (peer != 0)
  31696. {
  31697. if (wasMoved && wasResized)
  31698. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  31699. else if (wasMoved)
  31700. peer->setPosition (getX(), getY());
  31701. else if (wasResized)
  31702. peer->setSize (getWidth(), getHeight());
  31703. }
  31704. }
  31705. sendMovedResizedMessages (wasMoved, wasResized);
  31706. }
  31707. }
  31708. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  31709. {
  31710. JUCE_TRY
  31711. {
  31712. if (wasMoved)
  31713. moved();
  31714. if (wasResized)
  31715. {
  31716. resized();
  31717. for (int i = childComponentList_.size(); --i >= 0;)
  31718. {
  31719. childComponentList_.getUnchecked(i)->parentSizeChanged();
  31720. i = jmin (i, childComponentList_.size());
  31721. }
  31722. }
  31723. BailOutChecker checker (this);
  31724. if (parentComponent_ != 0)
  31725. parentComponent_->childBoundsChanged (this);
  31726. if (! checker.shouldBailOut())
  31727. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  31728. *this, wasMoved, wasResized);
  31729. }
  31730. JUCE_CATCH_EXCEPTION
  31731. }
  31732. void Component::setSize (const int w, const int h)
  31733. {
  31734. setBounds (getX(), getY(), w, h);
  31735. }
  31736. void Component::setTopLeftPosition (const int x, const int y)
  31737. {
  31738. setBounds (x, y, getWidth(), getHeight());
  31739. }
  31740. void Component::setTopRightPosition (const int x, const int y)
  31741. {
  31742. setTopLeftPosition (x - getWidth(), y);
  31743. }
  31744. void Component::setBounds (const Rectangle<int>& r)
  31745. {
  31746. setBounds (r.getX(),
  31747. r.getY(),
  31748. r.getWidth(),
  31749. r.getHeight());
  31750. }
  31751. void Component::setBoundsRelative (const float x, const float y,
  31752. const float w, const float h)
  31753. {
  31754. const int pw = getParentWidth();
  31755. const int ph = getParentHeight();
  31756. setBounds (roundToInt (x * pw),
  31757. roundToInt (y * ph),
  31758. roundToInt (w * pw),
  31759. roundToInt (h * ph));
  31760. }
  31761. void Component::setCentrePosition (const int x, const int y)
  31762. {
  31763. setTopLeftPosition (x - getWidth() / 2,
  31764. y - getHeight() / 2);
  31765. }
  31766. void Component::setCentreRelative (const float x, const float y)
  31767. {
  31768. setCentrePosition (roundToInt (getParentWidth() * x),
  31769. roundToInt (getParentHeight() * y));
  31770. }
  31771. void Component::centreWithSize (const int width, const int height)
  31772. {
  31773. const Rectangle<int> parentArea (getParentOrMainMonitorBounds());
  31774. setBounds (parentArea.getCentreX() - width / 2,
  31775. parentArea.getCentreY() - height / 2,
  31776. width, height);
  31777. }
  31778. void Component::setBoundsInset (const BorderSize& borders)
  31779. {
  31780. setBounds (borders.subtractedFrom (getParentOrMainMonitorBounds()));
  31781. }
  31782. void Component::setBoundsToFit (int x, int y, int width, int height,
  31783. const Justification& justification,
  31784. const bool onlyReduceInSize)
  31785. {
  31786. // it's no good calling this method unless both the component and
  31787. // target rectangle have a finite size.
  31788. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  31789. if (getWidth() > 0 && getHeight() > 0
  31790. && width > 0 && height > 0)
  31791. {
  31792. int newW, newH;
  31793. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  31794. {
  31795. newW = getWidth();
  31796. newH = getHeight();
  31797. }
  31798. else
  31799. {
  31800. const double imageRatio = getHeight() / (double) getWidth();
  31801. const double targetRatio = height / (double) width;
  31802. if (imageRatio <= targetRatio)
  31803. {
  31804. newW = width;
  31805. newH = jmin (height, roundToInt (newW * imageRatio));
  31806. }
  31807. else
  31808. {
  31809. newH = height;
  31810. newW = jmin (width, roundToInt (newH / imageRatio));
  31811. }
  31812. }
  31813. if (newW > 0 && newH > 0)
  31814. {
  31815. int newX, newY;
  31816. justification.applyToRectangle (newX, newY, newW, newH,
  31817. x, y, width, height);
  31818. setBounds (newX, newY, newW, newH);
  31819. }
  31820. }
  31821. }
  31822. bool Component::hitTest (int x, int y)
  31823. {
  31824. if (! flags.ignoresMouseClicksFlag)
  31825. return true;
  31826. if (flags.allowChildMouseClicksFlag)
  31827. {
  31828. for (int i = getNumChildComponents(); --i >= 0;)
  31829. {
  31830. Component* const c = getChildComponent (i);
  31831. if (c->isVisible()
  31832. && c->bounds_.contains (x, y)
  31833. && c->hitTest (x - c->getX(),
  31834. y - c->getY()))
  31835. {
  31836. return true;
  31837. }
  31838. }
  31839. }
  31840. return false;
  31841. }
  31842. void Component::setInterceptsMouseClicks (const bool allowClicks,
  31843. const bool allowClicksOnChildComponents) throw()
  31844. {
  31845. flags.ignoresMouseClicksFlag = ! allowClicks;
  31846. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  31847. }
  31848. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  31849. bool& allowsClicksOnChildComponents) const throw()
  31850. {
  31851. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  31852. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  31853. }
  31854. bool Component::contains (const int x, const int y)
  31855. {
  31856. if (((unsigned int) x) < (unsigned int) getWidth()
  31857. && ((unsigned int) y) < (unsigned int) getHeight()
  31858. && hitTest (x, y))
  31859. {
  31860. if (parentComponent_ != 0)
  31861. {
  31862. return parentComponent_->contains (x + getX(),
  31863. y + getY());
  31864. }
  31865. else if (flags.hasHeavyweightPeerFlag)
  31866. {
  31867. const ComponentPeer* const peer = getPeer();
  31868. if (peer != 0)
  31869. return peer->contains (Point<int> (x, y), true);
  31870. }
  31871. }
  31872. return false;
  31873. }
  31874. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  31875. {
  31876. if (! contains (x, y))
  31877. return false;
  31878. Component* p = this;
  31879. while (p->parentComponent_ != 0)
  31880. {
  31881. x += p->getX();
  31882. y += p->getY();
  31883. p = p->parentComponent_;
  31884. }
  31885. const Component* const c = p->getComponentAt (x, y);
  31886. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  31887. }
  31888. Component* Component::getComponentAt (const Point<int>& position)
  31889. {
  31890. return getComponentAt (position.getX(), position.getY());
  31891. }
  31892. Component* Component::getComponentAt (const int x, const int y)
  31893. {
  31894. if (flags.visibleFlag
  31895. && ((unsigned int) x) < (unsigned int) getWidth()
  31896. && ((unsigned int) y) < (unsigned int) getHeight()
  31897. && hitTest (x, y))
  31898. {
  31899. for (int i = childComponentList_.size(); --i >= 0;)
  31900. {
  31901. Component* const child = childComponentList_.getUnchecked(i);
  31902. Component* const c = child->getComponentAt (x - child->getX(),
  31903. y - child->getY());
  31904. if (c != 0)
  31905. return c;
  31906. }
  31907. return this;
  31908. }
  31909. return 0;
  31910. }
  31911. void Component::addChildComponent (Component* const child, int zOrder)
  31912. {
  31913. // if component methods are being called from threads other than the message
  31914. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31915. checkMessageManagerIsLocked
  31916. if (child != 0 && child->parentComponent_ != this)
  31917. {
  31918. if (child->parentComponent_ != 0)
  31919. child->parentComponent_->removeChildComponent (child);
  31920. else
  31921. child->removeFromDesktop();
  31922. child->parentComponent_ = this;
  31923. if (child->isVisible())
  31924. child->repaintParent();
  31925. if (! child->isAlwaysOnTop())
  31926. {
  31927. if (zOrder < 0 || zOrder > childComponentList_.size())
  31928. zOrder = childComponentList_.size();
  31929. while (zOrder > 0)
  31930. {
  31931. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  31932. break;
  31933. --zOrder;
  31934. }
  31935. }
  31936. childComponentList_.insert (zOrder, child);
  31937. child->internalHierarchyChanged();
  31938. internalChildrenChanged();
  31939. }
  31940. }
  31941. void Component::addAndMakeVisible (Component* const child, int zOrder)
  31942. {
  31943. if (child != 0)
  31944. {
  31945. child->setVisible (true);
  31946. addChildComponent (child, zOrder);
  31947. }
  31948. }
  31949. void Component::removeChildComponent (Component* const child)
  31950. {
  31951. removeChildComponent (childComponentList_.indexOf (child));
  31952. }
  31953. Component* Component::removeChildComponent (const int index)
  31954. {
  31955. // if component methods are being called from threads other than the message
  31956. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31957. checkMessageManagerIsLocked
  31958. Component* const child = childComponentList_ [index];
  31959. if (child != 0)
  31960. {
  31961. sendFakeMouseMove();
  31962. child->repaintParent();
  31963. childComponentList_.remove (index);
  31964. child->parentComponent_ = 0;
  31965. JUCE_TRY
  31966. {
  31967. if ((currentlyFocusedComponent == child)
  31968. || child->isParentOf (currentlyFocusedComponent))
  31969. {
  31970. // get rid first to force the grabKeyboardFocus to change to us.
  31971. giveAwayFocus();
  31972. grabKeyboardFocus();
  31973. }
  31974. }
  31975. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31976. catch (const std::exception& e)
  31977. {
  31978. currentlyFocusedComponent = 0;
  31979. Desktop::getInstance().triggerFocusCallback();
  31980. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31981. }
  31982. catch (...)
  31983. {
  31984. currentlyFocusedComponent = 0;
  31985. Desktop::getInstance().triggerFocusCallback();
  31986. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31987. }
  31988. #endif
  31989. child->internalHierarchyChanged();
  31990. internalChildrenChanged();
  31991. }
  31992. return child;
  31993. }
  31994. void Component::removeAllChildren()
  31995. {
  31996. while (childComponentList_.size() > 0)
  31997. removeChildComponent (childComponentList_.size() - 1);
  31998. }
  31999. void Component::deleteAllChildren()
  32000. {
  32001. while (childComponentList_.size() > 0)
  32002. delete (removeChildComponent (childComponentList_.size() - 1));
  32003. }
  32004. int Component::getNumChildComponents() const throw()
  32005. {
  32006. return childComponentList_.size();
  32007. }
  32008. Component* Component::getChildComponent (const int index) const throw()
  32009. {
  32010. return childComponentList_ [index];
  32011. }
  32012. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32013. {
  32014. return childComponentList_.indexOf (const_cast <Component*> (child));
  32015. }
  32016. Component* Component::getTopLevelComponent() const throw()
  32017. {
  32018. const Component* comp = this;
  32019. while (comp->parentComponent_ != 0)
  32020. comp = comp->parentComponent_;
  32021. return const_cast <Component*> (comp);
  32022. }
  32023. bool Component::isParentOf (const Component* possibleChild) const throw()
  32024. {
  32025. if (! possibleChild->isValidComponent())
  32026. {
  32027. jassert (possibleChild == 0);
  32028. return false;
  32029. }
  32030. while (possibleChild != 0)
  32031. {
  32032. possibleChild = possibleChild->parentComponent_;
  32033. if (possibleChild == this)
  32034. return true;
  32035. }
  32036. return false;
  32037. }
  32038. void Component::parentHierarchyChanged()
  32039. {
  32040. }
  32041. void Component::childrenChanged()
  32042. {
  32043. }
  32044. void Component::internalChildrenChanged()
  32045. {
  32046. if (componentListeners.isEmpty())
  32047. {
  32048. childrenChanged();
  32049. }
  32050. else
  32051. {
  32052. BailOutChecker checker (this);
  32053. childrenChanged();
  32054. if (! checker.shouldBailOut())
  32055. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32056. }
  32057. }
  32058. void Component::internalHierarchyChanged()
  32059. {
  32060. BailOutChecker checker (this);
  32061. parentHierarchyChanged();
  32062. if (checker.shouldBailOut())
  32063. return;
  32064. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32065. if (checker.shouldBailOut())
  32066. return;
  32067. for (int i = childComponentList_.size(); --i >= 0;)
  32068. {
  32069. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  32070. if (checker.shouldBailOut())
  32071. {
  32072. // you really shouldn't delete the parent component during a callback telling you
  32073. // that it's changed..
  32074. jassertfalse;
  32075. return;
  32076. }
  32077. i = jmin (i, childComponentList_.size());
  32078. }
  32079. }
  32080. void* Component::runModalLoopCallback (void* userData)
  32081. {
  32082. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32083. }
  32084. int Component::runModalLoop()
  32085. {
  32086. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32087. {
  32088. // use a callback so this can be called from non-gui threads
  32089. return (int) (pointer_sized_int) MessageManager::getInstance()
  32090. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  32091. }
  32092. if (! isCurrentlyModal())
  32093. enterModalState (true);
  32094. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32095. }
  32096. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  32097. {
  32098. // if component methods are being called from threads other than the message
  32099. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32100. checkMessageManagerIsLocked
  32101. // Check for an attempt to make a component modal when it already is!
  32102. // This can cause nasty problems..
  32103. jassert (! flags.currentlyModalFlag);
  32104. if (! isCurrentlyModal())
  32105. {
  32106. ModalComponentManager::getInstance()->startModal (this, callback);
  32107. flags.currentlyModalFlag = true;
  32108. setVisible (true);
  32109. if (takeKeyboardFocus_)
  32110. grabKeyboardFocus();
  32111. }
  32112. }
  32113. void Component::exitModalState (const int returnValue)
  32114. {
  32115. if (isCurrentlyModal())
  32116. {
  32117. if (MessageManager::getInstance()->isThisTheMessageThread())
  32118. {
  32119. ModalComponentManager::getInstance()->endModal (this, returnValue);
  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 ModalComponentManager::getInstance()->getNumModalComponents();
  32145. }
  32146. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32147. {
  32148. return ModalComponentManager::getInstance()->getModalComponent (index);
  32149. }
  32150. void Component::bringModalComponentToFront()
  32151. {
  32152. ComponentPeer* lastOne = 0;
  32153. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  32154. {
  32155. Component* const c = getCurrentlyModalComponent (i);
  32156. if (c == 0)
  32157. break;
  32158. ComponentPeer* peer = c->getPeer();
  32159. if (peer != 0 && peer != lastOne)
  32160. {
  32161. if (lastOne == 0)
  32162. {
  32163. peer->toFront (true);
  32164. peer->grabFocus();
  32165. }
  32166. else
  32167. peer->toBehind (lastOne);
  32168. lastOne = peer;
  32169. }
  32170. }
  32171. }
  32172. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  32173. {
  32174. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  32175. }
  32176. bool Component::isBroughtToFrontOnMouseClick() const throw()
  32177. {
  32178. return flags.bringToFrontOnClickFlag;
  32179. }
  32180. void Component::setMouseCursor (const MouseCursor& cursor)
  32181. {
  32182. if (cursor_ != cursor)
  32183. {
  32184. cursor_ = cursor;
  32185. if (flags.visibleFlag)
  32186. updateMouseCursor();
  32187. }
  32188. }
  32189. const MouseCursor Component::getMouseCursor()
  32190. {
  32191. return cursor_;
  32192. }
  32193. void Component::updateMouseCursor() const
  32194. {
  32195. sendFakeMouseMove();
  32196. }
  32197. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  32198. {
  32199. flags.repaintOnMouseActivityFlag = shouldRepaint;
  32200. }
  32201. void Component::repaintParent()
  32202. {
  32203. if (flags.visibleFlag)
  32204. internalRepaint (0, 0, getWidth(), getHeight());
  32205. }
  32206. void Component::repaint()
  32207. {
  32208. repaint (0, 0, getWidth(), getHeight());
  32209. }
  32210. void Component::repaint (const int x, const int y,
  32211. const int w, const int h)
  32212. {
  32213. bufferedImage_ = Image::null;
  32214. if (flags.visibleFlag)
  32215. internalRepaint (x, y, w, h);
  32216. }
  32217. void Component::repaint (const Rectangle<int>& area)
  32218. {
  32219. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  32220. }
  32221. void Component::internalRepaint (int x, int y, int w, int h)
  32222. {
  32223. // if component methods are being called from threads other than the message
  32224. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32225. checkMessageManagerIsLocked
  32226. if (x < 0)
  32227. {
  32228. w += x;
  32229. x = 0;
  32230. }
  32231. if (x + w > getWidth())
  32232. w = getWidth() - x;
  32233. if (w > 0)
  32234. {
  32235. if (y < 0)
  32236. {
  32237. h += y;
  32238. y = 0;
  32239. }
  32240. if (y + h > getHeight())
  32241. h = getHeight() - y;
  32242. if (h > 0)
  32243. {
  32244. if (parentComponent_ != 0)
  32245. {
  32246. x += getX();
  32247. y += getY();
  32248. if (parentComponent_->flags.visibleFlag)
  32249. parentComponent_->internalRepaint (x, y, w, h);
  32250. }
  32251. else if (flags.hasHeavyweightPeerFlag)
  32252. {
  32253. ComponentPeer* const peer = getPeer();
  32254. if (peer != 0)
  32255. peer->repaint (Rectangle<int> (x, y, w, h));
  32256. }
  32257. }
  32258. }
  32259. }
  32260. void Component::renderComponent (Graphics& g)
  32261. {
  32262. const Rectangle<int> clipBounds (g.getClipBounds());
  32263. g.saveState();
  32264. clipObscuredRegions (g, clipBounds, 0, 0);
  32265. if (! g.isClipEmpty())
  32266. {
  32267. if (flags.bufferToImageFlag)
  32268. {
  32269. if (bufferedImage_.isNull())
  32270. {
  32271. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32272. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  32273. Graphics imG (bufferedImage_);
  32274. paint (imG);
  32275. }
  32276. g.setColour (Colours::black);
  32277. g.drawImageAt (bufferedImage_, 0, 0);
  32278. }
  32279. else
  32280. {
  32281. paint (g);
  32282. }
  32283. }
  32284. g.restoreState();
  32285. for (int i = 0; i < childComponentList_.size(); ++i)
  32286. {
  32287. Component* const child = childComponentList_.getUnchecked (i);
  32288. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  32289. {
  32290. g.saveState();
  32291. if (g.reduceClipRegion (child->getX(), child->getY(),
  32292. child->getWidth(), child->getHeight()))
  32293. {
  32294. for (int j = i + 1; j < childComponentList_.size(); ++j)
  32295. {
  32296. const Component* const sibling = childComponentList_.getUnchecked (j);
  32297. if (sibling->flags.opaqueFlag && sibling->isVisible())
  32298. g.excludeClipRegion (sibling->getBounds());
  32299. }
  32300. if (! g.isClipEmpty())
  32301. {
  32302. g.setOrigin (child->getX(), child->getY());
  32303. child->paintEntireComponent (g);
  32304. }
  32305. }
  32306. g.restoreState();
  32307. }
  32308. }
  32309. g.saveState();
  32310. paintOverChildren (g);
  32311. g.restoreState();
  32312. }
  32313. void Component::paintEntireComponent (Graphics& g)
  32314. {
  32315. jassert (! g.isClipEmpty());
  32316. #if JUCE_DEBUG
  32317. flags.isInsidePaintCall = true;
  32318. #endif
  32319. if (effect_ != 0)
  32320. {
  32321. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32322. getWidth(), getHeight(),
  32323. ! flags.opaqueFlag, Image::NativeImage);
  32324. {
  32325. Graphics g2 (effectImage);
  32326. renderComponent (g2);
  32327. }
  32328. effect_->applyEffect (effectImage, g);
  32329. }
  32330. else
  32331. {
  32332. renderComponent (g);
  32333. }
  32334. #if JUCE_DEBUG
  32335. flags.isInsidePaintCall = false;
  32336. #endif
  32337. }
  32338. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  32339. const bool clipImageToComponentBounds)
  32340. {
  32341. Rectangle<int> r (areaToGrab);
  32342. if (clipImageToComponentBounds)
  32343. r = r.getIntersection (getLocalBounds());
  32344. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32345. jmax (1, r.getWidth()),
  32346. jmax (1, r.getHeight()),
  32347. true);
  32348. Graphics imageContext (componentImage);
  32349. imageContext.setOrigin (-r.getX(), -r.getY());
  32350. paintEntireComponent (imageContext);
  32351. return componentImage;
  32352. }
  32353. void Component::setComponentEffect (ImageEffectFilter* const effect)
  32354. {
  32355. if (effect_ != effect)
  32356. {
  32357. effect_ = effect;
  32358. repaint();
  32359. }
  32360. }
  32361. LookAndFeel& Component::getLookAndFeel() const throw()
  32362. {
  32363. const Component* c = this;
  32364. do
  32365. {
  32366. if (c->lookAndFeel_ != 0)
  32367. return *(c->lookAndFeel_);
  32368. c = c->parentComponent_;
  32369. }
  32370. while (c != 0);
  32371. return LookAndFeel::getDefaultLookAndFeel();
  32372. }
  32373. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  32374. {
  32375. if (lookAndFeel_ != newLookAndFeel)
  32376. {
  32377. lookAndFeel_ = newLookAndFeel;
  32378. sendLookAndFeelChange();
  32379. }
  32380. }
  32381. void Component::lookAndFeelChanged()
  32382. {
  32383. }
  32384. void Component::sendLookAndFeelChange()
  32385. {
  32386. repaint();
  32387. lookAndFeelChanged();
  32388. // (it's not a great idea to do anything that would delete this component
  32389. // during the lookAndFeelChanged() callback)
  32390. jassert (isValidComponent());
  32391. SafePointer<Component> safePointer (this);
  32392. for (int i = childComponentList_.size(); --i >= 0;)
  32393. {
  32394. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  32395. if (safePointer == 0)
  32396. return;
  32397. i = jmin (i, childComponentList_.size());
  32398. }
  32399. }
  32400. static const Identifier getColourPropertyId (const int colourId)
  32401. {
  32402. String s;
  32403. s.preallocateStorage (18);
  32404. s << "jcclr_" << String::toHexString (colourId);
  32405. return s;
  32406. }
  32407. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  32408. {
  32409. var* v = properties.getItem (getColourPropertyId (colourId));
  32410. if (v != 0)
  32411. return Colour ((int) *v);
  32412. if (inheritFromParent && parentComponent_ != 0)
  32413. return parentComponent_->findColour (colourId, true);
  32414. return getLookAndFeel().findColour (colourId);
  32415. }
  32416. bool Component::isColourSpecified (const int colourId) const
  32417. {
  32418. return properties.contains (getColourPropertyId (colourId));
  32419. }
  32420. void Component::removeColour (const int colourId)
  32421. {
  32422. if (properties.remove (getColourPropertyId (colourId)))
  32423. colourChanged();
  32424. }
  32425. void Component::setColour (const int colourId, const Colour& colour)
  32426. {
  32427. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  32428. colourChanged();
  32429. }
  32430. void Component::copyAllExplicitColoursTo (Component& target) const
  32431. {
  32432. bool changed = false;
  32433. for (int i = properties.size(); --i >= 0;)
  32434. {
  32435. const Identifier name (properties.getName(i));
  32436. if (name.toString().startsWith ("jcclr_"))
  32437. if (target.properties.set (name, properties [name]))
  32438. changed = true;
  32439. }
  32440. if (changed)
  32441. target.colourChanged();
  32442. }
  32443. void Component::colourChanged()
  32444. {
  32445. }
  32446. const Rectangle<int> Component::getLocalBounds() const throw()
  32447. {
  32448. return Rectangle<int> (getWidth(), getHeight());
  32449. }
  32450. const Rectangle<int> Component::getParentOrMainMonitorBounds() const
  32451. {
  32452. return parentComponent_ != 0 ? parentComponent_->getLocalBounds()
  32453. : Desktop::getInstance().getMainMonitorArea();
  32454. }
  32455. const Rectangle<int> Component::getUnclippedArea() const
  32456. {
  32457. int x = 0, y = 0, w = getWidth(), h = getHeight();
  32458. Component* p = parentComponent_;
  32459. int px = getX();
  32460. int py = getY();
  32461. while (p != 0)
  32462. {
  32463. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  32464. return Rectangle<int>();
  32465. px += p->getX();
  32466. py += p->getY();
  32467. p = p->parentComponent_;
  32468. }
  32469. return Rectangle<int> (x, y, w, h);
  32470. }
  32471. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  32472. const int deltaX, const int deltaY) const
  32473. {
  32474. for (int i = childComponentList_.size(); --i >= 0;)
  32475. {
  32476. const Component* const c = childComponentList_.getUnchecked(i);
  32477. if (c->isVisible())
  32478. {
  32479. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32480. if (! newClip.isEmpty())
  32481. {
  32482. if (c->isOpaque())
  32483. {
  32484. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  32485. }
  32486. else
  32487. {
  32488. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  32489. c->getX() + deltaX,
  32490. c->getY() + deltaY);
  32491. }
  32492. }
  32493. }
  32494. }
  32495. }
  32496. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  32497. {
  32498. result.clear();
  32499. const Rectangle<int> unclipped (getUnclippedArea());
  32500. if (! unclipped.isEmpty())
  32501. {
  32502. result.add (unclipped);
  32503. if (includeSiblings)
  32504. {
  32505. const Component* const c = getTopLevelComponent();
  32506. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  32507. c->getLocalBounds(), this);
  32508. }
  32509. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  32510. result.consolidate();
  32511. }
  32512. }
  32513. void Component::subtractObscuredRegions (RectangleList& result,
  32514. const Point<int>& delta,
  32515. const Rectangle<int>& clipRect,
  32516. const Component* const compToAvoid) const
  32517. {
  32518. for (int i = childComponentList_.size(); --i >= 0;)
  32519. {
  32520. const Component* const c = childComponentList_.getUnchecked(i);
  32521. if (c != compToAvoid && c->isVisible())
  32522. {
  32523. if (c->isOpaque())
  32524. {
  32525. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  32526. childBounds.translate (delta.getX(), delta.getY());
  32527. result.subtract (childBounds);
  32528. }
  32529. else
  32530. {
  32531. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32532. newClip.translate (-c->getX(), -c->getY());
  32533. c->subtractObscuredRegions (result, c->getPosition() + delta,
  32534. newClip, compToAvoid);
  32535. }
  32536. }
  32537. }
  32538. }
  32539. void Component::mouseEnter (const MouseEvent&)
  32540. {
  32541. // base class does nothing
  32542. }
  32543. void Component::mouseExit (const MouseEvent&)
  32544. {
  32545. // base class does nothing
  32546. }
  32547. void Component::mouseDown (const MouseEvent&)
  32548. {
  32549. // base class does nothing
  32550. }
  32551. void Component::mouseUp (const MouseEvent&)
  32552. {
  32553. // base class does nothing
  32554. }
  32555. void Component::mouseDrag (const MouseEvent&)
  32556. {
  32557. // base class does nothing
  32558. }
  32559. void Component::mouseMove (const MouseEvent&)
  32560. {
  32561. // base class does nothing
  32562. }
  32563. void Component::mouseDoubleClick (const MouseEvent&)
  32564. {
  32565. // base class does nothing
  32566. }
  32567. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  32568. {
  32569. // the base class just passes this event up to its parent..
  32570. if (parentComponent_ != 0)
  32571. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  32572. wheelIncrementX, wheelIncrementY);
  32573. }
  32574. void Component::resized()
  32575. {
  32576. // base class does nothing
  32577. }
  32578. void Component::moved()
  32579. {
  32580. // base class does nothing
  32581. }
  32582. void Component::childBoundsChanged (Component*)
  32583. {
  32584. // base class does nothing
  32585. }
  32586. void Component::parentSizeChanged()
  32587. {
  32588. // base class does nothing
  32589. }
  32590. void Component::addComponentListener (ComponentListener* const newListener)
  32591. {
  32592. jassert (isValidComponent());
  32593. componentListeners.add (newListener);
  32594. }
  32595. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  32596. {
  32597. jassert (isValidComponent());
  32598. componentListeners.remove (listenerToRemove);
  32599. }
  32600. void Component::inputAttemptWhenModal()
  32601. {
  32602. bringModalComponentToFront();
  32603. getLookAndFeel().playAlertSound();
  32604. }
  32605. bool Component::canModalEventBeSentToComponent (const Component*)
  32606. {
  32607. return false;
  32608. }
  32609. void Component::internalModalInputAttempt()
  32610. {
  32611. Component* const current = getCurrentlyModalComponent();
  32612. if (current != 0)
  32613. current->inputAttemptWhenModal();
  32614. }
  32615. void Component::paint (Graphics&)
  32616. {
  32617. // all painting is done in the subclasses
  32618. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  32619. }
  32620. void Component::paintOverChildren (Graphics&)
  32621. {
  32622. // all painting is done in the subclasses
  32623. }
  32624. void Component::handleMessage (const Message& message)
  32625. {
  32626. if (message.intParameter1 == exitModalStateMessage)
  32627. {
  32628. exitModalState (message.intParameter2);
  32629. }
  32630. else if (message.intParameter1 == customCommandMessage)
  32631. {
  32632. handleCommandMessage (message.intParameter2);
  32633. }
  32634. }
  32635. void Component::postCommandMessage (const int commandId)
  32636. {
  32637. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  32638. }
  32639. void Component::handleCommandMessage (int)
  32640. {
  32641. // used by subclasses
  32642. }
  32643. void Component::addMouseListener (MouseListener* const newListener,
  32644. const bool wantsEventsForAllNestedChildComponents)
  32645. {
  32646. // if component methods are being called from threads other than the message
  32647. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32648. checkMessageManagerIsLocked
  32649. if (mouseListeners_ == 0)
  32650. mouseListeners_ = new Array<MouseListener*>();
  32651. if (! mouseListeners_->contains (newListener))
  32652. {
  32653. if (wantsEventsForAllNestedChildComponents)
  32654. {
  32655. mouseListeners_->insert (0, newListener);
  32656. ++numDeepMouseListeners;
  32657. }
  32658. else
  32659. {
  32660. mouseListeners_->add (newListener);
  32661. }
  32662. }
  32663. }
  32664. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  32665. {
  32666. // if component methods are being called from threads other than the message
  32667. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32668. checkMessageManagerIsLocked
  32669. if (mouseListeners_ != 0)
  32670. {
  32671. const int index = mouseListeners_->indexOf (listenerToRemove);
  32672. if (index >= 0)
  32673. {
  32674. if (index < numDeepMouseListeners)
  32675. --numDeepMouseListeners;
  32676. mouseListeners_->remove (index);
  32677. }
  32678. }
  32679. }
  32680. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32681. {
  32682. if (isCurrentlyBlockedByAnotherModalComponent())
  32683. {
  32684. // if something else is modal, always just show a normal mouse cursor
  32685. source.showMouseCursor (MouseCursor::NormalCursor);
  32686. return;
  32687. }
  32688. if (! flags.mouseInsideFlag)
  32689. {
  32690. flags.mouseInsideFlag = true;
  32691. flags.mouseOverFlag = true;
  32692. flags.draggingFlag = false;
  32693. BailOutChecker checker (this);
  32694. if (flags.repaintOnMouseActivityFlag)
  32695. repaint();
  32696. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32697. this, this, time, relativePos,
  32698. time, 0, false);
  32699. mouseEnter (me);
  32700. if (checker.shouldBailOut())
  32701. return;
  32702. Desktop::getInstance().resetTimer();
  32703. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  32704. if (checker.shouldBailOut())
  32705. return;
  32706. if (mouseListeners_ != 0)
  32707. {
  32708. for (int i = mouseListeners_->size(); --i >= 0;)
  32709. {
  32710. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32711. if (checker.shouldBailOut())
  32712. return;
  32713. i = jmin (i, mouseListeners_->size());
  32714. }
  32715. }
  32716. Component* p = parentComponent_;
  32717. while (p != 0)
  32718. {
  32719. if (p->numDeepMouseListeners > 0)
  32720. {
  32721. BailOutChecker checker2 (this, p);
  32722. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32723. {
  32724. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32725. if (checker2.shouldBailOut())
  32726. return;
  32727. i = jmin (i, p->numDeepMouseListeners);
  32728. }
  32729. }
  32730. p = p->parentComponent_;
  32731. }
  32732. }
  32733. }
  32734. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32735. {
  32736. BailOutChecker checker (this);
  32737. if (flags.draggingFlag)
  32738. {
  32739. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  32740. if (checker.shouldBailOut())
  32741. return;
  32742. }
  32743. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  32744. {
  32745. flags.mouseInsideFlag = false;
  32746. flags.mouseOverFlag = false;
  32747. flags.draggingFlag = false;
  32748. if (flags.repaintOnMouseActivityFlag)
  32749. repaint();
  32750. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32751. this, this, time, relativePos,
  32752. time, 0, false);
  32753. mouseExit (me);
  32754. if (checker.shouldBailOut())
  32755. return;
  32756. Desktop::getInstance().resetTimer();
  32757. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  32758. if (checker.shouldBailOut())
  32759. return;
  32760. if (mouseListeners_ != 0)
  32761. {
  32762. for (int i = mouseListeners_->size(); --i >= 0;)
  32763. {
  32764. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  32765. if (checker.shouldBailOut())
  32766. return;
  32767. i = jmin (i, mouseListeners_->size());
  32768. }
  32769. }
  32770. Component* p = parentComponent_;
  32771. while (p != 0)
  32772. {
  32773. if (p->numDeepMouseListeners > 0)
  32774. {
  32775. BailOutChecker checker2 (this, p);
  32776. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32777. {
  32778. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  32779. if (checker2.shouldBailOut())
  32780. return;
  32781. i = jmin (i, p->numDeepMouseListeners);
  32782. }
  32783. }
  32784. p = p->parentComponent_;
  32785. }
  32786. }
  32787. }
  32788. class InternalDragRepeater : public Timer
  32789. {
  32790. public:
  32791. InternalDragRepeater()
  32792. {}
  32793. ~InternalDragRepeater()
  32794. {
  32795. clearSingletonInstance();
  32796. }
  32797. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  32798. void timerCallback()
  32799. {
  32800. Desktop& desktop = Desktop::getInstance();
  32801. int numMiceDown = 0;
  32802. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  32803. {
  32804. MouseInputSource* const source = desktop.getMouseSource(i);
  32805. if (source->isDragging())
  32806. {
  32807. source->triggerFakeMove();
  32808. ++numMiceDown;
  32809. }
  32810. }
  32811. if (numMiceDown == 0)
  32812. deleteInstance();
  32813. }
  32814. juce_UseDebuggingNewOperator
  32815. private:
  32816. InternalDragRepeater (const InternalDragRepeater&);
  32817. InternalDragRepeater& operator= (const InternalDragRepeater&);
  32818. };
  32819. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  32820. void Component::beginDragAutoRepeat (const int interval)
  32821. {
  32822. if (interval > 0)
  32823. {
  32824. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  32825. InternalDragRepeater::getInstance()->startTimer (interval);
  32826. }
  32827. else
  32828. {
  32829. InternalDragRepeater::deleteInstance();
  32830. }
  32831. }
  32832. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32833. {
  32834. Desktop& desktop = Desktop::getInstance();
  32835. BailOutChecker checker (this);
  32836. if (isCurrentlyBlockedByAnotherModalComponent())
  32837. {
  32838. internalModalInputAttempt();
  32839. if (checker.shouldBailOut())
  32840. return;
  32841. // If processing the input attempt has exited the modal loop, we'll allow the event
  32842. // to be delivered..
  32843. if (isCurrentlyBlockedByAnotherModalComponent())
  32844. {
  32845. // allow blocked mouse-events to go to global listeners..
  32846. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32847. this, this, time, relativePos, time,
  32848. source.getNumberOfMultipleClicks(), false);
  32849. desktop.resetTimer();
  32850. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32851. return;
  32852. }
  32853. }
  32854. {
  32855. Component* c = this;
  32856. while (c != 0)
  32857. {
  32858. if (c->isBroughtToFrontOnMouseClick())
  32859. {
  32860. c->toFront (true);
  32861. if (checker.shouldBailOut())
  32862. return;
  32863. }
  32864. c = c->parentComponent_;
  32865. }
  32866. }
  32867. if (! flags.dontFocusOnMouseClickFlag)
  32868. {
  32869. grabFocusInternal (focusChangedByMouseClick);
  32870. if (checker.shouldBailOut())
  32871. return;
  32872. }
  32873. flags.draggingFlag = true;
  32874. flags.mouseOverFlag = true;
  32875. if (flags.repaintOnMouseActivityFlag)
  32876. repaint();
  32877. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32878. this, this, time, relativePos, time,
  32879. source.getNumberOfMultipleClicks(), false);
  32880. mouseDown (me);
  32881. if (checker.shouldBailOut())
  32882. return;
  32883. desktop.resetTimer();
  32884. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32885. if (checker.shouldBailOut())
  32886. return;
  32887. if (mouseListeners_ != 0)
  32888. {
  32889. for (int i = mouseListeners_->size(); --i >= 0;)
  32890. {
  32891. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  32892. if (checker.shouldBailOut())
  32893. return;
  32894. i = jmin (i, mouseListeners_->size());
  32895. }
  32896. }
  32897. Component* p = parentComponent_;
  32898. while (p != 0)
  32899. {
  32900. if (p->numDeepMouseListeners > 0)
  32901. {
  32902. BailOutChecker checker2 (this, p);
  32903. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32904. {
  32905. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  32906. if (checker2.shouldBailOut())
  32907. return;
  32908. i = jmin (i, p->numDeepMouseListeners);
  32909. }
  32910. }
  32911. p = p->parentComponent_;
  32912. }
  32913. }
  32914. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  32915. {
  32916. if (flags.draggingFlag)
  32917. {
  32918. Desktop& desktop = Desktop::getInstance();
  32919. flags.draggingFlag = false;
  32920. BailOutChecker checker (this);
  32921. if (flags.repaintOnMouseActivityFlag)
  32922. repaint();
  32923. const MouseEvent me (source, relativePos,
  32924. oldModifiers, this, this, time,
  32925. globalPositionToRelative (source.getLastMouseDownPosition()),
  32926. source.getLastMouseDownTime(),
  32927. source.getNumberOfMultipleClicks(),
  32928. source.hasMouseMovedSignificantlySincePressed());
  32929. mouseUp (me);
  32930. if (checker.shouldBailOut())
  32931. return;
  32932. desktop.resetTimer();
  32933. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  32934. if (checker.shouldBailOut())
  32935. return;
  32936. if (mouseListeners_ != 0)
  32937. {
  32938. for (int i = mouseListeners_->size(); --i >= 0;)
  32939. {
  32940. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  32941. if (checker.shouldBailOut())
  32942. return;
  32943. i = jmin (i, mouseListeners_->size());
  32944. }
  32945. }
  32946. {
  32947. Component* p = parentComponent_;
  32948. while (p != 0)
  32949. {
  32950. if (p->numDeepMouseListeners > 0)
  32951. {
  32952. BailOutChecker checker2 (this, p);
  32953. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32954. {
  32955. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  32956. if (checker2.shouldBailOut())
  32957. return;
  32958. i = jmin (i, p->numDeepMouseListeners);
  32959. }
  32960. }
  32961. p = p->parentComponent_;
  32962. }
  32963. }
  32964. // check for double-click
  32965. if (me.getNumberOfClicks() >= 2)
  32966. {
  32967. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  32968. mouseDoubleClick (me);
  32969. if (checker.shouldBailOut())
  32970. return;
  32971. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  32972. if (checker.shouldBailOut())
  32973. return;
  32974. for (int i = numListeners; --i >= 0;)
  32975. {
  32976. if (checker.shouldBailOut())
  32977. return;
  32978. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  32979. if (ml != 0)
  32980. ml->mouseDoubleClick (me);
  32981. }
  32982. if (checker.shouldBailOut())
  32983. return;
  32984. Component* p = parentComponent_;
  32985. while (p != 0)
  32986. {
  32987. if (p->numDeepMouseListeners > 0)
  32988. {
  32989. BailOutChecker checker2 (this, p);
  32990. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32991. {
  32992. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  32993. if (checker2.shouldBailOut())
  32994. return;
  32995. i = jmin (i, p->numDeepMouseListeners);
  32996. }
  32997. }
  32998. p = p->parentComponent_;
  32999. }
  33000. }
  33001. }
  33002. }
  33003. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33004. {
  33005. if (flags.draggingFlag)
  33006. {
  33007. Desktop& desktop = Desktop::getInstance();
  33008. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  33009. BailOutChecker checker (this);
  33010. const MouseEvent me (source, relativePos,
  33011. source.getCurrentModifiers(), this, this, time,
  33012. globalPositionToRelative (source.getLastMouseDownPosition()),
  33013. source.getLastMouseDownTime(),
  33014. source.getNumberOfMultipleClicks(),
  33015. source.hasMouseMovedSignificantlySincePressed());
  33016. mouseDrag (me);
  33017. if (checker.shouldBailOut())
  33018. return;
  33019. desktop.resetTimer();
  33020. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33021. if (checker.shouldBailOut())
  33022. return;
  33023. if (mouseListeners_ != 0)
  33024. {
  33025. for (int i = mouseListeners_->size(); --i >= 0;)
  33026. {
  33027. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  33028. if (checker.shouldBailOut())
  33029. return;
  33030. i = jmin (i, mouseListeners_->size());
  33031. }
  33032. }
  33033. Component* p = parentComponent_;
  33034. while (p != 0)
  33035. {
  33036. if (p->numDeepMouseListeners > 0)
  33037. {
  33038. BailOutChecker checker2 (this, p);
  33039. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33040. {
  33041. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  33042. if (checker2.shouldBailOut())
  33043. return;
  33044. i = jmin (i, p->numDeepMouseListeners);
  33045. }
  33046. }
  33047. p = p->parentComponent_;
  33048. }
  33049. }
  33050. }
  33051. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33052. {
  33053. Desktop& desktop = Desktop::getInstance();
  33054. BailOutChecker checker (this);
  33055. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33056. this, this, time, relativePos,
  33057. time, 0, false);
  33058. if (isCurrentlyBlockedByAnotherModalComponent())
  33059. {
  33060. // allow blocked mouse-events to go to global listeners..
  33061. desktop.sendMouseMove();
  33062. }
  33063. else
  33064. {
  33065. flags.mouseOverFlag = true;
  33066. mouseMove (me);
  33067. if (checker.shouldBailOut())
  33068. return;
  33069. desktop.resetTimer();
  33070. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33071. if (checker.shouldBailOut())
  33072. return;
  33073. if (mouseListeners_ != 0)
  33074. {
  33075. for (int i = mouseListeners_->size(); --i >= 0;)
  33076. {
  33077. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  33078. if (checker.shouldBailOut())
  33079. return;
  33080. i = jmin (i, mouseListeners_->size());
  33081. }
  33082. }
  33083. Component* p = parentComponent_;
  33084. while (p != 0)
  33085. {
  33086. if (p->numDeepMouseListeners > 0)
  33087. {
  33088. BailOutChecker checker2 (this, p);
  33089. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33090. {
  33091. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  33092. if (checker2.shouldBailOut())
  33093. return;
  33094. i = jmin (i, p->numDeepMouseListeners);
  33095. }
  33096. }
  33097. p = p->parentComponent_;
  33098. }
  33099. }
  33100. }
  33101. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33102. const Time& time, const float amountX, const float amountY)
  33103. {
  33104. Desktop& desktop = Desktop::getInstance();
  33105. BailOutChecker checker (this);
  33106. const float wheelIncrementX = amountX / 256.0f;
  33107. const float wheelIncrementY = amountY / 256.0f;
  33108. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33109. this, this, time, relativePos, time, 0, false);
  33110. if (isCurrentlyBlockedByAnotherModalComponent())
  33111. {
  33112. // allow blocked mouse-events to go to global listeners..
  33113. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33114. }
  33115. else
  33116. {
  33117. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33118. if (checker.shouldBailOut())
  33119. return;
  33120. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33121. if (checker.shouldBailOut())
  33122. return;
  33123. if (mouseListeners_ != 0)
  33124. {
  33125. for (int i = mouseListeners_->size(); --i >= 0;)
  33126. {
  33127. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33128. if (checker.shouldBailOut())
  33129. return;
  33130. i = jmin (i, mouseListeners_->size());
  33131. }
  33132. }
  33133. Component* p = parentComponent_;
  33134. while (p != 0)
  33135. {
  33136. if (p->numDeepMouseListeners > 0)
  33137. {
  33138. BailOutChecker checker2 (this, p);
  33139. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33140. {
  33141. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33142. if (checker2.shouldBailOut())
  33143. return;
  33144. i = jmin (i, p->numDeepMouseListeners);
  33145. }
  33146. }
  33147. p = p->parentComponent_;
  33148. }
  33149. }
  33150. }
  33151. void Component::sendFakeMouseMove() const
  33152. {
  33153. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  33154. }
  33155. void Component::broughtToFront()
  33156. {
  33157. }
  33158. void Component::internalBroughtToFront()
  33159. {
  33160. if (! isValidComponent())
  33161. return;
  33162. if (flags.hasHeavyweightPeerFlag)
  33163. Desktop::getInstance().componentBroughtToFront (this);
  33164. BailOutChecker checker (this);
  33165. broughtToFront();
  33166. if (checker.shouldBailOut())
  33167. return;
  33168. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33169. if (checker.shouldBailOut())
  33170. return;
  33171. // When brought to the front and there's a modal component blocking this one,
  33172. // we need to bring the modal one to the front instead..
  33173. Component* const cm = getCurrentlyModalComponent();
  33174. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33175. bringModalComponentToFront();
  33176. }
  33177. void Component::focusGained (FocusChangeType)
  33178. {
  33179. // base class does nothing
  33180. }
  33181. void Component::internalFocusGain (const FocusChangeType cause)
  33182. {
  33183. SafePointer<Component> safePointer (this);
  33184. focusGained (cause);
  33185. if (safePointer != 0)
  33186. internalChildFocusChange (cause);
  33187. }
  33188. void Component::focusLost (FocusChangeType)
  33189. {
  33190. // base class does nothing
  33191. }
  33192. void Component::internalFocusLoss (const FocusChangeType cause)
  33193. {
  33194. SafePointer<Component> safePointer (this);
  33195. focusLost (focusChangedDirectly);
  33196. if (safePointer != 0)
  33197. internalChildFocusChange (cause);
  33198. }
  33199. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33200. {
  33201. // base class does nothing
  33202. }
  33203. void Component::internalChildFocusChange (FocusChangeType cause)
  33204. {
  33205. const bool childIsNowFocused = hasKeyboardFocus (true);
  33206. if (flags.childCompFocusedFlag != childIsNowFocused)
  33207. {
  33208. flags.childCompFocusedFlag = childIsNowFocused;
  33209. SafePointer<Component> safePointer (this);
  33210. focusOfChildComponentChanged (cause);
  33211. if (safePointer == 0)
  33212. return;
  33213. }
  33214. if (parentComponent_ != 0)
  33215. parentComponent_->internalChildFocusChange (cause);
  33216. }
  33217. bool Component::isEnabled() const throw()
  33218. {
  33219. return (! flags.isDisabledFlag)
  33220. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  33221. }
  33222. void Component::setEnabled (const bool shouldBeEnabled)
  33223. {
  33224. if (flags.isDisabledFlag == shouldBeEnabled)
  33225. {
  33226. flags.isDisabledFlag = ! shouldBeEnabled;
  33227. // if any parent components are disabled, setting our flag won't make a difference,
  33228. // so no need to send a change message
  33229. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  33230. sendEnablementChangeMessage();
  33231. }
  33232. }
  33233. void Component::sendEnablementChangeMessage()
  33234. {
  33235. SafePointer<Component> safePointer (this);
  33236. enablementChanged();
  33237. if (safePointer == 0)
  33238. return;
  33239. for (int i = getNumChildComponents(); --i >= 0;)
  33240. {
  33241. Component* const c = getChildComponent (i);
  33242. if (c != 0)
  33243. {
  33244. c->sendEnablementChangeMessage();
  33245. if (safePointer == 0)
  33246. return;
  33247. }
  33248. }
  33249. }
  33250. void Component::enablementChanged()
  33251. {
  33252. }
  33253. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33254. {
  33255. flags.wantsFocusFlag = wantsFocus;
  33256. }
  33257. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33258. {
  33259. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33260. }
  33261. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33262. {
  33263. return ! flags.dontFocusOnMouseClickFlag;
  33264. }
  33265. bool Component::getWantsKeyboardFocus() const throw()
  33266. {
  33267. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33268. }
  33269. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  33270. {
  33271. flags.isFocusContainerFlag = shouldBeFocusContainer;
  33272. }
  33273. bool Component::isFocusContainer() const throw()
  33274. {
  33275. return flags.isFocusContainerFlag;
  33276. }
  33277. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  33278. int Component::getExplicitFocusOrder() const
  33279. {
  33280. return properties [juce_explicitFocusOrderId];
  33281. }
  33282. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  33283. {
  33284. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  33285. }
  33286. KeyboardFocusTraverser* Component::createFocusTraverser()
  33287. {
  33288. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  33289. return new KeyboardFocusTraverser();
  33290. return parentComponent_->createFocusTraverser();
  33291. }
  33292. void Component::takeKeyboardFocus (const FocusChangeType cause)
  33293. {
  33294. // give the focus to this component
  33295. if (currentlyFocusedComponent != this)
  33296. {
  33297. JUCE_TRY
  33298. {
  33299. // get the focus onto our desktop window
  33300. ComponentPeer* const peer = getPeer();
  33301. if (peer != 0)
  33302. {
  33303. SafePointer<Component> safePointer (this);
  33304. peer->grabFocus();
  33305. if (peer->isFocused() && currentlyFocusedComponent != this)
  33306. {
  33307. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  33308. currentlyFocusedComponent = this;
  33309. Desktop::getInstance().triggerFocusCallback();
  33310. // call this after setting currentlyFocusedComponent so that the one that's
  33311. // losing it has a chance to see where focus is going
  33312. if (componentLosingFocus != 0)
  33313. componentLosingFocus->internalFocusLoss (cause);
  33314. if (currentlyFocusedComponent == this)
  33315. {
  33316. focusGained (cause);
  33317. if (safePointer != 0)
  33318. internalChildFocusChange (cause);
  33319. }
  33320. }
  33321. }
  33322. }
  33323. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  33324. catch (const std::exception& e)
  33325. {
  33326. currentlyFocusedComponent = 0;
  33327. Desktop::getInstance().triggerFocusCallback();
  33328. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  33329. }
  33330. catch (...)
  33331. {
  33332. currentlyFocusedComponent = 0;
  33333. Desktop::getInstance().triggerFocusCallback();
  33334. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  33335. }
  33336. #endif
  33337. }
  33338. }
  33339. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33340. {
  33341. if (isShowing())
  33342. {
  33343. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  33344. {
  33345. takeKeyboardFocus (cause);
  33346. }
  33347. else
  33348. {
  33349. if (isParentOf (currentlyFocusedComponent)
  33350. && currentlyFocusedComponent->isShowing())
  33351. {
  33352. // do nothing if the focused component is actually a child of ours..
  33353. }
  33354. else
  33355. {
  33356. // find the default child component..
  33357. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33358. if (traverser != 0)
  33359. {
  33360. Component* const defaultComp = traverser->getDefaultComponent (this);
  33361. traverser = 0;
  33362. if (defaultComp != 0)
  33363. {
  33364. defaultComp->grabFocusInternal (cause, false);
  33365. return;
  33366. }
  33367. }
  33368. if (canTryParent && parentComponent_ != 0)
  33369. {
  33370. // if no children want it and we're allowed to try our parent comp,
  33371. // then pass up to parent, which will try our siblings.
  33372. parentComponent_->grabFocusInternal (cause, true);
  33373. }
  33374. }
  33375. }
  33376. }
  33377. }
  33378. void Component::grabKeyboardFocus()
  33379. {
  33380. // if component methods are being called from threads other than the message
  33381. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33382. checkMessageManagerIsLocked
  33383. grabFocusInternal (focusChangedDirectly);
  33384. }
  33385. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33386. {
  33387. // if component methods are being called from threads other than the message
  33388. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33389. checkMessageManagerIsLocked
  33390. if (parentComponent_ != 0)
  33391. {
  33392. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33393. if (traverser != 0)
  33394. {
  33395. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  33396. : traverser->getPreviousComponent (this);
  33397. traverser = 0;
  33398. if (nextComp != 0)
  33399. {
  33400. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33401. {
  33402. SafePointer<Component> nextCompPointer (nextComp);
  33403. internalModalInputAttempt();
  33404. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33405. return;
  33406. }
  33407. nextComp->grabFocusInternal (focusChangedByTabKey);
  33408. return;
  33409. }
  33410. }
  33411. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  33412. }
  33413. }
  33414. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  33415. {
  33416. return (currentlyFocusedComponent == this)
  33417. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  33418. }
  33419. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  33420. {
  33421. return currentlyFocusedComponent;
  33422. }
  33423. void Component::giveAwayFocus()
  33424. {
  33425. // use a copy so we can clear the value before the call
  33426. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  33427. currentlyFocusedComponent = 0;
  33428. Desktop::getInstance().triggerFocusCallback();
  33429. if (componentLosingFocus != 0)
  33430. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  33431. }
  33432. bool Component::isMouseOver() const throw()
  33433. {
  33434. return flags.mouseOverFlag;
  33435. }
  33436. bool Component::isMouseButtonDown() const throw()
  33437. {
  33438. return flags.draggingFlag;
  33439. }
  33440. bool Component::isMouseOverOrDragging() const throw()
  33441. {
  33442. return flags.mouseOverFlag || flags.draggingFlag;
  33443. }
  33444. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  33445. {
  33446. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  33447. }
  33448. const Point<int> Component::getMouseXYRelative() const
  33449. {
  33450. return globalPositionToRelative (Desktop::getMousePosition());
  33451. }
  33452. const Rectangle<int> Component::getParentMonitorArea() const
  33453. {
  33454. return Desktop::getInstance()
  33455. .getMonitorAreaContaining (relativePositionToGlobal (getLocalBounds().getCentre()));
  33456. }
  33457. void Component::addKeyListener (KeyListener* const newListener)
  33458. {
  33459. if (keyListeners_ == 0)
  33460. keyListeners_ = new Array <KeyListener*>();
  33461. keyListeners_->addIfNotAlreadyThere (newListener);
  33462. }
  33463. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  33464. {
  33465. if (keyListeners_ != 0)
  33466. keyListeners_->removeValue (listenerToRemove);
  33467. }
  33468. bool Component::keyPressed (const KeyPress&)
  33469. {
  33470. return false;
  33471. }
  33472. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33473. {
  33474. return false;
  33475. }
  33476. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33477. {
  33478. if (parentComponent_ != 0)
  33479. parentComponent_->modifierKeysChanged (modifiers);
  33480. }
  33481. void Component::internalModifierKeysChanged()
  33482. {
  33483. sendFakeMouseMove();
  33484. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33485. }
  33486. ComponentPeer* Component::getPeer() const
  33487. {
  33488. if (flags.hasHeavyweightPeerFlag)
  33489. return ComponentPeer::getPeerFor (this);
  33490. else if (parentComponent_ != 0)
  33491. return parentComponent_->getPeer();
  33492. else
  33493. return 0;
  33494. }
  33495. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  33496. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  33497. {
  33498. jassert (component1 != 0);
  33499. }
  33500. bool Component::BailOutChecker::shouldBailOut() const throw()
  33501. {
  33502. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  33503. }
  33504. END_JUCE_NAMESPACE
  33505. /*** End of inlined file: juce_Component.cpp ***/
  33506. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  33507. BEGIN_JUCE_NAMESPACE
  33508. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  33509. void ComponentListener::componentBroughtToFront (Component&) {}
  33510. void ComponentListener::componentVisibilityChanged (Component&) {}
  33511. void ComponentListener::componentChildrenChanged (Component&) {}
  33512. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  33513. void ComponentListener::componentNameChanged (Component&) {}
  33514. void ComponentListener::componentBeingDeleted (Component&) {}
  33515. END_JUCE_NAMESPACE
  33516. /*** End of inlined file: juce_ComponentListener.cpp ***/
  33517. /*** Start of inlined file: juce_Desktop.cpp ***/
  33518. BEGIN_JUCE_NAMESPACE
  33519. Desktop::Desktop()
  33520. : mouseClickCounter (0),
  33521. kioskModeComponent (0)
  33522. {
  33523. createMouseInputSources();
  33524. refreshMonitorSizes();
  33525. }
  33526. Desktop::~Desktop()
  33527. {
  33528. jassert (instance == this);
  33529. instance = 0;
  33530. // doh! If you don't delete all your windows before exiting, you're going to
  33531. // be leaking memory!
  33532. jassert (desktopComponents.size() == 0);
  33533. }
  33534. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  33535. {
  33536. if (instance == 0)
  33537. instance = new Desktop();
  33538. return *instance;
  33539. }
  33540. Desktop* Desktop::instance = 0;
  33541. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  33542. const bool clipToWorkArea);
  33543. void Desktop::refreshMonitorSizes()
  33544. {
  33545. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  33546. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  33547. monitorCoordsClipped.clear();
  33548. monitorCoordsUnclipped.clear();
  33549. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33550. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33551. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33552. if (oldClipped != monitorCoordsClipped
  33553. || oldUnclipped != monitorCoordsUnclipped)
  33554. {
  33555. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33556. {
  33557. ComponentPeer* const p = ComponentPeer::getPeer (i);
  33558. if (p != 0)
  33559. p->handleScreenSizeChange();
  33560. }
  33561. }
  33562. }
  33563. int Desktop::getNumDisplayMonitors() const throw()
  33564. {
  33565. return monitorCoordsClipped.size();
  33566. }
  33567. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  33568. {
  33569. return clippedToWorkArea ? monitorCoordsClipped [index]
  33570. : monitorCoordsUnclipped [index];
  33571. }
  33572. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  33573. {
  33574. RectangleList rl;
  33575. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  33576. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33577. return rl;
  33578. }
  33579. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  33580. {
  33581. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  33582. }
  33583. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  33584. {
  33585. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  33586. double bestDistance = 1.0e10;
  33587. for (int i = getNumDisplayMonitors(); --i >= 0;)
  33588. {
  33589. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33590. if (rect.contains (position))
  33591. return rect;
  33592. const double distance = rect.getCentre().getDistanceFrom (position);
  33593. if (distance < bestDistance)
  33594. {
  33595. bestDistance = distance;
  33596. best = rect;
  33597. }
  33598. }
  33599. return best;
  33600. }
  33601. int Desktop::getNumComponents() const throw()
  33602. {
  33603. return desktopComponents.size();
  33604. }
  33605. Component* Desktop::getComponent (const int index) const throw()
  33606. {
  33607. return desktopComponents [index];
  33608. }
  33609. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  33610. {
  33611. for (int i = desktopComponents.size(); --i >= 0;)
  33612. {
  33613. Component* const c = desktopComponents.getUnchecked(i);
  33614. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  33615. if (c->contains (relative.getX(), relative.getY()))
  33616. return c->getComponentAt (relative.getX(), relative.getY());
  33617. }
  33618. return 0;
  33619. }
  33620. void Desktop::addDesktopComponent (Component* const c)
  33621. {
  33622. jassert (c != 0);
  33623. jassert (! desktopComponents.contains (c));
  33624. desktopComponents.addIfNotAlreadyThere (c);
  33625. }
  33626. void Desktop::removeDesktopComponent (Component* const c)
  33627. {
  33628. desktopComponents.removeValue (c);
  33629. }
  33630. void Desktop::componentBroughtToFront (Component* const c)
  33631. {
  33632. const int index = desktopComponents.indexOf (c);
  33633. jassert (index >= 0);
  33634. if (index >= 0)
  33635. {
  33636. int newIndex = -1;
  33637. if (! c->isAlwaysOnTop())
  33638. {
  33639. newIndex = desktopComponents.size();
  33640. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  33641. --newIndex;
  33642. --newIndex;
  33643. }
  33644. desktopComponents.move (index, newIndex);
  33645. }
  33646. }
  33647. const Point<int> Desktop::getLastMouseDownPosition() throw()
  33648. {
  33649. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  33650. }
  33651. int Desktop::getMouseButtonClickCounter() throw()
  33652. {
  33653. return getInstance().mouseClickCounter;
  33654. }
  33655. void Desktop::incrementMouseClickCounter() throw()
  33656. {
  33657. ++mouseClickCounter;
  33658. }
  33659. int Desktop::getNumDraggingMouseSources() const throw()
  33660. {
  33661. int num = 0;
  33662. for (int i = mouseSources.size(); --i >= 0;)
  33663. if (mouseSources.getUnchecked(i)->isDragging())
  33664. ++num;
  33665. return num;
  33666. }
  33667. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  33668. {
  33669. int num = 0;
  33670. for (int i = mouseSources.size(); --i >= 0;)
  33671. {
  33672. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  33673. if (mi->isDragging())
  33674. {
  33675. if (index == num)
  33676. return mi;
  33677. ++num;
  33678. }
  33679. }
  33680. return 0;
  33681. }
  33682. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  33683. {
  33684. focusListeners.add (listener);
  33685. }
  33686. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  33687. {
  33688. focusListeners.remove (listener);
  33689. }
  33690. void Desktop::triggerFocusCallback()
  33691. {
  33692. triggerAsyncUpdate();
  33693. }
  33694. void Desktop::handleAsyncUpdate()
  33695. {
  33696. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  33697. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  33698. }
  33699. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  33700. {
  33701. mouseListeners.add (listener);
  33702. resetTimer();
  33703. }
  33704. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  33705. {
  33706. mouseListeners.remove (listener);
  33707. resetTimer();
  33708. }
  33709. void Desktop::timerCallback()
  33710. {
  33711. if (lastFakeMouseMove != getMousePosition())
  33712. sendMouseMove();
  33713. }
  33714. void Desktop::sendMouseMove()
  33715. {
  33716. if (! mouseListeners.isEmpty())
  33717. {
  33718. startTimer (20);
  33719. lastFakeMouseMove = getMousePosition();
  33720. Component* const target = findComponentAt (lastFakeMouseMove);
  33721. if (target != 0)
  33722. {
  33723. Component::BailOutChecker checker (target);
  33724. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  33725. const Time now (Time::getCurrentTime());
  33726. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  33727. target, target, now, pos, now, 0, false);
  33728. if (me.mods.isAnyMouseButtonDown())
  33729. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33730. else
  33731. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33732. }
  33733. }
  33734. }
  33735. void Desktop::resetTimer()
  33736. {
  33737. if (mouseListeners.size() == 0)
  33738. stopTimer();
  33739. else
  33740. startTimer (100);
  33741. lastFakeMouseMove = getMousePosition();
  33742. }
  33743. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  33744. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  33745. {
  33746. if (kioskModeComponent != componentToUse)
  33747. {
  33748. // agh! Don't delete a component without first stopping it being the kiosk comp
  33749. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  33750. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  33751. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  33752. if (kioskModeComponent->isValidComponent())
  33753. {
  33754. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  33755. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  33756. }
  33757. kioskModeComponent = componentToUse;
  33758. if (kioskModeComponent != 0)
  33759. {
  33760. jassert (kioskModeComponent->isValidComponent());
  33761. // Only components that are already on the desktop can be put into kiosk mode!
  33762. jassert (kioskModeComponent->isOnDesktop());
  33763. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  33764. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  33765. }
  33766. }
  33767. }
  33768. END_JUCE_NAMESPACE
  33769. /*** End of inlined file: juce_Desktop.cpp ***/
  33770. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  33771. BEGIN_JUCE_NAMESPACE
  33772. class ModalComponentManager::ModalItem : public ComponentListener
  33773. {
  33774. public:
  33775. ModalItem (Component* const comp, Callback* const callback)
  33776. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  33777. {
  33778. if (callback != 0)
  33779. callbacks.add (callback);
  33780. jassert (comp != 0);
  33781. component->addComponentListener (this);
  33782. }
  33783. ~ModalItem()
  33784. {
  33785. if (! isDeleted)
  33786. component->removeComponentListener (this);
  33787. }
  33788. void componentBeingDeleted (Component&)
  33789. {
  33790. isDeleted = true;
  33791. cancel();
  33792. }
  33793. void componentVisibilityChanged (Component&)
  33794. {
  33795. if (! component->isShowing())
  33796. cancel();
  33797. }
  33798. void componentParentHierarchyChanged (Component&)
  33799. {
  33800. if (! component->isShowing())
  33801. cancel();
  33802. }
  33803. void cancel()
  33804. {
  33805. if (isActive)
  33806. {
  33807. isActive = false;
  33808. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  33809. }
  33810. }
  33811. Component* component;
  33812. OwnedArray<Callback> callbacks;
  33813. int returnValue;
  33814. bool isActive, isDeleted;
  33815. private:
  33816. ModalItem (const ModalItem&);
  33817. ModalItem& operator= (const ModalItem&);
  33818. };
  33819. ModalComponentManager::ModalComponentManager()
  33820. {
  33821. }
  33822. ModalComponentManager::~ModalComponentManager()
  33823. {
  33824. clearSingletonInstance();
  33825. }
  33826. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  33827. void ModalComponentManager::startModal (Component* component, Callback* callback)
  33828. {
  33829. if (component != 0)
  33830. stack.add (new ModalItem (component, callback));
  33831. }
  33832. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  33833. {
  33834. if (callback != 0)
  33835. {
  33836. ScopedPointer<Callback> callbackDeleter (callback);
  33837. for (int i = stack.size(); --i >= 0;)
  33838. {
  33839. ModalItem* const item = stack.getUnchecked(i);
  33840. if (item->component == component)
  33841. {
  33842. item->callbacks.add (callback);
  33843. callbackDeleter.release();
  33844. break;
  33845. }
  33846. }
  33847. }
  33848. }
  33849. void ModalComponentManager::endModal (Component* component)
  33850. {
  33851. for (int i = stack.size(); --i >= 0;)
  33852. {
  33853. ModalItem* const item = stack.getUnchecked(i);
  33854. if (item->component == component)
  33855. item->cancel();
  33856. }
  33857. }
  33858. void ModalComponentManager::endModal (Component* component, int returnValue)
  33859. {
  33860. for (int i = stack.size(); --i >= 0;)
  33861. {
  33862. ModalItem* const item = stack.getUnchecked(i);
  33863. if (item->component == component)
  33864. {
  33865. item->returnValue = returnValue;
  33866. item->cancel();
  33867. }
  33868. }
  33869. }
  33870. int ModalComponentManager::getNumModalComponents() const
  33871. {
  33872. int n = 0;
  33873. for (int i = 0; i < stack.size(); ++i)
  33874. if (stack.getUnchecked(i)->isActive)
  33875. ++n;
  33876. return n;
  33877. }
  33878. Component* ModalComponentManager::getModalComponent (const int index) const
  33879. {
  33880. int n = 0;
  33881. for (int i = stack.size(); --i >= 0;)
  33882. {
  33883. const ModalItem* const item = stack.getUnchecked(i);
  33884. if (item->isActive)
  33885. if (n++ == index)
  33886. return item->component;
  33887. }
  33888. return 0;
  33889. }
  33890. bool ModalComponentManager::isModal (Component* const comp) const
  33891. {
  33892. for (int i = stack.size(); --i >= 0;)
  33893. {
  33894. const ModalItem* const item = stack.getUnchecked(i);
  33895. if (item->isActive && item->component == comp)
  33896. return true;
  33897. }
  33898. return false;
  33899. }
  33900. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  33901. {
  33902. return comp == getModalComponent (0);
  33903. }
  33904. void ModalComponentManager::handleAsyncUpdate()
  33905. {
  33906. for (int i = stack.size(); --i >= 0;)
  33907. {
  33908. const ModalItem* const item = stack.getUnchecked(i);
  33909. if (! item->isActive)
  33910. {
  33911. for (int j = item->callbacks.size(); --j >= 0;)
  33912. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  33913. stack.remove (i);
  33914. }
  33915. }
  33916. }
  33917. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  33918. {
  33919. public:
  33920. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  33921. ~ReturnValueRetriever() {}
  33922. void modalStateFinished (int returnValue)
  33923. {
  33924. finished = true;
  33925. value = returnValue;
  33926. }
  33927. private:
  33928. int& value;
  33929. bool& finished;
  33930. ReturnValueRetriever (const ReturnValueRetriever&);
  33931. ReturnValueRetriever& operator= (const ReturnValueRetriever&);
  33932. };
  33933. int ModalComponentManager::runEventLoopForCurrentComponent()
  33934. {
  33935. // This can only be run from the message thread!
  33936. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  33937. Component* currentlyModal = getModalComponent (0);
  33938. if (currentlyModal == 0)
  33939. return 0;
  33940. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  33941. int returnValue = 0;
  33942. bool finished = false;
  33943. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  33944. JUCE_TRY
  33945. {
  33946. while (! finished)
  33947. {
  33948. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  33949. break;
  33950. }
  33951. }
  33952. JUCE_CATCH_EXCEPTION
  33953. if (prevFocused != 0)
  33954. prevFocused->grabKeyboardFocus();
  33955. return returnValue;
  33956. }
  33957. END_JUCE_NAMESPACE
  33958. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  33959. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  33960. BEGIN_JUCE_NAMESPACE
  33961. ArrowButton::ArrowButton (const String& name,
  33962. float arrowDirectionInRadians,
  33963. const Colour& arrowColour)
  33964. : Button (name),
  33965. colour (arrowColour)
  33966. {
  33967. path.lineTo (0.0f, 1.0f);
  33968. path.lineTo (1.0f, 0.5f);
  33969. path.closeSubPath();
  33970. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  33971. 0.5f, 0.5f));
  33972. setComponentEffect (&shadow);
  33973. buttonStateChanged();
  33974. }
  33975. ArrowButton::~ArrowButton()
  33976. {
  33977. }
  33978. void ArrowButton::paintButton (Graphics& g,
  33979. bool /*isMouseOverButton*/,
  33980. bool /*isButtonDown*/)
  33981. {
  33982. g.setColour (colour);
  33983. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  33984. (float) offset,
  33985. (float) (getWidth() - 3),
  33986. (float) (getHeight() - 3),
  33987. false));
  33988. }
  33989. void ArrowButton::buttonStateChanged()
  33990. {
  33991. offset = (isDown()) ? 1 : 0;
  33992. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  33993. 0.3f, -1, 0);
  33994. }
  33995. END_JUCE_NAMESPACE
  33996. /*** End of inlined file: juce_ArrowButton.cpp ***/
  33997. /*** Start of inlined file: juce_Button.cpp ***/
  33998. BEGIN_JUCE_NAMESPACE
  33999. class Button::RepeatTimer : public Timer
  34000. {
  34001. public:
  34002. RepeatTimer (Button& owner_) : owner (owner_) {}
  34003. void timerCallback() { owner.repeatTimerCallback(); }
  34004. juce_UseDebuggingNewOperator
  34005. private:
  34006. Button& owner;
  34007. RepeatTimer (const RepeatTimer&);
  34008. RepeatTimer& operator= (const RepeatTimer&);
  34009. };
  34010. Button::Button (const String& name)
  34011. : Component (name),
  34012. text (name),
  34013. buttonPressTime (0),
  34014. lastTimeCallbackTime (0),
  34015. commandManagerToUse (0),
  34016. autoRepeatDelay (-1),
  34017. autoRepeatSpeed (0),
  34018. autoRepeatMinimumDelay (-1),
  34019. radioGroupId (0),
  34020. commandID (0),
  34021. connectedEdgeFlags (0),
  34022. buttonState (buttonNormal),
  34023. lastToggleState (false),
  34024. clickTogglesState (false),
  34025. needsToRelease (false),
  34026. needsRepainting (false),
  34027. isKeyDown (false),
  34028. triggerOnMouseDown (false),
  34029. generateTooltip (false)
  34030. {
  34031. setWantsKeyboardFocus (true);
  34032. isOn.addListener (this);
  34033. }
  34034. Button::~Button()
  34035. {
  34036. isOn.removeListener (this);
  34037. if (commandManagerToUse != 0)
  34038. commandManagerToUse->removeListener (this);
  34039. repeatTimer = 0;
  34040. clearShortcuts();
  34041. }
  34042. void Button::setButtonText (const String& newText)
  34043. {
  34044. if (text != newText)
  34045. {
  34046. text = newText;
  34047. repaint();
  34048. }
  34049. }
  34050. void Button::setTooltip (const String& newTooltip)
  34051. {
  34052. SettableTooltipClient::setTooltip (newTooltip);
  34053. generateTooltip = false;
  34054. }
  34055. const String Button::getTooltip()
  34056. {
  34057. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34058. {
  34059. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34060. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34061. for (int i = 0; i < keyPresses.size(); ++i)
  34062. {
  34063. const String key (keyPresses.getReference(i).getTextDescription());
  34064. tt << " [";
  34065. if (key.length() == 1)
  34066. tt << TRANS("shortcut") << ": '" << key << "']";
  34067. else
  34068. tt << key << ']';
  34069. }
  34070. return tt;
  34071. }
  34072. return SettableTooltipClient::getTooltip();
  34073. }
  34074. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34075. {
  34076. if (connectedEdgeFlags != connectedEdgeFlags_)
  34077. {
  34078. connectedEdgeFlags = connectedEdgeFlags_;
  34079. repaint();
  34080. }
  34081. }
  34082. void Button::setToggleState (const bool shouldBeOn,
  34083. const bool sendChangeNotification)
  34084. {
  34085. if (shouldBeOn != lastToggleState)
  34086. {
  34087. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34088. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34089. lastToggleState = shouldBeOn;
  34090. repaint();
  34091. if (sendChangeNotification)
  34092. {
  34093. Component::SafePointer<Component> deletionWatcher (this);
  34094. sendClickMessage (ModifierKeys());
  34095. if (deletionWatcher == 0)
  34096. return;
  34097. }
  34098. if (lastToggleState)
  34099. turnOffOtherButtonsInGroup (sendChangeNotification);
  34100. }
  34101. }
  34102. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34103. {
  34104. clickTogglesState = shouldToggle;
  34105. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34106. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34107. // it is that this button represents, and the button will update its state to reflect this
  34108. // in the applicationCommandListChanged() method.
  34109. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34110. }
  34111. bool Button::getClickingTogglesState() const throw()
  34112. {
  34113. return clickTogglesState;
  34114. }
  34115. void Button::valueChanged (Value& value)
  34116. {
  34117. if (value.refersToSameSourceAs (isOn))
  34118. setToggleState (isOn.getValue(), true);
  34119. }
  34120. void Button::setRadioGroupId (const int newGroupId)
  34121. {
  34122. if (radioGroupId != newGroupId)
  34123. {
  34124. radioGroupId = newGroupId;
  34125. if (lastToggleState)
  34126. turnOffOtherButtonsInGroup (true);
  34127. }
  34128. }
  34129. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34130. {
  34131. Component* const p = getParentComponent();
  34132. if (p != 0 && radioGroupId != 0)
  34133. {
  34134. Component::SafePointer<Component> deletionWatcher (this);
  34135. for (int i = p->getNumChildComponents(); --i >= 0;)
  34136. {
  34137. Component* const c = p->getChildComponent (i);
  34138. if (c != this)
  34139. {
  34140. Button* const b = dynamic_cast <Button*> (c);
  34141. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34142. {
  34143. b->setToggleState (false, sendChangeNotification);
  34144. if (deletionWatcher == 0)
  34145. return;
  34146. }
  34147. }
  34148. }
  34149. }
  34150. }
  34151. void Button::enablementChanged()
  34152. {
  34153. updateState (0);
  34154. repaint();
  34155. }
  34156. Button::ButtonState Button::updateState (const MouseEvent* const e)
  34157. {
  34158. ButtonState state = buttonNormal;
  34159. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34160. {
  34161. Point<int> mousePos;
  34162. if (e == 0)
  34163. mousePos = getMouseXYRelative();
  34164. else
  34165. mousePos = e->getEventRelativeTo (this).getPosition();
  34166. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  34167. const bool down = isMouseButtonDown();
  34168. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34169. state = buttonDown;
  34170. else if (over)
  34171. state = buttonOver;
  34172. }
  34173. setState (state);
  34174. return state;
  34175. }
  34176. void Button::setState (const ButtonState newState)
  34177. {
  34178. if (buttonState != newState)
  34179. {
  34180. buttonState = newState;
  34181. repaint();
  34182. if (buttonState == buttonDown)
  34183. {
  34184. buttonPressTime = Time::getApproximateMillisecondCounter();
  34185. lastTimeCallbackTime = buttonPressTime;
  34186. }
  34187. sendStateMessage();
  34188. }
  34189. }
  34190. bool Button::isDown() const throw()
  34191. {
  34192. return buttonState == buttonDown;
  34193. }
  34194. bool Button::isOver() const throw()
  34195. {
  34196. return buttonState != buttonNormal;
  34197. }
  34198. void Button::buttonStateChanged()
  34199. {
  34200. }
  34201. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34202. {
  34203. const uint32 now = Time::getApproximateMillisecondCounter();
  34204. return now > buttonPressTime ? now - buttonPressTime : 0;
  34205. }
  34206. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34207. {
  34208. triggerOnMouseDown = isTriggeredOnMouseDown;
  34209. }
  34210. void Button::clicked()
  34211. {
  34212. }
  34213. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34214. {
  34215. clicked();
  34216. }
  34217. static const int clickMessageId = 0x2f3f4f99;
  34218. void Button::triggerClick()
  34219. {
  34220. postCommandMessage (clickMessageId);
  34221. }
  34222. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34223. {
  34224. if (clickTogglesState)
  34225. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34226. sendClickMessage (modifiers);
  34227. }
  34228. void Button::flashButtonState()
  34229. {
  34230. if (isEnabled())
  34231. {
  34232. needsToRelease = true;
  34233. setState (buttonDown);
  34234. getRepeatTimer().startTimer (100);
  34235. }
  34236. }
  34237. void Button::handleCommandMessage (int commandId)
  34238. {
  34239. if (commandId == clickMessageId)
  34240. {
  34241. if (isEnabled())
  34242. {
  34243. flashButtonState();
  34244. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34245. }
  34246. }
  34247. else
  34248. {
  34249. Component::handleCommandMessage (commandId);
  34250. }
  34251. }
  34252. void Button::addButtonListener (Listener* const newListener)
  34253. {
  34254. buttonListeners.add (newListener);
  34255. }
  34256. void Button::removeButtonListener (Listener* const listener)
  34257. {
  34258. buttonListeners.remove (listener);
  34259. }
  34260. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34261. {
  34262. Component::BailOutChecker checker (this);
  34263. if (commandManagerToUse != 0 && commandID != 0)
  34264. {
  34265. ApplicationCommandTarget::InvocationInfo info (commandID);
  34266. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34267. info.originatingComponent = this;
  34268. commandManagerToUse->invoke (info, true);
  34269. }
  34270. clicked (modifiers);
  34271. if (! checker.shouldBailOut())
  34272. buttonListeners.callChecked (checker, &Listener::buttonClicked, this);
  34273. }
  34274. void Button::sendStateMessage()
  34275. {
  34276. Component::BailOutChecker checker (this);
  34277. buttonStateChanged();
  34278. if (! checker.shouldBailOut())
  34279. buttonListeners.callChecked (checker, &Listener::buttonStateChanged, this);
  34280. }
  34281. void Button::paint (Graphics& g)
  34282. {
  34283. if (needsToRelease && isEnabled())
  34284. {
  34285. needsToRelease = false;
  34286. needsRepainting = true;
  34287. }
  34288. paintButton (g, isOver(), isDown());
  34289. }
  34290. void Button::mouseEnter (const MouseEvent& e)
  34291. {
  34292. updateState (&e);
  34293. }
  34294. void Button::mouseExit (const MouseEvent& e)
  34295. {
  34296. updateState (&e);
  34297. }
  34298. void Button::mouseDown (const MouseEvent& e)
  34299. {
  34300. updateState (&e);
  34301. if (isDown())
  34302. {
  34303. if (autoRepeatDelay >= 0)
  34304. getRepeatTimer().startTimer (autoRepeatDelay);
  34305. if (triggerOnMouseDown)
  34306. internalClickCallback (e.mods);
  34307. }
  34308. }
  34309. void Button::mouseUp (const MouseEvent& e)
  34310. {
  34311. const bool wasDown = isDown();
  34312. updateState (&e);
  34313. if (wasDown && isOver() && ! triggerOnMouseDown)
  34314. internalClickCallback (e.mods);
  34315. }
  34316. void Button::mouseDrag (const MouseEvent& e)
  34317. {
  34318. const ButtonState oldState = buttonState;
  34319. updateState (&e);
  34320. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  34321. getRepeatTimer().startTimer (autoRepeatSpeed);
  34322. }
  34323. void Button::focusGained (FocusChangeType)
  34324. {
  34325. updateState (0);
  34326. repaint();
  34327. }
  34328. void Button::focusLost (FocusChangeType)
  34329. {
  34330. updateState (0);
  34331. repaint();
  34332. }
  34333. void Button::setVisible (bool shouldBeVisible)
  34334. {
  34335. if (shouldBeVisible != isVisible())
  34336. {
  34337. Component::setVisible (shouldBeVisible);
  34338. if (! shouldBeVisible)
  34339. needsToRelease = false;
  34340. updateState (0);
  34341. }
  34342. else
  34343. {
  34344. Component::setVisible (shouldBeVisible);
  34345. }
  34346. }
  34347. void Button::parentHierarchyChanged()
  34348. {
  34349. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  34350. if (newKeySource != keySource.getComponent())
  34351. {
  34352. if (keySource != 0)
  34353. keySource->removeKeyListener (this);
  34354. keySource = newKeySource;
  34355. if (keySource != 0)
  34356. keySource->addKeyListener (this);
  34357. }
  34358. }
  34359. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  34360. const int commandID_,
  34361. const bool generateTooltip_)
  34362. {
  34363. commandID = commandID_;
  34364. generateTooltip = generateTooltip_;
  34365. if (commandManagerToUse != commandManagerToUse_)
  34366. {
  34367. if (commandManagerToUse != 0)
  34368. commandManagerToUse->removeListener (this);
  34369. commandManagerToUse = commandManagerToUse_;
  34370. if (commandManagerToUse != 0)
  34371. commandManagerToUse->addListener (this);
  34372. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34373. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34374. // it is that this button represents, and the button will update its state to reflect this
  34375. // in the applicationCommandListChanged() method.
  34376. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34377. }
  34378. if (commandManagerToUse != 0)
  34379. applicationCommandListChanged();
  34380. else
  34381. setEnabled (true);
  34382. }
  34383. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  34384. {
  34385. if (info.commandID == commandID
  34386. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  34387. {
  34388. flashButtonState();
  34389. }
  34390. }
  34391. void Button::applicationCommandListChanged()
  34392. {
  34393. if (commandManagerToUse != 0)
  34394. {
  34395. ApplicationCommandInfo info (0);
  34396. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  34397. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  34398. if (target != 0)
  34399. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  34400. }
  34401. }
  34402. void Button::addShortcut (const KeyPress& key)
  34403. {
  34404. if (key.isValid())
  34405. {
  34406. jassert (! isRegisteredForShortcut (key)); // already registered!
  34407. shortcuts.add (key);
  34408. parentHierarchyChanged();
  34409. }
  34410. }
  34411. void Button::clearShortcuts()
  34412. {
  34413. shortcuts.clear();
  34414. parentHierarchyChanged();
  34415. }
  34416. bool Button::isShortcutPressed() const
  34417. {
  34418. if (! isCurrentlyBlockedByAnotherModalComponent())
  34419. {
  34420. for (int i = shortcuts.size(); --i >= 0;)
  34421. if (shortcuts.getReference(i).isCurrentlyDown())
  34422. return true;
  34423. }
  34424. return false;
  34425. }
  34426. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  34427. {
  34428. for (int i = shortcuts.size(); --i >= 0;)
  34429. if (key == shortcuts.getReference(i))
  34430. return true;
  34431. return false;
  34432. }
  34433. bool Button::keyStateChanged (const bool, Component*)
  34434. {
  34435. if (! isEnabled())
  34436. return false;
  34437. const bool wasDown = isKeyDown;
  34438. isKeyDown = isShortcutPressed();
  34439. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  34440. getRepeatTimer().startTimer (autoRepeatDelay);
  34441. updateState (0);
  34442. if (isEnabled() && wasDown && ! isKeyDown)
  34443. {
  34444. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34445. // (return immediately - this button may now have been deleted)
  34446. return true;
  34447. }
  34448. return wasDown || isKeyDown;
  34449. }
  34450. bool Button::keyPressed (const KeyPress&, Component*)
  34451. {
  34452. // returning true will avoid forwarding events for keys that we're using as shortcuts
  34453. return isShortcutPressed();
  34454. }
  34455. bool Button::keyPressed (const KeyPress& key)
  34456. {
  34457. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  34458. {
  34459. triggerClick();
  34460. return true;
  34461. }
  34462. return false;
  34463. }
  34464. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  34465. const int repeatMillisecs,
  34466. const int minimumDelayInMillisecs) throw()
  34467. {
  34468. autoRepeatDelay = initialDelayMillisecs;
  34469. autoRepeatSpeed = repeatMillisecs;
  34470. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  34471. }
  34472. void Button::repeatTimerCallback()
  34473. {
  34474. if (needsRepainting)
  34475. {
  34476. getRepeatTimer().stopTimer();
  34477. updateState (0);
  34478. needsRepainting = false;
  34479. }
  34480. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  34481. {
  34482. int repeatSpeed = autoRepeatSpeed;
  34483. if (autoRepeatMinimumDelay >= 0)
  34484. {
  34485. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  34486. timeHeldDown *= timeHeldDown;
  34487. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  34488. }
  34489. repeatSpeed = jmax (1, repeatSpeed);
  34490. getRepeatTimer().startTimer (repeatSpeed);
  34491. const uint32 now = Time::getApproximateMillisecondCounter();
  34492. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  34493. lastTimeCallbackTime = now;
  34494. Component::SafePointer<Component> deletionWatcher (this);
  34495. for (int i = numTimesToCallback; --i >= 0;)
  34496. {
  34497. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34498. if (deletionWatcher == 0 || ! isDown())
  34499. return;
  34500. }
  34501. }
  34502. else if (! needsToRelease)
  34503. {
  34504. getRepeatTimer().stopTimer();
  34505. }
  34506. }
  34507. Button::RepeatTimer& Button::getRepeatTimer()
  34508. {
  34509. if (repeatTimer == 0)
  34510. repeatTimer = new RepeatTimer (*this);
  34511. return *repeatTimer;
  34512. }
  34513. END_JUCE_NAMESPACE
  34514. /*** End of inlined file: juce_Button.cpp ***/
  34515. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  34516. BEGIN_JUCE_NAMESPACE
  34517. DrawableButton::DrawableButton (const String& name,
  34518. const DrawableButton::ButtonStyle buttonStyle)
  34519. : Button (name),
  34520. style (buttonStyle),
  34521. edgeIndent (3)
  34522. {
  34523. if (buttonStyle == ImageOnButtonBackground)
  34524. {
  34525. backgroundOff = Colour (0xffbbbbff);
  34526. backgroundOn = Colour (0xff3333ff);
  34527. }
  34528. else
  34529. {
  34530. backgroundOff = Colours::transparentBlack;
  34531. backgroundOn = Colour (0xaabbbbff);
  34532. }
  34533. }
  34534. DrawableButton::~DrawableButton()
  34535. {
  34536. deleteImages();
  34537. }
  34538. void DrawableButton::deleteImages()
  34539. {
  34540. }
  34541. void DrawableButton::setImages (const Drawable* normal,
  34542. const Drawable* over,
  34543. const Drawable* down,
  34544. const Drawable* disabled,
  34545. const Drawable* normalOn,
  34546. const Drawable* overOn,
  34547. const Drawable* downOn,
  34548. const Drawable* disabledOn)
  34549. {
  34550. deleteImages();
  34551. jassert (normal != 0); // you really need to give it at least a normal image..
  34552. if (normal != 0)
  34553. normalImage = normal->createCopy();
  34554. if (over != 0)
  34555. overImage = over->createCopy();
  34556. if (down != 0)
  34557. downImage = down->createCopy();
  34558. if (disabled != 0)
  34559. disabledImage = disabled->createCopy();
  34560. if (normalOn != 0)
  34561. normalImageOn = normalOn->createCopy();
  34562. if (overOn != 0)
  34563. overImageOn = overOn->createCopy();
  34564. if (downOn != 0)
  34565. downImageOn = downOn->createCopy();
  34566. if (disabledOn != 0)
  34567. disabledImageOn = disabledOn->createCopy();
  34568. repaint();
  34569. }
  34570. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  34571. {
  34572. if (style != newStyle)
  34573. {
  34574. style = newStyle;
  34575. repaint();
  34576. }
  34577. }
  34578. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  34579. const Colour& toggledOnColour)
  34580. {
  34581. if (backgroundOff != toggledOffColour
  34582. || backgroundOn != toggledOnColour)
  34583. {
  34584. backgroundOff = toggledOffColour;
  34585. backgroundOn = toggledOnColour;
  34586. repaint();
  34587. }
  34588. }
  34589. const Colour& DrawableButton::getBackgroundColour() const throw()
  34590. {
  34591. return getToggleState() ? backgroundOn
  34592. : backgroundOff;
  34593. }
  34594. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  34595. {
  34596. edgeIndent = numPixelsIndent;
  34597. repaint();
  34598. }
  34599. void DrawableButton::paintButton (Graphics& g,
  34600. bool isMouseOverButton,
  34601. bool isButtonDown)
  34602. {
  34603. Rectangle<int> imageSpace;
  34604. if (style == ImageOnButtonBackground)
  34605. {
  34606. const int insetX = getWidth() / 4;
  34607. const int insetY = getHeight() / 4;
  34608. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  34609. getLookAndFeel().drawButtonBackground (g, *this,
  34610. getBackgroundColour(),
  34611. isMouseOverButton,
  34612. isButtonDown);
  34613. }
  34614. else
  34615. {
  34616. g.fillAll (getBackgroundColour());
  34617. const int textH = (style == ImageAboveTextLabel)
  34618. ? jmin (16, proportionOfHeight (0.25f))
  34619. : 0;
  34620. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  34621. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  34622. imageSpace.setBounds (indentX, indentY,
  34623. getWidth() - indentX * 2,
  34624. getHeight() - indentY * 2 - textH);
  34625. if (textH > 0)
  34626. {
  34627. g.setFont ((float) textH);
  34628. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  34629. g.drawFittedText (getButtonText(),
  34630. 2, getHeight() - textH - 1,
  34631. getWidth() - 4, textH,
  34632. Justification::centred, 1);
  34633. }
  34634. }
  34635. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  34636. g.setOpacity (1.0f);
  34637. const Drawable* imageToDraw = 0;
  34638. if (isEnabled())
  34639. {
  34640. imageToDraw = getCurrentImage();
  34641. }
  34642. else
  34643. {
  34644. imageToDraw = getToggleState() ? disabledImageOn
  34645. : disabledImage;
  34646. if (imageToDraw == 0)
  34647. {
  34648. g.setOpacity (0.4f);
  34649. imageToDraw = getNormalImage();
  34650. }
  34651. }
  34652. if (imageToDraw != 0)
  34653. {
  34654. if (style == ImageRaw)
  34655. {
  34656. imageToDraw->draw (g, 1.0f);
  34657. }
  34658. else
  34659. {
  34660. imageToDraw->drawWithin (g,
  34661. imageSpace.getX(),
  34662. imageSpace.getY(),
  34663. imageSpace.getWidth(),
  34664. imageSpace.getHeight(),
  34665. RectanglePlacement::centred,
  34666. 1.0f);
  34667. }
  34668. }
  34669. }
  34670. const Drawable* DrawableButton::getCurrentImage() const throw()
  34671. {
  34672. if (isDown())
  34673. return getDownImage();
  34674. if (isOver())
  34675. return getOverImage();
  34676. return getNormalImage();
  34677. }
  34678. const Drawable* DrawableButton::getNormalImage() const throw()
  34679. {
  34680. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  34681. : normalImage;
  34682. }
  34683. const Drawable* DrawableButton::getOverImage() const throw()
  34684. {
  34685. const Drawable* d = normalImage;
  34686. if (getToggleState())
  34687. {
  34688. if (overImageOn != 0)
  34689. d = overImageOn;
  34690. else if (normalImageOn != 0)
  34691. d = normalImageOn;
  34692. else if (overImage != 0)
  34693. d = overImage;
  34694. }
  34695. else
  34696. {
  34697. if (overImage != 0)
  34698. d = overImage;
  34699. }
  34700. return d;
  34701. }
  34702. const Drawable* DrawableButton::getDownImage() const throw()
  34703. {
  34704. const Drawable* d = normalImage;
  34705. if (getToggleState())
  34706. {
  34707. if (downImageOn != 0)
  34708. d = downImageOn;
  34709. else if (overImageOn != 0)
  34710. d = overImageOn;
  34711. else if (normalImageOn != 0)
  34712. d = normalImageOn;
  34713. else if (downImage != 0)
  34714. d = downImage;
  34715. else
  34716. d = getOverImage();
  34717. }
  34718. else
  34719. {
  34720. if (downImage != 0)
  34721. d = downImage;
  34722. else
  34723. d = getOverImage();
  34724. }
  34725. return d;
  34726. }
  34727. END_JUCE_NAMESPACE
  34728. /*** End of inlined file: juce_DrawableButton.cpp ***/
  34729. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  34730. BEGIN_JUCE_NAMESPACE
  34731. HyperlinkButton::HyperlinkButton (const String& linkText,
  34732. const URL& linkURL)
  34733. : Button (linkText),
  34734. url (linkURL),
  34735. font (14.0f, Font::underlined),
  34736. resizeFont (true),
  34737. justification (Justification::centred)
  34738. {
  34739. setMouseCursor (MouseCursor::PointingHandCursor);
  34740. setTooltip (linkURL.toString (false));
  34741. }
  34742. HyperlinkButton::~HyperlinkButton()
  34743. {
  34744. }
  34745. void HyperlinkButton::setFont (const Font& newFont,
  34746. const bool resizeToMatchComponentHeight,
  34747. const Justification& justificationType)
  34748. {
  34749. font = newFont;
  34750. resizeFont = resizeToMatchComponentHeight;
  34751. justification = justificationType;
  34752. repaint();
  34753. }
  34754. void HyperlinkButton::setURL (const URL& newURL) throw()
  34755. {
  34756. url = newURL;
  34757. setTooltip (newURL.toString (false));
  34758. }
  34759. const Font HyperlinkButton::getFontToUse() const
  34760. {
  34761. Font f (font);
  34762. if (resizeFont)
  34763. f.setHeight (getHeight() * 0.7f);
  34764. return f;
  34765. }
  34766. void HyperlinkButton::changeWidthToFitText()
  34767. {
  34768. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  34769. }
  34770. void HyperlinkButton::colourChanged()
  34771. {
  34772. repaint();
  34773. }
  34774. void HyperlinkButton::clicked()
  34775. {
  34776. if (url.isWellFormed())
  34777. url.launchInDefaultBrowser();
  34778. }
  34779. void HyperlinkButton::paintButton (Graphics& g,
  34780. bool isMouseOverButton,
  34781. bool isButtonDown)
  34782. {
  34783. const Colour textColour (findColour (textColourId));
  34784. if (isEnabled())
  34785. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  34786. : textColour);
  34787. else
  34788. g.setColour (textColour.withMultipliedAlpha (0.4f));
  34789. g.setFont (getFontToUse());
  34790. g.drawText (getButtonText(),
  34791. 2, 0, getWidth() - 2, getHeight(),
  34792. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  34793. true);
  34794. }
  34795. END_JUCE_NAMESPACE
  34796. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  34797. /*** Start of inlined file: juce_ImageButton.cpp ***/
  34798. BEGIN_JUCE_NAMESPACE
  34799. ImageButton::ImageButton (const String& text_)
  34800. : Button (text_),
  34801. scaleImageToFit (true),
  34802. preserveProportions (true),
  34803. alphaThreshold (0),
  34804. imageX (0),
  34805. imageY (0),
  34806. imageW (0),
  34807. imageH (0),
  34808. normalImage (0),
  34809. overImage (0),
  34810. downImage (0)
  34811. {
  34812. }
  34813. ImageButton::~ImageButton()
  34814. {
  34815. }
  34816. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  34817. const bool rescaleImagesWhenButtonSizeChanges,
  34818. const bool preserveImageProportions,
  34819. const Image& normalImage_,
  34820. const float imageOpacityWhenNormal,
  34821. const Colour& overlayColourWhenNormal,
  34822. const Image& overImage_,
  34823. const float imageOpacityWhenOver,
  34824. const Colour& overlayColourWhenOver,
  34825. const Image& downImage_,
  34826. const float imageOpacityWhenDown,
  34827. const Colour& overlayColourWhenDown,
  34828. const float hitTestAlphaThreshold)
  34829. {
  34830. normalImage = normalImage_;
  34831. overImage = overImage_;
  34832. downImage = downImage_;
  34833. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  34834. {
  34835. imageW = normalImage.getWidth();
  34836. imageH = normalImage.getHeight();
  34837. setSize (imageW, imageH);
  34838. }
  34839. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  34840. preserveProportions = preserveImageProportions;
  34841. normalOpacity = imageOpacityWhenNormal;
  34842. normalOverlay = overlayColourWhenNormal;
  34843. overOpacity = imageOpacityWhenOver;
  34844. overOverlay = overlayColourWhenOver;
  34845. downOpacity = imageOpacityWhenDown;
  34846. downOverlay = overlayColourWhenDown;
  34847. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  34848. repaint();
  34849. }
  34850. const Image ImageButton::getCurrentImage() const
  34851. {
  34852. if (isDown() || getToggleState())
  34853. return getDownImage();
  34854. if (isOver())
  34855. return getOverImage();
  34856. return getNormalImage();
  34857. }
  34858. const Image ImageButton::getNormalImage() const
  34859. {
  34860. return normalImage;
  34861. }
  34862. const Image ImageButton::getOverImage() const
  34863. {
  34864. return overImage.isValid() ? overImage
  34865. : normalImage;
  34866. }
  34867. const Image ImageButton::getDownImage() const
  34868. {
  34869. return downImage.isValid() ? downImage
  34870. : getOverImage();
  34871. }
  34872. void ImageButton::paintButton (Graphics& g,
  34873. bool isMouseOverButton,
  34874. bool isButtonDown)
  34875. {
  34876. if (! isEnabled())
  34877. {
  34878. isMouseOverButton = false;
  34879. isButtonDown = false;
  34880. }
  34881. Image im (getCurrentImage());
  34882. if (im.isValid())
  34883. {
  34884. const int iw = im.getWidth();
  34885. const int ih = im.getHeight();
  34886. imageW = getWidth();
  34887. imageH = getHeight();
  34888. imageX = (imageW - iw) >> 1;
  34889. imageY = (imageH - ih) >> 1;
  34890. if (scaleImageToFit)
  34891. {
  34892. if (preserveProportions)
  34893. {
  34894. int newW, newH;
  34895. const float imRatio = ih / (float)iw;
  34896. const float destRatio = imageH / (float)imageW;
  34897. if (imRatio > destRatio)
  34898. {
  34899. newW = roundToInt (imageH / imRatio);
  34900. newH = imageH;
  34901. }
  34902. else
  34903. {
  34904. newW = imageW;
  34905. newH = roundToInt (imageW * imRatio);
  34906. }
  34907. imageX = (imageW - newW) / 2;
  34908. imageY = (imageH - newH) / 2;
  34909. imageW = newW;
  34910. imageH = newH;
  34911. }
  34912. else
  34913. {
  34914. imageX = 0;
  34915. imageY = 0;
  34916. }
  34917. }
  34918. if (! scaleImageToFit)
  34919. {
  34920. imageW = iw;
  34921. imageH = ih;
  34922. }
  34923. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  34924. isButtonDown ? downOverlay
  34925. : (isMouseOverButton ? overOverlay
  34926. : normalOverlay),
  34927. isButtonDown ? downOpacity
  34928. : (isMouseOverButton ? overOpacity
  34929. : normalOpacity),
  34930. *this);
  34931. }
  34932. }
  34933. bool ImageButton::hitTest (int x, int y)
  34934. {
  34935. if (alphaThreshold == 0)
  34936. return true;
  34937. Image im (getCurrentImage());
  34938. return im.isNull() || (imageW > 0 && imageH > 0
  34939. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  34940. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  34941. }
  34942. END_JUCE_NAMESPACE
  34943. /*** End of inlined file: juce_ImageButton.cpp ***/
  34944. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  34945. BEGIN_JUCE_NAMESPACE
  34946. ShapeButton::ShapeButton (const String& text_,
  34947. const Colour& normalColour_,
  34948. const Colour& overColour_,
  34949. const Colour& downColour_)
  34950. : Button (text_),
  34951. normalColour (normalColour_),
  34952. overColour (overColour_),
  34953. downColour (downColour_),
  34954. maintainShapeProportions (false),
  34955. outlineWidth (0.0f)
  34956. {
  34957. }
  34958. ShapeButton::~ShapeButton()
  34959. {
  34960. }
  34961. void ShapeButton::setColours (const Colour& newNormalColour,
  34962. const Colour& newOverColour,
  34963. const Colour& newDownColour)
  34964. {
  34965. normalColour = newNormalColour;
  34966. overColour = newOverColour;
  34967. downColour = newDownColour;
  34968. }
  34969. void ShapeButton::setOutline (const Colour& newOutlineColour,
  34970. const float newOutlineWidth)
  34971. {
  34972. outlineColour = newOutlineColour;
  34973. outlineWidth = newOutlineWidth;
  34974. }
  34975. void ShapeButton::setShape (const Path& newShape,
  34976. const bool resizeNowToFitThisShape,
  34977. const bool maintainShapeProportions_,
  34978. const bool hasShadow)
  34979. {
  34980. shape = newShape;
  34981. maintainShapeProportions = maintainShapeProportions_;
  34982. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  34983. setComponentEffect ((hasShadow) ? &shadow : 0);
  34984. if (resizeNowToFitThisShape)
  34985. {
  34986. Rectangle<float> bounds (shape.getBounds());
  34987. if (hasShadow)
  34988. bounds.expand (4.0f, 4.0f);
  34989. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  34990. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  34991. 1 + (int) (bounds.getHeight() + outlineWidth));
  34992. }
  34993. }
  34994. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  34995. {
  34996. if (! isEnabled())
  34997. {
  34998. isMouseOverButton = false;
  34999. isButtonDown = false;
  35000. }
  35001. g.setColour ((isButtonDown) ? downColour
  35002. : (isMouseOverButton) ? overColour
  35003. : normalColour);
  35004. int w = getWidth();
  35005. int h = getHeight();
  35006. if (getComponentEffect() != 0)
  35007. {
  35008. w -= 4;
  35009. h -= 4;
  35010. }
  35011. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35012. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35013. w - offset - outlineWidth,
  35014. h - offset - outlineWidth,
  35015. maintainShapeProportions));
  35016. g.fillPath (shape, trans);
  35017. if (outlineWidth > 0.0f)
  35018. {
  35019. g.setColour (outlineColour);
  35020. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35021. }
  35022. }
  35023. END_JUCE_NAMESPACE
  35024. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35025. /*** Start of inlined file: juce_TextButton.cpp ***/
  35026. BEGIN_JUCE_NAMESPACE
  35027. TextButton::TextButton (const String& name,
  35028. const String& toolTip)
  35029. : Button (name)
  35030. {
  35031. setTooltip (toolTip);
  35032. }
  35033. TextButton::~TextButton()
  35034. {
  35035. }
  35036. void TextButton::paintButton (Graphics& g,
  35037. bool isMouseOverButton,
  35038. bool isButtonDown)
  35039. {
  35040. getLookAndFeel().drawButtonBackground (g, *this,
  35041. findColour (getToggleState() ? buttonOnColourId
  35042. : buttonColourId),
  35043. isMouseOverButton,
  35044. isButtonDown);
  35045. getLookAndFeel().drawButtonText (g, *this,
  35046. isMouseOverButton,
  35047. isButtonDown);
  35048. }
  35049. void TextButton::colourChanged()
  35050. {
  35051. repaint();
  35052. }
  35053. const Font TextButton::getFont()
  35054. {
  35055. return Font (jmin (15.0f, getHeight() * 0.6f));
  35056. }
  35057. void TextButton::changeWidthToFitText (const int newHeight)
  35058. {
  35059. if (newHeight >= 0)
  35060. setSize (jmax (1, getWidth()), newHeight);
  35061. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35062. getHeight());
  35063. }
  35064. END_JUCE_NAMESPACE
  35065. /*** End of inlined file: juce_TextButton.cpp ***/
  35066. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35067. BEGIN_JUCE_NAMESPACE
  35068. ToggleButton::ToggleButton (const String& buttonText)
  35069. : Button (buttonText)
  35070. {
  35071. setClickingTogglesState (true);
  35072. }
  35073. ToggleButton::~ToggleButton()
  35074. {
  35075. }
  35076. void ToggleButton::paintButton (Graphics& g,
  35077. bool isMouseOverButton,
  35078. bool isButtonDown)
  35079. {
  35080. getLookAndFeel().drawToggleButton (g, *this,
  35081. isMouseOverButton,
  35082. isButtonDown);
  35083. }
  35084. void ToggleButton::changeWidthToFitText()
  35085. {
  35086. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35087. }
  35088. void ToggleButton::colourChanged()
  35089. {
  35090. repaint();
  35091. }
  35092. END_JUCE_NAMESPACE
  35093. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35094. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35095. BEGIN_JUCE_NAMESPACE
  35096. ToolbarButton::ToolbarButton (const int itemId_,
  35097. const String& buttonText,
  35098. Drawable* const normalImage_,
  35099. Drawable* const toggledOnImage_)
  35100. : ToolbarItemComponent (itemId_, buttonText, true),
  35101. normalImage (normalImage_),
  35102. toggledOnImage (toggledOnImage_)
  35103. {
  35104. jassert (normalImage_ != 0);
  35105. }
  35106. ToolbarButton::~ToolbarButton()
  35107. {
  35108. }
  35109. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  35110. bool /*isToolbarVertical*/,
  35111. int& preferredSize,
  35112. int& minSize, int& maxSize)
  35113. {
  35114. preferredSize = minSize = maxSize = toolbarDepth;
  35115. return true;
  35116. }
  35117. void ToolbarButton::paintButtonArea (Graphics& g,
  35118. int width, int height,
  35119. bool /*isMouseOver*/,
  35120. bool /*isMouseDown*/)
  35121. {
  35122. Drawable* d = normalImage;
  35123. if (getToggleState() && toggledOnImage != 0)
  35124. d = toggledOnImage;
  35125. if (! isEnabled())
  35126. {
  35127. Image im (Image::ARGB, width, height, true);
  35128. {
  35129. Graphics g2 (im);
  35130. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35131. }
  35132. im.desaturate();
  35133. g.drawImageAt (im, 0, 0);
  35134. }
  35135. else
  35136. {
  35137. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35138. }
  35139. }
  35140. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35141. {
  35142. }
  35143. END_JUCE_NAMESPACE
  35144. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35145. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35146. BEGIN_JUCE_NAMESPACE
  35147. class CodeDocumentLine
  35148. {
  35149. public:
  35150. CodeDocumentLine (const juce_wchar* const line_,
  35151. const int lineLength_,
  35152. const int numNewLineChars,
  35153. const int lineStartInFile_)
  35154. : line (line_, lineLength_),
  35155. lineStartInFile (lineStartInFile_),
  35156. lineLength (lineLength_),
  35157. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35158. {
  35159. }
  35160. ~CodeDocumentLine()
  35161. {
  35162. }
  35163. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35164. {
  35165. const juce_wchar* const t = text;
  35166. int pos = 0;
  35167. while (t [pos] != 0)
  35168. {
  35169. const int startOfLine = pos;
  35170. int numNewLineChars = 0;
  35171. while (t[pos] != 0)
  35172. {
  35173. if (t[pos] == '\r')
  35174. {
  35175. ++numNewLineChars;
  35176. ++pos;
  35177. if (t[pos] == '\n')
  35178. {
  35179. ++numNewLineChars;
  35180. ++pos;
  35181. }
  35182. break;
  35183. }
  35184. if (t[pos] == '\n')
  35185. {
  35186. ++numNewLineChars;
  35187. ++pos;
  35188. break;
  35189. }
  35190. ++pos;
  35191. }
  35192. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  35193. numNewLineChars, startOfLine));
  35194. }
  35195. jassert (pos == text.length());
  35196. }
  35197. bool endsWithLineBreak() const throw()
  35198. {
  35199. return lineLengthWithoutNewLines != lineLength;
  35200. }
  35201. void updateLength() throw()
  35202. {
  35203. lineLengthWithoutNewLines = lineLength = line.length();
  35204. while (lineLengthWithoutNewLines > 0
  35205. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35206. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35207. {
  35208. --lineLengthWithoutNewLines;
  35209. }
  35210. }
  35211. String line;
  35212. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35213. };
  35214. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35215. : document (document_),
  35216. currentLine (document_->lines[0]),
  35217. line (0),
  35218. position (0)
  35219. {
  35220. }
  35221. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35222. : document (other.document),
  35223. currentLine (other.currentLine),
  35224. line (other.line),
  35225. position (other.position)
  35226. {
  35227. }
  35228. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35229. {
  35230. document = other.document;
  35231. currentLine = other.currentLine;
  35232. line = other.line;
  35233. position = other.position;
  35234. return *this;
  35235. }
  35236. CodeDocument::Iterator::~Iterator() throw()
  35237. {
  35238. }
  35239. juce_wchar CodeDocument::Iterator::nextChar()
  35240. {
  35241. if (currentLine == 0)
  35242. return 0;
  35243. jassert (currentLine == document->lines.getUnchecked (line));
  35244. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35245. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35246. {
  35247. ++line;
  35248. currentLine = document->lines [line];
  35249. }
  35250. return result;
  35251. }
  35252. void CodeDocument::Iterator::skip()
  35253. {
  35254. if (currentLine != 0)
  35255. {
  35256. jassert (currentLine == document->lines.getUnchecked (line));
  35257. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35258. {
  35259. ++line;
  35260. currentLine = document->lines [line];
  35261. }
  35262. }
  35263. }
  35264. void CodeDocument::Iterator::skipToEndOfLine()
  35265. {
  35266. if (currentLine != 0)
  35267. {
  35268. jassert (currentLine == document->lines.getUnchecked (line));
  35269. ++line;
  35270. currentLine = document->lines [line];
  35271. if (currentLine != 0)
  35272. position = currentLine->lineStartInFile;
  35273. else
  35274. position = document->getNumCharacters();
  35275. }
  35276. }
  35277. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35278. {
  35279. if (currentLine == 0)
  35280. return 0;
  35281. jassert (currentLine == document->lines.getUnchecked (line));
  35282. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35283. }
  35284. void CodeDocument::Iterator::skipWhitespace()
  35285. {
  35286. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35287. skip();
  35288. }
  35289. bool CodeDocument::Iterator::isEOF() const throw()
  35290. {
  35291. return currentLine == 0;
  35292. }
  35293. CodeDocument::Position::Position() throw()
  35294. : owner (0), characterPos (0), line (0),
  35295. indexInLine (0), positionMaintained (false)
  35296. {
  35297. }
  35298. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35299. const int line_, const int indexInLine_) throw()
  35300. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35301. characterPos (0), line (line_),
  35302. indexInLine (indexInLine_), positionMaintained (false)
  35303. {
  35304. setLineAndIndex (line_, indexInLine_);
  35305. }
  35306. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35307. const int characterPos_) throw()
  35308. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35309. positionMaintained (false)
  35310. {
  35311. setPosition (characterPos_);
  35312. }
  35313. CodeDocument::Position::Position (const Position& other) throw()
  35314. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  35315. indexInLine (other.indexInLine), positionMaintained (false)
  35316. {
  35317. jassert (*this == other);
  35318. }
  35319. CodeDocument::Position::~Position() throw()
  35320. {
  35321. setPositionMaintained (false);
  35322. }
  35323. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other) throw()
  35324. {
  35325. if (this != &other)
  35326. {
  35327. const bool wasPositionMaintained = positionMaintained;
  35328. if (owner != other.owner)
  35329. setPositionMaintained (false);
  35330. owner = other.owner;
  35331. line = other.line;
  35332. indexInLine = other.indexInLine;
  35333. characterPos = other.characterPos;
  35334. setPositionMaintained (wasPositionMaintained);
  35335. jassert (*this == other);
  35336. }
  35337. return *this;
  35338. }
  35339. bool CodeDocument::Position::operator== (const Position& other) const throw()
  35340. {
  35341. jassert ((characterPos == other.characterPos)
  35342. == (line == other.line && indexInLine == other.indexInLine));
  35343. return characterPos == other.characterPos
  35344. && line == other.line
  35345. && indexInLine == other.indexInLine
  35346. && owner == other.owner;
  35347. }
  35348. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  35349. {
  35350. return ! operator== (other);
  35351. }
  35352. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine) throw()
  35353. {
  35354. jassert (owner != 0);
  35355. if (owner->lines.size() == 0)
  35356. {
  35357. line = 0;
  35358. indexInLine = 0;
  35359. characterPos = 0;
  35360. }
  35361. else
  35362. {
  35363. if (newLine >= owner->lines.size())
  35364. {
  35365. line = owner->lines.size() - 1;
  35366. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35367. jassert (l != 0);
  35368. indexInLine = l->lineLengthWithoutNewLines;
  35369. characterPos = l->lineStartInFile + indexInLine;
  35370. }
  35371. else
  35372. {
  35373. line = jmax (0, newLine);
  35374. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35375. jassert (l != 0);
  35376. if (l->lineLengthWithoutNewLines > 0)
  35377. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  35378. else
  35379. indexInLine = 0;
  35380. characterPos = l->lineStartInFile + indexInLine;
  35381. }
  35382. }
  35383. }
  35384. void CodeDocument::Position::setPosition (const int newPosition) throw()
  35385. {
  35386. jassert (owner != 0);
  35387. line = 0;
  35388. indexInLine = 0;
  35389. characterPos = 0;
  35390. if (newPosition > 0)
  35391. {
  35392. int lineStart = 0;
  35393. int lineEnd = owner->lines.size();
  35394. for (;;)
  35395. {
  35396. if (lineEnd - lineStart < 4)
  35397. {
  35398. for (int i = lineStart; i < lineEnd; ++i)
  35399. {
  35400. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  35401. int index = newPosition - l->lineStartInFile;
  35402. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  35403. {
  35404. line = i;
  35405. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  35406. characterPos = l->lineStartInFile + indexInLine;
  35407. }
  35408. }
  35409. break;
  35410. }
  35411. else
  35412. {
  35413. const int midIndex = (lineStart + lineEnd + 1) / 2;
  35414. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  35415. if (newPosition >= mid->lineStartInFile)
  35416. lineStart = midIndex;
  35417. else
  35418. lineEnd = midIndex;
  35419. }
  35420. }
  35421. }
  35422. }
  35423. void CodeDocument::Position::moveBy (int characterDelta) throw()
  35424. {
  35425. jassert (owner != 0);
  35426. if (characterDelta == 1)
  35427. {
  35428. setPosition (getPosition());
  35429. // If moving right, make sure we don't get stuck between the \r and \n characters..
  35430. if (line < owner->lines.size())
  35431. {
  35432. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35433. if (indexInLine + characterDelta < l->lineLength
  35434. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  35435. ++characterDelta;
  35436. }
  35437. }
  35438. setPosition (characterPos + characterDelta);
  35439. }
  35440. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const throw()
  35441. {
  35442. CodeDocument::Position p (*this);
  35443. p.moveBy (characterDelta);
  35444. return p;
  35445. }
  35446. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const throw()
  35447. {
  35448. CodeDocument::Position p (*this);
  35449. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  35450. return p;
  35451. }
  35452. const juce_wchar CodeDocument::Position::getCharacter() const throw()
  35453. {
  35454. const CodeDocumentLine* const l = owner->lines [line];
  35455. return l == 0 ? 0 : l->line [getIndexInLine()];
  35456. }
  35457. const String CodeDocument::Position::getLineText() const throw()
  35458. {
  35459. const CodeDocumentLine* const l = owner->lines [line];
  35460. return l == 0 ? String::empty : l->line;
  35461. }
  35462. void CodeDocument::Position::setPositionMaintained (const bool isMaintained) throw()
  35463. {
  35464. if (isMaintained != positionMaintained)
  35465. {
  35466. positionMaintained = isMaintained;
  35467. if (owner != 0)
  35468. {
  35469. if (isMaintained)
  35470. {
  35471. jassert (! owner->positionsToMaintain.contains (this));
  35472. owner->positionsToMaintain.add (this);
  35473. }
  35474. else
  35475. {
  35476. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  35477. jassert (owner->positionsToMaintain.contains (this));
  35478. owner->positionsToMaintain.removeValue (this);
  35479. }
  35480. }
  35481. }
  35482. }
  35483. CodeDocument::CodeDocument()
  35484. : undoManager (std::numeric_limits<int>::max(), 10000),
  35485. currentActionIndex (0),
  35486. indexOfSavedState (-1),
  35487. maximumLineLength (-1),
  35488. newLineChars ("\r\n")
  35489. {
  35490. }
  35491. CodeDocument::~CodeDocument()
  35492. {
  35493. }
  35494. const String CodeDocument::getAllContent() const throw()
  35495. {
  35496. return getTextBetween (Position (this, 0),
  35497. Position (this, lines.size(), 0));
  35498. }
  35499. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const throw()
  35500. {
  35501. if (end.getPosition() <= start.getPosition())
  35502. return String::empty;
  35503. const int startLine = start.getLineNumber();
  35504. const int endLine = end.getLineNumber();
  35505. if (startLine == endLine)
  35506. {
  35507. CodeDocumentLine* const line = lines [startLine];
  35508. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  35509. }
  35510. String result;
  35511. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  35512. String::Concatenator concatenator (result);
  35513. const int maxLine = jmin (lines.size() - 1, endLine);
  35514. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  35515. {
  35516. const CodeDocumentLine* line = lines.getUnchecked(i);
  35517. int len = line->lineLength;
  35518. if (i == startLine)
  35519. {
  35520. const int index = start.getIndexInLine();
  35521. concatenator.append (line->line.substring (index, len));
  35522. }
  35523. else if (i == endLine)
  35524. {
  35525. len = end.getIndexInLine();
  35526. concatenator.append (line->line.substring (0, len));
  35527. }
  35528. else
  35529. {
  35530. concatenator.append (line->line);
  35531. }
  35532. }
  35533. return result;
  35534. }
  35535. int CodeDocument::getNumCharacters() const throw()
  35536. {
  35537. const CodeDocumentLine* const lastLine = lines.getLast();
  35538. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  35539. }
  35540. const String CodeDocument::getLine (const int lineIndex) const throw()
  35541. {
  35542. const CodeDocumentLine* const line = lines [lineIndex];
  35543. return (line == 0) ? String::empty : line->line;
  35544. }
  35545. int CodeDocument::getMaximumLineLength() throw()
  35546. {
  35547. if (maximumLineLength < 0)
  35548. {
  35549. maximumLineLength = 0;
  35550. for (int i = lines.size(); --i >= 0;)
  35551. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  35552. }
  35553. return maximumLineLength;
  35554. }
  35555. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  35556. {
  35557. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  35558. }
  35559. void CodeDocument::insertText (const Position& position, const String& text)
  35560. {
  35561. insert (text, position.getPosition(), true);
  35562. }
  35563. void CodeDocument::replaceAllContent (const String& newContent)
  35564. {
  35565. remove (0, getNumCharacters(), true);
  35566. insert (newContent, 0, true);
  35567. }
  35568. bool CodeDocument::loadFromStream (InputStream& stream)
  35569. {
  35570. replaceAllContent (stream.readEntireStreamAsString());
  35571. setSavePoint();
  35572. clearUndoHistory();
  35573. return true;
  35574. }
  35575. bool CodeDocument::writeToStream (OutputStream& stream)
  35576. {
  35577. for (int i = 0; i < lines.size(); ++i)
  35578. {
  35579. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  35580. const char* utf8 = temp.toUTF8();
  35581. if (! stream.write (utf8, (int) strlen (utf8)))
  35582. return false;
  35583. }
  35584. return true;
  35585. }
  35586. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  35587. {
  35588. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  35589. newLineChars = newLine;
  35590. }
  35591. void CodeDocument::newTransaction()
  35592. {
  35593. undoManager.beginNewTransaction (String::empty);
  35594. }
  35595. void CodeDocument::undo()
  35596. {
  35597. newTransaction();
  35598. undoManager.undo();
  35599. }
  35600. void CodeDocument::redo()
  35601. {
  35602. undoManager.redo();
  35603. }
  35604. void CodeDocument::clearUndoHistory()
  35605. {
  35606. undoManager.clearUndoHistory();
  35607. }
  35608. void CodeDocument::setSavePoint() throw()
  35609. {
  35610. indexOfSavedState = currentActionIndex;
  35611. }
  35612. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  35613. {
  35614. return currentActionIndex != indexOfSavedState;
  35615. }
  35616. static int getCodeCharacterCategory (const juce_wchar character) throw()
  35617. {
  35618. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  35619. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  35620. }
  35621. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  35622. {
  35623. Position p (position);
  35624. const int maxDistance = 256;
  35625. int i = 0;
  35626. while (i < maxDistance
  35627. && CharacterFunctions::isWhitespace (p.getCharacter())
  35628. && (i == 0 || (p.getCharacter() != '\n'
  35629. && p.getCharacter() != '\r')))
  35630. {
  35631. ++i;
  35632. p.moveBy (1);
  35633. }
  35634. if (i == 0)
  35635. {
  35636. const int type = getCodeCharacterCategory (p.getCharacter());
  35637. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  35638. {
  35639. ++i;
  35640. p.moveBy (1);
  35641. }
  35642. while (i < maxDistance
  35643. && CharacterFunctions::isWhitespace (p.getCharacter())
  35644. && (i == 0 || (p.getCharacter() != '\n'
  35645. && p.getCharacter() != '\r')))
  35646. {
  35647. ++i;
  35648. p.moveBy (1);
  35649. }
  35650. }
  35651. return p;
  35652. }
  35653. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  35654. {
  35655. Position p (position);
  35656. const int maxDistance = 256;
  35657. int i = 0;
  35658. bool stoppedAtLineStart = false;
  35659. while (i < maxDistance)
  35660. {
  35661. const juce_wchar c = p.movedBy (-1).getCharacter();
  35662. if (c == '\r' || c == '\n')
  35663. {
  35664. stoppedAtLineStart = true;
  35665. if (i > 0)
  35666. break;
  35667. }
  35668. if (! CharacterFunctions::isWhitespace (c))
  35669. break;
  35670. p.moveBy (-1);
  35671. ++i;
  35672. }
  35673. if (i < maxDistance && ! stoppedAtLineStart)
  35674. {
  35675. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  35676. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  35677. {
  35678. p.moveBy (-1);
  35679. ++i;
  35680. }
  35681. }
  35682. return p;
  35683. }
  35684. void CodeDocument::checkLastLineStatus()
  35685. {
  35686. while (lines.size() > 0
  35687. && lines.getLast()->lineLength == 0
  35688. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  35689. {
  35690. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  35691. lines.removeLast();
  35692. }
  35693. const CodeDocumentLine* const lastLine = lines.getLast();
  35694. if (lastLine != 0 && lastLine->endsWithLineBreak())
  35695. {
  35696. // check that there's an empty line at the end if the preceding one ends in a newline..
  35697. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  35698. }
  35699. }
  35700. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  35701. {
  35702. listeners.add (listener);
  35703. }
  35704. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  35705. {
  35706. listeners.remove (listener);
  35707. }
  35708. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  35709. {
  35710. Position startPos (this, startLine, 0);
  35711. Position endPos (this, endLine, 0);
  35712. listeners.call (&Listener::codeDocumentChanged, startPos, endPos);
  35713. }
  35714. class CodeDocumentInsertAction : public UndoableAction
  35715. {
  35716. CodeDocument& owner;
  35717. const String text;
  35718. int insertPos;
  35719. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  35720. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  35721. public:
  35722. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  35723. : owner (owner_),
  35724. text (text_),
  35725. insertPos (insertPos_)
  35726. {
  35727. }
  35728. ~CodeDocumentInsertAction() {}
  35729. bool perform()
  35730. {
  35731. owner.currentActionIndex++;
  35732. owner.insert (text, insertPos, false);
  35733. return true;
  35734. }
  35735. bool undo()
  35736. {
  35737. owner.currentActionIndex--;
  35738. owner.remove (insertPos, insertPos + text.length(), false);
  35739. return true;
  35740. }
  35741. int getSizeInUnits() { return text.length() + 32; }
  35742. };
  35743. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  35744. {
  35745. if (text.isEmpty())
  35746. return;
  35747. if (undoable)
  35748. {
  35749. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  35750. }
  35751. else
  35752. {
  35753. Position pos (this, insertPos);
  35754. const int firstAffectedLine = pos.getLineNumber();
  35755. int lastAffectedLine = firstAffectedLine + 1;
  35756. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  35757. String textInsideOriginalLine (text);
  35758. if (firstLine != 0)
  35759. {
  35760. const int index = pos.getIndexInLine();
  35761. textInsideOriginalLine = firstLine->line.substring (0, index)
  35762. + textInsideOriginalLine
  35763. + firstLine->line.substring (index);
  35764. }
  35765. maximumLineLength = -1;
  35766. Array <CodeDocumentLine*> newLines;
  35767. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  35768. jassert (newLines.size() > 0);
  35769. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  35770. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  35771. lines.set (firstAffectedLine, newFirstLine);
  35772. if (newLines.size() > 1)
  35773. {
  35774. for (int i = 1; i < newLines.size(); ++i)
  35775. {
  35776. CodeDocumentLine* const l = newLines.getUnchecked (i);
  35777. lines.insert (firstAffectedLine + i, l);
  35778. }
  35779. lastAffectedLine = lines.size();
  35780. }
  35781. int i, lineStart = newFirstLine->lineStartInFile;
  35782. for (i = firstAffectedLine; i < lines.size(); ++i)
  35783. {
  35784. CodeDocumentLine* const l = lines.getUnchecked (i);
  35785. l->lineStartInFile = lineStart;
  35786. lineStart += l->lineLength;
  35787. }
  35788. checkLastLineStatus();
  35789. const int newTextLength = text.length();
  35790. for (i = 0; i < positionsToMaintain.size(); ++i)
  35791. {
  35792. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  35793. if (p->getPosition() >= insertPos)
  35794. p->setPosition (p->getPosition() + newTextLength);
  35795. }
  35796. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35797. }
  35798. }
  35799. class CodeDocumentDeleteAction : public UndoableAction
  35800. {
  35801. CodeDocument& owner;
  35802. int startPos, endPos;
  35803. String removedText;
  35804. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  35805. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  35806. public:
  35807. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  35808. : owner (owner_),
  35809. startPos (startPos_),
  35810. endPos (endPos_)
  35811. {
  35812. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  35813. CodeDocument::Position (&owner, endPos));
  35814. }
  35815. ~CodeDocumentDeleteAction() {}
  35816. bool perform()
  35817. {
  35818. owner.currentActionIndex++;
  35819. owner.remove (startPos, endPos, false);
  35820. return true;
  35821. }
  35822. bool undo()
  35823. {
  35824. owner.currentActionIndex--;
  35825. owner.insert (removedText, startPos, false);
  35826. return true;
  35827. }
  35828. int getSizeInUnits() { return removedText.length() + 32; }
  35829. };
  35830. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  35831. {
  35832. if (endPos <= startPos)
  35833. return;
  35834. if (undoable)
  35835. {
  35836. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  35837. }
  35838. else
  35839. {
  35840. Position startPosition (this, startPos);
  35841. Position endPosition (this, endPos);
  35842. maximumLineLength = -1;
  35843. const int firstAffectedLine = startPosition.getLineNumber();
  35844. const int endLine = endPosition.getLineNumber();
  35845. int lastAffectedLine = firstAffectedLine + 1;
  35846. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  35847. if (firstAffectedLine == endLine)
  35848. {
  35849. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35850. + firstLine->line.substring (endPosition.getIndexInLine());
  35851. firstLine->updateLength();
  35852. }
  35853. else
  35854. {
  35855. lastAffectedLine = lines.size();
  35856. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  35857. jassert (lastLine != 0);
  35858. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35859. + lastLine->line.substring (endPosition.getIndexInLine());
  35860. firstLine->updateLength();
  35861. int numLinesToRemove = endLine - firstAffectedLine;
  35862. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  35863. }
  35864. int i;
  35865. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  35866. {
  35867. CodeDocumentLine* const l = lines.getUnchecked (i);
  35868. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  35869. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  35870. }
  35871. checkLastLineStatus();
  35872. const int totalChars = getNumCharacters();
  35873. for (i = 0; i < positionsToMaintain.size(); ++i)
  35874. {
  35875. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  35876. if (p->getPosition() > startPosition.getPosition())
  35877. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  35878. if (p->getPosition() > totalChars)
  35879. p->setPosition (totalChars);
  35880. }
  35881. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35882. }
  35883. }
  35884. END_JUCE_NAMESPACE
  35885. /*** End of inlined file: juce_CodeDocument.cpp ***/
  35886. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  35887. BEGIN_JUCE_NAMESPACE
  35888. class CodeEditorComponent::CaretComponent : public Component,
  35889. public Timer
  35890. {
  35891. public:
  35892. CaretComponent (CodeEditorComponent& owner_)
  35893. : owner (owner_)
  35894. {
  35895. setAlwaysOnTop (true);
  35896. setInterceptsMouseClicks (false, false);
  35897. }
  35898. ~CaretComponent()
  35899. {
  35900. }
  35901. void paint (Graphics& g)
  35902. {
  35903. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  35904. }
  35905. void timerCallback()
  35906. {
  35907. setVisible (shouldBeShown() && ! isVisible());
  35908. }
  35909. void updatePosition()
  35910. {
  35911. startTimer (400);
  35912. setVisible (shouldBeShown());
  35913. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  35914. }
  35915. private:
  35916. CodeEditorComponent& owner;
  35917. CaretComponent (const CaretComponent&);
  35918. CaretComponent& operator= (const CaretComponent&);
  35919. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  35920. };
  35921. class CodeEditorComponent::CodeEditorLine
  35922. {
  35923. public:
  35924. CodeEditorLine() throw()
  35925. : highlightColumnStart (0), highlightColumnEnd (0)
  35926. {
  35927. }
  35928. ~CodeEditorLine() throw()
  35929. {
  35930. }
  35931. bool update (CodeDocument& document, int lineNum,
  35932. CodeDocument::Iterator& source,
  35933. CodeTokeniser* analyser, const int spacesPerTab,
  35934. const CodeDocument::Position& selectionStart,
  35935. const CodeDocument::Position& selectionEnd)
  35936. {
  35937. Array <SyntaxToken> newTokens;
  35938. newTokens.ensureStorageAllocated (8);
  35939. if (analyser == 0)
  35940. {
  35941. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  35942. }
  35943. else if (lineNum < document.getNumLines())
  35944. {
  35945. const CodeDocument::Position pos (&document, lineNum, 0);
  35946. createTokens (pos.getPosition(), pos.getLineText(),
  35947. source, analyser, newTokens);
  35948. }
  35949. replaceTabsWithSpaces (newTokens, spacesPerTab);
  35950. int newHighlightStart = 0;
  35951. int newHighlightEnd = 0;
  35952. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  35953. {
  35954. const String line (document.getLine (lineNum));
  35955. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  35956. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  35957. line, spacesPerTab);
  35958. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  35959. line, spacesPerTab);
  35960. }
  35961. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  35962. {
  35963. highlightColumnStart = newHighlightStart;
  35964. highlightColumnEnd = newHighlightEnd;
  35965. }
  35966. else
  35967. {
  35968. if (tokens.size() == newTokens.size())
  35969. {
  35970. bool allTheSame = true;
  35971. for (int i = newTokens.size(); --i >= 0;)
  35972. {
  35973. if (tokens.getReference(i) != newTokens.getReference(i))
  35974. {
  35975. allTheSame = false;
  35976. break;
  35977. }
  35978. }
  35979. if (allTheSame)
  35980. return false;
  35981. }
  35982. }
  35983. tokens.swapWithArray (newTokens);
  35984. return true;
  35985. }
  35986. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  35987. float x, const int y, const int baselineOffset, const int lineHeight,
  35988. const Colour& highlightColour) const throw()
  35989. {
  35990. if (highlightColumnStart < highlightColumnEnd)
  35991. {
  35992. g.setColour (highlightColour);
  35993. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  35994. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  35995. }
  35996. int lastType = std::numeric_limits<int>::min();
  35997. for (int i = 0; i < tokens.size(); ++i)
  35998. {
  35999. SyntaxToken& token = tokens.getReference(i);
  36000. if (lastType != token.tokenType)
  36001. {
  36002. lastType = token.tokenType;
  36003. g.setColour (owner.getColourForTokenType (lastType));
  36004. }
  36005. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36006. if (i < tokens.size() - 1)
  36007. {
  36008. if (token.width < 0)
  36009. token.width = font.getStringWidthFloat (token.text);
  36010. x += token.width;
  36011. }
  36012. }
  36013. }
  36014. private:
  36015. struct SyntaxToken
  36016. {
  36017. String text;
  36018. int tokenType;
  36019. float width;
  36020. SyntaxToken (const String& text_, const int type) throw()
  36021. : text (text_), tokenType (type), width (-1.0f)
  36022. {
  36023. }
  36024. bool operator!= (const SyntaxToken& other) const throw()
  36025. {
  36026. return text != other.text || tokenType != other.tokenType;
  36027. }
  36028. };
  36029. Array <SyntaxToken> tokens;
  36030. int highlightColumnStart, highlightColumnEnd;
  36031. static void createTokens (int startPosition, const String& lineText,
  36032. CodeDocument::Iterator& source,
  36033. CodeTokeniser* analyser,
  36034. Array <SyntaxToken>& newTokens)
  36035. {
  36036. CodeDocument::Iterator lastIterator (source);
  36037. const int lineLength = lineText.length();
  36038. for (;;)
  36039. {
  36040. int tokenType = analyser->readNextToken (source);
  36041. int tokenStart = lastIterator.getPosition();
  36042. int tokenEnd = source.getPosition();
  36043. if (tokenEnd <= tokenStart)
  36044. break;
  36045. tokenEnd -= startPosition;
  36046. if (tokenEnd > 0)
  36047. {
  36048. tokenStart -= startPosition;
  36049. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36050. tokenType));
  36051. if (tokenEnd >= lineLength)
  36052. break;
  36053. }
  36054. lastIterator = source;
  36055. }
  36056. source = lastIterator;
  36057. }
  36058. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab) throw()
  36059. {
  36060. int x = 0;
  36061. for (int i = 0; i < tokens.size(); ++i)
  36062. {
  36063. SyntaxToken& t = tokens.getReference(i);
  36064. for (;;)
  36065. {
  36066. int tabPos = t.text.indexOfChar ('\t');
  36067. if (tabPos < 0)
  36068. break;
  36069. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36070. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36071. }
  36072. x += t.text.length();
  36073. }
  36074. }
  36075. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36076. {
  36077. jassert (index <= line.length());
  36078. int col = 0;
  36079. for (int i = 0; i < index; ++i)
  36080. {
  36081. if (line[i] != '\t')
  36082. ++col;
  36083. else
  36084. col += spacesPerTab - (col % spacesPerTab);
  36085. }
  36086. return col;
  36087. }
  36088. };
  36089. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36090. CodeTokeniser* const codeTokeniser_)
  36091. : document (document_),
  36092. firstLineOnScreen (0),
  36093. gutter (5),
  36094. spacesPerTab (4),
  36095. lineHeight (0),
  36096. linesOnScreen (0),
  36097. columnsOnScreen (0),
  36098. scrollbarThickness (16),
  36099. columnToTryToMaintain (-1),
  36100. useSpacesForTabs (false),
  36101. xOffset (0),
  36102. codeTokeniser (codeTokeniser_)
  36103. {
  36104. caretPos = CodeDocument::Position (&document_, 0, 0);
  36105. caretPos.setPositionMaintained (true);
  36106. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36107. selectionStart.setPositionMaintained (true);
  36108. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36109. selectionEnd.setPositionMaintained (true);
  36110. setOpaque (true);
  36111. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36112. setWantsKeyboardFocus (true);
  36113. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  36114. verticalScrollBar->setSingleStepSize (1.0);
  36115. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  36116. horizontalScrollBar->setSingleStepSize (1.0);
  36117. addAndMakeVisible (caret = new CaretComponent (*this));
  36118. Font f (12.0f);
  36119. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36120. setFont (f);
  36121. resetToDefaultColours();
  36122. verticalScrollBar->addListener (this);
  36123. horizontalScrollBar->addListener (this);
  36124. document.addListener (this);
  36125. }
  36126. CodeEditorComponent::~CodeEditorComponent()
  36127. {
  36128. document.removeListener (this);
  36129. deleteAllChildren();
  36130. }
  36131. void CodeEditorComponent::loadContent (const String& newContent)
  36132. {
  36133. clearCachedIterators (0);
  36134. document.replaceAllContent (newContent);
  36135. document.clearUndoHistory();
  36136. document.setSavePoint();
  36137. caretPos.setPosition (0);
  36138. selectionStart.setPosition (0);
  36139. selectionEnd.setPosition (0);
  36140. scrollToLine (0);
  36141. }
  36142. bool CodeEditorComponent::isTextInputActive() const
  36143. {
  36144. return true;
  36145. }
  36146. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36147. const CodeDocument::Position& affectedTextEnd)
  36148. {
  36149. clearCachedIterators (affectedTextStart.getLineNumber());
  36150. triggerAsyncUpdate();
  36151. caret->updatePosition();
  36152. columnToTryToMaintain = -1;
  36153. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36154. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36155. deselectAll();
  36156. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36157. || caretPos.getPosition() < affectedTextStart.getPosition())
  36158. moveCaretTo (affectedTextStart, false);
  36159. updateScrollBars();
  36160. }
  36161. void CodeEditorComponent::resized()
  36162. {
  36163. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36164. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36165. lines.clear();
  36166. rebuildLineTokens();
  36167. caret->updatePosition();
  36168. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36169. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36170. updateScrollBars();
  36171. }
  36172. void CodeEditorComponent::paint (Graphics& g)
  36173. {
  36174. handleUpdateNowIfNeeded();
  36175. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36176. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  36177. g.setFont (font);
  36178. const int baselineOffset = (int) font.getAscent();
  36179. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36180. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36181. const Rectangle<int> clip (g.getClipBounds());
  36182. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36183. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36184. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36185. {
  36186. lines.getUnchecked(j)->draw (*this, g, font,
  36187. (float) (gutter - xOffset * charWidth),
  36188. lineHeight * j, baselineOffset, lineHeight,
  36189. highlightColour);
  36190. }
  36191. }
  36192. void CodeEditorComponent::setScrollbarThickness (const int thickness) throw()
  36193. {
  36194. if (scrollbarThickness != thickness)
  36195. {
  36196. scrollbarThickness = thickness;
  36197. resized();
  36198. }
  36199. }
  36200. void CodeEditorComponent::handleAsyncUpdate()
  36201. {
  36202. rebuildLineTokens();
  36203. }
  36204. void CodeEditorComponent::rebuildLineTokens()
  36205. {
  36206. cancelPendingUpdate();
  36207. const int numNeeded = linesOnScreen + 1;
  36208. int minLineToRepaint = numNeeded;
  36209. int maxLineToRepaint = 0;
  36210. if (numNeeded != lines.size())
  36211. {
  36212. lines.clear();
  36213. for (int i = numNeeded; --i >= 0;)
  36214. lines.add (new CodeEditorLine());
  36215. minLineToRepaint = 0;
  36216. maxLineToRepaint = numNeeded;
  36217. }
  36218. jassert (numNeeded == lines.size());
  36219. CodeDocument::Iterator source (&document);
  36220. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36221. for (int i = 0; i < numNeeded; ++i)
  36222. {
  36223. CodeEditorLine* const line = lines.getUnchecked(i);
  36224. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36225. selectionStart, selectionEnd))
  36226. {
  36227. minLineToRepaint = jmin (minLineToRepaint, i);
  36228. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36229. }
  36230. }
  36231. if (minLineToRepaint <= maxLineToRepaint)
  36232. {
  36233. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36234. verticalScrollBar->getX() - gutter,
  36235. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36236. }
  36237. }
  36238. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36239. {
  36240. caretPos = newPos;
  36241. columnToTryToMaintain = -1;
  36242. if (highlighting)
  36243. {
  36244. if (dragType == notDragging)
  36245. {
  36246. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36247. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36248. dragType = draggingSelectionStart;
  36249. else
  36250. dragType = draggingSelectionEnd;
  36251. }
  36252. if (dragType == draggingSelectionStart)
  36253. {
  36254. selectionStart = caretPos;
  36255. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36256. {
  36257. const CodeDocument::Position temp (selectionStart);
  36258. selectionStart = selectionEnd;
  36259. selectionEnd = temp;
  36260. dragType = draggingSelectionEnd;
  36261. }
  36262. }
  36263. else
  36264. {
  36265. selectionEnd = caretPos;
  36266. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36267. {
  36268. const CodeDocument::Position temp (selectionStart);
  36269. selectionStart = selectionEnd;
  36270. selectionEnd = temp;
  36271. dragType = draggingSelectionStart;
  36272. }
  36273. }
  36274. triggerAsyncUpdate();
  36275. }
  36276. else
  36277. {
  36278. deselectAll();
  36279. }
  36280. caret->updatePosition();
  36281. scrollToKeepCaretOnScreen();
  36282. updateScrollBars();
  36283. }
  36284. void CodeEditorComponent::deselectAll()
  36285. {
  36286. if (selectionStart != selectionEnd)
  36287. triggerAsyncUpdate();
  36288. selectionStart = caretPos;
  36289. selectionEnd = caretPos;
  36290. }
  36291. void CodeEditorComponent::updateScrollBars()
  36292. {
  36293. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36294. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  36295. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36296. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  36297. }
  36298. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36299. {
  36300. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36301. newFirstLineOnScreen);
  36302. if (newFirstLineOnScreen != firstLineOnScreen)
  36303. {
  36304. firstLineOnScreen = newFirstLineOnScreen;
  36305. caret->updatePosition();
  36306. updateCachedIterators (firstLineOnScreen);
  36307. triggerAsyncUpdate();
  36308. }
  36309. }
  36310. void CodeEditorComponent::scrollToColumnInternal (double column)
  36311. {
  36312. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  36313. if (xOffset != newOffset)
  36314. {
  36315. xOffset = newOffset;
  36316. caret->updatePosition();
  36317. repaint();
  36318. }
  36319. }
  36320. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  36321. {
  36322. scrollToLineInternal (newFirstLineOnScreen);
  36323. updateScrollBars();
  36324. }
  36325. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  36326. {
  36327. scrollToColumnInternal (newFirstColumnOnScreen);
  36328. updateScrollBars();
  36329. }
  36330. void CodeEditorComponent::scrollBy (int deltaLines)
  36331. {
  36332. scrollToLine (firstLineOnScreen + deltaLines);
  36333. }
  36334. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  36335. {
  36336. if (caretPos.getLineNumber() < firstLineOnScreen)
  36337. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  36338. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36339. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  36340. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36341. if (column >= xOffset + columnsOnScreen - 1)
  36342. scrollToColumn (column + 1 - columnsOnScreen);
  36343. else if (column < xOffset)
  36344. scrollToColumn (column);
  36345. }
  36346. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const throw()
  36347. {
  36348. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  36349. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  36350. roundToInt (charWidth),
  36351. lineHeight);
  36352. }
  36353. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  36354. {
  36355. const int line = y / lineHeight + firstLineOnScreen;
  36356. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  36357. const int index = columnToIndex (line, column);
  36358. return CodeDocument::Position (&document, line, index);
  36359. }
  36360. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  36361. {
  36362. document.deleteSection (selectionStart, selectionEnd);
  36363. if (newText.isNotEmpty())
  36364. document.insertText (caretPos, newText);
  36365. scrollToKeepCaretOnScreen();
  36366. }
  36367. void CodeEditorComponent::insertTabAtCaret()
  36368. {
  36369. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  36370. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  36371. {
  36372. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  36373. }
  36374. if (useSpacesForTabs)
  36375. {
  36376. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36377. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  36378. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  36379. }
  36380. else
  36381. {
  36382. insertTextAtCaret ("\t");
  36383. }
  36384. }
  36385. void CodeEditorComponent::cut()
  36386. {
  36387. insertTextAtCaret (String::empty);
  36388. }
  36389. void CodeEditorComponent::copy()
  36390. {
  36391. newTransaction();
  36392. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  36393. if (selection.isNotEmpty())
  36394. SystemClipboard::copyTextToClipboard (selection);
  36395. }
  36396. void CodeEditorComponent::copyThenCut()
  36397. {
  36398. copy();
  36399. cut();
  36400. newTransaction();
  36401. }
  36402. void CodeEditorComponent::paste()
  36403. {
  36404. newTransaction();
  36405. const String clip (SystemClipboard::getTextFromClipboard());
  36406. if (clip.isNotEmpty())
  36407. insertTextAtCaret (clip);
  36408. newTransaction();
  36409. }
  36410. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  36411. {
  36412. newTransaction();
  36413. if (moveInWholeWordSteps)
  36414. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  36415. else
  36416. moveCaretTo (caretPos.movedBy (-1), selecting);
  36417. }
  36418. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  36419. {
  36420. newTransaction();
  36421. if (moveInWholeWordSteps)
  36422. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  36423. else
  36424. moveCaretTo (caretPos.movedBy (1), selecting);
  36425. }
  36426. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  36427. {
  36428. CodeDocument::Position pos (caretPos);
  36429. const int newLineNum = pos.getLineNumber() + delta;
  36430. if (columnToTryToMaintain < 0)
  36431. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  36432. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  36433. const int colToMaintain = columnToTryToMaintain;
  36434. moveCaretTo (pos, selecting);
  36435. columnToTryToMaintain = colToMaintain;
  36436. }
  36437. void CodeEditorComponent::cursorDown (const bool selecting)
  36438. {
  36439. newTransaction();
  36440. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  36441. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36442. else
  36443. moveLineDelta (1, selecting);
  36444. }
  36445. void CodeEditorComponent::cursorUp (const bool selecting)
  36446. {
  36447. newTransaction();
  36448. if (caretPos.getLineNumber() == 0)
  36449. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36450. else
  36451. moveLineDelta (-1, selecting);
  36452. }
  36453. void CodeEditorComponent::pageDown (const bool selecting)
  36454. {
  36455. newTransaction();
  36456. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  36457. moveLineDelta (linesOnScreen, selecting);
  36458. }
  36459. void CodeEditorComponent::pageUp (const bool selecting)
  36460. {
  36461. newTransaction();
  36462. scrollBy (-linesOnScreen);
  36463. moveLineDelta (-linesOnScreen, selecting);
  36464. }
  36465. void CodeEditorComponent::scrollUp()
  36466. {
  36467. newTransaction();
  36468. scrollBy (1);
  36469. if (caretPos.getLineNumber() < firstLineOnScreen)
  36470. moveLineDelta (1, false);
  36471. }
  36472. void CodeEditorComponent::scrollDown()
  36473. {
  36474. newTransaction();
  36475. scrollBy (-1);
  36476. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36477. moveLineDelta (-1, false);
  36478. }
  36479. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  36480. {
  36481. newTransaction();
  36482. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36483. }
  36484. static int findFirstNonWhitespaceChar (const String& line) throw()
  36485. {
  36486. const int len = line.length();
  36487. for (int i = 0; i < len; ++i)
  36488. if (! CharacterFunctions::isWhitespace (line [i]))
  36489. return i;
  36490. return 0;
  36491. }
  36492. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  36493. {
  36494. newTransaction();
  36495. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  36496. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  36497. index = 0;
  36498. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  36499. }
  36500. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  36501. {
  36502. newTransaction();
  36503. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36504. }
  36505. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  36506. {
  36507. newTransaction();
  36508. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  36509. }
  36510. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  36511. {
  36512. if (moveInWholeWordSteps)
  36513. {
  36514. cut(); // in case something is already highlighted
  36515. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  36516. }
  36517. else
  36518. {
  36519. if (selectionStart == selectionEnd)
  36520. selectionStart.moveBy (-1);
  36521. }
  36522. cut();
  36523. }
  36524. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  36525. {
  36526. if (moveInWholeWordSteps)
  36527. {
  36528. cut(); // in case something is already highlighted
  36529. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  36530. }
  36531. else
  36532. {
  36533. if (selectionStart == selectionEnd)
  36534. selectionEnd.moveBy (1);
  36535. else
  36536. newTransaction();
  36537. }
  36538. cut();
  36539. }
  36540. void CodeEditorComponent::selectAll()
  36541. {
  36542. newTransaction();
  36543. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  36544. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  36545. }
  36546. void CodeEditorComponent::undo()
  36547. {
  36548. document.undo();
  36549. scrollToKeepCaretOnScreen();
  36550. }
  36551. void CodeEditorComponent::redo()
  36552. {
  36553. document.redo();
  36554. scrollToKeepCaretOnScreen();
  36555. }
  36556. void CodeEditorComponent::newTransaction()
  36557. {
  36558. document.newTransaction();
  36559. startTimer (600);
  36560. }
  36561. void CodeEditorComponent::timerCallback()
  36562. {
  36563. newTransaction();
  36564. }
  36565. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  36566. {
  36567. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  36568. }
  36569. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  36570. {
  36571. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  36572. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  36573. }
  36574. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  36575. {
  36576. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  36577. CodeDocument::Position (&document, range.getEnd()));
  36578. }
  36579. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  36580. {
  36581. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  36582. const bool shiftDown = key.getModifiers().isShiftDown();
  36583. if (key.isKeyCode (KeyPress::leftKey))
  36584. {
  36585. cursorLeft (moveInWholeWordSteps, shiftDown);
  36586. }
  36587. else if (key.isKeyCode (KeyPress::rightKey))
  36588. {
  36589. cursorRight (moveInWholeWordSteps, shiftDown);
  36590. }
  36591. else if (key.isKeyCode (KeyPress::upKey))
  36592. {
  36593. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36594. scrollDown();
  36595. #if JUCE_MAC
  36596. else if (key.getModifiers().isCommandDown())
  36597. goToStartOfDocument (shiftDown);
  36598. #endif
  36599. else
  36600. cursorUp (shiftDown);
  36601. }
  36602. else if (key.isKeyCode (KeyPress::downKey))
  36603. {
  36604. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36605. scrollUp();
  36606. #if JUCE_MAC
  36607. else if (key.getModifiers().isCommandDown())
  36608. goToEndOfDocument (shiftDown);
  36609. #endif
  36610. else
  36611. cursorDown (shiftDown);
  36612. }
  36613. else if (key.isKeyCode (KeyPress::pageDownKey))
  36614. {
  36615. pageDown (shiftDown);
  36616. }
  36617. else if (key.isKeyCode (KeyPress::pageUpKey))
  36618. {
  36619. pageUp (shiftDown);
  36620. }
  36621. else if (key.isKeyCode (KeyPress::homeKey))
  36622. {
  36623. if (moveInWholeWordSteps)
  36624. goToStartOfDocument (shiftDown);
  36625. else
  36626. goToStartOfLine (shiftDown);
  36627. }
  36628. else if (key.isKeyCode (KeyPress::endKey))
  36629. {
  36630. if (moveInWholeWordSteps)
  36631. goToEndOfDocument (shiftDown);
  36632. else
  36633. goToEndOfLine (shiftDown);
  36634. }
  36635. else if (key.isKeyCode (KeyPress::backspaceKey))
  36636. {
  36637. backspace (moveInWholeWordSteps);
  36638. }
  36639. else if (key.isKeyCode (KeyPress::deleteKey))
  36640. {
  36641. deleteForward (moveInWholeWordSteps);
  36642. }
  36643. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  36644. {
  36645. copy();
  36646. }
  36647. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  36648. {
  36649. copyThenCut();
  36650. }
  36651. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  36652. {
  36653. paste();
  36654. }
  36655. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  36656. {
  36657. undo();
  36658. }
  36659. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  36660. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  36661. {
  36662. redo();
  36663. }
  36664. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  36665. {
  36666. selectAll();
  36667. }
  36668. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  36669. {
  36670. insertTabAtCaret();
  36671. }
  36672. else if (key == KeyPress::returnKey)
  36673. {
  36674. newTransaction();
  36675. insertTextAtCaret (document.getNewLineCharacters());
  36676. }
  36677. else if (key.isKeyCode (KeyPress::escapeKey))
  36678. {
  36679. newTransaction();
  36680. }
  36681. else if (key.getTextCharacter() >= ' ')
  36682. {
  36683. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  36684. }
  36685. else
  36686. {
  36687. return false;
  36688. }
  36689. return true;
  36690. }
  36691. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  36692. {
  36693. newTransaction();
  36694. dragType = notDragging;
  36695. if (! e.mods.isPopupMenu())
  36696. {
  36697. beginDragAutoRepeat (100);
  36698. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  36699. }
  36700. else
  36701. {
  36702. /*PopupMenu m;
  36703. addPopupMenuItems (m, &e);
  36704. const int result = m.show();
  36705. if (result != 0)
  36706. performPopupMenuAction (result);
  36707. */
  36708. }
  36709. }
  36710. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  36711. {
  36712. if (! e.mods.isPopupMenu())
  36713. moveCaretTo (getPositionAt (e.x, e.y), true);
  36714. }
  36715. void CodeEditorComponent::mouseUp (const MouseEvent&)
  36716. {
  36717. newTransaction();
  36718. beginDragAutoRepeat (0);
  36719. dragType = notDragging;
  36720. }
  36721. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  36722. {
  36723. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  36724. CodeDocument::Position tokenEnd (tokenStart);
  36725. if (e.getNumberOfClicks() > 2)
  36726. {
  36727. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  36728. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  36729. }
  36730. else
  36731. {
  36732. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  36733. tokenEnd.moveBy (1);
  36734. tokenStart = tokenEnd;
  36735. while (tokenStart.getIndexInLine() > 0
  36736. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  36737. tokenStart.moveBy (-1);
  36738. }
  36739. moveCaretTo (tokenEnd, false);
  36740. moveCaretTo (tokenStart, true);
  36741. }
  36742. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  36743. {
  36744. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  36745. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  36746. {
  36747. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  36748. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  36749. }
  36750. else
  36751. {
  36752. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  36753. }
  36754. }
  36755. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  36756. {
  36757. if (scrollBarThatHasMoved == verticalScrollBar)
  36758. scrollToLineInternal ((int) newRangeStart);
  36759. else
  36760. scrollToColumnInternal (newRangeStart);
  36761. }
  36762. void CodeEditorComponent::focusGained (FocusChangeType)
  36763. {
  36764. caret->updatePosition();
  36765. }
  36766. void CodeEditorComponent::focusLost (FocusChangeType)
  36767. {
  36768. caret->updatePosition();
  36769. }
  36770. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces) throw()
  36771. {
  36772. useSpacesForTabs = insertSpaces;
  36773. if (spacesPerTab != numSpaces)
  36774. {
  36775. spacesPerTab = numSpaces;
  36776. triggerAsyncUpdate();
  36777. }
  36778. }
  36779. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  36780. {
  36781. const String line (document.getLine (lineNum));
  36782. jassert (index <= line.length());
  36783. int col = 0;
  36784. for (int i = 0; i < index; ++i)
  36785. {
  36786. if (line[i] != '\t')
  36787. ++col;
  36788. else
  36789. col += getTabSize() - (col % getTabSize());
  36790. }
  36791. return col;
  36792. }
  36793. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  36794. {
  36795. const String line (document.getLine (lineNum));
  36796. const int lineLength = line.length();
  36797. int i, col = 0;
  36798. for (i = 0; i < lineLength; ++i)
  36799. {
  36800. if (line[i] != '\t')
  36801. ++col;
  36802. else
  36803. col += getTabSize() - (col % getTabSize());
  36804. if (col > column)
  36805. break;
  36806. }
  36807. return i;
  36808. }
  36809. void CodeEditorComponent::setFont (const Font& newFont)
  36810. {
  36811. font = newFont;
  36812. charWidth = font.getStringWidthFloat ("0");
  36813. lineHeight = roundToInt (font.getHeight());
  36814. resized();
  36815. }
  36816. void CodeEditorComponent::resetToDefaultColours()
  36817. {
  36818. coloursForTokenCategories.clear();
  36819. if (codeTokeniser != 0)
  36820. {
  36821. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  36822. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  36823. }
  36824. }
  36825. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  36826. {
  36827. jassert (tokenType < 256);
  36828. while (coloursForTokenCategories.size() < tokenType)
  36829. coloursForTokenCategories.add (Colours::black);
  36830. coloursForTokenCategories.set (tokenType, colour);
  36831. repaint();
  36832. }
  36833. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const throw()
  36834. {
  36835. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  36836. return findColour (CodeEditorComponent::defaultTextColourId);
  36837. return coloursForTokenCategories.getReference (tokenType);
  36838. }
  36839. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid) throw()
  36840. {
  36841. int i;
  36842. for (i = cachedIterators.size(); --i >= 0;)
  36843. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  36844. break;
  36845. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  36846. }
  36847. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  36848. {
  36849. const int maxNumCachedPositions = 5000;
  36850. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  36851. if (cachedIterators.size() == 0)
  36852. cachedIterators.add (new CodeDocument::Iterator (&document));
  36853. if (codeTokeniser == 0)
  36854. return;
  36855. for (;;)
  36856. {
  36857. CodeDocument::Iterator* last = cachedIterators.getLast();
  36858. if (last->getLine() >= maxLineNum)
  36859. break;
  36860. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  36861. cachedIterators.add (t);
  36862. const int targetLine = last->getLine() + linesBetweenCachedSources;
  36863. for (;;)
  36864. {
  36865. codeTokeniser->readNextToken (*t);
  36866. if (t->getLine() >= targetLine)
  36867. break;
  36868. if (t->isEOF())
  36869. return;
  36870. }
  36871. }
  36872. }
  36873. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  36874. {
  36875. if (codeTokeniser == 0)
  36876. return;
  36877. for (int i = cachedIterators.size(); --i >= 0;)
  36878. {
  36879. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  36880. if (t->getPosition() <= position)
  36881. {
  36882. source = *t;
  36883. break;
  36884. }
  36885. }
  36886. while (source.getPosition() < position)
  36887. {
  36888. const CodeDocument::Iterator original (source);
  36889. codeTokeniser->readNextToken (source);
  36890. if (source.getPosition() > position || source.isEOF())
  36891. {
  36892. source = original;
  36893. break;
  36894. }
  36895. }
  36896. }
  36897. END_JUCE_NAMESPACE
  36898. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  36899. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  36900. BEGIN_JUCE_NAMESPACE
  36901. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  36902. {
  36903. }
  36904. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  36905. {
  36906. }
  36907. namespace CppTokeniser
  36908. {
  36909. static bool isIdentifierStart (const juce_wchar c) throw()
  36910. {
  36911. return CharacterFunctions::isLetter (c)
  36912. || c == '_' || c == '@';
  36913. }
  36914. static bool isIdentifierBody (const juce_wchar c) throw()
  36915. {
  36916. return CharacterFunctions::isLetterOrDigit (c)
  36917. || c == '_' || c == '@';
  36918. }
  36919. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  36920. {
  36921. static const juce_wchar* const keywords2Char[] =
  36922. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  36923. static const juce_wchar* const keywords3Char[] =
  36924. { JUCE_T("for"), JUCE_T("int"), JUCE_T("new"), JUCE_T("try"), JUCE_T("xor"), JUCE_T("and"), JUCE_T("asm"), JUCE_T("not"), 0 };
  36925. static const juce_wchar* const keywords4Char[] =
  36926. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  36927. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  36928. static const juce_wchar* const keywords5Char[] =
  36929. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  36930. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  36931. static const juce_wchar* const keywords6Char[] =
  36932. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  36933. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  36934. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  36935. static const juce_wchar* const keywordsOther[] =
  36936. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  36937. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  36938. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  36939. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  36940. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  36941. const juce_wchar* const* k;
  36942. switch (tokenLength)
  36943. {
  36944. case 2: k = keywords2Char; break;
  36945. case 3: k = keywords3Char; break;
  36946. case 4: k = keywords4Char; break;
  36947. case 5: k = keywords5Char; break;
  36948. case 6: k = keywords6Char; break;
  36949. default:
  36950. if (tokenLength < 2 || tokenLength > 16)
  36951. return false;
  36952. k = keywordsOther;
  36953. break;
  36954. }
  36955. int i = 0;
  36956. while (k[i] != 0)
  36957. {
  36958. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  36959. return true;
  36960. ++i;
  36961. }
  36962. return false;
  36963. }
  36964. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  36965. {
  36966. int tokenLength = 0;
  36967. juce_wchar possibleIdentifier [19];
  36968. while (isIdentifierBody (source.peekNextChar()))
  36969. {
  36970. const juce_wchar c = source.nextChar();
  36971. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  36972. possibleIdentifier [tokenLength] = c;
  36973. ++tokenLength;
  36974. }
  36975. if (tokenLength > 1 && tokenLength <= 16)
  36976. {
  36977. possibleIdentifier [tokenLength] = 0;
  36978. if (isReservedKeyword (possibleIdentifier, tokenLength))
  36979. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  36980. }
  36981. return CPlusPlusCodeTokeniser::tokenType_identifier;
  36982. }
  36983. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  36984. {
  36985. const juce_wchar c = source.peekNextChar();
  36986. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  36987. source.skip();
  36988. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  36989. return false;
  36990. return true;
  36991. }
  36992. static bool isHexDigit (const juce_wchar c) throw()
  36993. {
  36994. return (c >= '0' && c <= '9')
  36995. || (c >= 'a' && c <= 'f')
  36996. || (c >= 'A' && c <= 'F');
  36997. }
  36998. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  36999. {
  37000. if (source.nextChar() != '0')
  37001. return false;
  37002. juce_wchar c = source.nextChar();
  37003. if (c != 'x' && c != 'X')
  37004. return false;
  37005. int numDigits = 0;
  37006. while (isHexDigit (source.peekNextChar()))
  37007. {
  37008. ++numDigits;
  37009. source.skip();
  37010. }
  37011. if (numDigits == 0)
  37012. return false;
  37013. return skipNumberSuffix (source);
  37014. }
  37015. static bool isOctalDigit (const juce_wchar c) throw()
  37016. {
  37017. return c >= '0' && c <= '7';
  37018. }
  37019. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37020. {
  37021. if (source.nextChar() != '0')
  37022. return false;
  37023. if (! isOctalDigit (source.nextChar()))
  37024. return false;
  37025. while (isOctalDigit (source.peekNextChar()))
  37026. source.skip();
  37027. return skipNumberSuffix (source);
  37028. }
  37029. static bool isDecimalDigit (const juce_wchar c) throw()
  37030. {
  37031. return c >= '0' && c <= '9';
  37032. }
  37033. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37034. {
  37035. int numChars = 0;
  37036. while (isDecimalDigit (source.peekNextChar()))
  37037. {
  37038. ++numChars;
  37039. source.skip();
  37040. }
  37041. if (numChars == 0)
  37042. return false;
  37043. return skipNumberSuffix (source);
  37044. }
  37045. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37046. {
  37047. int numDigits = 0;
  37048. while (isDecimalDigit (source.peekNextChar()))
  37049. {
  37050. source.skip();
  37051. ++numDigits;
  37052. }
  37053. const bool hasPoint = (source.peekNextChar() == '.');
  37054. if (hasPoint)
  37055. {
  37056. source.skip();
  37057. while (isDecimalDigit (source.peekNextChar()))
  37058. {
  37059. source.skip();
  37060. ++numDigits;
  37061. }
  37062. }
  37063. if (numDigits == 0)
  37064. return false;
  37065. juce_wchar c = source.peekNextChar();
  37066. const bool hasExponent = (c == 'e' || c == 'E');
  37067. if (hasExponent)
  37068. {
  37069. source.skip();
  37070. c = source.peekNextChar();
  37071. if (c == '+' || c == '-')
  37072. source.skip();
  37073. int numExpDigits = 0;
  37074. while (isDecimalDigit (source.peekNextChar()))
  37075. {
  37076. source.skip();
  37077. ++numExpDigits;
  37078. }
  37079. if (numExpDigits == 0)
  37080. return false;
  37081. }
  37082. c = source.peekNextChar();
  37083. if (c == 'f' || c == 'F')
  37084. source.skip();
  37085. else if (! (hasExponent || hasPoint))
  37086. return false;
  37087. return true;
  37088. }
  37089. static int parseNumber (CodeDocument::Iterator& source)
  37090. {
  37091. const CodeDocument::Iterator original (source);
  37092. if (parseFloatLiteral (source))
  37093. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37094. source = original;
  37095. if (parseHexLiteral (source))
  37096. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37097. source = original;
  37098. if (parseOctalLiteral (source))
  37099. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37100. source = original;
  37101. if (parseDecimalLiteral (source))
  37102. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37103. source = original;
  37104. source.skip();
  37105. return CPlusPlusCodeTokeniser::tokenType_error;
  37106. }
  37107. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  37108. {
  37109. const juce_wchar quote = source.nextChar();
  37110. for (;;)
  37111. {
  37112. const juce_wchar c = source.nextChar();
  37113. if (c == quote || c == 0)
  37114. break;
  37115. if (c == '\\')
  37116. source.skip();
  37117. }
  37118. }
  37119. static void skipComment (CodeDocument::Iterator& source) throw()
  37120. {
  37121. bool lastWasStar = false;
  37122. for (;;)
  37123. {
  37124. const juce_wchar c = source.nextChar();
  37125. if (c == 0 || (c == '/' && lastWasStar))
  37126. break;
  37127. lastWasStar = (c == '*');
  37128. }
  37129. }
  37130. }
  37131. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37132. {
  37133. int result = tokenType_error;
  37134. source.skipWhitespace();
  37135. juce_wchar firstChar = source.peekNextChar();
  37136. switch (firstChar)
  37137. {
  37138. case 0:
  37139. source.skip();
  37140. break;
  37141. case '0':
  37142. case '1':
  37143. case '2':
  37144. case '3':
  37145. case '4':
  37146. case '5':
  37147. case '6':
  37148. case '7':
  37149. case '8':
  37150. case '9':
  37151. result = CppTokeniser::parseNumber (source);
  37152. break;
  37153. case '.':
  37154. result = CppTokeniser::parseNumber (source);
  37155. if (result == tokenType_error)
  37156. result = tokenType_punctuation;
  37157. break;
  37158. case ',':
  37159. case ';':
  37160. case ':':
  37161. source.skip();
  37162. result = tokenType_punctuation;
  37163. break;
  37164. case '(':
  37165. case ')':
  37166. case '{':
  37167. case '}':
  37168. case '[':
  37169. case ']':
  37170. source.skip();
  37171. result = tokenType_bracket;
  37172. break;
  37173. case '"':
  37174. case '\'':
  37175. CppTokeniser::skipQuotedString (source);
  37176. result = tokenType_stringLiteral;
  37177. break;
  37178. case '+':
  37179. result = tokenType_operator;
  37180. source.skip();
  37181. if (source.peekNextChar() == '+')
  37182. source.skip();
  37183. else if (source.peekNextChar() == '=')
  37184. source.skip();
  37185. break;
  37186. case '-':
  37187. source.skip();
  37188. result = CppTokeniser::parseNumber (source);
  37189. if (result == tokenType_error)
  37190. {
  37191. result = tokenType_operator;
  37192. if (source.peekNextChar() == '-')
  37193. source.skip();
  37194. else if (source.peekNextChar() == '=')
  37195. source.skip();
  37196. }
  37197. break;
  37198. case '*':
  37199. case '%':
  37200. case '=':
  37201. case '!':
  37202. result = tokenType_operator;
  37203. source.skip();
  37204. if (source.peekNextChar() == '=')
  37205. source.skip();
  37206. break;
  37207. case '/':
  37208. result = tokenType_operator;
  37209. source.skip();
  37210. if (source.peekNextChar() == '=')
  37211. {
  37212. source.skip();
  37213. }
  37214. else if (source.peekNextChar() == '/')
  37215. {
  37216. result = tokenType_comment;
  37217. source.skipToEndOfLine();
  37218. }
  37219. else if (source.peekNextChar() == '*')
  37220. {
  37221. source.skip();
  37222. result = tokenType_comment;
  37223. CppTokeniser::skipComment (source);
  37224. }
  37225. break;
  37226. case '?':
  37227. case '~':
  37228. source.skip();
  37229. result = tokenType_operator;
  37230. break;
  37231. case '<':
  37232. source.skip();
  37233. result = tokenType_operator;
  37234. if (source.peekNextChar() == '=')
  37235. {
  37236. source.skip();
  37237. }
  37238. else if (source.peekNextChar() == '<')
  37239. {
  37240. source.skip();
  37241. if (source.peekNextChar() == '=')
  37242. source.skip();
  37243. }
  37244. break;
  37245. case '>':
  37246. source.skip();
  37247. result = tokenType_operator;
  37248. if (source.peekNextChar() == '=')
  37249. {
  37250. source.skip();
  37251. }
  37252. else if (source.peekNextChar() == '<')
  37253. {
  37254. source.skip();
  37255. if (source.peekNextChar() == '=')
  37256. source.skip();
  37257. }
  37258. break;
  37259. case '|':
  37260. source.skip();
  37261. result = tokenType_operator;
  37262. if (source.peekNextChar() == '=')
  37263. {
  37264. source.skip();
  37265. }
  37266. else if (source.peekNextChar() == '|')
  37267. {
  37268. source.skip();
  37269. if (source.peekNextChar() == '=')
  37270. source.skip();
  37271. }
  37272. break;
  37273. case '&':
  37274. source.skip();
  37275. result = tokenType_operator;
  37276. if (source.peekNextChar() == '=')
  37277. {
  37278. source.skip();
  37279. }
  37280. else if (source.peekNextChar() == '&')
  37281. {
  37282. source.skip();
  37283. if (source.peekNextChar() == '=')
  37284. source.skip();
  37285. }
  37286. break;
  37287. case '^':
  37288. source.skip();
  37289. result = tokenType_operator;
  37290. if (source.peekNextChar() == '=')
  37291. {
  37292. source.skip();
  37293. }
  37294. else if (source.peekNextChar() == '^')
  37295. {
  37296. source.skip();
  37297. if (source.peekNextChar() == '=')
  37298. source.skip();
  37299. }
  37300. break;
  37301. case '#':
  37302. result = tokenType_preprocessor;
  37303. source.skipToEndOfLine();
  37304. break;
  37305. default:
  37306. if (CppTokeniser::isIdentifierStart (firstChar))
  37307. result = CppTokeniser::parseIdentifier (source);
  37308. else
  37309. source.skip();
  37310. break;
  37311. }
  37312. return result;
  37313. }
  37314. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  37315. {
  37316. const char* const types[] =
  37317. {
  37318. "Error",
  37319. "Comment",
  37320. "C++ keyword",
  37321. "Identifier",
  37322. "Integer literal",
  37323. "Float literal",
  37324. "String literal",
  37325. "Operator",
  37326. "Bracket",
  37327. "Punctuation",
  37328. "Preprocessor line",
  37329. 0
  37330. };
  37331. return StringArray (types);
  37332. }
  37333. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  37334. {
  37335. const uint32 colours[] =
  37336. {
  37337. 0xffcc0000, // error
  37338. 0xff00aa00, // comment
  37339. 0xff0000cc, // keyword
  37340. 0xff000000, // identifier
  37341. 0xff880000, // int literal
  37342. 0xff885500, // float literal
  37343. 0xff990099, // string literal
  37344. 0xff225500, // operator
  37345. 0xff000055, // bracket
  37346. 0xff004400, // punctuation
  37347. 0xff660000 // preprocessor
  37348. };
  37349. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  37350. return Colour (colours [tokenType]);
  37351. return Colours::black;
  37352. }
  37353. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  37354. {
  37355. return CppTokeniser::isReservedKeyword (token, token.length());
  37356. }
  37357. END_JUCE_NAMESPACE
  37358. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37359. /*** Start of inlined file: juce_ComboBox.cpp ***/
  37360. BEGIN_JUCE_NAMESPACE
  37361. ComboBox::ComboBox (const String& name)
  37362. : Component (name),
  37363. lastCurrentId (0),
  37364. isButtonDown (false),
  37365. separatorPending (false),
  37366. menuActive (false),
  37367. label (0)
  37368. {
  37369. noChoicesMessage = TRANS("(no choices)");
  37370. setRepaintsOnMouseActivity (true);
  37371. lookAndFeelChanged();
  37372. currentId.addListener (this);
  37373. }
  37374. ComboBox::~ComboBox()
  37375. {
  37376. currentId.removeListener (this);
  37377. if (menuActive)
  37378. PopupMenu::dismissAllActiveMenus();
  37379. label = 0;
  37380. deleteAllChildren();
  37381. }
  37382. void ComboBox::setEditableText (const bool isEditable)
  37383. {
  37384. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  37385. {
  37386. label->setEditable (isEditable, isEditable, false);
  37387. setWantsKeyboardFocus (! isEditable);
  37388. resized();
  37389. }
  37390. }
  37391. bool ComboBox::isTextEditable() const throw()
  37392. {
  37393. return label->isEditable();
  37394. }
  37395. void ComboBox::setJustificationType (const Justification& justification) throw()
  37396. {
  37397. label->setJustificationType (justification);
  37398. }
  37399. const Justification ComboBox::getJustificationType() const throw()
  37400. {
  37401. return label->getJustificationType();
  37402. }
  37403. void ComboBox::setTooltip (const String& newTooltip)
  37404. {
  37405. SettableTooltipClient::setTooltip (newTooltip);
  37406. label->setTooltip (newTooltip);
  37407. }
  37408. void ComboBox::addItem (const String& newItemText,
  37409. const int newItemId) throw()
  37410. {
  37411. // you can't add empty strings to the list..
  37412. jassert (newItemText.isNotEmpty());
  37413. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  37414. jassert (newItemId != 0);
  37415. // you shouldn't use duplicate item IDs!
  37416. jassert (getItemForId (newItemId) == 0);
  37417. if (newItemText.isNotEmpty() && newItemId != 0)
  37418. {
  37419. if (separatorPending)
  37420. {
  37421. separatorPending = false;
  37422. ItemInfo* const item = new ItemInfo();
  37423. item->itemId = 0;
  37424. item->isEnabled = false;
  37425. item->isHeading = false;
  37426. items.add (item);
  37427. }
  37428. ItemInfo* const item = new ItemInfo();
  37429. item->name = newItemText;
  37430. item->itemId = newItemId;
  37431. item->isEnabled = true;
  37432. item->isHeading = false;
  37433. items.add (item);
  37434. }
  37435. }
  37436. void ComboBox::addSeparator() throw()
  37437. {
  37438. separatorPending = (items.size() > 0);
  37439. }
  37440. void ComboBox::addSectionHeading (const String& headingName) throw()
  37441. {
  37442. // you can't add empty strings to the list..
  37443. jassert (headingName.isNotEmpty());
  37444. if (headingName.isNotEmpty())
  37445. {
  37446. if (separatorPending)
  37447. {
  37448. separatorPending = false;
  37449. ItemInfo* const item = new ItemInfo();
  37450. item->itemId = 0;
  37451. item->isEnabled = false;
  37452. item->isHeading = false;
  37453. items.add (item);
  37454. }
  37455. ItemInfo* const item = new ItemInfo();
  37456. item->name = headingName;
  37457. item->itemId = 0;
  37458. item->isEnabled = true;
  37459. item->isHeading = true;
  37460. items.add (item);
  37461. }
  37462. }
  37463. void ComboBox::setItemEnabled (const int itemId,
  37464. const bool shouldBeEnabled) throw()
  37465. {
  37466. ItemInfo* const item = getItemForId (itemId);
  37467. if (item != 0)
  37468. item->isEnabled = shouldBeEnabled;
  37469. }
  37470. void ComboBox::changeItemText (const int itemId,
  37471. const String& newText) throw()
  37472. {
  37473. ItemInfo* const item = getItemForId (itemId);
  37474. jassert (item != 0);
  37475. if (item != 0)
  37476. item->name = newText;
  37477. }
  37478. void ComboBox::clear (const bool dontSendChangeMessage)
  37479. {
  37480. items.clear();
  37481. separatorPending = false;
  37482. if (! label->isEditable())
  37483. setSelectedItemIndex (-1, dontSendChangeMessage);
  37484. }
  37485. bool ComboBox::ItemInfo::isSeparator() const throw()
  37486. {
  37487. return name.isEmpty();
  37488. }
  37489. bool ComboBox::ItemInfo::isRealItem() const throw()
  37490. {
  37491. return ! (isHeading || name.isEmpty());
  37492. }
  37493. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  37494. {
  37495. if (itemId != 0)
  37496. {
  37497. for (int i = items.size(); --i >= 0;)
  37498. if (items.getUnchecked(i)->itemId == itemId)
  37499. return items.getUnchecked(i);
  37500. }
  37501. return 0;
  37502. }
  37503. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  37504. {
  37505. int n = 0;
  37506. for (int i = 0; i < items.size(); ++i)
  37507. {
  37508. ItemInfo* const item = items.getUnchecked(i);
  37509. if (item->isRealItem())
  37510. if (n++ == index)
  37511. return item;
  37512. }
  37513. return 0;
  37514. }
  37515. int ComboBox::getNumItems() const throw()
  37516. {
  37517. int n = 0;
  37518. for (int i = items.size(); --i >= 0;)
  37519. if (items.getUnchecked(i)->isRealItem())
  37520. ++n;
  37521. return n;
  37522. }
  37523. const String ComboBox::getItemText (const int index) const throw()
  37524. {
  37525. const ItemInfo* const item = getItemForIndex (index);
  37526. if (item != 0)
  37527. return item->name;
  37528. return String::empty;
  37529. }
  37530. int ComboBox::getItemId (const int index) const throw()
  37531. {
  37532. const ItemInfo* const item = getItemForIndex (index);
  37533. return (item != 0) ? item->itemId : 0;
  37534. }
  37535. int ComboBox::indexOfItemId (const int itemId) const throw()
  37536. {
  37537. int n = 0;
  37538. for (int i = 0; i < items.size(); ++i)
  37539. {
  37540. const ItemInfo* const item = items.getUnchecked(i);
  37541. if (item->isRealItem())
  37542. {
  37543. if (item->itemId == itemId)
  37544. return n;
  37545. ++n;
  37546. }
  37547. }
  37548. return -1;
  37549. }
  37550. int ComboBox::getSelectedItemIndex() const throw()
  37551. {
  37552. int index = indexOfItemId (currentId.getValue());
  37553. if (getText() != getItemText (index))
  37554. index = -1;
  37555. return index;
  37556. }
  37557. void ComboBox::setSelectedItemIndex (const int index,
  37558. const bool dontSendChangeMessage) throw()
  37559. {
  37560. setSelectedId (getItemId (index), dontSendChangeMessage);
  37561. }
  37562. int ComboBox::getSelectedId() const throw()
  37563. {
  37564. const ItemInfo* const item = getItemForId (currentId.getValue());
  37565. return (item != 0 && getText() == item->name)
  37566. ? item->itemId
  37567. : 0;
  37568. }
  37569. void ComboBox::setSelectedId (const int newItemId,
  37570. const bool dontSendChangeMessage) throw()
  37571. {
  37572. const ItemInfo* const item = getItemForId (newItemId);
  37573. const String newItemText (item != 0 ? item->name : String::empty);
  37574. if (lastCurrentId != newItemId || label->getText() != newItemText)
  37575. {
  37576. if (! dontSendChangeMessage)
  37577. triggerAsyncUpdate();
  37578. label->setText (newItemText, false);
  37579. lastCurrentId = newItemId;
  37580. currentId = newItemId;
  37581. repaint(); // for the benefit of the 'none selected' text
  37582. }
  37583. }
  37584. void ComboBox::valueChanged (Value&)
  37585. {
  37586. if (lastCurrentId != (int) currentId.getValue())
  37587. setSelectedId (currentId.getValue(), false);
  37588. }
  37589. const String ComboBox::getText() const throw()
  37590. {
  37591. return label->getText();
  37592. }
  37593. void ComboBox::setText (const String& newText,
  37594. const bool dontSendChangeMessage) throw()
  37595. {
  37596. for (int i = items.size(); --i >= 0;)
  37597. {
  37598. const ItemInfo* const item = items.getUnchecked(i);
  37599. if (item->isRealItem()
  37600. && item->name == newText)
  37601. {
  37602. setSelectedId (item->itemId, dontSendChangeMessage);
  37603. return;
  37604. }
  37605. }
  37606. lastCurrentId = 0;
  37607. currentId = 0;
  37608. if (label->getText() != newText)
  37609. {
  37610. label->setText (newText, false);
  37611. if (! dontSendChangeMessage)
  37612. triggerAsyncUpdate();
  37613. }
  37614. repaint();
  37615. }
  37616. void ComboBox::showEditor()
  37617. {
  37618. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  37619. label->showEditor();
  37620. }
  37621. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  37622. {
  37623. if (textWhenNothingSelected != newMessage)
  37624. {
  37625. textWhenNothingSelected = newMessage;
  37626. repaint();
  37627. }
  37628. }
  37629. const String ComboBox::getTextWhenNothingSelected() const throw()
  37630. {
  37631. return textWhenNothingSelected;
  37632. }
  37633. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  37634. {
  37635. noChoicesMessage = newMessage;
  37636. }
  37637. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  37638. {
  37639. return noChoicesMessage;
  37640. }
  37641. void ComboBox::paint (Graphics& g)
  37642. {
  37643. getLookAndFeel().drawComboBox (g,
  37644. getWidth(),
  37645. getHeight(),
  37646. isButtonDown,
  37647. label->getRight(),
  37648. 0,
  37649. getWidth() - label->getRight(),
  37650. getHeight(),
  37651. *this);
  37652. if (textWhenNothingSelected.isNotEmpty()
  37653. && label->getText().isEmpty()
  37654. && ! label->isBeingEdited())
  37655. {
  37656. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  37657. g.setFont (label->getFont());
  37658. g.drawFittedText (textWhenNothingSelected,
  37659. label->getX() + 2, label->getY() + 1,
  37660. label->getWidth() - 4, label->getHeight() - 2,
  37661. label->getJustificationType(),
  37662. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  37663. }
  37664. }
  37665. void ComboBox::resized()
  37666. {
  37667. if (getHeight() > 0 && getWidth() > 0)
  37668. getLookAndFeel().positionComboBoxText (*this, *label);
  37669. }
  37670. void ComboBox::enablementChanged()
  37671. {
  37672. repaint();
  37673. }
  37674. void ComboBox::lookAndFeelChanged()
  37675. {
  37676. repaint();
  37677. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  37678. if (label != 0)
  37679. {
  37680. newLabel->setEditable (label->isEditable());
  37681. newLabel->setJustificationType (label->getJustificationType());
  37682. newLabel->setTooltip (label->getTooltip());
  37683. newLabel->setText (label->getText(), false);
  37684. }
  37685. label = newLabel;
  37686. addAndMakeVisible (newLabel);
  37687. newLabel->addListener (this);
  37688. newLabel->addMouseListener (this, false);
  37689. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  37690. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  37691. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  37692. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37693. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  37694. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37695. resized();
  37696. }
  37697. void ComboBox::colourChanged()
  37698. {
  37699. lookAndFeelChanged();
  37700. }
  37701. bool ComboBox::keyPressed (const KeyPress& key)
  37702. {
  37703. bool used = false;
  37704. if (key.isKeyCode (KeyPress::upKey)
  37705. || key.isKeyCode (KeyPress::leftKey))
  37706. {
  37707. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  37708. used = true;
  37709. }
  37710. else if (key.isKeyCode (KeyPress::downKey)
  37711. || key.isKeyCode (KeyPress::rightKey))
  37712. {
  37713. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  37714. used = true;
  37715. }
  37716. else if (key.isKeyCode (KeyPress::returnKey))
  37717. {
  37718. showPopup();
  37719. used = true;
  37720. }
  37721. return used;
  37722. }
  37723. bool ComboBox::keyStateChanged (const bool isKeyDown)
  37724. {
  37725. // only forward key events that aren't used by this component
  37726. return isKeyDown
  37727. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  37728. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  37729. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  37730. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  37731. }
  37732. void ComboBox::focusGained (FocusChangeType)
  37733. {
  37734. repaint();
  37735. }
  37736. void ComboBox::focusLost (FocusChangeType)
  37737. {
  37738. repaint();
  37739. }
  37740. void ComboBox::labelTextChanged (Label*)
  37741. {
  37742. triggerAsyncUpdate();
  37743. }
  37744. class ComboBox::Callback : public ModalComponentManager::Callback
  37745. {
  37746. public:
  37747. Callback (ComboBox* const box_)
  37748. : box (box_)
  37749. {
  37750. }
  37751. void modalStateFinished (int returnValue)
  37752. {
  37753. if (box != 0)
  37754. {
  37755. box->menuActive = false;
  37756. if (returnValue != 0)
  37757. box->setSelectedId (returnValue);
  37758. }
  37759. }
  37760. private:
  37761. Component::SafePointer<ComboBox> box;
  37762. Callback (const Callback&);
  37763. Callback& operator= (const Callback&);
  37764. };
  37765. void ComboBox::showPopup()
  37766. {
  37767. if (! menuActive)
  37768. {
  37769. const int selectedId = getSelectedId();
  37770. PopupMenu menu;
  37771. menu.setLookAndFeel (&getLookAndFeel());
  37772. for (int i = 0; i < items.size(); ++i)
  37773. {
  37774. const ItemInfo* const item = items.getUnchecked(i);
  37775. if (item->isSeparator())
  37776. menu.addSeparator();
  37777. else if (item->isHeading)
  37778. menu.addSectionHeader (item->name);
  37779. else
  37780. menu.addItem (item->itemId, item->name,
  37781. item->isEnabled, item->itemId == selectedId);
  37782. }
  37783. if (items.size() == 0)
  37784. menu.addItem (1, noChoicesMessage, false);
  37785. menuActive = true;
  37786. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  37787. new Callback (this));
  37788. }
  37789. }
  37790. void ComboBox::mouseDown (const MouseEvent& e)
  37791. {
  37792. beginDragAutoRepeat (300);
  37793. isButtonDown = isEnabled();
  37794. if (isButtonDown
  37795. && (e.eventComponent == this || ! label->isEditable()))
  37796. {
  37797. showPopup();
  37798. }
  37799. }
  37800. void ComboBox::mouseDrag (const MouseEvent& e)
  37801. {
  37802. beginDragAutoRepeat (50);
  37803. if (isButtonDown && ! e.mouseWasClicked())
  37804. showPopup();
  37805. }
  37806. void ComboBox::mouseUp (const MouseEvent& e2)
  37807. {
  37808. if (isButtonDown)
  37809. {
  37810. isButtonDown = false;
  37811. repaint();
  37812. const MouseEvent e (e2.getEventRelativeTo (this));
  37813. if (reallyContains (e.x, e.y, true)
  37814. && (e2.eventComponent == this || ! label->isEditable()))
  37815. {
  37816. showPopup();
  37817. }
  37818. }
  37819. }
  37820. void ComboBox::addListener (Listener* const listener) throw()
  37821. {
  37822. listeners.add (listener);
  37823. }
  37824. void ComboBox::removeListener (Listener* const listener) throw()
  37825. {
  37826. listeners.remove (listener);
  37827. }
  37828. void ComboBox::handleAsyncUpdate()
  37829. {
  37830. Component::BailOutChecker checker (this);
  37831. listeners.callChecked (checker, &ComboBox::Listener::comboBoxChanged, this);
  37832. }
  37833. END_JUCE_NAMESPACE
  37834. /*** End of inlined file: juce_ComboBox.cpp ***/
  37835. /*** Start of inlined file: juce_Label.cpp ***/
  37836. BEGIN_JUCE_NAMESPACE
  37837. Label::Label (const String& componentName,
  37838. const String& labelText)
  37839. : Component (componentName),
  37840. textValue (labelText),
  37841. lastTextValue (labelText),
  37842. font (15.0f),
  37843. justification (Justification::centredLeft),
  37844. ownerComponent (0),
  37845. horizontalBorderSize (5),
  37846. verticalBorderSize (1),
  37847. minimumHorizontalScale (0.7f),
  37848. editSingleClick (false),
  37849. editDoubleClick (false),
  37850. lossOfFocusDiscardsChanges (false)
  37851. {
  37852. setColour (TextEditor::textColourId, Colours::black);
  37853. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37854. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37855. textValue.addListener (this);
  37856. }
  37857. Label::~Label()
  37858. {
  37859. textValue.removeListener (this);
  37860. if (ownerComponent != 0)
  37861. ownerComponent->removeComponentListener (this);
  37862. editor = 0;
  37863. }
  37864. void Label::setText (const String& newText,
  37865. const bool broadcastChangeMessage)
  37866. {
  37867. hideEditor (true);
  37868. if (lastTextValue != newText)
  37869. {
  37870. lastTextValue = newText;
  37871. textValue = newText;
  37872. repaint();
  37873. textWasChanged();
  37874. if (ownerComponent != 0)
  37875. componentMovedOrResized (*ownerComponent, true, true);
  37876. if (broadcastChangeMessage)
  37877. callChangeListeners();
  37878. }
  37879. }
  37880. const String Label::getText (const bool returnActiveEditorContents) const throw()
  37881. {
  37882. return (returnActiveEditorContents && isBeingEdited())
  37883. ? editor->getText()
  37884. : textValue.toString();
  37885. }
  37886. void Label::valueChanged (Value&)
  37887. {
  37888. if (lastTextValue != textValue.toString())
  37889. setText (textValue.toString(), true);
  37890. }
  37891. void Label::setFont (const Font& newFont) throw()
  37892. {
  37893. if (font != newFont)
  37894. {
  37895. font = newFont;
  37896. repaint();
  37897. }
  37898. }
  37899. const Font& Label::getFont() const throw()
  37900. {
  37901. return font;
  37902. }
  37903. void Label::setEditable (const bool editOnSingleClick,
  37904. const bool editOnDoubleClick,
  37905. const bool lossOfFocusDiscardsChanges_) throw()
  37906. {
  37907. editSingleClick = editOnSingleClick;
  37908. editDoubleClick = editOnDoubleClick;
  37909. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  37910. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  37911. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  37912. }
  37913. void Label::setJustificationType (const Justification& newJustification) throw()
  37914. {
  37915. if (justification != newJustification)
  37916. {
  37917. justification = newJustification;
  37918. repaint();
  37919. }
  37920. }
  37921. void Label::setBorderSize (int h, int v)
  37922. {
  37923. if (horizontalBorderSize != h || verticalBorderSize != v)
  37924. {
  37925. horizontalBorderSize = h;
  37926. verticalBorderSize = v;
  37927. repaint();
  37928. }
  37929. }
  37930. Component* Label::getAttachedComponent() const
  37931. {
  37932. return static_cast<Component*> (ownerComponent);
  37933. }
  37934. void Label::attachToComponent (Component* owner,
  37935. const bool onLeft)
  37936. {
  37937. if (ownerComponent != 0)
  37938. ownerComponent->removeComponentListener (this);
  37939. ownerComponent = owner;
  37940. leftOfOwnerComp = onLeft;
  37941. if (ownerComponent != 0)
  37942. {
  37943. setVisible (owner->isVisible());
  37944. ownerComponent->addComponentListener (this);
  37945. componentParentHierarchyChanged (*ownerComponent);
  37946. componentMovedOrResized (*ownerComponent, true, true);
  37947. }
  37948. }
  37949. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  37950. {
  37951. if (leftOfOwnerComp)
  37952. {
  37953. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  37954. component.getHeight());
  37955. setTopRightPosition (component.getX(), component.getY());
  37956. }
  37957. else
  37958. {
  37959. setSize (component.getWidth(),
  37960. 8 + roundToInt (getFont().getHeight()));
  37961. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  37962. }
  37963. }
  37964. void Label::componentParentHierarchyChanged (Component& component)
  37965. {
  37966. if (component.getParentComponent() != 0)
  37967. component.getParentComponent()->addChildComponent (this);
  37968. }
  37969. void Label::componentVisibilityChanged (Component& component)
  37970. {
  37971. setVisible (component.isVisible());
  37972. }
  37973. void Label::textWasEdited()
  37974. {
  37975. }
  37976. void Label::textWasChanged()
  37977. {
  37978. }
  37979. void Label::showEditor()
  37980. {
  37981. if (editor == 0)
  37982. {
  37983. addAndMakeVisible (editor = createEditorComponent());
  37984. editor->setText (getText(), false);
  37985. editor->addListener (this);
  37986. editor->grabKeyboardFocus();
  37987. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  37988. editor->addListener (this);
  37989. resized();
  37990. repaint();
  37991. editorShown (editor);
  37992. enterModalState (false);
  37993. editor->grabKeyboardFocus();
  37994. }
  37995. }
  37996. void Label::editorShown (TextEditor* /*editorComponent*/)
  37997. {
  37998. }
  37999. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38000. {
  38001. }
  38002. bool Label::updateFromTextEditorContents()
  38003. {
  38004. jassert (editor != 0);
  38005. const String newText (editor->getText());
  38006. if (textValue.toString() != newText)
  38007. {
  38008. lastTextValue = newText;
  38009. textValue = newText;
  38010. repaint();
  38011. textWasChanged();
  38012. if (ownerComponent != 0)
  38013. componentMovedOrResized (*ownerComponent, true, true);
  38014. return true;
  38015. }
  38016. return false;
  38017. }
  38018. void Label::hideEditor (const bool discardCurrentEditorContents)
  38019. {
  38020. if (editor != 0)
  38021. {
  38022. Component::SafePointer<Component> deletionChecker (this);
  38023. editorAboutToBeHidden (editor);
  38024. const bool changed = (! discardCurrentEditorContents)
  38025. && updateFromTextEditorContents();
  38026. editor = 0;
  38027. repaint();
  38028. if (changed)
  38029. textWasEdited();
  38030. if (deletionChecker != 0)
  38031. exitModalState (0);
  38032. if (changed && deletionChecker != 0)
  38033. callChangeListeners();
  38034. }
  38035. }
  38036. void Label::inputAttemptWhenModal()
  38037. {
  38038. if (editor != 0)
  38039. {
  38040. if (lossOfFocusDiscardsChanges)
  38041. textEditorEscapeKeyPressed (*editor);
  38042. else
  38043. textEditorReturnKeyPressed (*editor);
  38044. }
  38045. }
  38046. bool Label::isBeingEdited() const throw()
  38047. {
  38048. return editor != 0;
  38049. }
  38050. TextEditor* Label::createEditorComponent()
  38051. {
  38052. TextEditor* const ed = new TextEditor (getName());
  38053. ed->setFont (font);
  38054. // copy these colours from our own settings..
  38055. const int cols[] = { TextEditor::backgroundColourId,
  38056. TextEditor::textColourId,
  38057. TextEditor::highlightColourId,
  38058. TextEditor::highlightedTextColourId,
  38059. TextEditor::caretColourId,
  38060. TextEditor::outlineColourId,
  38061. TextEditor::focusedOutlineColourId,
  38062. TextEditor::shadowColourId };
  38063. for (int i = 0; i < numElementsInArray (cols); ++i)
  38064. ed->setColour (cols[i], findColour (cols[i]));
  38065. return ed;
  38066. }
  38067. void Label::paint (Graphics& g)
  38068. {
  38069. getLookAndFeel().drawLabel (g, *this);
  38070. }
  38071. void Label::mouseUp (const MouseEvent& e)
  38072. {
  38073. if (editSingleClick
  38074. && e.mouseWasClicked()
  38075. && contains (e.x, e.y)
  38076. && ! e.mods.isPopupMenu())
  38077. {
  38078. showEditor();
  38079. }
  38080. }
  38081. void Label::mouseDoubleClick (const MouseEvent& e)
  38082. {
  38083. if (editDoubleClick && ! e.mods.isPopupMenu())
  38084. showEditor();
  38085. }
  38086. void Label::resized()
  38087. {
  38088. if (editor != 0)
  38089. editor->setBoundsInset (BorderSize (0));
  38090. }
  38091. void Label::focusGained (FocusChangeType cause)
  38092. {
  38093. if (editSingleClick && cause == focusChangedByTabKey)
  38094. showEditor();
  38095. }
  38096. void Label::enablementChanged()
  38097. {
  38098. repaint();
  38099. }
  38100. void Label::colourChanged()
  38101. {
  38102. repaint();
  38103. }
  38104. void Label::setMinimumHorizontalScale (const float newScale)
  38105. {
  38106. if (minimumHorizontalScale != newScale)
  38107. {
  38108. minimumHorizontalScale = newScale;
  38109. repaint();
  38110. }
  38111. }
  38112. // We'll use a custom focus traverser here to make sure focus goes from the
  38113. // text editor to another component rather than back to the label itself.
  38114. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38115. {
  38116. public:
  38117. LabelKeyboardFocusTraverser() {}
  38118. Component* getNextComponent (Component* current)
  38119. {
  38120. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38121. ? current->getParentComponent() : current);
  38122. }
  38123. Component* getPreviousComponent (Component* current)
  38124. {
  38125. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38126. ? current->getParentComponent() : current);
  38127. }
  38128. };
  38129. KeyboardFocusTraverser* Label::createFocusTraverser()
  38130. {
  38131. return new LabelKeyboardFocusTraverser();
  38132. }
  38133. void Label::addListener (Listener* const listener) throw()
  38134. {
  38135. listeners.add (listener);
  38136. }
  38137. void Label::removeListener (Listener* const listener) throw()
  38138. {
  38139. listeners.remove (listener);
  38140. }
  38141. void Label::callChangeListeners()
  38142. {
  38143. Component::BailOutChecker checker (this);
  38144. listeners.callChecked (checker, &Label::Listener::labelTextChanged, this);
  38145. }
  38146. void Label::textEditorTextChanged (TextEditor& ed)
  38147. {
  38148. if (editor != 0)
  38149. {
  38150. jassert (&ed == editor);
  38151. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38152. {
  38153. if (lossOfFocusDiscardsChanges)
  38154. textEditorEscapeKeyPressed (ed);
  38155. else
  38156. textEditorReturnKeyPressed (ed);
  38157. }
  38158. }
  38159. }
  38160. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38161. {
  38162. if (editor != 0)
  38163. {
  38164. jassert (&ed == editor);
  38165. (void) ed;
  38166. const bool changed = updateFromTextEditorContents();
  38167. hideEditor (true);
  38168. if (changed)
  38169. {
  38170. Component::SafePointer<Component> deletionChecker (this);
  38171. textWasEdited();
  38172. if (deletionChecker != 0)
  38173. callChangeListeners();
  38174. }
  38175. }
  38176. }
  38177. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38178. {
  38179. if (editor != 0)
  38180. {
  38181. jassert (&ed == editor);
  38182. (void) ed;
  38183. editor->setText (textValue.toString(), false);
  38184. hideEditor (true);
  38185. }
  38186. }
  38187. void Label::textEditorFocusLost (TextEditor& ed)
  38188. {
  38189. textEditorTextChanged (ed);
  38190. }
  38191. END_JUCE_NAMESPACE
  38192. /*** End of inlined file: juce_Label.cpp ***/
  38193. /*** Start of inlined file: juce_ListBox.cpp ***/
  38194. BEGIN_JUCE_NAMESPACE
  38195. class ListBoxRowComponent : public Component,
  38196. public TooltipClient
  38197. {
  38198. public:
  38199. ListBoxRowComponent (ListBox& owner_)
  38200. : owner (owner_),
  38201. row (-1),
  38202. selected (false),
  38203. isDragging (false)
  38204. {
  38205. }
  38206. ~ListBoxRowComponent()
  38207. {
  38208. deleteAllChildren();
  38209. }
  38210. void paint (Graphics& g)
  38211. {
  38212. if (owner.getModel() != 0)
  38213. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38214. }
  38215. void update (const int row_, const bool selected_)
  38216. {
  38217. if (row != row_ || selected != selected_)
  38218. {
  38219. repaint();
  38220. row = row_;
  38221. selected = selected_;
  38222. }
  38223. if (owner.getModel() != 0)
  38224. {
  38225. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  38226. if (customComp != 0)
  38227. {
  38228. addAndMakeVisible (customComp);
  38229. customComp->setBounds (getLocalBounds());
  38230. for (int i = getNumChildComponents(); --i >= 0;)
  38231. if (getChildComponent (i) != customComp)
  38232. delete getChildComponent (i);
  38233. }
  38234. else
  38235. {
  38236. deleteAllChildren();
  38237. }
  38238. }
  38239. }
  38240. void mouseDown (const MouseEvent& e)
  38241. {
  38242. isDragging = false;
  38243. selectRowOnMouseUp = false;
  38244. if (isEnabled())
  38245. {
  38246. if (! selected)
  38247. {
  38248. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38249. if (owner.getModel() != 0)
  38250. owner.getModel()->listBoxItemClicked (row, e);
  38251. }
  38252. else
  38253. {
  38254. selectRowOnMouseUp = true;
  38255. }
  38256. }
  38257. }
  38258. void mouseUp (const MouseEvent& e)
  38259. {
  38260. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38261. {
  38262. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38263. if (owner.getModel() != 0)
  38264. owner.getModel()->listBoxItemClicked (row, e);
  38265. }
  38266. }
  38267. void mouseDoubleClick (const MouseEvent& e)
  38268. {
  38269. if (owner.getModel() != 0 && isEnabled())
  38270. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38271. }
  38272. void mouseDrag (const MouseEvent& e)
  38273. {
  38274. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38275. {
  38276. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38277. if (selectedRows.size() > 0)
  38278. {
  38279. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38280. if (dragDescription.isNotEmpty())
  38281. {
  38282. isDragging = true;
  38283. owner.startDragAndDrop (e, dragDescription);
  38284. }
  38285. }
  38286. }
  38287. }
  38288. void resized()
  38289. {
  38290. if (getNumChildComponents() > 0)
  38291. getChildComponent(0)->setBounds (getLocalBounds());
  38292. }
  38293. const String getTooltip()
  38294. {
  38295. if (owner.getModel() != 0)
  38296. return owner.getModel()->getTooltipForRow (row);
  38297. return String::empty;
  38298. }
  38299. juce_UseDebuggingNewOperator
  38300. bool neededFlag;
  38301. private:
  38302. ListBox& owner;
  38303. int row;
  38304. bool selected, isDragging, selectRowOnMouseUp;
  38305. ListBoxRowComponent (const ListBoxRowComponent&);
  38306. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  38307. };
  38308. class ListViewport : public Viewport
  38309. {
  38310. public:
  38311. int firstIndex, firstWholeIndex, lastWholeIndex;
  38312. bool hasUpdated;
  38313. ListViewport (ListBox& owner_)
  38314. : owner (owner_)
  38315. {
  38316. setWantsKeyboardFocus (false);
  38317. setViewedComponent (new Component());
  38318. getViewedComponent()->addMouseListener (this, false);
  38319. getViewedComponent()->setWantsKeyboardFocus (false);
  38320. }
  38321. ~ListViewport()
  38322. {
  38323. getViewedComponent()->removeMouseListener (this);
  38324. getViewedComponent()->deleteAllChildren();
  38325. }
  38326. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38327. {
  38328. return static_cast <ListBoxRowComponent*>
  38329. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  38330. }
  38331. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38332. {
  38333. const int index = getIndexOfChildComponent (rowComponent);
  38334. const int num = getViewedComponent()->getNumChildComponents();
  38335. for (int i = num; --i >= 0;)
  38336. if (((firstIndex + i) % jmax (1, num)) == index)
  38337. return firstIndex + i;
  38338. return -1;
  38339. }
  38340. Component* getComponentForRowIfOnscreen (const int row) const throw()
  38341. {
  38342. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  38343. ? getComponentForRow (row) : 0;
  38344. }
  38345. void visibleAreaChanged (int, int, int, int)
  38346. {
  38347. updateVisibleArea (true);
  38348. if (owner.getModel() != 0)
  38349. owner.getModel()->listWasScrolled();
  38350. }
  38351. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38352. {
  38353. hasUpdated = false;
  38354. const int newX = getViewedComponent()->getX();
  38355. int newY = getViewedComponent()->getY();
  38356. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  38357. const int newH = owner.totalItems * owner.getRowHeight();
  38358. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  38359. newY = getMaximumVisibleHeight() - newH;
  38360. getViewedComponent()->setBounds (newX, newY, newW, newH);
  38361. if (makeSureItUpdatesContent && ! hasUpdated)
  38362. updateContents();
  38363. }
  38364. void updateContents()
  38365. {
  38366. hasUpdated = true;
  38367. const int rowHeight = owner.getRowHeight();
  38368. if (rowHeight > 0)
  38369. {
  38370. const int y = getViewPositionY();
  38371. const int w = getViewedComponent()->getWidth();
  38372. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  38373. while (numNeeded > getViewedComponent()->getNumChildComponents())
  38374. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  38375. jassert (numNeeded >= 0);
  38376. while (numNeeded < getViewedComponent()->getNumChildComponents())
  38377. {
  38378. Component* const rowToRemove
  38379. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  38380. delete rowToRemove;
  38381. }
  38382. firstIndex = y / rowHeight;
  38383. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  38384. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  38385. for (int i = 0; i < numNeeded; ++i)
  38386. {
  38387. const int row = i + firstIndex;
  38388. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  38389. if (rowComp != 0)
  38390. {
  38391. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  38392. rowComp->update (row, owner.isRowSelected (row));
  38393. }
  38394. }
  38395. }
  38396. if (owner.headerComponent != 0)
  38397. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  38398. owner.outlineThickness,
  38399. jmax (owner.getWidth() - owner.outlineThickness * 2,
  38400. getViewedComponent()->getWidth()),
  38401. owner.headerComponent->getHeight());
  38402. }
  38403. void paint (Graphics& g)
  38404. {
  38405. if (isOpaque())
  38406. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  38407. }
  38408. bool keyPressed (const KeyPress& key)
  38409. {
  38410. if (key.isKeyCode (KeyPress::upKey)
  38411. || key.isKeyCode (KeyPress::downKey)
  38412. || key.isKeyCode (KeyPress::pageUpKey)
  38413. || key.isKeyCode (KeyPress::pageDownKey)
  38414. || key.isKeyCode (KeyPress::homeKey)
  38415. || key.isKeyCode (KeyPress::endKey))
  38416. {
  38417. // we want to avoid these keypresses going to the viewport, and instead allow
  38418. // them to pass up to our listbox..
  38419. return false;
  38420. }
  38421. return Viewport::keyPressed (key);
  38422. }
  38423. juce_UseDebuggingNewOperator
  38424. private:
  38425. ListBox& owner;
  38426. ListViewport (const ListViewport&);
  38427. ListViewport& operator= (const ListViewport&);
  38428. };
  38429. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  38430. : Component (name),
  38431. model (model_),
  38432. totalItems (0),
  38433. rowHeight (22),
  38434. minimumRowWidth (0),
  38435. outlineThickness (0),
  38436. lastRowSelected (-1),
  38437. mouseMoveSelects (false),
  38438. multipleSelection (false),
  38439. hasDoneInitialUpdate (false)
  38440. {
  38441. addAndMakeVisible (viewport = new ListViewport (*this));
  38442. setWantsKeyboardFocus (true);
  38443. colourChanged();
  38444. }
  38445. ListBox::~ListBox()
  38446. {
  38447. headerComponent = 0;
  38448. viewport = 0;
  38449. }
  38450. void ListBox::setModel (ListBoxModel* const newModel)
  38451. {
  38452. if (model != newModel)
  38453. {
  38454. model = newModel;
  38455. updateContent();
  38456. }
  38457. }
  38458. void ListBox::setMultipleSelectionEnabled (bool b)
  38459. {
  38460. multipleSelection = b;
  38461. }
  38462. void ListBox::setMouseMoveSelectsRows (bool b)
  38463. {
  38464. mouseMoveSelects = b;
  38465. if (b)
  38466. addMouseListener (this, true);
  38467. }
  38468. void ListBox::paint (Graphics& g)
  38469. {
  38470. if (! hasDoneInitialUpdate)
  38471. updateContent();
  38472. g.fillAll (findColour (backgroundColourId));
  38473. }
  38474. void ListBox::paintOverChildren (Graphics& g)
  38475. {
  38476. if (outlineThickness > 0)
  38477. {
  38478. g.setColour (findColour (outlineColourId));
  38479. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  38480. }
  38481. }
  38482. void ListBox::resized()
  38483. {
  38484. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  38485. outlineThickness,
  38486. outlineThickness,
  38487. outlineThickness));
  38488. viewport->setSingleStepSizes (20, getRowHeight());
  38489. viewport->updateVisibleArea (false);
  38490. }
  38491. void ListBox::visibilityChanged()
  38492. {
  38493. viewport->updateVisibleArea (true);
  38494. }
  38495. Viewport* ListBox::getViewport() const throw()
  38496. {
  38497. return viewport;
  38498. }
  38499. void ListBox::updateContent()
  38500. {
  38501. hasDoneInitialUpdate = true;
  38502. totalItems = (model != 0) ? model->getNumRows() : 0;
  38503. bool selectionChanged = false;
  38504. if (selected [selected.size() - 1] >= totalItems)
  38505. {
  38506. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38507. lastRowSelected = getSelectedRow (0);
  38508. selectionChanged = true;
  38509. }
  38510. viewport->updateVisibleArea (isVisible());
  38511. viewport->resized();
  38512. if (selectionChanged && model != 0)
  38513. model->selectedRowsChanged (lastRowSelected);
  38514. }
  38515. void ListBox::selectRow (const int row,
  38516. bool dontScroll,
  38517. bool deselectOthersFirst)
  38518. {
  38519. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  38520. }
  38521. void ListBox::selectRowInternal (const int row,
  38522. bool dontScroll,
  38523. bool deselectOthersFirst,
  38524. bool isMouseClick)
  38525. {
  38526. if (! multipleSelection)
  38527. deselectOthersFirst = true;
  38528. if ((! isRowSelected (row))
  38529. || (deselectOthersFirst && getNumSelectedRows() > 1))
  38530. {
  38531. if (((unsigned int) row) < (unsigned int) totalItems)
  38532. {
  38533. if (deselectOthersFirst)
  38534. selected.clear();
  38535. selected.addRange (Range<int> (row, row + 1));
  38536. if (getHeight() == 0 || getWidth() == 0)
  38537. dontScroll = true;
  38538. viewport->hasUpdated = false;
  38539. if (row < viewport->firstWholeIndex && ! dontScroll)
  38540. {
  38541. viewport->setViewPosition (viewport->getViewPositionX(),
  38542. row * getRowHeight());
  38543. }
  38544. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  38545. {
  38546. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  38547. if (row >= lastRowSelected + rowsOnScreen
  38548. && rowsOnScreen < totalItems - 1
  38549. && ! isMouseClick)
  38550. {
  38551. viewport->setViewPosition (viewport->getViewPositionX(),
  38552. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  38553. * getRowHeight());
  38554. }
  38555. else
  38556. {
  38557. viewport->setViewPosition (viewport->getViewPositionX(),
  38558. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38559. }
  38560. }
  38561. if (! viewport->hasUpdated)
  38562. viewport->updateContents();
  38563. lastRowSelected = row;
  38564. model->selectedRowsChanged (row);
  38565. }
  38566. else
  38567. {
  38568. if (deselectOthersFirst)
  38569. deselectAllRows();
  38570. }
  38571. }
  38572. }
  38573. void ListBox::deselectRow (const int row)
  38574. {
  38575. if (selected.contains (row))
  38576. {
  38577. selected.removeRange (Range <int> (row, row + 1));
  38578. if (row == lastRowSelected)
  38579. lastRowSelected = getSelectedRow (0);
  38580. viewport->updateContents();
  38581. model->selectedRowsChanged (lastRowSelected);
  38582. }
  38583. }
  38584. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  38585. const bool sendNotificationEventToModel)
  38586. {
  38587. selected = setOfRowsToBeSelected;
  38588. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38589. if (! isRowSelected (lastRowSelected))
  38590. lastRowSelected = getSelectedRow (0);
  38591. viewport->updateContents();
  38592. if ((model != 0) && sendNotificationEventToModel)
  38593. model->selectedRowsChanged (lastRowSelected);
  38594. }
  38595. const SparseSet<int> ListBox::getSelectedRows() const
  38596. {
  38597. return selected;
  38598. }
  38599. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  38600. {
  38601. if (multipleSelection && (firstRow != lastRow))
  38602. {
  38603. const int numRows = totalItems - 1;
  38604. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  38605. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  38606. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  38607. jmax (firstRow, lastRow) + 1));
  38608. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  38609. }
  38610. selectRowInternal (lastRow, false, false, true);
  38611. }
  38612. void ListBox::flipRowSelection (const int row)
  38613. {
  38614. if (isRowSelected (row))
  38615. deselectRow (row);
  38616. else
  38617. selectRowInternal (row, false, false, true);
  38618. }
  38619. void ListBox::deselectAllRows()
  38620. {
  38621. if (! selected.isEmpty())
  38622. {
  38623. selected.clear();
  38624. lastRowSelected = -1;
  38625. viewport->updateContents();
  38626. if (model != 0)
  38627. model->selectedRowsChanged (lastRowSelected);
  38628. }
  38629. }
  38630. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  38631. const ModifierKeys& mods)
  38632. {
  38633. if (multipleSelection && mods.isCommandDown())
  38634. {
  38635. flipRowSelection (row);
  38636. }
  38637. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  38638. {
  38639. selectRangeOfRows (lastRowSelected, row);
  38640. }
  38641. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  38642. {
  38643. selectRowInternal (row, false, true, true);
  38644. }
  38645. }
  38646. int ListBox::getNumSelectedRows() const
  38647. {
  38648. return selected.size();
  38649. }
  38650. int ListBox::getSelectedRow (const int index) const
  38651. {
  38652. return (((unsigned int) index) < (unsigned int) selected.size())
  38653. ? selected [index] : -1;
  38654. }
  38655. bool ListBox::isRowSelected (const int row) const
  38656. {
  38657. return selected.contains (row);
  38658. }
  38659. int ListBox::getLastRowSelected() const
  38660. {
  38661. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  38662. }
  38663. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  38664. {
  38665. if (((unsigned int) x) < (unsigned int) getWidth())
  38666. {
  38667. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  38668. if (((unsigned int) row) < (unsigned int) totalItems)
  38669. return row;
  38670. }
  38671. return -1;
  38672. }
  38673. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  38674. {
  38675. if (((unsigned int) x) < (unsigned int) getWidth())
  38676. {
  38677. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  38678. return jlimit (0, totalItems, row);
  38679. }
  38680. return -1;
  38681. }
  38682. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  38683. {
  38684. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  38685. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  38686. }
  38687. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  38688. {
  38689. return viewport->getRowNumberOfComponent (rowComponent);
  38690. }
  38691. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  38692. const bool relativeToComponentTopLeft) const throw()
  38693. {
  38694. int y = viewport->getY() + rowHeight * rowNumber;
  38695. if (relativeToComponentTopLeft)
  38696. y -= viewport->getViewPositionY();
  38697. return Rectangle<int> (viewport->getX(), y,
  38698. viewport->getViewedComponent()->getWidth(), rowHeight);
  38699. }
  38700. void ListBox::setVerticalPosition (const double proportion)
  38701. {
  38702. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38703. viewport->setViewPosition (viewport->getViewPositionX(),
  38704. jmax (0, roundToInt (proportion * offscreen)));
  38705. }
  38706. double ListBox::getVerticalPosition() const
  38707. {
  38708. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38709. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  38710. : 0;
  38711. }
  38712. int ListBox::getVisibleRowWidth() const throw()
  38713. {
  38714. return viewport->getViewWidth();
  38715. }
  38716. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  38717. {
  38718. if (row < viewport->firstWholeIndex)
  38719. {
  38720. viewport->setViewPosition (viewport->getViewPositionX(),
  38721. row * getRowHeight());
  38722. }
  38723. else if (row >= viewport->lastWholeIndex)
  38724. {
  38725. viewport->setViewPosition (viewport->getViewPositionX(),
  38726. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38727. }
  38728. }
  38729. bool ListBox::keyPressed (const KeyPress& key)
  38730. {
  38731. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  38732. const bool multiple = multipleSelection
  38733. && (lastRowSelected >= 0)
  38734. && (key.getModifiers().isShiftDown()
  38735. || key.getModifiers().isCtrlDown()
  38736. || key.getModifiers().isCommandDown());
  38737. if (key.isKeyCode (KeyPress::upKey))
  38738. {
  38739. if (multiple)
  38740. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  38741. else
  38742. selectRow (jmax (0, lastRowSelected - 1));
  38743. }
  38744. else if (key.isKeyCode (KeyPress::returnKey)
  38745. && isRowSelected (lastRowSelected))
  38746. {
  38747. if (model != 0)
  38748. model->returnKeyPressed (lastRowSelected);
  38749. }
  38750. else if (key.isKeyCode (KeyPress::pageUpKey))
  38751. {
  38752. if (multiple)
  38753. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  38754. else
  38755. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  38756. }
  38757. else if (key.isKeyCode (KeyPress::pageDownKey))
  38758. {
  38759. if (multiple)
  38760. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  38761. else
  38762. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  38763. }
  38764. else if (key.isKeyCode (KeyPress::homeKey))
  38765. {
  38766. if (multiple && key.getModifiers().isShiftDown())
  38767. selectRangeOfRows (lastRowSelected, 0);
  38768. else
  38769. selectRow (0);
  38770. }
  38771. else if (key.isKeyCode (KeyPress::endKey))
  38772. {
  38773. if (multiple && key.getModifiers().isShiftDown())
  38774. selectRangeOfRows (lastRowSelected, totalItems - 1);
  38775. else
  38776. selectRow (totalItems - 1);
  38777. }
  38778. else if (key.isKeyCode (KeyPress::downKey))
  38779. {
  38780. if (multiple)
  38781. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  38782. else
  38783. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  38784. }
  38785. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  38786. && isRowSelected (lastRowSelected))
  38787. {
  38788. if (model != 0)
  38789. model->deleteKeyPressed (lastRowSelected);
  38790. }
  38791. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  38792. {
  38793. selectRangeOfRows (0, std::numeric_limits<int>::max());
  38794. }
  38795. else
  38796. {
  38797. return false;
  38798. }
  38799. return true;
  38800. }
  38801. bool ListBox::keyStateChanged (const bool isKeyDown)
  38802. {
  38803. return isKeyDown
  38804. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38805. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  38806. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38807. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  38808. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  38809. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  38810. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  38811. }
  38812. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  38813. {
  38814. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  38815. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  38816. }
  38817. void ListBox::mouseMove (const MouseEvent& e)
  38818. {
  38819. if (mouseMoveSelects)
  38820. {
  38821. const MouseEvent e2 (e.getEventRelativeTo (this));
  38822. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  38823. }
  38824. }
  38825. void ListBox::mouseExit (const MouseEvent& e)
  38826. {
  38827. mouseMove (e);
  38828. }
  38829. void ListBox::mouseUp (const MouseEvent& e)
  38830. {
  38831. if (e.mouseWasClicked() && model != 0)
  38832. model->backgroundClicked();
  38833. }
  38834. void ListBox::setRowHeight (const int newHeight)
  38835. {
  38836. rowHeight = jmax (1, newHeight);
  38837. viewport->setSingleStepSizes (20, rowHeight);
  38838. updateContent();
  38839. }
  38840. int ListBox::getNumRowsOnScreen() const throw()
  38841. {
  38842. return viewport->getMaximumVisibleHeight() / rowHeight;
  38843. }
  38844. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  38845. {
  38846. minimumRowWidth = newMinimumWidth;
  38847. updateContent();
  38848. }
  38849. int ListBox::getVisibleContentWidth() const throw()
  38850. {
  38851. return viewport->getMaximumVisibleWidth();
  38852. }
  38853. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  38854. {
  38855. return viewport->getVerticalScrollBar();
  38856. }
  38857. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  38858. {
  38859. return viewport->getHorizontalScrollBar();
  38860. }
  38861. void ListBox::colourChanged()
  38862. {
  38863. setOpaque (findColour (backgroundColourId).isOpaque());
  38864. viewport->setOpaque (isOpaque());
  38865. repaint();
  38866. }
  38867. void ListBox::setOutlineThickness (const int outlineThickness_)
  38868. {
  38869. outlineThickness = outlineThickness_;
  38870. resized();
  38871. }
  38872. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  38873. {
  38874. if (newHeaderComponent != headerComponent)
  38875. {
  38876. headerComponent = newHeaderComponent;
  38877. addAndMakeVisible (newHeaderComponent);
  38878. ListBox::resized();
  38879. }
  38880. }
  38881. void ListBox::repaintRow (const int rowNumber) throw()
  38882. {
  38883. repaint (getRowPosition (rowNumber, true));
  38884. }
  38885. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  38886. {
  38887. Rectangle<int> imageArea;
  38888. const int firstRow = getRowContainingPosition (0, 0);
  38889. int i;
  38890. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38891. {
  38892. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38893. if (rowComp != 0 && isRowSelected (firstRow + i))
  38894. {
  38895. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38896. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  38897. imageArea = imageArea.getUnion (rowRect);
  38898. }
  38899. }
  38900. imageArea = imageArea.getIntersection (getLocalBounds());
  38901. imageX = imageArea.getX();
  38902. imageY = imageArea.getY();
  38903. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  38904. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38905. {
  38906. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38907. if (rowComp != 0 && isRowSelected (firstRow + i))
  38908. {
  38909. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38910. Graphics g (snapshot);
  38911. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  38912. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  38913. rowComp->paintEntireComponent (g);
  38914. }
  38915. }
  38916. return snapshot;
  38917. }
  38918. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  38919. {
  38920. DragAndDropContainer* const dragContainer
  38921. = DragAndDropContainer::findParentDragContainerFor (this);
  38922. if (dragContainer != 0)
  38923. {
  38924. int x, y;
  38925. Image dragImage (createSnapshotOfSelectedRows (x, y));
  38926. dragImage.multiplyAllAlphas (0.6f);
  38927. MouseEvent e2 (e.getEventRelativeTo (this));
  38928. const Point<int> p (x - e2.x, y - e2.y);
  38929. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  38930. }
  38931. else
  38932. {
  38933. // to be able to do a drag-and-drop operation, the listbox needs to
  38934. // be inside a component which is also a DragAndDropContainer.
  38935. jassertfalse;
  38936. }
  38937. }
  38938. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  38939. {
  38940. (void) existingComponentToUpdate;
  38941. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  38942. return 0;
  38943. }
  38944. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  38945. {
  38946. }
  38947. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  38948. {
  38949. }
  38950. void ListBoxModel::backgroundClicked()
  38951. {
  38952. }
  38953. void ListBoxModel::selectedRowsChanged (int)
  38954. {
  38955. }
  38956. void ListBoxModel::deleteKeyPressed (int)
  38957. {
  38958. }
  38959. void ListBoxModel::returnKeyPressed (int)
  38960. {
  38961. }
  38962. void ListBoxModel::listWasScrolled()
  38963. {
  38964. }
  38965. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  38966. {
  38967. return String::empty;
  38968. }
  38969. const String ListBoxModel::getTooltipForRow (int)
  38970. {
  38971. return String::empty;
  38972. }
  38973. END_JUCE_NAMESPACE
  38974. /*** End of inlined file: juce_ListBox.cpp ***/
  38975. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  38976. BEGIN_JUCE_NAMESPACE
  38977. ProgressBar::ProgressBar (double& progress_)
  38978. : progress (progress_),
  38979. displayPercentage (true),
  38980. lastCallbackTime (0)
  38981. {
  38982. currentValue = jlimit (0.0, 1.0, progress);
  38983. }
  38984. ProgressBar::~ProgressBar()
  38985. {
  38986. }
  38987. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  38988. {
  38989. displayPercentage = shouldDisplayPercentage;
  38990. repaint();
  38991. }
  38992. void ProgressBar::setTextToDisplay (const String& text)
  38993. {
  38994. displayPercentage = false;
  38995. displayedMessage = text;
  38996. }
  38997. void ProgressBar::lookAndFeelChanged()
  38998. {
  38999. setOpaque (findColour (backgroundColourId).isOpaque());
  39000. }
  39001. void ProgressBar::colourChanged()
  39002. {
  39003. lookAndFeelChanged();
  39004. }
  39005. void ProgressBar::paint (Graphics& g)
  39006. {
  39007. String text;
  39008. if (displayPercentage)
  39009. {
  39010. if (currentValue >= 0 && currentValue <= 1.0)
  39011. text << roundToInt (currentValue * 100.0) << '%';
  39012. }
  39013. else
  39014. {
  39015. text = displayedMessage;
  39016. }
  39017. getLookAndFeel().drawProgressBar (g, *this,
  39018. getWidth(), getHeight(),
  39019. currentValue, text);
  39020. }
  39021. void ProgressBar::visibilityChanged()
  39022. {
  39023. if (isVisible())
  39024. startTimer (30);
  39025. else
  39026. stopTimer();
  39027. }
  39028. void ProgressBar::timerCallback()
  39029. {
  39030. double newProgress = progress;
  39031. const uint32 now = Time::getMillisecondCounter();
  39032. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39033. lastCallbackTime = now;
  39034. if (currentValue != newProgress
  39035. || newProgress < 0 || newProgress >= 1.0
  39036. || currentMessage != displayedMessage)
  39037. {
  39038. if (currentValue < newProgress
  39039. && newProgress >= 0 && newProgress < 1.0
  39040. && currentValue >= 0 && currentValue < 1.0)
  39041. {
  39042. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39043. newProgress);
  39044. }
  39045. currentValue = newProgress;
  39046. currentMessage = displayedMessage;
  39047. repaint();
  39048. }
  39049. }
  39050. END_JUCE_NAMESPACE
  39051. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39052. /*** Start of inlined file: juce_Slider.cpp ***/
  39053. BEGIN_JUCE_NAMESPACE
  39054. class SliderPopupDisplayComponent : public BubbleComponent
  39055. {
  39056. public:
  39057. SliderPopupDisplayComponent (Slider* const owner_)
  39058. : owner (owner_),
  39059. font (15.0f, Font::bold)
  39060. {
  39061. setAlwaysOnTop (true);
  39062. }
  39063. ~SliderPopupDisplayComponent()
  39064. {
  39065. }
  39066. void paintContent (Graphics& g, int w, int h)
  39067. {
  39068. g.setFont (font);
  39069. g.setColour (Colours::black);
  39070. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39071. }
  39072. void getContentSize (int& w, int& h)
  39073. {
  39074. w = font.getStringWidth (text) + 18;
  39075. h = (int) (font.getHeight() * 1.6f);
  39076. }
  39077. void updatePosition (const String& newText)
  39078. {
  39079. if (text != newText)
  39080. {
  39081. text = newText;
  39082. repaint();
  39083. }
  39084. BubbleComponent::setPosition (owner);
  39085. }
  39086. juce_UseDebuggingNewOperator
  39087. private:
  39088. Slider* owner;
  39089. Font font;
  39090. String text;
  39091. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  39092. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  39093. };
  39094. Slider::Slider (const String& name)
  39095. : Component (name),
  39096. lastCurrentValue (0),
  39097. lastValueMin (0),
  39098. lastValueMax (0),
  39099. minimum (0),
  39100. maximum (10),
  39101. interval (0),
  39102. skewFactor (1.0),
  39103. velocityModeSensitivity (1.0),
  39104. velocityModeOffset (0.0),
  39105. velocityModeThreshold (1),
  39106. rotaryStart (float_Pi * 1.2f),
  39107. rotaryEnd (float_Pi * 2.8f),
  39108. numDecimalPlaces (7),
  39109. sliderRegionStart (0),
  39110. sliderRegionSize (1),
  39111. sliderBeingDragged (-1),
  39112. pixelsForFullDragExtent (250),
  39113. style (LinearHorizontal),
  39114. textBoxPos (TextBoxLeft),
  39115. textBoxWidth (80),
  39116. textBoxHeight (20),
  39117. incDecButtonMode (incDecButtonsNotDraggable),
  39118. editableText (true),
  39119. doubleClickToValue (false),
  39120. isVelocityBased (false),
  39121. userKeyOverridesVelocity (true),
  39122. rotaryStop (true),
  39123. incDecButtonsSideBySide (false),
  39124. sendChangeOnlyOnRelease (false),
  39125. popupDisplayEnabled (false),
  39126. menuEnabled (false),
  39127. menuShown (false),
  39128. scrollWheelEnabled (true),
  39129. snapsToMousePos (true),
  39130. valueBox (0),
  39131. incButton (0),
  39132. decButton (0),
  39133. popupDisplay (0),
  39134. parentForPopupDisplay (0)
  39135. {
  39136. setWantsKeyboardFocus (false);
  39137. setRepaintsOnMouseActivity (true);
  39138. lookAndFeelChanged();
  39139. updateText();
  39140. currentValue.addListener (this);
  39141. valueMin.addListener (this);
  39142. valueMax.addListener (this);
  39143. }
  39144. Slider::~Slider()
  39145. {
  39146. currentValue.removeListener (this);
  39147. valueMin.removeListener (this);
  39148. valueMax.removeListener (this);
  39149. popupDisplay = 0;
  39150. deleteAllChildren();
  39151. }
  39152. void Slider::handleAsyncUpdate()
  39153. {
  39154. cancelPendingUpdate();
  39155. Component::BailOutChecker checker (this);
  39156. listeners.callChecked (checker, &Slider::Listener::sliderValueChanged, this);
  39157. }
  39158. void Slider::sendDragStart()
  39159. {
  39160. startedDragging();
  39161. Component::BailOutChecker checker (this);
  39162. listeners.callChecked (checker, &Slider::Listener::sliderDragStarted, this);
  39163. }
  39164. void Slider::sendDragEnd()
  39165. {
  39166. stoppedDragging();
  39167. sliderBeingDragged = -1;
  39168. Component::BailOutChecker checker (this);
  39169. listeners.callChecked (checker, &Slider::Listener::sliderDragEnded, this);
  39170. }
  39171. void Slider::addListener (Listener* const listener)
  39172. {
  39173. listeners.add (listener);
  39174. }
  39175. void Slider::removeListener (Listener* const listener)
  39176. {
  39177. listeners.remove (listener);
  39178. }
  39179. void Slider::setSliderStyle (const SliderStyle newStyle)
  39180. {
  39181. if (style != newStyle)
  39182. {
  39183. style = newStyle;
  39184. repaint();
  39185. lookAndFeelChanged();
  39186. }
  39187. }
  39188. void Slider::setRotaryParameters (const float startAngleRadians,
  39189. const float endAngleRadians,
  39190. const bool stopAtEnd)
  39191. {
  39192. // make sure the values are sensible..
  39193. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39194. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39195. jassert (rotaryStart < rotaryEnd);
  39196. rotaryStart = startAngleRadians;
  39197. rotaryEnd = endAngleRadians;
  39198. rotaryStop = stopAtEnd;
  39199. }
  39200. void Slider::setVelocityBasedMode (const bool velBased)
  39201. {
  39202. isVelocityBased = velBased;
  39203. }
  39204. void Slider::setVelocityModeParameters (const double sensitivity,
  39205. const int threshold,
  39206. const double offset,
  39207. const bool userCanPressKeyToSwapMode)
  39208. {
  39209. jassert (threshold >= 0);
  39210. jassert (sensitivity > 0);
  39211. jassert (offset >= 0);
  39212. velocityModeSensitivity = sensitivity;
  39213. velocityModeOffset = offset;
  39214. velocityModeThreshold = threshold;
  39215. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39216. }
  39217. void Slider::setSkewFactor (const double factor)
  39218. {
  39219. skewFactor = factor;
  39220. }
  39221. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39222. {
  39223. if (maximum > minimum)
  39224. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39225. / (maximum - minimum));
  39226. }
  39227. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39228. {
  39229. jassert (distanceForFullScaleDrag > 0);
  39230. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39231. }
  39232. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39233. {
  39234. if (incDecButtonMode != mode)
  39235. {
  39236. incDecButtonMode = mode;
  39237. lookAndFeelChanged();
  39238. }
  39239. }
  39240. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39241. const bool isReadOnly,
  39242. const int textEntryBoxWidth,
  39243. const int textEntryBoxHeight)
  39244. {
  39245. if (textBoxPos != newPosition
  39246. || editableText != (! isReadOnly)
  39247. || textBoxWidth != textEntryBoxWidth
  39248. || textBoxHeight != textEntryBoxHeight)
  39249. {
  39250. textBoxPos = newPosition;
  39251. editableText = ! isReadOnly;
  39252. textBoxWidth = textEntryBoxWidth;
  39253. textBoxHeight = textEntryBoxHeight;
  39254. repaint();
  39255. lookAndFeelChanged();
  39256. }
  39257. }
  39258. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39259. {
  39260. editableText = shouldBeEditable;
  39261. if (valueBox != 0)
  39262. valueBox->setEditable (shouldBeEditable && isEnabled());
  39263. }
  39264. void Slider::showTextBox()
  39265. {
  39266. jassert (editableText); // this should probably be avoided in read-only sliders.
  39267. if (valueBox != 0)
  39268. valueBox->showEditor();
  39269. }
  39270. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39271. {
  39272. if (valueBox != 0)
  39273. {
  39274. valueBox->hideEditor (discardCurrentEditorContents);
  39275. if (discardCurrentEditorContents)
  39276. updateText();
  39277. }
  39278. }
  39279. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39280. {
  39281. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39282. }
  39283. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39284. {
  39285. snapsToMousePos = shouldSnapToMouse;
  39286. }
  39287. void Slider::setPopupDisplayEnabled (const bool enabled,
  39288. Component* const parentComponentToUse)
  39289. {
  39290. popupDisplayEnabled = enabled;
  39291. parentForPopupDisplay = parentComponentToUse;
  39292. }
  39293. void Slider::colourChanged()
  39294. {
  39295. lookAndFeelChanged();
  39296. }
  39297. void Slider::lookAndFeelChanged()
  39298. {
  39299. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39300. : getTextFromValue (currentValue.getValue()));
  39301. deleteAllChildren();
  39302. valueBox = 0;
  39303. LookAndFeel& lf = getLookAndFeel();
  39304. if (textBoxPos != NoTextBox)
  39305. {
  39306. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39307. valueBox->setWantsKeyboardFocus (false);
  39308. valueBox->setText (previousTextBoxContent, false);
  39309. valueBox->setEditable (editableText && isEnabled());
  39310. valueBox->addListener (this);
  39311. if (style == LinearBar)
  39312. valueBox->addMouseListener (this, false);
  39313. valueBox->setTooltip (getTooltip());
  39314. }
  39315. if (style == IncDecButtons)
  39316. {
  39317. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39318. incButton->addButtonListener (this);
  39319. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39320. decButton->addButtonListener (this);
  39321. if (incDecButtonMode != incDecButtonsNotDraggable)
  39322. {
  39323. incButton->addMouseListener (this, false);
  39324. decButton->addMouseListener (this, false);
  39325. }
  39326. else
  39327. {
  39328. incButton->setRepeatSpeed (300, 100, 20);
  39329. incButton->addMouseListener (decButton, false);
  39330. decButton->setRepeatSpeed (300, 100, 20);
  39331. decButton->addMouseListener (incButton, false);
  39332. }
  39333. incButton->setTooltip (getTooltip());
  39334. decButton->setTooltip (getTooltip());
  39335. }
  39336. setComponentEffect (lf.getSliderEffect());
  39337. resized();
  39338. repaint();
  39339. }
  39340. void Slider::setRange (const double newMin,
  39341. const double newMax,
  39342. const double newInt)
  39343. {
  39344. if (minimum != newMin
  39345. || maximum != newMax
  39346. || interval != newInt)
  39347. {
  39348. minimum = newMin;
  39349. maximum = newMax;
  39350. interval = newInt;
  39351. // figure out the number of DPs needed to display all values at this
  39352. // interval setting.
  39353. numDecimalPlaces = 7;
  39354. if (newInt != 0)
  39355. {
  39356. int v = abs ((int) (newInt * 10000000));
  39357. while ((v % 10) == 0)
  39358. {
  39359. --numDecimalPlaces;
  39360. v /= 10;
  39361. }
  39362. }
  39363. // keep the current values inside the new range..
  39364. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39365. {
  39366. setValue (getValue(), false, false);
  39367. }
  39368. else
  39369. {
  39370. setMinValue (getMinValue(), false, false);
  39371. setMaxValue (getMaxValue(), false, false);
  39372. }
  39373. updateText();
  39374. }
  39375. }
  39376. void Slider::triggerChangeMessage (const bool synchronous)
  39377. {
  39378. if (synchronous)
  39379. handleAsyncUpdate();
  39380. else
  39381. triggerAsyncUpdate();
  39382. valueChanged();
  39383. }
  39384. void Slider::valueChanged (Value& value)
  39385. {
  39386. if (value.refersToSameSourceAs (currentValue))
  39387. {
  39388. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39389. setValue (currentValue.getValue(), false, false);
  39390. }
  39391. else if (value.refersToSameSourceAs (valueMin))
  39392. setMinValue (valueMin.getValue(), false, false, true);
  39393. else if (value.refersToSameSourceAs (valueMax))
  39394. setMaxValue (valueMax.getValue(), false, false, true);
  39395. }
  39396. double Slider::getValue() const
  39397. {
  39398. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  39399. // methods to get the two values.
  39400. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39401. return currentValue.getValue();
  39402. }
  39403. void Slider::setValue (double newValue,
  39404. const bool sendUpdateMessage,
  39405. const bool sendMessageSynchronously)
  39406. {
  39407. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  39408. // methods to set the two values.
  39409. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39410. newValue = constrainedValue (newValue);
  39411. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39412. {
  39413. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  39414. newValue = jlimit ((double) valueMin.getValue(),
  39415. (double) valueMax.getValue(),
  39416. newValue);
  39417. }
  39418. if (newValue != lastCurrentValue)
  39419. {
  39420. if (valueBox != 0)
  39421. valueBox->hideEditor (true);
  39422. lastCurrentValue = newValue;
  39423. currentValue = newValue;
  39424. updateText();
  39425. repaint();
  39426. if (popupDisplay != 0)
  39427. {
  39428. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39429. ->updatePosition (getTextFromValue (newValue));
  39430. popupDisplay->repaint();
  39431. }
  39432. if (sendUpdateMessage)
  39433. triggerChangeMessage (sendMessageSynchronously);
  39434. }
  39435. }
  39436. double Slider::getMinValue() const
  39437. {
  39438. // The minimum value only applies to sliders that are in two- or three-value mode.
  39439. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39440. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39441. return valueMin.getValue();
  39442. }
  39443. double Slider::getMaxValue() const
  39444. {
  39445. // The maximum value only applies to sliders that are in two- or three-value mode.
  39446. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39447. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39448. return valueMax.getValue();
  39449. }
  39450. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39451. {
  39452. // The minimum value only applies to sliders that are in two- or three-value mode.
  39453. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39454. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39455. newValue = constrainedValue (newValue);
  39456. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39457. {
  39458. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  39459. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39460. newValue = jmin ((double) valueMax.getValue(), newValue);
  39461. }
  39462. else
  39463. {
  39464. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  39465. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39466. newValue = jmin (lastCurrentValue, newValue);
  39467. }
  39468. if (lastValueMin != newValue)
  39469. {
  39470. lastValueMin = newValue;
  39471. valueMin = newValue;
  39472. repaint();
  39473. if (popupDisplay != 0)
  39474. {
  39475. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39476. ->updatePosition (getTextFromValue (newValue));
  39477. popupDisplay->repaint();
  39478. }
  39479. if (sendUpdateMessage)
  39480. triggerChangeMessage (sendMessageSynchronously);
  39481. }
  39482. }
  39483. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39484. {
  39485. // The maximum value only applies to sliders that are in two- or three-value mode.
  39486. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39487. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39488. newValue = constrainedValue (newValue);
  39489. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39490. {
  39491. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  39492. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39493. newValue = jmax ((double) valueMin.getValue(), newValue);
  39494. }
  39495. else
  39496. {
  39497. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  39498. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39499. newValue = jmax (lastCurrentValue, newValue);
  39500. }
  39501. if (lastValueMax != newValue)
  39502. {
  39503. lastValueMax = newValue;
  39504. valueMax = newValue;
  39505. repaint();
  39506. if (popupDisplay != 0)
  39507. {
  39508. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39509. ->updatePosition (getTextFromValue (valueMax.getValue()));
  39510. popupDisplay->repaint();
  39511. }
  39512. if (sendUpdateMessage)
  39513. triggerChangeMessage (sendMessageSynchronously);
  39514. }
  39515. }
  39516. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  39517. const double valueToSetOnDoubleClick)
  39518. {
  39519. doubleClickToValue = isDoubleClickEnabled;
  39520. doubleClickReturnValue = valueToSetOnDoubleClick;
  39521. }
  39522. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  39523. {
  39524. isEnabled_ = doubleClickToValue;
  39525. return doubleClickReturnValue;
  39526. }
  39527. void Slider::updateText()
  39528. {
  39529. if (valueBox != 0)
  39530. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  39531. }
  39532. void Slider::setTextValueSuffix (const String& suffix)
  39533. {
  39534. if (textSuffix != suffix)
  39535. {
  39536. textSuffix = suffix;
  39537. updateText();
  39538. }
  39539. }
  39540. const String Slider::getTextValueSuffix() const
  39541. {
  39542. return textSuffix;
  39543. }
  39544. const String Slider::getTextFromValue (double v)
  39545. {
  39546. if (getNumDecimalPlacesToDisplay() > 0)
  39547. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  39548. else
  39549. return String (roundToInt (v)) + getTextValueSuffix();
  39550. }
  39551. double Slider::getValueFromText (const String& text)
  39552. {
  39553. String t (text.trimStart());
  39554. if (t.endsWith (textSuffix))
  39555. t = t.substring (0, t.length() - textSuffix.length());
  39556. while (t.startsWithChar ('+'))
  39557. t = t.substring (1).trimStart();
  39558. return t.initialSectionContainingOnly ("0123456789.,-")
  39559. .getDoubleValue();
  39560. }
  39561. double Slider::proportionOfLengthToValue (double proportion)
  39562. {
  39563. if (skewFactor != 1.0 && proportion > 0.0)
  39564. proportion = exp (log (proportion) / skewFactor);
  39565. return minimum + (maximum - minimum) * proportion;
  39566. }
  39567. double Slider::valueToProportionOfLength (double value)
  39568. {
  39569. const double n = (value - minimum) / (maximum - minimum);
  39570. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  39571. }
  39572. double Slider::snapValue (double attemptedValue, const bool)
  39573. {
  39574. return attemptedValue;
  39575. }
  39576. void Slider::startedDragging()
  39577. {
  39578. }
  39579. void Slider::stoppedDragging()
  39580. {
  39581. }
  39582. void Slider::valueChanged()
  39583. {
  39584. }
  39585. void Slider::enablementChanged()
  39586. {
  39587. repaint();
  39588. }
  39589. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  39590. {
  39591. menuEnabled = menuEnabled_;
  39592. }
  39593. void Slider::setScrollWheelEnabled (const bool enabled)
  39594. {
  39595. scrollWheelEnabled = enabled;
  39596. }
  39597. void Slider::labelTextChanged (Label* label)
  39598. {
  39599. const double newValue = snapValue (getValueFromText (label->getText()), false);
  39600. if (newValue != (double) currentValue.getValue())
  39601. {
  39602. sendDragStart();
  39603. setValue (newValue, true, true);
  39604. sendDragEnd();
  39605. }
  39606. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  39607. }
  39608. void Slider::buttonClicked (Button* button)
  39609. {
  39610. if (style == IncDecButtons)
  39611. {
  39612. sendDragStart();
  39613. if (button == incButton)
  39614. setValue (snapValue (getValue() + interval, false), true, true);
  39615. else if (button == decButton)
  39616. setValue (snapValue (getValue() - interval, false), true, true);
  39617. sendDragEnd();
  39618. }
  39619. }
  39620. double Slider::constrainedValue (double value) const
  39621. {
  39622. if (interval > 0)
  39623. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  39624. if (value <= minimum || maximum <= minimum)
  39625. value = minimum;
  39626. else if (value >= maximum)
  39627. value = maximum;
  39628. return value;
  39629. }
  39630. float Slider::getLinearSliderPos (const double value)
  39631. {
  39632. double sliderPosProportional;
  39633. if (maximum > minimum)
  39634. {
  39635. if (value < minimum)
  39636. {
  39637. sliderPosProportional = 0.0;
  39638. }
  39639. else if (value > maximum)
  39640. {
  39641. sliderPosProportional = 1.0;
  39642. }
  39643. else
  39644. {
  39645. sliderPosProportional = valueToProportionOfLength (value);
  39646. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  39647. }
  39648. }
  39649. else
  39650. {
  39651. sliderPosProportional = 0.5;
  39652. }
  39653. if (isVertical() || style == IncDecButtons)
  39654. sliderPosProportional = 1.0 - sliderPosProportional;
  39655. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  39656. }
  39657. bool Slider::isHorizontal() const
  39658. {
  39659. return style == LinearHorizontal
  39660. || style == LinearBar
  39661. || style == TwoValueHorizontal
  39662. || style == ThreeValueHorizontal;
  39663. }
  39664. bool Slider::isVertical() const
  39665. {
  39666. return style == LinearVertical
  39667. || style == TwoValueVertical
  39668. || style == ThreeValueVertical;
  39669. }
  39670. bool Slider::incDecDragDirectionIsHorizontal() const
  39671. {
  39672. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  39673. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  39674. }
  39675. float Slider::getPositionOfValue (const double value)
  39676. {
  39677. if (isHorizontal() || isVertical())
  39678. {
  39679. return getLinearSliderPos (value);
  39680. }
  39681. else
  39682. {
  39683. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  39684. return 0.0f;
  39685. }
  39686. }
  39687. void Slider::paint (Graphics& g)
  39688. {
  39689. if (style != IncDecButtons)
  39690. {
  39691. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39692. {
  39693. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  39694. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  39695. getLookAndFeel().drawRotarySlider (g,
  39696. sliderRect.getX(),
  39697. sliderRect.getY(),
  39698. sliderRect.getWidth(),
  39699. sliderRect.getHeight(),
  39700. sliderPos,
  39701. rotaryStart, rotaryEnd,
  39702. *this);
  39703. }
  39704. else
  39705. {
  39706. getLookAndFeel().drawLinearSlider (g,
  39707. sliderRect.getX(),
  39708. sliderRect.getY(),
  39709. sliderRect.getWidth(),
  39710. sliderRect.getHeight(),
  39711. getLinearSliderPos (lastCurrentValue),
  39712. getLinearSliderPos (lastValueMin),
  39713. getLinearSliderPos (lastValueMax),
  39714. style,
  39715. *this);
  39716. }
  39717. if (style == LinearBar && valueBox == 0)
  39718. {
  39719. g.setColour (findColour (Slider::textBoxOutlineColourId));
  39720. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  39721. }
  39722. }
  39723. }
  39724. void Slider::resized()
  39725. {
  39726. int minXSpace = 0;
  39727. int minYSpace = 0;
  39728. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39729. minXSpace = 30;
  39730. else
  39731. minYSpace = 15;
  39732. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  39733. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  39734. if (style == LinearBar)
  39735. {
  39736. if (valueBox != 0)
  39737. valueBox->setBounds (getLocalBounds());
  39738. }
  39739. else
  39740. {
  39741. if (textBoxPos == NoTextBox)
  39742. {
  39743. sliderRect = getLocalBounds();
  39744. }
  39745. else if (textBoxPos == TextBoxLeft)
  39746. {
  39747. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  39748. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  39749. }
  39750. else if (textBoxPos == TextBoxRight)
  39751. {
  39752. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  39753. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  39754. }
  39755. else if (textBoxPos == TextBoxAbove)
  39756. {
  39757. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  39758. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  39759. }
  39760. else if (textBoxPos == TextBoxBelow)
  39761. {
  39762. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  39763. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  39764. }
  39765. }
  39766. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  39767. if (style == LinearBar)
  39768. {
  39769. const int barIndent = 1;
  39770. sliderRegionStart = barIndent;
  39771. sliderRegionSize = getWidth() - barIndent * 2;
  39772. sliderRect.setBounds (sliderRegionStart, barIndent,
  39773. sliderRegionSize, getHeight() - barIndent * 2);
  39774. }
  39775. else if (isHorizontal())
  39776. {
  39777. sliderRegionStart = sliderRect.getX() + indent;
  39778. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  39779. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  39780. sliderRegionSize, sliderRect.getHeight());
  39781. }
  39782. else if (isVertical())
  39783. {
  39784. sliderRegionStart = sliderRect.getY() + indent;
  39785. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  39786. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  39787. sliderRect.getWidth(), sliderRegionSize);
  39788. }
  39789. else
  39790. {
  39791. sliderRegionStart = 0;
  39792. sliderRegionSize = 100;
  39793. }
  39794. if (style == IncDecButtons)
  39795. {
  39796. Rectangle<int> buttonRect (sliderRect);
  39797. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39798. buttonRect.expand (-2, 0);
  39799. else
  39800. buttonRect.expand (0, -2);
  39801. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  39802. if (incDecButtonsSideBySide)
  39803. {
  39804. decButton->setBounds (buttonRect.getX(),
  39805. buttonRect.getY(),
  39806. buttonRect.getWidth() / 2,
  39807. buttonRect.getHeight());
  39808. decButton->setConnectedEdges (Button::ConnectedOnRight);
  39809. incButton->setBounds (buttonRect.getCentreX(),
  39810. buttonRect.getY(),
  39811. buttonRect.getWidth() / 2,
  39812. buttonRect.getHeight());
  39813. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  39814. }
  39815. else
  39816. {
  39817. incButton->setBounds (buttonRect.getX(),
  39818. buttonRect.getY(),
  39819. buttonRect.getWidth(),
  39820. buttonRect.getHeight() / 2);
  39821. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  39822. decButton->setBounds (buttonRect.getX(),
  39823. buttonRect.getCentreY(),
  39824. buttonRect.getWidth(),
  39825. buttonRect.getHeight() / 2);
  39826. decButton->setConnectedEdges (Button::ConnectedOnTop);
  39827. }
  39828. }
  39829. }
  39830. void Slider::focusOfChildComponentChanged (FocusChangeType)
  39831. {
  39832. repaint();
  39833. }
  39834. void Slider::mouseDown (const MouseEvent& e)
  39835. {
  39836. mouseWasHidden = false;
  39837. incDecDragged = false;
  39838. mouseXWhenLastDragged = e.x;
  39839. mouseYWhenLastDragged = e.y;
  39840. mouseDragStartX = e.getMouseDownX();
  39841. mouseDragStartY = e.getMouseDownY();
  39842. if (isEnabled())
  39843. {
  39844. if (e.mods.isPopupMenu() && menuEnabled)
  39845. {
  39846. menuShown = true;
  39847. PopupMenu m;
  39848. m.setLookAndFeel (&getLookAndFeel());
  39849. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  39850. m.addSeparator();
  39851. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39852. {
  39853. PopupMenu rotaryMenu;
  39854. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  39855. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  39856. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  39857. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  39858. }
  39859. const int r = m.show();
  39860. if (r == 1)
  39861. {
  39862. setVelocityBasedMode (! isVelocityBased);
  39863. }
  39864. else if (r == 2)
  39865. {
  39866. setSliderStyle (Rotary);
  39867. }
  39868. else if (r == 3)
  39869. {
  39870. setSliderStyle (RotaryHorizontalDrag);
  39871. }
  39872. else if (r == 4)
  39873. {
  39874. setSliderStyle (RotaryVerticalDrag);
  39875. }
  39876. }
  39877. else if (maximum > minimum)
  39878. {
  39879. menuShown = false;
  39880. if (valueBox != 0)
  39881. valueBox->hideEditor (true);
  39882. sliderBeingDragged = 0;
  39883. if (style == TwoValueHorizontal
  39884. || style == TwoValueVertical
  39885. || style == ThreeValueHorizontal
  39886. || style == ThreeValueVertical)
  39887. {
  39888. const float mousePos = (float) (isVertical() ? e.y : e.x);
  39889. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  39890. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  39891. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  39892. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39893. {
  39894. if (maxPosDistance <= minPosDistance)
  39895. sliderBeingDragged = 2;
  39896. else
  39897. sliderBeingDragged = 1;
  39898. }
  39899. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39900. {
  39901. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  39902. sliderBeingDragged = 1;
  39903. else if (normalPosDistance >= maxPosDistance)
  39904. sliderBeingDragged = 2;
  39905. }
  39906. }
  39907. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39908. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  39909. * valueToProportionOfLength (currentValue.getValue());
  39910. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  39911. : ((sliderBeingDragged == 1) ? valueMin
  39912. : currentValue)).getValue();
  39913. valueOnMouseDown = valueWhenLastDragged;
  39914. if (popupDisplayEnabled)
  39915. {
  39916. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  39917. popupDisplay = popup;
  39918. if (parentForPopupDisplay != 0)
  39919. {
  39920. parentForPopupDisplay->addChildComponent (popup);
  39921. }
  39922. else
  39923. {
  39924. popup->addToDesktop (0);
  39925. }
  39926. popup->setVisible (true);
  39927. }
  39928. sendDragStart();
  39929. mouseDrag (e);
  39930. }
  39931. }
  39932. }
  39933. void Slider::mouseUp (const MouseEvent&)
  39934. {
  39935. if (isEnabled()
  39936. && (! menuShown)
  39937. && (maximum > minimum)
  39938. && (style != IncDecButtons || incDecDragged))
  39939. {
  39940. restoreMouseIfHidden();
  39941. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  39942. triggerChangeMessage (false);
  39943. sendDragEnd();
  39944. popupDisplay = 0;
  39945. if (style == IncDecButtons)
  39946. {
  39947. incButton->setState (Button::buttonNormal);
  39948. decButton->setState (Button::buttonNormal);
  39949. }
  39950. }
  39951. }
  39952. void Slider::restoreMouseIfHidden()
  39953. {
  39954. if (mouseWasHidden)
  39955. {
  39956. mouseWasHidden = false;
  39957. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  39958. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  39959. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  39960. : ((sliderBeingDragged == 1) ? getMinValue()
  39961. : (double) currentValue.getValue());
  39962. Point<int> mousePos;
  39963. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39964. {
  39965. mousePos = Desktop::getLastMouseDownPosition();
  39966. if (style == RotaryHorizontalDrag)
  39967. {
  39968. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  39969. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  39970. }
  39971. else
  39972. {
  39973. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  39974. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  39975. }
  39976. }
  39977. else
  39978. {
  39979. const int pixelPos = (int) getLinearSliderPos (pos);
  39980. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  39981. isVertical() ? pixelPos : (getHeight() / 2)));
  39982. }
  39983. Desktop::setMousePosition (mousePos);
  39984. }
  39985. }
  39986. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  39987. {
  39988. if (isEnabled()
  39989. && style != IncDecButtons
  39990. && style != Rotary
  39991. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  39992. {
  39993. restoreMouseIfHidden();
  39994. }
  39995. }
  39996. static double smallestAngleBetween (double a1, double a2)
  39997. {
  39998. return jmin (std::abs (a1 - a2),
  39999. std::abs (a1 + double_Pi * 2.0 - a2),
  40000. std::abs (a2 + double_Pi * 2.0 - a1));
  40001. }
  40002. void Slider::mouseDrag (const MouseEvent& e)
  40003. {
  40004. if (isEnabled()
  40005. && (! menuShown)
  40006. && (maximum > minimum))
  40007. {
  40008. if (style == Rotary)
  40009. {
  40010. int dx = e.x - sliderRect.getCentreX();
  40011. int dy = e.y - sliderRect.getCentreY();
  40012. if (dx * dx + dy * dy > 25)
  40013. {
  40014. double angle = std::atan2 ((double) dx, (double) -dy);
  40015. while (angle < 0.0)
  40016. angle += double_Pi * 2.0;
  40017. if (rotaryStop && ! e.mouseWasClicked())
  40018. {
  40019. if (std::abs (angle - lastAngle) > double_Pi)
  40020. {
  40021. if (angle >= lastAngle)
  40022. angle -= double_Pi * 2.0;
  40023. else
  40024. angle += double_Pi * 2.0;
  40025. }
  40026. if (angle >= lastAngle)
  40027. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40028. else
  40029. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40030. }
  40031. else
  40032. {
  40033. while (angle < rotaryStart)
  40034. angle += double_Pi * 2.0;
  40035. if (angle > rotaryEnd)
  40036. {
  40037. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  40038. angle = rotaryStart;
  40039. else
  40040. angle = rotaryEnd;
  40041. }
  40042. }
  40043. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40044. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40045. lastAngle = angle;
  40046. }
  40047. }
  40048. else
  40049. {
  40050. if (style == LinearBar && e.mouseWasClicked()
  40051. && valueBox != 0 && valueBox->isEditable())
  40052. return;
  40053. if (style == IncDecButtons && ! incDecDragged)
  40054. {
  40055. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40056. return;
  40057. incDecDragged = true;
  40058. mouseDragStartX = e.x;
  40059. mouseDragStartY = e.y;
  40060. }
  40061. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40062. : false))
  40063. || ((maximum - minimum) / sliderRegionSize < interval))
  40064. {
  40065. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40066. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40067. if (style == RotaryHorizontalDrag
  40068. || style == RotaryVerticalDrag
  40069. || style == IncDecButtons
  40070. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40071. && ! snapsToMousePos))
  40072. {
  40073. const int mouseDiff = (style == RotaryHorizontalDrag
  40074. || style == LinearHorizontal
  40075. || style == LinearBar
  40076. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40077. ? e.x - mouseDragStartX
  40078. : mouseDragStartY - e.y;
  40079. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40080. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40081. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40082. if (style == IncDecButtons)
  40083. {
  40084. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40085. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40086. }
  40087. }
  40088. else
  40089. {
  40090. if (isVertical())
  40091. scaledMousePos = 1.0 - scaledMousePos;
  40092. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40093. }
  40094. }
  40095. else
  40096. {
  40097. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40098. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40099. ? e.x - mouseXWhenLastDragged
  40100. : e.y - mouseYWhenLastDragged;
  40101. const double maxSpeed = jmax (200, sliderRegionSize);
  40102. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40103. if (speed != 0)
  40104. {
  40105. speed = 0.2 * velocityModeSensitivity
  40106. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40107. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40108. / maxSpeed))));
  40109. if (mouseDiff < 0)
  40110. speed = -speed;
  40111. if (isVertical() || style == RotaryVerticalDrag
  40112. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40113. speed = -speed;
  40114. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40115. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40116. e.source.enableUnboundedMouseMovement (true, false);
  40117. mouseWasHidden = true;
  40118. }
  40119. }
  40120. }
  40121. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40122. if (sliderBeingDragged == 0)
  40123. {
  40124. setValue (snapValue (valueWhenLastDragged, true),
  40125. ! sendChangeOnlyOnRelease, true);
  40126. }
  40127. else if (sliderBeingDragged == 1)
  40128. {
  40129. setMinValue (snapValue (valueWhenLastDragged, true),
  40130. ! sendChangeOnlyOnRelease, false, true);
  40131. if (e.mods.isShiftDown())
  40132. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40133. else
  40134. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40135. }
  40136. else
  40137. {
  40138. jassert (sliderBeingDragged == 2);
  40139. setMaxValue (snapValue (valueWhenLastDragged, true),
  40140. ! sendChangeOnlyOnRelease, false, true);
  40141. if (e.mods.isShiftDown())
  40142. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40143. else
  40144. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40145. }
  40146. mouseXWhenLastDragged = e.x;
  40147. mouseYWhenLastDragged = e.y;
  40148. }
  40149. }
  40150. void Slider::mouseDoubleClick (const MouseEvent&)
  40151. {
  40152. if (doubleClickToValue
  40153. && isEnabled()
  40154. && style != IncDecButtons
  40155. && minimum <= doubleClickReturnValue
  40156. && maximum >= doubleClickReturnValue)
  40157. {
  40158. sendDragStart();
  40159. setValue (doubleClickReturnValue, true, true);
  40160. sendDragEnd();
  40161. }
  40162. }
  40163. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40164. {
  40165. if (scrollWheelEnabled && isEnabled()
  40166. && style != TwoValueHorizontal
  40167. && style != TwoValueVertical)
  40168. {
  40169. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40170. {
  40171. if (valueBox != 0)
  40172. valueBox->hideEditor (false);
  40173. const double value = (double) currentValue.getValue();
  40174. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40175. const double currentPos = valueToProportionOfLength (value);
  40176. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40177. double delta = (newValue != value)
  40178. ? jmax (std::abs (newValue - value), interval) : 0;
  40179. if (value > newValue)
  40180. delta = -delta;
  40181. sendDragStart();
  40182. setValue (snapValue (value + delta, false), true, true);
  40183. sendDragEnd();
  40184. }
  40185. }
  40186. else
  40187. {
  40188. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40189. }
  40190. }
  40191. void Slider::Listener::sliderDragStarted (Slider*)
  40192. {
  40193. }
  40194. void Slider::Listener::sliderDragEnded (Slider*)
  40195. {
  40196. }
  40197. END_JUCE_NAMESPACE
  40198. /*** End of inlined file: juce_Slider.cpp ***/
  40199. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40200. BEGIN_JUCE_NAMESPACE
  40201. class DragOverlayComp : public Component
  40202. {
  40203. public:
  40204. DragOverlayComp (const Image& image_)
  40205. : image (image_)
  40206. {
  40207. image.duplicateIfShared();
  40208. image.multiplyAllAlphas (0.8f);
  40209. setAlwaysOnTop (true);
  40210. }
  40211. ~DragOverlayComp()
  40212. {
  40213. }
  40214. void paint (Graphics& g)
  40215. {
  40216. g.drawImageAt (image, 0, 0);
  40217. }
  40218. private:
  40219. Image image;
  40220. DragOverlayComp (const DragOverlayComp&);
  40221. DragOverlayComp& operator= (const DragOverlayComp&);
  40222. };
  40223. TableHeaderComponent::TableHeaderComponent()
  40224. : columnsChanged (false),
  40225. columnsResized (false),
  40226. sortChanged (false),
  40227. menuActive (true),
  40228. stretchToFit (false),
  40229. columnIdBeingResized (0),
  40230. columnIdBeingDragged (0),
  40231. columnIdUnderMouse (0),
  40232. lastDeliberateWidth (0)
  40233. {
  40234. }
  40235. TableHeaderComponent::~TableHeaderComponent()
  40236. {
  40237. dragOverlayComp = 0;
  40238. }
  40239. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40240. {
  40241. menuActive = hasMenu;
  40242. }
  40243. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40244. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40245. {
  40246. if (onlyCountVisibleColumns)
  40247. {
  40248. int num = 0;
  40249. for (int i = columns.size(); --i >= 0;)
  40250. if (columns.getUnchecked(i)->isVisible())
  40251. ++num;
  40252. return num;
  40253. }
  40254. else
  40255. {
  40256. return columns.size();
  40257. }
  40258. }
  40259. const String TableHeaderComponent::getColumnName (const int columnId) const
  40260. {
  40261. const ColumnInfo* const ci = getInfoForId (columnId);
  40262. return ci != 0 ? ci->name : String::empty;
  40263. }
  40264. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40265. {
  40266. ColumnInfo* const ci = getInfoForId (columnId);
  40267. if (ci != 0 && ci->name != newName)
  40268. {
  40269. ci->name = newName;
  40270. sendColumnsChanged();
  40271. }
  40272. }
  40273. void TableHeaderComponent::addColumn (const String& columnName,
  40274. const int columnId,
  40275. const int width,
  40276. const int minimumWidth,
  40277. const int maximumWidth,
  40278. const int propertyFlags,
  40279. const int insertIndex)
  40280. {
  40281. // can't have a duplicate or null ID!
  40282. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40283. jassert (width > 0);
  40284. ColumnInfo* const ci = new ColumnInfo();
  40285. ci->name = columnName;
  40286. ci->id = columnId;
  40287. ci->width = width;
  40288. ci->lastDeliberateWidth = width;
  40289. ci->minimumWidth = minimumWidth;
  40290. ci->maximumWidth = maximumWidth;
  40291. if (ci->maximumWidth < 0)
  40292. ci->maximumWidth = std::numeric_limits<int>::max();
  40293. jassert (ci->maximumWidth >= ci->minimumWidth);
  40294. ci->propertyFlags = propertyFlags;
  40295. columns.insert (insertIndex, ci);
  40296. sendColumnsChanged();
  40297. }
  40298. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40299. {
  40300. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40301. if (index >= 0)
  40302. {
  40303. columns.remove (index);
  40304. sortChanged = true;
  40305. sendColumnsChanged();
  40306. }
  40307. }
  40308. void TableHeaderComponent::removeAllColumns()
  40309. {
  40310. if (columns.size() > 0)
  40311. {
  40312. columns.clear();
  40313. sendColumnsChanged();
  40314. }
  40315. }
  40316. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40317. {
  40318. const int currentIndex = getIndexOfColumnId (columnId, false);
  40319. newIndex = visibleIndexToTotalIndex (newIndex);
  40320. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40321. {
  40322. columns.move (currentIndex, newIndex);
  40323. sendColumnsChanged();
  40324. }
  40325. }
  40326. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40327. {
  40328. const ColumnInfo* const ci = getInfoForId (columnId);
  40329. return ci != 0 ? ci->width : 0;
  40330. }
  40331. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40332. {
  40333. ColumnInfo* const ci = getInfoForId (columnId);
  40334. if (ci != 0 && ci->width != newWidth)
  40335. {
  40336. const int numColumns = getNumColumns (true);
  40337. ci->lastDeliberateWidth = ci->width
  40338. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40339. if (stretchToFit)
  40340. {
  40341. const int index = getIndexOfColumnId (columnId, true) + 1;
  40342. if (((unsigned int) index) < (unsigned int) numColumns)
  40343. {
  40344. const int x = getColumnPosition (index).getX();
  40345. if (lastDeliberateWidth == 0)
  40346. lastDeliberateWidth = getTotalWidth();
  40347. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40348. }
  40349. }
  40350. repaint();
  40351. columnsResized = true;
  40352. triggerAsyncUpdate();
  40353. }
  40354. }
  40355. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  40356. {
  40357. int n = 0;
  40358. for (int i = 0; i < columns.size(); ++i)
  40359. {
  40360. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  40361. {
  40362. if (columns.getUnchecked(i)->id == columnId)
  40363. return n;
  40364. ++n;
  40365. }
  40366. }
  40367. return -1;
  40368. }
  40369. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  40370. {
  40371. if (onlyCountVisibleColumns)
  40372. index = visibleIndexToTotalIndex (index);
  40373. const ColumnInfo* const ci = columns [index];
  40374. return (ci != 0) ? ci->id : 0;
  40375. }
  40376. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  40377. {
  40378. int x = 0, width = 0, n = 0;
  40379. for (int i = 0; i < columns.size(); ++i)
  40380. {
  40381. x += width;
  40382. if (columns.getUnchecked(i)->isVisible())
  40383. {
  40384. width = columns.getUnchecked(i)->width;
  40385. if (n++ == index)
  40386. break;
  40387. }
  40388. else
  40389. {
  40390. width = 0;
  40391. }
  40392. }
  40393. return Rectangle<int> (x, 0, width, getHeight());
  40394. }
  40395. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  40396. {
  40397. if (xToFind >= 0)
  40398. {
  40399. int x = 0;
  40400. for (int i = 0; i < columns.size(); ++i)
  40401. {
  40402. const ColumnInfo* const ci = columns.getUnchecked(i);
  40403. if (ci->isVisible())
  40404. {
  40405. x += ci->width;
  40406. if (xToFind < x)
  40407. return ci->id;
  40408. }
  40409. }
  40410. }
  40411. return 0;
  40412. }
  40413. int TableHeaderComponent::getTotalWidth() const
  40414. {
  40415. int w = 0;
  40416. for (int i = columns.size(); --i >= 0;)
  40417. if (columns.getUnchecked(i)->isVisible())
  40418. w += columns.getUnchecked(i)->width;
  40419. return w;
  40420. }
  40421. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  40422. {
  40423. stretchToFit = shouldStretchToFit;
  40424. lastDeliberateWidth = getTotalWidth();
  40425. resized();
  40426. }
  40427. bool TableHeaderComponent::isStretchToFitActive() const
  40428. {
  40429. return stretchToFit;
  40430. }
  40431. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  40432. {
  40433. if (stretchToFit && getWidth() > 0
  40434. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  40435. {
  40436. lastDeliberateWidth = targetTotalWidth;
  40437. resizeColumnsToFit (0, targetTotalWidth);
  40438. }
  40439. }
  40440. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  40441. {
  40442. targetTotalWidth = jmax (targetTotalWidth, 0);
  40443. StretchableObjectResizer sor;
  40444. int i;
  40445. for (i = firstColumnIndex; i < columns.size(); ++i)
  40446. {
  40447. ColumnInfo* const ci = columns.getUnchecked(i);
  40448. if (ci->isVisible())
  40449. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  40450. }
  40451. sor.resizeToFit (targetTotalWidth);
  40452. int visIndex = 0;
  40453. for (i = firstColumnIndex; i < columns.size(); ++i)
  40454. {
  40455. ColumnInfo* const ci = columns.getUnchecked(i);
  40456. if (ci->isVisible())
  40457. {
  40458. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  40459. (int) std::floor (sor.getItemSize (visIndex++)));
  40460. if (newWidth != ci->width)
  40461. {
  40462. ci->width = newWidth;
  40463. repaint();
  40464. columnsResized = true;
  40465. triggerAsyncUpdate();
  40466. }
  40467. }
  40468. }
  40469. }
  40470. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  40471. {
  40472. ColumnInfo* const ci = getInfoForId (columnId);
  40473. if (ci != 0 && shouldBeVisible != ci->isVisible())
  40474. {
  40475. if (shouldBeVisible)
  40476. ci->propertyFlags |= visible;
  40477. else
  40478. ci->propertyFlags &= ~visible;
  40479. sendColumnsChanged();
  40480. resized();
  40481. }
  40482. }
  40483. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  40484. {
  40485. const ColumnInfo* const ci = getInfoForId (columnId);
  40486. return ci != 0 && ci->isVisible();
  40487. }
  40488. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  40489. {
  40490. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  40491. {
  40492. for (int i = columns.size(); --i >= 0;)
  40493. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  40494. ColumnInfo* const ci = getInfoForId (columnId);
  40495. if (ci != 0)
  40496. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  40497. reSortTable();
  40498. }
  40499. }
  40500. int TableHeaderComponent::getSortColumnId() const
  40501. {
  40502. for (int i = columns.size(); --i >= 0;)
  40503. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40504. return columns.getUnchecked(i)->id;
  40505. return 0;
  40506. }
  40507. bool TableHeaderComponent::isSortedForwards() const
  40508. {
  40509. for (int i = columns.size(); --i >= 0;)
  40510. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40511. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  40512. return true;
  40513. }
  40514. void TableHeaderComponent::reSortTable()
  40515. {
  40516. sortChanged = true;
  40517. repaint();
  40518. triggerAsyncUpdate();
  40519. }
  40520. const String TableHeaderComponent::toString() const
  40521. {
  40522. String s;
  40523. XmlElement doc ("TABLELAYOUT");
  40524. doc.setAttribute ("sortedCol", getSortColumnId());
  40525. doc.setAttribute ("sortForwards", isSortedForwards());
  40526. for (int i = 0; i < columns.size(); ++i)
  40527. {
  40528. const ColumnInfo* const ci = columns.getUnchecked (i);
  40529. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  40530. e->setAttribute ("id", ci->id);
  40531. e->setAttribute ("visible", ci->isVisible());
  40532. e->setAttribute ("width", ci->width);
  40533. }
  40534. return doc.createDocument (String::empty, true, false);
  40535. }
  40536. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  40537. {
  40538. XmlDocument doc (storedVersion);
  40539. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  40540. int index = 0;
  40541. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  40542. {
  40543. forEachXmlChildElement (*storedXml, col)
  40544. {
  40545. const int tabId = col->getIntAttribute ("id");
  40546. ColumnInfo* const ci = getInfoForId (tabId);
  40547. if (ci != 0)
  40548. {
  40549. columns.move (columns.indexOf (ci), index);
  40550. ci->width = col->getIntAttribute ("width");
  40551. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  40552. }
  40553. ++index;
  40554. }
  40555. columnsResized = true;
  40556. sendColumnsChanged();
  40557. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  40558. storedXml->getBoolAttribute ("sortForwards", true));
  40559. }
  40560. }
  40561. void TableHeaderComponent::addListener (Listener* const newListener)
  40562. {
  40563. listeners.addIfNotAlreadyThere (newListener);
  40564. }
  40565. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  40566. {
  40567. listeners.removeValue (listenerToRemove);
  40568. }
  40569. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  40570. {
  40571. const ColumnInfo* const ci = getInfoForId (columnId);
  40572. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  40573. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  40574. }
  40575. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  40576. {
  40577. for (int i = 0; i < columns.size(); ++i)
  40578. {
  40579. const ColumnInfo* const ci = columns.getUnchecked(i);
  40580. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  40581. menu.addItem (ci->id, ci->name,
  40582. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  40583. isColumnVisible (ci->id));
  40584. }
  40585. }
  40586. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  40587. {
  40588. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  40589. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  40590. }
  40591. void TableHeaderComponent::paint (Graphics& g)
  40592. {
  40593. LookAndFeel& lf = getLookAndFeel();
  40594. lf.drawTableHeaderBackground (g, *this);
  40595. const Rectangle<int> clip (g.getClipBounds());
  40596. int x = 0;
  40597. for (int i = 0; i < columns.size(); ++i)
  40598. {
  40599. const ColumnInfo* const ci = columns.getUnchecked(i);
  40600. if (ci->isVisible())
  40601. {
  40602. if (x + ci->width > clip.getX()
  40603. && (ci->id != columnIdBeingDragged
  40604. || dragOverlayComp == 0
  40605. || ! dragOverlayComp->isVisible()))
  40606. {
  40607. g.saveState();
  40608. g.setOrigin (x, 0);
  40609. g.reduceClipRegion (0, 0, ci->width, getHeight());
  40610. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  40611. ci->id == columnIdUnderMouse,
  40612. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  40613. ci->propertyFlags);
  40614. g.restoreState();
  40615. }
  40616. x += ci->width;
  40617. if (x >= clip.getRight())
  40618. break;
  40619. }
  40620. }
  40621. }
  40622. void TableHeaderComponent::resized()
  40623. {
  40624. }
  40625. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  40626. {
  40627. updateColumnUnderMouse (e.x, e.y);
  40628. }
  40629. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  40630. {
  40631. updateColumnUnderMouse (e.x, e.y);
  40632. }
  40633. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  40634. {
  40635. updateColumnUnderMouse (e.x, e.y);
  40636. }
  40637. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  40638. {
  40639. repaint();
  40640. columnIdBeingResized = 0;
  40641. columnIdBeingDragged = 0;
  40642. if (columnIdUnderMouse != 0)
  40643. {
  40644. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  40645. if (e.mods.isPopupMenu())
  40646. columnClicked (columnIdUnderMouse, e.mods);
  40647. }
  40648. if (menuActive && e.mods.isPopupMenu())
  40649. showColumnChooserMenu (columnIdUnderMouse);
  40650. }
  40651. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  40652. {
  40653. if (columnIdBeingResized == 0
  40654. && columnIdBeingDragged == 0
  40655. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  40656. {
  40657. dragOverlayComp = 0;
  40658. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  40659. if (columnIdBeingResized != 0)
  40660. {
  40661. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40662. initialColumnWidth = ci->width;
  40663. }
  40664. else
  40665. {
  40666. beginDrag (e);
  40667. }
  40668. }
  40669. if (columnIdBeingResized != 0)
  40670. {
  40671. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40672. if (ci != 0)
  40673. {
  40674. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  40675. initialColumnWidth + e.getDistanceFromDragStartX());
  40676. if (stretchToFit)
  40677. {
  40678. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  40679. int minWidthOnRight = 0;
  40680. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  40681. if (columns.getUnchecked (i)->isVisible())
  40682. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  40683. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  40684. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  40685. }
  40686. setColumnWidth (columnIdBeingResized, w);
  40687. }
  40688. }
  40689. else if (columnIdBeingDragged != 0)
  40690. {
  40691. if (e.y >= -50 && e.y < getHeight() + 50)
  40692. {
  40693. if (dragOverlayComp != 0)
  40694. {
  40695. dragOverlayComp->setVisible (true);
  40696. dragOverlayComp->setBounds (jlimit (0,
  40697. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  40698. e.x - draggingColumnOffset),
  40699. 0,
  40700. dragOverlayComp->getWidth(),
  40701. getHeight());
  40702. for (int i = columns.size(); --i >= 0;)
  40703. {
  40704. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40705. int newIndex = currentIndex;
  40706. if (newIndex > 0)
  40707. {
  40708. // if the previous column isn't draggable, we can't move our column
  40709. // past it, because that'd change the undraggable column's position..
  40710. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  40711. if ((previous->propertyFlags & draggable) != 0)
  40712. {
  40713. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  40714. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  40715. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  40716. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  40717. {
  40718. --newIndex;
  40719. }
  40720. }
  40721. }
  40722. if (newIndex < columns.size() - 1)
  40723. {
  40724. // if the next column isn't draggable, we can't move our column
  40725. // past it, because that'd change the undraggable column's position..
  40726. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  40727. if ((nextCol->propertyFlags & draggable) != 0)
  40728. {
  40729. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  40730. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  40731. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  40732. > abs (dragOverlayComp->getRight() - rightOfNext))
  40733. {
  40734. ++newIndex;
  40735. }
  40736. }
  40737. }
  40738. if (newIndex != currentIndex)
  40739. moveColumn (columnIdBeingDragged, newIndex);
  40740. else
  40741. break;
  40742. }
  40743. }
  40744. }
  40745. else
  40746. {
  40747. endDrag (draggingColumnOriginalIndex);
  40748. }
  40749. }
  40750. }
  40751. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  40752. {
  40753. if (columnIdBeingDragged == 0)
  40754. {
  40755. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  40756. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  40757. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  40758. {
  40759. columnIdBeingDragged = 0;
  40760. }
  40761. else
  40762. {
  40763. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40764. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  40765. const int temp = columnIdBeingDragged;
  40766. columnIdBeingDragged = 0;
  40767. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  40768. columnIdBeingDragged = temp;
  40769. dragOverlayComp->setBounds (columnRect);
  40770. for (int i = listeners.size(); --i >= 0;)
  40771. {
  40772. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  40773. i = jmin (i, listeners.size() - 1);
  40774. }
  40775. }
  40776. }
  40777. }
  40778. void TableHeaderComponent::endDrag (const int finalIndex)
  40779. {
  40780. if (columnIdBeingDragged != 0)
  40781. {
  40782. moveColumn (columnIdBeingDragged, finalIndex);
  40783. columnIdBeingDragged = 0;
  40784. repaint();
  40785. for (int i = listeners.size(); --i >= 0;)
  40786. {
  40787. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  40788. i = jmin (i, listeners.size() - 1);
  40789. }
  40790. }
  40791. }
  40792. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  40793. {
  40794. mouseDrag (e);
  40795. for (int i = columns.size(); --i >= 0;)
  40796. if (columns.getUnchecked (i)->isVisible())
  40797. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  40798. columnIdBeingResized = 0;
  40799. repaint();
  40800. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  40801. updateColumnUnderMouse (e.x, e.y);
  40802. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  40803. columnClicked (columnIdUnderMouse, e.mods);
  40804. dragOverlayComp = 0;
  40805. }
  40806. const MouseCursor TableHeaderComponent::getMouseCursor()
  40807. {
  40808. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  40809. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  40810. return Component::getMouseCursor();
  40811. }
  40812. bool TableHeaderComponent::ColumnInfo::isVisible() const
  40813. {
  40814. return (propertyFlags & TableHeaderComponent::visible) != 0;
  40815. }
  40816. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  40817. {
  40818. for (int i = columns.size(); --i >= 0;)
  40819. if (columns.getUnchecked(i)->id == id)
  40820. return columns.getUnchecked(i);
  40821. return 0;
  40822. }
  40823. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  40824. {
  40825. int n = 0;
  40826. for (int i = 0; i < columns.size(); ++i)
  40827. {
  40828. if (columns.getUnchecked(i)->isVisible())
  40829. {
  40830. if (n == visibleIndex)
  40831. return i;
  40832. ++n;
  40833. }
  40834. }
  40835. return -1;
  40836. }
  40837. void TableHeaderComponent::sendColumnsChanged()
  40838. {
  40839. if (stretchToFit && lastDeliberateWidth > 0)
  40840. resizeAllColumnsToFit (lastDeliberateWidth);
  40841. repaint();
  40842. columnsChanged = true;
  40843. triggerAsyncUpdate();
  40844. }
  40845. void TableHeaderComponent::handleAsyncUpdate()
  40846. {
  40847. const bool changed = columnsChanged || sortChanged;
  40848. const bool sized = columnsResized || changed;
  40849. const bool sorted = sortChanged;
  40850. columnsChanged = false;
  40851. columnsResized = false;
  40852. sortChanged = false;
  40853. if (sorted)
  40854. {
  40855. for (int i = listeners.size(); --i >= 0;)
  40856. {
  40857. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  40858. i = jmin (i, listeners.size() - 1);
  40859. }
  40860. }
  40861. if (changed)
  40862. {
  40863. for (int i = listeners.size(); --i >= 0;)
  40864. {
  40865. listeners.getUnchecked(i)->tableColumnsChanged (this);
  40866. i = jmin (i, listeners.size() - 1);
  40867. }
  40868. }
  40869. if (sized)
  40870. {
  40871. for (int i = listeners.size(); --i >= 0;)
  40872. {
  40873. listeners.getUnchecked(i)->tableColumnsResized (this);
  40874. i = jmin (i, listeners.size() - 1);
  40875. }
  40876. }
  40877. }
  40878. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  40879. {
  40880. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  40881. {
  40882. const int draggableDistance = 3;
  40883. int x = 0;
  40884. for (int i = 0; i < columns.size(); ++i)
  40885. {
  40886. const ColumnInfo* const ci = columns.getUnchecked(i);
  40887. if (ci->isVisible())
  40888. {
  40889. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  40890. && (ci->propertyFlags & resizable) != 0)
  40891. return ci->id;
  40892. x += ci->width;
  40893. }
  40894. }
  40895. }
  40896. return 0;
  40897. }
  40898. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  40899. {
  40900. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  40901. ? getColumnIdAtX (x) : 0;
  40902. if (newCol != columnIdUnderMouse)
  40903. {
  40904. columnIdUnderMouse = newCol;
  40905. repaint();
  40906. }
  40907. }
  40908. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  40909. {
  40910. PopupMenu m;
  40911. addMenuItems (m, columnIdClicked);
  40912. if (m.getNumItems() > 0)
  40913. {
  40914. m.setLookAndFeel (&getLookAndFeel());
  40915. const int result = m.show();
  40916. if (result != 0)
  40917. reactToMenuItem (result, columnIdClicked);
  40918. }
  40919. }
  40920. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  40921. {
  40922. }
  40923. END_JUCE_NAMESPACE
  40924. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  40925. /*** Start of inlined file: juce_TableListBox.cpp ***/
  40926. BEGIN_JUCE_NAMESPACE
  40927. static const char* const tableColumnPropertyTag = "_tableColumnID";
  40928. class TableListRowComp : public Component,
  40929. public TooltipClient
  40930. {
  40931. public:
  40932. TableListRowComp (TableListBox& owner_)
  40933. : owner (owner_),
  40934. row (-1),
  40935. isSelected (false)
  40936. {
  40937. }
  40938. ~TableListRowComp()
  40939. {
  40940. deleteAllChildren();
  40941. }
  40942. void paint (Graphics& g)
  40943. {
  40944. TableListBoxModel* const model = owner.getModel();
  40945. if (model != 0)
  40946. {
  40947. const TableHeaderComponent* const header = owner.getHeader();
  40948. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  40949. const int numColumns = header->getNumColumns (true);
  40950. for (int i = 0; i < numColumns; ++i)
  40951. {
  40952. if (! columnsWithComponents [i])
  40953. {
  40954. const int columnId = header->getColumnIdOfIndex (i, true);
  40955. Rectangle<int> columnRect (header->getColumnPosition (i));
  40956. columnRect.setSize (columnRect.getWidth(), getHeight());
  40957. g.saveState();
  40958. g.reduceClipRegion (columnRect);
  40959. g.setOrigin (columnRect.getX(), 0);
  40960. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  40961. g.restoreState();
  40962. }
  40963. }
  40964. }
  40965. }
  40966. void update (const int newRow, const bool isNowSelected)
  40967. {
  40968. if (newRow != row || isNowSelected != isSelected)
  40969. {
  40970. row = newRow;
  40971. isSelected = isNowSelected;
  40972. repaint();
  40973. }
  40974. if (row < owner.getNumRows())
  40975. {
  40976. jassert (row >= 0);
  40977. const Identifier tagPropertyName ("_tableLastUseNum");
  40978. const int newTag = Random::getSystemRandom().nextInt();
  40979. const TableHeaderComponent* const header = owner.getHeader();
  40980. const int numColumns = header->getNumColumns (true);
  40981. int i;
  40982. columnsWithComponents.clear();
  40983. if (owner.getModel() != 0)
  40984. {
  40985. for (i = 0; i < numColumns; ++i)
  40986. {
  40987. const int columnId = header->getColumnIdOfIndex (i, true);
  40988. Component* const newComp
  40989. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  40990. findChildComponentForColumn (columnId));
  40991. if (newComp != 0)
  40992. {
  40993. addAndMakeVisible (newComp);
  40994. newComp->getProperties().set (tagPropertyName, newTag);
  40995. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  40996. const Rectangle<int> columnRect (header->getColumnPosition (i));
  40997. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  40998. columnsWithComponents.setBit (i);
  40999. }
  41000. }
  41001. }
  41002. for (i = getNumChildComponents(); --i >= 0;)
  41003. {
  41004. Component* const c = getChildComponent (i);
  41005. if ((int) c->getProperties() [tagPropertyName] != newTag)
  41006. delete c;
  41007. }
  41008. }
  41009. else
  41010. {
  41011. columnsWithComponents.clear();
  41012. deleteAllChildren();
  41013. }
  41014. }
  41015. void resized()
  41016. {
  41017. for (int i = getNumChildComponents(); --i >= 0;)
  41018. {
  41019. Component* const c = getChildComponent (i);
  41020. const int columnId = c->getProperties() [tableColumnPropertyTag];
  41021. if (columnId != 0)
  41022. {
  41023. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  41024. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41025. }
  41026. }
  41027. }
  41028. void mouseDown (const MouseEvent& e)
  41029. {
  41030. isDragging = false;
  41031. selectRowOnMouseUp = false;
  41032. if (isEnabled())
  41033. {
  41034. if (! isSelected)
  41035. {
  41036. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41037. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41038. if (columnId != 0 && owner.getModel() != 0)
  41039. owner.getModel()->cellClicked (row, columnId, e);
  41040. }
  41041. else
  41042. {
  41043. selectRowOnMouseUp = true;
  41044. }
  41045. }
  41046. }
  41047. void mouseDrag (const MouseEvent& e)
  41048. {
  41049. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41050. {
  41051. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41052. if (selectedRows.size() > 0)
  41053. {
  41054. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41055. if (dragDescription.isNotEmpty())
  41056. {
  41057. isDragging = true;
  41058. owner.startDragAndDrop (e, dragDescription);
  41059. }
  41060. }
  41061. }
  41062. }
  41063. void mouseUp (const MouseEvent& e)
  41064. {
  41065. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41066. {
  41067. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41068. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41069. if (columnId != 0 && owner.getModel() != 0)
  41070. owner.getModel()->cellClicked (row, columnId, e);
  41071. }
  41072. }
  41073. void mouseDoubleClick (const MouseEvent& e)
  41074. {
  41075. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41076. if (columnId != 0 && owner.getModel() != 0)
  41077. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41078. }
  41079. const String getTooltip()
  41080. {
  41081. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  41082. if (columnId != 0 && owner.getModel() != 0)
  41083. return owner.getModel()->getCellTooltip (row, columnId);
  41084. return String::empty;
  41085. }
  41086. Component* findChildComponentForColumn (const int columnId) const
  41087. {
  41088. for (int i = getNumChildComponents(); --i >= 0;)
  41089. {
  41090. Component* const c = getChildComponent (i);
  41091. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  41092. return c;
  41093. }
  41094. return 0;
  41095. }
  41096. juce_UseDebuggingNewOperator
  41097. private:
  41098. TableListBox& owner;
  41099. int row;
  41100. bool isSelected, isDragging, selectRowOnMouseUp;
  41101. BigInteger columnsWithComponents;
  41102. TableListRowComp (const TableListRowComp&);
  41103. TableListRowComp& operator= (const TableListRowComp&);
  41104. };
  41105. class TableListBoxHeader : public TableHeaderComponent
  41106. {
  41107. public:
  41108. TableListBoxHeader (TableListBox& owner_)
  41109. : owner (owner_)
  41110. {
  41111. }
  41112. ~TableListBoxHeader()
  41113. {
  41114. }
  41115. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41116. {
  41117. if (owner.isAutoSizeMenuOptionShown())
  41118. {
  41119. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  41120. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  41121. menu.addSeparator();
  41122. }
  41123. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41124. }
  41125. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41126. {
  41127. if (menuReturnId == 0xf836743)
  41128. {
  41129. owner.autoSizeColumn (columnIdClicked);
  41130. }
  41131. else if (menuReturnId == 0xf836744)
  41132. {
  41133. owner.autoSizeAllColumns();
  41134. }
  41135. else
  41136. {
  41137. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  41138. }
  41139. }
  41140. juce_UseDebuggingNewOperator
  41141. private:
  41142. TableListBox& owner;
  41143. TableListBoxHeader (const TableListBoxHeader&);
  41144. TableListBoxHeader& operator= (const TableListBoxHeader&);
  41145. };
  41146. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41147. : ListBox (name, 0),
  41148. model (model_),
  41149. autoSizeOptionsShown (true)
  41150. {
  41151. ListBox::model = this;
  41152. header = new TableListBoxHeader (*this);
  41153. header->setSize (100, 28);
  41154. header->addListener (this);
  41155. setHeaderComponent (header);
  41156. }
  41157. TableListBox::~TableListBox()
  41158. {
  41159. header = 0;
  41160. }
  41161. void TableListBox::setModel (TableListBoxModel* const newModel)
  41162. {
  41163. if (model != newModel)
  41164. {
  41165. model = newModel;
  41166. updateContent();
  41167. }
  41168. }
  41169. int TableListBox::getHeaderHeight() const
  41170. {
  41171. return header->getHeight();
  41172. }
  41173. void TableListBox::setHeaderHeight (const int newHeight)
  41174. {
  41175. header->setSize (header->getWidth(), newHeight);
  41176. resized();
  41177. }
  41178. void TableListBox::autoSizeColumn (const int columnId)
  41179. {
  41180. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41181. if (width > 0)
  41182. header->setColumnWidth (columnId, width);
  41183. }
  41184. void TableListBox::autoSizeAllColumns()
  41185. {
  41186. for (int i = 0; i < header->getNumColumns (true); ++i)
  41187. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41188. }
  41189. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41190. {
  41191. autoSizeOptionsShown = shouldBeShown;
  41192. }
  41193. bool TableListBox::isAutoSizeMenuOptionShown() const
  41194. {
  41195. return autoSizeOptionsShown;
  41196. }
  41197. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  41198. const int rowNumber,
  41199. const bool relativeToComponentTopLeft) const
  41200. {
  41201. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41202. if (relativeToComponentTopLeft)
  41203. headerCell.translate (header->getX(), 0);
  41204. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  41205. return Rectangle<int> (headerCell.getX(), row.getY(),
  41206. headerCell.getWidth(), row.getHeight());
  41207. }
  41208. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  41209. {
  41210. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  41211. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  41212. }
  41213. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41214. {
  41215. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41216. if (scrollbar != 0)
  41217. {
  41218. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41219. double x = scrollbar->getCurrentRangeStart();
  41220. const double w = scrollbar->getCurrentRangeSize();
  41221. if (pos.getX() < x)
  41222. x = pos.getX();
  41223. else if (pos.getRight() > x + w)
  41224. x += jmax (0.0, pos.getRight() - (x + w));
  41225. scrollbar->setCurrentRangeStart (x);
  41226. }
  41227. }
  41228. int TableListBox::getNumRows()
  41229. {
  41230. return model != 0 ? model->getNumRows() : 0;
  41231. }
  41232. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41233. {
  41234. }
  41235. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41236. {
  41237. if (existingComponentToUpdate == 0)
  41238. existingComponentToUpdate = new TableListRowComp (*this);
  41239. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41240. return existingComponentToUpdate;
  41241. }
  41242. void TableListBox::selectedRowsChanged (int row)
  41243. {
  41244. if (model != 0)
  41245. model->selectedRowsChanged (row);
  41246. }
  41247. void TableListBox::deleteKeyPressed (int row)
  41248. {
  41249. if (model != 0)
  41250. model->deleteKeyPressed (row);
  41251. }
  41252. void TableListBox::returnKeyPressed (int row)
  41253. {
  41254. if (model != 0)
  41255. model->returnKeyPressed (row);
  41256. }
  41257. void TableListBox::backgroundClicked()
  41258. {
  41259. if (model != 0)
  41260. model->backgroundClicked();
  41261. }
  41262. void TableListBox::listWasScrolled()
  41263. {
  41264. if (model != 0)
  41265. model->listWasScrolled();
  41266. }
  41267. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41268. {
  41269. setMinimumContentWidth (header->getTotalWidth());
  41270. repaint();
  41271. updateColumnComponents();
  41272. }
  41273. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41274. {
  41275. setMinimumContentWidth (header->getTotalWidth());
  41276. repaint();
  41277. updateColumnComponents();
  41278. }
  41279. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41280. {
  41281. if (model != 0)
  41282. model->sortOrderChanged (header->getSortColumnId(),
  41283. header->isSortedForwards());
  41284. }
  41285. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41286. {
  41287. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41288. repaint();
  41289. }
  41290. void TableListBox::resized()
  41291. {
  41292. ListBox::resized();
  41293. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41294. setMinimumContentWidth (header->getTotalWidth());
  41295. }
  41296. void TableListBox::updateColumnComponents() const
  41297. {
  41298. const int firstRow = getRowContainingPosition (0, 0);
  41299. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41300. {
  41301. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41302. if (rowComp != 0)
  41303. rowComp->resized();
  41304. }
  41305. }
  41306. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  41307. {
  41308. }
  41309. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  41310. {
  41311. }
  41312. void TableListBoxModel::backgroundClicked()
  41313. {
  41314. }
  41315. void TableListBoxModel::sortOrderChanged (int, const bool)
  41316. {
  41317. }
  41318. int TableListBoxModel::getColumnAutoSizeWidth (int)
  41319. {
  41320. return 0;
  41321. }
  41322. void TableListBoxModel::selectedRowsChanged (int)
  41323. {
  41324. }
  41325. void TableListBoxModel::deleteKeyPressed (int)
  41326. {
  41327. }
  41328. void TableListBoxModel::returnKeyPressed (int)
  41329. {
  41330. }
  41331. void TableListBoxModel::listWasScrolled()
  41332. {
  41333. }
  41334. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  41335. {
  41336. return String::empty;
  41337. }
  41338. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  41339. {
  41340. return String::empty;
  41341. }
  41342. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41343. {
  41344. (void) existingComponentToUpdate;
  41345. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41346. return 0;
  41347. }
  41348. END_JUCE_NAMESPACE
  41349. /*** End of inlined file: juce_TableListBox.cpp ***/
  41350. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41351. BEGIN_JUCE_NAMESPACE
  41352. // a word or space that can't be broken down any further
  41353. struct TextAtom
  41354. {
  41355. String atomText;
  41356. float width;
  41357. uint16 numChars;
  41358. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41359. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41360. const String getText (const juce_wchar passwordCharacter) const
  41361. {
  41362. if (passwordCharacter == 0)
  41363. return atomText;
  41364. else
  41365. return String::repeatedString (String::charToString (passwordCharacter),
  41366. atomText.length());
  41367. }
  41368. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41369. {
  41370. if (passwordCharacter == 0)
  41371. return atomText.substring (0, numChars);
  41372. else if (isNewLine())
  41373. return String::empty;
  41374. else
  41375. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41376. }
  41377. };
  41378. // a run of text with a single font and colour
  41379. class TextEditor::UniformTextSection
  41380. {
  41381. public:
  41382. UniformTextSection (const String& text,
  41383. const Font& font_,
  41384. const Colour& colour_,
  41385. const juce_wchar passwordCharacter)
  41386. : font (font_),
  41387. colour (colour_)
  41388. {
  41389. initialiseAtoms (text, passwordCharacter);
  41390. }
  41391. UniformTextSection (const UniformTextSection& other)
  41392. : font (other.font),
  41393. colour (other.colour)
  41394. {
  41395. atoms.ensureStorageAllocated (other.atoms.size());
  41396. for (int i = 0; i < other.atoms.size(); ++i)
  41397. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41398. }
  41399. ~UniformTextSection()
  41400. {
  41401. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41402. }
  41403. void clear()
  41404. {
  41405. for (int i = atoms.size(); --i >= 0;)
  41406. delete getAtom(i);
  41407. atoms.clear();
  41408. }
  41409. int getNumAtoms() const
  41410. {
  41411. return atoms.size();
  41412. }
  41413. TextAtom* getAtom (const int index) const throw()
  41414. {
  41415. return atoms.getUnchecked (index);
  41416. }
  41417. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  41418. {
  41419. if (other.atoms.size() > 0)
  41420. {
  41421. TextAtom* const lastAtom = atoms.getLast();
  41422. int i = 0;
  41423. if (lastAtom != 0)
  41424. {
  41425. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  41426. {
  41427. TextAtom* const first = other.getAtom(0);
  41428. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  41429. {
  41430. lastAtom->atomText += first->atomText;
  41431. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  41432. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  41433. delete first;
  41434. ++i;
  41435. }
  41436. }
  41437. }
  41438. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  41439. while (i < other.atoms.size())
  41440. {
  41441. atoms.add (other.getAtom(i));
  41442. ++i;
  41443. }
  41444. }
  41445. }
  41446. UniformTextSection* split (const int indexToBreakAt,
  41447. const juce_wchar passwordCharacter)
  41448. {
  41449. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  41450. font, colour,
  41451. passwordCharacter);
  41452. int index = 0;
  41453. for (int i = 0; i < atoms.size(); ++i)
  41454. {
  41455. TextAtom* const atom = getAtom(i);
  41456. const int nextIndex = index + atom->numChars;
  41457. if (index == indexToBreakAt)
  41458. {
  41459. int j;
  41460. for (j = i; j < atoms.size(); ++j)
  41461. section2->atoms.add (getAtom (j));
  41462. for (j = atoms.size(); --j >= i;)
  41463. atoms.remove (j);
  41464. break;
  41465. }
  41466. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  41467. {
  41468. TextAtom* const secondAtom = new TextAtom();
  41469. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  41470. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  41471. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  41472. section2->atoms.add (secondAtom);
  41473. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  41474. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41475. atom->numChars = (uint16) (indexToBreakAt - index);
  41476. int j;
  41477. for (j = i + 1; j < atoms.size(); ++j)
  41478. section2->atoms.add (getAtom (j));
  41479. for (j = atoms.size(); --j > i;)
  41480. atoms.remove (j);
  41481. break;
  41482. }
  41483. index = nextIndex;
  41484. }
  41485. return section2;
  41486. }
  41487. void appendAllText (String::Concatenator& concatenator) const
  41488. {
  41489. for (int i = 0; i < atoms.size(); ++i)
  41490. concatenator.append (getAtom(i)->atomText);
  41491. }
  41492. void appendSubstring (String::Concatenator& concatenator,
  41493. const Range<int>& range) const
  41494. {
  41495. int index = 0;
  41496. for (int i = 0; i < atoms.size(); ++i)
  41497. {
  41498. const TextAtom* const atom = getAtom (i);
  41499. const int nextIndex = index + atom->numChars;
  41500. if (range.getStart() < nextIndex)
  41501. {
  41502. if (range.getEnd() <= index)
  41503. break;
  41504. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  41505. if (! r.isEmpty())
  41506. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  41507. }
  41508. index = nextIndex;
  41509. }
  41510. }
  41511. int getTotalLength() const
  41512. {
  41513. int total = 0;
  41514. for (int i = atoms.size(); --i >= 0;)
  41515. total += getAtom(i)->numChars;
  41516. return total;
  41517. }
  41518. void setFont (const Font& newFont,
  41519. const juce_wchar passwordCharacter)
  41520. {
  41521. if (font != newFont)
  41522. {
  41523. font = newFont;
  41524. for (int i = atoms.size(); --i >= 0;)
  41525. {
  41526. TextAtom* const atom = atoms.getUnchecked(i);
  41527. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  41528. }
  41529. }
  41530. }
  41531. juce_UseDebuggingNewOperator
  41532. Font font;
  41533. Colour colour;
  41534. private:
  41535. Array <TextAtom*> atoms;
  41536. void initialiseAtoms (const String& textToParse,
  41537. const juce_wchar passwordCharacter)
  41538. {
  41539. int i = 0;
  41540. const int len = textToParse.length();
  41541. const juce_wchar* const text = textToParse;
  41542. while (i < len)
  41543. {
  41544. int start = i;
  41545. // create a whitespace atom unless it starts with non-ws
  41546. if (CharacterFunctions::isWhitespace (text[i])
  41547. && text[i] != '\r'
  41548. && text[i] != '\n')
  41549. {
  41550. while (i < len
  41551. && CharacterFunctions::isWhitespace (text[i])
  41552. && text[i] != '\r'
  41553. && text[i] != '\n')
  41554. {
  41555. ++i;
  41556. }
  41557. }
  41558. else
  41559. {
  41560. if (text[i] == '\r')
  41561. {
  41562. ++i;
  41563. if ((i < len) && (text[i] == '\n'))
  41564. {
  41565. ++start;
  41566. ++i;
  41567. }
  41568. }
  41569. else if (text[i] == '\n')
  41570. {
  41571. ++i;
  41572. }
  41573. else
  41574. {
  41575. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  41576. ++i;
  41577. }
  41578. }
  41579. TextAtom* const atom = new TextAtom();
  41580. atom->atomText = String (text + start, i - start);
  41581. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41582. atom->numChars = (uint16) (i - start);
  41583. atoms.add (atom);
  41584. }
  41585. }
  41586. UniformTextSection& operator= (const UniformTextSection& other);
  41587. };
  41588. class TextEditor::Iterator
  41589. {
  41590. public:
  41591. Iterator (const Array <UniformTextSection*>& sections_,
  41592. const float wordWrapWidth_,
  41593. const juce_wchar passwordCharacter_)
  41594. : indexInText (0),
  41595. lineY (0),
  41596. lineHeight (0),
  41597. maxDescent (0),
  41598. atomX (0),
  41599. atomRight (0),
  41600. atom (0),
  41601. currentSection (0),
  41602. sections (sections_),
  41603. sectionIndex (0),
  41604. atomIndex (0),
  41605. wordWrapWidth (wordWrapWidth_),
  41606. passwordCharacter (passwordCharacter_)
  41607. {
  41608. jassert (wordWrapWidth_ > 0);
  41609. if (sections.size() > 0)
  41610. {
  41611. currentSection = sections.getUnchecked (sectionIndex);
  41612. if (currentSection != 0)
  41613. beginNewLine();
  41614. }
  41615. }
  41616. Iterator (const Iterator& other)
  41617. : indexInText (other.indexInText),
  41618. lineY (other.lineY),
  41619. lineHeight (other.lineHeight),
  41620. maxDescent (other.maxDescent),
  41621. atomX (other.atomX),
  41622. atomRight (other.atomRight),
  41623. atom (other.atom),
  41624. currentSection (other.currentSection),
  41625. sections (other.sections),
  41626. sectionIndex (other.sectionIndex),
  41627. atomIndex (other.atomIndex),
  41628. wordWrapWidth (other.wordWrapWidth),
  41629. passwordCharacter (other.passwordCharacter),
  41630. tempAtom (other.tempAtom)
  41631. {
  41632. }
  41633. ~Iterator()
  41634. {
  41635. }
  41636. bool next()
  41637. {
  41638. if (atom == &tempAtom)
  41639. {
  41640. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  41641. if (numRemaining > 0)
  41642. {
  41643. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  41644. atomX = 0;
  41645. if (tempAtom.numChars > 0)
  41646. lineY += lineHeight;
  41647. indexInText += tempAtom.numChars;
  41648. GlyphArrangement g;
  41649. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  41650. int split;
  41651. for (split = 0; split < g.getNumGlyphs(); ++split)
  41652. if (shouldWrap (g.getGlyph (split).getRight()))
  41653. break;
  41654. if (split > 0 && split <= numRemaining)
  41655. {
  41656. tempAtom.numChars = (uint16) split;
  41657. tempAtom.width = g.getGlyph (split - 1).getRight();
  41658. atomRight = atomX + tempAtom.width;
  41659. return true;
  41660. }
  41661. }
  41662. }
  41663. bool forceNewLine = false;
  41664. if (sectionIndex >= sections.size())
  41665. {
  41666. moveToEndOfLastAtom();
  41667. return false;
  41668. }
  41669. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  41670. {
  41671. if (atomIndex >= currentSection->getNumAtoms())
  41672. {
  41673. if (++sectionIndex >= sections.size())
  41674. {
  41675. moveToEndOfLastAtom();
  41676. return false;
  41677. }
  41678. atomIndex = 0;
  41679. currentSection = sections.getUnchecked (sectionIndex);
  41680. }
  41681. else
  41682. {
  41683. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  41684. if (! lastAtom->isWhitespace())
  41685. {
  41686. // handle the case where the last atom in a section is actually part of the same
  41687. // word as the first atom of the next section...
  41688. float right = atomRight + lastAtom->width;
  41689. float lineHeight2 = lineHeight;
  41690. float maxDescent2 = maxDescent;
  41691. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  41692. {
  41693. const UniformTextSection* const s = sections.getUnchecked (section);
  41694. if (s->getNumAtoms() == 0)
  41695. break;
  41696. const TextAtom* const nextAtom = s->getAtom (0);
  41697. if (nextAtom->isWhitespace())
  41698. break;
  41699. right += nextAtom->width;
  41700. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  41701. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  41702. if (shouldWrap (right))
  41703. {
  41704. lineHeight = lineHeight2;
  41705. maxDescent = maxDescent2;
  41706. forceNewLine = true;
  41707. break;
  41708. }
  41709. if (s->getNumAtoms() > 1)
  41710. break;
  41711. }
  41712. }
  41713. }
  41714. }
  41715. if (atom != 0)
  41716. {
  41717. atomX = atomRight;
  41718. indexInText += atom->numChars;
  41719. if (atom->isNewLine())
  41720. beginNewLine();
  41721. }
  41722. atom = currentSection->getAtom (atomIndex);
  41723. atomRight = atomX + atom->width;
  41724. ++atomIndex;
  41725. if (shouldWrap (atomRight) || forceNewLine)
  41726. {
  41727. if (atom->isWhitespace())
  41728. {
  41729. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  41730. atomRight = jmin (atomRight, wordWrapWidth);
  41731. }
  41732. else
  41733. {
  41734. atomRight = atom->width;
  41735. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  41736. {
  41737. tempAtom = *atom;
  41738. tempAtom.width = 0;
  41739. tempAtom.numChars = 0;
  41740. atom = &tempAtom;
  41741. if (atomX > 0)
  41742. beginNewLine();
  41743. return next();
  41744. }
  41745. beginNewLine();
  41746. return true;
  41747. }
  41748. }
  41749. return true;
  41750. }
  41751. void beginNewLine()
  41752. {
  41753. atomX = 0;
  41754. lineY += lineHeight;
  41755. int tempSectionIndex = sectionIndex;
  41756. int tempAtomIndex = atomIndex;
  41757. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  41758. lineHeight = section->font.getHeight();
  41759. maxDescent = section->font.getDescent();
  41760. float x = (atom != 0) ? atom->width : 0;
  41761. while (! shouldWrap (x))
  41762. {
  41763. if (tempSectionIndex >= sections.size())
  41764. break;
  41765. bool checkSize = false;
  41766. if (tempAtomIndex >= section->getNumAtoms())
  41767. {
  41768. if (++tempSectionIndex >= sections.size())
  41769. break;
  41770. tempAtomIndex = 0;
  41771. section = sections.getUnchecked (tempSectionIndex);
  41772. checkSize = true;
  41773. }
  41774. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  41775. if (nextAtom == 0)
  41776. break;
  41777. x += nextAtom->width;
  41778. if (shouldWrap (x) || nextAtom->isNewLine())
  41779. break;
  41780. if (checkSize)
  41781. {
  41782. lineHeight = jmax (lineHeight, section->font.getHeight());
  41783. maxDescent = jmax (maxDescent, section->font.getDescent());
  41784. }
  41785. ++tempAtomIndex;
  41786. }
  41787. }
  41788. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  41789. {
  41790. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41791. {
  41792. if (lastSection != currentSection)
  41793. {
  41794. lastSection = currentSection;
  41795. g.setColour (currentSection->colour);
  41796. g.setFont (currentSection->font);
  41797. }
  41798. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  41799. GlyphArrangement ga;
  41800. ga.addLineOfText (currentSection->font,
  41801. atom->getTrimmedText (passwordCharacter),
  41802. atomX,
  41803. (float) roundToInt (lineY + lineHeight - maxDescent));
  41804. ga.draw (g);
  41805. }
  41806. }
  41807. void drawSelection (Graphics& g,
  41808. const Range<int>& selection) const
  41809. {
  41810. const int startX = roundToInt (indexToX (selection.getStart()));
  41811. const int endX = roundToInt (indexToX (selection.getEnd()));
  41812. const int y = roundToInt (lineY);
  41813. const int nextY = roundToInt (lineY + lineHeight);
  41814. g.fillRect (startX, y, endX - startX, nextY - y);
  41815. }
  41816. void drawSelectedText (Graphics& g,
  41817. const Range<int>& selection,
  41818. const Colour& selectedTextColour) const
  41819. {
  41820. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41821. {
  41822. GlyphArrangement ga;
  41823. ga.addLineOfText (currentSection->font,
  41824. atom->getTrimmedText (passwordCharacter),
  41825. atomX,
  41826. (float) roundToInt (lineY + lineHeight - maxDescent));
  41827. if (selection.getEnd() < indexInText + atom->numChars)
  41828. {
  41829. GlyphArrangement ga2 (ga);
  41830. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  41831. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  41832. g.setColour (currentSection->colour);
  41833. ga2.draw (g);
  41834. }
  41835. if (selection.getStart() > indexInText)
  41836. {
  41837. GlyphArrangement ga2 (ga);
  41838. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  41839. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  41840. g.setColour (currentSection->colour);
  41841. ga2.draw (g);
  41842. }
  41843. g.setColour (selectedTextColour);
  41844. ga.draw (g);
  41845. }
  41846. }
  41847. float indexToX (const int indexToFind) const
  41848. {
  41849. if (indexToFind <= indexInText)
  41850. return atomX;
  41851. if (indexToFind >= indexInText + atom->numChars)
  41852. return atomRight;
  41853. GlyphArrangement g;
  41854. g.addLineOfText (currentSection->font,
  41855. atom->getText (passwordCharacter),
  41856. atomX, 0.0f);
  41857. if (indexToFind - indexInText >= g.getNumGlyphs())
  41858. return atomRight;
  41859. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  41860. }
  41861. int xToIndex (const float xToFind) const
  41862. {
  41863. if (xToFind <= atomX || atom->isNewLine())
  41864. return indexInText;
  41865. if (xToFind >= atomRight)
  41866. return indexInText + atom->numChars;
  41867. GlyphArrangement g;
  41868. g.addLineOfText (currentSection->font,
  41869. atom->getText (passwordCharacter),
  41870. atomX, 0.0f);
  41871. int j;
  41872. for (j = 0; j < g.getNumGlyphs(); ++j)
  41873. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  41874. break;
  41875. return indexInText + j;
  41876. }
  41877. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  41878. {
  41879. while (next())
  41880. {
  41881. if (indexInText + atom->numChars > index)
  41882. {
  41883. cx = indexToX (index);
  41884. cy = lineY;
  41885. lineHeight_ = lineHeight;
  41886. return true;
  41887. }
  41888. }
  41889. cx = atomX;
  41890. cy = lineY;
  41891. lineHeight_ = lineHeight;
  41892. return false;
  41893. }
  41894. juce_UseDebuggingNewOperator
  41895. int indexInText;
  41896. float lineY, lineHeight, maxDescent;
  41897. float atomX, atomRight;
  41898. const TextAtom* atom;
  41899. const UniformTextSection* currentSection;
  41900. private:
  41901. const Array <UniformTextSection*>& sections;
  41902. int sectionIndex, atomIndex;
  41903. const float wordWrapWidth;
  41904. const juce_wchar passwordCharacter;
  41905. TextAtom tempAtom;
  41906. Iterator& operator= (const Iterator&);
  41907. void moveToEndOfLastAtom()
  41908. {
  41909. if (atom != 0)
  41910. {
  41911. atomX = atomRight;
  41912. if (atom->isNewLine())
  41913. {
  41914. atomX = 0.0f;
  41915. lineY += lineHeight;
  41916. }
  41917. }
  41918. }
  41919. bool shouldWrap (const float x) const
  41920. {
  41921. return (x - 0.0001f) >= wordWrapWidth;
  41922. }
  41923. };
  41924. class TextEditor::InsertAction : public UndoableAction
  41925. {
  41926. TextEditor& owner;
  41927. const String text;
  41928. const int insertIndex, oldCaretPos, newCaretPos;
  41929. const Font font;
  41930. const Colour colour;
  41931. InsertAction (const InsertAction&);
  41932. InsertAction& operator= (const InsertAction&);
  41933. public:
  41934. InsertAction (TextEditor& owner_,
  41935. const String& text_,
  41936. const int insertIndex_,
  41937. const Font& font_,
  41938. const Colour& colour_,
  41939. const int oldCaretPos_,
  41940. const int newCaretPos_)
  41941. : owner (owner_),
  41942. text (text_),
  41943. insertIndex (insertIndex_),
  41944. oldCaretPos (oldCaretPos_),
  41945. newCaretPos (newCaretPos_),
  41946. font (font_),
  41947. colour (colour_)
  41948. {
  41949. }
  41950. ~InsertAction()
  41951. {
  41952. }
  41953. bool perform()
  41954. {
  41955. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  41956. return true;
  41957. }
  41958. bool undo()
  41959. {
  41960. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  41961. return true;
  41962. }
  41963. int getSizeInUnits()
  41964. {
  41965. return text.length() + 16;
  41966. }
  41967. };
  41968. class TextEditor::RemoveAction : public UndoableAction
  41969. {
  41970. TextEditor& owner;
  41971. const Range<int> range;
  41972. const int oldCaretPos, newCaretPos;
  41973. Array <UniformTextSection*> removedSections;
  41974. RemoveAction (const RemoveAction&);
  41975. RemoveAction& operator= (const RemoveAction&);
  41976. public:
  41977. RemoveAction (TextEditor& owner_,
  41978. const Range<int> range_,
  41979. const int oldCaretPos_,
  41980. const int newCaretPos_,
  41981. const Array <UniformTextSection*>& removedSections_)
  41982. : owner (owner_),
  41983. range (range_),
  41984. oldCaretPos (oldCaretPos_),
  41985. newCaretPos (newCaretPos_),
  41986. removedSections (removedSections_)
  41987. {
  41988. }
  41989. ~RemoveAction()
  41990. {
  41991. for (int i = removedSections.size(); --i >= 0;)
  41992. {
  41993. UniformTextSection* const section = removedSections.getUnchecked (i);
  41994. section->clear();
  41995. delete section;
  41996. }
  41997. }
  41998. bool perform()
  41999. {
  42000. owner.remove (range, 0, newCaretPos);
  42001. return true;
  42002. }
  42003. bool undo()
  42004. {
  42005. owner.reinsert (range.getStart(), removedSections);
  42006. owner.moveCursorTo (oldCaretPos, false);
  42007. return true;
  42008. }
  42009. int getSizeInUnits()
  42010. {
  42011. int n = 0;
  42012. for (int i = removedSections.size(); --i >= 0;)
  42013. n += removedSections.getUnchecked (i)->getTotalLength();
  42014. return n + 16;
  42015. }
  42016. };
  42017. class TextEditor::TextHolderComponent : public Component,
  42018. public Timer,
  42019. public Value::Listener
  42020. {
  42021. public:
  42022. TextHolderComponent (TextEditor& owner_)
  42023. : owner (owner_)
  42024. {
  42025. setWantsKeyboardFocus (false);
  42026. setInterceptsMouseClicks (false, true);
  42027. owner.getTextValue().addListener (this);
  42028. }
  42029. ~TextHolderComponent()
  42030. {
  42031. owner.getTextValue().removeListener (this);
  42032. }
  42033. void paint (Graphics& g)
  42034. {
  42035. owner.drawContent (g);
  42036. }
  42037. void timerCallback()
  42038. {
  42039. owner.timerCallbackInt();
  42040. }
  42041. const MouseCursor getMouseCursor()
  42042. {
  42043. return owner.getMouseCursor();
  42044. }
  42045. void valueChanged (Value&)
  42046. {
  42047. owner.textWasChangedByValue();
  42048. }
  42049. private:
  42050. TextEditor& owner;
  42051. TextHolderComponent (const TextHolderComponent&);
  42052. TextHolderComponent& operator= (const TextHolderComponent&);
  42053. };
  42054. class TextEditorViewport : public Viewport
  42055. {
  42056. public:
  42057. TextEditorViewport (TextEditor* const owner_)
  42058. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42059. {
  42060. }
  42061. ~TextEditorViewport()
  42062. {
  42063. }
  42064. void visibleAreaChanged (int, int, int, int)
  42065. {
  42066. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42067. // appear and disappear, causing the wrap width to change.
  42068. {
  42069. const float wordWrapWidth = owner->getWordWrapWidth();
  42070. if (wordWrapWidth != lastWordWrapWidth)
  42071. {
  42072. lastWordWrapWidth = wordWrapWidth;
  42073. rentrant = true;
  42074. owner->updateTextHolderSize();
  42075. rentrant = false;
  42076. }
  42077. }
  42078. }
  42079. private:
  42080. TextEditor* const owner;
  42081. float lastWordWrapWidth;
  42082. bool rentrant;
  42083. TextEditorViewport (const TextEditorViewport&);
  42084. TextEditorViewport& operator= (const TextEditorViewport&);
  42085. };
  42086. namespace TextEditorDefs
  42087. {
  42088. const int flashSpeedIntervalMs = 380;
  42089. const int textChangeMessageId = 0x10003001;
  42090. const int returnKeyMessageId = 0x10003002;
  42091. const int escapeKeyMessageId = 0x10003003;
  42092. const int focusLossMessageId = 0x10003004;
  42093. const int maxActionsPerTransaction = 100;
  42094. }
  42095. TextEditor::TextEditor (const String& name,
  42096. const juce_wchar passwordCharacter_)
  42097. : Component (name),
  42098. borderSize (1, 1, 1, 3),
  42099. readOnly (false),
  42100. multiline (false),
  42101. wordWrap (false),
  42102. returnKeyStartsNewLine (false),
  42103. caretVisible (true),
  42104. popupMenuEnabled (true),
  42105. selectAllTextWhenFocused (false),
  42106. scrollbarVisible (true),
  42107. wasFocused (false),
  42108. caretFlashState (true),
  42109. keepCursorOnScreen (true),
  42110. tabKeyUsed (false),
  42111. menuActive (false),
  42112. valueTextNeedsUpdating (false),
  42113. cursorX (0),
  42114. cursorY (0),
  42115. cursorHeight (0),
  42116. maxTextLength (0),
  42117. leftIndent (4),
  42118. topIndent (4),
  42119. lastTransactionTime (0),
  42120. currentFont (14.0f),
  42121. totalNumChars (0),
  42122. caretPosition (0),
  42123. passwordCharacter (passwordCharacter_),
  42124. dragType (notDragging)
  42125. {
  42126. setOpaque (true);
  42127. addAndMakeVisible (viewport = new TextEditorViewport (this));
  42128. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42129. viewport->setWantsKeyboardFocus (false);
  42130. viewport->setScrollBarsShown (false, false);
  42131. setMouseCursor (MouseCursor::IBeamCursor);
  42132. setWantsKeyboardFocus (true);
  42133. }
  42134. TextEditor::~TextEditor()
  42135. {
  42136. textValue.referTo (Value());
  42137. clearInternal (0);
  42138. viewport = 0;
  42139. textHolder = 0;
  42140. }
  42141. void TextEditor::newTransaction()
  42142. {
  42143. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42144. undoManager.beginNewTransaction();
  42145. }
  42146. void TextEditor::doUndoRedo (const bool isRedo)
  42147. {
  42148. if (! isReadOnly())
  42149. {
  42150. if (isRedo ? undoManager.redo()
  42151. : undoManager.undo())
  42152. {
  42153. scrollToMakeSureCursorIsVisible();
  42154. repaint();
  42155. textChanged();
  42156. }
  42157. }
  42158. }
  42159. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42160. const bool shouldWordWrap)
  42161. {
  42162. if (multiline != shouldBeMultiLine
  42163. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42164. {
  42165. multiline = shouldBeMultiLine;
  42166. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42167. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42168. scrollbarVisible && multiline);
  42169. viewport->setViewPosition (0, 0);
  42170. resized();
  42171. scrollToMakeSureCursorIsVisible();
  42172. }
  42173. }
  42174. bool TextEditor::isMultiLine() const
  42175. {
  42176. return multiline;
  42177. }
  42178. void TextEditor::setScrollbarsShown (bool shown)
  42179. {
  42180. if (scrollbarVisible != shown)
  42181. {
  42182. scrollbarVisible = shown;
  42183. shown = shown && isMultiLine();
  42184. viewport->setScrollBarsShown (shown, shown);
  42185. }
  42186. }
  42187. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42188. {
  42189. if (readOnly != shouldBeReadOnly)
  42190. {
  42191. readOnly = shouldBeReadOnly;
  42192. enablementChanged();
  42193. }
  42194. }
  42195. bool TextEditor::isReadOnly() const
  42196. {
  42197. return readOnly || ! isEnabled();
  42198. }
  42199. bool TextEditor::isTextInputActive() const
  42200. {
  42201. return ! isReadOnly();
  42202. }
  42203. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42204. {
  42205. returnKeyStartsNewLine = shouldStartNewLine;
  42206. }
  42207. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42208. {
  42209. tabKeyUsed = shouldTabKeyBeUsed;
  42210. }
  42211. void TextEditor::setPopupMenuEnabled (const bool b)
  42212. {
  42213. popupMenuEnabled = b;
  42214. }
  42215. void TextEditor::setSelectAllWhenFocused (const bool b)
  42216. {
  42217. selectAllTextWhenFocused = b;
  42218. }
  42219. const Font TextEditor::getFont() const
  42220. {
  42221. return currentFont;
  42222. }
  42223. void TextEditor::setFont (const Font& newFont)
  42224. {
  42225. currentFont = newFont;
  42226. scrollToMakeSureCursorIsVisible();
  42227. }
  42228. void TextEditor::applyFontToAllText (const Font& newFont)
  42229. {
  42230. currentFont = newFont;
  42231. const Colour overallColour (findColour (textColourId));
  42232. for (int i = sections.size(); --i >= 0;)
  42233. {
  42234. UniformTextSection* const uts = sections.getUnchecked (i);
  42235. uts->setFont (newFont, passwordCharacter);
  42236. uts->colour = overallColour;
  42237. }
  42238. coalesceSimilarSections();
  42239. updateTextHolderSize();
  42240. scrollToMakeSureCursorIsVisible();
  42241. repaint();
  42242. }
  42243. void TextEditor::colourChanged()
  42244. {
  42245. setOpaque (findColour (backgroundColourId).isOpaque());
  42246. repaint();
  42247. }
  42248. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42249. {
  42250. caretVisible = shouldCaretBeVisible;
  42251. if (shouldCaretBeVisible)
  42252. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42253. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42254. : MouseCursor::NormalCursor);
  42255. }
  42256. void TextEditor::setInputRestrictions (const int maxLen,
  42257. const String& chars)
  42258. {
  42259. maxTextLength = jmax (0, maxLen);
  42260. allowedCharacters = chars;
  42261. }
  42262. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42263. {
  42264. textToShowWhenEmpty = text;
  42265. colourForTextWhenEmpty = colourToUse;
  42266. }
  42267. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42268. {
  42269. if (passwordCharacter != newPasswordCharacter)
  42270. {
  42271. passwordCharacter = newPasswordCharacter;
  42272. resized();
  42273. repaint();
  42274. }
  42275. }
  42276. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42277. {
  42278. viewport->setScrollBarThickness (newThicknessPixels);
  42279. }
  42280. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42281. {
  42282. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42283. }
  42284. void TextEditor::clear()
  42285. {
  42286. clearInternal (0);
  42287. updateTextHolderSize();
  42288. undoManager.clearUndoHistory();
  42289. }
  42290. void TextEditor::setText (const String& newText,
  42291. const bool sendTextChangeMessage)
  42292. {
  42293. const int newLength = newText.length();
  42294. if (newLength != getTotalNumChars() || getText() != newText)
  42295. {
  42296. const int oldCursorPos = caretPosition;
  42297. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42298. clearInternal (0);
  42299. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42300. // if you're adding text with line-feeds to a single-line text editor, it
  42301. // ain't gonna look right!
  42302. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42303. if (cursorWasAtEnd && ! isMultiLine())
  42304. moveCursorTo (getTotalNumChars(), false);
  42305. else
  42306. moveCursorTo (oldCursorPos, false);
  42307. if (sendTextChangeMessage)
  42308. textChanged();
  42309. updateTextHolderSize();
  42310. scrollToMakeSureCursorIsVisible();
  42311. undoManager.clearUndoHistory();
  42312. repaint();
  42313. }
  42314. }
  42315. Value& TextEditor::getTextValue()
  42316. {
  42317. if (valueTextNeedsUpdating)
  42318. {
  42319. valueTextNeedsUpdating = false;
  42320. textValue = getText();
  42321. }
  42322. return textValue;
  42323. }
  42324. void TextEditor::textWasChangedByValue()
  42325. {
  42326. if (textValue.getValueSource().getReferenceCount() > 1)
  42327. setText (textValue.getValue());
  42328. }
  42329. void TextEditor::textChanged()
  42330. {
  42331. updateTextHolderSize();
  42332. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42333. if (textValue.getValueSource().getReferenceCount() > 1)
  42334. {
  42335. valueTextNeedsUpdating = false;
  42336. textValue = getText();
  42337. }
  42338. }
  42339. void TextEditor::returnPressed()
  42340. {
  42341. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42342. }
  42343. void TextEditor::escapePressed()
  42344. {
  42345. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42346. }
  42347. void TextEditor::addListener (Listener* const newListener)
  42348. {
  42349. listeners.add (newListener);
  42350. }
  42351. void TextEditor::removeListener (Listener* const listenerToRemove)
  42352. {
  42353. listeners.remove (listenerToRemove);
  42354. }
  42355. void TextEditor::timerCallbackInt()
  42356. {
  42357. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42358. if (caretFlashState != newState)
  42359. {
  42360. caretFlashState = newState;
  42361. if (caretFlashState)
  42362. wasFocused = true;
  42363. if (caretVisible
  42364. && hasKeyboardFocus (false)
  42365. && ! isReadOnly())
  42366. {
  42367. repaintCaret();
  42368. }
  42369. }
  42370. const unsigned int now = Time::getApproximateMillisecondCounter();
  42371. if (now > lastTransactionTime + 200)
  42372. newTransaction();
  42373. }
  42374. void TextEditor::repaintCaret()
  42375. {
  42376. if (! findColour (caretColourId).isTransparent())
  42377. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42378. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42379. 4,
  42380. roundToInt (cursorHeight) + 2);
  42381. }
  42382. void TextEditor::repaintText (const Range<int>& range)
  42383. {
  42384. if (! range.isEmpty())
  42385. {
  42386. float x = 0, y = 0, lh = currentFont.getHeight();
  42387. const float wordWrapWidth = getWordWrapWidth();
  42388. if (wordWrapWidth > 0)
  42389. {
  42390. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42391. i.getCharPosition (range.getStart(), x, y, lh);
  42392. const int y1 = (int) y;
  42393. int y2;
  42394. if (range.getEnd() >= getTotalNumChars())
  42395. {
  42396. y2 = textHolder->getHeight();
  42397. }
  42398. else
  42399. {
  42400. i.getCharPosition (range.getEnd(), x, y, lh);
  42401. y2 = (int) (y + lh * 2.0f);
  42402. }
  42403. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42404. }
  42405. }
  42406. }
  42407. void TextEditor::moveCaret (int newCaretPos)
  42408. {
  42409. if (newCaretPos < 0)
  42410. newCaretPos = 0;
  42411. else if (newCaretPos > getTotalNumChars())
  42412. newCaretPos = getTotalNumChars();
  42413. if (newCaretPos != getCaretPosition())
  42414. {
  42415. repaintCaret();
  42416. caretFlashState = true;
  42417. caretPosition = newCaretPos;
  42418. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42419. scrollToMakeSureCursorIsVisible();
  42420. repaintCaret();
  42421. }
  42422. }
  42423. void TextEditor::setCaretPosition (const int newIndex)
  42424. {
  42425. moveCursorTo (newIndex, false);
  42426. }
  42427. int TextEditor::getCaretPosition() const
  42428. {
  42429. return caretPosition;
  42430. }
  42431. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  42432. const int desiredCaretY)
  42433. {
  42434. updateCaretPosition();
  42435. int vx = roundToInt (cursorX) - desiredCaretX;
  42436. int vy = roundToInt (cursorY) - desiredCaretY;
  42437. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  42438. {
  42439. vx += desiredCaretX - proportionOfWidth (0.2f);
  42440. }
  42441. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42442. {
  42443. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42444. }
  42445. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  42446. if (! isMultiLine())
  42447. {
  42448. vy = viewport->getViewPositionY();
  42449. }
  42450. else
  42451. {
  42452. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  42453. const int curH = roundToInt (cursorHeight);
  42454. if (desiredCaretY < 0)
  42455. {
  42456. vy = jmax (0, desiredCaretY + vy);
  42457. }
  42458. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42459. {
  42460. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42461. }
  42462. }
  42463. viewport->setViewPosition (vx, vy);
  42464. }
  42465. const Rectangle<int> TextEditor::getCaretRectangle()
  42466. {
  42467. updateCaretPosition();
  42468. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  42469. roundToInt (cursorY) - viewport->getY(),
  42470. 1, roundToInt (cursorHeight));
  42471. }
  42472. float TextEditor::getWordWrapWidth() const
  42473. {
  42474. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  42475. : 1.0e10f;
  42476. }
  42477. void TextEditor::updateTextHolderSize()
  42478. {
  42479. const float wordWrapWidth = getWordWrapWidth();
  42480. if (wordWrapWidth > 0)
  42481. {
  42482. float maxWidth = 0.0f;
  42483. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42484. while (i.next())
  42485. maxWidth = jmax (maxWidth, i.atomRight);
  42486. const int w = leftIndent + roundToInt (maxWidth);
  42487. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  42488. currentFont.getHeight()));
  42489. textHolder->setSize (w + 1, h + 1);
  42490. }
  42491. }
  42492. int TextEditor::getTextWidth() const
  42493. {
  42494. return textHolder->getWidth();
  42495. }
  42496. int TextEditor::getTextHeight() const
  42497. {
  42498. return textHolder->getHeight();
  42499. }
  42500. void TextEditor::setIndents (const int newLeftIndent,
  42501. const int newTopIndent)
  42502. {
  42503. leftIndent = newLeftIndent;
  42504. topIndent = newTopIndent;
  42505. }
  42506. void TextEditor::setBorder (const BorderSize& border)
  42507. {
  42508. borderSize = border;
  42509. resized();
  42510. }
  42511. const BorderSize TextEditor::getBorder() const
  42512. {
  42513. return borderSize;
  42514. }
  42515. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  42516. {
  42517. keepCursorOnScreen = shouldScrollToShowCursor;
  42518. }
  42519. void TextEditor::updateCaretPosition()
  42520. {
  42521. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  42522. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  42523. }
  42524. void TextEditor::scrollToMakeSureCursorIsVisible()
  42525. {
  42526. updateCaretPosition();
  42527. if (keepCursorOnScreen)
  42528. {
  42529. int x = viewport->getViewPositionX();
  42530. int y = viewport->getViewPositionY();
  42531. const int relativeCursorX = roundToInt (cursorX) - x;
  42532. const int relativeCursorY = roundToInt (cursorY) - y;
  42533. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  42534. {
  42535. x += relativeCursorX - proportionOfWidth (0.2f);
  42536. }
  42537. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42538. {
  42539. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42540. }
  42541. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  42542. if (! isMultiLine())
  42543. {
  42544. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  42545. }
  42546. else
  42547. {
  42548. const int curH = roundToInt (cursorHeight);
  42549. if (relativeCursorY < 0)
  42550. {
  42551. y = jmax (0, relativeCursorY + y);
  42552. }
  42553. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42554. {
  42555. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42556. }
  42557. }
  42558. viewport->setViewPosition (x, y);
  42559. }
  42560. }
  42561. void TextEditor::moveCursorTo (const int newPosition,
  42562. const bool isSelecting)
  42563. {
  42564. if (isSelecting)
  42565. {
  42566. moveCaret (newPosition);
  42567. const Range<int> oldSelection (selection);
  42568. if (dragType == notDragging)
  42569. {
  42570. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  42571. dragType = draggingSelectionStart;
  42572. else
  42573. dragType = draggingSelectionEnd;
  42574. }
  42575. if (dragType == draggingSelectionStart)
  42576. {
  42577. if (getCaretPosition() >= selection.getEnd())
  42578. dragType = draggingSelectionEnd;
  42579. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  42580. }
  42581. else
  42582. {
  42583. if (getCaretPosition() < selection.getStart())
  42584. dragType = draggingSelectionStart;
  42585. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  42586. }
  42587. repaintText (selection.getUnionWith (oldSelection));
  42588. }
  42589. else
  42590. {
  42591. dragType = notDragging;
  42592. repaintText (selection);
  42593. moveCaret (newPosition);
  42594. selection = Range<int>::emptyRange (getCaretPosition());
  42595. }
  42596. }
  42597. int TextEditor::getTextIndexAt (const int x,
  42598. const int y)
  42599. {
  42600. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  42601. (float) (y + viewport->getViewPositionY() - topIndent));
  42602. }
  42603. void TextEditor::insertTextAtCaret (const String& newText_)
  42604. {
  42605. String newText (newText_);
  42606. if (allowedCharacters.isNotEmpty())
  42607. newText = newText.retainCharacters (allowedCharacters);
  42608. if ((! returnKeyStartsNewLine) && newText == "\n")
  42609. {
  42610. returnPressed();
  42611. return;
  42612. }
  42613. if (! isMultiLine())
  42614. newText = newText.replaceCharacters ("\r\n", " ");
  42615. else
  42616. newText = newText.replace ("\r\n", "\n");
  42617. const int newCaretPos = selection.getStart() + newText.length();
  42618. const int insertIndex = selection.getStart();
  42619. remove (selection, getUndoManager(),
  42620. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  42621. if (maxTextLength > 0)
  42622. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  42623. if (newText.isNotEmpty())
  42624. insert (newText,
  42625. insertIndex,
  42626. currentFont,
  42627. findColour (textColourId),
  42628. getUndoManager(),
  42629. newCaretPos);
  42630. textChanged();
  42631. }
  42632. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  42633. {
  42634. moveCursorTo (newSelection.getStart(), false);
  42635. moveCursorTo (newSelection.getEnd(), true);
  42636. }
  42637. void TextEditor::copy()
  42638. {
  42639. if (passwordCharacter == 0)
  42640. {
  42641. const String selectedText (getHighlightedText());
  42642. if (selectedText.isNotEmpty())
  42643. SystemClipboard::copyTextToClipboard (selectedText);
  42644. }
  42645. }
  42646. void TextEditor::paste()
  42647. {
  42648. if (! isReadOnly())
  42649. {
  42650. const String clip (SystemClipboard::getTextFromClipboard());
  42651. if (clip.isNotEmpty())
  42652. insertTextAtCaret (clip);
  42653. }
  42654. }
  42655. void TextEditor::cut()
  42656. {
  42657. if (! isReadOnly())
  42658. {
  42659. moveCaret (selection.getEnd());
  42660. insertTextAtCaret (String::empty);
  42661. }
  42662. }
  42663. void TextEditor::drawContent (Graphics& g)
  42664. {
  42665. const float wordWrapWidth = getWordWrapWidth();
  42666. if (wordWrapWidth > 0)
  42667. {
  42668. g.setOrigin (leftIndent, topIndent);
  42669. const Rectangle<int> clip (g.getClipBounds());
  42670. Colour selectedTextColour;
  42671. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42672. while (i.lineY + 200.0 < clip.getY() && i.next())
  42673. {}
  42674. if (! selection.isEmpty())
  42675. {
  42676. g.setColour (findColour (highlightColourId)
  42677. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  42678. selectedTextColour = findColour (highlightedTextColourId);
  42679. Iterator i2 (i);
  42680. while (i2.next() && i2.lineY < clip.getBottom())
  42681. {
  42682. if (i2.lineY + i2.lineHeight >= clip.getY()
  42683. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  42684. {
  42685. i2.drawSelection (g, selection);
  42686. }
  42687. }
  42688. }
  42689. const UniformTextSection* lastSection = 0;
  42690. while (i.next() && i.lineY < clip.getBottom())
  42691. {
  42692. if (i.lineY + i.lineHeight >= clip.getY())
  42693. {
  42694. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  42695. {
  42696. i.drawSelectedText (g, selection, selectedTextColour);
  42697. lastSection = 0;
  42698. }
  42699. else
  42700. {
  42701. i.draw (g, lastSection);
  42702. }
  42703. }
  42704. }
  42705. }
  42706. }
  42707. void TextEditor::paint (Graphics& g)
  42708. {
  42709. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  42710. }
  42711. void TextEditor::paintOverChildren (Graphics& g)
  42712. {
  42713. if (caretFlashState
  42714. && hasKeyboardFocus (false)
  42715. && caretVisible
  42716. && ! isReadOnly())
  42717. {
  42718. g.setColour (findColour (caretColourId));
  42719. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  42720. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  42721. 2.0f, cursorHeight);
  42722. }
  42723. if (textToShowWhenEmpty.isNotEmpty()
  42724. && (! hasKeyboardFocus (false))
  42725. && getTotalNumChars() == 0)
  42726. {
  42727. g.setColour (colourForTextWhenEmpty);
  42728. g.setFont (getFont());
  42729. if (isMultiLine())
  42730. {
  42731. g.drawText (textToShowWhenEmpty,
  42732. 0, 0, getWidth(), getHeight(),
  42733. Justification::centred, true);
  42734. }
  42735. else
  42736. {
  42737. g.drawText (textToShowWhenEmpty,
  42738. leftIndent, topIndent,
  42739. viewport->getWidth() - leftIndent,
  42740. viewport->getHeight() - topIndent,
  42741. Justification::centredLeft, true);
  42742. }
  42743. }
  42744. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  42745. }
  42746. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  42747. {
  42748. public:
  42749. TextEditorMenuPerformer (TextEditor* const editor_)
  42750. : editor (editor_)
  42751. {
  42752. }
  42753. void modalStateFinished (int returnValue)
  42754. {
  42755. if (editor != 0 && returnValue != 0)
  42756. editor->performPopupMenuAction (returnValue);
  42757. }
  42758. private:
  42759. Component::SafePointer<TextEditor> editor;
  42760. TextEditorMenuPerformer (const TextEditorMenuPerformer&);
  42761. TextEditorMenuPerformer& operator= (const TextEditorMenuPerformer&);
  42762. };
  42763. void TextEditor::mouseDown (const MouseEvent& e)
  42764. {
  42765. beginDragAutoRepeat (100);
  42766. newTransaction();
  42767. if (wasFocused || ! selectAllTextWhenFocused)
  42768. {
  42769. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42770. {
  42771. moveCursorTo (getTextIndexAt (e.x, e.y),
  42772. e.mods.isShiftDown());
  42773. }
  42774. else
  42775. {
  42776. PopupMenu m;
  42777. m.setLookAndFeel (&getLookAndFeel());
  42778. addPopupMenuItems (m, &e);
  42779. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  42780. }
  42781. }
  42782. }
  42783. void TextEditor::mouseDrag (const MouseEvent& e)
  42784. {
  42785. if (wasFocused || ! selectAllTextWhenFocused)
  42786. {
  42787. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42788. {
  42789. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  42790. }
  42791. }
  42792. }
  42793. void TextEditor::mouseUp (const MouseEvent& e)
  42794. {
  42795. newTransaction();
  42796. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42797. if (wasFocused || ! selectAllTextWhenFocused)
  42798. {
  42799. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  42800. {
  42801. moveCaret (getTextIndexAt (e.x, e.y));
  42802. }
  42803. }
  42804. wasFocused = true;
  42805. }
  42806. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  42807. {
  42808. int tokenEnd = getTextIndexAt (e.x, e.y);
  42809. int tokenStart = tokenEnd;
  42810. if (e.getNumberOfClicks() > 3)
  42811. {
  42812. tokenStart = 0;
  42813. tokenEnd = getTotalNumChars();
  42814. }
  42815. else
  42816. {
  42817. const String t (getText());
  42818. const int totalLength = getTotalNumChars();
  42819. while (tokenEnd < totalLength)
  42820. {
  42821. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  42822. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  42823. ++tokenEnd;
  42824. else
  42825. break;
  42826. }
  42827. tokenStart = tokenEnd;
  42828. while (tokenStart > 0)
  42829. {
  42830. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  42831. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  42832. --tokenStart;
  42833. else
  42834. break;
  42835. }
  42836. if (e.getNumberOfClicks() > 2)
  42837. {
  42838. while (tokenEnd < totalLength)
  42839. {
  42840. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  42841. ++tokenEnd;
  42842. else
  42843. break;
  42844. }
  42845. while (tokenStart > 0)
  42846. {
  42847. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  42848. --tokenStart;
  42849. else
  42850. break;
  42851. }
  42852. }
  42853. }
  42854. moveCursorTo (tokenEnd, false);
  42855. moveCursorTo (tokenStart, true);
  42856. }
  42857. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  42858. {
  42859. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  42860. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  42861. }
  42862. bool TextEditor::keyPressed (const KeyPress& key)
  42863. {
  42864. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  42865. return false;
  42866. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  42867. if (key.isKeyCode (KeyPress::leftKey)
  42868. || key.isKeyCode (KeyPress::upKey))
  42869. {
  42870. newTransaction();
  42871. int newPos;
  42872. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  42873. newPos = indexAtPosition (cursorX, cursorY - 1);
  42874. else if (moveInWholeWordSteps)
  42875. newPos = findWordBreakBefore (getCaretPosition());
  42876. else
  42877. newPos = getCaretPosition() - 1;
  42878. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42879. }
  42880. else if (key.isKeyCode (KeyPress::rightKey)
  42881. || key.isKeyCode (KeyPress::downKey))
  42882. {
  42883. newTransaction();
  42884. int newPos;
  42885. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  42886. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  42887. else if (moveInWholeWordSteps)
  42888. newPos = findWordBreakAfter (getCaretPosition());
  42889. else
  42890. newPos = getCaretPosition() + 1;
  42891. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42892. }
  42893. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  42894. {
  42895. newTransaction();
  42896. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  42897. key.getModifiers().isShiftDown());
  42898. }
  42899. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  42900. {
  42901. newTransaction();
  42902. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  42903. key.getModifiers().isShiftDown());
  42904. }
  42905. else if (key.isKeyCode (KeyPress::homeKey))
  42906. {
  42907. newTransaction();
  42908. if (isMultiLine() && ! moveInWholeWordSteps)
  42909. moveCursorTo (indexAtPosition (0.0f, cursorY),
  42910. key.getModifiers().isShiftDown());
  42911. else
  42912. moveCursorTo (0, key.getModifiers().isShiftDown());
  42913. }
  42914. else if (key.isKeyCode (KeyPress::endKey))
  42915. {
  42916. newTransaction();
  42917. if (isMultiLine() && ! moveInWholeWordSteps)
  42918. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  42919. key.getModifiers().isShiftDown());
  42920. else
  42921. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  42922. }
  42923. else if (key.isKeyCode (KeyPress::backspaceKey))
  42924. {
  42925. if (moveInWholeWordSteps)
  42926. {
  42927. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  42928. }
  42929. else
  42930. {
  42931. if (selection.isEmpty() && selection.getStart() > 0)
  42932. selection.setStart (selection.getEnd() - 1);
  42933. }
  42934. cut();
  42935. }
  42936. else if (key.isKeyCode (KeyPress::deleteKey))
  42937. {
  42938. if (key.getModifiers().isShiftDown())
  42939. copy();
  42940. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  42941. selection.setEnd (selection.getStart() + 1);
  42942. cut();
  42943. }
  42944. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  42945. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  42946. {
  42947. newTransaction();
  42948. copy();
  42949. }
  42950. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  42951. {
  42952. newTransaction();
  42953. copy();
  42954. cut();
  42955. }
  42956. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  42957. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  42958. {
  42959. newTransaction();
  42960. paste();
  42961. }
  42962. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  42963. {
  42964. newTransaction();
  42965. doUndoRedo (false);
  42966. }
  42967. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  42968. {
  42969. newTransaction();
  42970. doUndoRedo (true);
  42971. }
  42972. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  42973. {
  42974. newTransaction();
  42975. moveCursorTo (getTotalNumChars(), false);
  42976. moveCursorTo (0, true);
  42977. }
  42978. else if (key == KeyPress::returnKey)
  42979. {
  42980. newTransaction();
  42981. insertTextAtCaret ("\n");
  42982. }
  42983. else if (key.isKeyCode (KeyPress::escapeKey))
  42984. {
  42985. newTransaction();
  42986. moveCursorTo (getCaretPosition(), false);
  42987. escapePressed();
  42988. }
  42989. else if (key.getTextCharacter() >= ' '
  42990. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  42991. {
  42992. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  42993. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42994. }
  42995. else
  42996. {
  42997. return false;
  42998. }
  42999. return true;
  43000. }
  43001. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43002. {
  43003. if (! isKeyDown)
  43004. return false;
  43005. #if JUCE_WINDOWS
  43006. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43007. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43008. #endif
  43009. // (overridden to avoid forwarding key events to the parent)
  43010. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43011. }
  43012. const int baseMenuItemID = 0x7fff0000;
  43013. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43014. {
  43015. const bool writable = ! isReadOnly();
  43016. if (passwordCharacter == 0)
  43017. {
  43018. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43019. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43020. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43021. }
  43022. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43023. m.addSeparator();
  43024. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43025. m.addSeparator();
  43026. if (getUndoManager() != 0)
  43027. {
  43028. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43029. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43030. }
  43031. }
  43032. void TextEditor::performPopupMenuAction (const int menuItemID)
  43033. {
  43034. switch (menuItemID)
  43035. {
  43036. case baseMenuItemID + 1:
  43037. copy();
  43038. cut();
  43039. break;
  43040. case baseMenuItemID + 2:
  43041. copy();
  43042. break;
  43043. case baseMenuItemID + 3:
  43044. paste();
  43045. break;
  43046. case baseMenuItemID + 4:
  43047. cut();
  43048. break;
  43049. case baseMenuItemID + 5:
  43050. moveCursorTo (getTotalNumChars(), false);
  43051. moveCursorTo (0, true);
  43052. break;
  43053. case baseMenuItemID + 6:
  43054. doUndoRedo (false);
  43055. break;
  43056. case baseMenuItemID + 7:
  43057. doUndoRedo (true);
  43058. break;
  43059. default:
  43060. break;
  43061. }
  43062. }
  43063. void TextEditor::focusGained (FocusChangeType)
  43064. {
  43065. newTransaction();
  43066. caretFlashState = true;
  43067. if (selectAllTextWhenFocused)
  43068. {
  43069. moveCursorTo (0, false);
  43070. moveCursorTo (getTotalNumChars(), true);
  43071. }
  43072. repaint();
  43073. if (caretVisible)
  43074. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43075. ComponentPeer* const peer = getPeer();
  43076. if (peer != 0 && ! isReadOnly())
  43077. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43078. }
  43079. void TextEditor::focusLost (FocusChangeType)
  43080. {
  43081. newTransaction();
  43082. wasFocused = false;
  43083. textHolder->stopTimer();
  43084. caretFlashState = false;
  43085. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43086. repaint();
  43087. }
  43088. void TextEditor::resized()
  43089. {
  43090. viewport->setBoundsInset (borderSize);
  43091. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43092. updateTextHolderSize();
  43093. if (! isMultiLine())
  43094. {
  43095. scrollToMakeSureCursorIsVisible();
  43096. }
  43097. else
  43098. {
  43099. updateCaretPosition();
  43100. }
  43101. }
  43102. void TextEditor::handleCommandMessage (const int commandId)
  43103. {
  43104. Component::BailOutChecker checker (this);
  43105. switch (commandId)
  43106. {
  43107. case TextEditorDefs::textChangeMessageId:
  43108. listeners.callChecked (checker, &Listener::textEditorTextChanged, (TextEditor&) *this);
  43109. break;
  43110. case TextEditorDefs::returnKeyMessageId:
  43111. listeners.callChecked (checker, &Listener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43112. break;
  43113. case TextEditorDefs::escapeKeyMessageId:
  43114. listeners.callChecked (checker, &Listener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43115. break;
  43116. case TextEditorDefs::focusLossMessageId:
  43117. listeners.callChecked (checker, &Listener::textEditorFocusLost, (TextEditor&) *this);
  43118. break;
  43119. default:
  43120. jassertfalse;
  43121. break;
  43122. }
  43123. }
  43124. void TextEditor::enablementChanged()
  43125. {
  43126. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43127. : MouseCursor::IBeamCursor);
  43128. repaint();
  43129. }
  43130. UndoManager* TextEditor::getUndoManager() throw()
  43131. {
  43132. return isReadOnly() ? 0 : &undoManager;
  43133. }
  43134. void TextEditor::clearInternal (UndoManager* const um)
  43135. {
  43136. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43137. }
  43138. void TextEditor::insert (const String& text,
  43139. const int insertIndex,
  43140. const Font& font,
  43141. const Colour& colour,
  43142. UndoManager* const um,
  43143. const int caretPositionToMoveTo)
  43144. {
  43145. if (text.isNotEmpty())
  43146. {
  43147. if (um != 0)
  43148. {
  43149. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43150. newTransaction();
  43151. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43152. caretPosition, caretPositionToMoveTo));
  43153. }
  43154. else
  43155. {
  43156. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43157. // a line gets moved due to word wrap
  43158. int index = 0;
  43159. int nextIndex = 0;
  43160. for (int i = 0; i < sections.size(); ++i)
  43161. {
  43162. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43163. if (insertIndex == index)
  43164. {
  43165. sections.insert (i, new UniformTextSection (text,
  43166. font, colour,
  43167. passwordCharacter));
  43168. break;
  43169. }
  43170. else if (insertIndex > index && insertIndex < nextIndex)
  43171. {
  43172. splitSection (i, insertIndex - index);
  43173. sections.insert (i + 1, new UniformTextSection (text,
  43174. font, colour,
  43175. passwordCharacter));
  43176. break;
  43177. }
  43178. index = nextIndex;
  43179. }
  43180. if (nextIndex == insertIndex)
  43181. sections.add (new UniformTextSection (text,
  43182. font, colour,
  43183. passwordCharacter));
  43184. coalesceSimilarSections();
  43185. totalNumChars = -1;
  43186. valueTextNeedsUpdating = true;
  43187. moveCursorTo (caretPositionToMoveTo, false);
  43188. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43189. }
  43190. }
  43191. }
  43192. void TextEditor::reinsert (const int insertIndex,
  43193. const Array <UniformTextSection*>& sectionsToInsert)
  43194. {
  43195. int index = 0;
  43196. int nextIndex = 0;
  43197. for (int i = 0; i < sections.size(); ++i)
  43198. {
  43199. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43200. if (insertIndex == index)
  43201. {
  43202. for (int j = sectionsToInsert.size(); --j >= 0;)
  43203. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43204. break;
  43205. }
  43206. else if (insertIndex > index && insertIndex < nextIndex)
  43207. {
  43208. splitSection (i, insertIndex - index);
  43209. for (int j = sectionsToInsert.size(); --j >= 0;)
  43210. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43211. break;
  43212. }
  43213. index = nextIndex;
  43214. }
  43215. if (nextIndex == insertIndex)
  43216. {
  43217. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43218. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43219. }
  43220. coalesceSimilarSections();
  43221. totalNumChars = -1;
  43222. valueTextNeedsUpdating = true;
  43223. }
  43224. void TextEditor::remove (const Range<int>& range,
  43225. UndoManager* const um,
  43226. const int caretPositionToMoveTo)
  43227. {
  43228. if (! range.isEmpty())
  43229. {
  43230. int index = 0;
  43231. for (int i = 0; i < sections.size(); ++i)
  43232. {
  43233. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43234. if (range.getStart() > index && range.getStart() < nextIndex)
  43235. {
  43236. splitSection (i, range.getStart() - index);
  43237. --i;
  43238. }
  43239. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43240. {
  43241. splitSection (i, range.getEnd() - index);
  43242. --i;
  43243. }
  43244. else
  43245. {
  43246. index = nextIndex;
  43247. if (index > range.getEnd())
  43248. break;
  43249. }
  43250. }
  43251. index = 0;
  43252. if (um != 0)
  43253. {
  43254. Array <UniformTextSection*> removedSections;
  43255. for (int i = 0; i < sections.size(); ++i)
  43256. {
  43257. if (range.getEnd() <= range.getStart())
  43258. break;
  43259. UniformTextSection* const section = sections.getUnchecked (i);
  43260. const int nextIndex = index + section->getTotalLength();
  43261. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43262. removedSections.add (new UniformTextSection (*section));
  43263. index = nextIndex;
  43264. }
  43265. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43266. newTransaction();
  43267. um->perform (new RemoveAction (*this, range, caretPosition,
  43268. caretPositionToMoveTo, removedSections));
  43269. }
  43270. else
  43271. {
  43272. Range<int> remainingRange (range);
  43273. for (int i = 0; i < sections.size(); ++i)
  43274. {
  43275. UniformTextSection* const section = sections.getUnchecked (i);
  43276. const int nextIndex = index + section->getTotalLength();
  43277. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43278. {
  43279. sections.remove(i);
  43280. section->clear();
  43281. delete section;
  43282. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43283. if (remainingRange.isEmpty())
  43284. break;
  43285. --i;
  43286. }
  43287. else
  43288. {
  43289. index = nextIndex;
  43290. }
  43291. }
  43292. coalesceSimilarSections();
  43293. totalNumChars = -1;
  43294. valueTextNeedsUpdating = true;
  43295. moveCursorTo (caretPositionToMoveTo, false);
  43296. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43297. }
  43298. }
  43299. }
  43300. const String TextEditor::getText() const
  43301. {
  43302. String t;
  43303. t.preallocateStorage (getTotalNumChars());
  43304. String::Concatenator concatenator (t);
  43305. for (int i = 0; i < sections.size(); ++i)
  43306. sections.getUnchecked (i)->appendAllText (concatenator);
  43307. return t;
  43308. }
  43309. const String TextEditor::getTextInRange (const Range<int>& range) const
  43310. {
  43311. String t;
  43312. if (! range.isEmpty())
  43313. {
  43314. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43315. String::Concatenator concatenator (t);
  43316. int index = 0;
  43317. for (int i = 0; i < sections.size(); ++i)
  43318. {
  43319. const UniformTextSection* const s = sections.getUnchecked (i);
  43320. const int nextIndex = index + s->getTotalLength();
  43321. if (range.getStart() < nextIndex)
  43322. {
  43323. if (range.getEnd() <= index)
  43324. break;
  43325. s->appendSubstring (concatenator, range - index);
  43326. }
  43327. index = nextIndex;
  43328. }
  43329. }
  43330. return t;
  43331. }
  43332. const String TextEditor::getHighlightedText() const
  43333. {
  43334. return getTextInRange (selection);
  43335. }
  43336. int TextEditor::getTotalNumChars() const
  43337. {
  43338. if (totalNumChars < 0)
  43339. {
  43340. totalNumChars = 0;
  43341. for (int i = sections.size(); --i >= 0;)
  43342. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43343. }
  43344. return totalNumChars;
  43345. }
  43346. bool TextEditor::isEmpty() const
  43347. {
  43348. return getTotalNumChars() == 0;
  43349. }
  43350. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43351. {
  43352. const float wordWrapWidth = getWordWrapWidth();
  43353. if (wordWrapWidth > 0 && sections.size() > 0)
  43354. {
  43355. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43356. i.getCharPosition (index, cx, cy, lineHeight);
  43357. }
  43358. else
  43359. {
  43360. cx = cy = 0;
  43361. lineHeight = currentFont.getHeight();
  43362. }
  43363. }
  43364. int TextEditor::indexAtPosition (const float x, const float y)
  43365. {
  43366. const float wordWrapWidth = getWordWrapWidth();
  43367. if (wordWrapWidth > 0)
  43368. {
  43369. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43370. while (i.next())
  43371. {
  43372. if (i.lineY + i.lineHeight > y)
  43373. {
  43374. if (i.lineY > y)
  43375. return jmax (0, i.indexInText - 1);
  43376. if (i.atomX >= x)
  43377. return i.indexInText;
  43378. if (x < i.atomRight)
  43379. return i.xToIndex (x);
  43380. }
  43381. }
  43382. }
  43383. return getTotalNumChars();
  43384. }
  43385. static int getCharacterCategory (const juce_wchar character)
  43386. {
  43387. return CharacterFunctions::isLetterOrDigit (character)
  43388. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  43389. }
  43390. int TextEditor::findWordBreakAfter (const int position) const
  43391. {
  43392. const String t (getTextInRange (Range<int> (position, position + 512)));
  43393. const int totalLength = t.length();
  43394. int i = 0;
  43395. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43396. ++i;
  43397. const int type = getCharacterCategory (t[i]);
  43398. while (i < totalLength && type == getCharacterCategory (t[i]))
  43399. ++i;
  43400. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43401. ++i;
  43402. return position + i;
  43403. }
  43404. int TextEditor::findWordBreakBefore (const int position) const
  43405. {
  43406. if (position <= 0)
  43407. return 0;
  43408. const int startOfBuffer = jmax (0, position - 512);
  43409. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43410. int i = position - startOfBuffer;
  43411. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43412. --i;
  43413. if (i > 0)
  43414. {
  43415. const int type = getCharacterCategory (t [i - 1]);
  43416. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  43417. --i;
  43418. }
  43419. jassert (startOfBuffer + i >= 0);
  43420. return startOfBuffer + i;
  43421. }
  43422. void TextEditor::splitSection (const int sectionIndex,
  43423. const int charToSplitAt)
  43424. {
  43425. jassert (sections[sectionIndex] != 0);
  43426. sections.insert (sectionIndex + 1,
  43427. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43428. }
  43429. void TextEditor::coalesceSimilarSections()
  43430. {
  43431. for (int i = 0; i < sections.size() - 1; ++i)
  43432. {
  43433. UniformTextSection* const s1 = sections.getUnchecked (i);
  43434. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  43435. if (s1->font == s2->font
  43436. && s1->colour == s2->colour)
  43437. {
  43438. s1->append (*s2, passwordCharacter);
  43439. sections.remove (i + 1);
  43440. delete s2;
  43441. --i;
  43442. }
  43443. }
  43444. }
  43445. END_JUCE_NAMESPACE
  43446. /*** End of inlined file: juce_TextEditor.cpp ***/
  43447. /*** Start of inlined file: juce_Toolbar.cpp ***/
  43448. BEGIN_JUCE_NAMESPACE
  43449. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  43450. class ToolbarSpacerComp : public ToolbarItemComponent
  43451. {
  43452. public:
  43453. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  43454. : ToolbarItemComponent (itemId_, String::empty, false),
  43455. fixedSize (fixedSize_),
  43456. drawBar (drawBar_)
  43457. {
  43458. }
  43459. ~ToolbarSpacerComp()
  43460. {
  43461. }
  43462. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  43463. int& preferredSize, int& minSize, int& maxSize)
  43464. {
  43465. if (fixedSize <= 0)
  43466. {
  43467. preferredSize = toolbarThickness * 2;
  43468. minSize = 4;
  43469. maxSize = 32768;
  43470. }
  43471. else
  43472. {
  43473. maxSize = roundToInt (toolbarThickness * fixedSize);
  43474. minSize = drawBar ? maxSize : jmin (4, maxSize);
  43475. preferredSize = maxSize;
  43476. if (getEditingMode() == editableOnPalette)
  43477. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  43478. }
  43479. return true;
  43480. }
  43481. void paintButtonArea (Graphics&, int, int, bool, bool)
  43482. {
  43483. }
  43484. void contentAreaChanged (const Rectangle<int>&)
  43485. {
  43486. }
  43487. int getResizeOrder() const throw()
  43488. {
  43489. return fixedSize <= 0 ? 0 : 1;
  43490. }
  43491. void paint (Graphics& g)
  43492. {
  43493. const int w = getWidth();
  43494. const int h = getHeight();
  43495. if (drawBar)
  43496. {
  43497. g.setColour (findColour (Toolbar::separatorColourId, true));
  43498. const float thickness = 0.2f;
  43499. if (isToolbarVertical())
  43500. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  43501. else
  43502. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  43503. }
  43504. if (getEditingMode() != normalMode && ! drawBar)
  43505. {
  43506. g.setColour (findColour (Toolbar::separatorColourId, true));
  43507. const int indentX = jmin (2, (w - 3) / 2);
  43508. const int indentY = jmin (2, (h - 3) / 2);
  43509. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  43510. if (fixedSize <= 0)
  43511. {
  43512. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  43513. if (isToolbarVertical())
  43514. {
  43515. x1 = w * 0.5f;
  43516. y1 = h * 0.4f;
  43517. x2 = x1;
  43518. y2 = indentX * 2.0f;
  43519. x3 = x1;
  43520. y3 = h * 0.6f;
  43521. x4 = x1;
  43522. y4 = h - y2;
  43523. hw = w * 0.15f;
  43524. hl = w * 0.2f;
  43525. }
  43526. else
  43527. {
  43528. x1 = w * 0.4f;
  43529. y1 = h * 0.5f;
  43530. x2 = indentX * 2.0f;
  43531. y2 = y1;
  43532. x3 = w * 0.6f;
  43533. y3 = y1;
  43534. x4 = w - x2;
  43535. y4 = y1;
  43536. hw = h * 0.15f;
  43537. hl = h * 0.2f;
  43538. }
  43539. Path p;
  43540. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  43541. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  43542. g.fillPath (p);
  43543. }
  43544. }
  43545. }
  43546. juce_UseDebuggingNewOperator
  43547. private:
  43548. const float fixedSize;
  43549. const bool drawBar;
  43550. ToolbarSpacerComp (const ToolbarSpacerComp&);
  43551. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  43552. };
  43553. class Toolbar::MissingItemsComponent : public PopupMenuCustomComponent
  43554. {
  43555. public:
  43556. MissingItemsComponent (Toolbar& owner_, const int height_)
  43557. : PopupMenuCustomComponent (true),
  43558. owner (owner_),
  43559. height (height_)
  43560. {
  43561. for (int i = owner_.items.size(); --i >= 0;)
  43562. {
  43563. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  43564. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  43565. {
  43566. oldIndexes.insert (0, i);
  43567. addAndMakeVisible (tc, 0);
  43568. }
  43569. }
  43570. layout (400);
  43571. }
  43572. ~MissingItemsComponent()
  43573. {
  43574. // deleting the toolbar while its menu it open??
  43575. jassert (owner.isValidComponent());
  43576. for (int i = 0; i < getNumChildComponents(); ++i)
  43577. {
  43578. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43579. if (tc != 0)
  43580. {
  43581. tc->setVisible (false);
  43582. const int index = oldIndexes.remove (i);
  43583. owner.addChildComponent (tc, index);
  43584. --i;
  43585. }
  43586. }
  43587. owner.resized();
  43588. }
  43589. void layout (const int preferredWidth)
  43590. {
  43591. const int indent = 8;
  43592. int x = indent;
  43593. int y = indent;
  43594. int maxX = 0;
  43595. for (int i = 0; i < getNumChildComponents(); ++i)
  43596. {
  43597. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43598. if (tc != 0)
  43599. {
  43600. int preferredSize = 1, minSize = 1, maxSize = 1;
  43601. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  43602. {
  43603. if (x + preferredSize > preferredWidth && x > indent)
  43604. {
  43605. x = indent;
  43606. y += height;
  43607. }
  43608. tc->setBounds (x, y, preferredSize, height);
  43609. x += preferredSize;
  43610. maxX = jmax (maxX, x);
  43611. }
  43612. }
  43613. }
  43614. setSize (maxX + 8, y + height + 8);
  43615. }
  43616. void getIdealSize (int& idealWidth, int& idealHeight)
  43617. {
  43618. idealWidth = getWidth();
  43619. idealHeight = getHeight();
  43620. }
  43621. juce_UseDebuggingNewOperator
  43622. private:
  43623. Toolbar& owner;
  43624. const int height;
  43625. Array <int> oldIndexes;
  43626. MissingItemsComponent (const MissingItemsComponent&);
  43627. MissingItemsComponent& operator= (const MissingItemsComponent&);
  43628. };
  43629. Toolbar::Toolbar()
  43630. : vertical (false),
  43631. isEditingActive (false),
  43632. toolbarStyle (Toolbar::iconsOnly)
  43633. {
  43634. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  43635. missingItemsButton->setAlwaysOnTop (true);
  43636. missingItemsButton->addButtonListener (this);
  43637. }
  43638. Toolbar::~Toolbar()
  43639. {
  43640. animator.cancelAllAnimations (true);
  43641. deleteAllChildren();
  43642. }
  43643. void Toolbar::setVertical (const bool shouldBeVertical)
  43644. {
  43645. if (vertical != shouldBeVertical)
  43646. {
  43647. vertical = shouldBeVertical;
  43648. resized();
  43649. }
  43650. }
  43651. void Toolbar::clear()
  43652. {
  43653. for (int i = items.size(); --i >= 0;)
  43654. {
  43655. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43656. items.remove (i);
  43657. delete tc;
  43658. }
  43659. resized();
  43660. }
  43661. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  43662. {
  43663. if (itemId == ToolbarItemFactory::separatorBarId)
  43664. return new ToolbarSpacerComp (itemId, 0.1f, true);
  43665. else if (itemId == ToolbarItemFactory::spacerId)
  43666. return new ToolbarSpacerComp (itemId, 0.5f, false);
  43667. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  43668. return new ToolbarSpacerComp (itemId, 0, false);
  43669. return factory.createItem (itemId);
  43670. }
  43671. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  43672. const int itemId,
  43673. const int insertIndex)
  43674. {
  43675. // An ID can't be zero - this might indicate a mistake somewhere?
  43676. jassert (itemId != 0);
  43677. ToolbarItemComponent* const tc = createItem (factory, itemId);
  43678. if (tc != 0)
  43679. {
  43680. #if JUCE_DEBUG
  43681. Array <int> allowedIds;
  43682. factory.getAllToolbarItemIds (allowedIds);
  43683. // If your factory can create an item for a given ID, it must also return
  43684. // that ID from its getAllToolbarItemIds() method!
  43685. jassert (allowedIds.contains (itemId));
  43686. #endif
  43687. items.insert (insertIndex, tc);
  43688. addAndMakeVisible (tc, insertIndex);
  43689. }
  43690. }
  43691. void Toolbar::addItem (ToolbarItemFactory& factory,
  43692. const int itemId,
  43693. const int insertIndex)
  43694. {
  43695. addItemInternal (factory, itemId, insertIndex);
  43696. resized();
  43697. }
  43698. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  43699. {
  43700. Array <int> ids;
  43701. factoryToUse.getDefaultItemSet (ids);
  43702. clear();
  43703. for (int i = 0; i < ids.size(); ++i)
  43704. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  43705. resized();
  43706. }
  43707. void Toolbar::removeToolbarItem (const int itemIndex)
  43708. {
  43709. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43710. if (tc != 0)
  43711. {
  43712. items.removeValue (tc);
  43713. delete tc;
  43714. resized();
  43715. }
  43716. }
  43717. int Toolbar::getNumItems() const throw()
  43718. {
  43719. return items.size();
  43720. }
  43721. int Toolbar::getItemId (const int itemIndex) const throw()
  43722. {
  43723. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43724. return tc != 0 ? tc->getItemId() : 0;
  43725. }
  43726. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  43727. {
  43728. return items [itemIndex];
  43729. }
  43730. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  43731. {
  43732. for (;;)
  43733. {
  43734. index += delta;
  43735. ToolbarItemComponent* const tc = getItemComponent (index);
  43736. if (tc == 0)
  43737. break;
  43738. if (tc->isActive)
  43739. return tc;
  43740. }
  43741. return 0;
  43742. }
  43743. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  43744. {
  43745. if (toolbarStyle != newStyle)
  43746. {
  43747. toolbarStyle = newStyle;
  43748. updateAllItemPositions (false);
  43749. }
  43750. }
  43751. const String Toolbar::toString() const
  43752. {
  43753. String s ("TB:");
  43754. for (int i = 0; i < getNumItems(); ++i)
  43755. s << getItemId(i) << ' ';
  43756. return s.trimEnd();
  43757. }
  43758. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  43759. const String& savedVersion)
  43760. {
  43761. if (! savedVersion.startsWith ("TB:"))
  43762. return false;
  43763. StringArray tokens;
  43764. tokens.addTokens (savedVersion.substring (3), false);
  43765. clear();
  43766. for (int i = 0; i < tokens.size(); ++i)
  43767. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  43768. resized();
  43769. return true;
  43770. }
  43771. void Toolbar::paint (Graphics& g)
  43772. {
  43773. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  43774. }
  43775. int Toolbar::getThickness() const throw()
  43776. {
  43777. return vertical ? getWidth() : getHeight();
  43778. }
  43779. int Toolbar::getLength() const throw()
  43780. {
  43781. return vertical ? getHeight() : getWidth();
  43782. }
  43783. void Toolbar::setEditingActive (const bool active)
  43784. {
  43785. if (isEditingActive != active)
  43786. {
  43787. isEditingActive = active;
  43788. updateAllItemPositions (false);
  43789. }
  43790. }
  43791. void Toolbar::resized()
  43792. {
  43793. updateAllItemPositions (false);
  43794. }
  43795. void Toolbar::updateAllItemPositions (const bool animate)
  43796. {
  43797. if (getWidth() > 0 && getHeight() > 0)
  43798. {
  43799. StretchableObjectResizer resizer;
  43800. int i;
  43801. for (i = 0; i < items.size(); ++i)
  43802. {
  43803. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43804. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  43805. : ToolbarItemComponent::normalMode);
  43806. tc->setStyle (toolbarStyle);
  43807. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  43808. int preferredSize = 1, minSize = 1, maxSize = 1;
  43809. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  43810. preferredSize, minSize, maxSize))
  43811. {
  43812. tc->isActive = true;
  43813. resizer.addItem (preferredSize, minSize, maxSize,
  43814. spacer != 0 ? spacer->getResizeOrder() : 2);
  43815. }
  43816. else
  43817. {
  43818. tc->isActive = false;
  43819. tc->setVisible (false);
  43820. }
  43821. }
  43822. resizer.resizeToFit (getLength());
  43823. int totalLength = 0;
  43824. for (i = 0; i < resizer.getNumItems(); ++i)
  43825. totalLength += (int) resizer.getItemSize (i);
  43826. const bool itemsOffTheEnd = totalLength > getLength();
  43827. const int extrasButtonSize = getThickness() / 2;
  43828. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  43829. missingItemsButton->setVisible (itemsOffTheEnd);
  43830. missingItemsButton->setEnabled (! isEditingActive);
  43831. if (vertical)
  43832. missingItemsButton->setCentrePosition (getWidth() / 2,
  43833. getHeight() - 4 - extrasButtonSize / 2);
  43834. else
  43835. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  43836. getHeight() / 2);
  43837. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  43838. : missingItemsButton->getX()) - 4
  43839. : getLength();
  43840. int pos = 0, activeIndex = 0;
  43841. for (i = 0; i < items.size(); ++i)
  43842. {
  43843. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43844. if (tc->isActive)
  43845. {
  43846. const int size = (int) resizer.getItemSize (activeIndex++);
  43847. Rectangle<int> newBounds;
  43848. if (vertical)
  43849. newBounds.setBounds (0, pos, getWidth(), size);
  43850. else
  43851. newBounds.setBounds (pos, 0, size, getHeight());
  43852. if (animate)
  43853. {
  43854. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  43855. }
  43856. else
  43857. {
  43858. animator.cancelAnimation (tc, false);
  43859. tc->setBounds (newBounds);
  43860. }
  43861. pos += size;
  43862. tc->setVisible (pos <= maxLength
  43863. && ((! tc->isBeingDragged)
  43864. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  43865. }
  43866. }
  43867. }
  43868. }
  43869. void Toolbar::buttonClicked (Button*)
  43870. {
  43871. jassert (missingItemsButton->isShowing());
  43872. if (missingItemsButton->isShowing())
  43873. {
  43874. PopupMenu m;
  43875. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  43876. m.showAt (missingItemsButton);
  43877. }
  43878. }
  43879. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  43880. Component* /*sourceComponent*/)
  43881. {
  43882. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  43883. }
  43884. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  43885. {
  43886. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43887. if (tc != 0)
  43888. {
  43889. if (getNumItems() == 0)
  43890. {
  43891. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43892. {
  43893. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43894. if (palette != 0)
  43895. palette->replaceComponent (tc);
  43896. }
  43897. else
  43898. {
  43899. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43900. }
  43901. items.add (tc);
  43902. addChildComponent (tc);
  43903. updateAllItemPositions (false);
  43904. }
  43905. else
  43906. {
  43907. for (int i = getNumItems(); --i >= 0;)
  43908. {
  43909. int currentIndex = getIndexOfChildComponent (tc);
  43910. if (currentIndex < 0)
  43911. {
  43912. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43913. {
  43914. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43915. if (palette != 0)
  43916. palette->replaceComponent (tc);
  43917. }
  43918. else
  43919. {
  43920. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43921. }
  43922. items.add (tc);
  43923. addChildComponent (tc);
  43924. currentIndex = getIndexOfChildComponent (tc);
  43925. updateAllItemPositions (true);
  43926. }
  43927. int newIndex = currentIndex;
  43928. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  43929. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  43930. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  43931. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  43932. if (prev != 0)
  43933. {
  43934. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  43935. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  43936. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  43937. {
  43938. newIndex = getIndexOfChildComponent (prev);
  43939. }
  43940. }
  43941. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  43942. if (next != 0)
  43943. {
  43944. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  43945. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  43946. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  43947. {
  43948. newIndex = getIndexOfChildComponent (next) + 1;
  43949. }
  43950. }
  43951. if (newIndex != currentIndex)
  43952. {
  43953. items.removeValue (tc);
  43954. removeChildComponent (tc);
  43955. addChildComponent (tc, newIndex);
  43956. items.insert (newIndex, tc);
  43957. updateAllItemPositions (true);
  43958. }
  43959. else
  43960. {
  43961. break;
  43962. }
  43963. }
  43964. }
  43965. }
  43966. }
  43967. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  43968. {
  43969. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43970. if (tc != 0)
  43971. {
  43972. if (isParentOf (tc))
  43973. {
  43974. items.removeValue (tc);
  43975. removeChildComponent (tc);
  43976. updateAllItemPositions (true);
  43977. }
  43978. }
  43979. }
  43980. void Toolbar::itemDropped (const String&, Component*, int, int)
  43981. {
  43982. }
  43983. void Toolbar::mouseDown (const MouseEvent& e)
  43984. {
  43985. if (e.mods.isPopupMenu())
  43986. {
  43987. }
  43988. }
  43989. class ToolbarCustomisationDialog : public DialogWindow
  43990. {
  43991. public:
  43992. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  43993. Toolbar* const toolbar_,
  43994. const int optionFlags)
  43995. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  43996. toolbar (toolbar_)
  43997. {
  43998. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  43999. setResizable (true, true);
  44000. setResizeLimits (400, 300, 1500, 1000);
  44001. positionNearBar();
  44002. }
  44003. ~ToolbarCustomisationDialog()
  44004. {
  44005. setContentComponent (0, true);
  44006. }
  44007. void closeButtonPressed()
  44008. {
  44009. setVisible (false);
  44010. }
  44011. bool canModalEventBeSentToComponent (const Component* comp)
  44012. {
  44013. return toolbar->isParentOf (comp);
  44014. }
  44015. void positionNearBar()
  44016. {
  44017. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44018. const int tbx = toolbar->getScreenX();
  44019. const int tby = toolbar->getScreenY();
  44020. const int gap = 8;
  44021. int x, y;
  44022. if (toolbar->isVertical())
  44023. {
  44024. y = tby;
  44025. if (tbx > screenSize.getCentreX())
  44026. x = tbx - getWidth() - gap;
  44027. else
  44028. x = tbx + toolbar->getWidth() + gap;
  44029. }
  44030. else
  44031. {
  44032. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44033. if (tby > screenSize.getCentreY())
  44034. y = tby - getHeight() - gap;
  44035. else
  44036. y = tby + toolbar->getHeight() + gap;
  44037. }
  44038. setTopLeftPosition (x, y);
  44039. }
  44040. private:
  44041. Toolbar* const toolbar;
  44042. class CustomiserPanel : public Component,
  44043. private ComboBox::Listener,
  44044. private Button::Listener
  44045. {
  44046. public:
  44047. CustomiserPanel (ToolbarItemFactory& factory_,
  44048. Toolbar* const toolbar_,
  44049. const int optionFlags)
  44050. : factory (factory_),
  44051. toolbar (toolbar_),
  44052. styleBox (0),
  44053. defaultButton (0)
  44054. {
  44055. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  44056. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44057. | Toolbar::allowIconsWithTextChoice
  44058. | Toolbar::allowTextOnlyChoice)) != 0)
  44059. {
  44060. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  44061. styleBox->setEditableText (false);
  44062. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  44063. styleBox->addItem (TRANS("Show icons only"), 1);
  44064. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  44065. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  44066. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  44067. styleBox->addItem (TRANS("Show descriptions only"), 3);
  44068. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  44069. styleBox->setSelectedId (1);
  44070. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  44071. styleBox->setSelectedId (2);
  44072. else if (toolbar_->getStyle() == Toolbar::textOnly)
  44073. styleBox->setSelectedId (3);
  44074. styleBox->addListener (this);
  44075. }
  44076. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44077. {
  44078. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  44079. defaultButton->addButtonListener (this);
  44080. }
  44081. addAndMakeVisible (instructions = new Label (String::empty,
  44082. 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.")));
  44083. instructions->setFont (Font (13.0f));
  44084. setSize (500, 300);
  44085. }
  44086. ~CustomiserPanel()
  44087. {
  44088. deleteAllChildren();
  44089. }
  44090. void comboBoxChanged (ComboBox*)
  44091. {
  44092. if (styleBox->getSelectedId() == 1)
  44093. toolbar->setStyle (Toolbar::iconsOnly);
  44094. else if (styleBox->getSelectedId() == 2)
  44095. toolbar->setStyle (Toolbar::iconsWithText);
  44096. else if (styleBox->getSelectedId() == 3)
  44097. toolbar->setStyle (Toolbar::textOnly);
  44098. palette->resized(); // to make it update the styles
  44099. }
  44100. void buttonClicked (Button*)
  44101. {
  44102. toolbar->addDefaultItems (factory);
  44103. }
  44104. void paint (Graphics& g)
  44105. {
  44106. Colour background;
  44107. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44108. if (dw != 0)
  44109. background = dw->getBackgroundColour();
  44110. g.setColour (background.contrasting().withAlpha (0.3f));
  44111. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  44112. }
  44113. void resized()
  44114. {
  44115. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  44116. if (styleBox != 0)
  44117. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  44118. if (defaultButton != 0)
  44119. {
  44120. defaultButton->changeWidthToFitText (22);
  44121. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  44122. }
  44123. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44124. }
  44125. private:
  44126. ToolbarItemFactory& factory;
  44127. Toolbar* const toolbar;
  44128. Label* instructions;
  44129. ToolbarItemPalette* palette;
  44130. ComboBox* styleBox;
  44131. TextButton* defaultButton;
  44132. };
  44133. };
  44134. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44135. {
  44136. setEditingActive (true);
  44137. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44138. dw.runModalLoop();
  44139. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  44140. setEditingActive (false);
  44141. }
  44142. END_JUCE_NAMESPACE
  44143. /*** End of inlined file: juce_Toolbar.cpp ***/
  44144. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44145. BEGIN_JUCE_NAMESPACE
  44146. ToolbarItemFactory::ToolbarItemFactory()
  44147. {
  44148. }
  44149. ToolbarItemFactory::~ToolbarItemFactory()
  44150. {
  44151. }
  44152. class ItemDragAndDropOverlayComponent : public Component
  44153. {
  44154. public:
  44155. ItemDragAndDropOverlayComponent()
  44156. : isDragging (false)
  44157. {
  44158. setAlwaysOnTop (true);
  44159. setRepaintsOnMouseActivity (true);
  44160. setMouseCursor (MouseCursor::DraggingHandCursor);
  44161. }
  44162. ~ItemDragAndDropOverlayComponent()
  44163. {
  44164. }
  44165. void paint (Graphics& g)
  44166. {
  44167. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44168. if (isMouseOverOrDragging()
  44169. && tc != 0
  44170. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44171. {
  44172. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44173. g.drawRect (0, 0, getWidth(), getHeight(),
  44174. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44175. }
  44176. }
  44177. void mouseDown (const MouseEvent& e)
  44178. {
  44179. isDragging = false;
  44180. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44181. if (tc != 0)
  44182. {
  44183. tc->dragOffsetX = e.x;
  44184. tc->dragOffsetY = e.y;
  44185. }
  44186. }
  44187. void mouseDrag (const MouseEvent& e)
  44188. {
  44189. if (! (isDragging || e.mouseWasClicked()))
  44190. {
  44191. isDragging = true;
  44192. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44193. if (dnd != 0)
  44194. {
  44195. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  44196. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44197. if (tc != 0)
  44198. {
  44199. tc->isBeingDragged = true;
  44200. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44201. tc->setVisible (false);
  44202. }
  44203. }
  44204. }
  44205. }
  44206. void mouseUp (const MouseEvent&)
  44207. {
  44208. isDragging = false;
  44209. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44210. if (tc != 0)
  44211. {
  44212. tc->isBeingDragged = false;
  44213. Toolbar* const tb = tc->getToolbar();
  44214. if (tb != 0)
  44215. tb->updateAllItemPositions (true);
  44216. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44217. delete tc;
  44218. }
  44219. }
  44220. void parentSizeChanged()
  44221. {
  44222. setBounds (0, 0, getParentWidth(), getParentHeight());
  44223. }
  44224. juce_UseDebuggingNewOperator
  44225. private:
  44226. bool isDragging;
  44227. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  44228. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  44229. };
  44230. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44231. const String& labelText,
  44232. const bool isBeingUsedAsAButton_)
  44233. : Button (labelText),
  44234. itemId (itemId_),
  44235. mode (normalMode),
  44236. toolbarStyle (Toolbar::iconsOnly),
  44237. dragOffsetX (0),
  44238. dragOffsetY (0),
  44239. isActive (true),
  44240. isBeingDragged (false),
  44241. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44242. {
  44243. // Your item ID can't be 0!
  44244. jassert (itemId_ != 0);
  44245. }
  44246. ToolbarItemComponent::~ToolbarItemComponent()
  44247. {
  44248. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44249. overlayComp = 0;
  44250. }
  44251. Toolbar* ToolbarItemComponent::getToolbar() const
  44252. {
  44253. return dynamic_cast <Toolbar*> (getParentComponent());
  44254. }
  44255. bool ToolbarItemComponent::isToolbarVertical() const
  44256. {
  44257. const Toolbar* const t = getToolbar();
  44258. return t != 0 && t->isVertical();
  44259. }
  44260. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44261. {
  44262. if (toolbarStyle != newStyle)
  44263. {
  44264. toolbarStyle = newStyle;
  44265. repaint();
  44266. resized();
  44267. }
  44268. }
  44269. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44270. {
  44271. if (isBeingUsedAsAButton)
  44272. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44273. over, down, *this);
  44274. if (toolbarStyle != Toolbar::iconsOnly)
  44275. {
  44276. const int indent = contentArea.getX();
  44277. int y = indent;
  44278. int h = getHeight() - indent * 2;
  44279. if (toolbarStyle == Toolbar::iconsWithText)
  44280. {
  44281. y = contentArea.getBottom() + indent / 2;
  44282. h -= contentArea.getHeight();
  44283. }
  44284. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44285. getButtonText(), *this);
  44286. }
  44287. if (! contentArea.isEmpty())
  44288. {
  44289. g.saveState();
  44290. g.setOrigin (contentArea.getX(), contentArea.getY());
  44291. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  44292. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44293. g.restoreState();
  44294. }
  44295. }
  44296. void ToolbarItemComponent::resized()
  44297. {
  44298. if (toolbarStyle != Toolbar::textOnly)
  44299. {
  44300. const int indent = jmin (proportionOfWidth (0.08f),
  44301. proportionOfHeight (0.08f));
  44302. contentArea = Rectangle<int> (indent, indent,
  44303. getWidth() - indent * 2,
  44304. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44305. : (getHeight() - indent * 2));
  44306. }
  44307. else
  44308. {
  44309. contentArea = Rectangle<int>();
  44310. }
  44311. contentAreaChanged (contentArea);
  44312. }
  44313. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44314. {
  44315. if (mode != newMode)
  44316. {
  44317. mode = newMode;
  44318. repaint();
  44319. if (mode == normalMode)
  44320. {
  44321. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44322. overlayComp = 0;
  44323. }
  44324. else if (overlayComp == 0)
  44325. {
  44326. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44327. overlayComp->parentSizeChanged();
  44328. }
  44329. resized();
  44330. }
  44331. }
  44332. END_JUCE_NAMESPACE
  44333. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44334. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44335. BEGIN_JUCE_NAMESPACE
  44336. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44337. Toolbar* const toolbar_)
  44338. : factory (factory_),
  44339. toolbar (toolbar_)
  44340. {
  44341. Component* const itemHolder = new Component();
  44342. Array <int> allIds;
  44343. factory_.getAllToolbarItemIds (allIds);
  44344. for (int i = 0; i < allIds.size(); ++i)
  44345. {
  44346. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  44347. jassert (tc != 0);
  44348. if (tc != 0)
  44349. {
  44350. itemHolder->addAndMakeVisible (tc);
  44351. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44352. }
  44353. }
  44354. viewport = new Viewport();
  44355. viewport->setViewedComponent (itemHolder);
  44356. addAndMakeVisible (viewport);
  44357. }
  44358. ToolbarItemPalette::~ToolbarItemPalette()
  44359. {
  44360. viewport->getViewedComponent()->deleteAllChildren();
  44361. deleteAllChildren();
  44362. }
  44363. void ToolbarItemPalette::resized()
  44364. {
  44365. viewport->setBoundsInset (BorderSize (1));
  44366. Component* const itemHolder = viewport->getViewedComponent();
  44367. const int indent = 8;
  44368. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  44369. const int height = toolbar->getThickness();
  44370. int x = indent;
  44371. int y = indent;
  44372. int maxX = 0;
  44373. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  44374. {
  44375. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  44376. if (tc != 0)
  44377. {
  44378. tc->setStyle (toolbar->getStyle());
  44379. int preferredSize = 1, minSize = 1, maxSize = 1;
  44380. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44381. {
  44382. if (x + preferredSize > preferredWidth && x > indent)
  44383. {
  44384. x = indent;
  44385. y += height;
  44386. }
  44387. tc->setBounds (x, y, preferredSize, height);
  44388. x += preferredSize + 8;
  44389. maxX = jmax (maxX, x);
  44390. }
  44391. }
  44392. }
  44393. itemHolder->setSize (maxX, y + height + 8);
  44394. }
  44395. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44396. {
  44397. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  44398. jassert (tc != 0);
  44399. if (tc != 0)
  44400. {
  44401. tc->setBounds (comp->getBounds());
  44402. tc->setStyle (toolbar->getStyle());
  44403. tc->setEditingMode (comp->getEditingMode());
  44404. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  44405. }
  44406. }
  44407. END_JUCE_NAMESPACE
  44408. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44409. /*** Start of inlined file: juce_TreeView.cpp ***/
  44410. BEGIN_JUCE_NAMESPACE
  44411. class TreeViewContentComponent : public Component,
  44412. public TooltipClient
  44413. {
  44414. public:
  44415. TreeViewContentComponent (TreeView& owner_)
  44416. : owner (owner_),
  44417. buttonUnderMouse (0),
  44418. isDragging (false)
  44419. {
  44420. }
  44421. ~TreeViewContentComponent()
  44422. {
  44423. deleteAllChildren();
  44424. }
  44425. void mouseDown (const MouseEvent& e)
  44426. {
  44427. updateButtonUnderMouse (e);
  44428. isDragging = false;
  44429. needSelectionOnMouseUp = false;
  44430. Rectangle<int> pos;
  44431. TreeViewItem* const item = findItemAt (e.y, pos);
  44432. if (item == 0)
  44433. return;
  44434. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44435. // as selection clicks)
  44436. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44437. {
  44438. if (e.x >= pos.getX() - owner.getIndentSize())
  44439. item->setOpen (! item->isOpen());
  44440. // (clicks to the left of an open/close button are ignored)
  44441. }
  44442. else
  44443. {
  44444. // mouse-down inside the body of the item..
  44445. if (! owner.isMultiSelectEnabled())
  44446. item->setSelected (true, true);
  44447. else if (item->isSelected())
  44448. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44449. else
  44450. selectBasedOnModifiers (item, e.mods);
  44451. if (e.x >= pos.getX())
  44452. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44453. }
  44454. }
  44455. void mouseUp (const MouseEvent& e)
  44456. {
  44457. updateButtonUnderMouse (e);
  44458. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44459. {
  44460. Rectangle<int> pos;
  44461. TreeViewItem* const item = findItemAt (e.y, pos);
  44462. if (item != 0)
  44463. selectBasedOnModifiers (item, e.mods);
  44464. }
  44465. }
  44466. void mouseDoubleClick (const MouseEvent& e)
  44467. {
  44468. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44469. {
  44470. Rectangle<int> pos;
  44471. TreeViewItem* const item = findItemAt (e.y, pos);
  44472. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44473. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44474. }
  44475. }
  44476. void mouseDrag (const MouseEvent& e)
  44477. {
  44478. if (isEnabled()
  44479. && ! (isDragging || e.mouseWasClicked()
  44480. || e.getDistanceFromDragStart() < 5
  44481. || e.mods.isPopupMenu()))
  44482. {
  44483. isDragging = true;
  44484. Rectangle<int> pos;
  44485. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44486. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44487. {
  44488. const String dragDescription (item->getDragSourceDescription());
  44489. if (dragDescription.isNotEmpty())
  44490. {
  44491. DragAndDropContainer* const dragContainer
  44492. = DragAndDropContainer::findParentDragContainerFor (this);
  44493. if (dragContainer != 0)
  44494. {
  44495. pos.setSize (pos.getWidth(), item->itemHeight);
  44496. Image dragImage (Component::createComponentSnapshot (pos, true));
  44497. dragImage.multiplyAllAlphas (0.6f);
  44498. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  44499. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  44500. }
  44501. else
  44502. {
  44503. // to be able to do a drag-and-drop operation, the treeview needs to
  44504. // be inside a component which is also a DragAndDropContainer.
  44505. jassertfalse;
  44506. }
  44507. }
  44508. }
  44509. }
  44510. }
  44511. void mouseMove (const MouseEvent& e)
  44512. {
  44513. updateButtonUnderMouse (e);
  44514. }
  44515. void mouseExit (const MouseEvent& e)
  44516. {
  44517. updateButtonUnderMouse (e);
  44518. }
  44519. void paint (Graphics& g)
  44520. {
  44521. if (owner.rootItem != 0)
  44522. {
  44523. owner.handleAsyncUpdate();
  44524. if (! owner.rootItemVisible)
  44525. g.setOrigin (0, -owner.rootItem->itemHeight);
  44526. owner.rootItem->paintRecursively (g, getWidth());
  44527. }
  44528. }
  44529. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  44530. {
  44531. if (owner.rootItem != 0)
  44532. {
  44533. owner.handleAsyncUpdate();
  44534. if (! owner.rootItemVisible)
  44535. y += owner.rootItem->itemHeight;
  44536. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  44537. if (ti != 0)
  44538. itemPosition = ti->getItemPosition (false);
  44539. return ti;
  44540. }
  44541. return 0;
  44542. }
  44543. void updateComponents()
  44544. {
  44545. const int visibleTop = -getY();
  44546. const int visibleBottom = visibleTop + getParentHeight();
  44547. BigInteger itemsToKeep;
  44548. {
  44549. TreeViewItem* item = owner.rootItem;
  44550. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  44551. while (item != 0 && y < visibleBottom)
  44552. {
  44553. y += item->itemHeight;
  44554. if (y >= visibleTop)
  44555. {
  44556. const int index = rowComponentIds.indexOf (item->uid);
  44557. if (index < 0)
  44558. {
  44559. Component* const comp = item->createItemComponent();
  44560. if (comp != 0)
  44561. {
  44562. addAndMakeVisible (comp);
  44563. itemsToKeep.setBit (rowComponentItems.size());
  44564. rowComponentItems.add (item);
  44565. rowComponentIds.add (item->uid);
  44566. rowComponents.add (comp);
  44567. }
  44568. }
  44569. else
  44570. {
  44571. itemsToKeep.setBit (index);
  44572. }
  44573. }
  44574. item = item->getNextVisibleItem (true);
  44575. }
  44576. }
  44577. for (int i = rowComponentItems.size(); --i >= 0;)
  44578. {
  44579. Component* const comp = rowComponents.getUnchecked(i);
  44580. bool keep = false;
  44581. if (isParentOf (comp))
  44582. {
  44583. if (itemsToKeep[i])
  44584. {
  44585. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  44586. Rectangle<int> pos (item->getItemPosition (false));
  44587. pos.setSize (pos.getWidth(), item->itemHeight);
  44588. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  44589. {
  44590. keep = true;
  44591. comp->setBounds (pos);
  44592. }
  44593. }
  44594. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  44595. {
  44596. keep = true;
  44597. comp->setSize (0, 0);
  44598. }
  44599. }
  44600. if (! keep)
  44601. {
  44602. delete comp;
  44603. rowComponents.remove (i);
  44604. rowComponentIds.remove (i);
  44605. rowComponentItems.remove (i);
  44606. }
  44607. }
  44608. }
  44609. void updateButtonUnderMouse (const MouseEvent& e)
  44610. {
  44611. TreeViewItem* newItem = 0;
  44612. if (owner.openCloseButtonsVisible)
  44613. {
  44614. Rectangle<int> pos;
  44615. TreeViewItem* item = findItemAt (e.y, pos);
  44616. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  44617. {
  44618. newItem = item;
  44619. if (! newItem->mightContainSubItems())
  44620. newItem = 0;
  44621. }
  44622. }
  44623. if (buttonUnderMouse != newItem)
  44624. {
  44625. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  44626. {
  44627. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44628. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44629. }
  44630. buttonUnderMouse = newItem;
  44631. if (buttonUnderMouse != 0)
  44632. {
  44633. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44634. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44635. }
  44636. }
  44637. }
  44638. bool isMouseOverButton (TreeViewItem* const item) const throw()
  44639. {
  44640. return item == buttonUnderMouse;
  44641. }
  44642. void resized()
  44643. {
  44644. owner.itemsChanged();
  44645. }
  44646. const String getTooltip()
  44647. {
  44648. Rectangle<int> pos;
  44649. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  44650. if (item != 0)
  44651. return item->getTooltip();
  44652. return owner.getTooltip();
  44653. }
  44654. juce_UseDebuggingNewOperator
  44655. private:
  44656. TreeView& owner;
  44657. Array <TreeViewItem*> rowComponentItems;
  44658. Array <int> rowComponentIds;
  44659. Array <Component*> rowComponents;
  44660. TreeViewItem* buttonUnderMouse;
  44661. bool isDragging, needSelectionOnMouseUp;
  44662. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  44663. {
  44664. TreeViewItem* firstSelected = 0;
  44665. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  44666. {
  44667. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  44668. jassert (lastSelected != 0);
  44669. int rowStart = firstSelected->getRowNumberInTree();
  44670. int rowEnd = lastSelected->getRowNumberInTree();
  44671. if (rowStart > rowEnd)
  44672. swapVariables (rowStart, rowEnd);
  44673. int ourRow = item->getRowNumberInTree();
  44674. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  44675. if (ourRow > otherEnd)
  44676. swapVariables (ourRow, otherEnd);
  44677. for (int i = ourRow; i <= otherEnd; ++i)
  44678. owner.getItemOnRow (i)->setSelected (true, false);
  44679. }
  44680. else
  44681. {
  44682. const bool cmd = modifiers.isCommandDown();
  44683. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  44684. }
  44685. }
  44686. bool containsItem (TreeViewItem* const item) const
  44687. {
  44688. for (int i = rowComponentItems.size(); --i >= 0;)
  44689. if (rowComponentItems.getUnchecked(i) == item)
  44690. return true;
  44691. return false;
  44692. }
  44693. static bool isMouseDraggingInChildCompOf (Component* const comp)
  44694. {
  44695. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  44696. {
  44697. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  44698. if (source->isDragging())
  44699. {
  44700. Component* const underMouse = source->getComponentUnderMouse();
  44701. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  44702. return true;
  44703. }
  44704. }
  44705. return false;
  44706. }
  44707. TreeViewContentComponent (const TreeViewContentComponent&);
  44708. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  44709. };
  44710. class TreeView::TreeViewport : public Viewport
  44711. {
  44712. public:
  44713. TreeViewport() throw() : lastX (-1) {}
  44714. ~TreeViewport() throw() {}
  44715. void updateComponents (const bool triggerResize = false)
  44716. {
  44717. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  44718. if (tvc != 0)
  44719. {
  44720. if (triggerResize)
  44721. tvc->resized();
  44722. else
  44723. tvc->updateComponents();
  44724. }
  44725. repaint();
  44726. }
  44727. void visibleAreaChanged (int x, int, int, int)
  44728. {
  44729. const bool hasScrolledSideways = (x != lastX);
  44730. lastX = x;
  44731. updateComponents (hasScrolledSideways);
  44732. }
  44733. juce_UseDebuggingNewOperator
  44734. private:
  44735. int lastX;
  44736. TreeViewport (const TreeViewport&);
  44737. TreeViewport& operator= (const TreeViewport&);
  44738. };
  44739. TreeView::TreeView (const String& componentName)
  44740. : Component (componentName),
  44741. rootItem (0),
  44742. indentSize (24),
  44743. defaultOpenness (false),
  44744. needsRecalculating (true),
  44745. rootItemVisible (true),
  44746. multiSelectEnabled (false),
  44747. openCloseButtonsVisible (true)
  44748. {
  44749. addAndMakeVisible (viewport = new TreeViewport());
  44750. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  44751. viewport->setWantsKeyboardFocus (false);
  44752. setWantsKeyboardFocus (true);
  44753. }
  44754. TreeView::~TreeView()
  44755. {
  44756. if (rootItem != 0)
  44757. rootItem->setOwnerView (0);
  44758. }
  44759. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  44760. {
  44761. if (rootItem != newRootItem)
  44762. {
  44763. if (newRootItem != 0)
  44764. {
  44765. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  44766. if (newRootItem->ownerView != 0)
  44767. newRootItem->ownerView->setRootItem (0);
  44768. }
  44769. if (rootItem != 0)
  44770. rootItem->setOwnerView (0);
  44771. rootItem = newRootItem;
  44772. if (newRootItem != 0)
  44773. newRootItem->setOwnerView (this);
  44774. needsRecalculating = true;
  44775. handleAsyncUpdate();
  44776. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44777. {
  44778. rootItem->setOpen (false); // force a re-open
  44779. rootItem->setOpen (true);
  44780. }
  44781. }
  44782. }
  44783. void TreeView::deleteRootItem()
  44784. {
  44785. const ScopedPointer <TreeViewItem> deleter (rootItem);
  44786. setRootItem (0);
  44787. }
  44788. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  44789. {
  44790. rootItemVisible = shouldBeVisible;
  44791. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44792. {
  44793. rootItem->setOpen (false); // force a re-open
  44794. rootItem->setOpen (true);
  44795. }
  44796. itemsChanged();
  44797. }
  44798. void TreeView::colourChanged()
  44799. {
  44800. setOpaque (findColour (backgroundColourId).isOpaque());
  44801. repaint();
  44802. }
  44803. void TreeView::setIndentSize (const int newIndentSize)
  44804. {
  44805. if (indentSize != newIndentSize)
  44806. {
  44807. indentSize = newIndentSize;
  44808. resized();
  44809. }
  44810. }
  44811. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  44812. {
  44813. if (defaultOpenness != isOpenByDefault)
  44814. {
  44815. defaultOpenness = isOpenByDefault;
  44816. itemsChanged();
  44817. }
  44818. }
  44819. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  44820. {
  44821. multiSelectEnabled = canMultiSelect;
  44822. }
  44823. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  44824. {
  44825. if (openCloseButtonsVisible != shouldBeVisible)
  44826. {
  44827. openCloseButtonsVisible = shouldBeVisible;
  44828. itemsChanged();
  44829. }
  44830. }
  44831. Viewport* TreeView::getViewport() const throw()
  44832. {
  44833. return viewport;
  44834. }
  44835. void TreeView::clearSelectedItems()
  44836. {
  44837. if (rootItem != 0)
  44838. rootItem->deselectAllRecursively();
  44839. }
  44840. int TreeView::getNumSelectedItems() const throw()
  44841. {
  44842. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  44843. }
  44844. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  44845. {
  44846. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  44847. }
  44848. int TreeView::getNumRowsInTree() const
  44849. {
  44850. if (rootItem != 0)
  44851. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  44852. return 0;
  44853. }
  44854. TreeViewItem* TreeView::getItemOnRow (int index) const
  44855. {
  44856. if (! rootItemVisible)
  44857. ++index;
  44858. if (rootItem != 0 && index >= 0)
  44859. return rootItem->getItemOnRow (index);
  44860. return 0;
  44861. }
  44862. TreeViewItem* TreeView::getItemAt (int y) const throw()
  44863. {
  44864. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  44865. Rectangle<int> pos;
  44866. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  44867. }
  44868. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  44869. {
  44870. if (rootItem == 0)
  44871. return 0;
  44872. return rootItem->findItemFromIdentifierString (identifierString);
  44873. }
  44874. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  44875. {
  44876. XmlElement* e = 0;
  44877. if (rootItem != 0)
  44878. {
  44879. e = rootItem->getOpennessState();
  44880. if (e != 0 && alsoIncludeScrollPosition)
  44881. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  44882. }
  44883. return e;
  44884. }
  44885. void TreeView::restoreOpennessState (const XmlElement& newState)
  44886. {
  44887. if (rootItem != 0)
  44888. {
  44889. rootItem->restoreOpennessState (newState);
  44890. if (newState.hasAttribute ("scrollPos"))
  44891. viewport->setViewPosition (viewport->getViewPositionX(),
  44892. newState.getIntAttribute ("scrollPos"));
  44893. }
  44894. }
  44895. void TreeView::paint (Graphics& g)
  44896. {
  44897. g.fillAll (findColour (backgroundColourId));
  44898. }
  44899. void TreeView::resized()
  44900. {
  44901. viewport->setBounds (getLocalBounds());
  44902. itemsChanged();
  44903. handleAsyncUpdate();
  44904. }
  44905. void TreeView::enablementChanged()
  44906. {
  44907. repaint();
  44908. }
  44909. void TreeView::moveSelectedRow (int delta)
  44910. {
  44911. if (delta == 0)
  44912. return;
  44913. int rowSelected = 0;
  44914. TreeViewItem* const firstSelected = getSelectedItem (0);
  44915. if (firstSelected != 0)
  44916. rowSelected = firstSelected->getRowNumberInTree();
  44917. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  44918. for (;;)
  44919. {
  44920. TreeViewItem* item = getItemOnRow (rowSelected);
  44921. if (item != 0)
  44922. {
  44923. if (! item->canBeSelected())
  44924. {
  44925. // if the row we want to highlight doesn't allow it, try skipping
  44926. // to the next item..
  44927. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  44928. rowSelected + (delta < 0 ? -1 : 1));
  44929. if (rowSelected != nextRowToTry)
  44930. {
  44931. rowSelected = nextRowToTry;
  44932. continue;
  44933. }
  44934. else
  44935. {
  44936. break;
  44937. }
  44938. }
  44939. item->setSelected (true, true);
  44940. scrollToKeepItemVisible (item);
  44941. }
  44942. break;
  44943. }
  44944. }
  44945. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  44946. {
  44947. if (item != 0 && item->ownerView == this)
  44948. {
  44949. handleAsyncUpdate();
  44950. item = item->getDeepestOpenParentItem();
  44951. int y = item->y;
  44952. int viewTop = viewport->getViewPositionY();
  44953. if (y < viewTop)
  44954. {
  44955. viewport->setViewPosition (viewport->getViewPositionX(), y);
  44956. }
  44957. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  44958. {
  44959. viewport->setViewPosition (viewport->getViewPositionX(),
  44960. (y + item->itemHeight) - viewport->getViewHeight());
  44961. }
  44962. }
  44963. }
  44964. bool TreeView::keyPressed (const KeyPress& key)
  44965. {
  44966. if (key.isKeyCode (KeyPress::upKey))
  44967. {
  44968. moveSelectedRow (-1);
  44969. }
  44970. else if (key.isKeyCode (KeyPress::downKey))
  44971. {
  44972. moveSelectedRow (1);
  44973. }
  44974. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  44975. {
  44976. if (rootItem != 0)
  44977. {
  44978. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  44979. if (key.isKeyCode (KeyPress::pageUpKey))
  44980. rowsOnScreen = -rowsOnScreen;
  44981. moveSelectedRow (rowsOnScreen);
  44982. }
  44983. }
  44984. else if (key.isKeyCode (KeyPress::homeKey))
  44985. {
  44986. moveSelectedRow (-0x3fffffff);
  44987. }
  44988. else if (key.isKeyCode (KeyPress::endKey))
  44989. {
  44990. moveSelectedRow (0x3fffffff);
  44991. }
  44992. else if (key.isKeyCode (KeyPress::returnKey))
  44993. {
  44994. TreeViewItem* const firstSelected = getSelectedItem (0);
  44995. if (firstSelected != 0)
  44996. firstSelected->setOpen (! firstSelected->isOpen());
  44997. }
  44998. else if (key.isKeyCode (KeyPress::leftKey))
  44999. {
  45000. TreeViewItem* const firstSelected = getSelectedItem (0);
  45001. if (firstSelected != 0)
  45002. {
  45003. if (firstSelected->isOpen())
  45004. {
  45005. firstSelected->setOpen (false);
  45006. }
  45007. else
  45008. {
  45009. TreeViewItem* parent = firstSelected->parentItem;
  45010. if ((! rootItemVisible) && parent == rootItem)
  45011. parent = 0;
  45012. if (parent != 0)
  45013. {
  45014. parent->setSelected (true, true);
  45015. scrollToKeepItemVisible (parent);
  45016. }
  45017. }
  45018. }
  45019. }
  45020. else if (key.isKeyCode (KeyPress::rightKey))
  45021. {
  45022. TreeViewItem* const firstSelected = getSelectedItem (0);
  45023. if (firstSelected != 0)
  45024. {
  45025. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45026. moveSelectedRow (1);
  45027. else
  45028. firstSelected->setOpen (true);
  45029. }
  45030. }
  45031. else
  45032. {
  45033. return false;
  45034. }
  45035. return true;
  45036. }
  45037. void TreeView::itemsChanged() throw()
  45038. {
  45039. needsRecalculating = true;
  45040. repaint();
  45041. triggerAsyncUpdate();
  45042. }
  45043. void TreeView::handleAsyncUpdate()
  45044. {
  45045. if (needsRecalculating)
  45046. {
  45047. needsRecalculating = false;
  45048. const ScopedLock sl (nodeAlterationLock);
  45049. if (rootItem != 0)
  45050. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45051. viewport->updateComponents();
  45052. if (rootItem != 0)
  45053. {
  45054. viewport->getViewedComponent()
  45055. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45056. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45057. }
  45058. else
  45059. {
  45060. viewport->getViewedComponent()->setSize (0, 0);
  45061. }
  45062. }
  45063. }
  45064. class TreeView::InsertPointHighlight : public Component
  45065. {
  45066. public:
  45067. InsertPointHighlight()
  45068. : lastItem (0)
  45069. {
  45070. setSize (100, 12);
  45071. setAlwaysOnTop (true);
  45072. setInterceptsMouseClicks (false, false);
  45073. }
  45074. ~InsertPointHighlight() {}
  45075. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45076. {
  45077. lastItem = item;
  45078. lastIndex = insertIndex;
  45079. const int offset = getHeight() / 2;
  45080. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45081. }
  45082. void paint (Graphics& g)
  45083. {
  45084. Path p;
  45085. const float h = (float) getHeight();
  45086. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45087. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45088. p.lineTo ((float) getWidth(), h / 2.0f);
  45089. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45090. g.strokePath (p, PathStrokeType (2.0f));
  45091. }
  45092. TreeViewItem* lastItem;
  45093. int lastIndex;
  45094. private:
  45095. InsertPointHighlight (const InsertPointHighlight&);
  45096. InsertPointHighlight& operator= (const InsertPointHighlight&);
  45097. };
  45098. class TreeView::TargetGroupHighlight : public Component
  45099. {
  45100. public:
  45101. TargetGroupHighlight()
  45102. {
  45103. setAlwaysOnTop (true);
  45104. setInterceptsMouseClicks (false, false);
  45105. }
  45106. ~TargetGroupHighlight() {}
  45107. void setTargetPosition (TreeViewItem* const item) throw()
  45108. {
  45109. Rectangle<int> r (item->getItemPosition (true));
  45110. r.setHeight (item->getItemHeight());
  45111. setBounds (r);
  45112. }
  45113. void paint (Graphics& g)
  45114. {
  45115. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45116. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45117. }
  45118. private:
  45119. TargetGroupHighlight (const TargetGroupHighlight&);
  45120. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  45121. };
  45122. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45123. {
  45124. beginDragAutoRepeat (1000 / 30);
  45125. if (dragInsertPointHighlight == 0)
  45126. {
  45127. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45128. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45129. }
  45130. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45131. dragTargetGroupHighlight->setTargetPosition (item);
  45132. }
  45133. void TreeView::hideDragHighlight() throw()
  45134. {
  45135. dragInsertPointHighlight = 0;
  45136. dragTargetGroupHighlight = 0;
  45137. }
  45138. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45139. const StringArray& files, const String& sourceDescription,
  45140. Component* sourceComponent) const throw()
  45141. {
  45142. insertIndex = 0;
  45143. TreeViewItem* item = getItemAt (y);
  45144. if (item == 0)
  45145. return 0;
  45146. Rectangle<int> itemPos (item->getItemPosition (true));
  45147. insertIndex = item->getIndexInParent();
  45148. const int oldY = y;
  45149. y = itemPos.getY();
  45150. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45151. {
  45152. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45153. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45154. {
  45155. // Check if we're trying to drag into an empty group item..
  45156. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45157. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45158. {
  45159. insertIndex = 0;
  45160. x = itemPos.getX() + getIndentSize();
  45161. y = itemPos.getBottom();
  45162. return item;
  45163. }
  45164. }
  45165. }
  45166. if (oldY > itemPos.getCentreY())
  45167. {
  45168. y += item->getItemHeight();
  45169. while (item->isLastOfSiblings() && item->parentItem != 0
  45170. && item->parentItem->parentItem != 0)
  45171. {
  45172. if (x > itemPos.getX())
  45173. break;
  45174. item = item->parentItem;
  45175. itemPos = item->getItemPosition (true);
  45176. insertIndex = item->getIndexInParent();
  45177. }
  45178. ++insertIndex;
  45179. }
  45180. x = itemPos.getX();
  45181. return item->parentItem;
  45182. }
  45183. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45184. {
  45185. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45186. int insertIndex;
  45187. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45188. if (item != 0)
  45189. {
  45190. if (scrolled || dragInsertPointHighlight == 0
  45191. || dragInsertPointHighlight->lastItem != item
  45192. || dragInsertPointHighlight->lastIndex != insertIndex)
  45193. {
  45194. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45195. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45196. showDragHighlight (item, insertIndex, x, y);
  45197. else
  45198. hideDragHighlight();
  45199. }
  45200. }
  45201. else
  45202. {
  45203. hideDragHighlight();
  45204. }
  45205. }
  45206. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45207. {
  45208. hideDragHighlight();
  45209. int insertIndex;
  45210. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45211. if (item != 0)
  45212. {
  45213. if (files.size() > 0)
  45214. {
  45215. if (item->isInterestedInFileDrag (files))
  45216. item->filesDropped (files, insertIndex);
  45217. }
  45218. else
  45219. {
  45220. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45221. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45222. }
  45223. }
  45224. }
  45225. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45226. {
  45227. return true;
  45228. }
  45229. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45230. {
  45231. fileDragMove (files, x, y);
  45232. }
  45233. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45234. {
  45235. handleDrag (files, String::empty, 0, x, y);
  45236. }
  45237. void TreeView::fileDragExit (const StringArray&)
  45238. {
  45239. hideDragHighlight();
  45240. }
  45241. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45242. {
  45243. handleDrop (files, String::empty, 0, x, y);
  45244. }
  45245. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45246. {
  45247. return true;
  45248. }
  45249. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45250. {
  45251. itemDragMove (sourceDescription, sourceComponent, x, y);
  45252. }
  45253. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45254. {
  45255. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45256. }
  45257. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45258. {
  45259. hideDragHighlight();
  45260. }
  45261. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45262. {
  45263. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45264. }
  45265. enum TreeViewOpenness
  45266. {
  45267. opennessDefault = 0,
  45268. opennessClosed = 1,
  45269. opennessOpen = 2
  45270. };
  45271. TreeViewItem::TreeViewItem()
  45272. : ownerView (0),
  45273. parentItem (0),
  45274. y (0),
  45275. itemHeight (0),
  45276. totalHeight (0),
  45277. selected (false),
  45278. redrawNeeded (true),
  45279. drawLinesInside (true),
  45280. drawsInLeftMargin (false),
  45281. openness (opennessDefault)
  45282. {
  45283. static int nextUID = 0;
  45284. uid = nextUID++;
  45285. }
  45286. TreeViewItem::~TreeViewItem()
  45287. {
  45288. }
  45289. const String TreeViewItem::getUniqueName() const
  45290. {
  45291. return String::empty;
  45292. }
  45293. void TreeViewItem::itemOpennessChanged (bool)
  45294. {
  45295. }
  45296. int TreeViewItem::getNumSubItems() const throw()
  45297. {
  45298. return subItems.size();
  45299. }
  45300. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45301. {
  45302. return subItems [index];
  45303. }
  45304. void TreeViewItem::clearSubItems()
  45305. {
  45306. if (subItems.size() > 0)
  45307. {
  45308. if (ownerView != 0)
  45309. {
  45310. const ScopedLock sl (ownerView->nodeAlterationLock);
  45311. subItems.clear();
  45312. treeHasChanged();
  45313. }
  45314. else
  45315. {
  45316. subItems.clear();
  45317. }
  45318. }
  45319. }
  45320. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45321. {
  45322. if (newItem != 0)
  45323. {
  45324. newItem->parentItem = this;
  45325. newItem->setOwnerView (ownerView);
  45326. newItem->y = 0;
  45327. newItem->itemHeight = newItem->getItemHeight();
  45328. newItem->totalHeight = 0;
  45329. newItem->itemWidth = newItem->getItemWidth();
  45330. newItem->totalWidth = 0;
  45331. if (ownerView != 0)
  45332. {
  45333. const ScopedLock sl (ownerView->nodeAlterationLock);
  45334. subItems.insert (insertPosition, newItem);
  45335. treeHasChanged();
  45336. if (newItem->isOpen())
  45337. newItem->itemOpennessChanged (true);
  45338. }
  45339. else
  45340. {
  45341. subItems.insert (insertPosition, newItem);
  45342. if (newItem->isOpen())
  45343. newItem->itemOpennessChanged (true);
  45344. }
  45345. }
  45346. }
  45347. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45348. {
  45349. if (ownerView != 0)
  45350. {
  45351. const ScopedLock sl (ownerView->nodeAlterationLock);
  45352. if (((unsigned int) index) < (unsigned int) subItems.size())
  45353. {
  45354. subItems.remove (index, deleteItem);
  45355. treeHasChanged();
  45356. }
  45357. }
  45358. else
  45359. {
  45360. subItems.remove (index, deleteItem);
  45361. }
  45362. }
  45363. bool TreeViewItem::isOpen() const throw()
  45364. {
  45365. if (openness == opennessDefault)
  45366. return ownerView != 0 && ownerView->defaultOpenness;
  45367. else
  45368. return openness == opennessOpen;
  45369. }
  45370. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45371. {
  45372. if (isOpen() != shouldBeOpen)
  45373. {
  45374. openness = shouldBeOpen ? opennessOpen
  45375. : opennessClosed;
  45376. treeHasChanged();
  45377. itemOpennessChanged (isOpen());
  45378. }
  45379. }
  45380. bool TreeViewItem::isSelected() const throw()
  45381. {
  45382. return selected;
  45383. }
  45384. void TreeViewItem::deselectAllRecursively()
  45385. {
  45386. setSelected (false, false);
  45387. for (int i = 0; i < subItems.size(); ++i)
  45388. subItems.getUnchecked(i)->deselectAllRecursively();
  45389. }
  45390. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45391. const bool deselectOtherItemsFirst)
  45392. {
  45393. if (shouldBeSelected && ! canBeSelected())
  45394. return;
  45395. if (deselectOtherItemsFirst)
  45396. getTopLevelItem()->deselectAllRecursively();
  45397. if (shouldBeSelected != selected)
  45398. {
  45399. selected = shouldBeSelected;
  45400. if (ownerView != 0)
  45401. ownerView->repaint();
  45402. itemSelectionChanged (shouldBeSelected);
  45403. }
  45404. }
  45405. void TreeViewItem::paintItem (Graphics&, int, int)
  45406. {
  45407. }
  45408. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45409. {
  45410. ownerView->getLookAndFeel()
  45411. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45412. }
  45413. void TreeViewItem::itemClicked (const MouseEvent&)
  45414. {
  45415. }
  45416. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45417. {
  45418. if (mightContainSubItems())
  45419. setOpen (! isOpen());
  45420. }
  45421. void TreeViewItem::itemSelectionChanged (bool)
  45422. {
  45423. }
  45424. const String TreeViewItem::getTooltip()
  45425. {
  45426. return String::empty;
  45427. }
  45428. const String TreeViewItem::getDragSourceDescription()
  45429. {
  45430. return String::empty;
  45431. }
  45432. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45433. {
  45434. return false;
  45435. }
  45436. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45437. {
  45438. }
  45439. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45440. {
  45441. return false;
  45442. }
  45443. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45444. {
  45445. }
  45446. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45447. {
  45448. const int indentX = getIndentX();
  45449. int width = itemWidth;
  45450. if (ownerView != 0 && width < 0)
  45451. width = ownerView->viewport->getViewWidth() - indentX;
  45452. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45453. if (relativeToTreeViewTopLeft)
  45454. r -= ownerView->viewport->getViewPosition();
  45455. return r;
  45456. }
  45457. void TreeViewItem::treeHasChanged() const throw()
  45458. {
  45459. if (ownerView != 0)
  45460. ownerView->itemsChanged();
  45461. }
  45462. void TreeViewItem::repaintItem() const
  45463. {
  45464. if (ownerView != 0 && areAllParentsOpen())
  45465. {
  45466. Rectangle<int> r (getItemPosition (true));
  45467. r.setLeft (0);
  45468. ownerView->viewport->repaint (r);
  45469. }
  45470. }
  45471. bool TreeViewItem::areAllParentsOpen() const throw()
  45472. {
  45473. return parentItem == 0
  45474. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45475. }
  45476. void TreeViewItem::updatePositions (int newY)
  45477. {
  45478. y = newY;
  45479. itemHeight = getItemHeight();
  45480. totalHeight = itemHeight;
  45481. itemWidth = getItemWidth();
  45482. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45483. if (isOpen())
  45484. {
  45485. newY += totalHeight;
  45486. for (int i = 0; i < subItems.size(); ++i)
  45487. {
  45488. TreeViewItem* const ti = subItems.getUnchecked(i);
  45489. ti->updatePositions (newY);
  45490. newY += ti->totalHeight;
  45491. totalHeight += ti->totalHeight;
  45492. totalWidth = jmax (totalWidth, ti->totalWidth);
  45493. }
  45494. }
  45495. }
  45496. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  45497. {
  45498. TreeViewItem* result = this;
  45499. TreeViewItem* item = this;
  45500. while (item->parentItem != 0)
  45501. {
  45502. item = item->parentItem;
  45503. if (! item->isOpen())
  45504. result = item;
  45505. }
  45506. return result;
  45507. }
  45508. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  45509. {
  45510. ownerView = newOwner;
  45511. for (int i = subItems.size(); --i >= 0;)
  45512. subItems.getUnchecked(i)->setOwnerView (newOwner);
  45513. }
  45514. int TreeViewItem::getIndentX() const throw()
  45515. {
  45516. const int indentWidth = ownerView->getIndentSize();
  45517. int x = ownerView->rootItemVisible ? indentWidth : 0;
  45518. if (! ownerView->openCloseButtonsVisible)
  45519. x -= indentWidth;
  45520. TreeViewItem* p = parentItem;
  45521. while (p != 0)
  45522. {
  45523. x += indentWidth;
  45524. p = p->parentItem;
  45525. }
  45526. return x;
  45527. }
  45528. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  45529. {
  45530. drawsInLeftMargin = canDrawInLeftMargin;
  45531. }
  45532. void TreeViewItem::paintRecursively (Graphics& g, int width)
  45533. {
  45534. jassert (ownerView != 0);
  45535. if (ownerView == 0)
  45536. return;
  45537. const int indent = getIndentX();
  45538. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  45539. g.setColour (ownerView->findColour (TreeView::linesColourId));
  45540. const float halfH = itemHeight * 0.5f;
  45541. int depth = 0;
  45542. TreeViewItem* p = parentItem;
  45543. while (p != 0)
  45544. {
  45545. ++depth;
  45546. p = p->parentItem;
  45547. }
  45548. if (! ownerView->rootItemVisible)
  45549. --depth;
  45550. const int indentWidth = ownerView->getIndentSize();
  45551. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  45552. {
  45553. float x = (depth + 0.5f) * indentWidth;
  45554. if (depth >= 0)
  45555. {
  45556. if (parentItem != 0 && parentItem->drawLinesInside)
  45557. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  45558. if ((parentItem != 0 && parentItem->drawLinesInside)
  45559. || (parentItem == 0 && drawLinesInside))
  45560. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  45561. }
  45562. p = parentItem;
  45563. int d = depth;
  45564. while (p != 0 && --d >= 0)
  45565. {
  45566. x -= (float) indentWidth;
  45567. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  45568. && ! p->isLastOfSiblings())
  45569. {
  45570. g.drawLine (x, 0, x, (float) itemHeight);
  45571. }
  45572. p = p->parentItem;
  45573. }
  45574. if (mightContainSubItems())
  45575. {
  45576. g.saveState();
  45577. g.setOrigin (depth * indentWidth, 0);
  45578. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  45579. paintOpenCloseButton (g, indentWidth, itemHeight,
  45580. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  45581. ->isMouseOverButton (this));
  45582. g.restoreState();
  45583. }
  45584. }
  45585. {
  45586. g.saveState();
  45587. g.setOrigin (indent, 0);
  45588. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  45589. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  45590. paintItem (g, itemW, itemHeight);
  45591. g.restoreState();
  45592. }
  45593. if (isOpen())
  45594. {
  45595. const Rectangle<int> clip (g.getClipBounds());
  45596. for (int i = 0; i < subItems.size(); ++i)
  45597. {
  45598. TreeViewItem* const ti = subItems.getUnchecked(i);
  45599. const int relY = ti->y - y;
  45600. if (relY >= clip.getBottom())
  45601. break;
  45602. if (relY + ti->totalHeight >= clip.getY())
  45603. {
  45604. g.saveState();
  45605. g.setOrigin (0, relY);
  45606. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  45607. ti->paintRecursively (g, width);
  45608. g.restoreState();
  45609. }
  45610. }
  45611. }
  45612. }
  45613. bool TreeViewItem::isLastOfSiblings() const throw()
  45614. {
  45615. return parentItem == 0
  45616. || parentItem->subItems.getLast() == this;
  45617. }
  45618. int TreeViewItem::getIndexInParent() const throw()
  45619. {
  45620. if (parentItem == 0)
  45621. return 0;
  45622. return parentItem->subItems.indexOf (this);
  45623. }
  45624. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  45625. {
  45626. return (parentItem == 0) ? this
  45627. : parentItem->getTopLevelItem();
  45628. }
  45629. int TreeViewItem::getNumRows() const throw()
  45630. {
  45631. int num = 1;
  45632. if (isOpen())
  45633. {
  45634. for (int i = subItems.size(); --i >= 0;)
  45635. num += subItems.getUnchecked(i)->getNumRows();
  45636. }
  45637. return num;
  45638. }
  45639. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  45640. {
  45641. if (index == 0)
  45642. return this;
  45643. if (index > 0 && isOpen())
  45644. {
  45645. --index;
  45646. for (int i = 0; i < subItems.size(); ++i)
  45647. {
  45648. TreeViewItem* const item = subItems.getUnchecked(i);
  45649. if (index == 0)
  45650. return item;
  45651. const int numRows = item->getNumRows();
  45652. if (numRows > index)
  45653. return item->getItemOnRow (index);
  45654. index -= numRows;
  45655. }
  45656. }
  45657. return 0;
  45658. }
  45659. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  45660. {
  45661. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  45662. {
  45663. const int h = itemHeight;
  45664. if (targetY < h)
  45665. return this;
  45666. if (isOpen())
  45667. {
  45668. targetY -= h;
  45669. for (int i = 0; i < subItems.size(); ++i)
  45670. {
  45671. TreeViewItem* const ti = subItems.getUnchecked(i);
  45672. if (targetY < ti->totalHeight)
  45673. return ti->findItemRecursively (targetY);
  45674. targetY -= ti->totalHeight;
  45675. }
  45676. }
  45677. }
  45678. return 0;
  45679. }
  45680. int TreeViewItem::countSelectedItemsRecursively() const throw()
  45681. {
  45682. int total = 0;
  45683. if (isSelected())
  45684. ++total;
  45685. for (int i = subItems.size(); --i >= 0;)
  45686. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  45687. return total;
  45688. }
  45689. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  45690. {
  45691. if (isSelected())
  45692. {
  45693. if (index == 0)
  45694. return this;
  45695. --index;
  45696. }
  45697. if (index >= 0)
  45698. {
  45699. for (int i = 0; i < subItems.size(); ++i)
  45700. {
  45701. TreeViewItem* const item = subItems.getUnchecked(i);
  45702. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  45703. if (found != 0)
  45704. return found;
  45705. index -= item->countSelectedItemsRecursively();
  45706. }
  45707. }
  45708. return 0;
  45709. }
  45710. int TreeViewItem::getRowNumberInTree() const throw()
  45711. {
  45712. if (parentItem != 0 && ownerView != 0)
  45713. {
  45714. int n = 1 + parentItem->getRowNumberInTree();
  45715. int ourIndex = parentItem->subItems.indexOf (this);
  45716. jassert (ourIndex >= 0);
  45717. while (--ourIndex >= 0)
  45718. n += parentItem->subItems [ourIndex]->getNumRows();
  45719. if (parentItem->parentItem == 0
  45720. && ! ownerView->rootItemVisible)
  45721. --n;
  45722. return n;
  45723. }
  45724. else
  45725. {
  45726. return 0;
  45727. }
  45728. }
  45729. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  45730. {
  45731. drawLinesInside = drawLines;
  45732. }
  45733. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  45734. {
  45735. if (recurse && isOpen() && subItems.size() > 0)
  45736. return subItems [0];
  45737. if (parentItem != 0)
  45738. {
  45739. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  45740. if (nextIndex >= parentItem->subItems.size())
  45741. return parentItem->getNextVisibleItem (false);
  45742. return parentItem->subItems [nextIndex];
  45743. }
  45744. return 0;
  45745. }
  45746. const String TreeViewItem::getItemIdentifierString() const
  45747. {
  45748. String s;
  45749. if (parentItem != 0)
  45750. s = parentItem->getItemIdentifierString();
  45751. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  45752. }
  45753. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  45754. {
  45755. const String thisId (getUniqueName());
  45756. if (thisId == identifierString)
  45757. return this;
  45758. if (identifierString.startsWith (thisId + "/"))
  45759. {
  45760. const String remainingPath (identifierString.substring (thisId.length() + 1));
  45761. bool wasOpen = isOpen();
  45762. setOpen (true);
  45763. for (int i = subItems.size(); --i >= 0;)
  45764. {
  45765. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  45766. if (item != 0)
  45767. return item;
  45768. }
  45769. setOpen (wasOpen);
  45770. }
  45771. return 0;
  45772. }
  45773. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  45774. {
  45775. if (e.hasTagName ("CLOSED"))
  45776. {
  45777. setOpen (false);
  45778. }
  45779. else if (e.hasTagName ("OPEN"))
  45780. {
  45781. setOpen (true);
  45782. forEachXmlChildElement (e, n)
  45783. {
  45784. const String id (n->getStringAttribute ("id"));
  45785. for (int i = 0; i < subItems.size(); ++i)
  45786. {
  45787. TreeViewItem* const ti = subItems.getUnchecked(i);
  45788. if (ti->getUniqueName() == id)
  45789. {
  45790. ti->restoreOpennessState (*n);
  45791. break;
  45792. }
  45793. }
  45794. }
  45795. }
  45796. }
  45797. XmlElement* TreeViewItem::getOpennessState() const throw()
  45798. {
  45799. const String name (getUniqueName());
  45800. if (name.isNotEmpty())
  45801. {
  45802. XmlElement* e;
  45803. if (isOpen())
  45804. {
  45805. e = new XmlElement ("OPEN");
  45806. for (int i = 0; i < subItems.size(); ++i)
  45807. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  45808. }
  45809. else
  45810. {
  45811. e = new XmlElement ("CLOSED");
  45812. }
  45813. e->setAttribute ("id", name);
  45814. return e;
  45815. }
  45816. else
  45817. {
  45818. // trying to save the openness for an element that has no name - this won't
  45819. // work because it needs the names to identify what to open.
  45820. jassertfalse;
  45821. }
  45822. return 0;
  45823. }
  45824. END_JUCE_NAMESPACE
  45825. /*** End of inlined file: juce_TreeView.cpp ***/
  45826. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45827. BEGIN_JUCE_NAMESPACE
  45828. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  45829. : fileList (listToShow)
  45830. {
  45831. }
  45832. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  45833. {
  45834. }
  45835. FileBrowserListener::~FileBrowserListener()
  45836. {
  45837. }
  45838. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  45839. {
  45840. listeners.add (listener);
  45841. }
  45842. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  45843. {
  45844. listeners.remove (listener);
  45845. }
  45846. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  45847. {
  45848. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45849. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  45850. }
  45851. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  45852. {
  45853. if (fileList.getDirectory().exists())
  45854. {
  45855. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45856. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  45857. }
  45858. }
  45859. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  45860. {
  45861. if (fileList.getDirectory().exists())
  45862. {
  45863. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45864. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  45865. }
  45866. }
  45867. END_JUCE_NAMESPACE
  45868. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45869. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  45870. BEGIN_JUCE_NAMESPACE
  45871. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  45872. TimeSliceThread& thread_)
  45873. : fileFilter (fileFilter_),
  45874. thread (thread_),
  45875. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  45876. fileFindHandle (0),
  45877. shouldStop (true)
  45878. {
  45879. }
  45880. DirectoryContentsList::~DirectoryContentsList()
  45881. {
  45882. clear();
  45883. }
  45884. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  45885. {
  45886. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  45887. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  45888. }
  45889. bool DirectoryContentsList::ignoresHiddenFiles() const
  45890. {
  45891. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  45892. }
  45893. const File& DirectoryContentsList::getDirectory() const
  45894. {
  45895. return root;
  45896. }
  45897. void DirectoryContentsList::setDirectory (const File& directory,
  45898. const bool includeDirectories,
  45899. const bool includeFiles)
  45900. {
  45901. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  45902. if (directory != root)
  45903. {
  45904. clear();
  45905. root = directory;
  45906. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  45907. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  45908. }
  45909. int newFlags = fileTypeFlags;
  45910. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  45911. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  45912. setTypeFlags (newFlags);
  45913. }
  45914. void DirectoryContentsList::setTypeFlags (const int newFlags)
  45915. {
  45916. if (fileTypeFlags != newFlags)
  45917. {
  45918. fileTypeFlags = newFlags;
  45919. refresh();
  45920. }
  45921. }
  45922. void DirectoryContentsList::clear()
  45923. {
  45924. shouldStop = true;
  45925. thread.removeTimeSliceClient (this);
  45926. fileFindHandle = 0;
  45927. if (files.size() > 0)
  45928. {
  45929. files.clear();
  45930. changed();
  45931. }
  45932. }
  45933. void DirectoryContentsList::refresh()
  45934. {
  45935. clear();
  45936. if (root.isDirectory())
  45937. {
  45938. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  45939. shouldStop = false;
  45940. thread.addTimeSliceClient (this);
  45941. }
  45942. }
  45943. int DirectoryContentsList::getNumFiles() const
  45944. {
  45945. return files.size();
  45946. }
  45947. bool DirectoryContentsList::getFileInfo (const int index,
  45948. FileInfo& result) const
  45949. {
  45950. const ScopedLock sl (fileListLock);
  45951. const FileInfo* const info = files [index];
  45952. if (info != 0)
  45953. {
  45954. result = *info;
  45955. return true;
  45956. }
  45957. return false;
  45958. }
  45959. const File DirectoryContentsList::getFile (const int index) const
  45960. {
  45961. const ScopedLock sl (fileListLock);
  45962. const FileInfo* const info = files [index];
  45963. if (info != 0)
  45964. return root.getChildFile (info->filename);
  45965. return File::nonexistent;
  45966. }
  45967. bool DirectoryContentsList::isStillLoading() const
  45968. {
  45969. return fileFindHandle != 0;
  45970. }
  45971. void DirectoryContentsList::changed()
  45972. {
  45973. sendChangeMessage (this);
  45974. }
  45975. bool DirectoryContentsList::useTimeSlice()
  45976. {
  45977. const uint32 startTime = Time::getApproximateMillisecondCounter();
  45978. bool hasChanged = false;
  45979. for (int i = 100; --i >= 0;)
  45980. {
  45981. if (! checkNextFile (hasChanged))
  45982. {
  45983. if (hasChanged)
  45984. changed();
  45985. return false;
  45986. }
  45987. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  45988. break;
  45989. }
  45990. if (hasChanged)
  45991. changed();
  45992. return true;
  45993. }
  45994. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  45995. {
  45996. if (fileFindHandle != 0)
  45997. {
  45998. bool fileFoundIsDir, isHidden, isReadOnly;
  45999. int64 fileSize;
  46000. Time modTime, creationTime;
  46001. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46002. &modTime, &creationTime, &isReadOnly))
  46003. {
  46004. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46005. fileSize, modTime, creationTime, isReadOnly))
  46006. {
  46007. hasChanged = true;
  46008. }
  46009. return true;
  46010. }
  46011. else
  46012. {
  46013. fileFindHandle = 0;
  46014. }
  46015. }
  46016. return false;
  46017. }
  46018. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46019. const DirectoryContentsList::FileInfo* const second)
  46020. {
  46021. #if JUCE_WINDOWS
  46022. if (first->isDirectory != second->isDirectory)
  46023. return first->isDirectory ? -1 : 1;
  46024. #endif
  46025. return first->filename.compareIgnoreCase (second->filename);
  46026. }
  46027. bool DirectoryContentsList::addFile (const File& file,
  46028. const bool isDir,
  46029. const int64 fileSize,
  46030. const Time& modTime,
  46031. const Time& creationTime,
  46032. const bool isReadOnly)
  46033. {
  46034. if (fileFilter == 0
  46035. || ((! isDir) && fileFilter->isFileSuitable (file))
  46036. || (isDir && fileFilter->isDirectorySuitable (file)))
  46037. {
  46038. ScopedPointer <FileInfo> info (new FileInfo());
  46039. info->filename = file.getFileName();
  46040. info->fileSize = fileSize;
  46041. info->modificationTime = modTime;
  46042. info->creationTime = creationTime;
  46043. info->isDirectory = isDir;
  46044. info->isReadOnly = isReadOnly;
  46045. const ScopedLock sl (fileListLock);
  46046. for (int i = files.size(); --i >= 0;)
  46047. if (files.getUnchecked(i)->filename == info->filename)
  46048. return false;
  46049. files.addSorted (*this, info.release());
  46050. return true;
  46051. }
  46052. return false;
  46053. }
  46054. END_JUCE_NAMESPACE
  46055. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46056. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46057. BEGIN_JUCE_NAMESPACE
  46058. FileBrowserComponent::FileBrowserComponent (int flags_,
  46059. const File& initialFileOrDirectory,
  46060. const FileFilter* fileFilter_,
  46061. FilePreviewComponent* previewComp_)
  46062. : FileFilter (String::empty),
  46063. fileFilter (fileFilter_),
  46064. flags (flags_),
  46065. previewComp (previewComp_),
  46066. thread ("Juce FileBrowser")
  46067. {
  46068. // You need to specify one or other of the open/save flags..
  46069. jassert ((flags & (saveMode | openMode)) != 0);
  46070. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46071. // You need to specify at least one of these flags..
  46072. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46073. String filename;
  46074. if (initialFileOrDirectory == File::nonexistent)
  46075. {
  46076. currentRoot = File::getCurrentWorkingDirectory();
  46077. }
  46078. else if (initialFileOrDirectory.isDirectory())
  46079. {
  46080. currentRoot = initialFileOrDirectory;
  46081. }
  46082. else
  46083. {
  46084. chosenFiles.add (initialFileOrDirectory);
  46085. currentRoot = initialFileOrDirectory.getParentDirectory();
  46086. filename = initialFileOrDirectory.getFileName();
  46087. }
  46088. fileList = new DirectoryContentsList (this, thread);
  46089. if ((flags & useTreeView) != 0)
  46090. {
  46091. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46092. if ((flags & canSelectMultipleItems) != 0)
  46093. tree->setMultiSelectEnabled (true);
  46094. addAndMakeVisible (tree);
  46095. fileListComponent = tree;
  46096. }
  46097. else
  46098. {
  46099. FileListComponent* const list = new FileListComponent (*fileList);
  46100. list->setOutlineThickness (1);
  46101. if ((flags & canSelectMultipleItems) != 0)
  46102. list->setMultipleSelectionEnabled (true);
  46103. addAndMakeVisible (list);
  46104. fileListComponent = list;
  46105. }
  46106. fileListComponent->addListener (this);
  46107. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  46108. currentPathBox->setEditableText (true);
  46109. StringArray rootNames, rootPaths;
  46110. const BigInteger separators (getRoots (rootNames, rootPaths));
  46111. for (int i = 0; i < rootNames.size(); ++i)
  46112. {
  46113. if (separators [i])
  46114. currentPathBox->addSeparator();
  46115. currentPathBox->addItem (rootNames[i], i + 1);
  46116. }
  46117. currentPathBox->addSeparator();
  46118. currentPathBox->addListener (this);
  46119. addAndMakeVisible (filenameBox = new TextEditor());
  46120. filenameBox->setMultiLine (false);
  46121. filenameBox->setSelectAllWhenFocused (true);
  46122. filenameBox->setText (filename, false);
  46123. filenameBox->addListener (this);
  46124. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46125. Label* label = new Label ("f", TRANS("file:"));
  46126. addAndMakeVisible (label);
  46127. label->attachToComponent (filenameBox, true);
  46128. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46129. goUpButton->addButtonListener (this);
  46130. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46131. if (previewComp != 0)
  46132. addAndMakeVisible (previewComp);
  46133. setRoot (currentRoot);
  46134. thread.startThread (4);
  46135. }
  46136. FileBrowserComponent::~FileBrowserComponent()
  46137. {
  46138. if (previewComp != 0)
  46139. removeChildComponent (previewComp);
  46140. deleteAllChildren();
  46141. fileList = 0;
  46142. thread.stopThread (10000);
  46143. }
  46144. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46145. {
  46146. listeners.add (newListener);
  46147. }
  46148. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46149. {
  46150. listeners.remove (listener);
  46151. }
  46152. bool FileBrowserComponent::isSaveMode() const throw()
  46153. {
  46154. return (flags & saveMode) != 0;
  46155. }
  46156. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46157. {
  46158. if (chosenFiles.size() == 0 && currentFileIsValid())
  46159. return 1;
  46160. return chosenFiles.size();
  46161. }
  46162. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46163. {
  46164. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  46165. return currentRoot;
  46166. if (! filenameBox->isReadOnly())
  46167. return currentRoot.getChildFile (filenameBox->getText());
  46168. return chosenFiles[index];
  46169. }
  46170. bool FileBrowserComponent::currentFileIsValid() const
  46171. {
  46172. if (isSaveMode())
  46173. return ! getSelectedFile (0).isDirectory();
  46174. else
  46175. return getSelectedFile (0).exists();
  46176. }
  46177. const File FileBrowserComponent::getHighlightedFile() const throw()
  46178. {
  46179. return fileListComponent->getSelectedFile (0);
  46180. }
  46181. void FileBrowserComponent::deselectAllFiles()
  46182. {
  46183. fileListComponent->deselectAllFiles();
  46184. }
  46185. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46186. {
  46187. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  46188. : false;
  46189. }
  46190. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46191. {
  46192. return true;
  46193. }
  46194. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46195. {
  46196. if (f.isDirectory())
  46197. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46198. return (flags & canSelectFiles) != 0 && f.exists()
  46199. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46200. }
  46201. const File FileBrowserComponent::getRoot() const
  46202. {
  46203. return currentRoot;
  46204. }
  46205. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46206. {
  46207. if (currentRoot != newRootDirectory)
  46208. {
  46209. fileListComponent->scrollToTop();
  46210. String path (newRootDirectory.getFullPathName());
  46211. if (path.isEmpty())
  46212. path = File::separatorString;
  46213. StringArray rootNames, rootPaths;
  46214. getRoots (rootNames, rootPaths);
  46215. if (! rootPaths.contains (path, true))
  46216. {
  46217. bool alreadyListed = false;
  46218. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  46219. {
  46220. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  46221. {
  46222. alreadyListed = true;
  46223. break;
  46224. }
  46225. }
  46226. if (! alreadyListed)
  46227. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  46228. }
  46229. }
  46230. currentRoot = newRootDirectory;
  46231. fileList->setDirectory (currentRoot, true, true);
  46232. String currentRootName (currentRoot.getFullPathName());
  46233. if (currentRootName.isEmpty())
  46234. currentRootName = File::separatorString;
  46235. currentPathBox->setText (currentRootName, true);
  46236. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46237. && currentRoot.getParentDirectory() != currentRoot);
  46238. }
  46239. void FileBrowserComponent::goUp()
  46240. {
  46241. setRoot (getRoot().getParentDirectory());
  46242. }
  46243. void FileBrowserComponent::refresh()
  46244. {
  46245. fileList->refresh();
  46246. }
  46247. const String FileBrowserComponent::getActionVerb() const
  46248. {
  46249. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46250. }
  46251. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46252. {
  46253. return previewComp;
  46254. }
  46255. void FileBrowserComponent::resized()
  46256. {
  46257. getLookAndFeel()
  46258. .layoutFileBrowserComponent (*this, fileListComponent,
  46259. previewComp, currentPathBox,
  46260. filenameBox, goUpButton);
  46261. }
  46262. void FileBrowserComponent::sendListenerChangeMessage()
  46263. {
  46264. Component::BailOutChecker checker (this);
  46265. if (previewComp != 0)
  46266. previewComp->selectedFileChanged (getSelectedFile (0));
  46267. // You shouldn't delete the browser when the file gets changed!
  46268. jassert (! checker.shouldBailOut());
  46269. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46270. }
  46271. void FileBrowserComponent::selectionChanged()
  46272. {
  46273. StringArray newFilenames;
  46274. bool resetChosenFiles = true;
  46275. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46276. {
  46277. const File f (fileListComponent->getSelectedFile (i));
  46278. if (isFileOrDirSuitable (f))
  46279. {
  46280. if (resetChosenFiles)
  46281. {
  46282. chosenFiles.clear();
  46283. resetChosenFiles = false;
  46284. }
  46285. chosenFiles.add (f);
  46286. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46287. }
  46288. }
  46289. if (newFilenames.size() > 0)
  46290. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  46291. sendListenerChangeMessage();
  46292. }
  46293. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46294. {
  46295. Component::BailOutChecker checker (this);
  46296. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46297. }
  46298. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46299. {
  46300. if (f.isDirectory())
  46301. {
  46302. setRoot (f);
  46303. if ((flags & canSelectDirectories) != 0)
  46304. filenameBox->setText (String::empty);
  46305. }
  46306. else
  46307. {
  46308. Component::BailOutChecker checker (this);
  46309. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46310. }
  46311. }
  46312. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46313. {
  46314. (void) key;
  46315. #if JUCE_LINUX || JUCE_WINDOWS
  46316. if (key.getModifiers().isCommandDown()
  46317. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46318. {
  46319. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46320. fileList->refresh();
  46321. return true;
  46322. }
  46323. #endif
  46324. return false;
  46325. }
  46326. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46327. {
  46328. sendListenerChangeMessage();
  46329. }
  46330. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46331. {
  46332. if (filenameBox->getText().containsChar (File::separator))
  46333. {
  46334. const File f (currentRoot.getChildFile (filenameBox->getText()));
  46335. if (f.isDirectory())
  46336. {
  46337. setRoot (f);
  46338. chosenFiles.clear();
  46339. filenameBox->setText (String::empty);
  46340. }
  46341. else
  46342. {
  46343. setRoot (f.getParentDirectory());
  46344. chosenFiles.clear();
  46345. chosenFiles.add (f);
  46346. filenameBox->setText (f.getFileName());
  46347. }
  46348. }
  46349. else
  46350. {
  46351. fileDoubleClicked (getSelectedFile (0));
  46352. }
  46353. }
  46354. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46355. {
  46356. }
  46357. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46358. {
  46359. if (! isSaveMode())
  46360. selectionChanged();
  46361. }
  46362. void FileBrowserComponent::buttonClicked (Button*)
  46363. {
  46364. goUp();
  46365. }
  46366. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46367. {
  46368. const String newText (currentPathBox->getText().trim().unquoted());
  46369. if (newText.isNotEmpty())
  46370. {
  46371. const int index = currentPathBox->getSelectedId() - 1;
  46372. StringArray rootNames, rootPaths;
  46373. getRoots (rootNames, rootPaths);
  46374. if (rootPaths [index].isNotEmpty())
  46375. {
  46376. setRoot (File (rootPaths [index]));
  46377. }
  46378. else
  46379. {
  46380. File f (newText);
  46381. for (;;)
  46382. {
  46383. if (f.isDirectory())
  46384. {
  46385. setRoot (f);
  46386. break;
  46387. }
  46388. if (f.getParentDirectory() == f)
  46389. break;
  46390. f = f.getParentDirectory();
  46391. }
  46392. }
  46393. }
  46394. }
  46395. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46396. {
  46397. BigInteger separators;
  46398. #if JUCE_WINDOWS
  46399. Array<File> roots;
  46400. File::findFileSystemRoots (roots);
  46401. rootPaths.clear();
  46402. for (int i = 0; i < roots.size(); ++i)
  46403. {
  46404. const File& drive = roots.getReference(i);
  46405. String name (drive.getFullPathName());
  46406. rootPaths.add (name);
  46407. if (drive.isOnHardDisk())
  46408. {
  46409. String volume (drive.getVolumeLabel());
  46410. if (volume.isEmpty())
  46411. volume = TRANS("Hard Drive");
  46412. name << " [" << drive.getVolumeLabel() << ']';
  46413. }
  46414. else if (drive.isOnCDRomDrive())
  46415. {
  46416. name << TRANS(" [CD/DVD drive]");
  46417. }
  46418. rootNames.add (name);
  46419. }
  46420. separators.setBit (rootPaths.size());
  46421. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46422. rootNames.add ("Documents");
  46423. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46424. rootNames.add ("Desktop");
  46425. #endif
  46426. #if JUCE_MAC
  46427. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46428. rootNames.add ("Home folder");
  46429. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46430. rootNames.add ("Documents");
  46431. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46432. rootNames.add ("Desktop");
  46433. separators.setBit (rootPaths.size());
  46434. Array <File> volumes;
  46435. File vol ("/Volumes");
  46436. vol.findChildFiles (volumes, File::findDirectories, false);
  46437. for (int i = 0; i < volumes.size(); ++i)
  46438. {
  46439. const File& volume = volumes.getReference(i);
  46440. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46441. {
  46442. rootPaths.add (volume.getFullPathName());
  46443. rootNames.add (volume.getFileName());
  46444. }
  46445. }
  46446. #endif
  46447. #if JUCE_LINUX
  46448. rootPaths.add ("/");
  46449. rootNames.add ("/");
  46450. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46451. rootNames.add ("Home folder");
  46452. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46453. rootNames.add ("Desktop");
  46454. #endif
  46455. return separators;
  46456. }
  46457. END_JUCE_NAMESPACE
  46458. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46459. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46460. BEGIN_JUCE_NAMESPACE
  46461. FileChooser::FileChooser (const String& chooserBoxTitle,
  46462. const File& currentFileOrDirectory,
  46463. const String& fileFilters,
  46464. const bool useNativeDialogBox_)
  46465. : title (chooserBoxTitle),
  46466. filters (fileFilters),
  46467. startingFile (currentFileOrDirectory),
  46468. useNativeDialogBox (useNativeDialogBox_)
  46469. {
  46470. #if JUCE_LINUX
  46471. useNativeDialogBox = false;
  46472. #endif
  46473. if (! fileFilters.containsNonWhitespaceChars())
  46474. filters = "*";
  46475. }
  46476. FileChooser::~FileChooser()
  46477. {
  46478. }
  46479. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  46480. {
  46481. return showDialog (false, true, false, false, false, previewComponent);
  46482. }
  46483. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  46484. {
  46485. return showDialog (false, true, false, false, true, previewComponent);
  46486. }
  46487. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  46488. {
  46489. return showDialog (true, true, false, false, true, previewComponent);
  46490. }
  46491. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  46492. {
  46493. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  46494. }
  46495. bool FileChooser::browseForDirectory()
  46496. {
  46497. return showDialog (true, false, false, false, false, 0);
  46498. }
  46499. const File FileChooser::getResult() const
  46500. {
  46501. // if you've used a multiple-file select, you should use the getResults() method
  46502. // to retrieve all the files that were chosen.
  46503. jassert (results.size() <= 1);
  46504. return results.getFirst();
  46505. }
  46506. const Array<File>& FileChooser::getResults() const
  46507. {
  46508. return results;
  46509. }
  46510. bool FileChooser::showDialog (const bool selectsDirectories,
  46511. const bool selectsFiles,
  46512. const bool isSave,
  46513. const bool warnAboutOverwritingExistingFiles,
  46514. const bool selectMultipleFiles,
  46515. FilePreviewComponent* const previewComponent)
  46516. {
  46517. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  46518. results.clear();
  46519. // the preview component needs to be the right size before you pass it in here..
  46520. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  46521. && previewComponent->getHeight() > 10));
  46522. #if JUCE_WINDOWS
  46523. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  46524. #elif JUCE_MAC
  46525. if (useNativeDialogBox && (previewComponent == 0))
  46526. #else
  46527. if (false)
  46528. #endif
  46529. {
  46530. showPlatformDialog (results, title, startingFile, filters,
  46531. selectsDirectories, selectsFiles, isSave,
  46532. warnAboutOverwritingExistingFiles,
  46533. selectMultipleFiles,
  46534. previewComponent);
  46535. }
  46536. else
  46537. {
  46538. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  46539. selectsDirectories ? "*" : String::empty,
  46540. String::empty);
  46541. int flags = isSave ? FileBrowserComponent::saveMode
  46542. : FileBrowserComponent::openMode;
  46543. if (selectsFiles)
  46544. flags |= FileBrowserComponent::canSelectFiles;
  46545. if (selectsDirectories)
  46546. {
  46547. flags |= FileBrowserComponent::canSelectDirectories;
  46548. if (! isSave)
  46549. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  46550. }
  46551. if (selectMultipleFiles)
  46552. flags |= FileBrowserComponent::canSelectMultipleItems;
  46553. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  46554. FileChooserDialogBox box (title, String::empty,
  46555. browserComponent,
  46556. warnAboutOverwritingExistingFiles,
  46557. browserComponent.findColour (AlertWindow::backgroundColourId));
  46558. if (box.show())
  46559. {
  46560. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  46561. results.add (browserComponent.getSelectedFile (i));
  46562. }
  46563. }
  46564. if (previouslyFocused != 0)
  46565. previouslyFocused->grabKeyboardFocus();
  46566. return results.size() > 0;
  46567. }
  46568. FilePreviewComponent::FilePreviewComponent()
  46569. {
  46570. }
  46571. FilePreviewComponent::~FilePreviewComponent()
  46572. {
  46573. }
  46574. END_JUCE_NAMESPACE
  46575. /*** End of inlined file: juce_FileChooser.cpp ***/
  46576. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  46577. BEGIN_JUCE_NAMESPACE
  46578. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  46579. const String& instructions,
  46580. FileBrowserComponent& chooserComponent,
  46581. const bool warnAboutOverwritingExistingFiles_,
  46582. const Colour& backgroundColour)
  46583. : ResizableWindow (name, backgroundColour, true),
  46584. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  46585. {
  46586. content = new ContentComponent();
  46587. content->setName (name);
  46588. content->instructions = instructions;
  46589. content->chooserComponent = &chooserComponent;
  46590. content->addAndMakeVisible (&chooserComponent);
  46591. content->okButton = new TextButton (chooserComponent.getActionVerb());
  46592. content->addAndMakeVisible (content->okButton);
  46593. content->okButton->addButtonListener (this);
  46594. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  46595. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  46596. content->cancelButton = new TextButton (TRANS("Cancel"));
  46597. content->addAndMakeVisible (content->cancelButton);
  46598. content->cancelButton->addButtonListener (this);
  46599. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  46600. setContentComponent (content);
  46601. setResizable (true, true);
  46602. setResizeLimits (300, 300, 1200, 1000);
  46603. content->chooserComponent->addListener (this);
  46604. }
  46605. FileChooserDialogBox::~FileChooserDialogBox()
  46606. {
  46607. content->chooserComponent->removeListener (this);
  46608. }
  46609. bool FileChooserDialogBox::show (int w, int h)
  46610. {
  46611. return showAt (-1, -1, w, h);
  46612. }
  46613. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  46614. {
  46615. if (w <= 0)
  46616. {
  46617. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  46618. if (previewComp != 0)
  46619. w = 400 + previewComp->getWidth();
  46620. else
  46621. w = 600;
  46622. }
  46623. if (h <= 0)
  46624. h = 500;
  46625. if (x < 0 || y < 0)
  46626. centreWithSize (w, h);
  46627. else
  46628. setBounds (x, y, w, h);
  46629. const bool ok = (runModalLoop() != 0);
  46630. setVisible (false);
  46631. return ok;
  46632. }
  46633. void FileChooserDialogBox::buttonClicked (Button* button)
  46634. {
  46635. if (button == content->okButton)
  46636. {
  46637. if (warnAboutOverwritingExistingFiles
  46638. && content->chooserComponent->isSaveMode()
  46639. && content->chooserComponent->getSelectedFile(0).exists())
  46640. {
  46641. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  46642. TRANS("File already exists"),
  46643. TRANS("There's already a file called:")
  46644. + "\n\n" + content->chooserComponent->getSelectedFile(0).getFullPathName()
  46645. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  46646. TRANS("overwrite"),
  46647. TRANS("cancel")))
  46648. {
  46649. return;
  46650. }
  46651. }
  46652. exitModalState (1);
  46653. }
  46654. else if (button == content->cancelButton)
  46655. closeButtonPressed();
  46656. }
  46657. void FileChooserDialogBox::closeButtonPressed()
  46658. {
  46659. setVisible (false);
  46660. }
  46661. void FileChooserDialogBox::selectionChanged()
  46662. {
  46663. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  46664. }
  46665. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  46666. {
  46667. }
  46668. void FileChooserDialogBox::fileDoubleClicked (const File&)
  46669. {
  46670. selectionChanged();
  46671. content->okButton->triggerClick();
  46672. }
  46673. FileChooserDialogBox::ContentComponent::ContentComponent()
  46674. {
  46675. setInterceptsMouseClicks (false, true);
  46676. }
  46677. FileChooserDialogBox::ContentComponent::~ContentComponent()
  46678. {
  46679. delete okButton;
  46680. delete cancelButton;
  46681. }
  46682. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  46683. {
  46684. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  46685. text.draw (g);
  46686. }
  46687. void FileChooserDialogBox::ContentComponent::resized()
  46688. {
  46689. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  46690. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  46691. const int y = roundToInt (bb.getBottom()) + 10;
  46692. const int buttonHeight = 26;
  46693. const int buttonY = getHeight() - buttonHeight - 8;
  46694. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  46695. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  46696. proportionOfWidth (0.2f), buttonHeight);
  46697. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  46698. proportionOfWidth (0.2f), buttonHeight);
  46699. }
  46700. END_JUCE_NAMESPACE
  46701. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  46702. /*** Start of inlined file: juce_FileFilter.cpp ***/
  46703. BEGIN_JUCE_NAMESPACE
  46704. FileFilter::FileFilter (const String& filterDescription)
  46705. : description (filterDescription)
  46706. {
  46707. }
  46708. FileFilter::~FileFilter()
  46709. {
  46710. }
  46711. const String& FileFilter::getDescription() const throw()
  46712. {
  46713. return description;
  46714. }
  46715. END_JUCE_NAMESPACE
  46716. /*** End of inlined file: juce_FileFilter.cpp ***/
  46717. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  46718. BEGIN_JUCE_NAMESPACE
  46719. const Image juce_createIconForFile (const File& file);
  46720. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  46721. : ListBox (String::empty, 0),
  46722. DirectoryContentsDisplayComponent (listToShow)
  46723. {
  46724. setModel (this);
  46725. fileList.addChangeListener (this);
  46726. }
  46727. FileListComponent::~FileListComponent()
  46728. {
  46729. fileList.removeChangeListener (this);
  46730. }
  46731. int FileListComponent::getNumSelectedFiles() const
  46732. {
  46733. return getNumSelectedRows();
  46734. }
  46735. const File FileListComponent::getSelectedFile (int index) const
  46736. {
  46737. return fileList.getFile (getSelectedRow (index));
  46738. }
  46739. void FileListComponent::deselectAllFiles()
  46740. {
  46741. deselectAllRows();
  46742. }
  46743. void FileListComponent::scrollToTop()
  46744. {
  46745. getVerticalScrollBar()->setCurrentRangeStart (0);
  46746. }
  46747. void FileListComponent::changeListenerCallback (void*)
  46748. {
  46749. updateContent();
  46750. if (lastDirectory != fileList.getDirectory())
  46751. {
  46752. lastDirectory = fileList.getDirectory();
  46753. deselectAllRows();
  46754. }
  46755. }
  46756. class FileListItemComponent : public Component,
  46757. public TimeSliceClient,
  46758. public AsyncUpdater
  46759. {
  46760. public:
  46761. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  46762. : owner (owner_), thread (thread_),
  46763. highlighted (false), index (0), icon (0)
  46764. {
  46765. }
  46766. ~FileListItemComponent()
  46767. {
  46768. thread.removeTimeSliceClient (this);
  46769. clearIcon();
  46770. }
  46771. void paint (Graphics& g)
  46772. {
  46773. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  46774. file.getFileName(),
  46775. &icon,
  46776. fileSize, modTime,
  46777. isDirectory, highlighted,
  46778. index);
  46779. }
  46780. void mouseDown (const MouseEvent& e)
  46781. {
  46782. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  46783. owner.sendMouseClickMessage (file, e);
  46784. }
  46785. void mouseDoubleClick (const MouseEvent&)
  46786. {
  46787. owner.sendDoubleClickMessage (file);
  46788. }
  46789. void update (const File& root,
  46790. const DirectoryContentsList::FileInfo* const fileInfo,
  46791. const int index_,
  46792. const bool highlighted_)
  46793. {
  46794. thread.removeTimeSliceClient (this);
  46795. if (highlighted_ != highlighted
  46796. || index_ != index)
  46797. {
  46798. index = index_;
  46799. highlighted = highlighted_;
  46800. repaint();
  46801. }
  46802. File newFile;
  46803. String newFileSize;
  46804. String newModTime;
  46805. if (fileInfo != 0)
  46806. {
  46807. newFile = root.getChildFile (fileInfo->filename);
  46808. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  46809. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  46810. }
  46811. if (newFile != file
  46812. || fileSize != newFileSize
  46813. || modTime != newModTime)
  46814. {
  46815. file = newFile;
  46816. fileSize = newFileSize;
  46817. modTime = newModTime;
  46818. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  46819. repaint();
  46820. clearIcon();
  46821. }
  46822. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  46823. {
  46824. updateIcon (true);
  46825. if (! icon.isValid())
  46826. thread.addTimeSliceClient (this);
  46827. }
  46828. }
  46829. bool useTimeSlice()
  46830. {
  46831. updateIcon (false);
  46832. return false;
  46833. }
  46834. void handleAsyncUpdate()
  46835. {
  46836. repaint();
  46837. }
  46838. juce_UseDebuggingNewOperator
  46839. private:
  46840. FileListComponent& owner;
  46841. TimeSliceThread& thread;
  46842. bool highlighted;
  46843. int index;
  46844. File file;
  46845. String fileSize;
  46846. String modTime;
  46847. Image icon;
  46848. bool isDirectory;
  46849. void clearIcon()
  46850. {
  46851. icon = Image::null;
  46852. }
  46853. void updateIcon (const bool onlyUpdateIfCached)
  46854. {
  46855. if (icon.isNull())
  46856. {
  46857. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  46858. Image im (ImageCache::getFromHashCode (hashCode));
  46859. if (im.isNull() && ! onlyUpdateIfCached)
  46860. {
  46861. im = juce_createIconForFile (file);
  46862. if (im.isValid())
  46863. ImageCache::addImageToCache (im, hashCode);
  46864. }
  46865. if (im.isValid())
  46866. {
  46867. icon = im;
  46868. triggerAsyncUpdate();
  46869. }
  46870. }
  46871. }
  46872. };
  46873. int FileListComponent::getNumRows()
  46874. {
  46875. return fileList.getNumFiles();
  46876. }
  46877. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  46878. {
  46879. }
  46880. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  46881. {
  46882. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  46883. if (comp == 0)
  46884. {
  46885. delete existingComponentToUpdate;
  46886. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  46887. }
  46888. DirectoryContentsList::FileInfo fileInfo;
  46889. if (fileList.getFileInfo (row, fileInfo))
  46890. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  46891. else
  46892. comp->update (fileList.getDirectory(), 0, row, isSelected);
  46893. return comp;
  46894. }
  46895. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  46896. {
  46897. sendSelectionChangeMessage();
  46898. }
  46899. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  46900. {
  46901. }
  46902. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  46903. {
  46904. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  46905. }
  46906. END_JUCE_NAMESPACE
  46907. /*** End of inlined file: juce_FileListComponent.cpp ***/
  46908. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  46909. BEGIN_JUCE_NAMESPACE
  46910. FilenameComponent::FilenameComponent (const String& name,
  46911. const File& currentFile,
  46912. const bool canEditFilename,
  46913. const bool isDirectory,
  46914. const bool isForSaving,
  46915. const String& fileBrowserWildcard,
  46916. const String& enforcedSuffix_,
  46917. const String& textWhenNothingSelected)
  46918. : Component (name),
  46919. maxRecentFiles (30),
  46920. isDir (isDirectory),
  46921. isSaving (isForSaving),
  46922. isFileDragOver (false),
  46923. wildcard (fileBrowserWildcard),
  46924. enforcedSuffix (enforcedSuffix_)
  46925. {
  46926. addAndMakeVisible (&filenameBox);
  46927. filenameBox.setEditableText (canEditFilename);
  46928. filenameBox.addListener (this);
  46929. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  46930. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  46931. setBrowseButtonText ("...");
  46932. setCurrentFile (currentFile, true);
  46933. }
  46934. FilenameComponent::~FilenameComponent()
  46935. {
  46936. }
  46937. void FilenameComponent::paintOverChildren (Graphics& g)
  46938. {
  46939. if (isFileDragOver)
  46940. {
  46941. g.setColour (Colours::red.withAlpha (0.2f));
  46942. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  46943. }
  46944. }
  46945. void FilenameComponent::resized()
  46946. {
  46947. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  46948. }
  46949. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  46950. {
  46951. browseButtonText = newBrowseButtonText;
  46952. lookAndFeelChanged();
  46953. }
  46954. void FilenameComponent::lookAndFeelChanged()
  46955. {
  46956. browseButton = 0;
  46957. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  46958. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  46959. resized();
  46960. browseButton->addButtonListener (this);
  46961. }
  46962. void FilenameComponent::setTooltip (const String& newTooltip)
  46963. {
  46964. SettableTooltipClient::setTooltip (newTooltip);
  46965. filenameBox.setTooltip (newTooltip);
  46966. }
  46967. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  46968. {
  46969. defaultBrowseFile = newDefaultDirectory;
  46970. }
  46971. void FilenameComponent::buttonClicked (Button*)
  46972. {
  46973. FileChooser fc (TRANS("Choose a new file"),
  46974. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  46975. : getCurrentFile(),
  46976. wildcard);
  46977. if (isDir ? fc.browseForDirectory()
  46978. : (isSaving ? fc.browseForFileToSave (false)
  46979. : fc.browseForFileToOpen()))
  46980. {
  46981. setCurrentFile (fc.getResult(), true);
  46982. }
  46983. }
  46984. void FilenameComponent::comboBoxChanged (ComboBox*)
  46985. {
  46986. setCurrentFile (getCurrentFile(), true);
  46987. }
  46988. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  46989. {
  46990. return true;
  46991. }
  46992. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  46993. {
  46994. isFileDragOver = false;
  46995. repaint();
  46996. const File f (filenames[0]);
  46997. if (f.exists() && (f.isDirectory() == isDir))
  46998. setCurrentFile (f, true);
  46999. }
  47000. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47001. {
  47002. isFileDragOver = true;
  47003. repaint();
  47004. }
  47005. void FilenameComponent::fileDragExit (const StringArray&)
  47006. {
  47007. isFileDragOver = false;
  47008. repaint();
  47009. }
  47010. const File FilenameComponent::getCurrentFile() const
  47011. {
  47012. File f (filenameBox.getText());
  47013. if (enforcedSuffix.isNotEmpty())
  47014. f = f.withFileExtension (enforcedSuffix);
  47015. return f;
  47016. }
  47017. void FilenameComponent::setCurrentFile (File newFile,
  47018. const bool addToRecentlyUsedList,
  47019. const bool sendChangeNotification)
  47020. {
  47021. if (enforcedSuffix.isNotEmpty())
  47022. newFile = newFile.withFileExtension (enforcedSuffix);
  47023. if (newFile.getFullPathName() != lastFilename)
  47024. {
  47025. lastFilename = newFile.getFullPathName();
  47026. if (addToRecentlyUsedList)
  47027. addRecentlyUsedFile (newFile);
  47028. filenameBox.setText (lastFilename, true);
  47029. if (sendChangeNotification)
  47030. triggerAsyncUpdate();
  47031. }
  47032. }
  47033. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47034. {
  47035. filenameBox.setEditableText (shouldBeEditable);
  47036. }
  47037. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47038. {
  47039. StringArray names;
  47040. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47041. names.add (filenameBox.getItemText (i));
  47042. return names;
  47043. }
  47044. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47045. {
  47046. if (filenames != getRecentlyUsedFilenames())
  47047. {
  47048. filenameBox.clear();
  47049. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47050. filenameBox.addItem (filenames[i], i + 1);
  47051. }
  47052. }
  47053. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47054. {
  47055. maxRecentFiles = jmax (1, newMaximum);
  47056. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47057. }
  47058. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47059. {
  47060. StringArray files (getRecentlyUsedFilenames());
  47061. if (file.getFullPathName().isNotEmpty())
  47062. {
  47063. files.removeString (file.getFullPathName(), true);
  47064. files.insert (0, file.getFullPathName());
  47065. setRecentlyUsedFilenames (files);
  47066. }
  47067. }
  47068. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47069. {
  47070. listeners.add (listener);
  47071. }
  47072. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47073. {
  47074. listeners.remove (listener);
  47075. }
  47076. void FilenameComponent::handleAsyncUpdate()
  47077. {
  47078. Component::BailOutChecker checker (this);
  47079. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47080. }
  47081. END_JUCE_NAMESPACE
  47082. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47083. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47084. BEGIN_JUCE_NAMESPACE
  47085. FileSearchPathListComponent::FileSearchPathListComponent()
  47086. {
  47087. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  47088. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47089. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47090. listBox->setOutlineThickness (1);
  47091. addAndMakeVisible (addButton = new TextButton ("+"));
  47092. addButton->addButtonListener (this);
  47093. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47094. addAndMakeVisible (removeButton = new TextButton ("-"));
  47095. removeButton->addButtonListener (this);
  47096. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47097. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  47098. changeButton->addButtonListener (this);
  47099. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47100. upButton->addButtonListener (this);
  47101. {
  47102. Path arrowPath;
  47103. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47104. DrawablePath arrowImage;
  47105. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47106. arrowImage.setPath (arrowPath);
  47107. upButton->setImages (&arrowImage);
  47108. }
  47109. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47110. downButton->addButtonListener (this);
  47111. {
  47112. Path arrowPath;
  47113. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47114. DrawablePath arrowImage;
  47115. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47116. arrowImage.setPath (arrowPath);
  47117. downButton->setImages (&arrowImage);
  47118. }
  47119. updateButtons();
  47120. }
  47121. FileSearchPathListComponent::~FileSearchPathListComponent()
  47122. {
  47123. deleteAllChildren();
  47124. }
  47125. void FileSearchPathListComponent::updateButtons()
  47126. {
  47127. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  47128. removeButton->setEnabled (anythingSelected);
  47129. changeButton->setEnabled (anythingSelected);
  47130. upButton->setEnabled (anythingSelected);
  47131. downButton->setEnabled (anythingSelected);
  47132. }
  47133. void FileSearchPathListComponent::changed()
  47134. {
  47135. listBox->updateContent();
  47136. listBox->repaint();
  47137. updateButtons();
  47138. }
  47139. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47140. {
  47141. if (newPath.toString() != path.toString())
  47142. {
  47143. path = newPath;
  47144. changed();
  47145. }
  47146. }
  47147. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47148. {
  47149. defaultBrowseTarget = newDefaultDirectory;
  47150. }
  47151. int FileSearchPathListComponent::getNumRows()
  47152. {
  47153. return path.getNumPaths();
  47154. }
  47155. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47156. {
  47157. if (rowIsSelected)
  47158. g.fillAll (findColour (TextEditor::highlightColourId));
  47159. g.setColour (findColour (ListBox::textColourId));
  47160. Font f (height * 0.7f);
  47161. f.setHorizontalScale (0.9f);
  47162. g.setFont (f);
  47163. g.drawText (path [rowNumber].getFullPathName(),
  47164. 4, 0, width - 6, height,
  47165. Justification::centredLeft, true);
  47166. }
  47167. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47168. {
  47169. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  47170. {
  47171. path.remove (row);
  47172. changed();
  47173. }
  47174. }
  47175. void FileSearchPathListComponent::returnKeyPressed (int row)
  47176. {
  47177. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47178. if (chooser.browseForDirectory())
  47179. {
  47180. path.remove (row);
  47181. path.add (chooser.getResult(), row);
  47182. changed();
  47183. }
  47184. }
  47185. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47186. {
  47187. returnKeyPressed (row);
  47188. }
  47189. void FileSearchPathListComponent::selectedRowsChanged (int)
  47190. {
  47191. updateButtons();
  47192. }
  47193. void FileSearchPathListComponent::paint (Graphics& g)
  47194. {
  47195. g.fillAll (findColour (backgroundColourId));
  47196. }
  47197. void FileSearchPathListComponent::resized()
  47198. {
  47199. const int buttonH = 22;
  47200. const int buttonY = getHeight() - buttonH - 4;
  47201. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47202. addButton->setBounds (2, buttonY, buttonH, buttonH);
  47203. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  47204. changeButton->changeWidthToFitText (buttonH);
  47205. downButton->setSize (buttonH * 2, buttonH);
  47206. upButton->setSize (buttonH * 2, buttonH);
  47207. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  47208. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  47209. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  47210. }
  47211. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47212. {
  47213. return true;
  47214. }
  47215. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47216. {
  47217. for (int i = filenames.size(); --i >= 0;)
  47218. {
  47219. const File f (filenames[i]);
  47220. if (f.isDirectory())
  47221. {
  47222. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  47223. path.add (f, row);
  47224. changed();
  47225. }
  47226. }
  47227. }
  47228. void FileSearchPathListComponent::buttonClicked (Button* button)
  47229. {
  47230. const int currentRow = listBox->getSelectedRow();
  47231. if (button == removeButton)
  47232. {
  47233. deleteKeyPressed (currentRow);
  47234. }
  47235. else if (button == addButton)
  47236. {
  47237. File start (defaultBrowseTarget);
  47238. if (start == File::nonexistent)
  47239. start = path [0];
  47240. if (start == File::nonexistent)
  47241. start = File::getCurrentWorkingDirectory();
  47242. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47243. if (chooser.browseForDirectory())
  47244. {
  47245. path.add (chooser.getResult(), currentRow);
  47246. }
  47247. }
  47248. else if (button == changeButton)
  47249. {
  47250. returnKeyPressed (currentRow);
  47251. }
  47252. else if (button == upButton)
  47253. {
  47254. if (currentRow > 0 && currentRow < path.getNumPaths())
  47255. {
  47256. const File f (path[currentRow]);
  47257. path.remove (currentRow);
  47258. path.add (f, currentRow - 1);
  47259. listBox->selectRow (currentRow - 1);
  47260. }
  47261. }
  47262. else if (button == downButton)
  47263. {
  47264. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47265. {
  47266. const File f (path[currentRow]);
  47267. path.remove (currentRow);
  47268. path.add (f, currentRow + 1);
  47269. listBox->selectRow (currentRow + 1);
  47270. }
  47271. }
  47272. changed();
  47273. }
  47274. END_JUCE_NAMESPACE
  47275. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47276. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47277. BEGIN_JUCE_NAMESPACE
  47278. const Image juce_createIconForFile (const File& file);
  47279. class FileListTreeItem : public TreeViewItem,
  47280. public TimeSliceClient,
  47281. public AsyncUpdater,
  47282. public ChangeListener
  47283. {
  47284. public:
  47285. FileListTreeItem (FileTreeComponent& owner_,
  47286. DirectoryContentsList* const parentContentsList_,
  47287. const int indexInContentsList_,
  47288. const File& file_,
  47289. TimeSliceThread& thread_)
  47290. : file (file_),
  47291. owner (owner_),
  47292. parentContentsList (parentContentsList_),
  47293. indexInContentsList (indexInContentsList_),
  47294. subContentsList (0),
  47295. canDeleteSubContentsList (false),
  47296. thread (thread_),
  47297. icon (0)
  47298. {
  47299. DirectoryContentsList::FileInfo fileInfo;
  47300. if (parentContentsList_ != 0
  47301. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47302. {
  47303. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47304. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47305. isDirectory = fileInfo.isDirectory;
  47306. }
  47307. else
  47308. {
  47309. isDirectory = true;
  47310. }
  47311. }
  47312. ~FileListTreeItem()
  47313. {
  47314. thread.removeTimeSliceClient (this);
  47315. clearSubItems();
  47316. if (canDeleteSubContentsList)
  47317. delete subContentsList;
  47318. }
  47319. bool mightContainSubItems() { return isDirectory; }
  47320. const String getUniqueName() const { return file.getFullPathName(); }
  47321. int getItemHeight() const { return 22; }
  47322. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47323. void itemOpennessChanged (bool isNowOpen)
  47324. {
  47325. if (isNowOpen)
  47326. {
  47327. clearSubItems();
  47328. isDirectory = file.isDirectory();
  47329. if (isDirectory)
  47330. {
  47331. if (subContentsList == 0)
  47332. {
  47333. jassert (parentContentsList != 0);
  47334. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47335. l->setDirectory (file, true, true);
  47336. setSubContentsList (l);
  47337. canDeleteSubContentsList = true;
  47338. }
  47339. changeListenerCallback (0);
  47340. }
  47341. }
  47342. }
  47343. void setSubContentsList (DirectoryContentsList* newList)
  47344. {
  47345. jassert (subContentsList == 0);
  47346. subContentsList = newList;
  47347. newList->addChangeListener (this);
  47348. }
  47349. void changeListenerCallback (void*)
  47350. {
  47351. clearSubItems();
  47352. if (isOpen() && subContentsList != 0)
  47353. {
  47354. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47355. {
  47356. FileListTreeItem* const item
  47357. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47358. addSubItem (item);
  47359. }
  47360. }
  47361. }
  47362. void paintItem (Graphics& g, int width, int height)
  47363. {
  47364. if (file != File::nonexistent)
  47365. {
  47366. updateIcon (true);
  47367. if (icon.isNull())
  47368. thread.addTimeSliceClient (this);
  47369. }
  47370. owner.getLookAndFeel()
  47371. .drawFileBrowserRow (g, width, height,
  47372. file.getFileName(),
  47373. &icon, fileSize, modTime,
  47374. isDirectory, isSelected(),
  47375. indexInContentsList);
  47376. }
  47377. void itemClicked (const MouseEvent& e)
  47378. {
  47379. owner.sendMouseClickMessage (file, e);
  47380. }
  47381. void itemDoubleClicked (const MouseEvent& e)
  47382. {
  47383. TreeViewItem::itemDoubleClicked (e);
  47384. owner.sendDoubleClickMessage (file);
  47385. }
  47386. void itemSelectionChanged (bool)
  47387. {
  47388. owner.sendSelectionChangeMessage();
  47389. }
  47390. bool useTimeSlice()
  47391. {
  47392. updateIcon (false);
  47393. thread.removeTimeSliceClient (this);
  47394. return false;
  47395. }
  47396. void handleAsyncUpdate()
  47397. {
  47398. owner.repaint();
  47399. }
  47400. const File file;
  47401. juce_UseDebuggingNewOperator
  47402. private:
  47403. FileTreeComponent& owner;
  47404. DirectoryContentsList* parentContentsList;
  47405. int indexInContentsList;
  47406. DirectoryContentsList* subContentsList;
  47407. bool isDirectory, canDeleteSubContentsList;
  47408. TimeSliceThread& thread;
  47409. Image icon;
  47410. String fileSize;
  47411. String modTime;
  47412. void updateIcon (const bool onlyUpdateIfCached)
  47413. {
  47414. if (icon.isNull())
  47415. {
  47416. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47417. Image im (ImageCache::getFromHashCode (hashCode));
  47418. if (im.isNull() && ! onlyUpdateIfCached)
  47419. {
  47420. im = juce_createIconForFile (file);
  47421. if (im.isValid())
  47422. ImageCache::addImageToCache (im, hashCode);
  47423. }
  47424. if (im.isValid())
  47425. {
  47426. icon = im;
  47427. triggerAsyncUpdate();
  47428. }
  47429. }
  47430. }
  47431. };
  47432. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  47433. : DirectoryContentsDisplayComponent (listToShow)
  47434. {
  47435. FileListTreeItem* const root
  47436. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  47437. listToShow.getTimeSliceThread());
  47438. root->setSubContentsList (&listToShow);
  47439. setRootItemVisible (false);
  47440. setRootItem (root);
  47441. }
  47442. FileTreeComponent::~FileTreeComponent()
  47443. {
  47444. deleteRootItem();
  47445. }
  47446. const File FileTreeComponent::getSelectedFile (const int index) const
  47447. {
  47448. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  47449. return item != 0 ? item->file
  47450. : File::nonexistent;
  47451. }
  47452. void FileTreeComponent::deselectAllFiles()
  47453. {
  47454. clearSelectedItems();
  47455. }
  47456. void FileTreeComponent::scrollToTop()
  47457. {
  47458. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  47459. }
  47460. void FileTreeComponent::setDragAndDropDescription (const String& description)
  47461. {
  47462. dragAndDropDescription = description;
  47463. }
  47464. END_JUCE_NAMESPACE
  47465. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  47466. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  47467. BEGIN_JUCE_NAMESPACE
  47468. ImagePreviewComponent::ImagePreviewComponent()
  47469. {
  47470. }
  47471. ImagePreviewComponent::~ImagePreviewComponent()
  47472. {
  47473. }
  47474. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  47475. {
  47476. const int availableW = proportionOfWidth (0.97f);
  47477. const int availableH = getHeight() - 13 * 4;
  47478. const double scale = jmin (1.0,
  47479. availableW / (double) w,
  47480. availableH / (double) h);
  47481. w = roundToInt (scale * w);
  47482. h = roundToInt (scale * h);
  47483. }
  47484. void ImagePreviewComponent::selectedFileChanged (const File& file)
  47485. {
  47486. if (fileToLoad != file)
  47487. {
  47488. fileToLoad = file;
  47489. startTimer (100);
  47490. }
  47491. }
  47492. void ImagePreviewComponent::timerCallback()
  47493. {
  47494. stopTimer();
  47495. currentThumbnail = Image::null;
  47496. currentDetails = String::empty;
  47497. repaint();
  47498. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  47499. if (in != 0)
  47500. {
  47501. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  47502. if (format != 0)
  47503. {
  47504. currentThumbnail = format->decodeImage (*in);
  47505. if (currentThumbnail.isValid())
  47506. {
  47507. int w = currentThumbnail.getWidth();
  47508. int h = currentThumbnail.getHeight();
  47509. currentDetails
  47510. << fileToLoad.getFileName() << "\n"
  47511. << format->getFormatName() << "\n"
  47512. << w << " x " << h << " pixels\n"
  47513. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  47514. getThumbSize (w, h);
  47515. currentThumbnail = currentThumbnail.rescaled (w, h);
  47516. }
  47517. }
  47518. }
  47519. }
  47520. void ImagePreviewComponent::paint (Graphics& g)
  47521. {
  47522. if (currentThumbnail.isValid())
  47523. {
  47524. g.setFont (13.0f);
  47525. int w = currentThumbnail.getWidth();
  47526. int h = currentThumbnail.getHeight();
  47527. getThumbSize (w, h);
  47528. const int numLines = 4;
  47529. const int totalH = 13 * numLines + h + 4;
  47530. const int y = (getHeight() - totalH) / 2;
  47531. g.drawImageWithin (currentThumbnail,
  47532. (getWidth() - w) / 2, y, w, h,
  47533. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  47534. false);
  47535. g.drawFittedText (currentDetails,
  47536. 0, y + h + 4, getWidth(), 100,
  47537. Justification::centredTop, numLines);
  47538. }
  47539. }
  47540. END_JUCE_NAMESPACE
  47541. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  47542. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  47543. BEGIN_JUCE_NAMESPACE
  47544. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  47545. const String& directoryWildcardPatterns,
  47546. const String& description_)
  47547. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  47548. : (description_ + " (" + fileWildcardPatterns + ")"))
  47549. {
  47550. parse (fileWildcardPatterns, fileWildcards);
  47551. parse (directoryWildcardPatterns, directoryWildcards);
  47552. }
  47553. WildcardFileFilter::~WildcardFileFilter()
  47554. {
  47555. }
  47556. bool WildcardFileFilter::isFileSuitable (const File& file) const
  47557. {
  47558. return match (file, fileWildcards);
  47559. }
  47560. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  47561. {
  47562. return match (file, directoryWildcards);
  47563. }
  47564. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  47565. {
  47566. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  47567. result.trim();
  47568. result.removeEmptyStrings();
  47569. // special case for *.*, because people use it to mean "any file", but it
  47570. // would actually ignore files with no extension.
  47571. for (int i = result.size(); --i >= 0;)
  47572. if (result[i] == "*.*")
  47573. result.set (i, "*");
  47574. }
  47575. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  47576. {
  47577. const String filename (file.getFileName());
  47578. for (int i = wildcards.size(); --i >= 0;)
  47579. if (filename.matchesWildcard (wildcards[i], true))
  47580. return true;
  47581. return false;
  47582. }
  47583. END_JUCE_NAMESPACE
  47584. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  47585. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47586. BEGIN_JUCE_NAMESPACE
  47587. KeyboardFocusTraverser::KeyboardFocusTraverser()
  47588. {
  47589. }
  47590. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  47591. {
  47592. }
  47593. namespace KeyboardFocusHelpers
  47594. {
  47595. // This will sort a set of components, so that they are ordered in terms of
  47596. // left-to-right and then top-to-bottom.
  47597. class ScreenPositionComparator
  47598. {
  47599. public:
  47600. ScreenPositionComparator() {}
  47601. static int compareElements (const Component* const first, const Component* const second)
  47602. {
  47603. int explicitOrder1 = first->getExplicitFocusOrder();
  47604. if (explicitOrder1 <= 0)
  47605. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  47606. int explicitOrder2 = second->getExplicitFocusOrder();
  47607. if (explicitOrder2 <= 0)
  47608. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  47609. if (explicitOrder1 != explicitOrder2)
  47610. return explicitOrder1 - explicitOrder2;
  47611. const int diff = first->getY() - second->getY();
  47612. return (diff == 0) ? first->getX() - second->getX()
  47613. : diff;
  47614. }
  47615. };
  47616. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  47617. {
  47618. if (parent->getNumChildComponents() > 0)
  47619. {
  47620. Array <Component*> localComps;
  47621. ScreenPositionComparator comparator;
  47622. int i;
  47623. for (i = parent->getNumChildComponents(); --i >= 0;)
  47624. {
  47625. Component* const c = parent->getChildComponent (i);
  47626. if (c->isVisible() && c->isEnabled())
  47627. localComps.addSorted (comparator, c);
  47628. }
  47629. for (i = 0; i < localComps.size(); ++i)
  47630. {
  47631. Component* const c = localComps.getUnchecked (i);
  47632. if (c->getWantsKeyboardFocus())
  47633. comps.add (c);
  47634. if (! c->isFocusContainer())
  47635. findAllFocusableComponents (c, comps);
  47636. }
  47637. }
  47638. }
  47639. }
  47640. static Component* getIncrementedComponent (Component* const current, const int delta)
  47641. {
  47642. Component* focusContainer = current->getParentComponent();
  47643. if (focusContainer != 0)
  47644. {
  47645. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  47646. focusContainer = focusContainer->getParentComponent();
  47647. if (focusContainer != 0)
  47648. {
  47649. Array <Component*> comps;
  47650. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  47651. if (comps.size() > 0)
  47652. {
  47653. const int index = comps.indexOf (current);
  47654. return comps [(index + comps.size() + delta) % comps.size()];
  47655. }
  47656. }
  47657. }
  47658. return 0;
  47659. }
  47660. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  47661. {
  47662. return getIncrementedComponent (current, 1);
  47663. }
  47664. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  47665. {
  47666. return getIncrementedComponent (current, -1);
  47667. }
  47668. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  47669. {
  47670. Array <Component*> comps;
  47671. if (parentComponent != 0)
  47672. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  47673. return comps.getFirst();
  47674. }
  47675. END_JUCE_NAMESPACE
  47676. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47677. /*** Start of inlined file: juce_KeyListener.cpp ***/
  47678. BEGIN_JUCE_NAMESPACE
  47679. bool KeyListener::keyStateChanged (const bool, Component*)
  47680. {
  47681. return false;
  47682. }
  47683. END_JUCE_NAMESPACE
  47684. /*** End of inlined file: juce_KeyListener.cpp ***/
  47685. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  47686. BEGIN_JUCE_NAMESPACE
  47687. // N.B. these two includes are put here deliberately to avoid problems with
  47688. // old GCCs failing on long include paths
  47689. const int maxKeys = 3;
  47690. class KeyMappingChangeButton : public Button
  47691. {
  47692. public:
  47693. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  47694. const CommandID commandID_,
  47695. const String& keyName,
  47696. const int keyNum_)
  47697. : Button (keyName),
  47698. owner (owner_),
  47699. commandID (commandID_),
  47700. keyNum (keyNum_)
  47701. {
  47702. setWantsKeyboardFocus (false);
  47703. setTriggeredOnMouseDown (keyNum >= 0);
  47704. if (keyNum_ < 0)
  47705. setTooltip (TRANS("adds a new key-mapping"));
  47706. else
  47707. setTooltip (TRANS("click to change this key-mapping"));
  47708. }
  47709. ~KeyMappingChangeButton()
  47710. {
  47711. }
  47712. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  47713. {
  47714. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  47715. keyNum >= 0 ? getName() : String::empty);
  47716. }
  47717. void clicked()
  47718. {
  47719. if (keyNum >= 0)
  47720. {
  47721. // existing key clicked..
  47722. PopupMenu m;
  47723. m.addItem (1, TRANS("change this key-mapping"));
  47724. m.addSeparator();
  47725. m.addItem (2, TRANS("remove this key-mapping"));
  47726. const int res = m.show();
  47727. if (res == 1)
  47728. {
  47729. owner->assignNewKey (commandID, keyNum);
  47730. }
  47731. else if (res == 2)
  47732. {
  47733. owner->getMappings()->removeKeyPress (commandID, keyNum);
  47734. }
  47735. }
  47736. else
  47737. {
  47738. // + button pressed..
  47739. owner->assignNewKey (commandID, -1);
  47740. }
  47741. }
  47742. void fitToContent (const int h) throw()
  47743. {
  47744. if (keyNum < 0)
  47745. {
  47746. setSize (h, h);
  47747. }
  47748. else
  47749. {
  47750. Font f (h * 0.6f);
  47751. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  47752. }
  47753. }
  47754. juce_UseDebuggingNewOperator
  47755. private:
  47756. KeyMappingEditorComponent* const owner;
  47757. const CommandID commandID;
  47758. const int keyNum;
  47759. KeyMappingChangeButton (const KeyMappingChangeButton&);
  47760. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  47761. };
  47762. class KeyMappingItemComponent : public Component
  47763. {
  47764. public:
  47765. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  47766. const CommandID commandID_)
  47767. : owner (owner_),
  47768. commandID (commandID_)
  47769. {
  47770. setInterceptsMouseClicks (false, true);
  47771. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  47772. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  47773. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  47774. {
  47775. KeyMappingChangeButton* const kb
  47776. = new KeyMappingChangeButton (owner_, commandID,
  47777. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  47778. kb->setEnabled (! isReadOnly);
  47779. addAndMakeVisible (kb);
  47780. }
  47781. KeyMappingChangeButton* const kb
  47782. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  47783. addChildComponent (kb);
  47784. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  47785. }
  47786. ~KeyMappingItemComponent()
  47787. {
  47788. deleteAllChildren();
  47789. }
  47790. void paint (Graphics& g)
  47791. {
  47792. g.setFont (getHeight() * 0.7f);
  47793. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  47794. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  47795. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  47796. Justification::centredLeft, true);
  47797. }
  47798. void resized()
  47799. {
  47800. int x = getWidth() - 4;
  47801. for (int i = getNumChildComponents(); --i >= 0;)
  47802. {
  47803. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  47804. kb->fitToContent (getHeight() - 2);
  47805. kb->setTopRightPosition (x, 1);
  47806. x -= kb->getWidth() + 5;
  47807. }
  47808. }
  47809. juce_UseDebuggingNewOperator
  47810. private:
  47811. KeyMappingEditorComponent* const owner;
  47812. const CommandID commandID;
  47813. KeyMappingItemComponent (const KeyMappingItemComponent&);
  47814. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  47815. };
  47816. class KeyMappingTreeViewItem : public TreeViewItem
  47817. {
  47818. public:
  47819. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  47820. const CommandID commandID_)
  47821. : owner (owner_),
  47822. commandID (commandID_)
  47823. {
  47824. }
  47825. ~KeyMappingTreeViewItem()
  47826. {
  47827. }
  47828. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  47829. bool mightContainSubItems() { return false; }
  47830. int getItemHeight() const { return 20; }
  47831. Component* createItemComponent()
  47832. {
  47833. return new KeyMappingItemComponent (owner, commandID);
  47834. }
  47835. juce_UseDebuggingNewOperator
  47836. private:
  47837. KeyMappingEditorComponent* const owner;
  47838. const CommandID commandID;
  47839. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  47840. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  47841. };
  47842. class KeyCategoryTreeViewItem : public TreeViewItem
  47843. {
  47844. public:
  47845. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  47846. const String& name)
  47847. : owner (owner_),
  47848. categoryName (name)
  47849. {
  47850. }
  47851. ~KeyCategoryTreeViewItem()
  47852. {
  47853. }
  47854. const String getUniqueName() const { return categoryName + "_cat"; }
  47855. bool mightContainSubItems() { return true; }
  47856. int getItemHeight() const { return 28; }
  47857. void paintItem (Graphics& g, int width, int height)
  47858. {
  47859. g.setFont (height * 0.6f, Font::bold);
  47860. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  47861. g.drawText (categoryName,
  47862. 2, 0, width - 2, height,
  47863. Justification::centredLeft, true);
  47864. }
  47865. void itemOpennessChanged (bool isNowOpen)
  47866. {
  47867. if (isNowOpen)
  47868. {
  47869. if (getNumSubItems() == 0)
  47870. {
  47871. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  47872. for (int i = 0; i < commands.size(); ++i)
  47873. {
  47874. if (owner->shouldCommandBeIncluded (commands[i]))
  47875. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  47876. }
  47877. }
  47878. }
  47879. else
  47880. {
  47881. clearSubItems();
  47882. }
  47883. }
  47884. juce_UseDebuggingNewOperator
  47885. private:
  47886. KeyMappingEditorComponent* owner;
  47887. String categoryName;
  47888. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  47889. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  47890. };
  47891. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  47892. const bool showResetToDefaultButton)
  47893. : mappings (mappingManager)
  47894. {
  47895. jassert (mappingManager != 0); // can't be null!
  47896. mappingManager->addChangeListener (this);
  47897. setLinesDrawnForSubItems (false);
  47898. resetButton = 0;
  47899. if (showResetToDefaultButton)
  47900. {
  47901. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  47902. resetButton->addButtonListener (this);
  47903. }
  47904. addAndMakeVisible (tree = new TreeView());
  47905. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  47906. tree->setRootItemVisible (false);
  47907. tree->setDefaultOpenness (true);
  47908. tree->setRootItem (this);
  47909. }
  47910. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  47911. {
  47912. mappings->removeChangeListener (this);
  47913. deleteAllChildren();
  47914. }
  47915. bool KeyMappingEditorComponent::mightContainSubItems()
  47916. {
  47917. return true;
  47918. }
  47919. const String KeyMappingEditorComponent::getUniqueName() const
  47920. {
  47921. return "keys";
  47922. }
  47923. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  47924. const Colour& textColour)
  47925. {
  47926. setColour (backgroundColourId, mainBackground);
  47927. setColour (textColourId, textColour);
  47928. tree->setColour (TreeView::backgroundColourId, mainBackground);
  47929. }
  47930. void KeyMappingEditorComponent::parentHierarchyChanged()
  47931. {
  47932. changeListenerCallback (0);
  47933. }
  47934. void KeyMappingEditorComponent::resized()
  47935. {
  47936. int h = getHeight();
  47937. if (resetButton != 0)
  47938. {
  47939. const int buttonHeight = 20;
  47940. h -= buttonHeight + 8;
  47941. int x = getWidth() - 8;
  47942. resetButton->changeWidthToFitText (buttonHeight);
  47943. resetButton->setTopRightPosition (x, h + 6);
  47944. }
  47945. tree->setBounds (0, 0, getWidth(), h);
  47946. }
  47947. void KeyMappingEditorComponent::buttonClicked (Button* button)
  47948. {
  47949. if (button == resetButton)
  47950. {
  47951. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  47952. TRANS("Reset to defaults"),
  47953. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  47954. TRANS("Reset")))
  47955. {
  47956. mappings->resetToDefaultMappings();
  47957. }
  47958. }
  47959. }
  47960. void KeyMappingEditorComponent::changeListenerCallback (void*)
  47961. {
  47962. ScopedPointer <XmlElement> oldOpenness (tree->getOpennessState (true));
  47963. clearSubItems();
  47964. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  47965. for (int i = 0; i < categories.size(); ++i)
  47966. {
  47967. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  47968. int count = 0;
  47969. for (int j = 0; j < commands.size(); ++j)
  47970. if (shouldCommandBeIncluded (commands[j]))
  47971. ++count;
  47972. if (count > 0)
  47973. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  47974. }
  47975. if (oldOpenness != 0)
  47976. tree->restoreOpennessState (*oldOpenness);
  47977. }
  47978. class KeyEntryWindow : public AlertWindow
  47979. {
  47980. public:
  47981. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  47982. : AlertWindow (TRANS("New key-mapping"),
  47983. TRANS("Please press a key combination now..."),
  47984. AlertWindow::NoIcon),
  47985. owner (owner_)
  47986. {
  47987. addButton (TRANS("ok"), 1);
  47988. addButton (TRANS("cancel"), 0);
  47989. // (avoid return + escape keys getting processed by the buttons..)
  47990. for (int i = getNumChildComponents(); --i >= 0;)
  47991. getChildComponent (i)->setWantsKeyboardFocus (false);
  47992. setWantsKeyboardFocus (true);
  47993. grabKeyboardFocus();
  47994. }
  47995. ~KeyEntryWindow()
  47996. {
  47997. }
  47998. bool keyPressed (const KeyPress& key)
  47999. {
  48000. lastPress = key;
  48001. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  48002. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  48003. if (previousCommand != 0)
  48004. {
  48005. message << "\n\n"
  48006. << TRANS("(Currently assigned to \"")
  48007. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  48008. << "\")";
  48009. }
  48010. setMessage (message);
  48011. return true;
  48012. }
  48013. bool keyStateChanged (bool)
  48014. {
  48015. return true;
  48016. }
  48017. KeyPress lastPress;
  48018. juce_UseDebuggingNewOperator
  48019. private:
  48020. KeyMappingEditorComponent* owner;
  48021. KeyEntryWindow (const KeyEntryWindow&);
  48022. KeyEntryWindow& operator= (const KeyEntryWindow&);
  48023. };
  48024. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  48025. {
  48026. KeyEntryWindow entryWindow (this);
  48027. if (entryWindow.runModalLoop() != 0)
  48028. {
  48029. entryWindow.setVisible (false);
  48030. if (entryWindow.lastPress.isValid())
  48031. {
  48032. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  48033. if (previousCommand != 0)
  48034. {
  48035. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48036. TRANS("Change key-mapping"),
  48037. TRANS("This key is already assigned to the command \"")
  48038. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  48039. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48040. TRANS("re-assign"),
  48041. TRANS("cancel")))
  48042. {
  48043. return;
  48044. }
  48045. }
  48046. mappings->removeKeyPress (entryWindow.lastPress);
  48047. if (index >= 0)
  48048. mappings->removeKeyPress (commandID, index);
  48049. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  48050. }
  48051. }
  48052. }
  48053. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48054. {
  48055. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48056. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  48057. }
  48058. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48059. {
  48060. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48061. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  48062. }
  48063. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48064. {
  48065. return key.getTextDescription();
  48066. }
  48067. END_JUCE_NAMESPACE
  48068. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48069. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48070. BEGIN_JUCE_NAMESPACE
  48071. KeyPress::KeyPress() throw()
  48072. : keyCode (0),
  48073. mods (0),
  48074. textCharacter (0)
  48075. {
  48076. }
  48077. KeyPress::KeyPress (const int keyCode_,
  48078. const ModifierKeys& mods_,
  48079. const juce_wchar textCharacter_) throw()
  48080. : keyCode (keyCode_),
  48081. mods (mods_),
  48082. textCharacter (textCharacter_)
  48083. {
  48084. }
  48085. KeyPress::KeyPress (const int keyCode_) throw()
  48086. : keyCode (keyCode_),
  48087. textCharacter (0)
  48088. {
  48089. }
  48090. KeyPress::KeyPress (const KeyPress& other) throw()
  48091. : keyCode (other.keyCode),
  48092. mods (other.mods),
  48093. textCharacter (other.textCharacter)
  48094. {
  48095. }
  48096. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48097. {
  48098. keyCode = other.keyCode;
  48099. mods = other.mods;
  48100. textCharacter = other.textCharacter;
  48101. return *this;
  48102. }
  48103. bool KeyPress::operator== (const KeyPress& other) const throw()
  48104. {
  48105. return mods.getRawFlags() == other.mods.getRawFlags()
  48106. && (textCharacter == other.textCharacter
  48107. || textCharacter == 0
  48108. || other.textCharacter == 0)
  48109. && (keyCode == other.keyCode
  48110. || (keyCode < 256
  48111. && other.keyCode < 256
  48112. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48113. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48114. }
  48115. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48116. {
  48117. return ! operator== (other);
  48118. }
  48119. bool KeyPress::isCurrentlyDown() const
  48120. {
  48121. return isKeyCurrentlyDown (keyCode)
  48122. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48123. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48124. }
  48125. namespace KeyPressHelpers
  48126. {
  48127. struct KeyNameAndCode
  48128. {
  48129. const char* name;
  48130. int code;
  48131. };
  48132. static const KeyNameAndCode translations[] =
  48133. {
  48134. { "spacebar", KeyPress::spaceKey },
  48135. { "return", KeyPress::returnKey },
  48136. { "escape", KeyPress::escapeKey },
  48137. { "backspace", KeyPress::backspaceKey },
  48138. { "cursor left", KeyPress::leftKey },
  48139. { "cursor right", KeyPress::rightKey },
  48140. { "cursor up", KeyPress::upKey },
  48141. { "cursor down", KeyPress::downKey },
  48142. { "page up", KeyPress::pageUpKey },
  48143. { "page down", KeyPress::pageDownKey },
  48144. { "home", KeyPress::homeKey },
  48145. { "end", KeyPress::endKey },
  48146. { "delete", KeyPress::deleteKey },
  48147. { "insert", KeyPress::insertKey },
  48148. { "tab", KeyPress::tabKey },
  48149. { "play", KeyPress::playKey },
  48150. { "stop", KeyPress::stopKey },
  48151. { "fast forward", KeyPress::fastForwardKey },
  48152. { "rewind", KeyPress::rewindKey }
  48153. };
  48154. static const String numberPadPrefix() { return "numpad "; }
  48155. }
  48156. const KeyPress KeyPress::createFromDescription (const String& desc)
  48157. {
  48158. int modifiers = 0;
  48159. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48160. || desc.containsWholeWordIgnoreCase ("control")
  48161. || desc.containsWholeWordIgnoreCase ("ctl"))
  48162. modifiers |= ModifierKeys::ctrlModifier;
  48163. if (desc.containsWholeWordIgnoreCase ("shift")
  48164. || desc.containsWholeWordIgnoreCase ("shft"))
  48165. modifiers |= ModifierKeys::shiftModifier;
  48166. if (desc.containsWholeWordIgnoreCase ("alt")
  48167. || desc.containsWholeWordIgnoreCase ("option"))
  48168. modifiers |= ModifierKeys::altModifier;
  48169. if (desc.containsWholeWordIgnoreCase ("command")
  48170. || desc.containsWholeWordIgnoreCase ("cmd"))
  48171. modifiers |= ModifierKeys::commandModifier;
  48172. int key = 0;
  48173. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48174. {
  48175. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48176. {
  48177. key = KeyPressHelpers::translations[i].code;
  48178. break;
  48179. }
  48180. }
  48181. if (key == 0)
  48182. {
  48183. // see if it's a numpad key..
  48184. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48185. {
  48186. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48187. if (lastChar >= '0' && lastChar <= '9')
  48188. key = numberPad0 + lastChar - '0';
  48189. else if (lastChar == '+')
  48190. key = numberPadAdd;
  48191. else if (lastChar == '-')
  48192. key = numberPadSubtract;
  48193. else if (lastChar == '*')
  48194. key = numberPadMultiply;
  48195. else if (lastChar == '/')
  48196. key = numberPadDivide;
  48197. else if (lastChar == '.')
  48198. key = numberPadDecimalPoint;
  48199. else if (lastChar == '=')
  48200. key = numberPadEquals;
  48201. else if (desc.endsWith ("separator"))
  48202. key = numberPadSeparator;
  48203. else if (desc.endsWith ("delete"))
  48204. key = numberPadDelete;
  48205. }
  48206. if (key == 0)
  48207. {
  48208. // see if it's a function key..
  48209. for (int i = 1; i <= 12; ++i)
  48210. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48211. key = F1Key + i - 1;
  48212. if (key == 0)
  48213. {
  48214. // give up and use the hex code..
  48215. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48216. .toLowerCase()
  48217. .retainCharacters ("0123456789abcdef")
  48218. .getHexValue32();
  48219. if (hexCode > 0)
  48220. key = hexCode;
  48221. else
  48222. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48223. }
  48224. }
  48225. }
  48226. return KeyPress (key, ModifierKeys (modifiers), 0);
  48227. }
  48228. const String KeyPress::getTextDescription() const
  48229. {
  48230. String desc;
  48231. if (keyCode > 0)
  48232. {
  48233. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48234. // want to store it as being a slash, not shift+whatever.
  48235. if (textCharacter == '/')
  48236. return "/";
  48237. if (mods.isCtrlDown())
  48238. desc << "ctrl + ";
  48239. if (mods.isShiftDown())
  48240. desc << "shift + ";
  48241. #if JUCE_MAC
  48242. // only do this on the mac, because on Windows ctrl and command are the same,
  48243. // and this would get confusing
  48244. if (mods.isCommandDown())
  48245. desc << "command + ";
  48246. if (mods.isAltDown())
  48247. desc << "option + ";
  48248. #else
  48249. if (mods.isAltDown())
  48250. desc << "alt + ";
  48251. #endif
  48252. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48253. if (keyCode == KeyPressHelpers::translations[i].code)
  48254. return desc + KeyPressHelpers::translations[i].name;
  48255. if (keyCode >= F1Key && keyCode <= F16Key)
  48256. desc << 'F' << (1 + keyCode - F1Key);
  48257. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48258. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48259. else if (keyCode >= 33 && keyCode < 176)
  48260. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48261. else if (keyCode == numberPadAdd)
  48262. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48263. else if (keyCode == numberPadSubtract)
  48264. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48265. else if (keyCode == numberPadMultiply)
  48266. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48267. else if (keyCode == numberPadDivide)
  48268. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48269. else if (keyCode == numberPadSeparator)
  48270. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48271. else if (keyCode == numberPadDecimalPoint)
  48272. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48273. else if (keyCode == numberPadDelete)
  48274. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48275. else
  48276. desc << '#' << String::toHexString (keyCode);
  48277. }
  48278. return desc;
  48279. }
  48280. END_JUCE_NAMESPACE
  48281. /*** End of inlined file: juce_KeyPress.cpp ***/
  48282. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48283. BEGIN_JUCE_NAMESPACE
  48284. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48285. : commandManager (commandManager_)
  48286. {
  48287. // A manager is needed to get the descriptions of commands, and will be called when
  48288. // a command is invoked. So you can't leave this null..
  48289. jassert (commandManager_ != 0);
  48290. Desktop::getInstance().addFocusChangeListener (this);
  48291. }
  48292. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48293. : commandManager (other.commandManager)
  48294. {
  48295. Desktop::getInstance().addFocusChangeListener (this);
  48296. }
  48297. KeyPressMappingSet::~KeyPressMappingSet()
  48298. {
  48299. Desktop::getInstance().removeFocusChangeListener (this);
  48300. }
  48301. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48302. {
  48303. for (int i = 0; i < mappings.size(); ++i)
  48304. if (mappings.getUnchecked(i)->commandID == commandID)
  48305. return mappings.getUnchecked (i)->keypresses;
  48306. return Array <KeyPress> ();
  48307. }
  48308. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48309. const KeyPress& newKeyPress,
  48310. int insertIndex)
  48311. {
  48312. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48313. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48314. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48315. && ! newKeyPress.getModifiers().isShiftDown()));
  48316. if (findCommandForKeyPress (newKeyPress) != commandID)
  48317. {
  48318. removeKeyPress (newKeyPress);
  48319. if (newKeyPress.isValid())
  48320. {
  48321. for (int i = mappings.size(); --i >= 0;)
  48322. {
  48323. if (mappings.getUnchecked(i)->commandID == commandID)
  48324. {
  48325. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48326. sendChangeMessage (this);
  48327. return;
  48328. }
  48329. }
  48330. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48331. if (ci != 0)
  48332. {
  48333. CommandMapping* const cm = new CommandMapping();
  48334. cm->commandID = commandID;
  48335. cm->keypresses.add (newKeyPress);
  48336. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48337. mappings.add (cm);
  48338. sendChangeMessage (this);
  48339. }
  48340. }
  48341. }
  48342. }
  48343. void KeyPressMappingSet::resetToDefaultMappings()
  48344. {
  48345. mappings.clear();
  48346. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48347. {
  48348. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48349. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48350. {
  48351. addKeyPress (ci->commandID,
  48352. ci->defaultKeypresses.getReference (j));
  48353. }
  48354. }
  48355. sendChangeMessage (this);
  48356. }
  48357. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48358. {
  48359. clearAllKeyPresses (commandID);
  48360. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48361. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48362. {
  48363. addKeyPress (ci->commandID,
  48364. ci->defaultKeypresses.getReference (j));
  48365. }
  48366. }
  48367. void KeyPressMappingSet::clearAllKeyPresses()
  48368. {
  48369. if (mappings.size() > 0)
  48370. {
  48371. sendChangeMessage (this);
  48372. mappings.clear();
  48373. }
  48374. }
  48375. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48376. {
  48377. for (int i = mappings.size(); --i >= 0;)
  48378. {
  48379. if (mappings.getUnchecked(i)->commandID == commandID)
  48380. {
  48381. mappings.remove (i);
  48382. sendChangeMessage (this);
  48383. }
  48384. }
  48385. }
  48386. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48387. {
  48388. if (keypress.isValid())
  48389. {
  48390. for (int i = mappings.size(); --i >= 0;)
  48391. {
  48392. CommandMapping* const cm = mappings.getUnchecked(i);
  48393. for (int j = cm->keypresses.size(); --j >= 0;)
  48394. {
  48395. if (keypress == cm->keypresses [j])
  48396. {
  48397. cm->keypresses.remove (j);
  48398. sendChangeMessage (this);
  48399. }
  48400. }
  48401. }
  48402. }
  48403. }
  48404. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48405. {
  48406. for (int i = mappings.size(); --i >= 0;)
  48407. {
  48408. if (mappings.getUnchecked(i)->commandID == commandID)
  48409. {
  48410. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48411. sendChangeMessage (this);
  48412. break;
  48413. }
  48414. }
  48415. }
  48416. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48417. {
  48418. for (int i = 0; i < mappings.size(); ++i)
  48419. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  48420. return mappings.getUnchecked(i)->commandID;
  48421. return 0;
  48422. }
  48423. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  48424. {
  48425. for (int i = mappings.size(); --i >= 0;)
  48426. if (mappings.getUnchecked(i)->commandID == commandID)
  48427. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  48428. return false;
  48429. }
  48430. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  48431. const KeyPress& key,
  48432. const bool isKeyDown,
  48433. const int millisecsSinceKeyPressed,
  48434. Component* const originatingComponent) const
  48435. {
  48436. ApplicationCommandTarget::InvocationInfo info (commandID);
  48437. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  48438. info.isKeyDown = isKeyDown;
  48439. info.keyPress = key;
  48440. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  48441. info.originatingComponent = originatingComponent;
  48442. commandManager->invoke (info, false);
  48443. }
  48444. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  48445. {
  48446. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  48447. {
  48448. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  48449. {
  48450. // if the XML was created as a set of differences from the default mappings,
  48451. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  48452. resetToDefaultMappings();
  48453. }
  48454. else
  48455. {
  48456. // if the XML was created calling createXml (false), then we need to clear all
  48457. // the keys and treat the xml as describing the entire set of mappings.
  48458. clearAllKeyPresses();
  48459. }
  48460. forEachXmlChildElement (xmlVersion, map)
  48461. {
  48462. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  48463. if (commandId != 0)
  48464. {
  48465. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  48466. if (map->hasTagName ("MAPPING"))
  48467. {
  48468. addKeyPress (commandId, key);
  48469. }
  48470. else if (map->hasTagName ("UNMAPPING"))
  48471. {
  48472. if (containsMapping (commandId, key))
  48473. removeKeyPress (key);
  48474. }
  48475. }
  48476. }
  48477. return true;
  48478. }
  48479. return false;
  48480. }
  48481. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  48482. {
  48483. ScopedPointer <KeyPressMappingSet> defaultSet;
  48484. if (saveDifferencesFromDefaultSet)
  48485. {
  48486. defaultSet = new KeyPressMappingSet (commandManager);
  48487. defaultSet->resetToDefaultMappings();
  48488. }
  48489. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  48490. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  48491. int i;
  48492. for (i = 0; i < mappings.size(); ++i)
  48493. {
  48494. const CommandMapping* const cm = mappings.getUnchecked(i);
  48495. for (int j = 0; j < cm->keypresses.size(); ++j)
  48496. {
  48497. if (defaultSet == 0
  48498. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48499. {
  48500. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  48501. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48502. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48503. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48504. }
  48505. }
  48506. }
  48507. if (defaultSet != 0)
  48508. {
  48509. for (i = 0; i < defaultSet->mappings.size(); ++i)
  48510. {
  48511. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  48512. for (int j = 0; j < cm->keypresses.size(); ++j)
  48513. {
  48514. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48515. {
  48516. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  48517. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48518. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48519. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48520. }
  48521. }
  48522. }
  48523. }
  48524. return doc;
  48525. }
  48526. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  48527. Component* originatingComponent)
  48528. {
  48529. bool used = false;
  48530. const CommandID commandID = findCommandForKeyPress (key);
  48531. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48532. if (ci != 0
  48533. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  48534. {
  48535. ApplicationCommandInfo info (0);
  48536. if (commandManager->getTargetForCommand (commandID, info) != 0
  48537. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  48538. {
  48539. invokeCommand (commandID, key, true, 0, originatingComponent);
  48540. used = true;
  48541. }
  48542. else
  48543. {
  48544. if (originatingComponent != 0)
  48545. originatingComponent->getLookAndFeel().playAlertSound();
  48546. }
  48547. }
  48548. return used;
  48549. }
  48550. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  48551. {
  48552. bool used = false;
  48553. const uint32 now = Time::getMillisecondCounter();
  48554. for (int i = mappings.size(); --i >= 0;)
  48555. {
  48556. CommandMapping* const cm = mappings.getUnchecked(i);
  48557. if (cm->wantsKeyUpDownCallbacks)
  48558. {
  48559. for (int j = cm->keypresses.size(); --j >= 0;)
  48560. {
  48561. const KeyPress key (cm->keypresses.getReference (j));
  48562. const bool isDown = key.isCurrentlyDown();
  48563. int keyPressEntryIndex = 0;
  48564. bool wasDown = false;
  48565. for (int k = keysDown.size(); --k >= 0;)
  48566. {
  48567. if (key == keysDown.getUnchecked(k)->key)
  48568. {
  48569. keyPressEntryIndex = k;
  48570. wasDown = true;
  48571. used = true;
  48572. break;
  48573. }
  48574. }
  48575. if (isDown != wasDown)
  48576. {
  48577. int millisecs = 0;
  48578. if (isDown)
  48579. {
  48580. KeyPressTime* const k = new KeyPressTime();
  48581. k->key = key;
  48582. k->timeWhenPressed = now;
  48583. keysDown.add (k);
  48584. }
  48585. else
  48586. {
  48587. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  48588. if (now > pressTime)
  48589. millisecs = now - pressTime;
  48590. keysDown.remove (keyPressEntryIndex);
  48591. }
  48592. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  48593. used = true;
  48594. }
  48595. }
  48596. }
  48597. }
  48598. return used;
  48599. }
  48600. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  48601. {
  48602. if (focusedComponent != 0)
  48603. focusedComponent->keyStateChanged (false);
  48604. }
  48605. END_JUCE_NAMESPACE
  48606. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  48607. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  48608. BEGIN_JUCE_NAMESPACE
  48609. ModifierKeys::ModifierKeys (const int flags_) throw()
  48610. : flags (flags_)
  48611. {
  48612. }
  48613. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  48614. : flags (other.flags)
  48615. {
  48616. }
  48617. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  48618. {
  48619. flags = other.flags;
  48620. return *this;
  48621. }
  48622. ModifierKeys ModifierKeys::currentModifiers;
  48623. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  48624. {
  48625. return currentModifiers;
  48626. }
  48627. int ModifierKeys::getNumMouseButtonsDown() const throw()
  48628. {
  48629. int num = 0;
  48630. if (isLeftButtonDown()) ++num;
  48631. if (isRightButtonDown()) ++num;
  48632. if (isMiddleButtonDown()) ++num;
  48633. return num;
  48634. }
  48635. END_JUCE_NAMESPACE
  48636. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  48637. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  48638. BEGIN_JUCE_NAMESPACE
  48639. class ComponentAnimator::AnimationTask
  48640. {
  48641. public:
  48642. AnimationTask (Component* const comp)
  48643. : component (comp)
  48644. {
  48645. }
  48646. Component::SafePointer<Component> component;
  48647. Rectangle<int> destination;
  48648. int msElapsed, msTotal;
  48649. double startSpeed, midSpeed, endSpeed, lastProgress;
  48650. double left, top, right, bottom;
  48651. bool useTimeslice (const int elapsed)
  48652. {
  48653. if (component == 0)
  48654. return false;
  48655. msElapsed += elapsed;
  48656. double newProgress = msElapsed / (double) msTotal;
  48657. if (newProgress >= 0 && newProgress < 1.0)
  48658. {
  48659. newProgress = timeToDistance (newProgress);
  48660. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  48661. jassert (newProgress >= lastProgress);
  48662. lastProgress = newProgress;
  48663. left += (destination.getX() - left) * delta;
  48664. top += (destination.getY() - top) * delta;
  48665. right += (destination.getRight() - right) * delta;
  48666. bottom += (destination.getBottom() - bottom) * delta;
  48667. if (delta < 1.0)
  48668. {
  48669. const Rectangle<int> newBounds (roundToInt (left),
  48670. roundToInt (top),
  48671. roundToInt (right - left),
  48672. roundToInt (bottom - top));
  48673. if (newBounds != destination)
  48674. {
  48675. component->setBounds (newBounds);
  48676. return true;
  48677. }
  48678. }
  48679. }
  48680. component->setBounds (destination);
  48681. return false;
  48682. }
  48683. void moveToFinalDestination()
  48684. {
  48685. if (component != 0)
  48686. component->setBounds (destination);
  48687. }
  48688. private:
  48689. inline double timeToDistance (const double time) const
  48690. {
  48691. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  48692. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  48693. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  48694. }
  48695. };
  48696. ComponentAnimator::ComponentAnimator()
  48697. : lastTime (0)
  48698. {
  48699. }
  48700. ComponentAnimator::~ComponentAnimator()
  48701. {
  48702. cancelAllAnimations (false);
  48703. jassert (tasks.size() == 0);
  48704. }
  48705. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  48706. {
  48707. for (int i = tasks.size(); --i >= 0;)
  48708. if (component == tasks.getUnchecked(i)->component.getComponent())
  48709. return tasks.getUnchecked(i);
  48710. return 0;
  48711. }
  48712. void ComponentAnimator::animateComponent (Component* const component,
  48713. const Rectangle<int>& finalPosition,
  48714. const int millisecondsToSpendMoving,
  48715. const double startSpeed,
  48716. const double endSpeed)
  48717. {
  48718. if (component != 0)
  48719. {
  48720. AnimationTask* at = findTaskFor (component);
  48721. if (at == 0)
  48722. {
  48723. at = new AnimationTask (component);
  48724. tasks.add (at);
  48725. sendChangeMessage (this);
  48726. }
  48727. at->msElapsed = 0;
  48728. at->lastProgress = 0;
  48729. at->msTotal = jmax (1, millisecondsToSpendMoving);
  48730. at->destination = finalPosition;
  48731. // the speeds must be 0 or greater!
  48732. jassert (startSpeed >= 0 && endSpeed >= 0)
  48733. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  48734. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  48735. at->midSpeed = invTotalDistance;
  48736. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  48737. at->left = component->getX();
  48738. at->top = component->getY();
  48739. at->right = component->getRight();
  48740. at->bottom = component->getBottom();
  48741. if (! isTimerRunning())
  48742. {
  48743. lastTime = Time::getMillisecondCounter();
  48744. startTimer (1000 / 50);
  48745. }
  48746. }
  48747. }
  48748. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  48749. {
  48750. for (int i = tasks.size(); --i >= 0;)
  48751. {
  48752. AnimationTask* const at = tasks.getUnchecked(i);
  48753. if (moveComponentsToTheirFinalPositions)
  48754. at->moveToFinalDestination();
  48755. delete at;
  48756. tasks.remove (i);
  48757. sendChangeMessage (this);
  48758. }
  48759. }
  48760. void ComponentAnimator::cancelAnimation (Component* const component,
  48761. const bool moveComponentToItsFinalPosition)
  48762. {
  48763. AnimationTask* const at = findTaskFor (component);
  48764. if (at != 0)
  48765. {
  48766. if (moveComponentToItsFinalPosition)
  48767. at->moveToFinalDestination();
  48768. tasks.removeValue (at);
  48769. delete at;
  48770. sendChangeMessage (this);
  48771. }
  48772. }
  48773. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  48774. {
  48775. AnimationTask* const at = findTaskFor (component);
  48776. if (at != 0)
  48777. return at->destination;
  48778. else if (component != 0)
  48779. return component->getBounds();
  48780. return Rectangle<int>();
  48781. }
  48782. bool ComponentAnimator::isAnimating (Component* component) const
  48783. {
  48784. return findTaskFor (component) != 0;
  48785. }
  48786. void ComponentAnimator::timerCallback()
  48787. {
  48788. const uint32 timeNow = Time::getMillisecondCounter();
  48789. if (lastTime == 0 || lastTime == timeNow)
  48790. lastTime = timeNow;
  48791. const int elapsed = timeNow - lastTime;
  48792. for (int i = tasks.size(); --i >= 0;)
  48793. {
  48794. AnimationTask* const at = tasks.getUnchecked(i);
  48795. if (! at->useTimeslice (elapsed))
  48796. {
  48797. tasks.remove (i);
  48798. delete at;
  48799. sendChangeMessage (this);
  48800. }
  48801. }
  48802. lastTime = timeNow;
  48803. if (tasks.size() == 0)
  48804. stopTimer();
  48805. }
  48806. END_JUCE_NAMESPACE
  48807. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  48808. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  48809. BEGIN_JUCE_NAMESPACE
  48810. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  48811. : minW (0),
  48812. maxW (0x3fffffff),
  48813. minH (0),
  48814. maxH (0x3fffffff),
  48815. minOffTop (0),
  48816. minOffLeft (0),
  48817. minOffBottom (0),
  48818. minOffRight (0),
  48819. aspectRatio (0.0)
  48820. {
  48821. }
  48822. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  48823. {
  48824. }
  48825. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  48826. {
  48827. minW = minimumWidth;
  48828. }
  48829. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  48830. {
  48831. maxW = maximumWidth;
  48832. }
  48833. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  48834. {
  48835. minH = minimumHeight;
  48836. }
  48837. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  48838. {
  48839. maxH = maximumHeight;
  48840. }
  48841. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  48842. {
  48843. jassert (maxW >= minimumWidth);
  48844. jassert (maxH >= minimumHeight);
  48845. jassert (minimumWidth > 0 && minimumHeight > 0);
  48846. minW = minimumWidth;
  48847. minH = minimumHeight;
  48848. if (minW > maxW)
  48849. maxW = minW;
  48850. if (minH > maxH)
  48851. maxH = minH;
  48852. }
  48853. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  48854. {
  48855. jassert (maximumWidth >= minW);
  48856. jassert (maximumHeight >= minH);
  48857. jassert (maximumWidth > 0 && maximumHeight > 0);
  48858. maxW = jmax (minW, maximumWidth);
  48859. maxH = jmax (minH, maximumHeight);
  48860. }
  48861. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  48862. const int minimumHeight,
  48863. const int maximumWidth,
  48864. const int maximumHeight) throw()
  48865. {
  48866. jassert (maximumWidth >= minimumWidth);
  48867. jassert (maximumHeight >= minimumHeight);
  48868. jassert (maximumWidth > 0 && maximumHeight > 0);
  48869. jassert (minimumWidth > 0 && minimumHeight > 0);
  48870. minW = jmax (0, minimumWidth);
  48871. minH = jmax (0, minimumHeight);
  48872. maxW = jmax (minW, maximumWidth);
  48873. maxH = jmax (minH, maximumHeight);
  48874. }
  48875. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  48876. const int minimumWhenOffTheLeft,
  48877. const int minimumWhenOffTheBottom,
  48878. const int minimumWhenOffTheRight) throw()
  48879. {
  48880. minOffTop = minimumWhenOffTheTop;
  48881. minOffLeft = minimumWhenOffTheLeft;
  48882. minOffBottom = minimumWhenOffTheBottom;
  48883. minOffRight = minimumWhenOffTheRight;
  48884. }
  48885. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  48886. {
  48887. aspectRatio = jmax (0.0, widthOverHeight);
  48888. }
  48889. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  48890. {
  48891. return aspectRatio;
  48892. }
  48893. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  48894. const Rectangle<int>& targetBounds,
  48895. const bool isStretchingTop,
  48896. const bool isStretchingLeft,
  48897. const bool isStretchingBottom,
  48898. const bool isStretchingRight)
  48899. {
  48900. jassert (component != 0);
  48901. Rectangle<int> limits, bounds (targetBounds);
  48902. BorderSize border;
  48903. Component* const parent = component->getParentComponent();
  48904. if (parent == 0)
  48905. {
  48906. ComponentPeer* peer = component->getPeer();
  48907. if (peer != 0)
  48908. border = peer->getFrameSize();
  48909. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  48910. }
  48911. else
  48912. {
  48913. limits.setSize (parent->getWidth(), parent->getHeight());
  48914. }
  48915. border.addTo (bounds);
  48916. checkBounds (bounds,
  48917. border.addedTo (component->getBounds()), limits,
  48918. isStretchingTop, isStretchingLeft,
  48919. isStretchingBottom, isStretchingRight);
  48920. border.subtractFrom (bounds);
  48921. applyBoundsToComponent (component, bounds);
  48922. }
  48923. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  48924. {
  48925. setBoundsForComponent (component, component->getBounds(),
  48926. false, false, false, false);
  48927. }
  48928. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  48929. const Rectangle<int>& bounds)
  48930. {
  48931. component->setBounds (bounds);
  48932. }
  48933. void ComponentBoundsConstrainer::resizeStart()
  48934. {
  48935. }
  48936. void ComponentBoundsConstrainer::resizeEnd()
  48937. {
  48938. }
  48939. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  48940. const Rectangle<int>& old,
  48941. const Rectangle<int>& limits,
  48942. const bool isStretchingTop,
  48943. const bool isStretchingLeft,
  48944. const bool isStretchingBottom,
  48945. const bool isStretchingRight)
  48946. {
  48947. int x = bounds.getX();
  48948. int y = bounds.getY();
  48949. int w = bounds.getWidth();
  48950. int h = bounds.getHeight();
  48951. // constrain the size if it's being stretched..
  48952. if (isStretchingLeft)
  48953. {
  48954. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  48955. w = old.getRight() - x;
  48956. }
  48957. if (isStretchingRight)
  48958. {
  48959. w = jlimit (minW, maxW, w);
  48960. }
  48961. if (isStretchingTop)
  48962. {
  48963. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  48964. h = old.getBottom() - y;
  48965. }
  48966. if (isStretchingBottom)
  48967. {
  48968. h = jlimit (minH, maxH, h);
  48969. }
  48970. // constrain the aspect ratio if one has been specified..
  48971. if (aspectRatio > 0.0 && w > 0 && h > 0)
  48972. {
  48973. bool adjustWidth;
  48974. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  48975. {
  48976. adjustWidth = true;
  48977. }
  48978. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  48979. {
  48980. adjustWidth = false;
  48981. }
  48982. else
  48983. {
  48984. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  48985. const double newRatio = std::abs (w / (double) h);
  48986. adjustWidth = (oldRatio > newRatio);
  48987. }
  48988. if (adjustWidth)
  48989. {
  48990. w = roundToInt (h * aspectRatio);
  48991. if (w > maxW || w < minW)
  48992. {
  48993. w = jlimit (minW, maxW, w);
  48994. h = roundToInt (w / aspectRatio);
  48995. }
  48996. }
  48997. else
  48998. {
  48999. h = roundToInt (w / aspectRatio);
  49000. if (h > maxH || h < minH)
  49001. {
  49002. h = jlimit (minH, maxH, h);
  49003. w = roundToInt (h * aspectRatio);
  49004. }
  49005. }
  49006. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49007. {
  49008. x = old.getX() + (old.getWidth() - w) / 2;
  49009. }
  49010. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49011. {
  49012. y = old.getY() + (old.getHeight() - h) / 2;
  49013. }
  49014. else
  49015. {
  49016. if (isStretchingLeft)
  49017. x = old.getRight() - w;
  49018. if (isStretchingTop)
  49019. y = old.getBottom() - h;
  49020. }
  49021. }
  49022. // ...and constrain the position if limits have been set for that.
  49023. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  49024. {
  49025. if (minOffTop > 0)
  49026. {
  49027. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  49028. if (y < limit)
  49029. {
  49030. if (isStretchingTop)
  49031. h -= (limit - y);
  49032. y = limit;
  49033. }
  49034. }
  49035. if (minOffLeft > 0)
  49036. {
  49037. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  49038. if (x < limit)
  49039. {
  49040. if (isStretchingLeft)
  49041. w -= (limit - x);
  49042. x = limit;
  49043. }
  49044. }
  49045. if (minOffBottom > 0)
  49046. {
  49047. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  49048. if (y > limit)
  49049. {
  49050. if (isStretchingBottom)
  49051. h += (limit - y);
  49052. else
  49053. y = limit;
  49054. }
  49055. }
  49056. if (minOffRight > 0)
  49057. {
  49058. const int limit = limits.getRight() - jmin (minOffRight, w);
  49059. if (x > limit)
  49060. {
  49061. if (isStretchingRight)
  49062. w += (limit - x);
  49063. else
  49064. x = limit;
  49065. }
  49066. }
  49067. }
  49068. jassert (w >= 0 && h >= 0);
  49069. bounds = Rectangle<int> (x, y, w, h);
  49070. }
  49071. END_JUCE_NAMESPACE
  49072. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49073. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49074. BEGIN_JUCE_NAMESPACE
  49075. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49076. : component (component_),
  49077. lastPeer (0),
  49078. reentrant (false)
  49079. {
  49080. jassert (component != 0); // can't use this with a null pointer..
  49081. component->addComponentListener (this);
  49082. registerWithParentComps();
  49083. }
  49084. ComponentMovementWatcher::~ComponentMovementWatcher()
  49085. {
  49086. component->removeComponentListener (this);
  49087. unregister();
  49088. }
  49089. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49090. {
  49091. // agh! don't delete the target component without deleting this object first!
  49092. jassert (component != 0);
  49093. if (! reentrant)
  49094. {
  49095. reentrant = true;
  49096. ComponentPeer* const peer = component->getPeer();
  49097. if (peer != lastPeer)
  49098. {
  49099. componentPeerChanged();
  49100. if (component == 0)
  49101. return;
  49102. lastPeer = peer;
  49103. }
  49104. unregister();
  49105. registerWithParentComps();
  49106. reentrant = false;
  49107. componentMovedOrResized (*component, true, true);
  49108. }
  49109. }
  49110. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49111. {
  49112. // agh! don't delete the target component without deleting this object first!
  49113. jassert (component != 0);
  49114. if (wasMoved)
  49115. {
  49116. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  49117. wasMoved = lastBounds.getPosition() != pos;
  49118. lastBounds.setPosition (pos);
  49119. }
  49120. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49121. lastBounds.setSize (component->getWidth(), component->getHeight());
  49122. if (wasMoved || wasResized)
  49123. componentMovedOrResized (wasMoved, wasResized);
  49124. }
  49125. void ComponentMovementWatcher::registerWithParentComps()
  49126. {
  49127. Component* p = component->getParentComponent();
  49128. while (p != 0)
  49129. {
  49130. p->addComponentListener (this);
  49131. registeredParentComps.add (p);
  49132. p = p->getParentComponent();
  49133. }
  49134. }
  49135. void ComponentMovementWatcher::unregister()
  49136. {
  49137. for (int i = registeredParentComps.size(); --i >= 0;)
  49138. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49139. registeredParentComps.clear();
  49140. }
  49141. END_JUCE_NAMESPACE
  49142. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49143. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49144. BEGIN_JUCE_NAMESPACE
  49145. GroupComponent::GroupComponent (const String& componentName,
  49146. const String& labelText)
  49147. : Component (componentName),
  49148. text (labelText),
  49149. justification (Justification::left)
  49150. {
  49151. setInterceptsMouseClicks (false, true);
  49152. }
  49153. GroupComponent::~GroupComponent()
  49154. {
  49155. }
  49156. void GroupComponent::setText (const String& newText)
  49157. {
  49158. if (text != newText)
  49159. {
  49160. text = newText;
  49161. repaint();
  49162. }
  49163. }
  49164. const String GroupComponent::getText() const
  49165. {
  49166. return text;
  49167. }
  49168. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49169. {
  49170. if (justification != newJustification)
  49171. {
  49172. justification = newJustification;
  49173. repaint();
  49174. }
  49175. }
  49176. void GroupComponent::paint (Graphics& g)
  49177. {
  49178. getLookAndFeel()
  49179. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49180. text, justification,
  49181. *this);
  49182. }
  49183. void GroupComponent::enablementChanged()
  49184. {
  49185. repaint();
  49186. }
  49187. void GroupComponent::colourChanged()
  49188. {
  49189. repaint();
  49190. }
  49191. END_JUCE_NAMESPACE
  49192. /*** End of inlined file: juce_GroupComponent.cpp ***/
  49193. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  49194. BEGIN_JUCE_NAMESPACE
  49195. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  49196. : DocumentWindow (String::empty, backgroundColour,
  49197. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  49198. {
  49199. }
  49200. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  49201. {
  49202. }
  49203. void MultiDocumentPanelWindow::maximiseButtonPressed()
  49204. {
  49205. MultiDocumentPanel* const owner = getOwner();
  49206. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49207. if (owner != 0)
  49208. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49209. }
  49210. void MultiDocumentPanelWindow::closeButtonPressed()
  49211. {
  49212. MultiDocumentPanel* const owner = getOwner();
  49213. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49214. if (owner != 0)
  49215. owner->closeDocument (getContentComponent(), true);
  49216. }
  49217. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49218. {
  49219. DocumentWindow::activeWindowStatusChanged();
  49220. updateOrder();
  49221. }
  49222. void MultiDocumentPanelWindow::broughtToFront()
  49223. {
  49224. DocumentWindow::broughtToFront();
  49225. updateOrder();
  49226. }
  49227. void MultiDocumentPanelWindow::updateOrder()
  49228. {
  49229. MultiDocumentPanel* const owner = getOwner();
  49230. if (owner != 0)
  49231. owner->updateOrder();
  49232. }
  49233. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49234. {
  49235. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49236. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49237. }
  49238. class MDITabbedComponentInternal : public TabbedComponent
  49239. {
  49240. public:
  49241. MDITabbedComponentInternal()
  49242. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  49243. {
  49244. }
  49245. ~MDITabbedComponentInternal()
  49246. {
  49247. }
  49248. void currentTabChanged (int, const String&)
  49249. {
  49250. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49251. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49252. if (owner != 0)
  49253. owner->updateOrder();
  49254. }
  49255. };
  49256. MultiDocumentPanel::MultiDocumentPanel()
  49257. : mode (MaximisedWindowsWithTabs),
  49258. tabComponent (0),
  49259. backgroundColour (Colours::lightblue),
  49260. maximumNumDocuments (0),
  49261. numDocsBeforeTabsUsed (0)
  49262. {
  49263. setOpaque (true);
  49264. }
  49265. MultiDocumentPanel::~MultiDocumentPanel()
  49266. {
  49267. closeAllDocuments (false);
  49268. }
  49269. static bool shouldDeleteComp (Component* const c)
  49270. {
  49271. return c->getProperties() ["mdiDocumentDelete_"];
  49272. }
  49273. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49274. {
  49275. while (components.size() > 0)
  49276. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49277. return false;
  49278. return true;
  49279. }
  49280. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  49281. {
  49282. return new MultiDocumentPanelWindow (backgroundColour);
  49283. }
  49284. void MultiDocumentPanel::addWindow (Component* component)
  49285. {
  49286. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  49287. dw->setResizable (true, false);
  49288. dw->setContentComponent (component, false, true);
  49289. dw->setName (component->getName());
  49290. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  49291. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  49292. int x = 4;
  49293. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  49294. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  49295. x += 16;
  49296. dw->setTopLeftPosition (x, x);
  49297. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  49298. if (pos.toString().isNotEmpty())
  49299. dw->restoreWindowStateFromString (pos.toString());
  49300. addAndMakeVisible (dw);
  49301. dw->toFront (true);
  49302. }
  49303. bool MultiDocumentPanel::addDocument (Component* const component,
  49304. const Colour& docColour,
  49305. const bool deleteWhenRemoved)
  49306. {
  49307. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  49308. // with a frame-within-a-frame! Just pass in the bare content component.
  49309. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  49310. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  49311. return false;
  49312. components.add (component);
  49313. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  49314. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  49315. component->addComponentListener (this);
  49316. if (mode == FloatingWindows)
  49317. {
  49318. if (isFullscreenWhenOneDocument())
  49319. {
  49320. if (components.size() == 1)
  49321. {
  49322. addAndMakeVisible (component);
  49323. }
  49324. else
  49325. {
  49326. if (components.size() == 2)
  49327. addWindow (components.getFirst());
  49328. addWindow (component);
  49329. }
  49330. }
  49331. else
  49332. {
  49333. addWindow (component);
  49334. }
  49335. }
  49336. else
  49337. {
  49338. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  49339. {
  49340. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  49341. Array <Component*> temp (components);
  49342. for (int i = 0; i < temp.size(); ++i)
  49343. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  49344. resized();
  49345. }
  49346. else
  49347. {
  49348. if (tabComponent != 0)
  49349. tabComponent->addTab (component->getName(), docColour, component, false);
  49350. else
  49351. addAndMakeVisible (component);
  49352. }
  49353. setActiveDocument (component);
  49354. }
  49355. resized();
  49356. activeDocumentChanged();
  49357. return true;
  49358. }
  49359. bool MultiDocumentPanel::closeDocument (Component* component,
  49360. const bool checkItsOkToCloseFirst)
  49361. {
  49362. if (components.contains (component))
  49363. {
  49364. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  49365. return false;
  49366. component->removeComponentListener (this);
  49367. const bool shouldDelete = shouldDeleteComp (component);
  49368. component->getProperties().remove ("mdiDocumentDelete_");
  49369. component->getProperties().remove ("mdiDocumentBkg_");
  49370. if (mode == FloatingWindows)
  49371. {
  49372. for (int i = getNumChildComponents(); --i >= 0;)
  49373. {
  49374. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49375. if (dw != 0 && dw->getContentComponent() == component)
  49376. {
  49377. dw->setContentComponent (0, false);
  49378. delete dw;
  49379. break;
  49380. }
  49381. }
  49382. if (shouldDelete)
  49383. delete component;
  49384. components.removeValue (component);
  49385. if (isFullscreenWhenOneDocument() && components.size() == 1)
  49386. {
  49387. for (int i = getNumChildComponents(); --i >= 0;)
  49388. {
  49389. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49390. if (dw != 0)
  49391. {
  49392. dw->setContentComponent (0, false);
  49393. delete dw;
  49394. }
  49395. }
  49396. addAndMakeVisible (components.getFirst());
  49397. }
  49398. }
  49399. else
  49400. {
  49401. jassert (components.indexOf (component) >= 0);
  49402. if (tabComponent != 0)
  49403. {
  49404. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49405. if (tabComponent->getTabContentComponent (i) == component)
  49406. tabComponent->removeTab (i);
  49407. }
  49408. else
  49409. {
  49410. removeChildComponent (component);
  49411. }
  49412. if (shouldDelete)
  49413. delete component;
  49414. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  49415. deleteAndZero (tabComponent);
  49416. components.removeValue (component);
  49417. if (components.size() > 0 && tabComponent == 0)
  49418. addAndMakeVisible (components.getFirst());
  49419. }
  49420. resized();
  49421. activeDocumentChanged();
  49422. }
  49423. else
  49424. {
  49425. jassertfalse;
  49426. }
  49427. return true;
  49428. }
  49429. int MultiDocumentPanel::getNumDocuments() const throw()
  49430. {
  49431. return components.size();
  49432. }
  49433. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  49434. {
  49435. return components [index];
  49436. }
  49437. Component* MultiDocumentPanel::getActiveDocument() const throw()
  49438. {
  49439. if (mode == FloatingWindows)
  49440. {
  49441. for (int i = getNumChildComponents(); --i >= 0;)
  49442. {
  49443. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49444. if (dw != 0 && dw->isActiveWindow())
  49445. return dw->getContentComponent();
  49446. }
  49447. }
  49448. return components.getLast();
  49449. }
  49450. void MultiDocumentPanel::setActiveDocument (Component* component)
  49451. {
  49452. if (mode == FloatingWindows)
  49453. {
  49454. component = getContainerComp (component);
  49455. if (component != 0)
  49456. component->toFront (true);
  49457. }
  49458. else if (tabComponent != 0)
  49459. {
  49460. jassert (components.indexOf (component) >= 0);
  49461. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49462. {
  49463. if (tabComponent->getTabContentComponent (i) == component)
  49464. {
  49465. tabComponent->setCurrentTabIndex (i);
  49466. break;
  49467. }
  49468. }
  49469. }
  49470. else
  49471. {
  49472. component->grabKeyboardFocus();
  49473. }
  49474. }
  49475. void MultiDocumentPanel::activeDocumentChanged()
  49476. {
  49477. }
  49478. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  49479. {
  49480. maximumNumDocuments = newNumber;
  49481. }
  49482. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  49483. {
  49484. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  49485. }
  49486. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  49487. {
  49488. return numDocsBeforeTabsUsed != 0;
  49489. }
  49490. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  49491. {
  49492. if (mode != newLayoutMode)
  49493. {
  49494. mode = newLayoutMode;
  49495. if (mode == FloatingWindows)
  49496. {
  49497. deleteAndZero (tabComponent);
  49498. }
  49499. else
  49500. {
  49501. for (int i = getNumChildComponents(); --i >= 0;)
  49502. {
  49503. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49504. if (dw != 0)
  49505. {
  49506. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  49507. dw->setContentComponent (0, false);
  49508. delete dw;
  49509. }
  49510. }
  49511. }
  49512. resized();
  49513. const Array <Component*> tempComps (components);
  49514. components.clear();
  49515. for (int i = 0; i < tempComps.size(); ++i)
  49516. {
  49517. Component* const c = tempComps.getUnchecked(i);
  49518. addDocument (c,
  49519. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  49520. shouldDeleteComp (c));
  49521. }
  49522. }
  49523. }
  49524. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  49525. {
  49526. if (backgroundColour != newBackgroundColour)
  49527. {
  49528. backgroundColour = newBackgroundColour;
  49529. setOpaque (newBackgroundColour.isOpaque());
  49530. repaint();
  49531. }
  49532. }
  49533. void MultiDocumentPanel::paint (Graphics& g)
  49534. {
  49535. g.fillAll (backgroundColour);
  49536. }
  49537. void MultiDocumentPanel::resized()
  49538. {
  49539. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  49540. {
  49541. for (int i = getNumChildComponents(); --i >= 0;)
  49542. getChildComponent (i)->setBounds (getLocalBounds());
  49543. }
  49544. setWantsKeyboardFocus (components.size() == 0);
  49545. }
  49546. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  49547. {
  49548. if (mode == FloatingWindows)
  49549. {
  49550. for (int i = 0; i < getNumChildComponents(); ++i)
  49551. {
  49552. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49553. if (dw != 0 && dw->getContentComponent() == c)
  49554. {
  49555. c = dw;
  49556. break;
  49557. }
  49558. }
  49559. }
  49560. return c;
  49561. }
  49562. void MultiDocumentPanel::componentNameChanged (Component&)
  49563. {
  49564. if (mode == FloatingWindows)
  49565. {
  49566. for (int i = 0; i < getNumChildComponents(); ++i)
  49567. {
  49568. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49569. if (dw != 0)
  49570. dw->setName (dw->getContentComponent()->getName());
  49571. }
  49572. }
  49573. else if (tabComponent != 0)
  49574. {
  49575. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49576. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  49577. }
  49578. }
  49579. void MultiDocumentPanel::updateOrder()
  49580. {
  49581. const Array <Component*> oldList (components);
  49582. if (mode == FloatingWindows)
  49583. {
  49584. components.clear();
  49585. for (int i = 0; i < getNumChildComponents(); ++i)
  49586. {
  49587. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49588. if (dw != 0)
  49589. components.add (dw->getContentComponent());
  49590. }
  49591. }
  49592. else
  49593. {
  49594. if (tabComponent != 0)
  49595. {
  49596. Component* const current = tabComponent->getCurrentContentComponent();
  49597. if (current != 0)
  49598. {
  49599. components.removeValue (current);
  49600. components.add (current);
  49601. }
  49602. }
  49603. }
  49604. if (components != oldList)
  49605. activeDocumentChanged();
  49606. }
  49607. END_JUCE_NAMESPACE
  49608. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  49609. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  49610. BEGIN_JUCE_NAMESPACE
  49611. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  49612. : zone (zoneFlags)
  49613. {
  49614. }
  49615. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  49616. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  49617. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  49618. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  49619. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  49620. const BorderSize& border,
  49621. const Point<int>& position)
  49622. {
  49623. int z = 0;
  49624. if (totalSize.contains (position)
  49625. && ! border.subtractedFrom (totalSize).contains (position))
  49626. {
  49627. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  49628. if (position.getX() < jmax (border.getLeft(), minW))
  49629. z |= left;
  49630. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  49631. z |= right;
  49632. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  49633. if (position.getY() < jmax (border.getTop(), minH))
  49634. z |= top;
  49635. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  49636. z |= bottom;
  49637. }
  49638. return Zone (z);
  49639. }
  49640. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  49641. {
  49642. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  49643. switch (zone)
  49644. {
  49645. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  49646. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  49647. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  49648. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  49649. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  49650. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  49651. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  49652. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  49653. default: break;
  49654. }
  49655. return mc;
  49656. }
  49657. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  49658. {
  49659. if (isDraggingWholeObject())
  49660. return b + offset;
  49661. if (isDraggingLeftEdge())
  49662. b.setLeft (b.getX() + offset.getX());
  49663. if (isDraggingRightEdge())
  49664. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  49665. if (isDraggingTopEdge())
  49666. b.setTop (b.getY() + offset.getY());
  49667. if (isDraggingBottomEdge())
  49668. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  49669. return b;
  49670. }
  49671. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  49672. {
  49673. if (isDraggingWholeObject())
  49674. return b + offset;
  49675. if (isDraggingLeftEdge())
  49676. b.setLeft (b.getX() + offset.getX());
  49677. if (isDraggingRightEdge())
  49678. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  49679. if (isDraggingTopEdge())
  49680. b.setTop (b.getY() + offset.getY());
  49681. if (isDraggingBottomEdge())
  49682. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  49683. return b;
  49684. }
  49685. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  49686. ComponentBoundsConstrainer* const constrainer_)
  49687. : component (componentToResize),
  49688. constrainer (constrainer_),
  49689. borderSize (5),
  49690. mouseZone (0)
  49691. {
  49692. }
  49693. ResizableBorderComponent::~ResizableBorderComponent()
  49694. {
  49695. }
  49696. void ResizableBorderComponent::paint (Graphics& g)
  49697. {
  49698. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  49699. }
  49700. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  49701. {
  49702. updateMouseZone (e);
  49703. }
  49704. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  49705. {
  49706. updateMouseZone (e);
  49707. }
  49708. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  49709. {
  49710. if (component == 0)
  49711. {
  49712. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  49713. return;
  49714. }
  49715. updateMouseZone (e);
  49716. originalBounds = component->getBounds();
  49717. if (constrainer != 0)
  49718. constrainer->resizeStart();
  49719. }
  49720. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  49721. {
  49722. if (component == 0)
  49723. {
  49724. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  49725. return;
  49726. }
  49727. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  49728. if (constrainer != 0)
  49729. constrainer->setBoundsForComponent (component, bounds,
  49730. mouseZone.isDraggingTopEdge(),
  49731. mouseZone.isDraggingLeftEdge(),
  49732. mouseZone.isDraggingBottomEdge(),
  49733. mouseZone.isDraggingRightEdge());
  49734. else
  49735. component->setBounds (bounds);
  49736. }
  49737. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  49738. {
  49739. if (constrainer != 0)
  49740. constrainer->resizeEnd();
  49741. }
  49742. bool ResizableBorderComponent::hitTest (int x, int y)
  49743. {
  49744. return x < borderSize.getLeft()
  49745. || x >= getWidth() - borderSize.getRight()
  49746. || y < borderSize.getTop()
  49747. || y >= getHeight() - borderSize.getBottom();
  49748. }
  49749. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  49750. {
  49751. if (borderSize != newBorderSize)
  49752. {
  49753. borderSize = newBorderSize;
  49754. repaint();
  49755. }
  49756. }
  49757. const BorderSize ResizableBorderComponent::getBorderThickness() const
  49758. {
  49759. return borderSize;
  49760. }
  49761. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  49762. {
  49763. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  49764. if (mouseZone != newZone)
  49765. {
  49766. mouseZone = newZone;
  49767. setMouseCursor (newZone.getMouseCursor());
  49768. }
  49769. }
  49770. END_JUCE_NAMESPACE
  49771. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  49772. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  49773. BEGIN_JUCE_NAMESPACE
  49774. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  49775. ComponentBoundsConstrainer* const constrainer_)
  49776. : component (componentToResize),
  49777. constrainer (constrainer_)
  49778. {
  49779. setRepaintsOnMouseActivity (true);
  49780. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  49781. }
  49782. ResizableCornerComponent::~ResizableCornerComponent()
  49783. {
  49784. }
  49785. void ResizableCornerComponent::paint (Graphics& g)
  49786. {
  49787. getLookAndFeel()
  49788. .drawCornerResizer (g, getWidth(), getHeight(),
  49789. isMouseOverOrDragging(),
  49790. isMouseButtonDown());
  49791. }
  49792. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  49793. {
  49794. if (component == 0)
  49795. {
  49796. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49797. return;
  49798. }
  49799. originalBounds = component->getBounds();
  49800. if (constrainer != 0)
  49801. constrainer->resizeStart();
  49802. }
  49803. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  49804. {
  49805. if (component == 0)
  49806. {
  49807. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49808. return;
  49809. }
  49810. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  49811. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  49812. if (constrainer != 0)
  49813. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  49814. else
  49815. component->setBounds (r);
  49816. }
  49817. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  49818. {
  49819. if (constrainer != 0)
  49820. constrainer->resizeStart();
  49821. }
  49822. bool ResizableCornerComponent::hitTest (int x, int y)
  49823. {
  49824. if (getWidth() <= 0)
  49825. return false;
  49826. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  49827. return y >= yAtX - getHeight() / 4;
  49828. }
  49829. END_JUCE_NAMESPACE
  49830. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  49831. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  49832. BEGIN_JUCE_NAMESPACE
  49833. class ScrollBar::ScrollbarButton : public Button
  49834. {
  49835. public:
  49836. int direction;
  49837. ScrollbarButton (const int direction_, ScrollBar& owner_)
  49838. : Button (String::empty),
  49839. direction (direction_),
  49840. owner (owner_)
  49841. {
  49842. setWantsKeyboardFocus (false);
  49843. }
  49844. ~ScrollbarButton()
  49845. {
  49846. }
  49847. void paintButton (Graphics& g, bool over, bool down)
  49848. {
  49849. getLookAndFeel()
  49850. .drawScrollbarButton (g, owner,
  49851. getWidth(), getHeight(),
  49852. direction,
  49853. owner.isVertical(),
  49854. over, down);
  49855. }
  49856. void clicked()
  49857. {
  49858. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  49859. }
  49860. juce_UseDebuggingNewOperator
  49861. private:
  49862. ScrollBar& owner;
  49863. ScrollbarButton (const ScrollbarButton&);
  49864. ScrollbarButton& operator= (const ScrollbarButton&);
  49865. };
  49866. ScrollBar::ScrollBar (const bool vertical_,
  49867. const bool buttonsAreVisible)
  49868. : totalRange (0.0, 1.0),
  49869. visibleRange (0.0, 0.1),
  49870. singleStepSize (0.1),
  49871. thumbAreaStart (0),
  49872. thumbAreaSize (0),
  49873. thumbStart (0),
  49874. thumbSize (0),
  49875. initialDelayInMillisecs (100),
  49876. repeatDelayInMillisecs (50),
  49877. minimumDelayInMillisecs (10),
  49878. vertical (vertical_),
  49879. isDraggingThumb (false),
  49880. autohides (true)
  49881. {
  49882. setButtonVisibility (buttonsAreVisible);
  49883. setRepaintsOnMouseActivity (true);
  49884. setFocusContainer (true);
  49885. }
  49886. ScrollBar::~ScrollBar()
  49887. {
  49888. upButton = 0;
  49889. downButton = 0;
  49890. }
  49891. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  49892. {
  49893. if (totalRange != newRangeLimit)
  49894. {
  49895. totalRange = newRangeLimit;
  49896. setCurrentRange (visibleRange);
  49897. updateThumbPosition();
  49898. }
  49899. }
  49900. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  49901. {
  49902. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  49903. setRangeLimits (Range<double> (newMinimum, newMaximum));
  49904. }
  49905. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  49906. {
  49907. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  49908. if (visibleRange != constrainedRange)
  49909. {
  49910. visibleRange = constrainedRange;
  49911. updateThumbPosition();
  49912. triggerAsyncUpdate();
  49913. }
  49914. }
  49915. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  49916. {
  49917. setCurrentRange (Range<double> (newStart, newStart + newSize));
  49918. }
  49919. void ScrollBar::setCurrentRangeStart (const double newStart)
  49920. {
  49921. setCurrentRange (visibleRange.movedToStartAt (newStart));
  49922. }
  49923. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  49924. {
  49925. singleStepSize = newSingleStepSize;
  49926. }
  49927. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  49928. {
  49929. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  49930. }
  49931. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  49932. {
  49933. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  49934. }
  49935. void ScrollBar::scrollToTop()
  49936. {
  49937. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  49938. }
  49939. void ScrollBar::scrollToBottom()
  49940. {
  49941. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  49942. }
  49943. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  49944. const int repeatDelayInMillisecs_,
  49945. const int minimumDelayInMillisecs_)
  49946. {
  49947. initialDelayInMillisecs = initialDelayInMillisecs_;
  49948. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  49949. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  49950. if (upButton != 0)
  49951. {
  49952. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49953. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49954. }
  49955. }
  49956. void ScrollBar::addListener (Listener* const listener)
  49957. {
  49958. listeners.add (listener);
  49959. }
  49960. void ScrollBar::removeListener (Listener* const listener)
  49961. {
  49962. listeners.remove (listener);
  49963. }
  49964. void ScrollBar::handleAsyncUpdate()
  49965. {
  49966. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  49967. listeners.call (&Listener::scrollBarMoved, this, start);
  49968. }
  49969. void ScrollBar::updateThumbPosition()
  49970. {
  49971. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  49972. : thumbAreaSize);
  49973. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49974. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  49975. if (newThumbSize > thumbAreaSize)
  49976. newThumbSize = thumbAreaSize;
  49977. int newThumbStart = thumbAreaStart;
  49978. if (totalRange.getLength() > visibleRange.getLength())
  49979. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  49980. / (totalRange.getLength() - visibleRange.getLength()));
  49981. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  49982. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  49983. {
  49984. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  49985. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  49986. if (vertical)
  49987. repaint (0, repaintStart, getWidth(), repaintSize);
  49988. else
  49989. repaint (repaintStart, 0, repaintSize, getHeight());
  49990. thumbStart = newThumbStart;
  49991. thumbSize = newThumbSize;
  49992. }
  49993. }
  49994. void ScrollBar::setOrientation (const bool shouldBeVertical)
  49995. {
  49996. if (vertical != shouldBeVertical)
  49997. {
  49998. vertical = shouldBeVertical;
  49999. if (upButton != 0)
  50000. {
  50001. upButton->direction = vertical ? 0 : 3;
  50002. downButton->direction = vertical ? 2 : 1;
  50003. }
  50004. updateThumbPosition();
  50005. }
  50006. }
  50007. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50008. {
  50009. upButton = 0;
  50010. downButton = 0;
  50011. if (buttonsAreVisible)
  50012. {
  50013. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50014. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50015. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50016. }
  50017. updateThumbPosition();
  50018. }
  50019. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50020. {
  50021. autohides = shouldHideWhenFullRange;
  50022. updateThumbPosition();
  50023. }
  50024. bool ScrollBar::autoHides() const throw()
  50025. {
  50026. return autohides;
  50027. }
  50028. void ScrollBar::paint (Graphics& g)
  50029. {
  50030. if (thumbAreaSize > 0)
  50031. {
  50032. LookAndFeel& lf = getLookAndFeel();
  50033. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50034. ? thumbSize : 0;
  50035. if (vertical)
  50036. {
  50037. lf.drawScrollbar (g, *this,
  50038. 0, thumbAreaStart,
  50039. getWidth(), thumbAreaSize,
  50040. vertical,
  50041. thumbStart, thumb,
  50042. isMouseOver(), isMouseButtonDown());
  50043. }
  50044. else
  50045. {
  50046. lf.drawScrollbar (g, *this,
  50047. thumbAreaStart, 0,
  50048. thumbAreaSize, getHeight(),
  50049. vertical,
  50050. thumbStart, thumb,
  50051. isMouseOver(), isMouseButtonDown());
  50052. }
  50053. }
  50054. }
  50055. void ScrollBar::lookAndFeelChanged()
  50056. {
  50057. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50058. }
  50059. void ScrollBar::resized()
  50060. {
  50061. const int length = ((vertical) ? getHeight() : getWidth());
  50062. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50063. : 0;
  50064. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50065. {
  50066. thumbAreaStart = length >> 1;
  50067. thumbAreaSize = 0;
  50068. }
  50069. else
  50070. {
  50071. thumbAreaStart = buttonSize;
  50072. thumbAreaSize = length - (buttonSize << 1);
  50073. }
  50074. if (upButton != 0)
  50075. {
  50076. if (vertical)
  50077. {
  50078. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50079. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50080. }
  50081. else
  50082. {
  50083. upButton->setBounds (0, 0, buttonSize, getHeight());
  50084. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50085. }
  50086. }
  50087. updateThumbPosition();
  50088. }
  50089. void ScrollBar::mouseDown (const MouseEvent& e)
  50090. {
  50091. isDraggingThumb = false;
  50092. lastMousePos = vertical ? e.y : e.x;
  50093. dragStartMousePos = lastMousePos;
  50094. dragStartRange = visibleRange.getStart();
  50095. if (dragStartMousePos < thumbStart)
  50096. {
  50097. moveScrollbarInPages (-1);
  50098. startTimer (400);
  50099. }
  50100. else if (dragStartMousePos >= thumbStart + thumbSize)
  50101. {
  50102. moveScrollbarInPages (1);
  50103. startTimer (400);
  50104. }
  50105. else
  50106. {
  50107. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50108. && (thumbAreaSize > thumbSize);
  50109. }
  50110. }
  50111. void ScrollBar::mouseDrag (const MouseEvent& e)
  50112. {
  50113. if (isDraggingThumb)
  50114. {
  50115. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  50116. setCurrentRangeStart (dragStartRange
  50117. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50118. / (thumbAreaSize - thumbSize));
  50119. }
  50120. else
  50121. {
  50122. lastMousePos = (vertical) ? e.y : e.x;
  50123. }
  50124. }
  50125. void ScrollBar::mouseUp (const MouseEvent&)
  50126. {
  50127. isDraggingThumb = false;
  50128. stopTimer();
  50129. repaint();
  50130. }
  50131. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50132. float wheelIncrementX,
  50133. float wheelIncrementY)
  50134. {
  50135. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50136. if (increment < 0)
  50137. increment = jmin (increment * 10.0f, -1.0f);
  50138. else if (increment > 0)
  50139. increment = jmax (increment * 10.0f, 1.0f);
  50140. setCurrentRange (visibleRange - singleStepSize * increment);
  50141. }
  50142. void ScrollBar::timerCallback()
  50143. {
  50144. if (isMouseButtonDown())
  50145. {
  50146. startTimer (40);
  50147. if (lastMousePos < thumbStart)
  50148. setCurrentRange (visibleRange - visibleRange.getLength());
  50149. else if (lastMousePos > thumbStart + thumbSize)
  50150. setCurrentRangeStart (visibleRange.getEnd());
  50151. }
  50152. else
  50153. {
  50154. stopTimer();
  50155. }
  50156. }
  50157. bool ScrollBar::keyPressed (const KeyPress& key)
  50158. {
  50159. if (! isVisible())
  50160. return false;
  50161. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50162. moveScrollbarInSteps (-1);
  50163. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50164. moveScrollbarInSteps (1);
  50165. else if (key.isKeyCode (KeyPress::pageUpKey))
  50166. moveScrollbarInPages (-1);
  50167. else if (key.isKeyCode (KeyPress::pageDownKey))
  50168. moveScrollbarInPages (1);
  50169. else if (key.isKeyCode (KeyPress::homeKey))
  50170. scrollToTop();
  50171. else if (key.isKeyCode (KeyPress::endKey))
  50172. scrollToBottom();
  50173. else
  50174. return false;
  50175. return true;
  50176. }
  50177. END_JUCE_NAMESPACE
  50178. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50179. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50180. BEGIN_JUCE_NAMESPACE
  50181. StretchableLayoutManager::StretchableLayoutManager()
  50182. : totalSize (0)
  50183. {
  50184. }
  50185. StretchableLayoutManager::~StretchableLayoutManager()
  50186. {
  50187. }
  50188. void StretchableLayoutManager::clearAllItems()
  50189. {
  50190. items.clear();
  50191. totalSize = 0;
  50192. }
  50193. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50194. const double minimumSize,
  50195. const double maximumSize,
  50196. const double preferredSize)
  50197. {
  50198. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  50199. if (layout == 0)
  50200. {
  50201. layout = new ItemLayoutProperties();
  50202. layout->itemIndex = itemIndex;
  50203. int i;
  50204. for (i = 0; i < items.size(); ++i)
  50205. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50206. break;
  50207. items.insert (i, layout);
  50208. }
  50209. layout->minSize = minimumSize;
  50210. layout->maxSize = maximumSize;
  50211. layout->preferredSize = preferredSize;
  50212. layout->currentSize = 0;
  50213. }
  50214. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50215. double& minimumSize,
  50216. double& maximumSize,
  50217. double& preferredSize) const
  50218. {
  50219. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50220. if (layout != 0)
  50221. {
  50222. minimumSize = layout->minSize;
  50223. maximumSize = layout->maxSize;
  50224. preferredSize = layout->preferredSize;
  50225. return true;
  50226. }
  50227. return false;
  50228. }
  50229. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50230. {
  50231. totalSize = newTotalSize;
  50232. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50233. }
  50234. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50235. {
  50236. int pos = 0;
  50237. for (int i = 0; i < itemIndex; ++i)
  50238. {
  50239. const ItemLayoutProperties* const layout = getInfoFor (i);
  50240. if (layout != 0)
  50241. pos += layout->currentSize;
  50242. }
  50243. return pos;
  50244. }
  50245. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50246. {
  50247. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50248. if (layout != 0)
  50249. return layout->currentSize;
  50250. return 0;
  50251. }
  50252. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50253. {
  50254. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50255. if (layout != 0)
  50256. return -layout->currentSize / (double) totalSize;
  50257. return 0;
  50258. }
  50259. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50260. int newPosition)
  50261. {
  50262. for (int i = items.size(); --i >= 0;)
  50263. {
  50264. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50265. if (layout->itemIndex == itemIndex)
  50266. {
  50267. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50268. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50269. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50270. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50271. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50272. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50273. endPos += layout->currentSize;
  50274. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50275. updatePrefSizesToMatchCurrentPositions();
  50276. break;
  50277. }
  50278. }
  50279. }
  50280. void StretchableLayoutManager::layOutComponents (Component** const components,
  50281. int numComponents,
  50282. int x, int y, int w, int h,
  50283. const bool vertically,
  50284. const bool resizeOtherDimension)
  50285. {
  50286. setTotalSize (vertically ? h : w);
  50287. int pos = vertically ? y : x;
  50288. for (int i = 0; i < numComponents; ++i)
  50289. {
  50290. const ItemLayoutProperties* const layout = getInfoFor (i);
  50291. if (layout != 0)
  50292. {
  50293. Component* const c = components[i];
  50294. if (c != 0)
  50295. {
  50296. if (i == numComponents - 1)
  50297. {
  50298. // if it's the last item, crop it to exactly fit the available space..
  50299. if (resizeOtherDimension)
  50300. {
  50301. if (vertically)
  50302. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  50303. else
  50304. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  50305. }
  50306. else
  50307. {
  50308. if (vertically)
  50309. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  50310. else
  50311. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  50312. }
  50313. }
  50314. else
  50315. {
  50316. if (resizeOtherDimension)
  50317. {
  50318. if (vertically)
  50319. c->setBounds (x, pos, w, layout->currentSize);
  50320. else
  50321. c->setBounds (pos, y, layout->currentSize, h);
  50322. }
  50323. else
  50324. {
  50325. if (vertically)
  50326. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  50327. else
  50328. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  50329. }
  50330. }
  50331. }
  50332. pos += layout->currentSize;
  50333. }
  50334. }
  50335. }
  50336. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  50337. {
  50338. for (int i = items.size(); --i >= 0;)
  50339. if (items.getUnchecked(i)->itemIndex == itemIndex)
  50340. return items.getUnchecked(i);
  50341. return 0;
  50342. }
  50343. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  50344. const int endIndex,
  50345. const int availableSpace,
  50346. int startPos)
  50347. {
  50348. // calculate the total sizes
  50349. int i;
  50350. double totalIdealSize = 0.0;
  50351. int totalMinimums = 0;
  50352. for (i = startIndex; i < endIndex; ++i)
  50353. {
  50354. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50355. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  50356. totalMinimums += layout->currentSize;
  50357. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  50358. }
  50359. if (totalIdealSize <= 0)
  50360. totalIdealSize = 1.0;
  50361. // now calc the best sizes..
  50362. int extraSpace = availableSpace - totalMinimums;
  50363. while (extraSpace > 0)
  50364. {
  50365. int numWantingMoreSpace = 0;
  50366. int numHavingTakenExtraSpace = 0;
  50367. // first figure out how many comps want a slice of the extra space..
  50368. for (i = startIndex; i < endIndex; ++i)
  50369. {
  50370. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50371. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  50372. const int bestSize = jlimit (layout->currentSize,
  50373. jmax (layout->currentSize,
  50374. sizeToRealSize (layout->maxSize, totalSize)),
  50375. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50376. if (bestSize > layout->currentSize)
  50377. ++numWantingMoreSpace;
  50378. }
  50379. // ..share out the extra space..
  50380. for (i = startIndex; i < endIndex; ++i)
  50381. {
  50382. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50383. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  50384. int bestSize = jlimit (layout->currentSize,
  50385. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  50386. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50387. const int extraWanted = bestSize - layout->currentSize;
  50388. if (extraWanted > 0)
  50389. {
  50390. const int extraAllowed = jmin (extraWanted,
  50391. extraSpace / jmax (1, numWantingMoreSpace));
  50392. if (extraAllowed > 0)
  50393. {
  50394. ++numHavingTakenExtraSpace;
  50395. --numWantingMoreSpace;
  50396. layout->currentSize += extraAllowed;
  50397. extraSpace -= extraAllowed;
  50398. }
  50399. }
  50400. }
  50401. if (numHavingTakenExtraSpace <= 0)
  50402. break;
  50403. }
  50404. // ..and calculate the end position
  50405. for (i = startIndex; i < endIndex; ++i)
  50406. {
  50407. ItemLayoutProperties* const layout = items.getUnchecked(i);
  50408. startPos += layout->currentSize;
  50409. }
  50410. return startPos;
  50411. }
  50412. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  50413. const int endIndex) const
  50414. {
  50415. int totalMinimums = 0;
  50416. for (int i = startIndex; i < endIndex; ++i)
  50417. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  50418. return totalMinimums;
  50419. }
  50420. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  50421. {
  50422. int totalMaximums = 0;
  50423. for (int i = startIndex; i < endIndex; ++i)
  50424. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  50425. return totalMaximums;
  50426. }
  50427. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  50428. {
  50429. for (int i = 0; i < items.size(); ++i)
  50430. {
  50431. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50432. layout->preferredSize
  50433. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  50434. : getItemCurrentAbsoluteSize (i);
  50435. }
  50436. }
  50437. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  50438. {
  50439. if (size < 0)
  50440. size *= -totalSpace;
  50441. return roundToInt (size);
  50442. }
  50443. END_JUCE_NAMESPACE
  50444. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  50445. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50446. BEGIN_JUCE_NAMESPACE
  50447. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  50448. const int itemIndex_,
  50449. const bool isVertical_)
  50450. : layout (layout_),
  50451. itemIndex (itemIndex_),
  50452. isVertical (isVertical_)
  50453. {
  50454. setRepaintsOnMouseActivity (true);
  50455. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  50456. : MouseCursor::UpDownResizeCursor));
  50457. }
  50458. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  50459. {
  50460. }
  50461. void StretchableLayoutResizerBar::paint (Graphics& g)
  50462. {
  50463. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  50464. getWidth(), getHeight(),
  50465. isVertical,
  50466. isMouseOver(),
  50467. isMouseButtonDown());
  50468. }
  50469. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  50470. {
  50471. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  50472. }
  50473. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  50474. {
  50475. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  50476. : e.getDistanceFromDragStartY());
  50477. layout->setItemPosition (itemIndex, desiredPos);
  50478. hasBeenMoved();
  50479. }
  50480. void StretchableLayoutResizerBar::hasBeenMoved()
  50481. {
  50482. if (getParentComponent() != 0)
  50483. getParentComponent()->resized();
  50484. }
  50485. END_JUCE_NAMESPACE
  50486. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50487. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  50488. BEGIN_JUCE_NAMESPACE
  50489. StretchableObjectResizer::StretchableObjectResizer()
  50490. {
  50491. }
  50492. StretchableObjectResizer::~StretchableObjectResizer()
  50493. {
  50494. }
  50495. void StretchableObjectResizer::addItem (const double size,
  50496. const double minSize, const double maxSize,
  50497. const int order)
  50498. {
  50499. // the order must be >= 0 but less than the maximum integer value.
  50500. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  50501. Item* const item = new Item();
  50502. item->size = size;
  50503. item->minSize = minSize;
  50504. item->maxSize = maxSize;
  50505. item->order = order;
  50506. items.add (item);
  50507. }
  50508. double StretchableObjectResizer::getItemSize (const int index) const throw()
  50509. {
  50510. const Item* const it = items [index];
  50511. return it != 0 ? it->size : 0;
  50512. }
  50513. void StretchableObjectResizer::resizeToFit (const double targetSize)
  50514. {
  50515. int order = 0;
  50516. for (;;)
  50517. {
  50518. double currentSize = 0;
  50519. double minSize = 0;
  50520. double maxSize = 0;
  50521. int nextHighestOrder = std::numeric_limits<int>::max();
  50522. for (int i = 0; i < items.size(); ++i)
  50523. {
  50524. const Item* const it = items.getUnchecked(i);
  50525. currentSize += it->size;
  50526. if (it->order <= order)
  50527. {
  50528. minSize += it->minSize;
  50529. maxSize += it->maxSize;
  50530. }
  50531. else
  50532. {
  50533. minSize += it->size;
  50534. maxSize += it->size;
  50535. nextHighestOrder = jmin (nextHighestOrder, it->order);
  50536. }
  50537. }
  50538. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  50539. if (thisIterationTarget >= currentSize)
  50540. {
  50541. const double availableExtraSpace = maxSize - currentSize;
  50542. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  50543. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  50544. for (int i = 0; i < items.size(); ++i)
  50545. {
  50546. Item* const it = items.getUnchecked(i);
  50547. if (it->order <= order)
  50548. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  50549. }
  50550. }
  50551. else
  50552. {
  50553. const double amountOfSlack = currentSize - minSize;
  50554. const double targetAmountOfSlack = thisIterationTarget - minSize;
  50555. const double scale = targetAmountOfSlack / amountOfSlack;
  50556. for (int i = 0; i < items.size(); ++i)
  50557. {
  50558. Item* const it = items.getUnchecked(i);
  50559. if (it->order <= order)
  50560. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  50561. }
  50562. }
  50563. if (nextHighestOrder < std::numeric_limits<int>::max())
  50564. order = nextHighestOrder;
  50565. else
  50566. break;
  50567. }
  50568. }
  50569. END_JUCE_NAMESPACE
  50570. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  50571. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  50572. BEGIN_JUCE_NAMESPACE
  50573. TabBarButton::TabBarButton (const String& name,
  50574. TabbedButtonBar* const owner_,
  50575. const int index)
  50576. : Button (name),
  50577. owner (owner_),
  50578. tabIndex (index),
  50579. overlapPixels (0)
  50580. {
  50581. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  50582. setComponentEffect (&shadow);
  50583. setWantsKeyboardFocus (false);
  50584. }
  50585. TabBarButton::~TabBarButton()
  50586. {
  50587. }
  50588. void TabBarButton::paintButton (Graphics& g,
  50589. bool isMouseOverButton,
  50590. bool isButtonDown)
  50591. {
  50592. int x, y, w, h;
  50593. getActiveArea (x, y, w, h);
  50594. g.setOrigin (x, y);
  50595. getLookAndFeel()
  50596. .drawTabButton (g, w, h,
  50597. owner->getTabBackgroundColour (tabIndex),
  50598. tabIndex, getButtonText(), *this,
  50599. owner->getOrientation(),
  50600. isMouseOverButton, isButtonDown,
  50601. getToggleState());
  50602. }
  50603. void TabBarButton::clicked (const ModifierKeys& mods)
  50604. {
  50605. if (mods.isPopupMenu())
  50606. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  50607. else
  50608. owner->setCurrentTabIndex (tabIndex);
  50609. }
  50610. bool TabBarButton::hitTest (int mx, int my)
  50611. {
  50612. int x, y, w, h;
  50613. getActiveArea (x, y, w, h);
  50614. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  50615. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  50616. {
  50617. if (((unsigned int) mx) < (unsigned int) getWidth()
  50618. && my >= y + overlapPixels
  50619. && my < y + h - overlapPixels)
  50620. return true;
  50621. }
  50622. else
  50623. {
  50624. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  50625. && ((unsigned int) my) < (unsigned int) getHeight())
  50626. return true;
  50627. }
  50628. Path p;
  50629. getLookAndFeel()
  50630. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  50631. owner->getOrientation(),
  50632. false, false, getToggleState());
  50633. return p.contains ((float) (mx - x),
  50634. (float) (my - y));
  50635. }
  50636. int TabBarButton::getBestTabLength (const int depth)
  50637. {
  50638. return jlimit (depth * 2,
  50639. depth * 7,
  50640. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  50641. }
  50642. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  50643. {
  50644. x = 0;
  50645. y = 0;
  50646. int r = getWidth();
  50647. int b = getHeight();
  50648. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  50649. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  50650. r -= spaceAroundImage;
  50651. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  50652. x += spaceAroundImage;
  50653. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  50654. y += spaceAroundImage;
  50655. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  50656. b -= spaceAroundImage;
  50657. w = r - x;
  50658. h = b - y;
  50659. }
  50660. class TabAreaBehindFrontButtonComponent : public Component
  50661. {
  50662. public:
  50663. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  50664. : owner (owner_)
  50665. {
  50666. setInterceptsMouseClicks (false, false);
  50667. }
  50668. ~TabAreaBehindFrontButtonComponent()
  50669. {
  50670. }
  50671. void paint (Graphics& g)
  50672. {
  50673. getLookAndFeel()
  50674. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  50675. *owner, owner->getOrientation());
  50676. }
  50677. void enablementChanged()
  50678. {
  50679. repaint();
  50680. }
  50681. private:
  50682. TabbedButtonBar* const owner;
  50683. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  50684. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  50685. };
  50686. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  50687. : orientation (orientation_),
  50688. currentTabIndex (-1)
  50689. {
  50690. setInterceptsMouseClicks (false, true);
  50691. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  50692. setFocusContainer (true);
  50693. }
  50694. TabbedButtonBar::~TabbedButtonBar()
  50695. {
  50696. extraTabsButton = 0;
  50697. deleteAllChildren();
  50698. }
  50699. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  50700. {
  50701. orientation = newOrientation;
  50702. for (int i = getNumChildComponents(); --i >= 0;)
  50703. getChildComponent (i)->resized();
  50704. resized();
  50705. }
  50706. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  50707. {
  50708. return new TabBarButton (name, this, index);
  50709. }
  50710. void TabbedButtonBar::clearTabs()
  50711. {
  50712. tabs.clear();
  50713. tabColours.clear();
  50714. currentTabIndex = -1;
  50715. extraTabsButton = 0;
  50716. removeChildComponent (behindFrontTab);
  50717. deleteAllChildren();
  50718. addChildComponent (behindFrontTab);
  50719. setCurrentTabIndex (-1);
  50720. }
  50721. void TabbedButtonBar::addTab (const String& tabName,
  50722. const Colour& tabBackgroundColour,
  50723. int insertIndex)
  50724. {
  50725. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  50726. if (tabName.isNotEmpty())
  50727. {
  50728. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  50729. insertIndex = tabs.size();
  50730. for (int i = tabs.size(); --i >= insertIndex;)
  50731. {
  50732. TabBarButton* const tb = getTabButton (i);
  50733. if (tb != 0)
  50734. tb->tabIndex++;
  50735. }
  50736. tabs.insert (insertIndex, tabName);
  50737. tabColours.insert (insertIndex, tabBackgroundColour);
  50738. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  50739. jassert (tb != 0); // your createTabButton() mustn't return zero!
  50740. addAndMakeVisible (tb, insertIndex);
  50741. resized();
  50742. if (currentTabIndex < 0)
  50743. setCurrentTabIndex (0);
  50744. }
  50745. }
  50746. void TabbedButtonBar::setTabName (const int tabIndex,
  50747. const String& newName)
  50748. {
  50749. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  50750. && tabs[tabIndex] != newName)
  50751. {
  50752. tabs.set (tabIndex, newName);
  50753. TabBarButton* const tb = getTabButton (tabIndex);
  50754. if (tb != 0)
  50755. tb->setButtonText (newName);
  50756. resized();
  50757. }
  50758. }
  50759. void TabbedButtonBar::removeTab (const int tabIndex)
  50760. {
  50761. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  50762. {
  50763. const int oldTabIndex = currentTabIndex;
  50764. if (currentTabIndex == tabIndex)
  50765. currentTabIndex = -1;
  50766. tabs.remove (tabIndex);
  50767. tabColours.remove (tabIndex);
  50768. delete getTabButton (tabIndex);
  50769. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  50770. {
  50771. TabBarButton* const tb = getTabButton (i);
  50772. if (tb != 0)
  50773. tb->tabIndex--;
  50774. }
  50775. resized();
  50776. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  50777. }
  50778. }
  50779. void TabbedButtonBar::moveTab (const int currentIndex,
  50780. const int newIndex)
  50781. {
  50782. tabs.move (currentIndex, newIndex);
  50783. tabColours.move (currentIndex, newIndex);
  50784. resized();
  50785. }
  50786. int TabbedButtonBar::getNumTabs() const
  50787. {
  50788. return tabs.size();
  50789. }
  50790. const StringArray TabbedButtonBar::getTabNames() const
  50791. {
  50792. return tabs;
  50793. }
  50794. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  50795. {
  50796. if (currentTabIndex != newIndex)
  50797. {
  50798. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  50799. newIndex = -1;
  50800. currentTabIndex = newIndex;
  50801. for (int i = 0; i < getNumChildComponents(); ++i)
  50802. {
  50803. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50804. if (tb != 0)
  50805. tb->setToggleState (tb->tabIndex == newIndex, false);
  50806. }
  50807. resized();
  50808. if (sendChangeMessage_)
  50809. sendChangeMessage (this);
  50810. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  50811. }
  50812. }
  50813. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  50814. {
  50815. for (int i = getNumChildComponents(); --i >= 0;)
  50816. {
  50817. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50818. if (tb != 0 && tb->tabIndex == index)
  50819. return tb;
  50820. }
  50821. return 0;
  50822. }
  50823. void TabbedButtonBar::lookAndFeelChanged()
  50824. {
  50825. extraTabsButton = 0;
  50826. resized();
  50827. }
  50828. void TabbedButtonBar::resized()
  50829. {
  50830. const double minimumScale = 0.7;
  50831. int depth = getWidth();
  50832. int length = getHeight();
  50833. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50834. swapVariables (depth, length);
  50835. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  50836. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  50837. int i, totalLength = overlap;
  50838. int numVisibleButtons = tabs.size();
  50839. for (i = 0; i < getNumChildComponents(); ++i)
  50840. {
  50841. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50842. if (tb != 0)
  50843. {
  50844. totalLength += tb->getBestTabLength (depth) - overlap;
  50845. tb->overlapPixels = overlap / 2;
  50846. }
  50847. }
  50848. double scale = 1.0;
  50849. if (totalLength > length)
  50850. scale = jmax (minimumScale, length / (double) totalLength);
  50851. const bool isTooBig = totalLength * scale > length;
  50852. int tabsButtonPos = 0;
  50853. if (isTooBig)
  50854. {
  50855. if (extraTabsButton == 0)
  50856. {
  50857. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  50858. extraTabsButton->addButtonListener (this);
  50859. extraTabsButton->setAlwaysOnTop (true);
  50860. extraTabsButton->setTriggeredOnMouseDown (true);
  50861. }
  50862. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  50863. extraTabsButton->setSize (buttonSize, buttonSize);
  50864. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50865. {
  50866. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  50867. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  50868. }
  50869. else
  50870. {
  50871. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  50872. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  50873. }
  50874. totalLength = 0;
  50875. for (i = 0; i < tabs.size(); ++i)
  50876. {
  50877. TabBarButton* const tb = getTabButton (i);
  50878. if (tb != 0)
  50879. {
  50880. const int newLength = totalLength + tb->getBestTabLength (depth);
  50881. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  50882. {
  50883. totalLength += overlap;
  50884. break;
  50885. }
  50886. numVisibleButtons = i + 1;
  50887. totalLength = newLength - overlap;
  50888. }
  50889. }
  50890. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  50891. }
  50892. else
  50893. {
  50894. extraTabsButton = 0;
  50895. }
  50896. int pos = 0;
  50897. TabBarButton* frontTab = 0;
  50898. for (i = 0; i < tabs.size(); ++i)
  50899. {
  50900. TabBarButton* const tb = getTabButton (i);
  50901. if (tb != 0)
  50902. {
  50903. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  50904. if (i < numVisibleButtons)
  50905. {
  50906. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50907. tb->setBounds (pos, 0, bestLength, getHeight());
  50908. else
  50909. tb->setBounds (0, pos, getWidth(), bestLength);
  50910. tb->toBack();
  50911. if (tb->tabIndex == currentTabIndex)
  50912. frontTab = tb;
  50913. tb->setVisible (true);
  50914. }
  50915. else
  50916. {
  50917. tb->setVisible (false);
  50918. }
  50919. pos += bestLength - overlap;
  50920. }
  50921. }
  50922. behindFrontTab->setBounds (getLocalBounds());
  50923. if (frontTab != 0)
  50924. {
  50925. frontTab->toFront (false);
  50926. behindFrontTab->toBehind (frontTab);
  50927. }
  50928. }
  50929. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  50930. {
  50931. return tabColours [tabIndex];
  50932. }
  50933. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  50934. {
  50935. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  50936. && tabColours [tabIndex] != newColour)
  50937. {
  50938. tabColours.set (tabIndex, newColour);
  50939. repaint();
  50940. }
  50941. }
  50942. void TabbedButtonBar::buttonClicked (Button* button)
  50943. {
  50944. if (button == extraTabsButton)
  50945. {
  50946. PopupMenu m;
  50947. for (int i = 0; i < tabs.size(); ++i)
  50948. {
  50949. TabBarButton* const tb = getTabButton (i);
  50950. if (tb != 0 && ! tb->isVisible())
  50951. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  50952. }
  50953. const int res = m.showAt (extraTabsButton);
  50954. if (res != 0)
  50955. setCurrentTabIndex (res - 1);
  50956. }
  50957. }
  50958. void TabbedButtonBar::currentTabChanged (const int, const String&)
  50959. {
  50960. }
  50961. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  50962. {
  50963. }
  50964. END_JUCE_NAMESPACE
  50965. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  50966. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  50967. BEGIN_JUCE_NAMESPACE
  50968. class TabCompButtonBar : public TabbedButtonBar
  50969. {
  50970. public:
  50971. TabCompButtonBar (TabbedComponent* const owner_,
  50972. const TabbedButtonBar::Orientation orientation_)
  50973. : TabbedButtonBar (orientation_),
  50974. owner (owner_)
  50975. {
  50976. }
  50977. ~TabCompButtonBar()
  50978. {
  50979. }
  50980. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  50981. {
  50982. owner->changeCallback (newCurrentTabIndex, newTabName);
  50983. }
  50984. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  50985. {
  50986. owner->popupMenuClickOnTab (tabIndex, tabName);
  50987. }
  50988. const Colour getTabBackgroundColour (const int tabIndex)
  50989. {
  50990. return owner->tabs->getTabBackgroundColour (tabIndex);
  50991. }
  50992. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  50993. {
  50994. return owner->createTabButton (tabName, tabIndex);
  50995. }
  50996. juce_UseDebuggingNewOperator
  50997. private:
  50998. TabbedComponent* const owner;
  50999. TabCompButtonBar (const TabCompButtonBar&);
  51000. TabCompButtonBar& operator= (const TabCompButtonBar&);
  51001. };
  51002. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51003. : panelComponent (0),
  51004. tabDepth (30),
  51005. outlineThickness (1),
  51006. edgeIndent (0)
  51007. {
  51008. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  51009. }
  51010. TabbedComponent::~TabbedComponent()
  51011. {
  51012. clearTabs();
  51013. delete tabs;
  51014. }
  51015. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51016. {
  51017. tabs->setOrientation (orientation);
  51018. resized();
  51019. }
  51020. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51021. {
  51022. return tabs->getOrientation();
  51023. }
  51024. void TabbedComponent::setTabBarDepth (const int newDepth)
  51025. {
  51026. if (tabDepth != newDepth)
  51027. {
  51028. tabDepth = newDepth;
  51029. resized();
  51030. }
  51031. }
  51032. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  51033. {
  51034. return new TabBarButton (tabName, tabs, tabIndex);
  51035. }
  51036. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  51037. void TabbedComponent::clearTabs()
  51038. {
  51039. if (panelComponent != 0)
  51040. {
  51041. panelComponent->setVisible (false);
  51042. removeChildComponent (panelComponent);
  51043. panelComponent = 0;
  51044. }
  51045. tabs->clearTabs();
  51046. for (int i = contentComponents.size(); --i >= 0;)
  51047. {
  51048. Component* const c = contentComponents.getUnchecked(i);
  51049. // be careful not to delete these components until they've been removed from the tab component
  51050. jassert (c == 0 || c->isValidComponent());
  51051. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51052. delete c;
  51053. }
  51054. contentComponents.clear();
  51055. }
  51056. void TabbedComponent::addTab (const String& tabName,
  51057. const Colour& tabBackgroundColour,
  51058. Component* const contentComponent,
  51059. const bool deleteComponentWhenNotNeeded,
  51060. const int insertIndex)
  51061. {
  51062. contentComponents.insert (insertIndex, contentComponent);
  51063. if (contentComponent != 0)
  51064. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  51065. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51066. }
  51067. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51068. {
  51069. tabs->setTabName (tabIndex, newName);
  51070. }
  51071. void TabbedComponent::removeTab (const int tabIndex)
  51072. {
  51073. Component* const c = contentComponents [tabIndex];
  51074. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51075. {
  51076. if (c == panelComponent)
  51077. panelComponent = 0;
  51078. delete c;
  51079. }
  51080. contentComponents.remove (tabIndex);
  51081. tabs->removeTab (tabIndex);
  51082. }
  51083. int TabbedComponent::getNumTabs() const
  51084. {
  51085. return tabs->getNumTabs();
  51086. }
  51087. const StringArray TabbedComponent::getTabNames() const
  51088. {
  51089. return tabs->getTabNames();
  51090. }
  51091. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51092. {
  51093. return contentComponents [tabIndex];
  51094. }
  51095. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51096. {
  51097. return tabs->getTabBackgroundColour (tabIndex);
  51098. }
  51099. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51100. {
  51101. tabs->setTabBackgroundColour (tabIndex, newColour);
  51102. if (getCurrentTabIndex() == tabIndex)
  51103. repaint();
  51104. }
  51105. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51106. {
  51107. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51108. }
  51109. int TabbedComponent::getCurrentTabIndex() const
  51110. {
  51111. return tabs->getCurrentTabIndex();
  51112. }
  51113. const String& TabbedComponent::getCurrentTabName() const
  51114. {
  51115. return tabs->getCurrentTabName();
  51116. }
  51117. void TabbedComponent::setOutline (int thickness)
  51118. {
  51119. outlineThickness = thickness;
  51120. repaint();
  51121. }
  51122. void TabbedComponent::setIndent (const int indentThickness)
  51123. {
  51124. edgeIndent = indentThickness;
  51125. }
  51126. void TabbedComponent::paint (Graphics& g)
  51127. {
  51128. g.fillAll (findColour (backgroundColourId));
  51129. const TabbedButtonBar::Orientation o = getOrientation();
  51130. int x = 0;
  51131. int y = 0;
  51132. int r = getWidth();
  51133. int b = getHeight();
  51134. if (o == TabbedButtonBar::TabsAtTop)
  51135. y += tabDepth;
  51136. else if (o == TabbedButtonBar::TabsAtBottom)
  51137. b -= tabDepth;
  51138. else if (o == TabbedButtonBar::TabsAtLeft)
  51139. x += tabDepth;
  51140. else if (o == TabbedButtonBar::TabsAtRight)
  51141. r -= tabDepth;
  51142. g.reduceClipRegion (x, y, r - x, b - y);
  51143. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51144. if (outlineThickness > 0)
  51145. {
  51146. if (o == TabbedButtonBar::TabsAtTop)
  51147. --y;
  51148. else if (o == TabbedButtonBar::TabsAtBottom)
  51149. ++b;
  51150. else if (o == TabbedButtonBar::TabsAtLeft)
  51151. --x;
  51152. else if (o == TabbedButtonBar::TabsAtRight)
  51153. ++r;
  51154. g.setColour (findColour (outlineColourId));
  51155. g.drawRect (x, y, r - x, b - y, outlineThickness);
  51156. }
  51157. }
  51158. void TabbedComponent::resized()
  51159. {
  51160. const TabbedButtonBar::Orientation o = getOrientation();
  51161. const int indent = edgeIndent + outlineThickness;
  51162. BorderSize indents (indent);
  51163. if (o == TabbedButtonBar::TabsAtTop)
  51164. {
  51165. tabs->setBounds (0, 0, getWidth(), tabDepth);
  51166. indents.setTop (tabDepth + edgeIndent);
  51167. }
  51168. else if (o == TabbedButtonBar::TabsAtBottom)
  51169. {
  51170. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  51171. indents.setBottom (tabDepth + edgeIndent);
  51172. }
  51173. else if (o == TabbedButtonBar::TabsAtLeft)
  51174. {
  51175. tabs->setBounds (0, 0, tabDepth, getHeight());
  51176. indents.setLeft (tabDepth + edgeIndent);
  51177. }
  51178. else if (o == TabbedButtonBar::TabsAtRight)
  51179. {
  51180. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  51181. indents.setRight (tabDepth + edgeIndent);
  51182. }
  51183. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  51184. for (int i = contentComponents.size(); --i >= 0;)
  51185. if (contentComponents.getUnchecked (i) != 0)
  51186. contentComponents.getUnchecked (i)->setBounds (bounds);
  51187. }
  51188. void TabbedComponent::lookAndFeelChanged()
  51189. {
  51190. for (int i = contentComponents.size(); --i >= 0;)
  51191. if (contentComponents.getUnchecked (i) != 0)
  51192. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  51193. }
  51194. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  51195. const String& newTabName)
  51196. {
  51197. if (panelComponent != 0)
  51198. {
  51199. panelComponent->setVisible (false);
  51200. removeChildComponent (panelComponent);
  51201. panelComponent = 0;
  51202. }
  51203. if (getCurrentTabIndex() >= 0)
  51204. {
  51205. panelComponent = contentComponents [getCurrentTabIndex()];
  51206. if (panelComponent != 0)
  51207. {
  51208. // do these ops as two stages instead of addAndMakeVisible() so that the
  51209. // component has always got a parent when it gets the visibilityChanged() callback
  51210. addChildComponent (panelComponent);
  51211. panelComponent->setVisible (true);
  51212. panelComponent->toFront (true);
  51213. }
  51214. repaint();
  51215. }
  51216. resized();
  51217. currentTabChanged (newCurrentTabIndex, newTabName);
  51218. }
  51219. void TabbedComponent::currentTabChanged (const int, const String&)
  51220. {
  51221. }
  51222. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  51223. {
  51224. }
  51225. END_JUCE_NAMESPACE
  51226. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51227. /*** Start of inlined file: juce_Viewport.cpp ***/
  51228. BEGIN_JUCE_NAMESPACE
  51229. Viewport::Viewport (const String& componentName)
  51230. : Component (componentName),
  51231. scrollBarThickness (0),
  51232. singleStepX (16),
  51233. singleStepY (16),
  51234. showHScrollbar (true),
  51235. showVScrollbar (true),
  51236. verticalScrollBar (true),
  51237. horizontalScrollBar (false)
  51238. {
  51239. // content holder is used to clip the contents so they don't overlap the scrollbars
  51240. addAndMakeVisible (&contentHolder);
  51241. contentHolder.setInterceptsMouseClicks (false, true);
  51242. addChildComponent (&verticalScrollBar);
  51243. addChildComponent (&horizontalScrollBar);
  51244. verticalScrollBar.addListener (this);
  51245. horizontalScrollBar.addListener (this);
  51246. setInterceptsMouseClicks (false, true);
  51247. setWantsKeyboardFocus (true);
  51248. }
  51249. Viewport::~Viewport()
  51250. {
  51251. contentHolder.deleteAllChildren();
  51252. }
  51253. void Viewport::visibleAreaChanged (int, int, int, int)
  51254. {
  51255. }
  51256. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51257. {
  51258. if (contentComp.getComponent() != newViewedComponent)
  51259. {
  51260. {
  51261. ScopedPointer<Component> oldCompDeleter (contentComp);
  51262. contentComp = 0;
  51263. }
  51264. contentComp = newViewedComponent;
  51265. if (contentComp != 0)
  51266. {
  51267. contentComp->setTopLeftPosition (0, 0);
  51268. contentHolder.addAndMakeVisible (contentComp);
  51269. contentComp->addComponentListener (this);
  51270. }
  51271. updateVisibleArea();
  51272. }
  51273. }
  51274. int Viewport::getMaximumVisibleWidth() const
  51275. {
  51276. return contentHolder.getWidth();
  51277. }
  51278. int Viewport::getMaximumVisibleHeight() const
  51279. {
  51280. return contentHolder.getHeight();
  51281. }
  51282. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51283. {
  51284. if (contentComp != 0)
  51285. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  51286. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  51287. }
  51288. void Viewport::setViewPosition (const Point<int>& newPosition)
  51289. {
  51290. setViewPosition (newPosition.getX(), newPosition.getY());
  51291. }
  51292. void Viewport::setViewPositionProportionately (const double x, const double y)
  51293. {
  51294. if (contentComp != 0)
  51295. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51296. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51297. }
  51298. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  51299. {
  51300. if (contentComp != 0)
  51301. {
  51302. int dx = 0, dy = 0;
  51303. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  51304. {
  51305. if (mouseX < activeBorderThickness)
  51306. dx = activeBorderThickness - mouseX;
  51307. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  51308. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  51309. if (dx < 0)
  51310. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  51311. else
  51312. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51313. }
  51314. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  51315. {
  51316. if (mouseY < activeBorderThickness)
  51317. dy = activeBorderThickness - mouseY;
  51318. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  51319. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  51320. if (dy < 0)
  51321. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  51322. else
  51323. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51324. }
  51325. if (dx != 0 || dy != 0)
  51326. {
  51327. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  51328. contentComp->getY() + dy);
  51329. return true;
  51330. }
  51331. }
  51332. return false;
  51333. }
  51334. void Viewport::componentMovedOrResized (Component&, bool, bool)
  51335. {
  51336. updateVisibleArea();
  51337. }
  51338. void Viewport::resized()
  51339. {
  51340. updateVisibleArea();
  51341. }
  51342. void Viewport::updateVisibleArea()
  51343. {
  51344. const int scrollbarWidth = getScrollBarThickness();
  51345. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  51346. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  51347. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  51348. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  51349. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  51350. Rectangle<int> contentArea (getLocalBounds());
  51351. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  51352. {
  51353. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  51354. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  51355. if (vBarVisible)
  51356. contentArea.setWidth (getWidth() - scrollbarWidth);
  51357. if (hBarVisible)
  51358. contentArea.setHeight (getHeight() - scrollbarWidth);
  51359. if (! contentArea.contains (contentComp->getBounds()))
  51360. {
  51361. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  51362. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  51363. }
  51364. }
  51365. if (vBarVisible)
  51366. contentArea.setWidth (getWidth() - scrollbarWidth);
  51367. if (hBarVisible)
  51368. contentArea.setHeight (getHeight() - scrollbarWidth);
  51369. contentHolder.setBounds (contentArea);
  51370. Rectangle<int> contentBounds;
  51371. if (contentComp != 0)
  51372. contentBounds = contentComp->getBounds();
  51373. const Point<int> visibleOrigin (-contentBounds.getPosition());
  51374. if (hBarVisible)
  51375. {
  51376. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  51377. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  51378. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  51379. horizontalScrollBar.setSingleStepSize (singleStepX);
  51380. horizontalScrollBar.cancelPendingUpdate();
  51381. }
  51382. if (vBarVisible)
  51383. {
  51384. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  51385. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  51386. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  51387. verticalScrollBar.setSingleStepSize (singleStepY);
  51388. verticalScrollBar.cancelPendingUpdate();
  51389. }
  51390. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  51391. horizontalScrollBar.setVisible (hBarVisible);
  51392. verticalScrollBar.setVisible (vBarVisible);
  51393. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  51394. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  51395. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  51396. if (lastVisibleArea != visibleArea)
  51397. {
  51398. lastVisibleArea = visibleArea;
  51399. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  51400. }
  51401. horizontalScrollBar.handleUpdateNowIfNeeded();
  51402. verticalScrollBar.handleUpdateNowIfNeeded();
  51403. }
  51404. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  51405. {
  51406. if (singleStepX != stepX || singleStepY != stepY)
  51407. {
  51408. singleStepX = stepX;
  51409. singleStepY = stepY;
  51410. updateVisibleArea();
  51411. }
  51412. }
  51413. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  51414. const bool showHorizontalScrollbarIfNeeded)
  51415. {
  51416. if (showVScrollbar != showVerticalScrollbarIfNeeded
  51417. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  51418. {
  51419. showVScrollbar = showVerticalScrollbarIfNeeded;
  51420. showHScrollbar = showHorizontalScrollbarIfNeeded;
  51421. updateVisibleArea();
  51422. }
  51423. }
  51424. void Viewport::setScrollBarThickness (const int thickness)
  51425. {
  51426. if (scrollBarThickness != thickness)
  51427. {
  51428. scrollBarThickness = thickness;
  51429. updateVisibleArea();
  51430. }
  51431. }
  51432. int Viewport::getScrollBarThickness() const
  51433. {
  51434. return scrollBarThickness > 0 ? scrollBarThickness
  51435. : getLookAndFeel().getDefaultScrollbarWidth();
  51436. }
  51437. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  51438. {
  51439. verticalScrollBar.setButtonVisibility (buttonsVisible);
  51440. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  51441. }
  51442. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  51443. {
  51444. const int newRangeStartInt = roundToInt (newRangeStart);
  51445. if (scrollBarThatHasMoved == &horizontalScrollBar)
  51446. {
  51447. setViewPosition (newRangeStartInt, getViewPositionY());
  51448. }
  51449. else if (scrollBarThatHasMoved == &verticalScrollBar)
  51450. {
  51451. setViewPosition (getViewPositionX(), newRangeStartInt);
  51452. }
  51453. }
  51454. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  51455. {
  51456. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  51457. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  51458. }
  51459. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  51460. {
  51461. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  51462. {
  51463. const bool hasVertBar = verticalScrollBar.isVisible();
  51464. const bool hasHorzBar = horizontalScrollBar.isVisible();
  51465. if (hasHorzBar || hasVertBar)
  51466. {
  51467. if (wheelIncrementX != 0)
  51468. {
  51469. wheelIncrementX *= 14.0f * singleStepX;
  51470. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  51471. : jmax (wheelIncrementX, 1.0f);
  51472. }
  51473. if (wheelIncrementY != 0)
  51474. {
  51475. wheelIncrementY *= 14.0f * singleStepY;
  51476. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  51477. : jmax (wheelIncrementY, 1.0f);
  51478. }
  51479. Point<int> pos (getViewPosition());
  51480. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  51481. {
  51482. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  51483. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  51484. }
  51485. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  51486. {
  51487. if (wheelIncrementX == 0 && ! hasVertBar)
  51488. wheelIncrementX = wheelIncrementY;
  51489. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  51490. }
  51491. else if (hasVertBar && wheelIncrementY != 0)
  51492. {
  51493. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  51494. }
  51495. if (pos != getViewPosition())
  51496. {
  51497. setViewPosition (pos);
  51498. return true;
  51499. }
  51500. }
  51501. }
  51502. return false;
  51503. }
  51504. bool Viewport::keyPressed (const KeyPress& key)
  51505. {
  51506. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  51507. || key.isKeyCode (KeyPress::downKey)
  51508. || key.isKeyCode (KeyPress::pageUpKey)
  51509. || key.isKeyCode (KeyPress::pageDownKey)
  51510. || key.isKeyCode (KeyPress::homeKey)
  51511. || key.isKeyCode (KeyPress::endKey);
  51512. if (verticalScrollBar.isVisible() && isUpDownKey)
  51513. return verticalScrollBar.keyPressed (key);
  51514. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  51515. || key.isKeyCode (KeyPress::rightKey);
  51516. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  51517. return horizontalScrollBar.keyPressed (key);
  51518. return false;
  51519. }
  51520. END_JUCE_NAMESPACE
  51521. /*** End of inlined file: juce_Viewport.cpp ***/
  51522. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  51523. BEGIN_JUCE_NAMESPACE
  51524. static const Colour createBaseColour (const Colour& buttonColour,
  51525. const bool hasKeyboardFocus,
  51526. const bool isMouseOverButton,
  51527. const bool isButtonDown) throw()
  51528. {
  51529. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  51530. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  51531. if (isButtonDown)
  51532. return baseColour.contrasting (0.2f);
  51533. else if (isMouseOverButton)
  51534. return baseColour.contrasting (0.1f);
  51535. return baseColour;
  51536. }
  51537. LookAndFeel::LookAndFeel()
  51538. {
  51539. /* if this fails it means you're trying to create a LookAndFeel object before
  51540. the static Colours have been initialised. That ain't gonna work. It probably
  51541. means that you're using a static LookAndFeel object and that your compiler has
  51542. decided to intialise it before the Colours class.
  51543. */
  51544. jassert (Colours::white == Colour (0xffffffff));
  51545. // set up the standard set of colours..
  51546. const int textButtonColour = 0xffbbbbff;
  51547. const int textHighlightColour = 0x401111ee;
  51548. const int standardOutlineColour = 0xb2808080;
  51549. static const int standardColours[] =
  51550. {
  51551. TextButton::buttonColourId, textButtonColour,
  51552. TextButton::buttonOnColourId, 0xff4444ff,
  51553. TextButton::textColourOnId, 0xff000000,
  51554. TextButton::textColourOffId, 0xff000000,
  51555. ComboBox::buttonColourId, 0xffbbbbff,
  51556. ComboBox::outlineColourId, standardOutlineColour,
  51557. ToggleButton::textColourId, 0xff000000,
  51558. TextEditor::backgroundColourId, 0xffffffff,
  51559. TextEditor::textColourId, 0xff000000,
  51560. TextEditor::highlightColourId, textHighlightColour,
  51561. TextEditor::highlightedTextColourId, 0xff000000,
  51562. TextEditor::caretColourId, 0xff000000,
  51563. TextEditor::outlineColourId, 0x00000000,
  51564. TextEditor::focusedOutlineColourId, textButtonColour,
  51565. TextEditor::shadowColourId, 0x38000000,
  51566. Label::backgroundColourId, 0x00000000,
  51567. Label::textColourId, 0xff000000,
  51568. Label::outlineColourId, 0x00000000,
  51569. ScrollBar::backgroundColourId, 0x00000000,
  51570. ScrollBar::thumbColourId, 0xffffffff,
  51571. ScrollBar::trackColourId, 0xffffffff,
  51572. TreeView::linesColourId, 0x4c000000,
  51573. TreeView::backgroundColourId, 0x00000000,
  51574. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  51575. PopupMenu::backgroundColourId, 0xffffffff,
  51576. PopupMenu::textColourId, 0xff000000,
  51577. PopupMenu::headerTextColourId, 0xff000000,
  51578. PopupMenu::highlightedTextColourId, 0xffffffff,
  51579. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  51580. ComboBox::textColourId, 0xff000000,
  51581. ComboBox::backgroundColourId, 0xffffffff,
  51582. ComboBox::arrowColourId, 0x99000000,
  51583. ListBox::backgroundColourId, 0xffffffff,
  51584. ListBox::outlineColourId, standardOutlineColour,
  51585. ListBox::textColourId, 0xff000000,
  51586. Slider::backgroundColourId, 0x00000000,
  51587. Slider::thumbColourId, textButtonColour,
  51588. Slider::trackColourId, 0x7fffffff,
  51589. Slider::rotarySliderFillColourId, 0x7f0000ff,
  51590. Slider::rotarySliderOutlineColourId, 0x66000000,
  51591. Slider::textBoxTextColourId, 0xff000000,
  51592. Slider::textBoxBackgroundColourId, 0xffffffff,
  51593. Slider::textBoxHighlightColourId, textHighlightColour,
  51594. Slider::textBoxOutlineColourId, standardOutlineColour,
  51595. ResizableWindow::backgroundColourId, 0xff777777,
  51596. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  51597. AlertWindow::backgroundColourId, 0xffededed,
  51598. AlertWindow::textColourId, 0xff000000,
  51599. AlertWindow::outlineColourId, 0xff666666,
  51600. ProgressBar::backgroundColourId, 0xffeeeeee,
  51601. ProgressBar::foregroundColourId, 0xffaaaaee,
  51602. TooltipWindow::backgroundColourId, 0xffeeeebb,
  51603. TooltipWindow::textColourId, 0xff000000,
  51604. TooltipWindow::outlineColourId, 0x4c000000,
  51605. TabbedComponent::backgroundColourId, 0x00000000,
  51606. TabbedComponent::outlineColourId, 0xff777777,
  51607. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  51608. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  51609. Toolbar::backgroundColourId, 0xfff6f8f9,
  51610. Toolbar::separatorColourId, 0x4c000000,
  51611. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  51612. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  51613. Toolbar::labelTextColourId, 0xff000000,
  51614. Toolbar::editingModeOutlineColourId, 0xffff0000,
  51615. HyperlinkButton::textColourId, 0xcc1111ee,
  51616. GroupComponent::outlineColourId, 0x66000000,
  51617. GroupComponent::textColourId, 0xff000000,
  51618. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  51619. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  51620. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  51621. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  51622. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  51623. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  51624. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  51625. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  51626. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  51627. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  51628. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  51629. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  51630. CodeEditorComponent::backgroundColourId, 0xffffffff,
  51631. CodeEditorComponent::caretColourId, 0xff000000,
  51632. CodeEditorComponent::highlightColourId, textHighlightColour,
  51633. CodeEditorComponent::defaultTextColourId, 0xff000000,
  51634. ColourSelector::backgroundColourId, 0xffe5e5e5,
  51635. ColourSelector::labelTextColourId, 0xff000000,
  51636. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  51637. KeyMappingEditorComponent::textColourId, 0xff000000,
  51638. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  51639. FileChooserDialogBox::titleTextColourId, 0xff000000,
  51640. };
  51641. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  51642. setColour (standardColours [i], Colour (standardColours [i + 1]));
  51643. static String defaultSansName, defaultSerifName, defaultFixedName;
  51644. if (defaultSansName.isEmpty())
  51645. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  51646. defaultSans = defaultSansName;
  51647. defaultSerif = defaultSerifName;
  51648. defaultFixed = defaultFixedName;
  51649. }
  51650. LookAndFeel::~LookAndFeel()
  51651. {
  51652. }
  51653. const Colour LookAndFeel::findColour (const int colourId) const throw()
  51654. {
  51655. const int index = colourIds.indexOf (colourId);
  51656. if (index >= 0)
  51657. return colours [index];
  51658. jassertfalse;
  51659. return Colours::black;
  51660. }
  51661. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  51662. {
  51663. const int index = colourIds.indexOf (colourId);
  51664. if (index >= 0)
  51665. {
  51666. colours.set (index, colour);
  51667. }
  51668. else
  51669. {
  51670. colourIds.add (colourId);
  51671. colours.add (colour);
  51672. }
  51673. }
  51674. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  51675. {
  51676. return colourIds.contains (colourId);
  51677. }
  51678. static LookAndFeel* defaultLF = 0;
  51679. static LookAndFeel* currentDefaultLF = 0;
  51680. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  51681. {
  51682. // if this happens, your app hasn't initialised itself properly.. if you're
  51683. // trying to hack your own main() function, have a look at
  51684. // JUCEApplication::initialiseForGUI()
  51685. jassert (currentDefaultLF != 0);
  51686. return *currentDefaultLF;
  51687. }
  51688. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  51689. {
  51690. if (newDefaultLookAndFeel == 0)
  51691. {
  51692. if (defaultLF == 0)
  51693. defaultLF = new LookAndFeel();
  51694. newDefaultLookAndFeel = defaultLF;
  51695. }
  51696. currentDefaultLF = newDefaultLookAndFeel;
  51697. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  51698. {
  51699. Component* const c = Desktop::getInstance().getComponent (i);
  51700. if (c != 0)
  51701. c->sendLookAndFeelChange();
  51702. }
  51703. }
  51704. void LookAndFeel::clearDefaultLookAndFeel() throw()
  51705. {
  51706. if (currentDefaultLF == defaultLF)
  51707. currentDefaultLF = 0;
  51708. deleteAndZero (defaultLF);
  51709. }
  51710. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  51711. {
  51712. String faceName (font.getTypefaceName());
  51713. if (faceName == Font::getDefaultSansSerifFontName())
  51714. faceName = defaultSans;
  51715. else if (faceName == Font::getDefaultSerifFontName())
  51716. faceName = defaultSerif;
  51717. else if (faceName == Font::getDefaultMonospacedFontName())
  51718. faceName = defaultFixed;
  51719. Font f (font);
  51720. f.setTypefaceName (faceName);
  51721. return Typeface::createSystemTypefaceFor (f);
  51722. }
  51723. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  51724. {
  51725. defaultSans = newName;
  51726. }
  51727. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  51728. {
  51729. return component.getMouseCursor();
  51730. }
  51731. void LookAndFeel::drawButtonBackground (Graphics& g,
  51732. Button& button,
  51733. const Colour& backgroundColour,
  51734. bool isMouseOverButton,
  51735. bool isButtonDown)
  51736. {
  51737. const int width = button.getWidth();
  51738. const int height = button.getHeight();
  51739. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  51740. const float halfThickness = outlineThickness * 0.5f;
  51741. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  51742. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  51743. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  51744. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  51745. const Colour baseColour (createBaseColour (backgroundColour,
  51746. button.hasKeyboardFocus (true),
  51747. isMouseOverButton, isButtonDown)
  51748. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51749. drawGlassLozenge (g,
  51750. indentL,
  51751. indentT,
  51752. width - indentL - indentR,
  51753. height - indentT - indentB,
  51754. baseColour, outlineThickness, -1.0f,
  51755. button.isConnectedOnLeft(),
  51756. button.isConnectedOnRight(),
  51757. button.isConnectedOnTop(),
  51758. button.isConnectedOnBottom());
  51759. }
  51760. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  51761. {
  51762. return button.getFont();
  51763. }
  51764. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  51765. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  51766. {
  51767. Font font (getFontForTextButton (button));
  51768. g.setFont (font);
  51769. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  51770. : TextButton::textColourOffId)
  51771. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51772. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  51773. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  51774. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  51775. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  51776. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  51777. g.drawFittedText (button.getButtonText(),
  51778. leftIndent,
  51779. yIndent,
  51780. button.getWidth() - leftIndent - rightIndent,
  51781. button.getHeight() - yIndent * 2,
  51782. Justification::centred, 2);
  51783. }
  51784. void LookAndFeel::drawTickBox (Graphics& g,
  51785. Component& component,
  51786. float x, float y, float w, float h,
  51787. const bool ticked,
  51788. const bool isEnabled,
  51789. const bool isMouseOverButton,
  51790. const bool isButtonDown)
  51791. {
  51792. const float boxSize = w * 0.7f;
  51793. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  51794. createBaseColour (component.findColour (TextButton::buttonColourId)
  51795. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  51796. true,
  51797. isMouseOverButton,
  51798. isButtonDown),
  51799. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  51800. if (ticked)
  51801. {
  51802. Path tick;
  51803. tick.startNewSubPath (1.5f, 3.0f);
  51804. tick.lineTo (3.0f, 6.0f);
  51805. tick.lineTo (6.0f, 0.0f);
  51806. g.setColour (isEnabled ? Colours::black : Colours::grey);
  51807. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  51808. .translated (x, y));
  51809. g.strokePath (tick, PathStrokeType (2.5f), trans);
  51810. }
  51811. }
  51812. void LookAndFeel::drawToggleButton (Graphics& g,
  51813. ToggleButton& button,
  51814. bool isMouseOverButton,
  51815. bool isButtonDown)
  51816. {
  51817. if (button.hasKeyboardFocus (true))
  51818. {
  51819. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  51820. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  51821. }
  51822. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  51823. const float tickWidth = fontSize * 1.1f;
  51824. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  51825. tickWidth, tickWidth,
  51826. button.getToggleState(),
  51827. button.isEnabled(),
  51828. isMouseOverButton,
  51829. isButtonDown);
  51830. g.setColour (button.findColour (ToggleButton::textColourId));
  51831. g.setFont (fontSize);
  51832. if (! button.isEnabled())
  51833. g.setOpacity (0.5f);
  51834. const int textX = (int) tickWidth + 5;
  51835. g.drawFittedText (button.getButtonText(),
  51836. textX, 0,
  51837. button.getWidth() - textX - 2, button.getHeight(),
  51838. Justification::centredLeft, 10);
  51839. }
  51840. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  51841. {
  51842. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  51843. const int tickWidth = jmin (24, button.getHeight());
  51844. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  51845. button.getHeight());
  51846. }
  51847. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  51848. const String& message,
  51849. const String& button1,
  51850. const String& button2,
  51851. const String& button3,
  51852. AlertWindow::AlertIconType iconType,
  51853. int numButtons,
  51854. Component* associatedComponent)
  51855. {
  51856. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  51857. if (numButtons == 1)
  51858. {
  51859. aw->addButton (button1, 0,
  51860. KeyPress (KeyPress::escapeKey, 0, 0),
  51861. KeyPress (KeyPress::returnKey, 0, 0));
  51862. }
  51863. else
  51864. {
  51865. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  51866. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  51867. if (button1ShortCut == button2ShortCut)
  51868. button2ShortCut = KeyPress();
  51869. if (numButtons == 2)
  51870. {
  51871. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  51872. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  51873. }
  51874. else if (numButtons == 3)
  51875. {
  51876. aw->addButton (button1, 1, button1ShortCut);
  51877. aw->addButton (button2, 2, button2ShortCut);
  51878. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  51879. }
  51880. }
  51881. return aw;
  51882. }
  51883. void LookAndFeel::drawAlertBox (Graphics& g,
  51884. AlertWindow& alert,
  51885. const Rectangle<int>& textArea,
  51886. TextLayout& textLayout)
  51887. {
  51888. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  51889. int iconSpaceUsed = 0;
  51890. Justification alignment (Justification::horizontallyCentred);
  51891. const int iconWidth = 80;
  51892. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  51893. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  51894. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  51895. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  51896. iconSize, iconSize);
  51897. if (alert.getAlertType() != AlertWindow::NoIcon)
  51898. {
  51899. Path icon;
  51900. uint32 colour;
  51901. char character;
  51902. if (alert.getAlertType() == AlertWindow::WarningIcon)
  51903. {
  51904. colour = 0x55ff5555;
  51905. character = '!';
  51906. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  51907. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  51908. (float) iconRect.getX(), (float) iconRect.getBottom());
  51909. icon = icon.createPathWithRoundedCorners (5.0f);
  51910. }
  51911. else
  51912. {
  51913. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  51914. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  51915. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  51916. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  51917. }
  51918. GlyphArrangement ga;
  51919. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  51920. String::charToString (character),
  51921. (float) iconRect.getX(), (float) iconRect.getY(),
  51922. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  51923. Justification::centred, false);
  51924. ga.createPath (icon);
  51925. icon.setUsingNonZeroWinding (false);
  51926. g.setColour (Colour (colour));
  51927. g.fillPath (icon);
  51928. iconSpaceUsed = iconWidth;
  51929. alignment = Justification::left;
  51930. }
  51931. g.setColour (alert.findColour (AlertWindow::textColourId));
  51932. textLayout.drawWithin (g,
  51933. textArea.getX() + iconSpaceUsed, textArea.getY(),
  51934. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  51935. alignment.getFlags() | Justification::top);
  51936. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  51937. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  51938. }
  51939. int LookAndFeel::getAlertBoxWindowFlags()
  51940. {
  51941. return ComponentPeer::windowAppearsOnTaskbar
  51942. | ComponentPeer::windowHasDropShadow;
  51943. }
  51944. int LookAndFeel::getAlertWindowButtonHeight()
  51945. {
  51946. return 28;
  51947. }
  51948. const Font LookAndFeel::getAlertWindowFont()
  51949. {
  51950. return Font (12.0f);
  51951. }
  51952. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  51953. int width, int height,
  51954. double progress, const String& textToShow)
  51955. {
  51956. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  51957. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  51958. g.fillAll (background);
  51959. if (progress >= 0.0f && progress < 1.0f)
  51960. {
  51961. drawGlassLozenge (g, 1.0f, 1.0f,
  51962. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  51963. (float) (height - 2),
  51964. foreground,
  51965. 0.5f, 0.0f,
  51966. true, true, true, true);
  51967. }
  51968. else
  51969. {
  51970. // spinning bar..
  51971. g.setColour (foreground);
  51972. const int stripeWidth = height * 2;
  51973. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  51974. Path p;
  51975. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  51976. p.addQuadrilateral (x, 0.0f,
  51977. x + stripeWidth * 0.5f, 0.0f,
  51978. x, (float) height,
  51979. x - stripeWidth * 0.5f, (float) height);
  51980. Image im (Image::ARGB, width, height, true);
  51981. {
  51982. Graphics g2 (im);
  51983. drawGlassLozenge (g2, 1.0f, 1.0f,
  51984. (float) (width - 2),
  51985. (float) (height - 2),
  51986. foreground,
  51987. 0.5f, 0.0f,
  51988. true, true, true, true);
  51989. }
  51990. g.setTiledImageFill (im, 0, 0, 0.85f);
  51991. g.fillPath (p);
  51992. }
  51993. if (textToShow.isNotEmpty())
  51994. {
  51995. g.setColour (Colour::contrasting (background, foreground));
  51996. g.setFont (height * 0.6f);
  51997. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  51998. }
  51999. }
  52000. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52001. {
  52002. const float radius = jmin (w, h) * 0.4f;
  52003. const float thickness = radius * 0.15f;
  52004. Path p;
  52005. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52006. radius * 0.6f, thickness,
  52007. thickness * 0.5f);
  52008. const float cx = x + w * 0.5f;
  52009. const float cy = y + h * 0.5f;
  52010. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52011. for (int i = 0; i < 12; ++i)
  52012. {
  52013. const int n = (i + 12 - animationIndex) % 12;
  52014. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52015. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52016. .translated (cx, cy));
  52017. }
  52018. }
  52019. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52020. ScrollBar& scrollbar,
  52021. int width, int height,
  52022. int buttonDirection,
  52023. bool /*isScrollbarVertical*/,
  52024. bool /*isMouseOverButton*/,
  52025. bool isButtonDown)
  52026. {
  52027. Path p;
  52028. if (buttonDirection == 0)
  52029. p.addTriangle (width * 0.5f, height * 0.2f,
  52030. width * 0.1f, height * 0.7f,
  52031. width * 0.9f, height * 0.7f);
  52032. else if (buttonDirection == 1)
  52033. p.addTriangle (width * 0.8f, height * 0.5f,
  52034. width * 0.3f, height * 0.1f,
  52035. width * 0.3f, height * 0.9f);
  52036. else if (buttonDirection == 2)
  52037. p.addTriangle (width * 0.5f, height * 0.8f,
  52038. width * 0.1f, height * 0.3f,
  52039. width * 0.9f, height * 0.3f);
  52040. else if (buttonDirection == 3)
  52041. p.addTriangle (width * 0.2f, height * 0.5f,
  52042. width * 0.7f, height * 0.1f,
  52043. width * 0.7f, height * 0.9f);
  52044. if (isButtonDown)
  52045. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52046. else
  52047. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52048. g.fillPath (p);
  52049. g.setColour (Colour (0x80000000));
  52050. g.strokePath (p, PathStrokeType (0.5f));
  52051. }
  52052. void LookAndFeel::drawScrollbar (Graphics& g,
  52053. ScrollBar& scrollbar,
  52054. int x, int y,
  52055. int width, int height,
  52056. bool isScrollbarVertical,
  52057. int thumbStartPosition,
  52058. int thumbSize,
  52059. bool /*isMouseOver*/,
  52060. bool /*isMouseDown*/)
  52061. {
  52062. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52063. Path slotPath, thumbPath;
  52064. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52065. const float slotIndentx2 = slotIndent * 2.0f;
  52066. const float thumbIndent = slotIndent + 1.0f;
  52067. const float thumbIndentx2 = thumbIndent * 2.0f;
  52068. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52069. if (isScrollbarVertical)
  52070. {
  52071. slotPath.addRoundedRectangle (x + slotIndent,
  52072. y + slotIndent,
  52073. width - slotIndentx2,
  52074. height - slotIndentx2,
  52075. (width - slotIndentx2) * 0.5f);
  52076. if (thumbSize > 0)
  52077. thumbPath.addRoundedRectangle (x + thumbIndent,
  52078. thumbStartPosition + thumbIndent,
  52079. width - thumbIndentx2,
  52080. thumbSize - thumbIndentx2,
  52081. (width - thumbIndentx2) * 0.5f);
  52082. gx1 = (float) x;
  52083. gx2 = x + width * 0.7f;
  52084. }
  52085. else
  52086. {
  52087. slotPath.addRoundedRectangle (x + slotIndent,
  52088. y + slotIndent,
  52089. width - slotIndentx2,
  52090. height - slotIndentx2,
  52091. (height - slotIndentx2) * 0.5f);
  52092. if (thumbSize > 0)
  52093. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52094. y + thumbIndent,
  52095. thumbSize - thumbIndentx2,
  52096. height - thumbIndentx2,
  52097. (height - thumbIndentx2) * 0.5f);
  52098. gy1 = (float) y;
  52099. gy2 = y + height * 0.7f;
  52100. }
  52101. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52102. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  52103. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  52104. g.fillPath (slotPath);
  52105. if (isScrollbarVertical)
  52106. {
  52107. gx1 = x + width * 0.6f;
  52108. gx2 = (float) x + width;
  52109. }
  52110. else
  52111. {
  52112. gy1 = y + height * 0.6f;
  52113. gy2 = (float) y + height;
  52114. }
  52115. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52116. Colour (0x19000000), gx2, gy2, false));
  52117. g.fillPath (slotPath);
  52118. g.setColour (thumbColour);
  52119. g.fillPath (thumbPath);
  52120. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52121. Colours::transparentBlack, gx2, gy2, false));
  52122. g.saveState();
  52123. if (isScrollbarVertical)
  52124. g.reduceClipRegion (x + width / 2, y, width, height);
  52125. else
  52126. g.reduceClipRegion (x, y + height / 2, width, height);
  52127. g.fillPath (thumbPath);
  52128. g.restoreState();
  52129. g.setColour (Colour (0x4c000000));
  52130. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52131. }
  52132. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52133. {
  52134. return 0;
  52135. }
  52136. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52137. {
  52138. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52139. }
  52140. int LookAndFeel::getDefaultScrollbarWidth()
  52141. {
  52142. return 18;
  52143. }
  52144. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52145. {
  52146. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52147. : scrollbar.getHeight());
  52148. }
  52149. const Path LookAndFeel::getTickShape (const float height)
  52150. {
  52151. static const unsigned char tickShapeData[] =
  52152. {
  52153. 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,
  52154. 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,
  52155. 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,
  52156. 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,
  52157. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52158. };
  52159. Path p;
  52160. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52161. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52162. return p;
  52163. }
  52164. const Path LookAndFeel::getCrossShape (const float height)
  52165. {
  52166. static const unsigned char crossShapeData[] =
  52167. {
  52168. 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,
  52169. 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,
  52170. 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,
  52171. 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,
  52172. 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,
  52173. 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,
  52174. 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
  52175. };
  52176. Path p;
  52177. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52178. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52179. return p;
  52180. }
  52181. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52182. {
  52183. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52184. x += (w - boxSize) >> 1;
  52185. y += (h - boxSize) >> 1;
  52186. w = boxSize;
  52187. h = boxSize;
  52188. g.setColour (Colour (0xe5ffffff));
  52189. g.fillRect (x, y, w, h);
  52190. g.setColour (Colour (0x80000000));
  52191. g.drawRect (x, y, w, h);
  52192. const float size = boxSize / 2 + 1.0f;
  52193. const float centre = (float) (boxSize / 2);
  52194. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  52195. if (isPlus)
  52196. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  52197. }
  52198. void LookAndFeel::drawBubble (Graphics& g,
  52199. float tipX, float tipY,
  52200. float boxX, float boxY,
  52201. float boxW, float boxH)
  52202. {
  52203. int side = 0;
  52204. if (tipX < boxX)
  52205. side = 1;
  52206. else if (tipX > boxX + boxW)
  52207. side = 3;
  52208. else if (tipY > boxY + boxH)
  52209. side = 2;
  52210. const float indent = 2.0f;
  52211. Path p;
  52212. p.addBubble (boxX + indent,
  52213. boxY + indent,
  52214. boxW - indent * 2.0f,
  52215. boxH - indent * 2.0f,
  52216. 5.0f,
  52217. tipX, tipY,
  52218. side,
  52219. 0.5f,
  52220. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  52221. //xxx need to take comp as param for colour
  52222. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  52223. g.fillPath (p);
  52224. //xxx as above
  52225. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  52226. g.strokePath (p, PathStrokeType (1.33f));
  52227. }
  52228. const Font LookAndFeel::getPopupMenuFont()
  52229. {
  52230. return Font (17.0f);
  52231. }
  52232. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  52233. const bool isSeparator,
  52234. int standardMenuItemHeight,
  52235. int& idealWidth,
  52236. int& idealHeight)
  52237. {
  52238. if (isSeparator)
  52239. {
  52240. idealWidth = 50;
  52241. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  52242. }
  52243. else
  52244. {
  52245. Font font (getPopupMenuFont());
  52246. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  52247. font.setHeight (standardMenuItemHeight / 1.3f);
  52248. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  52249. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  52250. }
  52251. }
  52252. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  52253. {
  52254. const Colour background (findColour (PopupMenu::backgroundColourId));
  52255. g.fillAll (background);
  52256. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  52257. for (int i = 0; i < height; i += 3)
  52258. g.fillRect (0, i, width, 1);
  52259. #if ! JUCE_MAC
  52260. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  52261. g.drawRect (0, 0, width, height);
  52262. #endif
  52263. }
  52264. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  52265. int width, int height,
  52266. bool isScrollUpArrow)
  52267. {
  52268. const Colour background (findColour (PopupMenu::backgroundColourId));
  52269. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  52270. background.withAlpha (0.0f),
  52271. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  52272. false));
  52273. g.fillRect (1, 1, width - 2, height - 2);
  52274. const float hw = width * 0.5f;
  52275. const float arrowW = height * 0.3f;
  52276. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  52277. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  52278. Path p;
  52279. p.addTriangle (hw - arrowW, y1,
  52280. hw + arrowW, y1,
  52281. hw, y2);
  52282. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  52283. g.fillPath (p);
  52284. }
  52285. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  52286. int width, int height,
  52287. const bool isSeparator,
  52288. const bool isActive,
  52289. const bool isHighlighted,
  52290. const bool isTicked,
  52291. const bool hasSubMenu,
  52292. const String& text,
  52293. const String& shortcutKeyText,
  52294. Image* image,
  52295. const Colour* const textColourToUse)
  52296. {
  52297. const float halfH = height * 0.5f;
  52298. if (isSeparator)
  52299. {
  52300. const float separatorIndent = 5.5f;
  52301. g.setColour (Colour (0x33000000));
  52302. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  52303. g.setColour (Colour (0x66ffffff));
  52304. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  52305. }
  52306. else
  52307. {
  52308. Colour textColour (findColour (PopupMenu::textColourId));
  52309. if (textColourToUse != 0)
  52310. textColour = *textColourToUse;
  52311. if (isHighlighted)
  52312. {
  52313. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  52314. g.fillRect (1, 1, width - 2, height - 2);
  52315. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  52316. }
  52317. else
  52318. {
  52319. g.setColour (textColour);
  52320. }
  52321. if (! isActive)
  52322. g.setOpacity (0.3f);
  52323. Font font (getPopupMenuFont());
  52324. if (font.getHeight() > height / 1.3f)
  52325. font.setHeight (height / 1.3f);
  52326. g.setFont (font);
  52327. const int leftBorder = (height * 5) / 4;
  52328. const int rightBorder = 4;
  52329. if (image != 0)
  52330. {
  52331. g.drawImageWithin (*image,
  52332. 2, 1, leftBorder - 4, height - 2,
  52333. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  52334. }
  52335. else if (isTicked)
  52336. {
  52337. const Path tick (getTickShape (1.0f));
  52338. const float th = font.getAscent();
  52339. const float ty = halfH - th * 0.5f;
  52340. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  52341. th, true));
  52342. }
  52343. g.drawFittedText (text,
  52344. leftBorder, 0,
  52345. width - (leftBorder + rightBorder), height,
  52346. Justification::centredLeft, 1);
  52347. if (shortcutKeyText.isNotEmpty())
  52348. {
  52349. Font f2 (font);
  52350. f2.setHeight (f2.getHeight() * 0.75f);
  52351. f2.setHorizontalScale (0.95f);
  52352. g.setFont (f2);
  52353. g.drawText (shortcutKeyText,
  52354. leftBorder,
  52355. 0,
  52356. width - (leftBorder + rightBorder + 4),
  52357. height,
  52358. Justification::centredRight,
  52359. true);
  52360. }
  52361. if (hasSubMenu)
  52362. {
  52363. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  52364. const float x = width - height * 0.6f;
  52365. Path p;
  52366. p.addTriangle (x, halfH - arrowH * 0.5f,
  52367. x, halfH + arrowH * 0.5f,
  52368. x + arrowH * 0.6f, halfH);
  52369. g.fillPath (p);
  52370. }
  52371. }
  52372. }
  52373. int LookAndFeel::getMenuWindowFlags()
  52374. {
  52375. return ComponentPeer::windowHasDropShadow;
  52376. }
  52377. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  52378. bool, MenuBarComponent& menuBar)
  52379. {
  52380. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  52381. if (menuBar.isEnabled())
  52382. {
  52383. drawShinyButtonShape (g,
  52384. -4.0f, 0.0f,
  52385. width + 8.0f, (float) height,
  52386. 0.0f,
  52387. baseColour,
  52388. 0.4f,
  52389. true, true, true, true);
  52390. }
  52391. else
  52392. {
  52393. g.fillAll (baseColour);
  52394. }
  52395. }
  52396. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  52397. {
  52398. return Font (menuBar.getHeight() * 0.7f);
  52399. }
  52400. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  52401. {
  52402. return getMenuBarFont (menuBar, itemIndex, itemText)
  52403. .getStringWidth (itemText) + menuBar.getHeight();
  52404. }
  52405. void LookAndFeel::drawMenuBarItem (Graphics& g,
  52406. int width, int height,
  52407. int itemIndex,
  52408. const String& itemText,
  52409. bool isMouseOverItem,
  52410. bool isMenuOpen,
  52411. bool /*isMouseOverBar*/,
  52412. MenuBarComponent& menuBar)
  52413. {
  52414. if (! menuBar.isEnabled())
  52415. {
  52416. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  52417. .withMultipliedAlpha (0.5f));
  52418. }
  52419. else if (isMenuOpen || isMouseOverItem)
  52420. {
  52421. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  52422. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  52423. }
  52424. else
  52425. {
  52426. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  52427. }
  52428. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  52429. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  52430. }
  52431. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  52432. TextEditor& textEditor)
  52433. {
  52434. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  52435. }
  52436. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  52437. {
  52438. if (textEditor.isEnabled())
  52439. {
  52440. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  52441. {
  52442. const int border = 2;
  52443. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  52444. g.drawRect (0, 0, width, height, border);
  52445. g.setOpacity (1.0f);
  52446. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  52447. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  52448. }
  52449. else
  52450. {
  52451. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  52452. g.drawRect (0, 0, width, height);
  52453. g.setOpacity (1.0f);
  52454. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  52455. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  52456. }
  52457. }
  52458. }
  52459. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  52460. const bool isButtonDown,
  52461. int buttonX, int buttonY,
  52462. int buttonW, int buttonH,
  52463. ComboBox& box)
  52464. {
  52465. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  52466. if (box.isEnabled() && box.hasKeyboardFocus (false))
  52467. {
  52468. g.setColour (box.findColour (TextButton::buttonColourId));
  52469. g.drawRect (0, 0, width, height, 2);
  52470. }
  52471. else
  52472. {
  52473. g.setColour (box.findColour (ComboBox::outlineColourId));
  52474. g.drawRect (0, 0, width, height);
  52475. }
  52476. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  52477. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  52478. box.hasKeyboardFocus (true),
  52479. false, isButtonDown)
  52480. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  52481. drawGlassLozenge (g,
  52482. buttonX + outlineThickness, buttonY + outlineThickness,
  52483. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  52484. baseColour, outlineThickness, -1.0f,
  52485. true, true, true, true);
  52486. if (box.isEnabled())
  52487. {
  52488. const float arrowX = 0.3f;
  52489. const float arrowH = 0.2f;
  52490. Path p;
  52491. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  52492. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  52493. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  52494. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  52495. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  52496. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  52497. g.setColour (box.findColour (ComboBox::arrowColourId));
  52498. g.fillPath (p);
  52499. }
  52500. }
  52501. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  52502. {
  52503. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  52504. }
  52505. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  52506. {
  52507. return new Label (String::empty, String::empty);
  52508. }
  52509. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  52510. {
  52511. label.setBounds (1, 1,
  52512. box.getWidth() + 3 - box.getHeight(),
  52513. box.getHeight() - 2);
  52514. label.setFont (getComboBoxFont (box));
  52515. }
  52516. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  52517. {
  52518. g.fillAll (label.findColour (Label::backgroundColourId));
  52519. if (! label.isBeingEdited())
  52520. {
  52521. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  52522. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  52523. g.setFont (label.getFont());
  52524. g.drawFittedText (label.getText(),
  52525. label.getHorizontalBorderSize(),
  52526. label.getVerticalBorderSize(),
  52527. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  52528. label.getHeight() - 2 * label.getVerticalBorderSize(),
  52529. label.getJustificationType(),
  52530. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  52531. label.getMinimumHorizontalScale());
  52532. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  52533. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52534. }
  52535. else if (label.isEnabled())
  52536. {
  52537. g.setColour (label.findColour (Label::outlineColourId));
  52538. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52539. }
  52540. }
  52541. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  52542. int x, int y,
  52543. int width, int height,
  52544. float /*sliderPos*/,
  52545. float /*minSliderPos*/,
  52546. float /*maxSliderPos*/,
  52547. const Slider::SliderStyle /*style*/,
  52548. Slider& slider)
  52549. {
  52550. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52551. const Colour trackColour (slider.findColour (Slider::trackColourId));
  52552. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  52553. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  52554. Path indent;
  52555. if (slider.isHorizontal())
  52556. {
  52557. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  52558. const float ih = sliderRadius;
  52559. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  52560. gradCol2, 0.0f, iy + ih, false));
  52561. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  52562. width + sliderRadius, ih,
  52563. 5.0f);
  52564. g.fillPath (indent);
  52565. }
  52566. else
  52567. {
  52568. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  52569. const float iw = sliderRadius;
  52570. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  52571. gradCol2, ix + iw, 0.0f, false));
  52572. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  52573. iw, height + sliderRadius,
  52574. 5.0f);
  52575. g.fillPath (indent);
  52576. }
  52577. g.setColour (Colour (0x4c000000));
  52578. g.strokePath (indent, PathStrokeType (0.5f));
  52579. }
  52580. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  52581. int x, int y,
  52582. int width, int height,
  52583. float sliderPos,
  52584. float minSliderPos,
  52585. float maxSliderPos,
  52586. const Slider::SliderStyle style,
  52587. Slider& slider)
  52588. {
  52589. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52590. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  52591. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  52592. slider.isMouseOverOrDragging() && slider.isEnabled(),
  52593. slider.isMouseButtonDown() && slider.isEnabled()));
  52594. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  52595. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  52596. {
  52597. float kx, ky;
  52598. if (style == Slider::LinearVertical)
  52599. {
  52600. kx = x + width * 0.5f;
  52601. ky = sliderPos;
  52602. }
  52603. else
  52604. {
  52605. kx = sliderPos;
  52606. ky = y + height * 0.5f;
  52607. }
  52608. drawGlassSphere (g,
  52609. kx - sliderRadius,
  52610. ky - sliderRadius,
  52611. sliderRadius * 2.0f,
  52612. knobColour, outlineThickness);
  52613. }
  52614. else
  52615. {
  52616. if (style == Slider::ThreeValueVertical)
  52617. {
  52618. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  52619. sliderPos - sliderRadius,
  52620. sliderRadius * 2.0f,
  52621. knobColour, outlineThickness);
  52622. }
  52623. else if (style == Slider::ThreeValueHorizontal)
  52624. {
  52625. drawGlassSphere (g,sliderPos - sliderRadius,
  52626. y + height * 0.5f - sliderRadius,
  52627. sliderRadius * 2.0f,
  52628. knobColour, outlineThickness);
  52629. }
  52630. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  52631. {
  52632. const float sr = jmin (sliderRadius, width * 0.4f);
  52633. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  52634. minSliderPos - sliderRadius,
  52635. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  52636. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  52637. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  52638. }
  52639. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  52640. {
  52641. const float sr = jmin (sliderRadius, height * 0.4f);
  52642. drawGlassPointer (g, minSliderPos - sr,
  52643. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  52644. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  52645. drawGlassPointer (g, maxSliderPos - sliderRadius,
  52646. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  52647. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  52648. }
  52649. }
  52650. }
  52651. void LookAndFeel::drawLinearSlider (Graphics& g,
  52652. int x, int y,
  52653. int width, int height,
  52654. float sliderPos,
  52655. float minSliderPos,
  52656. float maxSliderPos,
  52657. const Slider::SliderStyle style,
  52658. Slider& slider)
  52659. {
  52660. g.fillAll (slider.findColour (Slider::backgroundColourId));
  52661. if (style == Slider::LinearBar)
  52662. {
  52663. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52664. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  52665. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  52666. false,
  52667. isMouseOver,
  52668. isMouseOver || slider.isMouseButtonDown()));
  52669. drawShinyButtonShape (g,
  52670. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  52671. baseColour,
  52672. slider.isEnabled() ? 0.9f : 0.3f,
  52673. true, true, true, true);
  52674. }
  52675. else
  52676. {
  52677. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52678. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52679. }
  52680. }
  52681. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  52682. {
  52683. return jmin (7,
  52684. slider.getHeight() / 2,
  52685. slider.getWidth() / 2) + 2;
  52686. }
  52687. void LookAndFeel::drawRotarySlider (Graphics& g,
  52688. int x, int y,
  52689. int width, int height,
  52690. float sliderPos,
  52691. const float rotaryStartAngle,
  52692. const float rotaryEndAngle,
  52693. Slider& slider)
  52694. {
  52695. const float radius = jmin (width / 2, height / 2) - 2.0f;
  52696. const float centreX = x + width * 0.5f;
  52697. const float centreY = y + height * 0.5f;
  52698. const float rx = centreX - radius;
  52699. const float ry = centreY - radius;
  52700. const float rw = radius * 2.0f;
  52701. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  52702. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52703. if (radius > 12.0f)
  52704. {
  52705. if (slider.isEnabled())
  52706. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52707. else
  52708. g.setColour (Colour (0x80808080));
  52709. const float thickness = 0.7f;
  52710. {
  52711. Path filledArc;
  52712. filledArc.addPieSegment (rx, ry, rw, rw,
  52713. rotaryStartAngle,
  52714. angle,
  52715. thickness);
  52716. g.fillPath (filledArc);
  52717. }
  52718. if (thickness > 0)
  52719. {
  52720. const float innerRadius = radius * 0.2f;
  52721. Path p;
  52722. p.addTriangle (-innerRadius, 0.0f,
  52723. 0.0f, -radius * thickness * 1.1f,
  52724. innerRadius, 0.0f);
  52725. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  52726. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52727. }
  52728. if (slider.isEnabled())
  52729. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  52730. else
  52731. g.setColour (Colour (0x80808080));
  52732. Path outlineArc;
  52733. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  52734. outlineArc.closeSubPath();
  52735. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  52736. }
  52737. else
  52738. {
  52739. if (slider.isEnabled())
  52740. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52741. else
  52742. g.setColour (Colour (0x80808080));
  52743. Path p;
  52744. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  52745. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  52746. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  52747. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52748. }
  52749. }
  52750. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  52751. {
  52752. return new TextButton (isIncrement ? "+" : "-", String::empty);
  52753. }
  52754. class SliderLabelComp : public Label
  52755. {
  52756. public:
  52757. SliderLabelComp() : Label (String::empty, String::empty) {}
  52758. ~SliderLabelComp() {}
  52759. void mouseWheelMove (const MouseEvent&, float, float) {}
  52760. };
  52761. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  52762. {
  52763. Label* const l = new SliderLabelComp();
  52764. l->setJustificationType (Justification::centred);
  52765. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52766. l->setColour (Label::backgroundColourId,
  52767. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  52768. : slider.findColour (Slider::textBoxBackgroundColourId));
  52769. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52770. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52771. l->setColour (TextEditor::backgroundColourId,
  52772. slider.findColour (Slider::textBoxBackgroundColourId)
  52773. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  52774. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52775. return l;
  52776. }
  52777. ImageEffectFilter* LookAndFeel::getSliderEffect()
  52778. {
  52779. return 0;
  52780. }
  52781. static const TextLayout layoutTooltipText (const String& text) throw()
  52782. {
  52783. const float tooltipFontSize = 12.0f;
  52784. const int maxToolTipWidth = 400;
  52785. const Font f (tooltipFontSize, Font::bold);
  52786. TextLayout tl (text, f);
  52787. tl.layout (maxToolTipWidth, Justification::left, true);
  52788. return tl;
  52789. }
  52790. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  52791. {
  52792. const TextLayout tl (layoutTooltipText (tipText));
  52793. width = tl.getWidth() + 14;
  52794. height = tl.getHeight() + 6;
  52795. }
  52796. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  52797. {
  52798. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  52799. const Colour textCol (findColour (TooltipWindow::textColourId));
  52800. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  52801. g.setColour (findColour (TooltipWindow::outlineColourId));
  52802. g.drawRect (0, 0, width, height, 1);
  52803. #endif
  52804. const TextLayout tl (layoutTooltipText (text));
  52805. g.setColour (findColour (TooltipWindow::textColourId));
  52806. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  52807. }
  52808. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  52809. {
  52810. return new TextButton (text, TRANS("click to browse for a different file"));
  52811. }
  52812. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  52813. ComboBox* filenameBox,
  52814. Button* browseButton)
  52815. {
  52816. browseButton->setSize (80, filenameComp.getHeight());
  52817. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  52818. if (tb != 0)
  52819. tb->changeWidthToFitText();
  52820. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  52821. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  52822. }
  52823. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  52824. int imageX, int imageY, int imageW, int imageH,
  52825. const Colour& overlayColour,
  52826. float imageOpacity,
  52827. ImageButton& button)
  52828. {
  52829. if (! button.isEnabled())
  52830. imageOpacity *= 0.3f;
  52831. if (! overlayColour.isOpaque())
  52832. {
  52833. g.setOpacity (imageOpacity);
  52834. g.drawImage (*image, imageX, imageY, imageW, imageH,
  52835. 0, 0, image->getWidth(), image->getHeight(), false);
  52836. }
  52837. if (! overlayColour.isTransparent())
  52838. {
  52839. g.setColour (overlayColour);
  52840. g.drawImage (*image, imageX, imageY, imageW, imageH,
  52841. 0, 0, image->getWidth(), image->getHeight(), true);
  52842. }
  52843. }
  52844. void LookAndFeel::drawCornerResizer (Graphics& g,
  52845. int w, int h,
  52846. bool /*isMouseOver*/,
  52847. bool /*isMouseDragging*/)
  52848. {
  52849. const float lineThickness = jmin (w, h) * 0.075f;
  52850. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  52851. {
  52852. g.setColour (Colours::lightgrey);
  52853. g.drawLine (w * i,
  52854. h + 1.0f,
  52855. w + 1.0f,
  52856. h * i,
  52857. lineThickness);
  52858. g.setColour (Colours::darkgrey);
  52859. g.drawLine (w * i + lineThickness,
  52860. h + 1.0f,
  52861. w + 1.0f,
  52862. h * i + lineThickness,
  52863. lineThickness);
  52864. }
  52865. }
  52866. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  52867. const BorderSize& /*borders*/)
  52868. {
  52869. }
  52870. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  52871. const BorderSize& /*border*/, ResizableWindow& window)
  52872. {
  52873. g.fillAll (window.getBackgroundColour());
  52874. }
  52875. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  52876. const BorderSize& border, ResizableWindow&)
  52877. {
  52878. g.setColour (Colour (0x80000000));
  52879. g.drawRect (0, 0, w, h);
  52880. g.setColour (Colour (0x19000000));
  52881. g.drawRect (border.getLeft() - 1,
  52882. border.getTop() - 1,
  52883. w + 2 - border.getLeftAndRight(),
  52884. h + 2 - border.getTopAndBottom());
  52885. }
  52886. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  52887. Graphics& g, int w, int h,
  52888. int titleSpaceX, int titleSpaceW,
  52889. const Image* icon,
  52890. bool drawTitleTextOnLeft)
  52891. {
  52892. const bool isActive = window.isActiveWindow();
  52893. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  52894. 0.0f, 0.0f,
  52895. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  52896. 0.0f, (float) h, false));
  52897. g.fillAll();
  52898. Font font (h * 0.65f, Font::bold);
  52899. g.setFont (font);
  52900. int textW = font.getStringWidth (window.getName());
  52901. int iconW = 0;
  52902. int iconH = 0;
  52903. if (icon != 0)
  52904. {
  52905. iconH = (int) font.getHeight();
  52906. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  52907. }
  52908. textW = jmin (titleSpaceW, textW + iconW);
  52909. int textX = drawTitleTextOnLeft ? titleSpaceX
  52910. : jmax (titleSpaceX, (w - textW) / 2);
  52911. if (textX + textW > titleSpaceX + titleSpaceW)
  52912. textX = titleSpaceX + titleSpaceW - textW;
  52913. if (icon != 0)
  52914. {
  52915. g.setOpacity (isActive ? 1.0f : 0.6f);
  52916. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  52917. RectanglePlacement::centred, false);
  52918. textX += iconW;
  52919. textW -= iconW;
  52920. }
  52921. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  52922. g.setColour (findColour (DocumentWindow::textColourId));
  52923. else
  52924. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  52925. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  52926. }
  52927. class GlassWindowButton : public Button
  52928. {
  52929. public:
  52930. GlassWindowButton (const String& name, const Colour& col,
  52931. const Path& normalShape_,
  52932. const Path& toggledShape_) throw()
  52933. : Button (name),
  52934. colour (col),
  52935. normalShape (normalShape_),
  52936. toggledShape (toggledShape_)
  52937. {
  52938. }
  52939. ~GlassWindowButton()
  52940. {
  52941. }
  52942. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  52943. {
  52944. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  52945. if (! isEnabled())
  52946. alpha *= 0.5f;
  52947. float x = 0, y = 0, diam;
  52948. if (getWidth() < getHeight())
  52949. {
  52950. diam = (float) getWidth();
  52951. y = (getHeight() - getWidth()) * 0.5f;
  52952. }
  52953. else
  52954. {
  52955. diam = (float) getHeight();
  52956. y = (getWidth() - getHeight()) * 0.5f;
  52957. }
  52958. x += diam * 0.05f;
  52959. y += diam * 0.05f;
  52960. diam *= 0.9f;
  52961. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  52962. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  52963. g.fillEllipse (x, y, diam, diam);
  52964. x += 2.0f;
  52965. y += 2.0f;
  52966. diam -= 4.0f;
  52967. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  52968. Path& p = getToggleState() ? toggledShape : normalShape;
  52969. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  52970. diam * 0.4f, diam * 0.4f, true));
  52971. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  52972. g.fillPath (p, t);
  52973. }
  52974. juce_UseDebuggingNewOperator
  52975. private:
  52976. Colour colour;
  52977. Path normalShape, toggledShape;
  52978. GlassWindowButton (const GlassWindowButton&);
  52979. GlassWindowButton& operator= (const GlassWindowButton&);
  52980. };
  52981. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  52982. {
  52983. Path shape;
  52984. const float crossThickness = 0.25f;
  52985. if (buttonType == DocumentWindow::closeButton)
  52986. {
  52987. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  52988. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  52989. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  52990. }
  52991. else if (buttonType == DocumentWindow::minimiseButton)
  52992. {
  52993. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  52994. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  52995. }
  52996. else if (buttonType == DocumentWindow::maximiseButton)
  52997. {
  52998. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  52999. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53000. Path fullscreenShape;
  53001. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53002. fullscreenShape.lineTo (0.0f, 100.0f);
  53003. fullscreenShape.lineTo (0.0f, 0.0f);
  53004. fullscreenShape.lineTo (100.0f, 0.0f);
  53005. fullscreenShape.lineTo (100.0f, 45.0f);
  53006. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53007. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53008. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53009. }
  53010. jassertfalse;
  53011. return 0;
  53012. }
  53013. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53014. int titleBarX,
  53015. int titleBarY,
  53016. int titleBarW,
  53017. int titleBarH,
  53018. Button* minimiseButton,
  53019. Button* maximiseButton,
  53020. Button* closeButton,
  53021. bool positionTitleBarButtonsOnLeft)
  53022. {
  53023. const int buttonW = titleBarH - titleBarH / 8;
  53024. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53025. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53026. if (closeButton != 0)
  53027. {
  53028. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53029. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53030. }
  53031. if (positionTitleBarButtonsOnLeft)
  53032. swapVariables (minimiseButton, maximiseButton);
  53033. if (maximiseButton != 0)
  53034. {
  53035. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53036. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53037. }
  53038. if (minimiseButton != 0)
  53039. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53040. }
  53041. int LookAndFeel::getDefaultMenuBarHeight()
  53042. {
  53043. return 24;
  53044. }
  53045. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53046. {
  53047. return new DropShadower (0.4f, 1, 5, 10);
  53048. }
  53049. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53050. int w, int h,
  53051. bool /*isVerticalBar*/,
  53052. bool isMouseOver,
  53053. bool isMouseDragging)
  53054. {
  53055. float alpha = 0.5f;
  53056. if (isMouseOver || isMouseDragging)
  53057. {
  53058. g.fillAll (Colour (0x190000ff));
  53059. alpha = 1.0f;
  53060. }
  53061. const float cx = w * 0.5f;
  53062. const float cy = h * 0.5f;
  53063. const float cr = jmin (w, h) * 0.4f;
  53064. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53065. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53066. true));
  53067. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53068. }
  53069. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53070. const String& text,
  53071. const Justification& position,
  53072. GroupComponent& group)
  53073. {
  53074. const float textH = 15.0f;
  53075. const float indent = 3.0f;
  53076. const float textEdgeGap = 4.0f;
  53077. float cs = 5.0f;
  53078. Font f (textH);
  53079. Path p;
  53080. float x = indent;
  53081. float y = f.getAscent() - 3.0f;
  53082. float w = jmax (0.0f, width - x * 2.0f);
  53083. float h = jmax (0.0f, height - y - indent);
  53084. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53085. const float cs2 = 2.0f * cs;
  53086. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53087. float textX = cs + textEdgeGap;
  53088. if (position.testFlags (Justification::horizontallyCentred))
  53089. textX = cs + (w - cs2 - textW) * 0.5f;
  53090. else if (position.testFlags (Justification::right))
  53091. textX = w - cs - textW - textEdgeGap;
  53092. p.startNewSubPath (x + textX + textW, y);
  53093. p.lineTo (x + w - cs, y);
  53094. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53095. p.lineTo (x + w, y + h - cs);
  53096. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53097. p.lineTo (x + cs, y + h);
  53098. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53099. p.lineTo (x, y + cs);
  53100. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53101. p.lineTo (x + textX, y);
  53102. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53103. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53104. .withMultipliedAlpha (alpha));
  53105. g.strokePath (p, PathStrokeType (2.0f));
  53106. g.setColour (group.findColour (GroupComponent::textColourId)
  53107. .withMultipliedAlpha (alpha));
  53108. g.setFont (f);
  53109. g.drawText (text,
  53110. roundToInt (x + textX), 0,
  53111. roundToInt (textW),
  53112. roundToInt (textH),
  53113. Justification::centred, true);
  53114. }
  53115. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53116. {
  53117. return 1 + tabDepth / 3;
  53118. }
  53119. int LookAndFeel::getTabButtonSpaceAroundImage()
  53120. {
  53121. return 4;
  53122. }
  53123. void LookAndFeel::createTabButtonShape (Path& p,
  53124. int width, int height,
  53125. int /*tabIndex*/,
  53126. const String& /*text*/,
  53127. Button& /*button*/,
  53128. TabbedButtonBar::Orientation orientation,
  53129. const bool /*isMouseOver*/,
  53130. const bool /*isMouseDown*/,
  53131. const bool /*isFrontTab*/)
  53132. {
  53133. const float w = (float) width;
  53134. const float h = (float) height;
  53135. float length = w;
  53136. float depth = h;
  53137. if (orientation == TabbedButtonBar::TabsAtLeft
  53138. || orientation == TabbedButtonBar::TabsAtRight)
  53139. {
  53140. swapVariables (length, depth);
  53141. }
  53142. const float indent = (float) getTabButtonOverlap ((int) depth);
  53143. const float overhang = 4.0f;
  53144. if (orientation == TabbedButtonBar::TabsAtLeft)
  53145. {
  53146. p.startNewSubPath (w, 0.0f);
  53147. p.lineTo (0.0f, indent);
  53148. p.lineTo (0.0f, h - indent);
  53149. p.lineTo (w, h);
  53150. p.lineTo (w + overhang, h + overhang);
  53151. p.lineTo (w + overhang, -overhang);
  53152. }
  53153. else if (orientation == TabbedButtonBar::TabsAtRight)
  53154. {
  53155. p.startNewSubPath (0.0f, 0.0f);
  53156. p.lineTo (w, indent);
  53157. p.lineTo (w, h - indent);
  53158. p.lineTo (0.0f, h);
  53159. p.lineTo (-overhang, h + overhang);
  53160. p.lineTo (-overhang, -overhang);
  53161. }
  53162. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53163. {
  53164. p.startNewSubPath (0.0f, 0.0f);
  53165. p.lineTo (indent, h);
  53166. p.lineTo (w - indent, h);
  53167. p.lineTo (w, 0.0f);
  53168. p.lineTo (w + overhang, -overhang);
  53169. p.lineTo (-overhang, -overhang);
  53170. }
  53171. else
  53172. {
  53173. p.startNewSubPath (0.0f, h);
  53174. p.lineTo (indent, 0.0f);
  53175. p.lineTo (w - indent, 0.0f);
  53176. p.lineTo (w, h);
  53177. p.lineTo (w + overhang, h + overhang);
  53178. p.lineTo (-overhang, h + overhang);
  53179. }
  53180. p.closeSubPath();
  53181. p = p.createPathWithRoundedCorners (3.0f);
  53182. }
  53183. void LookAndFeel::fillTabButtonShape (Graphics& g,
  53184. const Path& path,
  53185. const Colour& preferredColour,
  53186. int /*tabIndex*/,
  53187. const String& /*text*/,
  53188. Button& button,
  53189. TabbedButtonBar::Orientation /*orientation*/,
  53190. const bool /*isMouseOver*/,
  53191. const bool /*isMouseDown*/,
  53192. const bool isFrontTab)
  53193. {
  53194. g.setColour (isFrontTab ? preferredColour
  53195. : preferredColour.withMultipliedAlpha (0.9f));
  53196. g.fillPath (path);
  53197. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  53198. : TabbedButtonBar::tabOutlineColourId, false)
  53199. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  53200. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  53201. }
  53202. void LookAndFeel::drawTabButtonText (Graphics& g,
  53203. int x, int y, int w, int h,
  53204. const Colour& preferredBackgroundColour,
  53205. int /*tabIndex*/,
  53206. const String& text,
  53207. Button& button,
  53208. TabbedButtonBar::Orientation orientation,
  53209. const bool isMouseOver,
  53210. const bool isMouseDown,
  53211. const bool isFrontTab)
  53212. {
  53213. int length = w;
  53214. int depth = h;
  53215. if (orientation == TabbedButtonBar::TabsAtLeft
  53216. || orientation == TabbedButtonBar::TabsAtRight)
  53217. {
  53218. swapVariables (length, depth);
  53219. }
  53220. Font font (depth * 0.6f);
  53221. font.setUnderline (button.hasKeyboardFocus (false));
  53222. GlyphArrangement textLayout;
  53223. textLayout.addFittedText (font, text.trim(),
  53224. 0.0f, 0.0f, (float) length, (float) depth,
  53225. Justification::centred,
  53226. jmax (1, depth / 12));
  53227. AffineTransform transform;
  53228. if (orientation == TabbedButtonBar::TabsAtLeft)
  53229. {
  53230. transform = transform.rotated (float_Pi * -0.5f)
  53231. .translated ((float) x, (float) (y + h));
  53232. }
  53233. else if (orientation == TabbedButtonBar::TabsAtRight)
  53234. {
  53235. transform = transform.rotated (float_Pi * 0.5f)
  53236. .translated ((float) (x + w), (float) y);
  53237. }
  53238. else
  53239. {
  53240. transform = transform.translated ((float) x, (float) y);
  53241. }
  53242. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  53243. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  53244. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  53245. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  53246. else
  53247. g.setColour (preferredBackgroundColour.contrasting());
  53248. if (! (isMouseOver || isMouseDown))
  53249. g.setOpacity (0.8f);
  53250. if (! button.isEnabled())
  53251. g.setOpacity (0.3f);
  53252. textLayout.draw (g, transform);
  53253. }
  53254. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  53255. const String& text,
  53256. int tabDepth,
  53257. Button&)
  53258. {
  53259. Font f (tabDepth * 0.6f);
  53260. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  53261. }
  53262. void LookAndFeel::drawTabButton (Graphics& g,
  53263. int w, int h,
  53264. const Colour& preferredColour,
  53265. int tabIndex,
  53266. const String& text,
  53267. Button& button,
  53268. TabbedButtonBar::Orientation orientation,
  53269. const bool isMouseOver,
  53270. const bool isMouseDown,
  53271. const bool isFrontTab)
  53272. {
  53273. int length = w;
  53274. int depth = h;
  53275. if (orientation == TabbedButtonBar::TabsAtLeft
  53276. || orientation == TabbedButtonBar::TabsAtRight)
  53277. {
  53278. swapVariables (length, depth);
  53279. }
  53280. Path tabShape;
  53281. createTabButtonShape (tabShape, w, h,
  53282. tabIndex, text, button, orientation,
  53283. isMouseOver, isMouseDown, isFrontTab);
  53284. fillTabButtonShape (g, tabShape, preferredColour,
  53285. tabIndex, text, button, orientation,
  53286. isMouseOver, isMouseDown, isFrontTab);
  53287. const int indent = getTabButtonOverlap (depth);
  53288. int x = 0, y = 0;
  53289. if (orientation == TabbedButtonBar::TabsAtLeft
  53290. || orientation == TabbedButtonBar::TabsAtRight)
  53291. {
  53292. y += indent;
  53293. h -= indent * 2;
  53294. }
  53295. else
  53296. {
  53297. x += indent;
  53298. w -= indent * 2;
  53299. }
  53300. drawTabButtonText (g, x, y, w, h, preferredColour,
  53301. tabIndex, text, button, orientation,
  53302. isMouseOver, isMouseDown, isFrontTab);
  53303. }
  53304. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  53305. int w, int h,
  53306. TabbedButtonBar& tabBar,
  53307. TabbedButtonBar::Orientation orientation)
  53308. {
  53309. const float shadowSize = 0.2f;
  53310. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  53311. Rectangle<int> shadowRect;
  53312. if (orientation == TabbedButtonBar::TabsAtLeft)
  53313. {
  53314. x1 = (float) w;
  53315. x2 = w * (1.0f - shadowSize);
  53316. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  53317. }
  53318. else if (orientation == TabbedButtonBar::TabsAtRight)
  53319. {
  53320. x2 = w * shadowSize;
  53321. shadowRect.setBounds (0, 0, (int) x2, h);
  53322. }
  53323. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53324. {
  53325. y2 = h * shadowSize;
  53326. shadowRect.setBounds (0, 0, w, (int) y2);
  53327. }
  53328. else
  53329. {
  53330. y1 = (float) h;
  53331. y2 = h * (1.0f - shadowSize);
  53332. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  53333. }
  53334. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  53335. Colours::transparentBlack, x2, y2, false));
  53336. shadowRect.expand (2, 2);
  53337. g.fillRect (shadowRect);
  53338. g.setColour (Colour (0x80000000));
  53339. if (orientation == TabbedButtonBar::TabsAtLeft)
  53340. {
  53341. g.fillRect (w - 1, 0, 1, h);
  53342. }
  53343. else if (orientation == TabbedButtonBar::TabsAtRight)
  53344. {
  53345. g.fillRect (0, 0, 1, h);
  53346. }
  53347. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53348. {
  53349. g.fillRect (0, 0, w, 1);
  53350. }
  53351. else
  53352. {
  53353. g.fillRect (0, h - 1, w, 1);
  53354. }
  53355. }
  53356. Button* LookAndFeel::createTabBarExtrasButton()
  53357. {
  53358. const float thickness = 7.0f;
  53359. const float indent = 22.0f;
  53360. Path p;
  53361. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  53362. DrawablePath ellipse;
  53363. ellipse.setPath (p);
  53364. ellipse.setFill (Colour (0x99ffffff));
  53365. p.clear();
  53366. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53367. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53368. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53369. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53370. p.setUsingNonZeroWinding (false);
  53371. DrawablePath dp;
  53372. dp.setPath (p);
  53373. dp.setFill (Colour (0x59000000));
  53374. DrawableComposite normalImage;
  53375. normalImage.insertDrawable (ellipse);
  53376. normalImage.insertDrawable (dp);
  53377. dp.setFill (Colour (0xcc000000));
  53378. DrawableComposite overImage;
  53379. overImage.insertDrawable (ellipse);
  53380. overImage.insertDrawable (dp);
  53381. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  53382. db->setImages (&normalImage, &overImage, 0);
  53383. return db;
  53384. }
  53385. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  53386. {
  53387. g.fillAll (Colours::white);
  53388. const int w = header.getWidth();
  53389. const int h = header.getHeight();
  53390. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  53391. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  53392. false));
  53393. g.fillRect (0, h / 2, w, h);
  53394. g.setColour (Colour (0x33000000));
  53395. g.fillRect (0, h - 1, w, 1);
  53396. for (int i = header.getNumColumns (true); --i >= 0;)
  53397. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  53398. }
  53399. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  53400. int width, int height,
  53401. bool isMouseOver, bool isMouseDown,
  53402. int columnFlags)
  53403. {
  53404. if (isMouseDown)
  53405. g.fillAll (Colour (0x8899aadd));
  53406. else if (isMouseOver)
  53407. g.fillAll (Colour (0x5599aadd));
  53408. int rightOfText = width - 4;
  53409. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  53410. {
  53411. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  53412. const float bottom = height - top;
  53413. const float w = height * 0.5f;
  53414. const float x = rightOfText - (w * 1.25f);
  53415. rightOfText = (int) x;
  53416. Path sortArrow;
  53417. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  53418. g.setColour (Colour (0x99000000));
  53419. g.fillPath (sortArrow);
  53420. }
  53421. g.setColour (Colours::black);
  53422. g.setFont (height * 0.5f, Font::bold);
  53423. const int textX = 4;
  53424. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  53425. }
  53426. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  53427. {
  53428. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  53429. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  53430. background.darker (0.1f),
  53431. toolbar.isVertical() ? w - 1.0f : 0.0f,
  53432. toolbar.isVertical() ? 0.0f : h - 1.0f,
  53433. false));
  53434. g.fillAll();
  53435. }
  53436. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  53437. {
  53438. return createTabBarExtrasButton();
  53439. }
  53440. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  53441. bool isMouseOver, bool isMouseDown,
  53442. ToolbarItemComponent& component)
  53443. {
  53444. if (isMouseDown)
  53445. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  53446. else if (isMouseOver)
  53447. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  53448. }
  53449. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  53450. const String& text, ToolbarItemComponent& component)
  53451. {
  53452. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  53453. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  53454. const float fontHeight = jmin (14.0f, height * 0.85f);
  53455. g.setFont (fontHeight);
  53456. g.drawFittedText (text,
  53457. x, y, width, height,
  53458. Justification::centred,
  53459. jmax (1, height / (int) fontHeight));
  53460. }
  53461. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  53462. bool isOpen, int width, int height)
  53463. {
  53464. const int buttonSize = (height * 3) / 4;
  53465. const int buttonIndent = (height - buttonSize) / 2;
  53466. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  53467. const int textX = buttonIndent * 2 + buttonSize + 2;
  53468. g.setColour (Colours::black);
  53469. g.setFont (height * 0.7f, Font::bold);
  53470. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  53471. }
  53472. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  53473. PropertyComponent&)
  53474. {
  53475. g.setColour (Colour (0x66ffffff));
  53476. g.fillRect (0, 0, width, height - 1);
  53477. }
  53478. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  53479. PropertyComponent& component)
  53480. {
  53481. g.setColour (Colours::black);
  53482. if (! component.isEnabled())
  53483. g.setOpacity (0.6f);
  53484. g.setFont (jmin (height, 24) * 0.65f);
  53485. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  53486. g.drawFittedText (component.getName(),
  53487. 3, r.getY(), r.getX() - 5, r.getHeight(),
  53488. Justification::centredLeft, 2);
  53489. }
  53490. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  53491. {
  53492. return Rectangle<int> (component.getWidth() / 3, 1,
  53493. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  53494. }
  53495. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  53496. {
  53497. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  53498. {
  53499. Graphics g2 (content);
  53500. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  53501. g2.fillPath (path);
  53502. g2.setColour (Colours::white.withAlpha (0.8f));
  53503. g2.strokePath (path, PathStrokeType (2.0f));
  53504. }
  53505. DropShadowEffect shadow;
  53506. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  53507. shadow.applyEffect (content, g);
  53508. }
  53509. void LookAndFeel::createFileChooserHeaderText (const String& title,
  53510. const String& instructions,
  53511. GlyphArrangement& text,
  53512. int width)
  53513. {
  53514. text.clear();
  53515. text.addJustifiedText (Font (17.0f, Font::bold), title,
  53516. 8.0f, 22.0f, width - 16.0f,
  53517. Justification::centred);
  53518. text.addJustifiedText (Font (14.0f), instructions,
  53519. 8.0f, 24.0f + 16.0f, width - 16.0f,
  53520. Justification::centred);
  53521. }
  53522. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  53523. const String& filename, Image* icon,
  53524. const String& fileSizeDescription,
  53525. const String& fileTimeDescription,
  53526. const bool isDirectory,
  53527. const bool isItemSelected,
  53528. const int /*itemIndex*/)
  53529. {
  53530. if (isItemSelected)
  53531. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  53532. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  53533. g.setFont (height * 0.7f);
  53534. Image im;
  53535. if (icon != 0)
  53536. im = *icon;
  53537. if (im.isNull())
  53538. im = isDirectory ? getDefaultFolderImage()
  53539. : getDefaultDocumentFileImage();
  53540. const int x = 32;
  53541. if (im.isValid())
  53542. {
  53543. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  53544. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  53545. false);
  53546. }
  53547. if (width > 450 && ! isDirectory)
  53548. {
  53549. const int sizeX = roundToInt (width * 0.7f);
  53550. const int dateX = roundToInt (width * 0.8f);
  53551. g.drawFittedText (filename,
  53552. x, 0, sizeX - x, height,
  53553. Justification::centredLeft, 1);
  53554. g.setFont (height * 0.5f);
  53555. g.setColour (Colours::darkgrey);
  53556. if (! isDirectory)
  53557. {
  53558. g.drawFittedText (fileSizeDescription,
  53559. sizeX, 0, dateX - sizeX - 8, height,
  53560. Justification::centredRight, 1);
  53561. g.drawFittedText (fileTimeDescription,
  53562. dateX, 0, width - 8 - dateX, height,
  53563. Justification::centredRight, 1);
  53564. }
  53565. }
  53566. else
  53567. {
  53568. g.drawFittedText (filename,
  53569. x, 0, width - x, height,
  53570. Justification::centredLeft, 1);
  53571. }
  53572. }
  53573. Button* LookAndFeel::createFileBrowserGoUpButton()
  53574. {
  53575. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  53576. Path arrowPath;
  53577. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  53578. DrawablePath arrowImage;
  53579. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  53580. arrowImage.setPath (arrowPath);
  53581. goUpButton->setImages (&arrowImage);
  53582. return goUpButton;
  53583. }
  53584. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  53585. DirectoryContentsDisplayComponent* fileListComponent,
  53586. FilePreviewComponent* previewComp,
  53587. ComboBox* currentPathBox,
  53588. TextEditor* filenameBox,
  53589. Button* goUpButton)
  53590. {
  53591. const int x = 8;
  53592. int w = browserComp.getWidth() - x - x;
  53593. if (previewComp != 0)
  53594. {
  53595. const int previewWidth = w / 3;
  53596. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  53597. w -= previewWidth + 4;
  53598. }
  53599. int y = 4;
  53600. const int controlsHeight = 22;
  53601. const int bottomSectionHeight = controlsHeight + 8;
  53602. const int upButtonWidth = 50;
  53603. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  53604. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  53605. y += controlsHeight + 4;
  53606. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  53607. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  53608. y = listAsComp->getBottom() + 4;
  53609. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  53610. }
  53611. const Image LookAndFeel::getDefaultFolderImage()
  53612. {
  53613. 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,
  53614. 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,
  53615. 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,
  53616. 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,
  53617. 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,
  53618. 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,
  53619. 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,
  53620. 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,
  53621. 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,
  53622. 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,
  53623. 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,
  53624. 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,
  53625. 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,
  53626. 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,
  53627. 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,
  53628. 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,
  53629. 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,
  53630. 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,
  53631. 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,
  53632. 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,
  53633. 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,
  53634. 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,
  53635. 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,
  53636. 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,
  53637. 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,
  53638. 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,
  53639. 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,
  53640. 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,
  53641. 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,
  53642. 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,
  53643. 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,
  53644. 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,
  53645. 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,
  53646. 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,
  53647. 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,
  53648. 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,
  53649. 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,
  53650. 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,
  53651. 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,
  53652. 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,
  53653. 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,
  53654. 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,
  53655. 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,
  53656. 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};
  53657. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  53658. }
  53659. const Image LookAndFeel::getDefaultDocumentFileImage()
  53660. {
  53661. 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,
  53662. 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,
  53663. 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,
  53664. 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,
  53665. 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,
  53666. 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,
  53667. 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,
  53668. 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,
  53669. 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,
  53670. 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,
  53671. 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,
  53672. 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,
  53673. 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,
  53674. 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,
  53675. 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,
  53676. 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,
  53677. 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,
  53678. 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,
  53679. 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,
  53680. 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,
  53681. 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,
  53682. 174,66,96,130,0,0};
  53683. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  53684. }
  53685. void LookAndFeel::playAlertSound()
  53686. {
  53687. PlatformUtilities::beep();
  53688. }
  53689. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  53690. {
  53691. g.setColour (Colours::white.withAlpha (0.7f));
  53692. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  53693. g.setColour (Colours::black.withAlpha (0.2f));
  53694. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  53695. const int totalBlocks = 7;
  53696. const int numBlocks = roundToInt (totalBlocks * level);
  53697. const float w = (width - 6.0f) / (float) totalBlocks;
  53698. for (int i = 0; i < totalBlocks; ++i)
  53699. {
  53700. if (i >= numBlocks)
  53701. g.setColour (Colours::lightblue.withAlpha (0.6f));
  53702. else
  53703. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  53704. : Colours::red);
  53705. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  53706. }
  53707. }
  53708. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  53709. {
  53710. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  53711. if (keyDescription.isNotEmpty())
  53712. {
  53713. if (button.isEnabled())
  53714. {
  53715. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  53716. g.fillAll (textColour.withAlpha (alpha));
  53717. g.setOpacity (0.3f);
  53718. g.drawBevel (0, 0, width, height, 2);
  53719. }
  53720. g.setColour (textColour);
  53721. g.setFont (height * 0.6f);
  53722. g.drawFittedText (keyDescription,
  53723. 3, 0, width - 6, height,
  53724. Justification::centred, 1);
  53725. }
  53726. else
  53727. {
  53728. const float thickness = 7.0f;
  53729. const float indent = 22.0f;
  53730. Path p;
  53731. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53732. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53733. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53734. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53735. p.setUsingNonZeroWinding (false);
  53736. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  53737. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  53738. }
  53739. if (button.hasKeyboardFocus (false))
  53740. {
  53741. g.setColour (textColour.withAlpha (0.4f));
  53742. g.drawRect (0, 0, width, height);
  53743. }
  53744. }
  53745. static void createRoundedPath (Path& p,
  53746. const float x, const float y,
  53747. const float w, const float h,
  53748. const float cs,
  53749. const bool curveTopLeft, const bool curveTopRight,
  53750. const bool curveBottomLeft, const bool curveBottomRight) throw()
  53751. {
  53752. const float cs2 = 2.0f * cs;
  53753. if (curveTopLeft)
  53754. {
  53755. p.startNewSubPath (x, y + cs);
  53756. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53757. }
  53758. else
  53759. {
  53760. p.startNewSubPath (x, y);
  53761. }
  53762. if (curveTopRight)
  53763. {
  53764. p.lineTo (x + w - cs, y);
  53765. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  53766. }
  53767. else
  53768. {
  53769. p.lineTo (x + w, y);
  53770. }
  53771. if (curveBottomRight)
  53772. {
  53773. p.lineTo (x + w, y + h - cs);
  53774. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53775. }
  53776. else
  53777. {
  53778. p.lineTo (x + w, y + h);
  53779. }
  53780. if (curveBottomLeft)
  53781. {
  53782. p.lineTo (x + cs, y + h);
  53783. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53784. }
  53785. else
  53786. {
  53787. p.lineTo (x, y + h);
  53788. }
  53789. p.closeSubPath();
  53790. }
  53791. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  53792. float x, float y, float w, float h,
  53793. float maxCornerSize,
  53794. const Colour& baseColour,
  53795. const float strokeWidth,
  53796. const bool flatOnLeft,
  53797. const bool flatOnRight,
  53798. const bool flatOnTop,
  53799. const bool flatOnBottom) throw()
  53800. {
  53801. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  53802. return;
  53803. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  53804. Path outline;
  53805. createRoundedPath (outline, x, y, w, h, cs,
  53806. ! (flatOnLeft || flatOnTop),
  53807. ! (flatOnRight || flatOnTop),
  53808. ! (flatOnLeft || flatOnBottom),
  53809. ! (flatOnRight || flatOnBottom));
  53810. ColourGradient cg (baseColour, 0.0f, y,
  53811. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  53812. false);
  53813. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  53814. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  53815. g.setGradientFill (cg);
  53816. g.fillPath (outline);
  53817. g.setColour (Colour (0x80000000));
  53818. g.strokePath (outline, PathStrokeType (strokeWidth));
  53819. }
  53820. void LookAndFeel::drawGlassSphere (Graphics& g,
  53821. const float x, const float y,
  53822. const float diameter,
  53823. const Colour& colour,
  53824. const float outlineThickness) throw()
  53825. {
  53826. if (diameter <= outlineThickness)
  53827. return;
  53828. Path p;
  53829. p.addEllipse (x, y, diameter, diameter);
  53830. {
  53831. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53832. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53833. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53834. g.setGradientFill (cg);
  53835. g.fillPath (p);
  53836. }
  53837. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  53838. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  53839. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  53840. ColourGradient cg (Colours::transparentBlack,
  53841. x + diameter * 0.5f, y + diameter * 0.5f,
  53842. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53843. x, y + diameter * 0.5f, true);
  53844. cg.addColour (0.7, Colours::transparentBlack);
  53845. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  53846. g.setGradientFill (cg);
  53847. g.fillPath (p);
  53848. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53849. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  53850. }
  53851. void LookAndFeel::drawGlassPointer (Graphics& g,
  53852. const float x, const float y,
  53853. const float diameter,
  53854. const Colour& colour, const float outlineThickness,
  53855. const int direction) throw()
  53856. {
  53857. if (diameter <= outlineThickness)
  53858. return;
  53859. Path p;
  53860. p.startNewSubPath (x + diameter * 0.5f, y);
  53861. p.lineTo (x + diameter, y + diameter * 0.6f);
  53862. p.lineTo (x + diameter, y + diameter);
  53863. p.lineTo (x, y + diameter);
  53864. p.lineTo (x, y + diameter * 0.6f);
  53865. p.closeSubPath();
  53866. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  53867. {
  53868. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53869. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53870. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53871. g.setGradientFill (cg);
  53872. g.fillPath (p);
  53873. }
  53874. ColourGradient cg (Colours::transparentBlack,
  53875. x + diameter * 0.5f, y + diameter * 0.5f,
  53876. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53877. x - diameter * 0.2f, y + diameter * 0.5f, true);
  53878. cg.addColour (0.5, Colours::transparentBlack);
  53879. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  53880. g.setGradientFill (cg);
  53881. g.fillPath (p);
  53882. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53883. g.strokePath (p, PathStrokeType (outlineThickness));
  53884. }
  53885. void LookAndFeel::drawGlassLozenge (Graphics& g,
  53886. const float x, const float y,
  53887. const float width, const float height,
  53888. const Colour& colour,
  53889. const float outlineThickness,
  53890. const float cornerSize,
  53891. const bool flatOnLeft,
  53892. const bool flatOnRight,
  53893. const bool flatOnTop,
  53894. const bool flatOnBottom) throw()
  53895. {
  53896. if (width <= outlineThickness || height <= outlineThickness)
  53897. return;
  53898. const int intX = (int) x;
  53899. const int intY = (int) y;
  53900. const int intW = (int) width;
  53901. const int intH = (int) height;
  53902. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  53903. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  53904. const int intEdge = (int) edgeBlurRadius;
  53905. Path outline;
  53906. createRoundedPath (outline, x, y, width, height, cs,
  53907. ! (flatOnLeft || flatOnTop),
  53908. ! (flatOnRight || flatOnTop),
  53909. ! (flatOnLeft || flatOnBottom),
  53910. ! (flatOnRight || flatOnBottom));
  53911. {
  53912. ColourGradient cg (colour.darker (0.2f), 0, y,
  53913. colour.darker (0.2f), 0, y + height, false);
  53914. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  53915. cg.addColour (0.4, colour);
  53916. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  53917. g.setGradientFill (cg);
  53918. g.fillPath (outline);
  53919. }
  53920. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  53921. colour.darker (0.2f), x, y + height * 0.5f, true);
  53922. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  53923. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  53924. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  53925. {
  53926. g.saveState();
  53927. g.setGradientFill (cg);
  53928. g.reduceClipRegion (intX, intY, intEdge, intH);
  53929. g.fillPath (outline);
  53930. g.restoreState();
  53931. }
  53932. if (! (flatOnRight || flatOnTop || flatOnBottom))
  53933. {
  53934. cg.point1.setX (x + width - edgeBlurRadius);
  53935. cg.point2.setX (x + width);
  53936. g.saveState();
  53937. g.setGradientFill (cg);
  53938. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  53939. g.fillPath (outline);
  53940. g.restoreState();
  53941. }
  53942. {
  53943. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  53944. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  53945. Path highlight;
  53946. createRoundedPath (highlight,
  53947. x + leftIndent,
  53948. y + cs * 0.1f,
  53949. width - (leftIndent + rightIndent),
  53950. height * 0.4f, cs * 0.4f,
  53951. ! (flatOnLeft || flatOnTop),
  53952. ! (flatOnRight || flatOnTop),
  53953. ! (flatOnLeft || flatOnBottom),
  53954. ! (flatOnRight || flatOnBottom));
  53955. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  53956. Colours::transparentWhite, 0, y + height * 0.4f, false));
  53957. g.fillPath (highlight);
  53958. }
  53959. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  53960. g.strokePath (outline, PathStrokeType (outlineThickness));
  53961. }
  53962. END_JUCE_NAMESPACE
  53963. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  53964. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  53965. BEGIN_JUCE_NAMESPACE
  53966. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  53967. {
  53968. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  53969. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  53970. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  53971. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  53972. setColour (Slider::thumbColourId, Colours::white);
  53973. setColour (Slider::trackColourId, Colour (0x7f000000));
  53974. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  53975. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  53976. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  53977. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  53978. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  53979. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  53980. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  53981. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  53982. }
  53983. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  53984. {
  53985. }
  53986. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  53987. Button& button,
  53988. const Colour& backgroundColour,
  53989. bool isMouseOverButton,
  53990. bool isButtonDown)
  53991. {
  53992. const int width = button.getWidth();
  53993. const int height = button.getHeight();
  53994. const float indent = 2.0f;
  53995. const int cornerSize = jmin (roundToInt (width * 0.4f),
  53996. roundToInt (height * 0.4f));
  53997. Path p;
  53998. p.addRoundedRectangle (indent, indent,
  53999. width - indent * 2.0f,
  54000. height - indent * 2.0f,
  54001. (float) cornerSize);
  54002. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54003. if (isMouseOverButton)
  54004. {
  54005. if (isButtonDown)
  54006. bc = bc.brighter();
  54007. else if (bc.getBrightness() > 0.5f)
  54008. bc = bc.darker (0.1f);
  54009. else
  54010. bc = bc.brighter (0.1f);
  54011. }
  54012. g.setColour (bc);
  54013. g.fillPath (p);
  54014. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54015. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54016. }
  54017. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54018. Component& /*component*/,
  54019. float x, float y, float w, float h,
  54020. const bool ticked,
  54021. const bool isEnabled,
  54022. const bool /*isMouseOverButton*/,
  54023. const bool isButtonDown)
  54024. {
  54025. Path box;
  54026. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54027. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54028. : Colours::lightgrey.withAlpha (0.1f));
  54029. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54030. g.fillPath (box, trans);
  54031. g.setColour (Colours::black.withAlpha (0.6f));
  54032. g.strokePath (box, PathStrokeType (0.9f), trans);
  54033. if (ticked)
  54034. {
  54035. Path tick;
  54036. tick.startNewSubPath (1.5f, 3.0f);
  54037. tick.lineTo (3.0f, 6.0f);
  54038. tick.lineTo (6.0f, 0.0f);
  54039. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54040. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54041. }
  54042. }
  54043. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54044. ToggleButton& button,
  54045. bool isMouseOverButton,
  54046. bool isButtonDown)
  54047. {
  54048. if (button.hasKeyboardFocus (true))
  54049. {
  54050. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54051. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54052. }
  54053. const int tickWidth = jmin (20, button.getHeight() - 4);
  54054. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54055. (float) tickWidth, (float) tickWidth,
  54056. button.getToggleState(),
  54057. button.isEnabled(),
  54058. isMouseOverButton,
  54059. isButtonDown);
  54060. g.setColour (button.findColour (ToggleButton::textColourId));
  54061. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54062. if (! button.isEnabled())
  54063. g.setOpacity (0.5f);
  54064. const int textX = tickWidth + 5;
  54065. g.drawFittedText (button.getButtonText(),
  54066. textX, 4,
  54067. button.getWidth() - textX - 2, button.getHeight() - 8,
  54068. Justification::centredLeft, 10);
  54069. }
  54070. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54071. int width, int height,
  54072. double progress, const String& textToShow)
  54073. {
  54074. if (progress < 0 || progress >= 1.0)
  54075. {
  54076. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54077. }
  54078. else
  54079. {
  54080. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54081. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54082. g.fillAll (background);
  54083. g.setColour (foreground);
  54084. g.fillRect (1, 1,
  54085. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54086. height - 2);
  54087. if (textToShow.isNotEmpty())
  54088. {
  54089. g.setColour (Colour::contrasting (background, foreground));
  54090. g.setFont (height * 0.6f);
  54091. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54092. }
  54093. }
  54094. }
  54095. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54096. ScrollBar& bar,
  54097. int width, int height,
  54098. int buttonDirection,
  54099. bool isScrollbarVertical,
  54100. bool isMouseOverButton,
  54101. bool isButtonDown)
  54102. {
  54103. if (isScrollbarVertical)
  54104. width -= 2;
  54105. else
  54106. height -= 2;
  54107. Path p;
  54108. if (buttonDirection == 0)
  54109. p.addTriangle (width * 0.5f, height * 0.2f,
  54110. width * 0.1f, height * 0.7f,
  54111. width * 0.9f, height * 0.7f);
  54112. else if (buttonDirection == 1)
  54113. p.addTriangle (width * 0.8f, height * 0.5f,
  54114. width * 0.3f, height * 0.1f,
  54115. width * 0.3f, height * 0.9f);
  54116. else if (buttonDirection == 2)
  54117. p.addTriangle (width * 0.5f, height * 0.8f,
  54118. width * 0.1f, height * 0.3f,
  54119. width * 0.9f, height * 0.3f);
  54120. else if (buttonDirection == 3)
  54121. p.addTriangle (width * 0.2f, height * 0.5f,
  54122. width * 0.7f, height * 0.1f,
  54123. width * 0.7f, height * 0.9f);
  54124. if (isButtonDown)
  54125. g.setColour (Colours::white);
  54126. else if (isMouseOverButton)
  54127. g.setColour (Colours::white.withAlpha (0.7f));
  54128. else
  54129. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54130. g.fillPath (p);
  54131. g.setColour (Colours::black.withAlpha (0.5f));
  54132. g.strokePath (p, PathStrokeType (0.5f));
  54133. }
  54134. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54135. ScrollBar& bar,
  54136. int x, int y,
  54137. int width, int height,
  54138. bool isScrollbarVertical,
  54139. int thumbStartPosition,
  54140. int thumbSize,
  54141. bool isMouseOver,
  54142. bool isMouseDown)
  54143. {
  54144. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54145. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54146. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54147. if (thumbSize > 0.0f)
  54148. {
  54149. Rectangle<int> thumb;
  54150. if (isScrollbarVertical)
  54151. {
  54152. width -= 2;
  54153. g.fillRect (x + roundToInt (width * 0.35f), y,
  54154. roundToInt (width * 0.3f), height);
  54155. thumb.setBounds (x + 1, thumbStartPosition,
  54156. width - 2, thumbSize);
  54157. }
  54158. else
  54159. {
  54160. height -= 2;
  54161. g.fillRect (x, y + roundToInt (height * 0.35f),
  54162. width, roundToInt (height * 0.3f));
  54163. thumb.setBounds (thumbStartPosition, y + 1,
  54164. thumbSize, height - 2);
  54165. }
  54166. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54167. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54168. g.fillRect (thumb);
  54169. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54170. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54171. if (thumbSize > 16)
  54172. {
  54173. for (int i = 3; --i >= 0;)
  54174. {
  54175. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54176. g.setColour (Colours::black.withAlpha (0.15f));
  54177. if (isScrollbarVertical)
  54178. {
  54179. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54180. g.setColour (Colours::white.withAlpha (0.15f));
  54181. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54182. }
  54183. else
  54184. {
  54185. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54186. g.setColour (Colours::white.withAlpha (0.15f));
  54187. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54188. }
  54189. }
  54190. }
  54191. }
  54192. }
  54193. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  54194. {
  54195. return &scrollbarShadow;
  54196. }
  54197. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  54198. {
  54199. g.fillAll (findColour (PopupMenu::backgroundColourId));
  54200. g.setColour (Colours::black.withAlpha (0.6f));
  54201. g.drawRect (0, 0, width, height);
  54202. }
  54203. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  54204. bool, MenuBarComponent& menuBar)
  54205. {
  54206. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  54207. }
  54208. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  54209. {
  54210. if (textEditor.isEnabled())
  54211. {
  54212. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  54213. g.drawRect (0, 0, width, height);
  54214. }
  54215. }
  54216. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  54217. const bool isButtonDown,
  54218. int buttonX, int buttonY,
  54219. int buttonW, int buttonH,
  54220. ComboBox& box)
  54221. {
  54222. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  54223. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  54224. : ComboBox::backgroundColourId));
  54225. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  54226. g.setColour (box.findColour (ComboBox::outlineColourId));
  54227. g.drawRect (0, 0, width, height);
  54228. const float arrowX = 0.2f;
  54229. const float arrowH = 0.3f;
  54230. if (box.isEnabled())
  54231. {
  54232. Path p;
  54233. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  54234. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  54235. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  54236. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  54237. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  54238. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  54239. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  54240. : ComboBox::buttonColourId));
  54241. g.fillPath (p);
  54242. }
  54243. }
  54244. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  54245. {
  54246. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  54247. f.setHorizontalScale (0.9f);
  54248. return f;
  54249. }
  54250. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54251. {
  54252. Path p;
  54253. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54254. g.setColour (fill);
  54255. g.fillPath (p);
  54256. g.setColour (outline);
  54257. g.strokePath (p, PathStrokeType (0.3f));
  54258. }
  54259. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54260. int x, int y,
  54261. int w, int h,
  54262. float sliderPos,
  54263. float minSliderPos,
  54264. float maxSliderPos,
  54265. const Slider::SliderStyle style,
  54266. Slider& slider)
  54267. {
  54268. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54269. if (style == Slider::LinearBar)
  54270. {
  54271. g.setColour (slider.findColour (Slider::thumbColourId));
  54272. g.fillRect (x, y, (int) sliderPos - x, h);
  54273. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54274. g.drawRect (x, y, (int) sliderPos - x, h);
  54275. }
  54276. else
  54277. {
  54278. g.setColour (slider.findColour (Slider::trackColourId)
  54279. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54280. if (slider.isHorizontal())
  54281. {
  54282. g.fillRect (x, y + roundToInt (h * 0.6f),
  54283. w, roundToInt (h * 0.2f));
  54284. }
  54285. else
  54286. {
  54287. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  54288. jmin (4, roundToInt (w * 0.2f)), h);
  54289. }
  54290. float alpha = 0.35f;
  54291. if (slider.isEnabled())
  54292. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  54293. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  54294. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  54295. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  54296. {
  54297. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  54298. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  54299. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  54300. fill, outline);
  54301. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  54302. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  54303. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  54304. fill, outline);
  54305. }
  54306. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  54307. {
  54308. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54309. minSliderPos - 7.0f, y + h * 0.9f ,
  54310. minSliderPos, y + h * 0.9f,
  54311. fill, outline);
  54312. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54313. maxSliderPos, y + h * 0.9f,
  54314. maxSliderPos + 7.0f, y + h * 0.9f,
  54315. fill, outline);
  54316. }
  54317. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  54318. {
  54319. drawTriangle (g, sliderPos, y + h * 0.9f,
  54320. sliderPos - 7.0f, y + h * 0.2f,
  54321. sliderPos + 7.0f, y + h * 0.2f,
  54322. fill, outline);
  54323. }
  54324. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  54325. {
  54326. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  54327. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  54328. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  54329. fill, outline);
  54330. }
  54331. }
  54332. }
  54333. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  54334. {
  54335. if (isIncrement)
  54336. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  54337. else
  54338. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  54339. }
  54340. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  54341. {
  54342. return &scrollbarShadow;
  54343. }
  54344. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  54345. {
  54346. return 8;
  54347. }
  54348. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  54349. int w, int h,
  54350. bool isMouseOver,
  54351. bool isMouseDragging)
  54352. {
  54353. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  54354. : Colours::darkgrey);
  54355. const float lineThickness = jmin (w, h) * 0.1f;
  54356. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  54357. {
  54358. g.drawLine (w * i,
  54359. h + 1.0f,
  54360. w + 1.0f,
  54361. h * i,
  54362. lineThickness);
  54363. }
  54364. }
  54365. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  54366. {
  54367. Path shape;
  54368. if (buttonType == DocumentWindow::closeButton)
  54369. {
  54370. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  54371. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  54372. ShapeButton* const b = new ShapeButton ("close",
  54373. Colour (0x7fff3333),
  54374. Colour (0xd7ff3333),
  54375. Colour (0xf7ff3333));
  54376. b->setShape (shape, true, true, true);
  54377. return b;
  54378. }
  54379. else if (buttonType == DocumentWindow::minimiseButton)
  54380. {
  54381. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54382. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  54383. DrawablePath dp;
  54384. dp.setPath (shape);
  54385. dp.setFill (Colours::black.withAlpha (0.3f));
  54386. b->setImages (&dp);
  54387. return b;
  54388. }
  54389. else if (buttonType == DocumentWindow::maximiseButton)
  54390. {
  54391. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  54392. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54393. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  54394. DrawablePath dp;
  54395. dp.setPath (shape);
  54396. dp.setFill (Colours::black.withAlpha (0.3f));
  54397. b->setImages (&dp);
  54398. return b;
  54399. }
  54400. jassertfalse;
  54401. return 0;
  54402. }
  54403. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  54404. int titleBarX,
  54405. int titleBarY,
  54406. int titleBarW,
  54407. int titleBarH,
  54408. Button* minimiseButton,
  54409. Button* maximiseButton,
  54410. Button* closeButton,
  54411. bool positionTitleBarButtonsOnLeft)
  54412. {
  54413. titleBarY += titleBarH / 8;
  54414. titleBarH -= titleBarH / 4;
  54415. const int buttonW = titleBarH;
  54416. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  54417. : titleBarX + titleBarW - buttonW - 4;
  54418. if (closeButton != 0)
  54419. {
  54420. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54421. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  54422. : -(buttonW + buttonW / 5);
  54423. }
  54424. if (positionTitleBarButtonsOnLeft)
  54425. swapVariables (minimiseButton, maximiseButton);
  54426. if (maximiseButton != 0)
  54427. {
  54428. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54429. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  54430. }
  54431. if (minimiseButton != 0)
  54432. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54433. }
  54434. END_JUCE_NAMESPACE
  54435. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54436. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  54437. BEGIN_JUCE_NAMESPACE
  54438. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  54439. : model (0),
  54440. itemUnderMouse (-1),
  54441. currentPopupIndex (-1),
  54442. topLevelIndexClicked (0),
  54443. lastMouseX (0),
  54444. lastMouseY (0)
  54445. {
  54446. setRepaintsOnMouseActivity (true);
  54447. setWantsKeyboardFocus (false);
  54448. setMouseClickGrabsKeyboardFocus (false);
  54449. setModel (model_);
  54450. }
  54451. MenuBarComponent::~MenuBarComponent()
  54452. {
  54453. setModel (0);
  54454. Desktop::getInstance().removeGlobalMouseListener (this);
  54455. }
  54456. MenuBarModel* MenuBarComponent::getModel() const throw()
  54457. {
  54458. return model;
  54459. }
  54460. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  54461. {
  54462. if (model != newModel)
  54463. {
  54464. if (model != 0)
  54465. model->removeListener (this);
  54466. model = newModel;
  54467. if (model != 0)
  54468. model->addListener (this);
  54469. repaint();
  54470. menuBarItemsChanged (0);
  54471. }
  54472. }
  54473. void MenuBarComponent::paint (Graphics& g)
  54474. {
  54475. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  54476. getLookAndFeel().drawMenuBarBackground (g,
  54477. getWidth(),
  54478. getHeight(),
  54479. isMouseOverBar,
  54480. *this);
  54481. if (model != 0)
  54482. {
  54483. for (int i = 0; i < menuNames.size(); ++i)
  54484. {
  54485. g.saveState();
  54486. g.setOrigin (xPositions [i], 0);
  54487. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  54488. getLookAndFeel().drawMenuBarItem (g,
  54489. xPositions[i + 1] - xPositions[i],
  54490. getHeight(),
  54491. i,
  54492. menuNames[i],
  54493. i == itemUnderMouse,
  54494. i == currentPopupIndex,
  54495. isMouseOverBar,
  54496. *this);
  54497. g.restoreState();
  54498. }
  54499. }
  54500. }
  54501. void MenuBarComponent::resized()
  54502. {
  54503. xPositions.clear();
  54504. int x = 2;
  54505. xPositions.add (x);
  54506. for (int i = 0; i < menuNames.size(); ++i)
  54507. {
  54508. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  54509. xPositions.add (x);
  54510. }
  54511. }
  54512. int MenuBarComponent::getItemAt (const int x, const int y)
  54513. {
  54514. for (int i = 0; i < xPositions.size(); ++i)
  54515. if (x >= xPositions[i] && x < xPositions[i + 1])
  54516. return reallyContains (x, y, true) ? i : -1;
  54517. return -1;
  54518. }
  54519. void MenuBarComponent::repaintMenuItem (int index)
  54520. {
  54521. if (((unsigned int) index) < (unsigned int) xPositions.size())
  54522. {
  54523. const int x1 = xPositions [index];
  54524. const int x2 = xPositions [index + 1];
  54525. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  54526. }
  54527. }
  54528. void MenuBarComponent::setItemUnderMouse (const int index)
  54529. {
  54530. if (itemUnderMouse != index)
  54531. {
  54532. repaintMenuItem (itemUnderMouse);
  54533. itemUnderMouse = index;
  54534. repaintMenuItem (itemUnderMouse);
  54535. }
  54536. }
  54537. void MenuBarComponent::setOpenItem (int index)
  54538. {
  54539. if (currentPopupIndex != index)
  54540. {
  54541. repaintMenuItem (currentPopupIndex);
  54542. currentPopupIndex = index;
  54543. repaintMenuItem (currentPopupIndex);
  54544. if (index >= 0)
  54545. Desktop::getInstance().addGlobalMouseListener (this);
  54546. else
  54547. Desktop::getInstance().removeGlobalMouseListener (this);
  54548. }
  54549. }
  54550. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  54551. {
  54552. setItemUnderMouse (getItemAt (x, y));
  54553. }
  54554. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  54555. {
  54556. public:
  54557. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  54558. : bar (bar_), topLevelIndex (topLevelIndex_)
  54559. {
  54560. }
  54561. ~AsyncCallback() {}
  54562. void modalStateFinished (int returnValue)
  54563. {
  54564. if (bar != 0)
  54565. bar->menuDismissed (topLevelIndex, returnValue);
  54566. }
  54567. private:
  54568. Component::SafePointer<MenuBarComponent> bar;
  54569. const int topLevelIndex;
  54570. AsyncCallback (const AsyncCallback&);
  54571. AsyncCallback& operator= (const AsyncCallback&);
  54572. };
  54573. void MenuBarComponent::showMenu (int index)
  54574. {
  54575. if (index != currentPopupIndex)
  54576. {
  54577. PopupMenu::dismissAllActiveMenus();
  54578. menuBarItemsChanged (0);
  54579. setOpenItem (index);
  54580. setItemUnderMouse (index);
  54581. if (index >= 0)
  54582. {
  54583. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  54584. menuNames [itemUnderMouse]));
  54585. if (m.lookAndFeel == 0)
  54586. m.setLookAndFeel (&getLookAndFeel());
  54587. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  54588. m.showMenu (itemPos + getScreenPosition(),
  54589. 0, itemPos.getWidth(), 0, 0, true, this,
  54590. new AsyncCallback (this, index));
  54591. }
  54592. }
  54593. }
  54594. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  54595. {
  54596. topLevelIndexClicked = topLevelIndex;
  54597. postCommandMessage (itemId);
  54598. }
  54599. void MenuBarComponent::handleCommandMessage (int commandId)
  54600. {
  54601. const Point<int> mousePos (getMouseXYRelative());
  54602. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54603. if (! isCurrentlyBlockedByAnotherModalComponent())
  54604. setOpenItem (-1);
  54605. if (commandId != 0 && model != 0)
  54606. model->menuItemSelected (commandId, topLevelIndexClicked);
  54607. }
  54608. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  54609. {
  54610. if (e.eventComponent == this)
  54611. updateItemUnderMouse (e.x, e.y);
  54612. }
  54613. void MenuBarComponent::mouseExit (const MouseEvent& e)
  54614. {
  54615. if (e.eventComponent == this)
  54616. updateItemUnderMouse (e.x, e.y);
  54617. }
  54618. void MenuBarComponent::mouseDown (const MouseEvent& e)
  54619. {
  54620. if (currentPopupIndex < 0)
  54621. {
  54622. const MouseEvent e2 (e.getEventRelativeTo (this));
  54623. updateItemUnderMouse (e2.x, e2.y);
  54624. currentPopupIndex = -2;
  54625. showMenu (itemUnderMouse);
  54626. }
  54627. }
  54628. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  54629. {
  54630. const MouseEvent e2 (e.getEventRelativeTo (this));
  54631. const int item = getItemAt (e2.x, e2.y);
  54632. if (item >= 0)
  54633. showMenu (item);
  54634. }
  54635. void MenuBarComponent::mouseUp (const MouseEvent& e)
  54636. {
  54637. const MouseEvent e2 (e.getEventRelativeTo (this));
  54638. updateItemUnderMouse (e2.x, e2.y);
  54639. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  54640. {
  54641. setOpenItem (-1);
  54642. PopupMenu::dismissAllActiveMenus();
  54643. }
  54644. }
  54645. void MenuBarComponent::mouseMove (const MouseEvent& e)
  54646. {
  54647. const MouseEvent e2 (e.getEventRelativeTo (this));
  54648. if (lastMouseX != e2.x || lastMouseY != e2.y)
  54649. {
  54650. if (currentPopupIndex >= 0)
  54651. {
  54652. const int item = getItemAt (e2.x, e2.y);
  54653. if (item >= 0)
  54654. showMenu (item);
  54655. }
  54656. else
  54657. {
  54658. updateItemUnderMouse (e2.x, e2.y);
  54659. }
  54660. lastMouseX = e2.x;
  54661. lastMouseY = e2.y;
  54662. }
  54663. }
  54664. bool MenuBarComponent::keyPressed (const KeyPress& key)
  54665. {
  54666. bool used = false;
  54667. const int numMenus = menuNames.size();
  54668. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  54669. if (key.isKeyCode (KeyPress::leftKey))
  54670. {
  54671. showMenu ((currentIndex + numMenus - 1) % numMenus);
  54672. used = true;
  54673. }
  54674. else if (key.isKeyCode (KeyPress::rightKey))
  54675. {
  54676. showMenu ((currentIndex + 1) % numMenus);
  54677. used = true;
  54678. }
  54679. return used;
  54680. }
  54681. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  54682. {
  54683. StringArray newNames;
  54684. if (model != 0)
  54685. newNames = model->getMenuBarNames();
  54686. if (newNames != menuNames)
  54687. {
  54688. menuNames = newNames;
  54689. repaint();
  54690. resized();
  54691. }
  54692. }
  54693. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  54694. const ApplicationCommandTarget::InvocationInfo& info)
  54695. {
  54696. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  54697. return;
  54698. for (int i = 0; i < menuNames.size(); ++i)
  54699. {
  54700. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  54701. if (menu.containsCommandItem (info.commandID))
  54702. {
  54703. setItemUnderMouse (i);
  54704. startTimer (200);
  54705. break;
  54706. }
  54707. }
  54708. }
  54709. void MenuBarComponent::timerCallback()
  54710. {
  54711. stopTimer();
  54712. const Point<int> mousePos (getMouseXYRelative());
  54713. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54714. }
  54715. END_JUCE_NAMESPACE
  54716. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  54717. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  54718. BEGIN_JUCE_NAMESPACE
  54719. MenuBarModel::MenuBarModel() throw()
  54720. : manager (0)
  54721. {
  54722. }
  54723. MenuBarModel::~MenuBarModel()
  54724. {
  54725. setApplicationCommandManagerToWatch (0);
  54726. }
  54727. void MenuBarModel::menuItemsChanged()
  54728. {
  54729. triggerAsyncUpdate();
  54730. }
  54731. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  54732. {
  54733. if (manager != newManager)
  54734. {
  54735. if (manager != 0)
  54736. manager->removeListener (this);
  54737. manager = newManager;
  54738. if (manager != 0)
  54739. manager->addListener (this);
  54740. }
  54741. }
  54742. void MenuBarModel::addListener (Listener* const newListener) throw()
  54743. {
  54744. listeners.add (newListener);
  54745. }
  54746. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  54747. {
  54748. // Trying to remove a listener that isn't on the list!
  54749. // If this assertion happens because this object is a dangling pointer, make sure you've not
  54750. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  54751. jassert (listeners.contains (listenerToRemove));
  54752. listeners.remove (listenerToRemove);
  54753. }
  54754. void MenuBarModel::handleAsyncUpdate()
  54755. {
  54756. listeners.call (&Listener::menuBarItemsChanged, this);
  54757. }
  54758. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  54759. {
  54760. listeners.call (&Listener::menuCommandInvoked, this, info);
  54761. }
  54762. void MenuBarModel::applicationCommandListChanged()
  54763. {
  54764. menuItemsChanged();
  54765. }
  54766. END_JUCE_NAMESPACE
  54767. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  54768. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  54769. BEGIN_JUCE_NAMESPACE
  54770. class PopupMenu::Item
  54771. {
  54772. public:
  54773. Item()
  54774. : itemId (0), active (true), isSeparator (true), isTicked (false),
  54775. usesColour (false), customComp (0), commandManager (0)
  54776. {
  54777. }
  54778. Item (const int itemId_,
  54779. const String& text_,
  54780. const bool active_,
  54781. const bool isTicked_,
  54782. const Image& im,
  54783. const Colour& textColour_,
  54784. const bool usesColour_,
  54785. PopupMenuCustomComponent* const customComp_,
  54786. const PopupMenu* const subMenu_,
  54787. ApplicationCommandManager* const commandManager_)
  54788. : itemId (itemId_), text (text_), textColour (textColour_),
  54789. active (active_), isSeparator (false), isTicked (isTicked_),
  54790. usesColour (usesColour_), image (im), customComp (customComp_),
  54791. commandManager (commandManager_)
  54792. {
  54793. if (subMenu_ != 0)
  54794. subMenu = new PopupMenu (*subMenu_);
  54795. if (commandManager_ != 0 && itemId_ != 0)
  54796. {
  54797. String shortcutKey;
  54798. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  54799. ->getKeyPressesAssignedToCommand (itemId_));
  54800. for (int i = 0; i < keyPresses.size(); ++i)
  54801. {
  54802. const String key (keyPresses.getReference(i).getTextDescription());
  54803. if (shortcutKey.isNotEmpty())
  54804. shortcutKey << ", ";
  54805. if (key.length() == 1)
  54806. shortcutKey << "shortcut: '" << key << '\'';
  54807. else
  54808. shortcutKey << key;
  54809. }
  54810. shortcutKey = shortcutKey.trim();
  54811. if (shortcutKey.isNotEmpty())
  54812. text << "<end>" << shortcutKey;
  54813. }
  54814. }
  54815. Item (const Item& other)
  54816. : itemId (other.itemId),
  54817. text (other.text),
  54818. textColour (other.textColour),
  54819. active (other.active),
  54820. isSeparator (other.isSeparator),
  54821. isTicked (other.isTicked),
  54822. usesColour (other.usesColour),
  54823. image (other.image),
  54824. customComp (other.customComp),
  54825. commandManager (other.commandManager)
  54826. {
  54827. if (other.subMenu != 0)
  54828. subMenu = new PopupMenu (*(other.subMenu));
  54829. }
  54830. ~Item()
  54831. {
  54832. customComp = 0;
  54833. }
  54834. bool canBeTriggered() const throw()
  54835. {
  54836. return active && ! (isSeparator || (subMenu != 0));
  54837. }
  54838. bool hasActiveSubMenu() const throw()
  54839. {
  54840. return active && (subMenu != 0);
  54841. }
  54842. const int itemId;
  54843. String text;
  54844. const Colour textColour;
  54845. const bool active, isSeparator, isTicked, usesColour;
  54846. Image image;
  54847. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  54848. ScopedPointer <PopupMenu> subMenu;
  54849. ApplicationCommandManager* const commandManager;
  54850. juce_UseDebuggingNewOperator
  54851. private:
  54852. Item& operator= (const Item&);
  54853. };
  54854. class PopupMenu::ItemComponent : public Component
  54855. {
  54856. public:
  54857. ItemComponent (const PopupMenu::Item& itemInfo_)
  54858. : itemInfo (itemInfo_),
  54859. isHighlighted (false)
  54860. {
  54861. if (itemInfo.customComp != 0)
  54862. addAndMakeVisible (itemInfo.customComp);
  54863. }
  54864. ~ItemComponent()
  54865. {
  54866. if (itemInfo.customComp != 0)
  54867. removeChildComponent (itemInfo.customComp);
  54868. }
  54869. void getIdealSize (int& idealWidth,
  54870. int& idealHeight,
  54871. const int standardItemHeight)
  54872. {
  54873. if (itemInfo.customComp != 0)
  54874. {
  54875. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  54876. }
  54877. else
  54878. {
  54879. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  54880. itemInfo.isSeparator,
  54881. standardItemHeight,
  54882. idealWidth,
  54883. idealHeight);
  54884. }
  54885. }
  54886. void paint (Graphics& g)
  54887. {
  54888. if (itemInfo.customComp == 0)
  54889. {
  54890. String mainText (itemInfo.text);
  54891. String endText;
  54892. const int endIndex = mainText.indexOf ("<end>");
  54893. if (endIndex >= 0)
  54894. {
  54895. endText = mainText.substring (endIndex + 5).trim();
  54896. mainText = mainText.substring (0, endIndex);
  54897. }
  54898. getLookAndFeel()
  54899. .drawPopupMenuItem (g, getWidth(), getHeight(),
  54900. itemInfo.isSeparator,
  54901. itemInfo.active,
  54902. isHighlighted,
  54903. itemInfo.isTicked,
  54904. itemInfo.subMenu != 0,
  54905. mainText, endText,
  54906. itemInfo.image.isValid() ? &itemInfo.image : 0,
  54907. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  54908. }
  54909. }
  54910. void resized()
  54911. {
  54912. if (getNumChildComponents() > 0)
  54913. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  54914. }
  54915. void setHighlighted (bool shouldBeHighlighted)
  54916. {
  54917. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  54918. if (isHighlighted != shouldBeHighlighted)
  54919. {
  54920. isHighlighted = shouldBeHighlighted;
  54921. if (itemInfo.customComp != 0)
  54922. {
  54923. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  54924. itemInfo.customComp->repaint();
  54925. }
  54926. repaint();
  54927. }
  54928. }
  54929. PopupMenu::Item itemInfo;
  54930. juce_UseDebuggingNewOperator
  54931. private:
  54932. bool isHighlighted;
  54933. ItemComponent (const ItemComponent&);
  54934. ItemComponent& operator= (const ItemComponent&);
  54935. };
  54936. namespace PopupMenuSettings
  54937. {
  54938. static const int scrollZone = 24;
  54939. static const int borderSize = 2;
  54940. static const int timerInterval = 50;
  54941. static const int dismissCommandId = 0x6287345f;
  54942. }
  54943. class PopupMenu::Window : public Component,
  54944. private Timer
  54945. {
  54946. public:
  54947. Window()
  54948. : Component ("menu"),
  54949. owner (0),
  54950. currentChild (0),
  54951. activeSubMenu (0),
  54952. managerOfChosenCommand (0),
  54953. minimumWidth (0),
  54954. maximumNumColumns (7),
  54955. standardItemHeight (0),
  54956. isOver (false),
  54957. hasBeenOver (false),
  54958. isDown (false),
  54959. needsToScroll (false),
  54960. hideOnExit (false),
  54961. disableMouseMoves (false),
  54962. hasAnyJuceCompHadFocus (false),
  54963. numColumns (0),
  54964. contentHeight (0),
  54965. childYOffset (0),
  54966. timeEnteredCurrentChildComp (0),
  54967. scrollAcceleration (1.0)
  54968. {
  54969. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  54970. setWantsKeyboardFocus (true);
  54971. setMouseClickGrabsKeyboardFocus (false);
  54972. setOpaque (true);
  54973. setAlwaysOnTop (true);
  54974. Desktop::getInstance().addGlobalMouseListener (this);
  54975. getActiveWindows().add (this);
  54976. }
  54977. ~Window()
  54978. {
  54979. getActiveWindows().removeValue (this);
  54980. Desktop::getInstance().removeGlobalMouseListener (this);
  54981. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54982. activeSubMenu = 0;
  54983. deleteAllChildren();
  54984. }
  54985. static Window* create (const PopupMenu& menu,
  54986. const bool dismissOnMouseUp,
  54987. Window* const owner_,
  54988. const Rectangle<int>& target,
  54989. const int minimumWidth,
  54990. const int maximumNumColumns,
  54991. const int standardItemHeight,
  54992. const bool alignToRectangle,
  54993. const int itemIdThatMustBeVisible,
  54994. ApplicationCommandManager** managerOfChosenCommand,
  54995. Component* const componentAttachedTo)
  54996. {
  54997. if (menu.items.size() > 0)
  54998. {
  54999. int totalItems = 0;
  55000. ScopedPointer <Window> mw (new Window());
  55001. mw->setLookAndFeel (menu.lookAndFeel);
  55002. mw->setWantsKeyboardFocus (false);
  55003. mw->minimumWidth = minimumWidth;
  55004. mw->maximumNumColumns = maximumNumColumns;
  55005. mw->standardItemHeight = standardItemHeight;
  55006. mw->dismissOnMouseUp = dismissOnMouseUp;
  55007. for (int i = 0; i < menu.items.size(); ++i)
  55008. {
  55009. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  55010. mw->addItem (*item);
  55011. ++totalItems;
  55012. }
  55013. if (totalItems > 0)
  55014. {
  55015. mw->owner = owner_;
  55016. mw->managerOfChosenCommand = managerOfChosenCommand;
  55017. mw->componentAttachedTo = componentAttachedTo;
  55018. mw->componentAttachedToOriginal = componentAttachedTo;
  55019. mw->calculateWindowPos (target, alignToRectangle);
  55020. mw->setTopLeftPosition (mw->windowPos.getX(),
  55021. mw->windowPos.getY());
  55022. mw->updateYPositions();
  55023. if (itemIdThatMustBeVisible != 0)
  55024. {
  55025. const int y = target.getY() - mw->windowPos.getY();
  55026. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  55027. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  55028. }
  55029. mw->resizeToBestWindowPos();
  55030. mw->addToDesktop (ComponentPeer::windowIsTemporary
  55031. | mw->getLookAndFeel().getMenuWindowFlags());
  55032. return mw.release();
  55033. }
  55034. }
  55035. return 0;
  55036. }
  55037. void paint (Graphics& g)
  55038. {
  55039. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55040. }
  55041. void paintOverChildren (Graphics& g)
  55042. {
  55043. if (isScrolling())
  55044. {
  55045. LookAndFeel& lf = getLookAndFeel();
  55046. if (isScrollZoneActive (false))
  55047. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55048. if (isScrollZoneActive (true))
  55049. {
  55050. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55051. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55052. }
  55053. }
  55054. }
  55055. bool isScrollZoneActive (bool bottomOne) const
  55056. {
  55057. return isScrolling()
  55058. && (bottomOne
  55059. ? childYOffset < contentHeight - windowPos.getHeight()
  55060. : childYOffset > 0);
  55061. }
  55062. void addItem (const PopupMenu::Item& item)
  55063. {
  55064. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  55065. addAndMakeVisible (mic);
  55066. int itemW = 80;
  55067. int itemH = 16;
  55068. mic->getIdealSize (itemW, itemH, standardItemHeight);
  55069. mic->setSize (itemW, jlimit (2, 600, itemH));
  55070. mic->addMouseListener (this, false);
  55071. }
  55072. // hide this and all sub-comps
  55073. void hide (const PopupMenu::Item* const item)
  55074. {
  55075. if (isVisible())
  55076. {
  55077. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55078. activeSubMenu = 0;
  55079. currentChild = 0;
  55080. exitModalState (item != 0 ? item->itemId : 0);
  55081. setVisible (false);
  55082. if (item != 0
  55083. && item->commandManager != 0
  55084. && item->itemId != 0)
  55085. {
  55086. *managerOfChosenCommand = item->commandManager;
  55087. }
  55088. }
  55089. }
  55090. void dismissMenu (const PopupMenu::Item* const item)
  55091. {
  55092. if (owner != 0)
  55093. {
  55094. owner->dismissMenu (item);
  55095. }
  55096. else
  55097. {
  55098. if (item != 0)
  55099. {
  55100. // need a copy of this on the stack as the one passed in will get deleted during this call
  55101. const PopupMenu::Item mi (*item);
  55102. hide (&mi);
  55103. }
  55104. else
  55105. {
  55106. hide (0);
  55107. }
  55108. }
  55109. }
  55110. void mouseMove (const MouseEvent&)
  55111. {
  55112. timerCallback();
  55113. }
  55114. void mouseDown (const MouseEvent&)
  55115. {
  55116. timerCallback();
  55117. }
  55118. void mouseDrag (const MouseEvent&)
  55119. {
  55120. timerCallback();
  55121. }
  55122. void mouseUp (const MouseEvent&)
  55123. {
  55124. timerCallback();
  55125. }
  55126. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55127. {
  55128. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55129. lastMouse = Point<int> (-1, -1);
  55130. }
  55131. bool keyPressed (const KeyPress& key)
  55132. {
  55133. if (key.isKeyCode (KeyPress::downKey))
  55134. {
  55135. selectNextItem (1);
  55136. }
  55137. else if (key.isKeyCode (KeyPress::upKey))
  55138. {
  55139. selectNextItem (-1);
  55140. }
  55141. else if (key.isKeyCode (KeyPress::leftKey))
  55142. {
  55143. if (owner != 0)
  55144. {
  55145. Component::SafePointer<Window> parentWindow (owner);
  55146. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55147. hide (0);
  55148. if (parentWindow != 0)
  55149. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55150. disableTimerUntilMouseMoves();
  55151. }
  55152. else if (componentAttachedTo != 0)
  55153. {
  55154. componentAttachedTo->keyPressed (key);
  55155. }
  55156. }
  55157. else if (key.isKeyCode (KeyPress::rightKey))
  55158. {
  55159. disableTimerUntilMouseMoves();
  55160. if (showSubMenuFor (currentChild))
  55161. {
  55162. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55163. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55164. activeSubMenu->selectNextItem (1);
  55165. }
  55166. else if (componentAttachedTo != 0)
  55167. {
  55168. componentAttachedTo->keyPressed (key);
  55169. }
  55170. }
  55171. else if (key.isKeyCode (KeyPress::returnKey))
  55172. {
  55173. triggerCurrentlyHighlightedItem();
  55174. }
  55175. else if (key.isKeyCode (KeyPress::escapeKey))
  55176. {
  55177. dismissMenu (0);
  55178. }
  55179. else
  55180. {
  55181. return false;
  55182. }
  55183. return true;
  55184. }
  55185. void inputAttemptWhenModal()
  55186. {
  55187. Component::SafePointer<Component> deletionChecker (this);
  55188. timerCallback();
  55189. if (deletionChecker != 0 && ! isOverAnyMenu())
  55190. {
  55191. if (componentAttachedTo != 0)
  55192. {
  55193. // we want to dismiss the menu, but if we do it synchronously, then
  55194. // the mouse-click will be allowed to pass through. That's good, except
  55195. // when the user clicks on the button that orginally popped the menu up,
  55196. // as they'll expect the menu to go away, and in fact it'll just
  55197. // come back. So only dismiss synchronously if they're not on the original
  55198. // comp that we're attached to.
  55199. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55200. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  55201. {
  55202. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55203. return;
  55204. }
  55205. }
  55206. dismissMenu (0);
  55207. }
  55208. }
  55209. void handleCommandMessage (int commandId)
  55210. {
  55211. Component::handleCommandMessage (commandId);
  55212. if (commandId == PopupMenuSettings::dismissCommandId)
  55213. dismissMenu (0);
  55214. }
  55215. void timerCallback()
  55216. {
  55217. if (! isVisible())
  55218. return;
  55219. if (componentAttachedTo != componentAttachedToOriginal)
  55220. {
  55221. dismissMenu (0);
  55222. return;
  55223. }
  55224. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55225. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55226. return;
  55227. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55228. // move rather than a real timer callback
  55229. const Point<int> globalMousePos (Desktop::getMousePosition());
  55230. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  55231. const uint32 now = Time::getMillisecondCounter();
  55232. if (now > timeEnteredCurrentChildComp + 100
  55233. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  55234. && currentChild->isValidComponent()
  55235. && (! disableMouseMoves)
  55236. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55237. {
  55238. showSubMenuFor (currentChild);
  55239. }
  55240. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55241. {
  55242. highlightItemUnderMouse (globalMousePos, localMousePos);
  55243. }
  55244. bool overScrollArea = false;
  55245. if (isScrolling()
  55246. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  55247. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55248. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55249. {
  55250. if (now > lastScroll + 20)
  55251. {
  55252. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55253. int amount = 0;
  55254. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  55255. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  55256. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55257. lastScroll = now;
  55258. }
  55259. overScrollArea = true;
  55260. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55261. }
  55262. else
  55263. {
  55264. scrollAcceleration = 1.0;
  55265. }
  55266. const bool wasDown = isDown;
  55267. bool isOverAny = isOverAnyMenu();
  55268. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55269. {
  55270. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55271. isOverAny = isOverAnyMenu();
  55272. }
  55273. if (hideOnExit && hasBeenOver && ! isOverAny)
  55274. {
  55275. hide (0);
  55276. }
  55277. else
  55278. {
  55279. isDown = hasBeenOver
  55280. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55281. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55282. bool anyFocused = Process::isForegroundProcess();
  55283. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55284. {
  55285. // because no component at all may have focus, our test here will
  55286. // only be triggered when something has focus and then loses it.
  55287. anyFocused = ! hasAnyJuceCompHadFocus;
  55288. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55289. {
  55290. if (ComponentPeer::getPeer (i)->isFocused())
  55291. {
  55292. anyFocused = true;
  55293. hasAnyJuceCompHadFocus = true;
  55294. break;
  55295. }
  55296. }
  55297. }
  55298. if (! anyFocused)
  55299. {
  55300. if (now > lastFocused + 10)
  55301. {
  55302. wasHiddenBecauseOfAppChange() = true;
  55303. dismissMenu (0);
  55304. return; // may have been deleted by the previous call..
  55305. }
  55306. }
  55307. else if (wasDown && now > menuCreationTime + 250
  55308. && ! (isDown || overScrollArea))
  55309. {
  55310. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55311. if (isOver)
  55312. {
  55313. triggerCurrentlyHighlightedItem();
  55314. }
  55315. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55316. {
  55317. dismissMenu (0);
  55318. }
  55319. return; // may have been deleted by the previous calls..
  55320. }
  55321. else
  55322. {
  55323. lastFocused = now;
  55324. }
  55325. }
  55326. }
  55327. static Array<Window*>& getActiveWindows()
  55328. {
  55329. static Array<Window*> activeMenuWindows;
  55330. return activeMenuWindows;
  55331. }
  55332. static bool& wasHiddenBecauseOfAppChange() throw()
  55333. {
  55334. static bool b = false;
  55335. return b;
  55336. }
  55337. juce_UseDebuggingNewOperator
  55338. private:
  55339. Window* owner;
  55340. PopupMenu::ItemComponent* currentChild;
  55341. ScopedPointer <Window> activeSubMenu;
  55342. ApplicationCommandManager** managerOfChosenCommand;
  55343. Component::SafePointer<Component> componentAttachedTo;
  55344. Component* componentAttachedToOriginal;
  55345. Rectangle<int> windowPos;
  55346. Point<int> lastMouse;
  55347. int minimumWidth, maximumNumColumns, standardItemHeight;
  55348. bool isOver, hasBeenOver, isDown, needsToScroll;
  55349. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55350. int numColumns, contentHeight, childYOffset;
  55351. Array <int> columnWidths;
  55352. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55353. double scrollAcceleration;
  55354. bool overlaps (const Rectangle<int>& r) const
  55355. {
  55356. return r.intersects (getBounds())
  55357. || (owner != 0 && owner->overlaps (r));
  55358. }
  55359. bool isOverAnyMenu() const
  55360. {
  55361. return (owner != 0) ? owner->isOverAnyMenu()
  55362. : isOverChildren();
  55363. }
  55364. bool isOverChildren() const
  55365. {
  55366. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55367. return isVisible()
  55368. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  55369. }
  55370. void updateMouseOverStatus (const Point<int>& globalMousePos)
  55371. {
  55372. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  55373. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  55374. if (activeSubMenu != 0)
  55375. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55376. }
  55377. bool treeContains (const Window* const window) const throw()
  55378. {
  55379. const Window* mw = this;
  55380. while (mw->owner != 0)
  55381. mw = mw->owner;
  55382. while (mw != 0)
  55383. {
  55384. if (mw == window)
  55385. return true;
  55386. mw = mw->activeSubMenu;
  55387. }
  55388. return false;
  55389. }
  55390. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  55391. {
  55392. const Rectangle<int> mon (Desktop::getInstance()
  55393. .getMonitorAreaContaining (target.getCentre(),
  55394. #if JUCE_MAC
  55395. true));
  55396. #else
  55397. false)); // on windows, don't stop the menu overlapping the taskbar
  55398. #endif
  55399. int x, y, widthToUse, heightToUse;
  55400. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  55401. if (alignToRectangle)
  55402. {
  55403. x = target.getX();
  55404. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  55405. const int spaceOver = target.getY() - mon.getY();
  55406. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  55407. y = target.getBottom();
  55408. else
  55409. y = target.getY() - heightToUse;
  55410. }
  55411. else
  55412. {
  55413. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  55414. if (owner != 0)
  55415. {
  55416. if (owner->owner != 0)
  55417. {
  55418. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  55419. > owner->owner->getX() + owner->owner->getWidth() / 2);
  55420. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  55421. tendTowardsRight = true;
  55422. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  55423. tendTowardsRight = false;
  55424. }
  55425. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  55426. {
  55427. tendTowardsRight = true;
  55428. }
  55429. }
  55430. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  55431. target.getX() - mon.getX()) - 32;
  55432. if (biggestSpace < widthToUse)
  55433. {
  55434. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  55435. if (numColumns > 1)
  55436. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  55437. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  55438. }
  55439. if (tendTowardsRight)
  55440. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  55441. else
  55442. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  55443. y = target.getY();
  55444. if (target.getCentreY() > mon.getCentreY())
  55445. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  55446. }
  55447. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  55448. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  55449. windowPos.setBounds (x, y, widthToUse, heightToUse);
  55450. // sets this flag if it's big enough to obscure any of its parent menus
  55451. hideOnExit = (owner != 0)
  55452. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  55453. }
  55454. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  55455. {
  55456. numColumns = 0;
  55457. contentHeight = 0;
  55458. const int maxMenuH = getParentHeight() - 24;
  55459. int totalW;
  55460. do
  55461. {
  55462. ++numColumns;
  55463. totalW = workOutBestSize (maxMenuW);
  55464. if (totalW > maxMenuW)
  55465. {
  55466. numColumns = jmax (1, numColumns - 1);
  55467. totalW = workOutBestSize (maxMenuW); // to update col widths
  55468. break;
  55469. }
  55470. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  55471. {
  55472. break;
  55473. }
  55474. } while (numColumns < maximumNumColumns);
  55475. const int actualH = jmin (contentHeight, maxMenuH);
  55476. needsToScroll = contentHeight > actualH;
  55477. width = updateYPositions();
  55478. height = actualH + PopupMenuSettings::borderSize * 2;
  55479. }
  55480. int workOutBestSize (const int maxMenuW)
  55481. {
  55482. int totalW = 0;
  55483. contentHeight = 0;
  55484. int childNum = 0;
  55485. for (int col = 0; col < numColumns; ++col)
  55486. {
  55487. int i, colW = 50, colH = 0;
  55488. const int numChildren = jmin (getNumChildComponents() - childNum,
  55489. (getNumChildComponents() + numColumns - 1) / numColumns);
  55490. for (i = numChildren; --i >= 0;)
  55491. {
  55492. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  55493. colH += getChildComponent (childNum + i)->getHeight();
  55494. }
  55495. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  55496. columnWidths.set (col, colW);
  55497. totalW += colW;
  55498. contentHeight = jmax (contentHeight, colH);
  55499. childNum += numChildren;
  55500. }
  55501. if (totalW < minimumWidth)
  55502. {
  55503. totalW = minimumWidth;
  55504. for (int col = 0; col < numColumns; ++col)
  55505. columnWidths.set (0, totalW / numColumns);
  55506. }
  55507. return totalW;
  55508. }
  55509. void ensureItemIsVisible (const int itemId, int wantedY)
  55510. {
  55511. jassert (itemId != 0)
  55512. for (int i = getNumChildComponents(); --i >= 0;)
  55513. {
  55514. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  55515. if (m != 0
  55516. && m->itemInfo.itemId == itemId
  55517. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  55518. {
  55519. const int currentY = m->getY();
  55520. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  55521. {
  55522. if (wantedY < 0)
  55523. wantedY = jlimit (PopupMenuSettings::scrollZone,
  55524. jmax (PopupMenuSettings::scrollZone,
  55525. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  55526. currentY);
  55527. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  55528. int deltaY = wantedY - currentY;
  55529. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  55530. jmin (windowPos.getHeight(), mon.getHeight()));
  55531. const int newY = jlimit (mon.getY(),
  55532. mon.getBottom() - windowPos.getHeight(),
  55533. windowPos.getY() + deltaY);
  55534. deltaY -= newY - windowPos.getY();
  55535. childYOffset -= deltaY;
  55536. windowPos.setPosition (windowPos.getX(), newY);
  55537. updateYPositions();
  55538. }
  55539. break;
  55540. }
  55541. }
  55542. }
  55543. void resizeToBestWindowPos()
  55544. {
  55545. Rectangle<int> r (windowPos);
  55546. if (childYOffset < 0)
  55547. {
  55548. r.setBounds (r.getX(), r.getY() - childYOffset,
  55549. r.getWidth(), r.getHeight() + childYOffset);
  55550. }
  55551. else if (childYOffset > 0)
  55552. {
  55553. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  55554. if (spaceAtBottom > 0)
  55555. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  55556. }
  55557. setBounds (r);
  55558. updateYPositions();
  55559. }
  55560. void alterChildYPos (const int delta)
  55561. {
  55562. if (isScrolling())
  55563. {
  55564. childYOffset += delta;
  55565. if (delta < 0)
  55566. {
  55567. childYOffset = jmax (childYOffset, 0);
  55568. }
  55569. else if (delta > 0)
  55570. {
  55571. childYOffset = jmin (childYOffset,
  55572. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  55573. }
  55574. updateYPositions();
  55575. }
  55576. else
  55577. {
  55578. childYOffset = 0;
  55579. }
  55580. resizeToBestWindowPos();
  55581. repaint();
  55582. }
  55583. int updateYPositions()
  55584. {
  55585. int x = 0;
  55586. int childNum = 0;
  55587. for (int col = 0; col < numColumns; ++col)
  55588. {
  55589. const int numChildren = jmin (getNumChildComponents() - childNum,
  55590. (getNumChildComponents() + numColumns - 1) / numColumns);
  55591. const int colW = columnWidths [col];
  55592. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  55593. for (int i = 0; i < numChildren; ++i)
  55594. {
  55595. Component* const c = getChildComponent (childNum + i);
  55596. c->setBounds (x, y, colW, c->getHeight());
  55597. y += c->getHeight();
  55598. }
  55599. x += colW;
  55600. childNum += numChildren;
  55601. }
  55602. return x;
  55603. }
  55604. bool isScrolling() const throw()
  55605. {
  55606. return childYOffset != 0 || needsToScroll;
  55607. }
  55608. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  55609. {
  55610. if (currentChild->isValidComponent())
  55611. currentChild->setHighlighted (false);
  55612. currentChild = child;
  55613. if (currentChild != 0)
  55614. {
  55615. currentChild->setHighlighted (true);
  55616. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  55617. }
  55618. }
  55619. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  55620. {
  55621. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55622. activeSubMenu = 0;
  55623. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  55624. {
  55625. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  55626. dismissOnMouseUp,
  55627. this,
  55628. childComp->getScreenBounds(),
  55629. 0, maximumNumColumns,
  55630. standardItemHeight,
  55631. false, 0, managerOfChosenCommand,
  55632. componentAttachedTo);
  55633. if (activeSubMenu != 0)
  55634. {
  55635. activeSubMenu->setVisible (true);
  55636. activeSubMenu->enterModalState (false);
  55637. activeSubMenu->toFront (false);
  55638. return true;
  55639. }
  55640. }
  55641. return false;
  55642. }
  55643. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  55644. {
  55645. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55646. if (isOver)
  55647. hasBeenOver = true;
  55648. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  55649. {
  55650. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  55651. if (disableMouseMoves && isOver)
  55652. disableMouseMoves = false;
  55653. }
  55654. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  55655. return;
  55656. bool isMovingTowardsMenu = false;
  55657. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  55658. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  55659. {
  55660. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  55661. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  55662. // extends from the last mouse pos to the submenu's rectangle..
  55663. float subX = (float) activeSubMenu->getScreenX();
  55664. if (activeSubMenu->getX() > getX())
  55665. {
  55666. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  55667. }
  55668. else
  55669. {
  55670. lastMouse += Point<int> (2, 0);
  55671. subX += activeSubMenu->getWidth();
  55672. }
  55673. Path areaTowardsSubMenu;
  55674. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  55675. (float) lastMouse.getY(),
  55676. subX,
  55677. (float) activeSubMenu->getScreenY(),
  55678. subX,
  55679. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  55680. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  55681. }
  55682. lastMouse = globalMousePos;
  55683. if (! isMovingTowardsMenu)
  55684. {
  55685. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  55686. if (c == this)
  55687. c = 0;
  55688. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  55689. if (mic == 0 && c != 0)
  55690. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  55691. if (mic != currentChild
  55692. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  55693. {
  55694. if (isOver && (c != 0) && (activeSubMenu != 0))
  55695. {
  55696. activeSubMenu->hide (0);
  55697. }
  55698. if (! isOver)
  55699. mic = 0;
  55700. setCurrentlyHighlightedChild (mic);
  55701. }
  55702. }
  55703. }
  55704. void triggerCurrentlyHighlightedItem()
  55705. {
  55706. if (currentChild->isValidComponent()
  55707. && currentChild->itemInfo.canBeTriggered()
  55708. && (currentChild->itemInfo.customComp == 0
  55709. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  55710. {
  55711. dismissMenu (&currentChild->itemInfo);
  55712. }
  55713. }
  55714. void selectNextItem (const int delta)
  55715. {
  55716. disableTimerUntilMouseMoves();
  55717. PopupMenu::ItemComponent* mic = 0;
  55718. bool wasLastOne = (currentChild == 0);
  55719. const int numItems = getNumChildComponents();
  55720. for (int i = 0; i < numItems + 1; ++i)
  55721. {
  55722. int index = (delta > 0) ? i : (numItems - 1 - i);
  55723. index = (index + numItems) % numItems;
  55724. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  55725. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  55726. && wasLastOne)
  55727. break;
  55728. if (mic == currentChild)
  55729. wasLastOne = true;
  55730. }
  55731. setCurrentlyHighlightedChild (mic);
  55732. }
  55733. void disableTimerUntilMouseMoves()
  55734. {
  55735. disableMouseMoves = true;
  55736. if (owner != 0)
  55737. owner->disableTimerUntilMouseMoves();
  55738. }
  55739. Window (const Window&);
  55740. Window& operator= (const Window&);
  55741. };
  55742. PopupMenu::PopupMenu()
  55743. : lookAndFeel (0),
  55744. separatorPending (false)
  55745. {
  55746. }
  55747. PopupMenu::PopupMenu (const PopupMenu& other)
  55748. : lookAndFeel (other.lookAndFeel),
  55749. separatorPending (false)
  55750. {
  55751. items.addCopiesOf (other.items);
  55752. }
  55753. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  55754. {
  55755. if (this != &other)
  55756. {
  55757. lookAndFeel = other.lookAndFeel;
  55758. clear();
  55759. items.addCopiesOf (other.items);
  55760. }
  55761. return *this;
  55762. }
  55763. PopupMenu::~PopupMenu()
  55764. {
  55765. clear();
  55766. }
  55767. void PopupMenu::clear()
  55768. {
  55769. items.clear();
  55770. separatorPending = false;
  55771. }
  55772. void PopupMenu::addSeparatorIfPending()
  55773. {
  55774. if (separatorPending)
  55775. {
  55776. separatorPending = false;
  55777. if (items.size() > 0)
  55778. items.add (new Item());
  55779. }
  55780. }
  55781. void PopupMenu::addItem (const int itemResultId,
  55782. const String& itemText,
  55783. const bool isActive,
  55784. const bool isTicked,
  55785. const Image& iconToUse)
  55786. {
  55787. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55788. // didn't pick anything, so you shouldn't use it as the id
  55789. // for an item..
  55790. addSeparatorIfPending();
  55791. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  55792. Colours::black, false, 0, 0, 0));
  55793. }
  55794. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  55795. const int commandID,
  55796. const String& displayName)
  55797. {
  55798. jassert (commandManager != 0 && commandID != 0);
  55799. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  55800. if (registeredInfo != 0)
  55801. {
  55802. ApplicationCommandInfo info (*registeredInfo);
  55803. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  55804. addSeparatorIfPending();
  55805. items.add (new Item (commandID,
  55806. displayName.isNotEmpty() ? displayName
  55807. : info.shortName,
  55808. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  55809. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  55810. Image::null,
  55811. Colours::black,
  55812. false,
  55813. 0, 0,
  55814. commandManager));
  55815. }
  55816. }
  55817. void PopupMenu::addColouredItem (const int itemResultId,
  55818. const String& itemText,
  55819. const Colour& itemTextColour,
  55820. const bool isActive,
  55821. const bool isTicked,
  55822. const Image& iconToUse)
  55823. {
  55824. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55825. // didn't pick anything, so you shouldn't use it as the id
  55826. // for an item..
  55827. addSeparatorIfPending();
  55828. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  55829. itemTextColour, true, 0, 0, 0));
  55830. }
  55831. void PopupMenu::addCustomItem (const int itemResultId,
  55832. PopupMenuCustomComponent* const customComponent)
  55833. {
  55834. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55835. // didn't pick anything, so you shouldn't use it as the id
  55836. // for an item..
  55837. addSeparatorIfPending();
  55838. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  55839. Colours::black, false, customComponent, 0, 0));
  55840. }
  55841. class NormalComponentWrapper : public PopupMenuCustomComponent
  55842. {
  55843. public:
  55844. NormalComponentWrapper (Component* const comp,
  55845. const int w, const int h,
  55846. const bool triggerMenuItemAutomaticallyWhenClicked)
  55847. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  55848. width (w),
  55849. height (h)
  55850. {
  55851. addAndMakeVisible (comp);
  55852. }
  55853. ~NormalComponentWrapper() {}
  55854. void getIdealSize (int& idealWidth, int& idealHeight)
  55855. {
  55856. idealWidth = width;
  55857. idealHeight = height;
  55858. }
  55859. void resized()
  55860. {
  55861. if (getChildComponent(0) != 0)
  55862. getChildComponent(0)->setBounds (getLocalBounds());
  55863. }
  55864. juce_UseDebuggingNewOperator
  55865. private:
  55866. const int width, height;
  55867. NormalComponentWrapper (const NormalComponentWrapper&);
  55868. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  55869. };
  55870. void PopupMenu::addCustomItem (const int itemResultId,
  55871. Component* customComponent,
  55872. int idealWidth, int idealHeight,
  55873. const bool triggerMenuItemAutomaticallyWhenClicked)
  55874. {
  55875. addCustomItem (itemResultId,
  55876. new NormalComponentWrapper (customComponent,
  55877. idealWidth, idealHeight,
  55878. triggerMenuItemAutomaticallyWhenClicked));
  55879. }
  55880. void PopupMenu::addSubMenu (const String& subMenuName,
  55881. const PopupMenu& subMenu,
  55882. const bool isActive,
  55883. const Image& iconToUse,
  55884. const bool isTicked)
  55885. {
  55886. addSeparatorIfPending();
  55887. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  55888. iconToUse, Colours::black, false, 0, &subMenu, 0));
  55889. }
  55890. void PopupMenu::addSeparator()
  55891. {
  55892. separatorPending = true;
  55893. }
  55894. class HeaderItemComponent : public PopupMenuCustomComponent
  55895. {
  55896. public:
  55897. HeaderItemComponent (const String& name)
  55898. : PopupMenuCustomComponent (false)
  55899. {
  55900. setName (name);
  55901. }
  55902. ~HeaderItemComponent()
  55903. {
  55904. }
  55905. void paint (Graphics& g)
  55906. {
  55907. Font f (getLookAndFeel().getPopupMenuFont());
  55908. f.setBold (true);
  55909. g.setFont (f);
  55910. g.setColour (findColour (PopupMenu::headerTextColourId));
  55911. g.drawFittedText (getName(),
  55912. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  55913. Justification::bottomLeft, 1);
  55914. }
  55915. void getIdealSize (int& idealWidth,
  55916. int& idealHeight)
  55917. {
  55918. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  55919. idealHeight += idealHeight / 2;
  55920. idealWidth += idealWidth / 4;
  55921. }
  55922. juce_UseDebuggingNewOperator
  55923. };
  55924. void PopupMenu::addSectionHeader (const String& title)
  55925. {
  55926. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  55927. }
  55928. // This invokes any command manager commands and deletes the menu window when it is dismissed
  55929. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  55930. {
  55931. public:
  55932. PopupMenuCompletionCallback()
  55933. : managerOfChosenCommand (0)
  55934. {
  55935. }
  55936. ~PopupMenuCompletionCallback() {}
  55937. void modalStateFinished (int result)
  55938. {
  55939. if (managerOfChosenCommand != 0 && result != 0)
  55940. {
  55941. ApplicationCommandTarget::InvocationInfo info (result);
  55942. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  55943. managerOfChosenCommand->invoke (info, true);
  55944. }
  55945. }
  55946. ApplicationCommandManager* managerOfChosenCommand;
  55947. ScopedPointer<Component> component;
  55948. private:
  55949. PopupMenuCompletionCallback (const PopupMenuCompletionCallback&);
  55950. PopupMenuCompletionCallback& operator= (const PopupMenuCompletionCallback&);
  55951. };
  55952. int PopupMenu::showMenu (const Rectangle<int>& target,
  55953. const int itemIdThatMustBeVisible,
  55954. const int minimumWidth,
  55955. const int maximumNumColumns,
  55956. const int standardItemHeight,
  55957. const bool alignToRectangle,
  55958. Component* const componentAttachedTo,
  55959. ModalComponentManager::Callback* userCallback)
  55960. {
  55961. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  55962. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  55963. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  55964. Window::wasHiddenBecauseOfAppChange() = false;
  55965. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  55966. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  55967. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  55968. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  55969. standardItemHeight, alignToRectangle, itemIdThatMustBeVisible,
  55970. &callback->managerOfChosenCommand, componentAttachedTo);
  55971. if (callback->component == 0)
  55972. return 0;
  55973. callbackDeleter.release();
  55974. callback->component->enterModalState (false, userCallbackDeleter.release());
  55975. callback->component->toFront (false); // need to do this after making it modal, or it could
  55976. // be stuck behind other comps that are already modal..
  55977. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  55978. if (userCallback != 0)
  55979. return 0;
  55980. const int result = callback->component->runModalLoop();
  55981. if (! Window::wasHiddenBecauseOfAppChange())
  55982. {
  55983. if (prevTopLevel != 0)
  55984. prevTopLevel->toFront (true);
  55985. if (prevFocused != 0)
  55986. prevFocused->grabKeyboardFocus();
  55987. }
  55988. return result;
  55989. }
  55990. int PopupMenu::show (const int itemIdThatMustBeVisible,
  55991. const int minimumWidth,
  55992. const int maximumNumColumns,
  55993. const int standardItemHeight,
  55994. ModalComponentManager::Callback* callback)
  55995. {
  55996. const Point<int> mousePos (Desktop::getMousePosition());
  55997. return showAt (mousePos.getX(), mousePos.getY(),
  55998. itemIdThatMustBeVisible,
  55999. minimumWidth,
  56000. maximumNumColumns,
  56001. standardItemHeight,
  56002. callback);
  56003. }
  56004. int PopupMenu::showAt (const int screenX,
  56005. const int screenY,
  56006. const int itemIdThatMustBeVisible,
  56007. const int minimumWidth,
  56008. const int maximumNumColumns,
  56009. const int standardItemHeight,
  56010. ModalComponentManager::Callback* callback)
  56011. {
  56012. return showMenu (Rectangle<int> (screenX, screenY, 1, 1),
  56013. itemIdThatMustBeVisible,
  56014. minimumWidth, maximumNumColumns,
  56015. standardItemHeight,
  56016. false, 0, callback);
  56017. }
  56018. int PopupMenu::showAt (Component* componentToAttachTo,
  56019. const int itemIdThatMustBeVisible,
  56020. const int minimumWidth,
  56021. const int maximumNumColumns,
  56022. const int standardItemHeight,
  56023. ModalComponentManager::Callback* callback)
  56024. {
  56025. if (componentToAttachTo != 0)
  56026. {
  56027. return showMenu (componentToAttachTo->getScreenBounds(),
  56028. itemIdThatMustBeVisible,
  56029. minimumWidth,
  56030. maximumNumColumns,
  56031. standardItemHeight,
  56032. true, componentToAttachTo, callback);
  56033. }
  56034. else
  56035. {
  56036. return show (itemIdThatMustBeVisible,
  56037. minimumWidth,
  56038. maximumNumColumns,
  56039. standardItemHeight,
  56040. callback);
  56041. }
  56042. }
  56043. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56044. {
  56045. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  56046. {
  56047. Window* const pmw = Window::getActiveWindows()[i];
  56048. if (pmw != 0)
  56049. pmw->dismissMenu (0);
  56050. }
  56051. }
  56052. int PopupMenu::getNumItems() const throw()
  56053. {
  56054. int num = 0;
  56055. for (int i = items.size(); --i >= 0;)
  56056. if (! (items.getUnchecked(i))->isSeparator)
  56057. ++num;
  56058. return num;
  56059. }
  56060. bool PopupMenu::containsCommandItem (const int commandID) const
  56061. {
  56062. for (int i = items.size(); --i >= 0;)
  56063. {
  56064. const Item* mi = items.getUnchecked (i);
  56065. if ((mi->itemId == commandID && mi->commandManager != 0)
  56066. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56067. {
  56068. return true;
  56069. }
  56070. }
  56071. return false;
  56072. }
  56073. bool PopupMenu::containsAnyActiveItems() const throw()
  56074. {
  56075. for (int i = items.size(); --i >= 0;)
  56076. {
  56077. const Item* const mi = items.getUnchecked (i);
  56078. if (mi->subMenu != 0)
  56079. {
  56080. if (mi->subMenu->containsAnyActiveItems())
  56081. return true;
  56082. }
  56083. else if (mi->active)
  56084. {
  56085. return true;
  56086. }
  56087. }
  56088. return false;
  56089. }
  56090. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56091. {
  56092. lookAndFeel = newLookAndFeel;
  56093. }
  56094. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  56095. : isHighlighted (false),
  56096. isTriggeredAutomatically (isTriggeredAutomatically_)
  56097. {
  56098. }
  56099. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  56100. {
  56101. }
  56102. void PopupMenuCustomComponent::triggerMenuItem()
  56103. {
  56104. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56105. if (mic != 0)
  56106. {
  56107. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56108. if (pmw != 0)
  56109. {
  56110. pmw->dismissMenu (&mic->itemInfo);
  56111. }
  56112. else
  56113. {
  56114. // something must have gone wrong with the component hierarchy if this happens..
  56115. jassertfalse;
  56116. }
  56117. }
  56118. else
  56119. {
  56120. // why isn't this component inside a menu? Not much point triggering the item if
  56121. // there's no menu.
  56122. jassertfalse;
  56123. }
  56124. }
  56125. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56126. : subMenu (0),
  56127. itemId (0),
  56128. isSeparator (false),
  56129. isTicked (false),
  56130. isEnabled (false),
  56131. isCustomComponent (false),
  56132. isSectionHeader (false),
  56133. customColour (0),
  56134. customImage (0),
  56135. menu (menu_),
  56136. index (0)
  56137. {
  56138. }
  56139. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56140. {
  56141. }
  56142. bool PopupMenu::MenuItemIterator::next()
  56143. {
  56144. if (index >= menu.items.size())
  56145. return false;
  56146. const Item* const item = menu.items.getUnchecked (index);
  56147. ++index;
  56148. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56149. subMenu = item->subMenu;
  56150. itemId = item->itemId;
  56151. isSeparator = item->isSeparator;
  56152. isTicked = item->isTicked;
  56153. isEnabled = item->active;
  56154. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  56155. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56156. customColour = item->usesColour ? &(item->textColour) : 0;
  56157. customImage = item->image;
  56158. commandManager = item->commandManager;
  56159. return true;
  56160. }
  56161. END_JUCE_NAMESPACE
  56162. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56163. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56164. BEGIN_JUCE_NAMESPACE
  56165. ComponentDragger::ComponentDragger()
  56166. : constrainer (0)
  56167. {
  56168. }
  56169. ComponentDragger::~ComponentDragger()
  56170. {
  56171. }
  56172. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  56173. ComponentBoundsConstrainer* const constrainer_)
  56174. {
  56175. jassert (componentToDrag->isValidComponent());
  56176. if (componentToDrag != 0)
  56177. {
  56178. constrainer = constrainer_;
  56179. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  56180. }
  56181. }
  56182. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  56183. {
  56184. jassert (componentToDrag->isValidComponent());
  56185. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  56186. if (componentToDrag != 0)
  56187. {
  56188. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  56189. const Component* const parentComp = componentToDrag->getParentComponent();
  56190. if (parentComp != 0)
  56191. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  56192. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  56193. if (constrainer != 0)
  56194. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56195. else
  56196. componentToDrag->setBounds (bounds);
  56197. }
  56198. }
  56199. END_JUCE_NAMESPACE
  56200. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56201. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56202. BEGIN_JUCE_NAMESPACE
  56203. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56204. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56205. class DragImageComponent : public Component,
  56206. public Timer
  56207. {
  56208. public:
  56209. DragImageComponent (const Image& im,
  56210. const String& desc,
  56211. Component* const sourceComponent,
  56212. Component* const mouseDragSource_,
  56213. DragAndDropContainer* const o,
  56214. const Point<int>& imageOffset_)
  56215. : image (im),
  56216. source (sourceComponent),
  56217. mouseDragSource (mouseDragSource_),
  56218. owner (o),
  56219. dragDesc (desc),
  56220. imageOffset (imageOffset_),
  56221. hasCheckedForExternalDrag (false),
  56222. drawImage (true)
  56223. {
  56224. setSize (im.getWidth(), im.getHeight());
  56225. if (mouseDragSource == 0)
  56226. mouseDragSource = source;
  56227. mouseDragSource->addMouseListener (this, false);
  56228. startTimer (200);
  56229. setInterceptsMouseClicks (false, false);
  56230. setAlwaysOnTop (true);
  56231. }
  56232. ~DragImageComponent()
  56233. {
  56234. if (owner->dragImageComponent == this)
  56235. owner->dragImageComponent.release();
  56236. if (mouseDragSource != 0)
  56237. {
  56238. mouseDragSource->removeMouseListener (this);
  56239. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56240. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56241. }
  56242. }
  56243. void paint (Graphics& g)
  56244. {
  56245. if (isOpaque())
  56246. g.fillAll (Colours::white);
  56247. if (drawImage)
  56248. {
  56249. g.setOpacity (1.0f);
  56250. g.drawImageAt (image, 0, 0);
  56251. }
  56252. }
  56253. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56254. {
  56255. Component* hit = getParentComponent();
  56256. if (hit == 0)
  56257. {
  56258. hit = Desktop::getInstance().findComponentAt (screenPos);
  56259. }
  56260. else
  56261. {
  56262. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  56263. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56264. }
  56265. // (note: use a local copy of the dragDesc member in case the callback runs
  56266. // a modal loop and deletes this object before the method completes)
  56267. const String dragDescLocal (dragDesc);
  56268. while (hit != 0)
  56269. {
  56270. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56271. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56272. {
  56273. relativePos = hit->globalPositionToRelative (screenPos);
  56274. return ddt;
  56275. }
  56276. hit = hit->getParentComponent();
  56277. }
  56278. return 0;
  56279. }
  56280. void mouseUp (const MouseEvent& e)
  56281. {
  56282. if (e.originalComponent != this)
  56283. {
  56284. if (mouseDragSource != 0)
  56285. mouseDragSource->removeMouseListener (this);
  56286. bool dropAccepted = false;
  56287. DragAndDropTarget* ddt = 0;
  56288. Point<int> relPos;
  56289. if (isVisible())
  56290. {
  56291. setVisible (false);
  56292. ddt = findTarget (e.getScreenPosition(), relPos);
  56293. // fade this component and remove it - it'll be deleted later by the timer callback
  56294. dropAccepted = ddt != 0;
  56295. setVisible (true);
  56296. if (dropAccepted || source == 0)
  56297. {
  56298. fadeOutComponent (120);
  56299. }
  56300. else
  56301. {
  56302. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  56303. source->getHeight() / 2)));
  56304. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  56305. getHeight() / 2)));
  56306. fadeOutComponent (120,
  56307. target.getX() - ourCentre.getX(),
  56308. target.getY() - ourCentre.getY());
  56309. }
  56310. }
  56311. if (getParentComponent() != 0)
  56312. getParentComponent()->removeChildComponent (this);
  56313. if (dropAccepted && ddt != 0)
  56314. {
  56315. // (note: use a local copy of the dragDesc member in case the callback runs
  56316. // a modal loop and deletes this object before the method completes)
  56317. const String dragDescLocal (dragDesc);
  56318. currentlyOverComp = 0;
  56319. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56320. }
  56321. // careful - this object could now be deleted..
  56322. }
  56323. }
  56324. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56325. {
  56326. // (note: use a local copy of the dragDesc member in case the callback runs
  56327. // a modal loop and deletes this object before it returns)
  56328. const String dragDescLocal (dragDesc);
  56329. Point<int> newPos (screenPos + imageOffset);
  56330. if (getParentComponent() != 0)
  56331. newPos = getParentComponent()->globalPositionToRelative (newPos);
  56332. //if (newX != getX() || newY != getY())
  56333. {
  56334. setTopLeftPosition (newPos.getX(), newPos.getY());
  56335. Point<int> relPos;
  56336. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56337. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56338. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56339. if (ddtComp != currentlyOverComp)
  56340. {
  56341. if (currentlyOverComp != 0 && source != 0
  56342. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56343. {
  56344. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56345. }
  56346. currentlyOverComp = ddtComp;
  56347. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56348. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56349. }
  56350. DragAndDropTarget* target = getCurrentlyOver();
  56351. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  56352. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56353. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  56354. {
  56355. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56356. {
  56357. hasCheckedForExternalDrag = true;
  56358. StringArray files;
  56359. bool canMoveFiles = false;
  56360. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56361. && files.size() > 0)
  56362. {
  56363. Component::SafePointer<Component> cdw (this);
  56364. setVisible (false);
  56365. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56366. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56367. if (cdw != 0)
  56368. delete this;
  56369. return;
  56370. }
  56371. }
  56372. }
  56373. }
  56374. }
  56375. void mouseDrag (const MouseEvent& e)
  56376. {
  56377. if (e.originalComponent != this)
  56378. updateLocation (true, e.getScreenPosition());
  56379. }
  56380. void timerCallback()
  56381. {
  56382. if (source == 0)
  56383. {
  56384. delete this;
  56385. }
  56386. else if (! isMouseButtonDownAnywhere())
  56387. {
  56388. if (mouseDragSource != 0)
  56389. mouseDragSource->removeMouseListener (this);
  56390. delete this;
  56391. }
  56392. }
  56393. private:
  56394. Image image;
  56395. Component::SafePointer<Component> source;
  56396. Component::SafePointer<Component> mouseDragSource;
  56397. DragAndDropContainer* const owner;
  56398. Component::SafePointer<Component> currentlyOverComp;
  56399. DragAndDropTarget* getCurrentlyOver()
  56400. {
  56401. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  56402. }
  56403. String dragDesc;
  56404. const Point<int> imageOffset;
  56405. bool hasCheckedForExternalDrag, drawImage;
  56406. DragImageComponent (const DragImageComponent&);
  56407. DragImageComponent& operator= (const DragImageComponent&);
  56408. };
  56409. DragAndDropContainer::DragAndDropContainer()
  56410. {
  56411. }
  56412. DragAndDropContainer::~DragAndDropContainer()
  56413. {
  56414. dragImageComponent = 0;
  56415. }
  56416. void DragAndDropContainer::startDragging (const String& sourceDescription,
  56417. Component* sourceComponent,
  56418. const Image& dragImage_,
  56419. const bool allowDraggingToExternalWindows,
  56420. const Point<int>* imageOffsetFromMouse)
  56421. {
  56422. Image dragImage (dragImage_);
  56423. if (dragImageComponent == 0)
  56424. {
  56425. Component* const thisComp = dynamic_cast <Component*> (this);
  56426. if (thisComp == 0)
  56427. {
  56428. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  56429. return;
  56430. }
  56431. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  56432. if (draggingSource == 0 || ! draggingSource->isDragging())
  56433. {
  56434. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  56435. return;
  56436. }
  56437. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  56438. Point<int> imageOffset;
  56439. if (dragImage.isNull())
  56440. {
  56441. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  56442. .convertedToFormat (Image::ARGB);
  56443. dragImage.multiplyAllAlphas (0.6f);
  56444. const int lo = 150;
  56445. const int hi = 400;
  56446. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  56447. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  56448. for (int y = dragImage.getHeight(); --y >= 0;)
  56449. {
  56450. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  56451. for (int x = dragImage.getWidth(); --x >= 0;)
  56452. {
  56453. const int dx = x - clipped.getX();
  56454. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  56455. if (distance > lo)
  56456. {
  56457. const float alpha = (distance > hi) ? 0
  56458. : (hi - distance) / (float) (hi - lo)
  56459. + Random::getSystemRandom().nextFloat() * 0.008f;
  56460. dragImage.multiplyAlphaAt (x, y, alpha);
  56461. }
  56462. }
  56463. }
  56464. imageOffset = -clipped;
  56465. }
  56466. else
  56467. {
  56468. if (imageOffsetFromMouse == 0)
  56469. imageOffset = -dragImage.getBounds().getCentre();
  56470. else
  56471. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  56472. }
  56473. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  56474. draggingSource->getComponentUnderMouse(), this, imageOffset);
  56475. currentDragDesc = sourceDescription;
  56476. if (allowDraggingToExternalWindows)
  56477. {
  56478. if (! Desktop::canUseSemiTransparentWindows())
  56479. dragImageComponent->setOpaque (true);
  56480. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56481. | ComponentPeer::windowIsTemporary
  56482. | ComponentPeer::windowIgnoresKeyPresses);
  56483. }
  56484. else
  56485. thisComp->addChildComponent (dragImageComponent);
  56486. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  56487. dragImageComponent->setVisible (true);
  56488. }
  56489. }
  56490. bool DragAndDropContainer::isDragAndDropActive() const
  56491. {
  56492. return dragImageComponent != 0;
  56493. }
  56494. const String DragAndDropContainer::getCurrentDragDescription() const
  56495. {
  56496. return (dragImageComponent != 0) ? currentDragDesc
  56497. : String::empty;
  56498. }
  56499. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  56500. {
  56501. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  56502. }
  56503. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  56504. {
  56505. return false;
  56506. }
  56507. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  56508. {
  56509. }
  56510. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  56511. {
  56512. }
  56513. void DragAndDropTarget::itemDragExit (const String&, Component*)
  56514. {
  56515. }
  56516. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  56517. {
  56518. return true;
  56519. }
  56520. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  56521. {
  56522. }
  56523. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  56524. {
  56525. }
  56526. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  56527. {
  56528. }
  56529. END_JUCE_NAMESPACE
  56530. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  56531. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  56532. BEGIN_JUCE_NAMESPACE
  56533. class MouseCursor::SharedCursorHandle
  56534. {
  56535. public:
  56536. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  56537. : handle (createStandardMouseCursor (type)),
  56538. refCount (1),
  56539. standardType (type),
  56540. isStandard (true)
  56541. {
  56542. }
  56543. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  56544. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  56545. refCount (1),
  56546. standardType (MouseCursor::NormalCursor),
  56547. isStandard (false)
  56548. {
  56549. }
  56550. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  56551. {
  56552. const ScopedLock sl (getLock());
  56553. for (int i = 0; i < getCursors().size(); ++i)
  56554. {
  56555. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  56556. if (sc->standardType == type)
  56557. return sc->retain();
  56558. }
  56559. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  56560. getCursors().add (sc);
  56561. return sc;
  56562. }
  56563. SharedCursorHandle* retain() throw()
  56564. {
  56565. ++refCount;
  56566. return this;
  56567. }
  56568. void release()
  56569. {
  56570. if (--refCount == 0)
  56571. {
  56572. if (isStandard)
  56573. {
  56574. const ScopedLock sl (getLock());
  56575. getCursors().removeValue (this);
  56576. }
  56577. delete this;
  56578. }
  56579. }
  56580. void* getHandle() const throw() { return handle; }
  56581. juce_UseDebuggingNewOperator
  56582. private:
  56583. void* const handle;
  56584. Atomic <int> refCount;
  56585. const MouseCursor::StandardCursorType standardType;
  56586. const bool isStandard;
  56587. static CriticalSection& getLock()
  56588. {
  56589. static CriticalSection lock;
  56590. return lock;
  56591. }
  56592. static Array <SharedCursorHandle*>& getCursors()
  56593. {
  56594. static Array <SharedCursorHandle*> cursors;
  56595. return cursors;
  56596. }
  56597. ~SharedCursorHandle()
  56598. {
  56599. deleteMouseCursor (handle, isStandard);
  56600. }
  56601. SharedCursorHandle& operator= (const SharedCursorHandle&);
  56602. };
  56603. MouseCursor::MouseCursor()
  56604. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  56605. {
  56606. jassert (cursorHandle != 0);
  56607. }
  56608. MouseCursor::MouseCursor (const StandardCursorType type)
  56609. : cursorHandle (SharedCursorHandle::createStandard (type))
  56610. {
  56611. jassert (cursorHandle != 0);
  56612. }
  56613. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  56614. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  56615. {
  56616. }
  56617. MouseCursor::MouseCursor (const MouseCursor& other)
  56618. : cursorHandle (other.cursorHandle->retain())
  56619. {
  56620. }
  56621. MouseCursor::~MouseCursor()
  56622. {
  56623. cursorHandle->release();
  56624. }
  56625. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  56626. {
  56627. other.cursorHandle->retain();
  56628. cursorHandle->release();
  56629. cursorHandle = other.cursorHandle;
  56630. return *this;
  56631. }
  56632. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  56633. {
  56634. return getHandle() == other.getHandle();
  56635. }
  56636. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  56637. {
  56638. return getHandle() != other.getHandle();
  56639. }
  56640. void* MouseCursor::getHandle() const throw()
  56641. {
  56642. return cursorHandle->getHandle();
  56643. }
  56644. void MouseCursor::showWaitCursor()
  56645. {
  56646. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  56647. }
  56648. void MouseCursor::hideWaitCursor()
  56649. {
  56650. Desktop::getInstance().getMainMouseSource().revealCursor();
  56651. }
  56652. END_JUCE_NAMESPACE
  56653. /*** End of inlined file: juce_MouseCursor.cpp ***/
  56654. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  56655. BEGIN_JUCE_NAMESPACE
  56656. MouseEvent::MouseEvent (MouseInputSource& source_,
  56657. const Point<int>& position,
  56658. const ModifierKeys& mods_,
  56659. Component* const eventComponent_,
  56660. Component* const originator,
  56661. const Time& eventTime_,
  56662. const Point<int> mouseDownPos_,
  56663. const Time& mouseDownTime_,
  56664. const int numberOfClicks_,
  56665. const bool mouseWasDragged) throw()
  56666. : x (position.getX()),
  56667. y (position.getY()),
  56668. mods (mods_),
  56669. eventComponent (eventComponent_),
  56670. originalComponent (originator),
  56671. eventTime (eventTime_),
  56672. source (source_),
  56673. mouseDownPos (mouseDownPos_),
  56674. mouseDownTime (mouseDownTime_),
  56675. numberOfClicks (numberOfClicks_),
  56676. wasMovedSinceMouseDown (mouseWasDragged)
  56677. {
  56678. }
  56679. MouseEvent::~MouseEvent() throw()
  56680. {
  56681. }
  56682. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  56683. {
  56684. if (otherComponent == 0)
  56685. {
  56686. jassertfalse;
  56687. return *this;
  56688. }
  56689. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  56690. mods, otherComponent, originalComponent, eventTime,
  56691. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  56692. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  56693. }
  56694. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  56695. {
  56696. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  56697. eventTime, mouseDownPos, mouseDownTime,
  56698. numberOfClicks, wasMovedSinceMouseDown);
  56699. }
  56700. bool MouseEvent::mouseWasClicked() const throw()
  56701. {
  56702. return ! wasMovedSinceMouseDown;
  56703. }
  56704. int MouseEvent::getMouseDownX() const throw()
  56705. {
  56706. return mouseDownPos.getX();
  56707. }
  56708. int MouseEvent::getMouseDownY() const throw()
  56709. {
  56710. return mouseDownPos.getY();
  56711. }
  56712. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  56713. {
  56714. return mouseDownPos;
  56715. }
  56716. int MouseEvent::getDistanceFromDragStartX() const throw()
  56717. {
  56718. return x - mouseDownPos.getX();
  56719. }
  56720. int MouseEvent::getDistanceFromDragStartY() const throw()
  56721. {
  56722. return y - mouseDownPos.getY();
  56723. }
  56724. int MouseEvent::getDistanceFromDragStart() const throw()
  56725. {
  56726. return mouseDownPos.getDistanceFrom (getPosition());
  56727. }
  56728. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  56729. {
  56730. return getPosition() - mouseDownPos;
  56731. }
  56732. int MouseEvent::getLengthOfMousePress() const throw()
  56733. {
  56734. if (mouseDownTime.toMilliseconds() > 0)
  56735. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  56736. return 0;
  56737. }
  56738. const Point<int> MouseEvent::getPosition() const throw()
  56739. {
  56740. return Point<int> (x, y);
  56741. }
  56742. int MouseEvent::getScreenX() const
  56743. {
  56744. return getScreenPosition().getX();
  56745. }
  56746. int MouseEvent::getScreenY() const
  56747. {
  56748. return getScreenPosition().getY();
  56749. }
  56750. const Point<int> MouseEvent::getScreenPosition() const
  56751. {
  56752. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  56753. }
  56754. int MouseEvent::getMouseDownScreenX() const
  56755. {
  56756. return getMouseDownScreenPosition().getX();
  56757. }
  56758. int MouseEvent::getMouseDownScreenY() const
  56759. {
  56760. return getMouseDownScreenPosition().getY();
  56761. }
  56762. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  56763. {
  56764. return eventComponent->relativePositionToGlobal (mouseDownPos);
  56765. }
  56766. int MouseEvent::doubleClickTimeOutMs = 400;
  56767. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  56768. {
  56769. doubleClickTimeOutMs = newTime;
  56770. }
  56771. int MouseEvent::getDoubleClickTimeout() throw()
  56772. {
  56773. return doubleClickTimeOutMs;
  56774. }
  56775. END_JUCE_NAMESPACE
  56776. /*** End of inlined file: juce_MouseEvent.cpp ***/
  56777. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  56778. BEGIN_JUCE_NAMESPACE
  56779. class MouseInputSourceInternal : public AsyncUpdater
  56780. {
  56781. public:
  56782. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  56783. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0), lastTime (0),
  56784. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  56785. mouseEventCounter (0)
  56786. {
  56787. zerostruct (mouseDowns);
  56788. }
  56789. ~MouseInputSourceInternal()
  56790. {
  56791. }
  56792. bool isDragging() const throw()
  56793. {
  56794. return buttonState.isAnyMouseButtonDown();
  56795. }
  56796. Component* getComponentUnderMouse() const
  56797. {
  56798. return static_cast <Component*> (componentUnderMouse);
  56799. }
  56800. const ModifierKeys getCurrentModifiers() const
  56801. {
  56802. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  56803. }
  56804. ComponentPeer* getPeer()
  56805. {
  56806. if (! ComponentPeer::isValidPeer (lastPeer))
  56807. lastPeer = 0;
  56808. return lastPeer;
  56809. }
  56810. Component* findComponentAt (const Point<int>& screenPos)
  56811. {
  56812. ComponentPeer* const peer = getPeer();
  56813. if (peer != 0)
  56814. {
  56815. Component* const comp = peer->getComponent();
  56816. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  56817. // (the contains() call is needed to test for overlapping desktop windows)
  56818. if (comp->contains (relativePos.getX(), relativePos.getY()))
  56819. return comp->getComponentAt (relativePos);
  56820. }
  56821. return 0;
  56822. }
  56823. const Point<int> getScreenPosition() const throw()
  56824. {
  56825. return lastScreenPos + unboundedMouseOffset;
  56826. }
  56827. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  56828. {
  56829. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56830. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  56831. }
  56832. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  56833. {
  56834. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56835. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  56836. }
  56837. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  56838. {
  56839. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56840. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  56841. }
  56842. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  56843. {
  56844. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56845. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  56846. }
  56847. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  56848. {
  56849. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56850. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  56851. }
  56852. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  56853. {
  56854. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56855. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  56856. }
  56857. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  56858. {
  56859. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56860. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  56861. }
  56862. // (returns true if the button change caused a modal event loop)
  56863. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  56864. {
  56865. if (buttonState == newButtonState)
  56866. return false;
  56867. setScreenPos (screenPos, time, false);
  56868. // (ignore secondary clicks when there's already a button down)
  56869. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  56870. {
  56871. buttonState = newButtonState;
  56872. return false;
  56873. }
  56874. const int lastCounter = mouseEventCounter;
  56875. if (buttonState.isAnyMouseButtonDown())
  56876. {
  56877. Component* const current = getComponentUnderMouse();
  56878. if (current != 0)
  56879. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  56880. enableUnboundedMouseMovement (false, false);
  56881. }
  56882. buttonState = newButtonState;
  56883. if (buttonState.isAnyMouseButtonDown())
  56884. {
  56885. Desktop::getInstance().incrementMouseClickCounter();
  56886. Component* const current = getComponentUnderMouse();
  56887. if (current != 0)
  56888. {
  56889. registerMouseDown (screenPos, time, current);
  56890. sendMouseDown (current, screenPos, time);
  56891. }
  56892. }
  56893. return lastCounter != mouseEventCounter;
  56894. }
  56895. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  56896. {
  56897. Component* current = getComponentUnderMouse();
  56898. if (newComponent != current)
  56899. {
  56900. Component::SafePointer<Component> safeNewComp (newComponent);
  56901. const ModifierKeys originalButtonState (buttonState);
  56902. if (current != 0)
  56903. {
  56904. setButtons (screenPos, time, ModifierKeys());
  56905. sendMouseExit (current, screenPos, time);
  56906. buttonState = originalButtonState;
  56907. }
  56908. componentUnderMouse = safeNewComp;
  56909. current = getComponentUnderMouse();
  56910. if (current != 0)
  56911. sendMouseEnter (current, screenPos, time);
  56912. revealCursor (false);
  56913. setButtons (screenPos, time, originalButtonState);
  56914. }
  56915. }
  56916. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  56917. {
  56918. ModifierKeys::updateCurrentModifiers();
  56919. if (newPeer != lastPeer)
  56920. {
  56921. setComponentUnderMouse (0, screenPos, time);
  56922. lastPeer = newPeer;
  56923. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  56924. }
  56925. }
  56926. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  56927. {
  56928. if (! isDragging())
  56929. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  56930. if (newScreenPos != lastScreenPos || forceUpdate)
  56931. {
  56932. cancelPendingUpdate();
  56933. lastScreenPos = newScreenPos;
  56934. Component* const current = getComponentUnderMouse();
  56935. if (current != 0)
  56936. {
  56937. if (isDragging())
  56938. {
  56939. registerMouseDrag (newScreenPos);
  56940. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  56941. if (isUnboundedMouseModeOn)
  56942. handleUnboundedDrag (current);
  56943. }
  56944. else
  56945. {
  56946. sendMouseMove (current, newScreenPos, time);
  56947. }
  56948. }
  56949. revealCursor (false);
  56950. }
  56951. }
  56952. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  56953. {
  56954. jassert (newPeer != 0);
  56955. lastTime = time;
  56956. ++mouseEventCounter;
  56957. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  56958. if (isDragging() && newMods.isAnyMouseButtonDown())
  56959. {
  56960. setScreenPos (screenPos, time, false);
  56961. }
  56962. else
  56963. {
  56964. setPeer (newPeer, screenPos, time);
  56965. ComponentPeer* peer = getPeer();
  56966. if (peer != 0)
  56967. {
  56968. if (setButtons (screenPos, time, newMods))
  56969. return; // some modal events have been dispatched, so the current event is now out-of-date
  56970. peer = getPeer();
  56971. if (peer != 0)
  56972. setScreenPos (screenPos, time, false);
  56973. }
  56974. }
  56975. }
  56976. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  56977. {
  56978. jassert (peer != 0);
  56979. lastTime = time;
  56980. ++mouseEventCounter;
  56981. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  56982. setPeer (peer, screenPos, time);
  56983. setScreenPos (screenPos, time, false);
  56984. triggerFakeMove();
  56985. if (! isDragging())
  56986. {
  56987. Component* current = getComponentUnderMouse();
  56988. if (current != 0)
  56989. sendMouseWheel (current, screenPos, time, x, y);
  56990. }
  56991. }
  56992. const Time getLastMouseDownTime() const throw()
  56993. {
  56994. return Time (mouseDowns[0].time);
  56995. }
  56996. const Point<int> getLastMouseDownPosition() const throw()
  56997. {
  56998. return mouseDowns[0].position;
  56999. }
  57000. int getNumberOfMultipleClicks() const throw()
  57001. {
  57002. int numClicks = 0;
  57003. if (mouseDowns[0].time != 0)
  57004. {
  57005. if (! mouseMovedSignificantlySincePressed)
  57006. ++numClicks;
  57007. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57008. {
  57009. if (mouseDowns[0].time - mouseDowns[i].time < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  57010. && abs (mouseDowns[0].position.getX() - mouseDowns[i].position.getX()) < 8
  57011. && abs (mouseDowns[0].position.getY() - mouseDowns[i].position.getY()) < 8)
  57012. {
  57013. ++numClicks;
  57014. }
  57015. else
  57016. {
  57017. break;
  57018. }
  57019. }
  57020. }
  57021. return numClicks;
  57022. }
  57023. bool hasMouseMovedSignificantlySincePressed() const throw()
  57024. {
  57025. return mouseMovedSignificantlySincePressed
  57026. || lastTime > mouseDowns[0].time + 300;
  57027. }
  57028. void triggerFakeMove()
  57029. {
  57030. triggerAsyncUpdate();
  57031. }
  57032. void handleAsyncUpdate()
  57033. {
  57034. if (! isDragging())
  57035. setScreenPos (Desktop::getMousePosition(), jmax (lastTime, Time::currentTimeMillis()), true);
  57036. }
  57037. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57038. {
  57039. enable = enable && isDragging();
  57040. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57041. if (enable != isUnboundedMouseModeOn)
  57042. {
  57043. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57044. {
  57045. // when released, return the mouse to within the component's bounds
  57046. Component* current = getComponentUnderMouse();
  57047. if (current != 0)
  57048. Desktop::setMousePosition (current->getScreenBounds()
  57049. .getConstrainedPoint (current->getMouseXYRelative()));
  57050. }
  57051. isUnboundedMouseModeOn = enable;
  57052. unboundedMouseOffset = Point<int>();
  57053. revealCursor (true);
  57054. }
  57055. }
  57056. void handleUnboundedDrag (Component* current)
  57057. {
  57058. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57059. if (! screenArea.contains (lastScreenPos))
  57060. {
  57061. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57062. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57063. Desktop::setMousePosition (componentCentre);
  57064. }
  57065. else if (isCursorVisibleUntilOffscreen
  57066. && (! unboundedMouseOffset.isOrigin())
  57067. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57068. {
  57069. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57070. unboundedMouseOffset = Point<int>();
  57071. }
  57072. }
  57073. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57074. {
  57075. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57076. {
  57077. cursor = MouseCursor::NoCursor;
  57078. forcedUpdate = true;
  57079. }
  57080. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57081. {
  57082. currentCursorHandle = cursor.getHandle();
  57083. cursor.showInWindow (getPeer());
  57084. }
  57085. }
  57086. void hideCursor()
  57087. {
  57088. showMouseCursor (MouseCursor::NoCursor, true);
  57089. }
  57090. void revealCursor (bool forcedUpdate)
  57091. {
  57092. MouseCursor mc (MouseCursor::NormalCursor);
  57093. Component* current = getComponentUnderMouse();
  57094. if (current != 0)
  57095. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57096. showMouseCursor (mc, forcedUpdate);
  57097. }
  57098. int index;
  57099. bool isMouseDevice;
  57100. Point<int> lastScreenPos;
  57101. ModifierKeys buttonState;
  57102. private:
  57103. MouseInputSource& source;
  57104. Component::SafePointer<Component> componentUnderMouse;
  57105. ComponentPeer* lastPeer;
  57106. Point<int> unboundedMouseOffset;
  57107. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57108. void* currentCursorHandle;
  57109. int mouseEventCounter;
  57110. struct RecentMouseDown
  57111. {
  57112. Point<int> position;
  57113. int64 time;
  57114. Component* component;
  57115. };
  57116. RecentMouseDown mouseDowns[4];
  57117. bool mouseMovedSignificantlySincePressed;
  57118. int64 lastTime;
  57119. void registerMouseDown (const Point<int>& screenPos, const int64 time, Component* const component) throw()
  57120. {
  57121. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57122. mouseDowns[i] = mouseDowns[i - 1];
  57123. mouseDowns[0].position = screenPos;
  57124. mouseDowns[0].time = time;
  57125. mouseDowns[0].component = component;
  57126. mouseMovedSignificantlySincePressed = false;
  57127. }
  57128. void registerMouseDrag (const Point<int>& screenPos) throw()
  57129. {
  57130. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57131. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57132. }
  57133. MouseInputSourceInternal (const MouseInputSourceInternal&);
  57134. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  57135. };
  57136. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57137. {
  57138. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57139. }
  57140. MouseInputSource::~MouseInputSource()
  57141. {
  57142. }
  57143. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57144. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57145. bool MouseInputSource::canHover() const { return isMouse(); }
  57146. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57147. int MouseInputSource::getIndex() const { return pimpl->index; }
  57148. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57149. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57150. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57151. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57152. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57153. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57154. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57155. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57156. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57157. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57158. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57159. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57160. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57161. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57162. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57163. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57164. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57165. {
  57166. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  57167. }
  57168. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57169. {
  57170. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  57171. }
  57172. END_JUCE_NAMESPACE
  57173. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57174. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  57175. BEGIN_JUCE_NAMESPACE
  57176. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  57177. : source (0),
  57178. hoverTimeMillisecs (hoverTimeMillisecs_),
  57179. hasJustHovered (false)
  57180. {
  57181. internalTimer.owner = this;
  57182. }
  57183. MouseHoverDetector::~MouseHoverDetector()
  57184. {
  57185. setHoverComponent (0);
  57186. }
  57187. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  57188. {
  57189. hoverTimeMillisecs = newTimeInMillisecs;
  57190. }
  57191. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  57192. {
  57193. if (source != newSourceComponent)
  57194. {
  57195. internalTimer.stopTimer();
  57196. hasJustHovered = false;
  57197. if (source != 0)
  57198. {
  57199. // ! you need to delete the hover detector before deleting its component
  57200. jassert (source->isValidComponent());
  57201. source->removeMouseListener (&internalTimer);
  57202. }
  57203. source = newSourceComponent;
  57204. if (newSourceComponent != 0)
  57205. newSourceComponent->addMouseListener (&internalTimer, false);
  57206. }
  57207. }
  57208. void MouseHoverDetector::hoverTimerCallback()
  57209. {
  57210. internalTimer.stopTimer();
  57211. if (source != 0)
  57212. {
  57213. const Point<int> pos (source->getMouseXYRelative());
  57214. if (source->reallyContains (pos.getX(), pos.getY(), false))
  57215. {
  57216. hasJustHovered = true;
  57217. mouseHovered (pos.getX(), pos.getY());
  57218. }
  57219. }
  57220. }
  57221. void MouseHoverDetector::checkJustHoveredCallback()
  57222. {
  57223. if (hasJustHovered)
  57224. {
  57225. hasJustHovered = false;
  57226. mouseMovedAfterHover();
  57227. }
  57228. }
  57229. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  57230. {
  57231. owner->hoverTimerCallback();
  57232. }
  57233. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  57234. {
  57235. stopTimer();
  57236. owner->checkJustHoveredCallback();
  57237. }
  57238. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  57239. {
  57240. stopTimer();
  57241. owner->checkJustHoveredCallback();
  57242. }
  57243. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  57244. {
  57245. stopTimer();
  57246. owner->checkJustHoveredCallback();
  57247. }
  57248. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  57249. {
  57250. stopTimer();
  57251. owner->checkJustHoveredCallback();
  57252. }
  57253. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  57254. {
  57255. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  57256. {
  57257. lastX = e.x;
  57258. lastY = e.y;
  57259. if (owner->source != 0)
  57260. startTimer (owner->hoverTimeMillisecs);
  57261. owner->checkJustHoveredCallback();
  57262. }
  57263. }
  57264. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  57265. {
  57266. stopTimer();
  57267. owner->checkJustHoveredCallback();
  57268. }
  57269. END_JUCE_NAMESPACE
  57270. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  57271. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57272. BEGIN_JUCE_NAMESPACE
  57273. void MouseListener::mouseEnter (const MouseEvent&)
  57274. {
  57275. }
  57276. void MouseListener::mouseExit (const MouseEvent&)
  57277. {
  57278. }
  57279. void MouseListener::mouseDown (const MouseEvent&)
  57280. {
  57281. }
  57282. void MouseListener::mouseUp (const MouseEvent&)
  57283. {
  57284. }
  57285. void MouseListener::mouseDrag (const MouseEvent&)
  57286. {
  57287. }
  57288. void MouseListener::mouseMove (const MouseEvent&)
  57289. {
  57290. }
  57291. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57292. {
  57293. }
  57294. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57295. {
  57296. }
  57297. END_JUCE_NAMESPACE
  57298. /*** End of inlined file: juce_MouseListener.cpp ***/
  57299. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57300. BEGIN_JUCE_NAMESPACE
  57301. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57302. const String& buttonTextWhenTrue,
  57303. const String& buttonTextWhenFalse)
  57304. : PropertyComponent (name),
  57305. onText (buttonTextWhenTrue),
  57306. offText (buttonTextWhenFalse)
  57307. {
  57308. addAndMakeVisible (&button);
  57309. button.setClickingTogglesState (false);
  57310. button.addButtonListener (this);
  57311. }
  57312. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57313. const String& name,
  57314. const String& buttonText)
  57315. : PropertyComponent (name),
  57316. onText (buttonText),
  57317. offText (buttonText)
  57318. {
  57319. addAndMakeVisible (&button);
  57320. button.setClickingTogglesState (false);
  57321. button.setButtonText (buttonText);
  57322. button.getToggleStateValue().referTo (valueToControl);
  57323. button.setClickingTogglesState (true);
  57324. }
  57325. BooleanPropertyComponent::~BooleanPropertyComponent()
  57326. {
  57327. }
  57328. void BooleanPropertyComponent::setState (const bool newState)
  57329. {
  57330. button.setToggleState (newState, true);
  57331. }
  57332. bool BooleanPropertyComponent::getState() const
  57333. {
  57334. return button.getToggleState();
  57335. }
  57336. void BooleanPropertyComponent::paint (Graphics& g)
  57337. {
  57338. PropertyComponent::paint (g);
  57339. g.setColour (Colours::white);
  57340. g.fillRect (button.getBounds());
  57341. g.setColour (findColour (ComboBox::outlineColourId));
  57342. g.drawRect (button.getBounds());
  57343. }
  57344. void BooleanPropertyComponent::refresh()
  57345. {
  57346. button.setToggleState (getState(), false);
  57347. button.setButtonText (button.getToggleState() ? onText : offText);
  57348. }
  57349. void BooleanPropertyComponent::buttonClicked (Button*)
  57350. {
  57351. setState (! getState());
  57352. }
  57353. END_JUCE_NAMESPACE
  57354. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57355. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57356. BEGIN_JUCE_NAMESPACE
  57357. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57358. const bool triggerOnMouseDown)
  57359. : PropertyComponent (name)
  57360. {
  57361. addAndMakeVisible (&button);
  57362. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  57363. button.addButtonListener (this);
  57364. }
  57365. ButtonPropertyComponent::~ButtonPropertyComponent()
  57366. {
  57367. }
  57368. void ButtonPropertyComponent::refresh()
  57369. {
  57370. button.setButtonText (getButtonText());
  57371. }
  57372. void ButtonPropertyComponent::buttonClicked (Button*)
  57373. {
  57374. buttonClicked();
  57375. }
  57376. END_JUCE_NAMESPACE
  57377. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57378. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57379. BEGIN_JUCE_NAMESPACE
  57380. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  57381. public Value::Listener
  57382. {
  57383. public:
  57384. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  57385. : sourceValue (sourceValue_),
  57386. mappings (mappings_)
  57387. {
  57388. sourceValue.addListener (this);
  57389. }
  57390. ~RemapperValueSource() {}
  57391. const var getValue() const
  57392. {
  57393. return mappings.indexOf (sourceValue.getValue()) + 1;
  57394. }
  57395. void setValue (const var& newValue)
  57396. {
  57397. const var remappedVal (mappings [(int) newValue - 1]);
  57398. if (remappedVal != sourceValue)
  57399. sourceValue = remappedVal;
  57400. }
  57401. void valueChanged (Value&)
  57402. {
  57403. sendChangeMessage (true);
  57404. }
  57405. juce_UseDebuggingNewOperator
  57406. protected:
  57407. Value sourceValue;
  57408. Array<var> mappings;
  57409. RemapperValueSource (const RemapperValueSource&);
  57410. const RemapperValueSource& operator= (const RemapperValueSource&);
  57411. };
  57412. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57413. : PropertyComponent (name),
  57414. isCustomClass (true)
  57415. {
  57416. }
  57417. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57418. const String& name,
  57419. const StringArray& choices_,
  57420. const Array <var>& correspondingValues)
  57421. : PropertyComponent (name),
  57422. choices (choices_),
  57423. isCustomClass (false)
  57424. {
  57425. // The array of corresponding values must contain one value for each of the items in
  57426. // the choices array!
  57427. jassert (correspondingValues.size() == choices.size());
  57428. createComboBox();
  57429. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  57430. }
  57431. ChoicePropertyComponent::~ChoicePropertyComponent()
  57432. {
  57433. }
  57434. void ChoicePropertyComponent::createComboBox()
  57435. {
  57436. addAndMakeVisible (&comboBox);
  57437. for (int i = 0; i < choices.size(); ++i)
  57438. {
  57439. if (choices[i].isNotEmpty())
  57440. comboBox.addItem (choices[i], i + 1);
  57441. else
  57442. comboBox.addSeparator();
  57443. }
  57444. comboBox.setEditableText (false);
  57445. }
  57446. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  57447. {
  57448. jassertfalse; // you need to override this method in your subclass!
  57449. }
  57450. int ChoicePropertyComponent::getIndex() const
  57451. {
  57452. jassertfalse; // you need to override this method in your subclass!
  57453. return -1;
  57454. }
  57455. const StringArray& ChoicePropertyComponent::getChoices() const
  57456. {
  57457. return choices;
  57458. }
  57459. void ChoicePropertyComponent::refresh()
  57460. {
  57461. if (isCustomClass)
  57462. {
  57463. if (! comboBox.isVisible())
  57464. {
  57465. createComboBox();
  57466. comboBox.addListener (this);
  57467. }
  57468. comboBox.setSelectedId (getIndex() + 1, true);
  57469. }
  57470. }
  57471. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  57472. {
  57473. if (isCustomClass)
  57474. {
  57475. const int newIndex = comboBox.getSelectedId() - 1;
  57476. if (newIndex != getIndex())
  57477. setIndex (newIndex);
  57478. }
  57479. }
  57480. END_JUCE_NAMESPACE
  57481. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57482. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  57483. BEGIN_JUCE_NAMESPACE
  57484. PropertyComponent::PropertyComponent (const String& name,
  57485. const int preferredHeight_)
  57486. : Component (name),
  57487. preferredHeight (preferredHeight_)
  57488. {
  57489. jassert (name.isNotEmpty());
  57490. }
  57491. PropertyComponent::~PropertyComponent()
  57492. {
  57493. }
  57494. void PropertyComponent::paint (Graphics& g)
  57495. {
  57496. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  57497. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  57498. }
  57499. void PropertyComponent::resized()
  57500. {
  57501. if (getNumChildComponents() > 0)
  57502. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  57503. }
  57504. void PropertyComponent::enablementChanged()
  57505. {
  57506. repaint();
  57507. }
  57508. END_JUCE_NAMESPACE
  57509. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  57510. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  57511. BEGIN_JUCE_NAMESPACE
  57512. class PropertyPanel::PropertyHolderComponent : public Component
  57513. {
  57514. public:
  57515. PropertyHolderComponent()
  57516. {
  57517. }
  57518. ~PropertyHolderComponent()
  57519. {
  57520. deleteAllChildren();
  57521. }
  57522. void paint (Graphics&)
  57523. {
  57524. }
  57525. void updateLayout (int width);
  57526. void refreshAll() const;
  57527. private:
  57528. PropertyHolderComponent (const PropertyHolderComponent&);
  57529. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  57530. };
  57531. class PropertySectionComponent : public Component
  57532. {
  57533. public:
  57534. PropertySectionComponent (const String& sectionTitle,
  57535. const Array <PropertyComponent*>& newProperties,
  57536. const bool open)
  57537. : Component (sectionTitle),
  57538. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  57539. isOpen_ (open)
  57540. {
  57541. for (int i = newProperties.size(); --i >= 0;)
  57542. {
  57543. addAndMakeVisible (newProperties.getUnchecked(i));
  57544. newProperties.getUnchecked(i)->refresh();
  57545. }
  57546. }
  57547. ~PropertySectionComponent()
  57548. {
  57549. deleteAllChildren();
  57550. }
  57551. void paint (Graphics& g)
  57552. {
  57553. if (titleHeight > 0)
  57554. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  57555. }
  57556. void resized()
  57557. {
  57558. int y = titleHeight;
  57559. for (int i = getNumChildComponents(); --i >= 0;)
  57560. {
  57561. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57562. if (pec != 0)
  57563. {
  57564. const int prefH = pec->getPreferredHeight();
  57565. pec->setBounds (1, y, getWidth() - 2, prefH);
  57566. y += prefH;
  57567. }
  57568. }
  57569. }
  57570. int getPreferredHeight() const
  57571. {
  57572. int y = titleHeight;
  57573. if (isOpen())
  57574. {
  57575. for (int i = 0; i < getNumChildComponents(); ++i)
  57576. {
  57577. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57578. if (pec != 0)
  57579. y += pec->getPreferredHeight();
  57580. }
  57581. }
  57582. return y;
  57583. }
  57584. void setOpen (const bool open)
  57585. {
  57586. if (isOpen_ != open)
  57587. {
  57588. isOpen_ = open;
  57589. for (int i = 0; i < getNumChildComponents(); ++i)
  57590. {
  57591. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57592. if (pec != 0)
  57593. pec->setVisible (open);
  57594. }
  57595. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  57596. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  57597. if (pp != 0)
  57598. pp->resized();
  57599. }
  57600. }
  57601. bool isOpen() const
  57602. {
  57603. return isOpen_;
  57604. }
  57605. void refreshAll() const
  57606. {
  57607. for (int i = 0; i < getNumChildComponents(); ++i)
  57608. {
  57609. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57610. if (pec != 0)
  57611. pec->refresh();
  57612. }
  57613. }
  57614. void mouseDown (const MouseEvent&)
  57615. {
  57616. }
  57617. void mouseUp (const MouseEvent& e)
  57618. {
  57619. if (e.getMouseDownX() < titleHeight
  57620. && e.x < titleHeight
  57621. && e.y < titleHeight
  57622. && e.getNumberOfClicks() != 2)
  57623. {
  57624. setOpen (! isOpen());
  57625. }
  57626. }
  57627. void mouseDoubleClick (const MouseEvent& e)
  57628. {
  57629. if (e.y < titleHeight)
  57630. setOpen (! isOpen());
  57631. }
  57632. private:
  57633. int titleHeight;
  57634. bool isOpen_;
  57635. PropertySectionComponent (const PropertySectionComponent&);
  57636. PropertySectionComponent& operator= (const PropertySectionComponent&);
  57637. };
  57638. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  57639. {
  57640. int y = 0;
  57641. for (int i = getNumChildComponents(); --i >= 0;)
  57642. {
  57643. PropertySectionComponent* const section
  57644. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57645. if (section != 0)
  57646. {
  57647. const int prefH = section->getPreferredHeight();
  57648. section->setBounds (0, y, width, prefH);
  57649. y += prefH;
  57650. }
  57651. }
  57652. setSize (width, y);
  57653. repaint();
  57654. }
  57655. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  57656. {
  57657. for (int i = getNumChildComponents(); --i >= 0;)
  57658. {
  57659. PropertySectionComponent* const section
  57660. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57661. if (section != 0)
  57662. section->refreshAll();
  57663. }
  57664. }
  57665. PropertyPanel::PropertyPanel()
  57666. {
  57667. messageWhenEmpty = TRANS("(nothing selected)");
  57668. addAndMakeVisible (&viewport);
  57669. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  57670. viewport.setFocusContainer (true);
  57671. }
  57672. PropertyPanel::~PropertyPanel()
  57673. {
  57674. clear();
  57675. }
  57676. void PropertyPanel::paint (Graphics& g)
  57677. {
  57678. if (propertyHolderComponent->getNumChildComponents() == 0)
  57679. {
  57680. g.setColour (Colours::black.withAlpha (0.5f));
  57681. g.setFont (14.0f);
  57682. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  57683. Justification::centred, true);
  57684. }
  57685. }
  57686. void PropertyPanel::resized()
  57687. {
  57688. viewport.setBounds (getLocalBounds());
  57689. updatePropHolderLayout();
  57690. }
  57691. void PropertyPanel::clear()
  57692. {
  57693. if (propertyHolderComponent->getNumChildComponents() > 0)
  57694. {
  57695. propertyHolderComponent->deleteAllChildren();
  57696. repaint();
  57697. }
  57698. }
  57699. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  57700. {
  57701. if (propertyHolderComponent->getNumChildComponents() == 0)
  57702. repaint();
  57703. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  57704. newProperties,
  57705. true), 0);
  57706. updatePropHolderLayout();
  57707. }
  57708. void PropertyPanel::addSection (const String& sectionTitle,
  57709. const Array <PropertyComponent*>& newProperties,
  57710. const bool shouldBeOpen)
  57711. {
  57712. jassert (sectionTitle.isNotEmpty());
  57713. if (propertyHolderComponent->getNumChildComponents() == 0)
  57714. repaint();
  57715. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  57716. newProperties,
  57717. shouldBeOpen), 0);
  57718. updatePropHolderLayout();
  57719. }
  57720. void PropertyPanel::updatePropHolderLayout() const
  57721. {
  57722. const int maxWidth = viewport.getMaximumVisibleWidth();
  57723. propertyHolderComponent->updateLayout (maxWidth);
  57724. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  57725. if (maxWidth != newMaxWidth)
  57726. {
  57727. // need to do this twice because of scrollbars changing the size, etc.
  57728. propertyHolderComponent->updateLayout (newMaxWidth);
  57729. }
  57730. }
  57731. void PropertyPanel::refreshAll() const
  57732. {
  57733. propertyHolderComponent->refreshAll();
  57734. }
  57735. const StringArray PropertyPanel::getSectionNames() const
  57736. {
  57737. StringArray s;
  57738. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57739. {
  57740. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57741. if (section != 0 && section->getName().isNotEmpty())
  57742. s.add (section->getName());
  57743. }
  57744. return s;
  57745. }
  57746. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  57747. {
  57748. int index = 0;
  57749. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57750. {
  57751. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57752. if (section != 0 && section->getName().isNotEmpty())
  57753. {
  57754. if (index == sectionIndex)
  57755. return section->isOpen();
  57756. ++index;
  57757. }
  57758. }
  57759. return false;
  57760. }
  57761. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  57762. {
  57763. int index = 0;
  57764. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57765. {
  57766. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57767. if (section != 0 && section->getName().isNotEmpty())
  57768. {
  57769. if (index == sectionIndex)
  57770. {
  57771. section->setOpen (shouldBeOpen);
  57772. break;
  57773. }
  57774. ++index;
  57775. }
  57776. }
  57777. }
  57778. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  57779. {
  57780. int index = 0;
  57781. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57782. {
  57783. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57784. if (section != 0 && section->getName().isNotEmpty())
  57785. {
  57786. if (index == sectionIndex)
  57787. {
  57788. section->setEnabled (shouldBeEnabled);
  57789. break;
  57790. }
  57791. ++index;
  57792. }
  57793. }
  57794. }
  57795. XmlElement* PropertyPanel::getOpennessState() const
  57796. {
  57797. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  57798. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  57799. const StringArray sections (getSectionNames());
  57800. for (int i = 0; i < sections.size(); ++i)
  57801. {
  57802. if (sections[i].isNotEmpty())
  57803. {
  57804. XmlElement* const e = xml->createNewChildElement ("SECTION");
  57805. e->setAttribute ("name", sections[i]);
  57806. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  57807. }
  57808. }
  57809. return xml;
  57810. }
  57811. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  57812. {
  57813. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  57814. {
  57815. const StringArray sections (getSectionNames());
  57816. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  57817. {
  57818. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  57819. e->getBoolAttribute ("open"));
  57820. }
  57821. viewport.setViewPosition (viewport.getViewPositionX(),
  57822. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  57823. }
  57824. }
  57825. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  57826. {
  57827. if (messageWhenEmpty != newMessage)
  57828. {
  57829. messageWhenEmpty = newMessage;
  57830. repaint();
  57831. }
  57832. }
  57833. const String& PropertyPanel::getMessageWhenEmpty() const
  57834. {
  57835. return messageWhenEmpty;
  57836. }
  57837. END_JUCE_NAMESPACE
  57838. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  57839. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  57840. BEGIN_JUCE_NAMESPACE
  57841. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  57842. const double rangeMin,
  57843. const double rangeMax,
  57844. const double interval,
  57845. const double skewFactor)
  57846. : PropertyComponent (name)
  57847. {
  57848. addAndMakeVisible (&slider);
  57849. slider.setRange (rangeMin, rangeMax, interval);
  57850. slider.setSkewFactor (skewFactor);
  57851. slider.setSliderStyle (Slider::LinearBar);
  57852. slider.addListener (this);
  57853. }
  57854. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  57855. const String& name,
  57856. const double rangeMin,
  57857. const double rangeMax,
  57858. const double interval,
  57859. const double skewFactor)
  57860. : PropertyComponent (name)
  57861. {
  57862. addAndMakeVisible (&slider);
  57863. slider.setRange (rangeMin, rangeMax, interval);
  57864. slider.setSkewFactor (skewFactor);
  57865. slider.setSliderStyle (Slider::LinearBar);
  57866. slider.getValueObject().referTo (valueToControl);
  57867. }
  57868. SliderPropertyComponent::~SliderPropertyComponent()
  57869. {
  57870. }
  57871. void SliderPropertyComponent::setValue (const double /*newValue*/)
  57872. {
  57873. }
  57874. double SliderPropertyComponent::getValue() const
  57875. {
  57876. return slider.getValue();
  57877. }
  57878. void SliderPropertyComponent::refresh()
  57879. {
  57880. slider.setValue (getValue(), false);
  57881. }
  57882. void SliderPropertyComponent::sliderValueChanged (Slider*)
  57883. {
  57884. if (getValue() != slider.getValue())
  57885. setValue (slider.getValue());
  57886. }
  57887. END_JUCE_NAMESPACE
  57888. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  57889. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  57890. BEGIN_JUCE_NAMESPACE
  57891. class TextPropLabel : public Label
  57892. {
  57893. TextPropertyComponent& owner;
  57894. int maxChars;
  57895. bool isMultiline;
  57896. public:
  57897. TextPropLabel (TextPropertyComponent& owner_,
  57898. const int maxChars_, const bool isMultiline_)
  57899. : Label (String::empty, String::empty),
  57900. owner (owner_),
  57901. maxChars (maxChars_),
  57902. isMultiline (isMultiline_)
  57903. {
  57904. setEditable (true, true, false);
  57905. setColour (backgroundColourId, Colours::white);
  57906. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  57907. }
  57908. ~TextPropLabel()
  57909. {
  57910. }
  57911. TextEditor* createEditorComponent()
  57912. {
  57913. TextEditor* const textEditor = Label::createEditorComponent();
  57914. textEditor->setInputRestrictions (maxChars);
  57915. if (isMultiline)
  57916. {
  57917. textEditor->setMultiLine (true, true);
  57918. textEditor->setReturnKeyStartsNewLine (true);
  57919. }
  57920. return textEditor;
  57921. }
  57922. void textWasEdited()
  57923. {
  57924. owner.textWasEdited();
  57925. }
  57926. };
  57927. TextPropertyComponent::TextPropertyComponent (const String& name,
  57928. const int maxNumChars,
  57929. const bool isMultiLine)
  57930. : PropertyComponent (name)
  57931. {
  57932. createEditor (maxNumChars, isMultiLine);
  57933. }
  57934. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  57935. const String& name,
  57936. const int maxNumChars,
  57937. const bool isMultiLine)
  57938. : PropertyComponent (name)
  57939. {
  57940. createEditor (maxNumChars, isMultiLine);
  57941. textEditor->getTextValue().referTo (valueToControl);
  57942. }
  57943. TextPropertyComponent::~TextPropertyComponent()
  57944. {
  57945. deleteAllChildren();
  57946. }
  57947. void TextPropertyComponent::setText (const String& newText)
  57948. {
  57949. textEditor->setText (newText, true);
  57950. }
  57951. const String TextPropertyComponent::getText() const
  57952. {
  57953. return textEditor->getText();
  57954. }
  57955. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  57956. {
  57957. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  57958. if (isMultiLine)
  57959. {
  57960. textEditor->setJustificationType (Justification::topLeft);
  57961. preferredHeight = 120;
  57962. }
  57963. }
  57964. void TextPropertyComponent::refresh()
  57965. {
  57966. textEditor->setText (getText(), false);
  57967. }
  57968. void TextPropertyComponent::textWasEdited()
  57969. {
  57970. const String newText (textEditor->getText());
  57971. if (getText() != newText)
  57972. setText (newText);
  57973. }
  57974. END_JUCE_NAMESPACE
  57975. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  57976. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  57977. BEGIN_JUCE_NAMESPACE
  57978. class SimpleDeviceManagerInputLevelMeter : public Component,
  57979. public Timer
  57980. {
  57981. public:
  57982. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  57983. : manager (manager_),
  57984. level (0)
  57985. {
  57986. startTimer (50);
  57987. manager->enableInputLevelMeasurement (true);
  57988. }
  57989. ~SimpleDeviceManagerInputLevelMeter()
  57990. {
  57991. manager->enableInputLevelMeasurement (false);
  57992. }
  57993. void timerCallback()
  57994. {
  57995. const float newLevel = (float) manager->getCurrentInputLevel();
  57996. if (std::abs (level - newLevel) > 0.005f)
  57997. {
  57998. level = newLevel;
  57999. repaint();
  58000. }
  58001. }
  58002. void paint (Graphics& g)
  58003. {
  58004. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58005. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58006. }
  58007. private:
  58008. AudioDeviceManager* const manager;
  58009. float level;
  58010. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  58011. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  58012. };
  58013. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58014. public ListBoxModel
  58015. {
  58016. public:
  58017. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58018. const String& noItemsMessage_,
  58019. const int minNumber_,
  58020. const int maxNumber_)
  58021. : ListBox (String::empty, 0),
  58022. deviceManager (deviceManager_),
  58023. noItemsMessage (noItemsMessage_),
  58024. minNumber (minNumber_),
  58025. maxNumber (maxNumber_)
  58026. {
  58027. items = MidiInput::getDevices();
  58028. setModel (this);
  58029. setOutlineThickness (1);
  58030. }
  58031. ~MidiInputSelectorComponentListBox()
  58032. {
  58033. }
  58034. int getNumRows()
  58035. {
  58036. return items.size();
  58037. }
  58038. void paintListBoxItem (int row,
  58039. Graphics& g,
  58040. int width, int height,
  58041. bool rowIsSelected)
  58042. {
  58043. if (((unsigned int) row) < (unsigned int) items.size())
  58044. {
  58045. if (rowIsSelected)
  58046. g.fillAll (findColour (TextEditor::highlightColourId)
  58047. .withMultipliedAlpha (0.3f));
  58048. const String item (items [row]);
  58049. bool enabled = deviceManager.isMidiInputEnabled (item);
  58050. const int x = getTickX();
  58051. const float tickW = height * 0.75f;
  58052. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58053. enabled, true, true, false);
  58054. g.setFont (height * 0.6f);
  58055. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58056. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58057. }
  58058. }
  58059. void listBoxItemClicked (int row, const MouseEvent& e)
  58060. {
  58061. selectRow (row);
  58062. if (e.x < getTickX())
  58063. flipEnablement (row);
  58064. }
  58065. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58066. {
  58067. flipEnablement (row);
  58068. }
  58069. void returnKeyPressed (int row)
  58070. {
  58071. flipEnablement (row);
  58072. }
  58073. void paint (Graphics& g)
  58074. {
  58075. ListBox::paint (g);
  58076. if (items.size() == 0)
  58077. {
  58078. g.setColour (Colours::grey);
  58079. g.setFont (13.0f);
  58080. g.drawText (noItemsMessage,
  58081. 0, 0, getWidth(), getHeight() / 2,
  58082. Justification::centred, true);
  58083. }
  58084. }
  58085. int getBestHeight (const int preferredHeight)
  58086. {
  58087. const int extra = getOutlineThickness() * 2;
  58088. return jmax (getRowHeight() * 2 + extra,
  58089. jmin (getRowHeight() * getNumRows() + extra,
  58090. preferredHeight));
  58091. }
  58092. juce_UseDebuggingNewOperator
  58093. private:
  58094. AudioDeviceManager& deviceManager;
  58095. const String noItemsMessage;
  58096. StringArray items;
  58097. int minNumber, maxNumber;
  58098. void flipEnablement (const int row)
  58099. {
  58100. if (((unsigned int) row) < (unsigned int) items.size())
  58101. {
  58102. const String item (items [row]);
  58103. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58104. }
  58105. }
  58106. int getTickX() const
  58107. {
  58108. return getRowHeight() + 5;
  58109. }
  58110. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  58111. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  58112. };
  58113. class AudioDeviceSettingsPanel : public Component,
  58114. public ChangeListener,
  58115. public ComboBox::Listener,
  58116. public Button::Listener
  58117. {
  58118. public:
  58119. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58120. AudioIODeviceType::DeviceSetupDetails& setup_,
  58121. const bool hideAdvancedOptionsWithButton)
  58122. : type (type_),
  58123. setup (setup_)
  58124. {
  58125. if (hideAdvancedOptionsWithButton)
  58126. {
  58127. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58128. showAdvancedSettingsButton->addButtonListener (this);
  58129. }
  58130. type->scanForDevices();
  58131. setup.manager->addChangeListener (this);
  58132. changeListenerCallback (0);
  58133. }
  58134. ~AudioDeviceSettingsPanel()
  58135. {
  58136. setup.manager->removeChangeListener (this);
  58137. }
  58138. void resized()
  58139. {
  58140. const int lx = proportionOfWidth (0.35f);
  58141. const int w = proportionOfWidth (0.4f);
  58142. const int h = 24;
  58143. const int space = 6;
  58144. const int dh = h + space;
  58145. int y = 0;
  58146. if (outputDeviceDropDown != 0)
  58147. {
  58148. outputDeviceDropDown->setBounds (lx, y, w, h);
  58149. if (testButton != 0)
  58150. testButton->setBounds (proportionOfWidth (0.77f),
  58151. outputDeviceDropDown->getY(),
  58152. proportionOfWidth (0.18f),
  58153. h);
  58154. y += dh;
  58155. }
  58156. if (inputDeviceDropDown != 0)
  58157. {
  58158. inputDeviceDropDown->setBounds (lx, y, w, h);
  58159. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58160. inputDeviceDropDown->getY(),
  58161. proportionOfWidth (0.18f),
  58162. h);
  58163. y += dh;
  58164. }
  58165. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58166. if (outputChanList != 0)
  58167. {
  58168. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58169. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58170. y += bh + space;
  58171. }
  58172. if (inputChanList != 0)
  58173. {
  58174. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58175. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58176. y += bh + space;
  58177. }
  58178. y += space * 2;
  58179. if (showAdvancedSettingsButton != 0)
  58180. {
  58181. showAdvancedSettingsButton->changeWidthToFitText (h);
  58182. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58183. }
  58184. if (sampleRateDropDown != 0)
  58185. {
  58186. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58187. || ! showAdvancedSettingsButton->isVisible());
  58188. sampleRateDropDown->setBounds (lx, y, w, h);
  58189. y += dh;
  58190. }
  58191. if (bufferSizeDropDown != 0)
  58192. {
  58193. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58194. || ! showAdvancedSettingsButton->isVisible());
  58195. bufferSizeDropDown->setBounds (lx, y, w, h);
  58196. y += dh;
  58197. }
  58198. if (showUIButton != 0)
  58199. {
  58200. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58201. || ! showAdvancedSettingsButton->isVisible());
  58202. showUIButton->changeWidthToFitText (h);
  58203. showUIButton->setTopLeftPosition (lx, y);
  58204. }
  58205. }
  58206. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58207. {
  58208. if (comboBoxThatHasChanged == 0)
  58209. return;
  58210. AudioDeviceManager::AudioDeviceSetup config;
  58211. setup.manager->getAudioDeviceSetup (config);
  58212. String error;
  58213. if (comboBoxThatHasChanged == outputDeviceDropDown
  58214. || comboBoxThatHasChanged == inputDeviceDropDown)
  58215. {
  58216. if (outputDeviceDropDown != 0)
  58217. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58218. : outputDeviceDropDown->getText();
  58219. if (inputDeviceDropDown != 0)
  58220. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58221. : inputDeviceDropDown->getText();
  58222. if (! type->hasSeparateInputsAndOutputs())
  58223. config.inputDeviceName = config.outputDeviceName;
  58224. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58225. config.useDefaultInputChannels = true;
  58226. else
  58227. config.useDefaultOutputChannels = true;
  58228. error = setup.manager->setAudioDeviceSetup (config, true);
  58229. showCorrectDeviceName (inputDeviceDropDown, true);
  58230. showCorrectDeviceName (outputDeviceDropDown, false);
  58231. updateControlPanelButton();
  58232. resized();
  58233. }
  58234. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58235. {
  58236. if (sampleRateDropDown->getSelectedId() > 0)
  58237. {
  58238. config.sampleRate = sampleRateDropDown->getSelectedId();
  58239. error = setup.manager->setAudioDeviceSetup (config, true);
  58240. }
  58241. }
  58242. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58243. {
  58244. if (bufferSizeDropDown->getSelectedId() > 0)
  58245. {
  58246. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58247. error = setup.manager->setAudioDeviceSetup (config, true);
  58248. }
  58249. }
  58250. if (error.isNotEmpty())
  58251. {
  58252. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58253. "Error when trying to open audio device!",
  58254. error);
  58255. }
  58256. }
  58257. void buttonClicked (Button* button)
  58258. {
  58259. if (button == showAdvancedSettingsButton)
  58260. {
  58261. showAdvancedSettingsButton->setVisible (false);
  58262. resized();
  58263. }
  58264. else if (button == showUIButton)
  58265. {
  58266. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58267. if (device != 0 && device->showControlPanel())
  58268. {
  58269. setup.manager->closeAudioDevice();
  58270. setup.manager->restartLastAudioDevice();
  58271. getTopLevelComponent()->toFront (true);
  58272. }
  58273. }
  58274. else if (button == testButton && testButton != 0)
  58275. {
  58276. setup.manager->playTestSound();
  58277. }
  58278. }
  58279. void updateControlPanelButton()
  58280. {
  58281. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58282. showUIButton = 0;
  58283. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58284. {
  58285. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58286. TRANS ("opens the device's own control panel")));
  58287. showUIButton->addButtonListener (this);
  58288. }
  58289. resized();
  58290. }
  58291. void changeListenerCallback (void*)
  58292. {
  58293. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58294. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58295. {
  58296. if (outputDeviceDropDown == 0)
  58297. {
  58298. outputDeviceDropDown = new ComboBox (String::empty);
  58299. outputDeviceDropDown->addListener (this);
  58300. addAndMakeVisible (outputDeviceDropDown);
  58301. outputDeviceLabel = new Label (String::empty,
  58302. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58303. : TRANS ("device:"));
  58304. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58305. if (setup.maxNumOutputChannels > 0)
  58306. {
  58307. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58308. testButton->addButtonListener (this);
  58309. }
  58310. }
  58311. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58312. }
  58313. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58314. {
  58315. if (inputDeviceDropDown == 0)
  58316. {
  58317. inputDeviceDropDown = new ComboBox (String::empty);
  58318. inputDeviceDropDown->addListener (this);
  58319. addAndMakeVisible (inputDeviceDropDown);
  58320. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58321. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58322. addAndMakeVisible (inputLevelMeter
  58323. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58324. }
  58325. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58326. }
  58327. updateControlPanelButton();
  58328. showCorrectDeviceName (inputDeviceDropDown, true);
  58329. showCorrectDeviceName (outputDeviceDropDown, false);
  58330. if (currentDevice != 0)
  58331. {
  58332. if (setup.maxNumOutputChannels > 0
  58333. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58334. {
  58335. if (outputChanList == 0)
  58336. {
  58337. addAndMakeVisible (outputChanList
  58338. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58339. TRANS ("(no audio output channels found)")));
  58340. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58341. outputChanLabel->attachToComponent (outputChanList, true);
  58342. }
  58343. outputChanList->refresh();
  58344. }
  58345. else
  58346. {
  58347. outputChanLabel = 0;
  58348. outputChanList = 0;
  58349. }
  58350. if (setup.maxNumInputChannels > 0
  58351. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58352. {
  58353. if (inputChanList == 0)
  58354. {
  58355. addAndMakeVisible (inputChanList
  58356. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58357. TRANS ("(no audio input channels found)")));
  58358. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58359. inputChanLabel->attachToComponent (inputChanList, true);
  58360. }
  58361. inputChanList->refresh();
  58362. }
  58363. else
  58364. {
  58365. inputChanLabel = 0;
  58366. inputChanList = 0;
  58367. }
  58368. // sample rate..
  58369. {
  58370. if (sampleRateDropDown == 0)
  58371. {
  58372. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58373. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58374. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58375. }
  58376. else
  58377. {
  58378. sampleRateDropDown->clear();
  58379. sampleRateDropDown->removeListener (this);
  58380. }
  58381. const int numRates = currentDevice->getNumSampleRates();
  58382. for (int i = 0; i < numRates; ++i)
  58383. {
  58384. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58385. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58386. }
  58387. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58388. sampleRateDropDown->addListener (this);
  58389. }
  58390. // buffer size
  58391. {
  58392. if (bufferSizeDropDown == 0)
  58393. {
  58394. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58395. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58396. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58397. }
  58398. else
  58399. {
  58400. bufferSizeDropDown->clear();
  58401. bufferSizeDropDown->removeListener (this);
  58402. }
  58403. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58404. double currentRate = currentDevice->getCurrentSampleRate();
  58405. if (currentRate == 0)
  58406. currentRate = 48000.0;
  58407. for (int i = 0; i < numBufferSizes; ++i)
  58408. {
  58409. const int bs = currentDevice->getBufferSizeSamples (i);
  58410. bufferSizeDropDown->addItem (String (bs)
  58411. + " samples ("
  58412. + String (bs * 1000.0 / currentRate, 1)
  58413. + " ms)",
  58414. bs);
  58415. }
  58416. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58417. bufferSizeDropDown->addListener (this);
  58418. }
  58419. }
  58420. else
  58421. {
  58422. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58423. sampleRateLabel = 0;
  58424. bufferSizeLabel = 0;
  58425. sampleRateDropDown = 0;
  58426. bufferSizeDropDown = 0;
  58427. if (outputDeviceDropDown != 0)
  58428. outputDeviceDropDown->setSelectedId (-1, true);
  58429. if (inputDeviceDropDown != 0)
  58430. inputDeviceDropDown->setSelectedId (-1, true);
  58431. }
  58432. resized();
  58433. setSize (getWidth(), getLowestY() + 4);
  58434. }
  58435. private:
  58436. AudioIODeviceType* const type;
  58437. const AudioIODeviceType::DeviceSetupDetails setup;
  58438. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  58439. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  58440. ScopedPointer<TextButton> testButton;
  58441. ScopedPointer<Component> inputLevelMeter;
  58442. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  58443. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58444. {
  58445. if (box != 0)
  58446. {
  58447. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58448. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58449. box->setSelectedId (index + 1, true);
  58450. if (testButton != 0 && ! isInput)
  58451. testButton->setEnabled (index >= 0);
  58452. }
  58453. }
  58454. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58455. {
  58456. const StringArray devs (type->getDeviceNames (isInputs));
  58457. combo.clear (true);
  58458. for (int i = 0; i < devs.size(); ++i)
  58459. combo.addItem (devs[i], i + 1);
  58460. combo.addItem (TRANS("<< none >>"), -1);
  58461. combo.setSelectedId (-1, true);
  58462. }
  58463. int getLowestY() const
  58464. {
  58465. int y = 0;
  58466. for (int i = getNumChildComponents(); --i >= 0;)
  58467. y = jmax (y, getChildComponent (i)->getBottom());
  58468. return y;
  58469. }
  58470. public:
  58471. class ChannelSelectorListBox : public ListBox,
  58472. public ListBoxModel
  58473. {
  58474. public:
  58475. enum BoxType
  58476. {
  58477. audioInputType,
  58478. audioOutputType
  58479. };
  58480. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  58481. const BoxType type_,
  58482. const String& noItemsMessage_)
  58483. : ListBox (String::empty, 0),
  58484. setup (setup_),
  58485. type (type_),
  58486. noItemsMessage (noItemsMessage_)
  58487. {
  58488. refresh();
  58489. setModel (this);
  58490. setOutlineThickness (1);
  58491. }
  58492. ~ChannelSelectorListBox()
  58493. {
  58494. }
  58495. void refresh()
  58496. {
  58497. items.clear();
  58498. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58499. if (currentDevice != 0)
  58500. {
  58501. if (type == audioInputType)
  58502. items = currentDevice->getInputChannelNames();
  58503. else if (type == audioOutputType)
  58504. items = currentDevice->getOutputChannelNames();
  58505. if (setup.useStereoPairs)
  58506. {
  58507. StringArray pairs;
  58508. for (int i = 0; i < items.size(); i += 2)
  58509. {
  58510. const String name (items[i]);
  58511. const String name2 (items[i + 1]);
  58512. String commonBit;
  58513. for (int j = 0; j < name.length(); ++j)
  58514. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  58515. commonBit = name.substring (0, j);
  58516. // Make sure we only split the name at a space, because otherwise, things
  58517. // like "input 11" + "input 12" would become "input 11 + 2"
  58518. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  58519. commonBit = commonBit.dropLastCharacters (1);
  58520. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  58521. }
  58522. items = pairs;
  58523. }
  58524. }
  58525. updateContent();
  58526. repaint();
  58527. }
  58528. int getNumRows()
  58529. {
  58530. return items.size();
  58531. }
  58532. void paintListBoxItem (int row,
  58533. Graphics& g,
  58534. int width, int height,
  58535. bool rowIsSelected)
  58536. {
  58537. if (((unsigned int) row) < (unsigned int) items.size())
  58538. {
  58539. if (rowIsSelected)
  58540. g.fillAll (findColour (TextEditor::highlightColourId)
  58541. .withMultipliedAlpha (0.3f));
  58542. const String item (items [row]);
  58543. bool enabled = false;
  58544. AudioDeviceManager::AudioDeviceSetup config;
  58545. setup.manager->getAudioDeviceSetup (config);
  58546. if (setup.useStereoPairs)
  58547. {
  58548. if (type == audioInputType)
  58549. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  58550. else if (type == audioOutputType)
  58551. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  58552. }
  58553. else
  58554. {
  58555. if (type == audioInputType)
  58556. enabled = config.inputChannels [row];
  58557. else if (type == audioOutputType)
  58558. enabled = config.outputChannels [row];
  58559. }
  58560. const int x = getTickX();
  58561. const float tickW = height * 0.75f;
  58562. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58563. enabled, true, true, false);
  58564. g.setFont (height * 0.6f);
  58565. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58566. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58567. }
  58568. }
  58569. void listBoxItemClicked (int row, const MouseEvent& e)
  58570. {
  58571. selectRow (row);
  58572. if (e.x < getTickX())
  58573. flipEnablement (row);
  58574. }
  58575. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58576. {
  58577. flipEnablement (row);
  58578. }
  58579. void returnKeyPressed (int row)
  58580. {
  58581. flipEnablement (row);
  58582. }
  58583. void paint (Graphics& g)
  58584. {
  58585. ListBox::paint (g);
  58586. if (items.size() == 0)
  58587. {
  58588. g.setColour (Colours::grey);
  58589. g.setFont (13.0f);
  58590. g.drawText (noItemsMessage,
  58591. 0, 0, getWidth(), getHeight() / 2,
  58592. Justification::centred, true);
  58593. }
  58594. }
  58595. int getBestHeight (int maxHeight)
  58596. {
  58597. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  58598. getNumRows())
  58599. + getOutlineThickness() * 2;
  58600. }
  58601. juce_UseDebuggingNewOperator
  58602. private:
  58603. const AudioIODeviceType::DeviceSetupDetails setup;
  58604. const BoxType type;
  58605. const String noItemsMessage;
  58606. StringArray items;
  58607. void flipEnablement (const int row)
  58608. {
  58609. jassert (type == audioInputType || type == audioOutputType);
  58610. if (((unsigned int) row) < (unsigned int) items.size())
  58611. {
  58612. AudioDeviceManager::AudioDeviceSetup config;
  58613. setup.manager->getAudioDeviceSetup (config);
  58614. if (setup.useStereoPairs)
  58615. {
  58616. BigInteger bits;
  58617. BigInteger& original = (type == audioInputType ? config.inputChannels
  58618. : config.outputChannels);
  58619. int i;
  58620. for (i = 0; i < 256; i += 2)
  58621. bits.setBit (i / 2, original [i] || original [i + 1]);
  58622. if (type == audioInputType)
  58623. {
  58624. config.useDefaultInputChannels = false;
  58625. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  58626. }
  58627. else
  58628. {
  58629. config.useDefaultOutputChannels = false;
  58630. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  58631. }
  58632. for (i = 0; i < 256; ++i)
  58633. original.setBit (i, bits [i / 2]);
  58634. }
  58635. else
  58636. {
  58637. if (type == audioInputType)
  58638. {
  58639. config.useDefaultInputChannels = false;
  58640. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  58641. }
  58642. else
  58643. {
  58644. config.useDefaultOutputChannels = false;
  58645. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  58646. }
  58647. }
  58648. String error (setup.manager->setAudioDeviceSetup (config, true));
  58649. if (! error.isEmpty())
  58650. {
  58651. //xxx
  58652. }
  58653. }
  58654. }
  58655. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  58656. {
  58657. const int numActive = chans.countNumberOfSetBits();
  58658. if (chans [index])
  58659. {
  58660. if (numActive > minNumber)
  58661. chans.setBit (index, false);
  58662. }
  58663. else
  58664. {
  58665. if (numActive >= maxNumber)
  58666. {
  58667. const int firstActiveChan = chans.findNextSetBit();
  58668. chans.setBit (index > firstActiveChan
  58669. ? firstActiveChan : chans.getHighestBit(),
  58670. false);
  58671. }
  58672. chans.setBit (index, true);
  58673. }
  58674. }
  58675. int getTickX() const
  58676. {
  58677. return getRowHeight() + 5;
  58678. }
  58679. ChannelSelectorListBox (const ChannelSelectorListBox&);
  58680. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  58681. };
  58682. private:
  58683. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  58684. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  58685. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  58686. };
  58687. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  58688. const int minInputChannels_,
  58689. const int maxInputChannels_,
  58690. const int minOutputChannels_,
  58691. const int maxOutputChannels_,
  58692. const bool showMidiInputOptions,
  58693. const bool showMidiOutputSelector,
  58694. const bool showChannelsAsStereoPairs_,
  58695. const bool hideAdvancedOptionsWithButton_)
  58696. : deviceManager (deviceManager_),
  58697. deviceTypeDropDown (0),
  58698. deviceTypeDropDownLabel (0),
  58699. minOutputChannels (minOutputChannels_),
  58700. maxOutputChannels (maxOutputChannels_),
  58701. minInputChannels (minInputChannels_),
  58702. maxInputChannels (maxInputChannels_),
  58703. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  58704. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  58705. {
  58706. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  58707. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  58708. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  58709. {
  58710. deviceTypeDropDown = new ComboBox (String::empty);
  58711. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  58712. {
  58713. deviceTypeDropDown
  58714. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  58715. i + 1);
  58716. }
  58717. addAndMakeVisible (deviceTypeDropDown);
  58718. deviceTypeDropDown->addListener (this);
  58719. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  58720. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  58721. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  58722. }
  58723. if (showMidiInputOptions)
  58724. {
  58725. addAndMakeVisible (midiInputsList
  58726. = new MidiInputSelectorComponentListBox (deviceManager,
  58727. TRANS("(no midi inputs available)"),
  58728. 0, 0));
  58729. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  58730. midiInputsLabel->setJustificationType (Justification::topRight);
  58731. midiInputsLabel->attachToComponent (midiInputsList, true);
  58732. }
  58733. else
  58734. {
  58735. midiInputsList = 0;
  58736. midiInputsLabel = 0;
  58737. }
  58738. if (showMidiOutputSelector)
  58739. {
  58740. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  58741. midiOutputSelector->addListener (this);
  58742. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  58743. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  58744. }
  58745. else
  58746. {
  58747. midiOutputSelector = 0;
  58748. midiOutputLabel = 0;
  58749. }
  58750. deviceManager_.addChangeListener (this);
  58751. changeListenerCallback (0);
  58752. }
  58753. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  58754. {
  58755. deviceManager.removeChangeListener (this);
  58756. }
  58757. void AudioDeviceSelectorComponent::resized()
  58758. {
  58759. const int lx = proportionOfWidth (0.35f);
  58760. const int w = proportionOfWidth (0.4f);
  58761. const int h = 24;
  58762. const int space = 6;
  58763. const int dh = h + space;
  58764. int y = 15;
  58765. if (deviceTypeDropDown != 0)
  58766. {
  58767. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  58768. y += dh + space * 2;
  58769. }
  58770. if (audioDeviceSettingsComp != 0)
  58771. {
  58772. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  58773. y += audioDeviceSettingsComp->getHeight() + space;
  58774. }
  58775. if (midiInputsList != 0)
  58776. {
  58777. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  58778. midiInputsList->setBounds (lx, y, w, bh);
  58779. y += bh + space;
  58780. }
  58781. if (midiOutputSelector != 0)
  58782. midiOutputSelector->setBounds (lx, y, w, h);
  58783. }
  58784. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  58785. {
  58786. if (child == audioDeviceSettingsComp)
  58787. resized();
  58788. }
  58789. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  58790. {
  58791. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  58792. if (device != 0 && device->hasControlPanel())
  58793. {
  58794. if (device->showControlPanel())
  58795. deviceManager.restartLastAudioDevice();
  58796. getTopLevelComponent()->toFront (true);
  58797. }
  58798. }
  58799. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58800. {
  58801. if (comboBoxThatHasChanged == deviceTypeDropDown)
  58802. {
  58803. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  58804. if (type != 0)
  58805. {
  58806. audioDeviceSettingsComp = 0;
  58807. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  58808. changeListenerCallback (0); // needed in case the type hasn't actally changed
  58809. }
  58810. }
  58811. else if (comboBoxThatHasChanged == midiOutputSelector)
  58812. {
  58813. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  58814. }
  58815. }
  58816. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  58817. {
  58818. if (deviceTypeDropDown != 0)
  58819. {
  58820. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  58821. }
  58822. if (audioDeviceSettingsComp == 0
  58823. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  58824. {
  58825. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  58826. audioDeviceSettingsComp = 0;
  58827. AudioIODeviceType* const type
  58828. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  58829. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  58830. if (type != 0)
  58831. {
  58832. AudioIODeviceType::DeviceSetupDetails details;
  58833. details.manager = &deviceManager;
  58834. details.minNumInputChannels = minInputChannels;
  58835. details.maxNumInputChannels = maxInputChannels;
  58836. details.minNumOutputChannels = minOutputChannels;
  58837. details.maxNumOutputChannels = maxOutputChannels;
  58838. details.useStereoPairs = showChannelsAsStereoPairs;
  58839. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  58840. if (audioDeviceSettingsComp != 0)
  58841. {
  58842. addAndMakeVisible (audioDeviceSettingsComp);
  58843. audioDeviceSettingsComp->resized();
  58844. }
  58845. }
  58846. }
  58847. if (midiInputsList != 0)
  58848. {
  58849. midiInputsList->updateContent();
  58850. midiInputsList->repaint();
  58851. }
  58852. if (midiOutputSelector != 0)
  58853. {
  58854. midiOutputSelector->clear();
  58855. const StringArray midiOuts (MidiOutput::getDevices());
  58856. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  58857. midiOutputSelector->addSeparator();
  58858. for (int i = 0; i < midiOuts.size(); ++i)
  58859. midiOutputSelector->addItem (midiOuts[i], i + 1);
  58860. int current = -1;
  58861. if (deviceManager.getDefaultMidiOutput() != 0)
  58862. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  58863. midiOutputSelector->setSelectedId (current, true);
  58864. }
  58865. resized();
  58866. }
  58867. END_JUCE_NAMESPACE
  58868. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58869. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  58870. BEGIN_JUCE_NAMESPACE
  58871. BubbleComponent::BubbleComponent()
  58872. : side (0),
  58873. allowablePlacements (above | below | left | right),
  58874. arrowTipX (0.0f),
  58875. arrowTipY (0.0f)
  58876. {
  58877. setInterceptsMouseClicks (false, false);
  58878. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  58879. setComponentEffect (&shadow);
  58880. }
  58881. BubbleComponent::~BubbleComponent()
  58882. {
  58883. }
  58884. void BubbleComponent::paint (Graphics& g)
  58885. {
  58886. int x = content.getX();
  58887. int y = content.getY();
  58888. int w = content.getWidth();
  58889. int h = content.getHeight();
  58890. int cw, ch;
  58891. getContentSize (cw, ch);
  58892. if (side == 3)
  58893. x += w - cw;
  58894. else if (side != 1)
  58895. x += (w - cw) / 2;
  58896. w = cw;
  58897. if (side == 2)
  58898. y += h - ch;
  58899. else if (side != 0)
  58900. y += (h - ch) / 2;
  58901. h = ch;
  58902. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  58903. (float) x, (float) y,
  58904. (float) w, (float) h);
  58905. const int cx = x + (w - cw) / 2;
  58906. const int cy = y + (h - ch) / 2;
  58907. const int indent = 3;
  58908. g.setOrigin (cx + indent, cy + indent);
  58909. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  58910. paintContent (g, cw - indent * 2, ch - indent * 2);
  58911. }
  58912. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  58913. {
  58914. allowablePlacements = newPlacement;
  58915. }
  58916. void BubbleComponent::setPosition (Component* componentToPointTo)
  58917. {
  58918. jassert (componentToPointTo->isValidComponent());
  58919. Point<int> pos;
  58920. if (getParentComponent() != 0)
  58921. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  58922. else
  58923. pos = componentToPointTo->relativePositionToGlobal (pos);
  58924. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  58925. }
  58926. void BubbleComponent::setPosition (const int arrowTipX_,
  58927. const int arrowTipY_)
  58928. {
  58929. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  58930. }
  58931. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  58932. {
  58933. Rectangle<int> availableSpace;
  58934. if (getParentComponent() != 0)
  58935. {
  58936. availableSpace.setSize (getParentComponent()->getWidth(),
  58937. getParentComponent()->getHeight());
  58938. }
  58939. else
  58940. {
  58941. availableSpace = getParentMonitorArea();
  58942. }
  58943. int x = 0;
  58944. int y = 0;
  58945. int w = 150;
  58946. int h = 30;
  58947. getContentSize (w, h);
  58948. w += 30;
  58949. h += 30;
  58950. const float edgeIndent = 2.0f;
  58951. const int arrowLength = jmin (10, h / 3, w / 3);
  58952. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  58953. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  58954. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  58955. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  58956. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  58957. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  58958. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  58959. {
  58960. spaceLeft = spaceRight = 0;
  58961. }
  58962. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  58963. && (spaceLeft > w + 20 || spaceRight > w + 20))
  58964. {
  58965. spaceAbove = spaceBelow = 0;
  58966. }
  58967. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  58968. {
  58969. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  58970. arrowTipX = w * 0.5f;
  58971. content.setSize (w, h - arrowLength);
  58972. if (spaceAbove >= spaceBelow)
  58973. {
  58974. // above
  58975. y = rectangleToPointTo.getY() - h;
  58976. content.setPosition (0, 0);
  58977. arrowTipY = h - edgeIndent;
  58978. side = 2;
  58979. }
  58980. else
  58981. {
  58982. // below
  58983. y = rectangleToPointTo.getBottom();
  58984. content.setPosition (0, arrowLength);
  58985. arrowTipY = edgeIndent;
  58986. side = 0;
  58987. }
  58988. }
  58989. else
  58990. {
  58991. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  58992. arrowTipY = h * 0.5f;
  58993. content.setSize (w - arrowLength, h);
  58994. if (spaceLeft > spaceRight)
  58995. {
  58996. // on the left
  58997. x = rectangleToPointTo.getX() - w;
  58998. content.setPosition (0, 0);
  58999. arrowTipX = w - edgeIndent;
  59000. side = 3;
  59001. }
  59002. else
  59003. {
  59004. // on the right
  59005. x = rectangleToPointTo.getRight();
  59006. content.setPosition (arrowLength, 0);
  59007. arrowTipX = edgeIndent;
  59008. side = 1;
  59009. }
  59010. }
  59011. setBounds (x, y, w, h);
  59012. }
  59013. END_JUCE_NAMESPACE
  59014. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59015. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59016. BEGIN_JUCE_NAMESPACE
  59017. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59018. : fadeOutLength (fadeOutLengthMs),
  59019. deleteAfterUse (false)
  59020. {
  59021. }
  59022. BubbleMessageComponent::~BubbleMessageComponent()
  59023. {
  59024. fadeOutComponent (fadeOutLength);
  59025. }
  59026. void BubbleMessageComponent::showAt (int x, int y,
  59027. const String& text,
  59028. const int numMillisecondsBeforeRemoving,
  59029. const bool removeWhenMouseClicked,
  59030. const bool deleteSelfAfterUse)
  59031. {
  59032. textLayout.clear();
  59033. textLayout.setText (text, Font (14.0f));
  59034. textLayout.layout (256, Justification::centredLeft, true);
  59035. setPosition (x, y);
  59036. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59037. }
  59038. void BubbleMessageComponent::showAt (Component* const component,
  59039. const String& text,
  59040. const int numMillisecondsBeforeRemoving,
  59041. const bool removeWhenMouseClicked,
  59042. const bool deleteSelfAfterUse)
  59043. {
  59044. textLayout.clear();
  59045. textLayout.setText (text, Font (14.0f));
  59046. textLayout.layout (256, Justification::centredLeft, true);
  59047. setPosition (component);
  59048. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59049. }
  59050. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59051. const bool removeWhenMouseClicked,
  59052. const bool deleteSelfAfterUse)
  59053. {
  59054. setVisible (true);
  59055. deleteAfterUse = deleteSelfAfterUse;
  59056. if (numMillisecondsBeforeRemoving > 0)
  59057. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59058. else
  59059. expiryTime = 0;
  59060. startTimer (77);
  59061. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59062. if (! (removeWhenMouseClicked && isShowing()))
  59063. mouseClickCounter += 0xfffff;
  59064. repaint();
  59065. }
  59066. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59067. {
  59068. w = textLayout.getWidth() + 16;
  59069. h = textLayout.getHeight() + 16;
  59070. }
  59071. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59072. {
  59073. g.setColour (findColour (TooltipWindow::textColourId));
  59074. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59075. }
  59076. void BubbleMessageComponent::timerCallback()
  59077. {
  59078. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59079. {
  59080. stopTimer();
  59081. setVisible (false);
  59082. if (deleteAfterUse)
  59083. delete this;
  59084. }
  59085. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59086. {
  59087. stopTimer();
  59088. fadeOutComponent (fadeOutLength);
  59089. if (deleteAfterUse)
  59090. delete this;
  59091. }
  59092. }
  59093. END_JUCE_NAMESPACE
  59094. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59095. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59096. BEGIN_JUCE_NAMESPACE
  59097. class ColourComponentSlider : public Slider
  59098. {
  59099. public:
  59100. ColourComponentSlider (const String& name)
  59101. : Slider (name)
  59102. {
  59103. setRange (0.0, 255.0, 1.0);
  59104. }
  59105. ~ColourComponentSlider()
  59106. {
  59107. }
  59108. const String getTextFromValue (double value)
  59109. {
  59110. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59111. }
  59112. double getValueFromText (const String& text)
  59113. {
  59114. return (double) text.getHexValue32();
  59115. }
  59116. private:
  59117. ColourComponentSlider (const ColourComponentSlider&);
  59118. ColourComponentSlider& operator= (const ColourComponentSlider&);
  59119. };
  59120. class ColourSpaceMarker : public Component
  59121. {
  59122. public:
  59123. ColourSpaceMarker()
  59124. {
  59125. setInterceptsMouseClicks (false, false);
  59126. }
  59127. ~ColourSpaceMarker()
  59128. {
  59129. }
  59130. void paint (Graphics& g)
  59131. {
  59132. g.setColour (Colour::greyLevel (0.1f));
  59133. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59134. g.setColour (Colour::greyLevel (0.9f));
  59135. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59136. }
  59137. private:
  59138. ColourSpaceMarker (const ColourSpaceMarker&);
  59139. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  59140. };
  59141. class ColourSelector::ColourSpaceView : public Component
  59142. {
  59143. public:
  59144. ColourSpaceView (ColourSelector* owner_,
  59145. float& h_, float& s_, float& v_,
  59146. const int edgeSize)
  59147. : owner (owner_),
  59148. h (h_), s (s_), v (v_),
  59149. lastHue (0.0f),
  59150. edge (edgeSize)
  59151. {
  59152. addAndMakeVisible (&marker);
  59153. setMouseCursor (MouseCursor::CrosshairCursor);
  59154. }
  59155. ~ColourSpaceView()
  59156. {
  59157. }
  59158. void paint (Graphics& g)
  59159. {
  59160. if (colours.isNull())
  59161. {
  59162. const int width = getWidth() / 2;
  59163. const int height = getHeight() / 2;
  59164. colours = Image (Image::RGB, width, height, false);
  59165. Image::BitmapData pixels (colours, true);
  59166. for (int y = 0; y < height; ++y)
  59167. {
  59168. const float val = 1.0f - y / (float) height;
  59169. for (int x = 0; x < width; ++x)
  59170. {
  59171. const float sat = x / (float) width;
  59172. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59173. }
  59174. }
  59175. }
  59176. g.setOpacity (1.0f);
  59177. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59178. 0, 0, colours.getWidth(), colours.getHeight());
  59179. }
  59180. void mouseDown (const MouseEvent& e)
  59181. {
  59182. mouseDrag (e);
  59183. }
  59184. void mouseDrag (const MouseEvent& e)
  59185. {
  59186. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59187. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59188. owner->setSV (sat, val);
  59189. }
  59190. void updateIfNeeded()
  59191. {
  59192. if (lastHue != h)
  59193. {
  59194. lastHue = h;
  59195. colours = Image::null;
  59196. repaint();
  59197. }
  59198. updateMarker();
  59199. }
  59200. void resized()
  59201. {
  59202. colours = Image::null;
  59203. updateMarker();
  59204. }
  59205. private:
  59206. ColourSelector* const owner;
  59207. float& h;
  59208. float& s;
  59209. float& v;
  59210. float lastHue;
  59211. ColourSpaceMarker marker;
  59212. const int edge;
  59213. Image colours;
  59214. void updateMarker()
  59215. {
  59216. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59217. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59218. edge * 2, edge * 2);
  59219. }
  59220. ColourSpaceView (const ColourSpaceView&);
  59221. ColourSpaceView& operator= (const ColourSpaceView&);
  59222. };
  59223. class HueSelectorMarker : public Component
  59224. {
  59225. public:
  59226. HueSelectorMarker()
  59227. {
  59228. setInterceptsMouseClicks (false, false);
  59229. }
  59230. ~HueSelectorMarker()
  59231. {
  59232. }
  59233. void paint (Graphics& g)
  59234. {
  59235. Path p;
  59236. p.addTriangle (1.0f, 1.0f,
  59237. getWidth() * 0.3f, getHeight() * 0.5f,
  59238. 1.0f, getHeight() - 1.0f);
  59239. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59240. getWidth() * 0.7f, getHeight() * 0.5f,
  59241. getWidth() - 1.0f, getHeight() - 1.0f);
  59242. g.setColour (Colours::white.withAlpha (0.75f));
  59243. g.fillPath (p);
  59244. g.setColour (Colours::black.withAlpha (0.75f));
  59245. g.strokePath (p, PathStrokeType (1.2f));
  59246. }
  59247. private:
  59248. HueSelectorMarker (const HueSelectorMarker&);
  59249. HueSelectorMarker& operator= (const HueSelectorMarker&);
  59250. };
  59251. class ColourSelector::HueSelectorComp : public Component
  59252. {
  59253. public:
  59254. HueSelectorComp (ColourSelector* owner_,
  59255. float& h_, float& s_, float& v_,
  59256. const int edgeSize)
  59257. : owner (owner_),
  59258. h (h_), s (s_), v (v_),
  59259. lastHue (0.0f),
  59260. edge (edgeSize)
  59261. {
  59262. addAndMakeVisible (&marker);
  59263. }
  59264. ~HueSelectorComp()
  59265. {
  59266. }
  59267. void paint (Graphics& g)
  59268. {
  59269. const float yScale = 1.0f / (getHeight() - edge * 2);
  59270. const Rectangle<int> clip (g.getClipBounds());
  59271. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59272. {
  59273. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59274. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59275. }
  59276. }
  59277. void resized()
  59278. {
  59279. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59280. getWidth(), edge * 2);
  59281. }
  59282. void mouseDown (const MouseEvent& e)
  59283. {
  59284. mouseDrag (e);
  59285. }
  59286. void mouseDrag (const MouseEvent& e)
  59287. {
  59288. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  59289. owner->setHue (hue);
  59290. }
  59291. void updateIfNeeded()
  59292. {
  59293. resized();
  59294. }
  59295. private:
  59296. ColourSelector* const owner;
  59297. float& h;
  59298. float& s;
  59299. float& v;
  59300. float lastHue;
  59301. HueSelectorMarker marker;
  59302. const int edge;
  59303. HueSelectorComp (const HueSelectorComp&);
  59304. HueSelectorComp& operator= (const HueSelectorComp&);
  59305. };
  59306. class ColourSelector::SwatchComponent : public Component
  59307. {
  59308. public:
  59309. SwatchComponent (ColourSelector* owner_, int index_)
  59310. : owner (owner_),
  59311. index (index_)
  59312. {
  59313. }
  59314. ~SwatchComponent()
  59315. {
  59316. }
  59317. void paint (Graphics& g)
  59318. {
  59319. const Colour colour (owner->getSwatchColour (index));
  59320. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  59321. Colour (0xffdddddd).overlaidWith (colour),
  59322. Colour (0xffffffff).overlaidWith (colour));
  59323. }
  59324. void mouseDown (const MouseEvent&)
  59325. {
  59326. PopupMenu m;
  59327. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59328. m.addSeparator();
  59329. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59330. const int r = m.showAt (this);
  59331. if (r == 1)
  59332. {
  59333. owner->setCurrentColour (owner->getSwatchColour (index));
  59334. }
  59335. else if (r == 2)
  59336. {
  59337. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  59338. {
  59339. owner->setSwatchColour (index, owner->getCurrentColour());
  59340. repaint();
  59341. }
  59342. }
  59343. }
  59344. private:
  59345. ColourSelector* const owner;
  59346. const int index;
  59347. SwatchComponent (const SwatchComponent&);
  59348. SwatchComponent& operator= (const SwatchComponent&);
  59349. };
  59350. ColourSelector::ColourSelector (const int flags_,
  59351. const int edgeGap_,
  59352. const int gapAroundColourSpaceComponent)
  59353. : colour (Colours::white),
  59354. colourSpace (0),
  59355. hueSelector (0),
  59356. flags (flags_),
  59357. edgeGap (edgeGap_)
  59358. {
  59359. // not much point having a selector with no components in it!
  59360. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59361. updateHSV();
  59362. if ((flags & showSliders) != 0)
  59363. {
  59364. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59365. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59366. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59367. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59368. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59369. for (int i = 4; --i >= 0;)
  59370. sliders[i]->addListener (this);
  59371. }
  59372. else
  59373. {
  59374. zeromem (sliders, sizeof (sliders));
  59375. }
  59376. if ((flags & showColourspace) != 0)
  59377. {
  59378. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  59379. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  59380. }
  59381. update();
  59382. }
  59383. ColourSelector::~ColourSelector()
  59384. {
  59385. dispatchPendingMessages();
  59386. swatchComponents.clear();
  59387. deleteAllChildren();
  59388. }
  59389. const Colour ColourSelector::getCurrentColour() const
  59390. {
  59391. return ((flags & showAlphaChannel) != 0) ? colour
  59392. : colour.withAlpha ((uint8) 0xff);
  59393. }
  59394. void ColourSelector::setCurrentColour (const Colour& c)
  59395. {
  59396. if (c != colour)
  59397. {
  59398. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59399. updateHSV();
  59400. update();
  59401. }
  59402. }
  59403. void ColourSelector::setHue (float newH)
  59404. {
  59405. newH = jlimit (0.0f, 1.0f, newH);
  59406. if (h != newH)
  59407. {
  59408. h = newH;
  59409. colour = Colour (h, s, v, colour.getFloatAlpha());
  59410. update();
  59411. }
  59412. }
  59413. void ColourSelector::setSV (float newS, float newV)
  59414. {
  59415. newS = jlimit (0.0f, 1.0f, newS);
  59416. newV = jlimit (0.0f, 1.0f, newV);
  59417. if (s != newS || v != newV)
  59418. {
  59419. s = newS;
  59420. v = newV;
  59421. colour = Colour (h, s, v, colour.getFloatAlpha());
  59422. update();
  59423. }
  59424. }
  59425. void ColourSelector::updateHSV()
  59426. {
  59427. colour.getHSB (h, s, v);
  59428. }
  59429. void ColourSelector::update()
  59430. {
  59431. if (sliders[0] != 0)
  59432. {
  59433. sliders[0]->setValue ((int) colour.getRed());
  59434. sliders[1]->setValue ((int) colour.getGreen());
  59435. sliders[2]->setValue ((int) colour.getBlue());
  59436. sliders[3]->setValue ((int) colour.getAlpha());
  59437. }
  59438. if (colourSpace != 0)
  59439. {
  59440. colourSpace->updateIfNeeded();
  59441. hueSelector->updateIfNeeded();
  59442. }
  59443. if ((flags & showColourAtTop) != 0)
  59444. repaint (previewArea);
  59445. sendChangeMessage (this);
  59446. }
  59447. void ColourSelector::paint (Graphics& g)
  59448. {
  59449. g.fillAll (findColour (backgroundColourId));
  59450. if ((flags & showColourAtTop) != 0)
  59451. {
  59452. const Colour currentColour (getCurrentColour());
  59453. g.fillCheckerBoard (previewArea, 10, 10,
  59454. Colour (0xffdddddd).overlaidWith (currentColour),
  59455. Colour (0xffffffff).overlaidWith (currentColour));
  59456. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59457. g.setFont (14.0f, true);
  59458. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59459. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  59460. Justification::centred, false);
  59461. }
  59462. if ((flags & showSliders) != 0)
  59463. {
  59464. g.setColour (findColour (labelTextColourId));
  59465. g.setFont (11.0f);
  59466. for (int i = 4; --i >= 0;)
  59467. {
  59468. if (sliders[i]->isVisible())
  59469. g.drawText (sliders[i]->getName() + ":",
  59470. 0, sliders[i]->getY(),
  59471. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59472. Justification::centredRight, false);
  59473. }
  59474. }
  59475. }
  59476. void ColourSelector::resized()
  59477. {
  59478. const int swatchesPerRow = 8;
  59479. const int swatchHeight = 22;
  59480. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59481. const int numSwatches = getNumSwatches();
  59482. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59483. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59484. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59485. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  59486. int y = topSpace;
  59487. if ((flags & showColourspace) != 0)
  59488. {
  59489. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59490. colourSpace->setBounds (edgeGap, y,
  59491. getWidth() - hueWidth - edgeGap - 4,
  59492. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59493. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59494. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59495. colourSpace->getHeight());
  59496. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59497. }
  59498. if ((flags & showSliders) != 0)
  59499. {
  59500. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59501. for (int i = 0; i < numSliders; ++i)
  59502. {
  59503. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  59504. proportionOfWidth (0.72f), sliderHeight - 2);
  59505. y += sliderHeight;
  59506. }
  59507. }
  59508. if (numSwatches > 0)
  59509. {
  59510. const int startX = 8;
  59511. const int xGap = 4;
  59512. const int yGap = 4;
  59513. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  59514. y += edgeGap;
  59515. if (swatchComponents.size() != numSwatches)
  59516. {
  59517. swatchComponents.clear();
  59518. for (int i = 0; i < numSwatches; ++i)
  59519. {
  59520. SwatchComponent* const sc = new SwatchComponent (this, i);
  59521. swatchComponents.add (sc);
  59522. addAndMakeVisible (sc);
  59523. }
  59524. }
  59525. int x = startX;
  59526. for (int i = 0; i < swatchComponents.size(); ++i)
  59527. {
  59528. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  59529. sc->setBounds (x + xGap / 2,
  59530. y + yGap / 2,
  59531. swatchWidth - xGap,
  59532. swatchHeight - yGap);
  59533. if (((i + 1) % swatchesPerRow) == 0)
  59534. {
  59535. x = startX;
  59536. y += swatchHeight;
  59537. }
  59538. else
  59539. {
  59540. x += swatchWidth;
  59541. }
  59542. }
  59543. }
  59544. }
  59545. void ColourSelector::sliderValueChanged (Slider*)
  59546. {
  59547. if (sliders[0] != 0)
  59548. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  59549. (uint8) sliders[1]->getValue(),
  59550. (uint8) sliders[2]->getValue(),
  59551. (uint8) sliders[3]->getValue()));
  59552. }
  59553. int ColourSelector::getNumSwatches() const
  59554. {
  59555. return 0;
  59556. }
  59557. const Colour ColourSelector::getSwatchColour (const int) const
  59558. {
  59559. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59560. return Colours::black;
  59561. }
  59562. void ColourSelector::setSwatchColour (const int, const Colour&) const
  59563. {
  59564. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59565. }
  59566. END_JUCE_NAMESPACE
  59567. /*** End of inlined file: juce_ColourSelector.cpp ***/
  59568. /*** Start of inlined file: juce_DropShadower.cpp ***/
  59569. BEGIN_JUCE_NAMESPACE
  59570. class ShadowWindow : public Component
  59571. {
  59572. Component* owner;
  59573. Image shadowImageSections [12];
  59574. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  59575. public:
  59576. ShadowWindow (Component* const owner_,
  59577. const int type_,
  59578. const Image shadowImageSections_ [12])
  59579. : owner (owner_),
  59580. type (type_)
  59581. {
  59582. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  59583. shadowImageSections [i] = shadowImageSections_ [i];
  59584. setInterceptsMouseClicks (false, false);
  59585. if (owner_->isOnDesktop())
  59586. {
  59587. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  59588. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  59589. | ComponentPeer::windowIsTemporary
  59590. | ComponentPeer::windowIgnoresKeyPresses);
  59591. }
  59592. else if (owner_->getParentComponent() != 0)
  59593. {
  59594. owner_->getParentComponent()->addChildComponent (this);
  59595. }
  59596. }
  59597. ~ShadowWindow()
  59598. {
  59599. }
  59600. void paint (Graphics& g)
  59601. {
  59602. const Image& topLeft = shadowImageSections [type * 3];
  59603. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  59604. const Image& filler = shadowImageSections [type * 3 + 2];
  59605. g.setOpacity (1.0f);
  59606. if (type < 2)
  59607. {
  59608. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  59609. g.drawImage (topLeft,
  59610. 0, 0, topLeft.getWidth(), imH,
  59611. 0, 0, topLeft.getWidth(), imH);
  59612. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  59613. g.drawImage (bottomRight,
  59614. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  59615. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  59616. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59617. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  59618. }
  59619. else
  59620. {
  59621. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  59622. g.drawImage (topLeft,
  59623. 0, 0, imW, topLeft.getHeight(),
  59624. 0, 0, imW, topLeft.getHeight());
  59625. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  59626. g.drawImage (bottomRight,
  59627. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  59628. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  59629. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59630. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  59631. }
  59632. }
  59633. void resized()
  59634. {
  59635. repaint(); // (needed for correct repainting)
  59636. }
  59637. private:
  59638. ShadowWindow (const ShadowWindow&);
  59639. ShadowWindow& operator= (const ShadowWindow&);
  59640. };
  59641. DropShadower::DropShadower (const float alpha_,
  59642. const int xOffset_,
  59643. const int yOffset_,
  59644. const float blurRadius_)
  59645. : owner (0),
  59646. numShadows (0),
  59647. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  59648. xOffset (xOffset_),
  59649. yOffset (yOffset_),
  59650. alpha (alpha_),
  59651. blurRadius (blurRadius_),
  59652. inDestructor (false),
  59653. reentrant (false)
  59654. {
  59655. }
  59656. DropShadower::~DropShadower()
  59657. {
  59658. if (owner != 0)
  59659. owner->removeComponentListener (this);
  59660. inDestructor = true;
  59661. deleteShadowWindows();
  59662. }
  59663. void DropShadower::deleteShadowWindows()
  59664. {
  59665. if (numShadows > 0)
  59666. {
  59667. int i;
  59668. for (i = numShadows; --i >= 0;)
  59669. delete shadowWindows[i];
  59670. numShadows = 0;
  59671. }
  59672. }
  59673. void DropShadower::setOwner (Component* componentToFollow)
  59674. {
  59675. if (componentToFollow != owner)
  59676. {
  59677. if (owner != 0)
  59678. owner->removeComponentListener (this);
  59679. // (the component can't be null)
  59680. jassert (componentToFollow != 0);
  59681. owner = componentToFollow;
  59682. jassert (owner != 0);
  59683. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  59684. owner->addComponentListener (this);
  59685. updateShadows();
  59686. }
  59687. }
  59688. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  59689. {
  59690. updateShadows();
  59691. }
  59692. void DropShadower::componentBroughtToFront (Component&)
  59693. {
  59694. bringShadowWindowsToFront();
  59695. }
  59696. void DropShadower::componentChildrenChanged (Component&)
  59697. {
  59698. }
  59699. void DropShadower::componentParentHierarchyChanged (Component&)
  59700. {
  59701. deleteShadowWindows();
  59702. updateShadows();
  59703. }
  59704. void DropShadower::componentVisibilityChanged (Component&)
  59705. {
  59706. updateShadows();
  59707. }
  59708. void DropShadower::updateShadows()
  59709. {
  59710. if (reentrant || inDestructor || (owner == 0))
  59711. return;
  59712. reentrant = true;
  59713. ComponentPeer* const nw = owner->getPeer();
  59714. const bool isOwnerVisible = owner->isVisible()
  59715. && (nw == 0 || ! nw->isMinimised());
  59716. const bool createShadowWindows = numShadows == 0
  59717. && owner->getWidth() > 0
  59718. && owner->getHeight() > 0
  59719. && isOwnerVisible
  59720. && (Desktop::canUseSemiTransparentWindows()
  59721. || owner->getParentComponent() != 0);
  59722. if (createShadowWindows)
  59723. {
  59724. // keep a cached version of the image to save doing the gaussian too often
  59725. String imageId;
  59726. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  59727. const int hash = imageId.hashCode();
  59728. Image bigIm (ImageCache::getFromHashCode (hash));
  59729. if (bigIm.isNull())
  59730. {
  59731. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  59732. Graphics bigG (bigIm);
  59733. bigG.setColour (Colours::black.withAlpha (alpha));
  59734. bigG.fillRect (shadowEdge + xOffset,
  59735. shadowEdge + yOffset,
  59736. bigIm.getWidth() - (shadowEdge * 2),
  59737. bigIm.getHeight() - (shadowEdge * 2));
  59738. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  59739. blurKernel.createGaussianBlur (blurRadius);
  59740. blurKernel.applyToImage (bigIm, bigIm,
  59741. Rectangle<int> (xOffset, yOffset,
  59742. bigIm.getWidth(), bigIm.getHeight()));
  59743. ImageCache::addImageToCache (bigIm, hash);
  59744. }
  59745. const int iw = bigIm.getWidth();
  59746. const int ih = bigIm.getHeight();
  59747. const int shadowEdge2 = shadowEdge * 2;
  59748. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  59749. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  59750. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  59751. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  59752. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  59753. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  59754. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  59755. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  59756. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  59757. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  59758. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  59759. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  59760. for (int i = 0; i < 4; ++i)
  59761. {
  59762. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  59763. ++numShadows;
  59764. }
  59765. }
  59766. if (numShadows > 0)
  59767. {
  59768. for (int i = numShadows; --i >= 0;)
  59769. {
  59770. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  59771. shadowWindows[i]->setVisible (isOwnerVisible);
  59772. }
  59773. const int x = owner->getX();
  59774. const int y = owner->getY() - shadowEdge;
  59775. const int w = owner->getWidth();
  59776. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  59777. shadowWindows[0]->setBounds (x - shadowEdge,
  59778. y,
  59779. shadowEdge,
  59780. h);
  59781. shadowWindows[1]->setBounds (x + w,
  59782. y,
  59783. shadowEdge,
  59784. h);
  59785. shadowWindows[2]->setBounds (x,
  59786. y,
  59787. w,
  59788. shadowEdge);
  59789. shadowWindows[3]->setBounds (x,
  59790. owner->getBottom(),
  59791. w,
  59792. shadowEdge);
  59793. }
  59794. reentrant = false;
  59795. if (createShadowWindows)
  59796. bringShadowWindowsToFront();
  59797. }
  59798. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  59799. const int sx, const int sy)
  59800. {
  59801. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  59802. Graphics g (shadowImageSections[num]);
  59803. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  59804. }
  59805. void DropShadower::bringShadowWindowsToFront()
  59806. {
  59807. if (! (inDestructor || reentrant))
  59808. {
  59809. updateShadows();
  59810. reentrant = true;
  59811. for (int i = numShadows; --i >= 0;)
  59812. shadowWindows[i]->toBehind (owner);
  59813. reentrant = false;
  59814. }
  59815. }
  59816. END_JUCE_NAMESPACE
  59817. /*** End of inlined file: juce_DropShadower.cpp ***/
  59818. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  59819. BEGIN_JUCE_NAMESPACE
  59820. class MagnifyingPeer : public ComponentPeer
  59821. {
  59822. public:
  59823. MagnifyingPeer (Component* const component_,
  59824. MagnifierComponent* const magnifierComp_)
  59825. : ComponentPeer (component_, 0),
  59826. magnifierComp (magnifierComp_)
  59827. {
  59828. }
  59829. ~MagnifyingPeer()
  59830. {
  59831. }
  59832. void* getNativeHandle() const { return 0; }
  59833. void setVisible (bool) {}
  59834. void setTitle (const String&) {}
  59835. void setPosition (int, int) {}
  59836. void setSize (int, int) {}
  59837. void setBounds (int, int, int, int, bool) {}
  59838. void setMinimised (bool) {}
  59839. bool isMinimised() const { return false; }
  59840. void setFullScreen (bool) {}
  59841. bool isFullScreen() const { return false; }
  59842. const BorderSize getFrameSize() const { return BorderSize (0); }
  59843. bool setAlwaysOnTop (bool) { return true; }
  59844. void toFront (bool) {}
  59845. void toBehind (ComponentPeer*) {}
  59846. void setIcon (const Image&) {}
  59847. bool isFocused() const
  59848. {
  59849. return magnifierComp->hasKeyboardFocus (true);
  59850. }
  59851. void grabFocus()
  59852. {
  59853. ComponentPeer* peer = magnifierComp->getPeer();
  59854. if (peer != 0)
  59855. peer->grabFocus();
  59856. }
  59857. void textInputRequired (const Point<int>& position)
  59858. {
  59859. ComponentPeer* peer = magnifierComp->getPeer();
  59860. if (peer != 0)
  59861. peer->textInputRequired (position);
  59862. }
  59863. const Rectangle<int> getBounds() const
  59864. {
  59865. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  59866. component->getWidth(), component->getHeight());
  59867. }
  59868. const Point<int> getScreenPosition() const
  59869. {
  59870. return magnifierComp->getScreenPosition();
  59871. }
  59872. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  59873. {
  59874. const double zoom = magnifierComp->getScaleFactor();
  59875. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  59876. roundToInt (relativePosition.getY() * zoom)));
  59877. }
  59878. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  59879. {
  59880. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  59881. const double zoom = magnifierComp->getScaleFactor();
  59882. return Point<int> (roundToInt (p.getX() / zoom),
  59883. roundToInt (p.getY() / zoom));
  59884. }
  59885. bool contains (const Point<int>& position, bool) const
  59886. {
  59887. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  59888. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  59889. }
  59890. void repaint (const Rectangle<int>& area)
  59891. {
  59892. const double zoom = magnifierComp->getScaleFactor();
  59893. magnifierComp->repaint ((int) (area.getX() * zoom),
  59894. (int) (area.getY() * zoom),
  59895. roundToInt (area.getWidth() * zoom) + 1,
  59896. roundToInt (area.getHeight() * zoom) + 1);
  59897. }
  59898. void performAnyPendingRepaintsNow()
  59899. {
  59900. }
  59901. juce_UseDebuggingNewOperator
  59902. private:
  59903. MagnifierComponent* const magnifierComp;
  59904. MagnifyingPeer (const MagnifyingPeer&);
  59905. MagnifyingPeer& operator= (const MagnifyingPeer&);
  59906. };
  59907. class PeerHolderComp : public Component
  59908. {
  59909. public:
  59910. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  59911. : magnifierComp (magnifierComp_)
  59912. {
  59913. setVisible (true);
  59914. }
  59915. ~PeerHolderComp()
  59916. {
  59917. }
  59918. ComponentPeer* createNewPeer (int, void*)
  59919. {
  59920. return new MagnifyingPeer (this, magnifierComp);
  59921. }
  59922. void childBoundsChanged (Component* c)
  59923. {
  59924. if (c != 0)
  59925. {
  59926. setSize (c->getWidth(), c->getHeight());
  59927. magnifierComp->childBoundsChanged (this);
  59928. }
  59929. }
  59930. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  59931. {
  59932. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  59933. Component* const p = magnifierComp->getParentComponent();
  59934. if (p != 0)
  59935. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  59936. }
  59937. private:
  59938. MagnifierComponent* const magnifierComp;
  59939. PeerHolderComp (const PeerHolderComp&);
  59940. PeerHolderComp& operator= (const PeerHolderComp&);
  59941. };
  59942. MagnifierComponent::MagnifierComponent (Component* const content_,
  59943. const bool deleteContentCompWhenNoLongerNeeded)
  59944. : content (content_),
  59945. scaleFactor (0.0),
  59946. peer (0),
  59947. deleteContent (deleteContentCompWhenNoLongerNeeded),
  59948. quality (Graphics::lowResamplingQuality),
  59949. mouseSource (0, true)
  59950. {
  59951. holderComp = new PeerHolderComp (this);
  59952. setScaleFactor (1.0);
  59953. }
  59954. MagnifierComponent::~MagnifierComponent()
  59955. {
  59956. delete holderComp;
  59957. if (deleteContent)
  59958. delete content;
  59959. }
  59960. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  59961. {
  59962. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  59963. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  59964. if (scaleFactor != newScaleFactor)
  59965. {
  59966. scaleFactor = newScaleFactor;
  59967. if (scaleFactor == 1.0)
  59968. {
  59969. holderComp->removeFromDesktop();
  59970. peer = 0;
  59971. addChildComponent (content);
  59972. childBoundsChanged (content);
  59973. }
  59974. else
  59975. {
  59976. holderComp->addAndMakeVisible (content);
  59977. holderComp->childBoundsChanged (content);
  59978. childBoundsChanged (holderComp);
  59979. holderComp->addToDesktop (0);
  59980. peer = holderComp->getPeer();
  59981. }
  59982. repaint();
  59983. }
  59984. }
  59985. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  59986. {
  59987. quality = newQuality;
  59988. }
  59989. void MagnifierComponent::paint (Graphics& g)
  59990. {
  59991. const int w = holderComp->getWidth();
  59992. const int h = holderComp->getHeight();
  59993. if (w == 0 || h == 0)
  59994. return;
  59995. const Rectangle<int> r (g.getClipBounds());
  59996. const int srcX = (int) (r.getX() / scaleFactor);
  59997. const int srcY = (int) (r.getY() / scaleFactor);
  59998. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  59999. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  60000. if (scaleFactor >= 1.0)
  60001. {
  60002. ++srcW;
  60003. ++srcH;
  60004. }
  60005. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  60006. temp.clear (Rectangle<int> (srcX, srcY, srcW, srcH));
  60007. {
  60008. Graphics g2 (temp);
  60009. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  60010. holderComp->paintEntireComponent (g2);
  60011. }
  60012. g.setImageResamplingQuality (quality);
  60013. g.drawImageTransformed (temp, AffineTransform::scale ((float) scaleFactor, (float) scaleFactor), false);
  60014. }
  60015. void MagnifierComponent::childBoundsChanged (Component* c)
  60016. {
  60017. if (c != 0)
  60018. setSize (roundToInt (c->getWidth() * scaleFactor),
  60019. roundToInt (c->getHeight() * scaleFactor));
  60020. }
  60021. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  60022. {
  60023. if (peer != 0)
  60024. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  60025. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  60026. }
  60027. void MagnifierComponent::mouseDown (const MouseEvent& e)
  60028. {
  60029. passOnMouseEventToPeer (e);
  60030. }
  60031. void MagnifierComponent::mouseUp (const MouseEvent& e)
  60032. {
  60033. passOnMouseEventToPeer (e);
  60034. }
  60035. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  60036. {
  60037. passOnMouseEventToPeer (e);
  60038. }
  60039. void MagnifierComponent::mouseMove (const MouseEvent& e)
  60040. {
  60041. passOnMouseEventToPeer (e);
  60042. }
  60043. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  60044. {
  60045. passOnMouseEventToPeer (e);
  60046. }
  60047. void MagnifierComponent::mouseExit (const MouseEvent& e)
  60048. {
  60049. passOnMouseEventToPeer (e);
  60050. }
  60051. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60052. {
  60053. if (peer != 0)
  60054. peer->handleMouseWheel (e.source.getIndex(),
  60055. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  60056. ix * 256.0f, iy * 256.0f);
  60057. else
  60058. Component::mouseWheelMove (e, ix, iy);
  60059. }
  60060. int MagnifierComponent::scaleInt (const int n) const
  60061. {
  60062. return roundToInt (n / scaleFactor);
  60063. }
  60064. END_JUCE_NAMESPACE
  60065. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  60066. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60067. BEGIN_JUCE_NAMESPACE
  60068. class MidiKeyboardUpDownButton : public Button
  60069. {
  60070. public:
  60071. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  60072. const int delta_)
  60073. : Button (String::empty),
  60074. owner (owner_),
  60075. delta (delta_)
  60076. {
  60077. setOpaque (true);
  60078. }
  60079. ~MidiKeyboardUpDownButton()
  60080. {
  60081. }
  60082. void clicked()
  60083. {
  60084. int note = owner->getLowestVisibleKey();
  60085. if (delta < 0)
  60086. note = (note - 1) / 12;
  60087. else
  60088. note = note / 12 + 1;
  60089. owner->setLowestVisibleKey (note * 12);
  60090. }
  60091. void paintButton (Graphics& g,
  60092. bool isMouseOverButton,
  60093. bool isButtonDown)
  60094. {
  60095. owner->drawUpDownButton (g, getWidth(), getHeight(),
  60096. isMouseOverButton, isButtonDown,
  60097. delta > 0);
  60098. }
  60099. private:
  60100. MidiKeyboardComponent* const owner;
  60101. const int delta;
  60102. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  60103. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  60104. };
  60105. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60106. const Orientation orientation_)
  60107. : state (state_),
  60108. xOffset (0),
  60109. blackNoteLength (1),
  60110. keyWidth (16.0f),
  60111. orientation (orientation_),
  60112. midiChannel (1),
  60113. midiInChannelMask (0xffff),
  60114. velocity (1.0f),
  60115. noteUnderMouse (-1),
  60116. mouseDownNote (-1),
  60117. rangeStart (0),
  60118. rangeEnd (127),
  60119. firstKey (12 * 4),
  60120. canScroll (true),
  60121. mouseDragging (false),
  60122. useMousePositionForVelocity (true),
  60123. keyMappingOctave (6),
  60124. octaveNumForMiddleC (3)
  60125. {
  60126. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  60127. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  60128. // initialise with a default set of querty key-mappings..
  60129. const char* const keymap = "awsedftgyhujkolp;";
  60130. for (int i = String (keymap).length(); --i >= 0;)
  60131. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60132. setOpaque (true);
  60133. setWantsKeyboardFocus (true);
  60134. state.addListener (this);
  60135. }
  60136. MidiKeyboardComponent::~MidiKeyboardComponent()
  60137. {
  60138. state.removeListener (this);
  60139. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60140. deleteAllChildren();
  60141. }
  60142. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60143. {
  60144. keyWidth = widthInPixels;
  60145. resized();
  60146. }
  60147. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60148. {
  60149. if (orientation != newOrientation)
  60150. {
  60151. orientation = newOrientation;
  60152. resized();
  60153. }
  60154. }
  60155. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60156. const int highestNote)
  60157. {
  60158. jassert (lowestNote >= 0 && lowestNote <= 127);
  60159. jassert (highestNote >= 0 && highestNote <= 127);
  60160. jassert (lowestNote <= highestNote);
  60161. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60162. {
  60163. rangeStart = jlimit (0, 127, lowestNote);
  60164. rangeEnd = jlimit (0, 127, highestNote);
  60165. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60166. resized();
  60167. }
  60168. }
  60169. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60170. {
  60171. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60172. if (noteNumber != firstKey)
  60173. {
  60174. firstKey = noteNumber;
  60175. sendChangeMessage (this);
  60176. resized();
  60177. }
  60178. }
  60179. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60180. {
  60181. if (canScroll != canScroll_)
  60182. {
  60183. canScroll = canScroll_;
  60184. resized();
  60185. }
  60186. }
  60187. void MidiKeyboardComponent::colourChanged()
  60188. {
  60189. repaint();
  60190. }
  60191. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60192. {
  60193. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60194. if (midiChannel != midiChannelNumber)
  60195. {
  60196. resetAnyKeysInUse();
  60197. midiChannel = jlimit (1, 16, midiChannelNumber);
  60198. }
  60199. }
  60200. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60201. {
  60202. midiInChannelMask = midiChannelMask;
  60203. triggerAsyncUpdate();
  60204. }
  60205. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60206. {
  60207. velocity = jlimit (0.0f, 1.0f, velocity_);
  60208. useMousePositionForVelocity = useMousePositionForVelocity_;
  60209. }
  60210. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60211. {
  60212. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60213. static const float blackNoteWidth = 0.7f;
  60214. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60215. 1.0f, 2 - blackNoteWidth * 0.4f,
  60216. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60217. 4.0f, 5 - blackNoteWidth * 0.5f,
  60218. 5.0f, 6 - blackNoteWidth * 0.3f,
  60219. 6.0f };
  60220. static const float widths[] = { 1.0f, blackNoteWidth,
  60221. 1.0f, blackNoteWidth,
  60222. 1.0f, 1.0f, blackNoteWidth,
  60223. 1.0f, blackNoteWidth,
  60224. 1.0f, blackNoteWidth,
  60225. 1.0f };
  60226. const int octave = midiNoteNumber / 12;
  60227. const int note = midiNoteNumber % 12;
  60228. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60229. w = roundToInt (widths [note] * keyWidth_);
  60230. }
  60231. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60232. {
  60233. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60234. int rx, rw;
  60235. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60236. x -= xOffset + rx;
  60237. }
  60238. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60239. {
  60240. int x, y;
  60241. getKeyPos (midiNoteNumber, x, y);
  60242. return x;
  60243. }
  60244. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60245. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60246. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60247. {
  60248. if (! reallyContains (pos.getX(), pos.getY(), false))
  60249. return -1;
  60250. Point<int> p (pos);
  60251. if (orientation != horizontalKeyboard)
  60252. {
  60253. p = Point<int> (p.getY(), p.getX());
  60254. if (orientation == verticalKeyboardFacingLeft)
  60255. p = Point<int> (p.getX(), getWidth() - p.getY());
  60256. else
  60257. p = Point<int> (getHeight() - p.getX(), p.getY());
  60258. }
  60259. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60260. }
  60261. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60262. {
  60263. if (pos.getY() < blackNoteLength)
  60264. {
  60265. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60266. {
  60267. for (int i = 0; i < 5; ++i)
  60268. {
  60269. const int note = octaveStart + blackNotes [i];
  60270. if (note >= rangeStart && note <= rangeEnd)
  60271. {
  60272. int kx, kw;
  60273. getKeyPos (note, kx, kw);
  60274. kx += xOffset;
  60275. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60276. {
  60277. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60278. return note;
  60279. }
  60280. }
  60281. }
  60282. }
  60283. }
  60284. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60285. {
  60286. for (int i = 0; i < 7; ++i)
  60287. {
  60288. const int note = octaveStart + whiteNotes [i];
  60289. if (note >= rangeStart && note <= rangeEnd)
  60290. {
  60291. int kx, kw;
  60292. getKeyPos (note, kx, kw);
  60293. kx += xOffset;
  60294. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60295. {
  60296. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60297. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60298. return note;
  60299. }
  60300. }
  60301. }
  60302. }
  60303. mousePositionVelocity = 0;
  60304. return -1;
  60305. }
  60306. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60307. {
  60308. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60309. {
  60310. int x, w;
  60311. getKeyPos (noteNum, x, w);
  60312. if (orientation == horizontalKeyboard)
  60313. repaint (x, 0, w, getHeight());
  60314. else if (orientation == verticalKeyboardFacingLeft)
  60315. repaint (0, x, getWidth(), w);
  60316. else if (orientation == verticalKeyboardFacingRight)
  60317. repaint (0, getHeight() - x - w, getWidth(), w);
  60318. }
  60319. }
  60320. void MidiKeyboardComponent::paint (Graphics& g)
  60321. {
  60322. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60323. const Colour lineColour (findColour (keySeparatorLineColourId));
  60324. const Colour textColour (findColour (textLabelColourId));
  60325. int x, w, octave;
  60326. for (octave = 0; octave < 128; octave += 12)
  60327. {
  60328. for (int white = 0; white < 7; ++white)
  60329. {
  60330. const int noteNum = octave + whiteNotes [white];
  60331. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60332. {
  60333. getKeyPos (noteNum, x, w);
  60334. if (orientation == horizontalKeyboard)
  60335. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60336. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60337. noteUnderMouse == noteNum,
  60338. lineColour, textColour);
  60339. else if (orientation == verticalKeyboardFacingLeft)
  60340. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60341. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60342. noteUnderMouse == noteNum,
  60343. lineColour, textColour);
  60344. else if (orientation == verticalKeyboardFacingRight)
  60345. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60346. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60347. noteUnderMouse == noteNum,
  60348. lineColour, textColour);
  60349. }
  60350. }
  60351. }
  60352. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60353. if (orientation == verticalKeyboardFacingLeft)
  60354. {
  60355. x1 = getWidth() - 1.0f;
  60356. x2 = getWidth() - 5.0f;
  60357. }
  60358. else if (orientation == verticalKeyboardFacingRight)
  60359. x2 = 5.0f;
  60360. else
  60361. y2 = 5.0f;
  60362. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60363. Colours::transparentBlack, x2, y2, false));
  60364. getKeyPos (rangeEnd, x, w);
  60365. x += w;
  60366. if (orientation == verticalKeyboardFacingLeft)
  60367. g.fillRect (getWidth() - 5, 0, 5, x);
  60368. else if (orientation == verticalKeyboardFacingRight)
  60369. g.fillRect (0, 0, 5, x);
  60370. else
  60371. g.fillRect (0, 0, x, 5);
  60372. g.setColour (lineColour);
  60373. if (orientation == verticalKeyboardFacingLeft)
  60374. g.fillRect (0, 0, 1, x);
  60375. else if (orientation == verticalKeyboardFacingRight)
  60376. g.fillRect (getWidth() - 1, 0, 1, x);
  60377. else
  60378. g.fillRect (0, getHeight() - 1, x, 1);
  60379. const Colour blackNoteColour (findColour (blackNoteColourId));
  60380. for (octave = 0; octave < 128; octave += 12)
  60381. {
  60382. for (int black = 0; black < 5; ++black)
  60383. {
  60384. const int noteNum = octave + blackNotes [black];
  60385. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60386. {
  60387. getKeyPos (noteNum, x, w);
  60388. if (orientation == horizontalKeyboard)
  60389. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60390. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60391. noteUnderMouse == noteNum,
  60392. blackNoteColour);
  60393. else if (orientation == verticalKeyboardFacingLeft)
  60394. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60395. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60396. noteUnderMouse == noteNum,
  60397. blackNoteColour);
  60398. else if (orientation == verticalKeyboardFacingRight)
  60399. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60400. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60401. noteUnderMouse == noteNum,
  60402. blackNoteColour);
  60403. }
  60404. }
  60405. }
  60406. }
  60407. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60408. Graphics& g, int x, int y, int w, int h,
  60409. bool isDown, bool isOver,
  60410. const Colour& lineColour,
  60411. const Colour& textColour)
  60412. {
  60413. Colour c (Colours::transparentWhite);
  60414. if (isDown)
  60415. c = findColour (keyDownOverlayColourId);
  60416. if (isOver)
  60417. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60418. g.setColour (c);
  60419. g.fillRect (x, y, w, h);
  60420. const String text (getWhiteNoteText (midiNoteNumber));
  60421. if (! text.isEmpty())
  60422. {
  60423. g.setColour (textColour);
  60424. Font f (jmin (12.0f, keyWidth * 0.9f));
  60425. f.setHorizontalScale (0.8f);
  60426. g.setFont (f);
  60427. Justification justification (Justification::centredBottom);
  60428. if (orientation == verticalKeyboardFacingLeft)
  60429. justification = Justification::centredLeft;
  60430. else if (orientation == verticalKeyboardFacingRight)
  60431. justification = Justification::centredRight;
  60432. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60433. }
  60434. g.setColour (lineColour);
  60435. if (orientation == horizontalKeyboard)
  60436. g.fillRect (x, y, 1, h);
  60437. else if (orientation == verticalKeyboardFacingLeft)
  60438. g.fillRect (x, y, w, 1);
  60439. else if (orientation == verticalKeyboardFacingRight)
  60440. g.fillRect (x, y + h - 1, w, 1);
  60441. if (midiNoteNumber == rangeEnd)
  60442. {
  60443. if (orientation == horizontalKeyboard)
  60444. g.fillRect (x + w, y, 1, h);
  60445. else if (orientation == verticalKeyboardFacingLeft)
  60446. g.fillRect (x, y + h, w, 1);
  60447. else if (orientation == verticalKeyboardFacingRight)
  60448. g.fillRect (x, y - 1, w, 1);
  60449. }
  60450. }
  60451. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60452. Graphics& g, int x, int y, int w, int h,
  60453. bool isDown, bool isOver,
  60454. const Colour& noteFillColour)
  60455. {
  60456. Colour c (noteFillColour);
  60457. if (isDown)
  60458. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60459. if (isOver)
  60460. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60461. g.setColour (c);
  60462. g.fillRect (x, y, w, h);
  60463. if (isDown)
  60464. {
  60465. g.setColour (noteFillColour);
  60466. g.drawRect (x, y, w, h);
  60467. }
  60468. else
  60469. {
  60470. const int xIndent = jmax (1, jmin (w, h) / 8);
  60471. g.setColour (c.brighter());
  60472. if (orientation == horizontalKeyboard)
  60473. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60474. else if (orientation == verticalKeyboardFacingLeft)
  60475. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60476. else if (orientation == verticalKeyboardFacingRight)
  60477. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60478. }
  60479. }
  60480. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60481. {
  60482. octaveNumForMiddleC = octaveNumForMiddleC_;
  60483. repaint();
  60484. }
  60485. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60486. {
  60487. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60488. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60489. return String::empty;
  60490. }
  60491. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60492. const bool isMouseOver_,
  60493. const bool isButtonDown,
  60494. const bool movesOctavesUp)
  60495. {
  60496. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60497. float angle;
  60498. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60499. angle = movesOctavesUp ? 0.0f : 0.5f;
  60500. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60501. angle = movesOctavesUp ? 0.25f : 0.75f;
  60502. else
  60503. angle = movesOctavesUp ? 0.75f : 0.25f;
  60504. Path path;
  60505. path.lineTo (0.0f, 1.0f);
  60506. path.lineTo (1.0f, 0.5f);
  60507. path.closeSubPath();
  60508. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60509. g.setColour (findColour (upDownButtonArrowColourId)
  60510. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60511. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60512. w - 2.0f,
  60513. h - 2.0f,
  60514. true));
  60515. }
  60516. void MidiKeyboardComponent::resized()
  60517. {
  60518. int w = getWidth();
  60519. int h = getHeight();
  60520. if (w > 0 && h > 0)
  60521. {
  60522. if (orientation != horizontalKeyboard)
  60523. swapVariables (w, h);
  60524. blackNoteLength = roundToInt (h * 0.7f);
  60525. int kx2, kw2;
  60526. getKeyPos (rangeEnd, kx2, kw2);
  60527. kx2 += kw2;
  60528. if (firstKey != rangeStart)
  60529. {
  60530. int kx1, kw1;
  60531. getKeyPos (rangeStart, kx1, kw1);
  60532. if (kx2 - kx1 <= w)
  60533. {
  60534. firstKey = rangeStart;
  60535. sendChangeMessage (this);
  60536. repaint();
  60537. }
  60538. }
  60539. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60540. scrollDown->setVisible (showScrollButtons);
  60541. scrollUp->setVisible (showScrollButtons);
  60542. xOffset = 0;
  60543. if (showScrollButtons)
  60544. {
  60545. const int scrollButtonW = jmin (12, w / 2);
  60546. if (orientation == horizontalKeyboard)
  60547. {
  60548. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60549. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60550. }
  60551. else if (orientation == verticalKeyboardFacingLeft)
  60552. {
  60553. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60554. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60555. }
  60556. else if (orientation == verticalKeyboardFacingRight)
  60557. {
  60558. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60559. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60560. }
  60561. int endOfLastKey, kw;
  60562. getKeyPos (rangeEnd, endOfLastKey, kw);
  60563. endOfLastKey += kw;
  60564. float mousePositionVelocity;
  60565. const int spaceAvailable = w - scrollButtonW * 2;
  60566. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60567. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60568. {
  60569. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60570. sendChangeMessage (this);
  60571. }
  60572. int newOffset = 0;
  60573. getKeyPos (firstKey, newOffset, kw);
  60574. xOffset = newOffset - scrollButtonW;
  60575. }
  60576. else
  60577. {
  60578. firstKey = rangeStart;
  60579. }
  60580. timerCallback();
  60581. repaint();
  60582. }
  60583. }
  60584. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  60585. {
  60586. triggerAsyncUpdate();
  60587. }
  60588. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  60589. {
  60590. triggerAsyncUpdate();
  60591. }
  60592. void MidiKeyboardComponent::handleAsyncUpdate()
  60593. {
  60594. for (int i = rangeStart; i <= rangeEnd; ++i)
  60595. {
  60596. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  60597. {
  60598. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  60599. repaintNote (i);
  60600. }
  60601. }
  60602. }
  60603. void MidiKeyboardComponent::resetAnyKeysInUse()
  60604. {
  60605. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  60606. {
  60607. state.allNotesOff (midiChannel);
  60608. keysPressed.clear();
  60609. mouseDownNote = -1;
  60610. }
  60611. }
  60612. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  60613. {
  60614. float mousePositionVelocity = 0.0f;
  60615. const int newNote = (mouseDragging || isMouseOver())
  60616. ? xyToNote (pos, mousePositionVelocity) : -1;
  60617. if (noteUnderMouse != newNote)
  60618. {
  60619. if (mouseDownNote >= 0)
  60620. {
  60621. state.noteOff (midiChannel, mouseDownNote);
  60622. mouseDownNote = -1;
  60623. }
  60624. if (mouseDragging && newNote >= 0)
  60625. {
  60626. if (! useMousePositionForVelocity)
  60627. mousePositionVelocity = 1.0f;
  60628. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  60629. mouseDownNote = newNote;
  60630. }
  60631. repaintNote (noteUnderMouse);
  60632. noteUnderMouse = newNote;
  60633. repaintNote (noteUnderMouse);
  60634. }
  60635. else if (mouseDownNote >= 0 && ! mouseDragging)
  60636. {
  60637. state.noteOff (midiChannel, mouseDownNote);
  60638. mouseDownNote = -1;
  60639. }
  60640. }
  60641. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  60642. {
  60643. updateNoteUnderMouse (e.getPosition());
  60644. stopTimer();
  60645. }
  60646. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  60647. {
  60648. float mousePositionVelocity;
  60649. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60650. if (newNote >= 0)
  60651. mouseDraggedToKey (newNote, e);
  60652. updateNoteUnderMouse (e.getPosition());
  60653. }
  60654. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  60655. {
  60656. return true;
  60657. }
  60658. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  60659. {
  60660. }
  60661. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  60662. {
  60663. float mousePositionVelocity;
  60664. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60665. mouseDragging = false;
  60666. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  60667. {
  60668. repaintNote (noteUnderMouse);
  60669. noteUnderMouse = -1;
  60670. mouseDragging = true;
  60671. updateNoteUnderMouse (e.getPosition());
  60672. startTimer (500);
  60673. }
  60674. }
  60675. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  60676. {
  60677. mouseDragging = false;
  60678. updateNoteUnderMouse (e.getPosition());
  60679. stopTimer();
  60680. }
  60681. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  60682. {
  60683. updateNoteUnderMouse (e.getPosition());
  60684. }
  60685. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  60686. {
  60687. updateNoteUnderMouse (e.getPosition());
  60688. }
  60689. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  60690. {
  60691. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  60692. }
  60693. void MidiKeyboardComponent::timerCallback()
  60694. {
  60695. updateNoteUnderMouse (getMouseXYRelative());
  60696. }
  60697. void MidiKeyboardComponent::clearKeyMappings()
  60698. {
  60699. resetAnyKeysInUse();
  60700. keyPressNotes.clear();
  60701. keyPresses.clear();
  60702. }
  60703. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  60704. const int midiNoteOffsetFromC)
  60705. {
  60706. removeKeyPressForNote (midiNoteOffsetFromC);
  60707. keyPressNotes.add (midiNoteOffsetFromC);
  60708. keyPresses.add (key);
  60709. }
  60710. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  60711. {
  60712. for (int i = keyPressNotes.size(); --i >= 0;)
  60713. {
  60714. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  60715. {
  60716. keyPressNotes.remove (i);
  60717. keyPresses.remove (i);
  60718. }
  60719. }
  60720. }
  60721. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  60722. {
  60723. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  60724. keyMappingOctave = newOctaveNumber;
  60725. }
  60726. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  60727. {
  60728. bool keyPressUsed = false;
  60729. for (int i = keyPresses.size(); --i >= 0;)
  60730. {
  60731. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  60732. if (keyPresses.getReference(i).isCurrentlyDown())
  60733. {
  60734. if (! keysPressed [note])
  60735. {
  60736. keysPressed.setBit (note);
  60737. state.noteOn (midiChannel, note, velocity);
  60738. keyPressUsed = true;
  60739. }
  60740. }
  60741. else
  60742. {
  60743. if (keysPressed [note])
  60744. {
  60745. keysPressed.clearBit (note);
  60746. state.noteOff (midiChannel, note);
  60747. keyPressUsed = true;
  60748. }
  60749. }
  60750. }
  60751. return keyPressUsed;
  60752. }
  60753. void MidiKeyboardComponent::focusLost (FocusChangeType)
  60754. {
  60755. resetAnyKeysInUse();
  60756. }
  60757. END_JUCE_NAMESPACE
  60758. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60759. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  60760. #if JUCE_OPENGL
  60761. BEGIN_JUCE_NAMESPACE
  60762. extern void juce_glViewport (const int w, const int h);
  60763. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  60764. const int alphaBits_,
  60765. const int depthBufferBits_,
  60766. const int stencilBufferBits_)
  60767. : redBits (bitsPerRGBComponent),
  60768. greenBits (bitsPerRGBComponent),
  60769. blueBits (bitsPerRGBComponent),
  60770. alphaBits (alphaBits_),
  60771. depthBufferBits (depthBufferBits_),
  60772. stencilBufferBits (stencilBufferBits_),
  60773. accumulationBufferRedBits (0),
  60774. accumulationBufferGreenBits (0),
  60775. accumulationBufferBlueBits (0),
  60776. accumulationBufferAlphaBits (0),
  60777. fullSceneAntiAliasingNumSamples (0)
  60778. {
  60779. }
  60780. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  60781. : redBits (other.redBits),
  60782. greenBits (other.greenBits),
  60783. blueBits (other.blueBits),
  60784. alphaBits (other.alphaBits),
  60785. depthBufferBits (other.depthBufferBits),
  60786. stencilBufferBits (other.stencilBufferBits),
  60787. accumulationBufferRedBits (other.accumulationBufferRedBits),
  60788. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  60789. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  60790. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  60791. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  60792. {
  60793. }
  60794. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  60795. {
  60796. redBits = other.redBits;
  60797. greenBits = other.greenBits;
  60798. blueBits = other.blueBits;
  60799. alphaBits = other.alphaBits;
  60800. depthBufferBits = other.depthBufferBits;
  60801. stencilBufferBits = other.stencilBufferBits;
  60802. accumulationBufferRedBits = other.accumulationBufferRedBits;
  60803. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  60804. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  60805. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  60806. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  60807. return *this;
  60808. }
  60809. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  60810. {
  60811. return redBits == other.redBits
  60812. && greenBits == other.greenBits
  60813. && blueBits == other.blueBits
  60814. && alphaBits == other.alphaBits
  60815. && depthBufferBits == other.depthBufferBits
  60816. && stencilBufferBits == other.stencilBufferBits
  60817. && accumulationBufferRedBits == other.accumulationBufferRedBits
  60818. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  60819. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  60820. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  60821. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  60822. }
  60823. static Array<OpenGLContext*> knownContexts;
  60824. OpenGLContext::OpenGLContext() throw()
  60825. {
  60826. knownContexts.add (this);
  60827. }
  60828. OpenGLContext::~OpenGLContext()
  60829. {
  60830. knownContexts.removeValue (this);
  60831. }
  60832. OpenGLContext* OpenGLContext::getCurrentContext()
  60833. {
  60834. for (int i = knownContexts.size(); --i >= 0;)
  60835. {
  60836. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  60837. if (oglc->isActive())
  60838. return oglc;
  60839. }
  60840. return 0;
  60841. }
  60842. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  60843. {
  60844. public:
  60845. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  60846. : ComponentMovementWatcher (owner_),
  60847. owner (owner_),
  60848. wasShowing (false)
  60849. {
  60850. }
  60851. ~OpenGLComponentWatcher() {}
  60852. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  60853. {
  60854. owner->updateContextPosition();
  60855. }
  60856. void componentPeerChanged()
  60857. {
  60858. const ScopedLock sl (owner->getContextLock());
  60859. owner->deleteContext();
  60860. }
  60861. void componentVisibilityChanged (Component&)
  60862. {
  60863. const bool isShowingNow = owner->isShowing();
  60864. if (wasShowing != isShowingNow)
  60865. {
  60866. wasShowing = isShowingNow;
  60867. if (! isShowingNow)
  60868. {
  60869. const ScopedLock sl (owner->getContextLock());
  60870. owner->deleteContext();
  60871. }
  60872. }
  60873. }
  60874. juce_UseDebuggingNewOperator
  60875. private:
  60876. OpenGLComponent* const owner;
  60877. bool wasShowing;
  60878. };
  60879. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  60880. : type (type_),
  60881. contextToShareListsWith (0),
  60882. needToUpdateViewport (true)
  60883. {
  60884. setOpaque (true);
  60885. componentWatcher = new OpenGLComponentWatcher (this);
  60886. }
  60887. OpenGLComponent::~OpenGLComponent()
  60888. {
  60889. deleteContext();
  60890. componentWatcher = 0;
  60891. }
  60892. void OpenGLComponent::deleteContext()
  60893. {
  60894. const ScopedLock sl (contextLock);
  60895. context = 0;
  60896. }
  60897. void OpenGLComponent::updateContextPosition()
  60898. {
  60899. needToUpdateViewport = true;
  60900. if (getWidth() > 0 && getHeight() > 0)
  60901. {
  60902. Component* const topComp = getTopLevelComponent();
  60903. if (topComp->getPeer() != 0)
  60904. {
  60905. const ScopedLock sl (contextLock);
  60906. if (context != 0)
  60907. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  60908. getScreenY() - topComp->getScreenY(),
  60909. getWidth(),
  60910. getHeight(),
  60911. topComp->getHeight());
  60912. }
  60913. }
  60914. }
  60915. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  60916. {
  60917. OpenGLPixelFormat pf;
  60918. const ScopedLock sl (contextLock);
  60919. if (context != 0)
  60920. pf = context->getPixelFormat();
  60921. return pf;
  60922. }
  60923. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  60924. {
  60925. if (! (preferredPixelFormat == formatToUse))
  60926. {
  60927. const ScopedLock sl (contextLock);
  60928. deleteContext();
  60929. preferredPixelFormat = formatToUse;
  60930. }
  60931. }
  60932. void OpenGLComponent::shareWith (OpenGLContext* c)
  60933. {
  60934. if (contextToShareListsWith != c)
  60935. {
  60936. const ScopedLock sl (contextLock);
  60937. deleteContext();
  60938. contextToShareListsWith = c;
  60939. }
  60940. }
  60941. bool OpenGLComponent::makeCurrentContextActive()
  60942. {
  60943. if (context == 0)
  60944. {
  60945. const ScopedLock sl (contextLock);
  60946. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  60947. {
  60948. context = createContext();
  60949. if (context != 0)
  60950. {
  60951. updateContextPosition();
  60952. if (context->makeActive())
  60953. newOpenGLContextCreated();
  60954. }
  60955. }
  60956. }
  60957. return context != 0 && context->makeActive();
  60958. }
  60959. void OpenGLComponent::makeCurrentContextInactive()
  60960. {
  60961. if (context != 0)
  60962. context->makeInactive();
  60963. }
  60964. bool OpenGLComponent::isActiveContext() const throw()
  60965. {
  60966. return context != 0 && context->isActive();
  60967. }
  60968. void OpenGLComponent::swapBuffers()
  60969. {
  60970. if (context != 0)
  60971. context->swapBuffers();
  60972. }
  60973. void OpenGLComponent::paint (Graphics&)
  60974. {
  60975. if (renderAndSwapBuffers())
  60976. {
  60977. ComponentPeer* const peer = getPeer();
  60978. if (peer != 0)
  60979. {
  60980. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  60981. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  60982. }
  60983. }
  60984. }
  60985. bool OpenGLComponent::renderAndSwapBuffers()
  60986. {
  60987. const ScopedLock sl (contextLock);
  60988. if (! makeCurrentContextActive())
  60989. return false;
  60990. if (needToUpdateViewport)
  60991. {
  60992. needToUpdateViewport = false;
  60993. juce_glViewport (getWidth(), getHeight());
  60994. }
  60995. renderOpenGL();
  60996. swapBuffers();
  60997. return true;
  60998. }
  60999. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61000. {
  61001. Component::internalRepaint (x, y, w, h);
  61002. if (context != 0)
  61003. context->repaint();
  61004. }
  61005. END_JUCE_NAMESPACE
  61006. #endif
  61007. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61008. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61009. BEGIN_JUCE_NAMESPACE
  61010. PreferencesPanel::PreferencesPanel()
  61011. : buttonSize (70)
  61012. {
  61013. }
  61014. PreferencesPanel::~PreferencesPanel()
  61015. {
  61016. currentPage = 0;
  61017. deleteAllChildren();
  61018. }
  61019. void PreferencesPanel::addSettingsPage (const String& title,
  61020. const Drawable* icon,
  61021. const Drawable* overIcon,
  61022. const Drawable* downIcon)
  61023. {
  61024. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61025. button->setImages (icon, overIcon, downIcon);
  61026. button->setRadioGroupId (1);
  61027. button->addButtonListener (this);
  61028. button->setClickingTogglesState (true);
  61029. button->setWantsKeyboardFocus (false);
  61030. addAndMakeVisible (button);
  61031. resized();
  61032. if (currentPage == 0)
  61033. setCurrentPage (title);
  61034. }
  61035. void PreferencesPanel::addSettingsPage (const String& title,
  61036. const void* imageData,
  61037. const int imageDataSize)
  61038. {
  61039. DrawableImage icon, iconOver, iconDown;
  61040. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61041. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61042. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61043. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61044. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61045. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61046. }
  61047. class PrefsDialogWindow : public DialogWindow
  61048. {
  61049. public:
  61050. PrefsDialogWindow (const String& dialogtitle,
  61051. const Colour& backgroundColour)
  61052. : DialogWindow (dialogtitle, backgroundColour, true)
  61053. {
  61054. }
  61055. ~PrefsDialogWindow()
  61056. {
  61057. }
  61058. void closeButtonPressed()
  61059. {
  61060. exitModalState (0);
  61061. }
  61062. private:
  61063. PrefsDialogWindow (const PrefsDialogWindow&);
  61064. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  61065. };
  61066. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  61067. int dialogWidth,
  61068. int dialogHeight,
  61069. const Colour& backgroundColour)
  61070. {
  61071. setSize (dialogWidth, dialogHeight);
  61072. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  61073. dw.setContentComponent (this, true, true);
  61074. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  61075. dw.runModalLoop();
  61076. dw.setContentComponent (0, false, false);
  61077. }
  61078. void PreferencesPanel::resized()
  61079. {
  61080. int x = 0;
  61081. for (int i = 0; i < getNumChildComponents(); ++i)
  61082. {
  61083. Component* c = getChildComponent (i);
  61084. if (dynamic_cast <DrawableButton*> (c) == 0)
  61085. {
  61086. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  61087. }
  61088. else
  61089. {
  61090. c->setBounds (x, 0, buttonSize, buttonSize);
  61091. x += buttonSize;
  61092. }
  61093. }
  61094. }
  61095. void PreferencesPanel::paint (Graphics& g)
  61096. {
  61097. g.setColour (Colours::grey);
  61098. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61099. }
  61100. void PreferencesPanel::setCurrentPage (const String& pageName)
  61101. {
  61102. if (currentPageName != pageName)
  61103. {
  61104. currentPageName = pageName;
  61105. currentPage = 0;
  61106. currentPage = createComponentForPage (pageName);
  61107. if (currentPage != 0)
  61108. {
  61109. addAndMakeVisible (currentPage);
  61110. currentPage->toBack();
  61111. resized();
  61112. }
  61113. for (int i = 0; i < getNumChildComponents(); ++i)
  61114. {
  61115. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61116. if (db != 0 && db->getName() == pageName)
  61117. {
  61118. db->setToggleState (true, false);
  61119. break;
  61120. }
  61121. }
  61122. }
  61123. }
  61124. void PreferencesPanel::buttonClicked (Button*)
  61125. {
  61126. for (int i = 0; i < getNumChildComponents(); ++i)
  61127. {
  61128. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61129. if (db != 0 && db->getToggleState())
  61130. {
  61131. setCurrentPage (db->getName());
  61132. break;
  61133. }
  61134. }
  61135. }
  61136. END_JUCE_NAMESPACE
  61137. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61138. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61139. #if JUCE_WINDOWS || JUCE_LINUX
  61140. BEGIN_JUCE_NAMESPACE
  61141. SystemTrayIconComponent::SystemTrayIconComponent()
  61142. {
  61143. addToDesktop (0);
  61144. }
  61145. SystemTrayIconComponent::~SystemTrayIconComponent()
  61146. {
  61147. }
  61148. END_JUCE_NAMESPACE
  61149. #endif
  61150. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61151. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61152. BEGIN_JUCE_NAMESPACE
  61153. class AlertWindowTextEditor : public TextEditor
  61154. {
  61155. public:
  61156. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61157. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61158. {
  61159. setSelectAllWhenFocused (true);
  61160. }
  61161. ~AlertWindowTextEditor()
  61162. {
  61163. }
  61164. void returnPressed()
  61165. {
  61166. // pass these up the component hierarchy to be trigger the buttons
  61167. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61168. }
  61169. void escapePressed()
  61170. {
  61171. // pass these up the component hierarchy to be trigger the buttons
  61172. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61173. }
  61174. private:
  61175. AlertWindowTextEditor (const AlertWindowTextEditor&);
  61176. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  61177. static juce_wchar getDefaultPasswordChar() throw()
  61178. {
  61179. #if JUCE_LINUX
  61180. return 0x2022;
  61181. #else
  61182. return 0x25cf;
  61183. #endif
  61184. }
  61185. };
  61186. AlertWindow::AlertWindow (const String& title,
  61187. const String& message,
  61188. AlertIconType iconType,
  61189. Component* associatedComponent_)
  61190. : TopLevelWindow (title, true),
  61191. alertIconType (iconType),
  61192. associatedComponent (associatedComponent_)
  61193. {
  61194. if (message.isEmpty())
  61195. text = " "; // to force an update if the message is empty
  61196. setMessage (message);
  61197. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61198. {
  61199. Component* const c = Desktop::getInstance().getComponent (i);
  61200. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61201. {
  61202. setAlwaysOnTop (true);
  61203. break;
  61204. }
  61205. }
  61206. if (! JUCEApplication::isStandaloneApp)
  61207. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61208. lookAndFeelChanged();
  61209. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61210. }
  61211. AlertWindow::~AlertWindow()
  61212. {
  61213. for (int i = customComps.size(); --i >= 0;)
  61214. removeChildComponent ((Component*) customComps[i]);
  61215. deleteAllChildren();
  61216. }
  61217. void AlertWindow::userTriedToCloseWindow()
  61218. {
  61219. exitModalState (0);
  61220. }
  61221. void AlertWindow::setMessage (const String& message)
  61222. {
  61223. const String newMessage (message.substring (0, 2048));
  61224. if (text != newMessage)
  61225. {
  61226. text = newMessage;
  61227. font.setHeight (15.0f);
  61228. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61229. textLayout.setText (getName() + "\n\n", titleFont);
  61230. textLayout.appendText (text, font);
  61231. updateLayout (true);
  61232. repaint();
  61233. }
  61234. }
  61235. void AlertWindow::buttonClicked (Button* button)
  61236. {
  61237. for (int i = 0; i < buttons.size(); i++)
  61238. {
  61239. TextButton* const c = (TextButton*) buttons[i];
  61240. if (button->getName() == c->getName())
  61241. {
  61242. if (c->getParentComponent() != 0)
  61243. c->getParentComponent()->exitModalState (c->getCommandID());
  61244. break;
  61245. }
  61246. }
  61247. }
  61248. void AlertWindow::addButton (const String& name,
  61249. const int returnValue,
  61250. const KeyPress& shortcutKey1,
  61251. const KeyPress& shortcutKey2)
  61252. {
  61253. TextButton* const b = new TextButton (name, String::empty);
  61254. b->setWantsKeyboardFocus (true);
  61255. b->setMouseClickGrabsKeyboardFocus (false);
  61256. b->setCommandToTrigger (0, returnValue, false);
  61257. b->addShortcut (shortcutKey1);
  61258. b->addShortcut (shortcutKey2);
  61259. b->addButtonListener (this);
  61260. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61261. addAndMakeVisible (b, 0);
  61262. buttons.add (b);
  61263. updateLayout (false);
  61264. }
  61265. int AlertWindow::getNumButtons() const
  61266. {
  61267. return buttons.size();
  61268. }
  61269. void AlertWindow::triggerButtonClick (const String& buttonName)
  61270. {
  61271. for (int i = buttons.size(); --i >= 0;)
  61272. {
  61273. TextButton* const b = (TextButton*) buttons[i];
  61274. if (buttonName == b->getName())
  61275. {
  61276. b->triggerClick();
  61277. break;
  61278. }
  61279. }
  61280. }
  61281. void AlertWindow::addTextEditor (const String& name,
  61282. const String& initialContents,
  61283. const String& onScreenLabel,
  61284. const bool isPasswordBox)
  61285. {
  61286. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61287. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61288. tc->setFont (font);
  61289. tc->setText (initialContents);
  61290. tc->setCaretPosition (initialContents.length());
  61291. addAndMakeVisible (tc);
  61292. textBoxes.add (tc);
  61293. allComps.add (tc);
  61294. textboxNames.add (onScreenLabel);
  61295. updateLayout (false);
  61296. }
  61297. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61298. {
  61299. for (int i = textBoxes.size(); --i >= 0;)
  61300. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  61301. return ((TextEditor*)textBoxes[i])->getText();
  61302. return String::empty;
  61303. }
  61304. void AlertWindow::addComboBox (const String& name,
  61305. const StringArray& items,
  61306. const String& onScreenLabel)
  61307. {
  61308. ComboBox* const cb = new ComboBox (name);
  61309. for (int i = 0; i < items.size(); ++i)
  61310. cb->addItem (items[i], i + 1);
  61311. addAndMakeVisible (cb);
  61312. cb->setSelectedItemIndex (0);
  61313. comboBoxes.add (cb);
  61314. allComps.add (cb);
  61315. comboBoxNames.add (onScreenLabel);
  61316. updateLayout (false);
  61317. }
  61318. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61319. {
  61320. for (int i = comboBoxes.size(); --i >= 0;)
  61321. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  61322. return (ComboBox*) comboBoxes[i];
  61323. return 0;
  61324. }
  61325. class AlertTextComp : public TextEditor
  61326. {
  61327. public:
  61328. AlertTextComp (const String& message,
  61329. const Font& font)
  61330. {
  61331. setReadOnly (true);
  61332. setMultiLine (true, true);
  61333. setCaretVisible (false);
  61334. setScrollbarsShown (true);
  61335. lookAndFeelChanged();
  61336. setWantsKeyboardFocus (false);
  61337. setFont (font);
  61338. setText (message, false);
  61339. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61340. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61341. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61342. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61343. }
  61344. ~AlertTextComp()
  61345. {
  61346. }
  61347. int getPreferredWidth() const throw() { return bestWidth; }
  61348. void updateLayout (const int width)
  61349. {
  61350. TextLayout text;
  61351. text.appendText (getText(), getFont());
  61352. text.layout (width - 8, Justification::topLeft, true);
  61353. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61354. }
  61355. private:
  61356. int bestWidth;
  61357. AlertTextComp (const AlertTextComp&);
  61358. AlertTextComp& operator= (const AlertTextComp&);
  61359. };
  61360. void AlertWindow::addTextBlock (const String& textBlock)
  61361. {
  61362. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61363. textBlocks.add (c);
  61364. allComps.add (c);
  61365. addAndMakeVisible (c);
  61366. updateLayout (false);
  61367. }
  61368. void AlertWindow::addProgressBarComponent (double& progressValue)
  61369. {
  61370. ProgressBar* const pb = new ProgressBar (progressValue);
  61371. progressBars.add (pb);
  61372. allComps.add (pb);
  61373. addAndMakeVisible (pb);
  61374. updateLayout (false);
  61375. }
  61376. void AlertWindow::addCustomComponent (Component* const component)
  61377. {
  61378. customComps.add (component);
  61379. allComps.add (component);
  61380. addAndMakeVisible (component);
  61381. updateLayout (false);
  61382. }
  61383. int AlertWindow::getNumCustomComponents() const
  61384. {
  61385. return customComps.size();
  61386. }
  61387. Component* AlertWindow::getCustomComponent (const int index) const
  61388. {
  61389. return (Component*) customComps [index];
  61390. }
  61391. Component* AlertWindow::removeCustomComponent (const int index)
  61392. {
  61393. Component* const c = getCustomComponent (index);
  61394. if (c != 0)
  61395. {
  61396. customComps.removeValue (c);
  61397. allComps.removeValue (c);
  61398. removeChildComponent (c);
  61399. updateLayout (false);
  61400. }
  61401. return c;
  61402. }
  61403. void AlertWindow::paint (Graphics& g)
  61404. {
  61405. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61406. g.setColour (findColour (textColourId));
  61407. g.setFont (getLookAndFeel().getAlertWindowFont());
  61408. int i;
  61409. for (i = textBoxes.size(); --i >= 0;)
  61410. {
  61411. const TextEditor* const te = (TextEditor*) textBoxes[i];
  61412. g.drawFittedText (textboxNames[i],
  61413. te->getX(), te->getY() - 14,
  61414. te->getWidth(), 14,
  61415. Justification::centredLeft, 1);
  61416. }
  61417. for (i = comboBoxNames.size(); --i >= 0;)
  61418. {
  61419. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  61420. g.drawFittedText (comboBoxNames[i],
  61421. cb->getX(), cb->getY() - 14,
  61422. cb->getWidth(), 14,
  61423. Justification::centredLeft, 1);
  61424. }
  61425. for (i = customComps.size(); --i >= 0;)
  61426. {
  61427. const Component* const c = (Component*) customComps[i];
  61428. g.drawFittedText (c->getName(),
  61429. c->getX(), c->getY() - 14,
  61430. c->getWidth(), 14,
  61431. Justification::centredLeft, 1);
  61432. }
  61433. }
  61434. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61435. {
  61436. const int titleH = 24;
  61437. const int iconWidth = 80;
  61438. const int wid = jmax (font.getStringWidth (text),
  61439. font.getStringWidth (getName()));
  61440. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61441. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61442. const int edgeGap = 10;
  61443. const int labelHeight = 18;
  61444. int iconSpace;
  61445. if (alertIconType == NoIcon)
  61446. {
  61447. textLayout.layout (w, Justification::horizontallyCentred, true);
  61448. iconSpace = 0;
  61449. }
  61450. else
  61451. {
  61452. textLayout.layout (w, Justification::left, true);
  61453. iconSpace = iconWidth;
  61454. }
  61455. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61456. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61457. const int textLayoutH = textLayout.getHeight();
  61458. const int textBottom = 16 + titleH + textLayoutH;
  61459. int h = textBottom;
  61460. int buttonW = 40;
  61461. int i;
  61462. for (i = 0; i < buttons.size(); ++i)
  61463. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  61464. w = jmax (buttonW, w);
  61465. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61466. if (buttons.size() > 0)
  61467. h += 20 + ((TextButton*) buttons[0])->getHeight();
  61468. for (i = customComps.size(); --i >= 0;)
  61469. {
  61470. Component* c = (Component*) customComps[i];
  61471. w = jmax (w, (c->getWidth() * 100) / 80);
  61472. h += 10 + c->getHeight();
  61473. if (c->getName().isNotEmpty())
  61474. h += labelHeight;
  61475. }
  61476. for (i = textBlocks.size(); --i >= 0;)
  61477. {
  61478. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61479. w = jmax (w, ac->getPreferredWidth());
  61480. }
  61481. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61482. for (i = textBlocks.size(); --i >= 0;)
  61483. {
  61484. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61485. ac->updateLayout ((int) (w * 0.8f));
  61486. h += ac->getHeight() + 10;
  61487. }
  61488. h = jmin (getParentHeight() - 50, h);
  61489. if (onlyIncreaseSize)
  61490. {
  61491. w = jmax (w, getWidth());
  61492. h = jmax (h, getHeight());
  61493. }
  61494. if (! isVisible())
  61495. {
  61496. centreAroundComponent (associatedComponent, w, h);
  61497. }
  61498. else
  61499. {
  61500. const int cx = getX() + getWidth() / 2;
  61501. const int cy = getY() + getHeight() / 2;
  61502. setBounds (cx - w / 2,
  61503. cy - h / 2,
  61504. w, h);
  61505. }
  61506. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61507. const int spacer = 16;
  61508. int totalWidth = -spacer;
  61509. for (i = buttons.size(); --i >= 0;)
  61510. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  61511. int x = (w - totalWidth) / 2;
  61512. int y = (int) (getHeight() * 0.95f);
  61513. for (i = 0; i < buttons.size(); ++i)
  61514. {
  61515. TextButton* const c = (TextButton*) buttons[i];
  61516. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61517. c->setTopLeftPosition (x, ny);
  61518. if (ny < y)
  61519. y = ny;
  61520. x += c->getWidth() + spacer;
  61521. c->toFront (false);
  61522. }
  61523. y = textBottom;
  61524. for (i = 0; i < allComps.size(); ++i)
  61525. {
  61526. Component* const c = (Component*) allComps[i];
  61527. h = 22;
  61528. const int comboIndex = comboBoxes.indexOf (c);
  61529. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61530. y += labelHeight;
  61531. const int tbIndex = textBoxes.indexOf (c);
  61532. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61533. y += labelHeight;
  61534. if (customComps.contains (c))
  61535. {
  61536. if (c->getName().isNotEmpty())
  61537. y += labelHeight;
  61538. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61539. h = c->getHeight();
  61540. }
  61541. else if (textBlocks.contains (c))
  61542. {
  61543. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61544. h = c->getHeight();
  61545. }
  61546. else
  61547. {
  61548. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61549. }
  61550. y += h + 10;
  61551. }
  61552. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61553. }
  61554. bool AlertWindow::containsAnyExtraComponents() const
  61555. {
  61556. return textBoxes.size()
  61557. + comboBoxes.size()
  61558. + progressBars.size()
  61559. + customComps.size() > 0;
  61560. }
  61561. void AlertWindow::mouseDown (const MouseEvent&)
  61562. {
  61563. dragger.startDraggingComponent (this, &constrainer);
  61564. }
  61565. void AlertWindow::mouseDrag (const MouseEvent& e)
  61566. {
  61567. dragger.dragComponent (this, e);
  61568. }
  61569. bool AlertWindow::keyPressed (const KeyPress& key)
  61570. {
  61571. for (int i = buttons.size(); --i >= 0;)
  61572. {
  61573. TextButton* const b = (TextButton*) buttons[i];
  61574. if (b->isRegisteredForShortcut (key))
  61575. {
  61576. b->triggerClick();
  61577. return true;
  61578. }
  61579. }
  61580. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61581. {
  61582. exitModalState (0);
  61583. return true;
  61584. }
  61585. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61586. {
  61587. ((TextButton*) buttons.getFirst())->triggerClick();
  61588. return true;
  61589. }
  61590. return false;
  61591. }
  61592. void AlertWindow::lookAndFeelChanged()
  61593. {
  61594. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61595. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61596. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61597. }
  61598. int AlertWindow::getDesktopWindowStyleFlags() const
  61599. {
  61600. return getLookAndFeel().getAlertBoxWindowFlags();
  61601. }
  61602. struct AlertWindowInfo
  61603. {
  61604. String title, message, button1, button2, button3;
  61605. AlertWindow::AlertIconType iconType;
  61606. int numButtons;
  61607. Component::SafePointer<Component> associatedComponent;
  61608. int run() const
  61609. {
  61610. return (int) (pointer_sized_int)
  61611. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61612. }
  61613. private:
  61614. int show() const
  61615. {
  61616. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61617. : LookAndFeel::getDefaultLookAndFeel();
  61618. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61619. iconType, numButtons, associatedComponent));
  61620. jassert (alertBox != 0); // you have to return one of these!
  61621. return alertBox->runModalLoop();
  61622. }
  61623. static void* showCallback (void* userData)
  61624. {
  61625. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  61626. }
  61627. };
  61628. void AlertWindow::showMessageBox (AlertIconType iconType,
  61629. const String& title,
  61630. const String& message,
  61631. const String& buttonText,
  61632. Component* associatedComponent)
  61633. {
  61634. AlertWindowInfo info;
  61635. info.title = title;
  61636. info.message = message;
  61637. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  61638. info.iconType = iconType;
  61639. info.numButtons = 1;
  61640. info.associatedComponent = associatedComponent;
  61641. info.run();
  61642. }
  61643. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  61644. const String& title,
  61645. const String& message,
  61646. const String& button1Text,
  61647. const String& button2Text,
  61648. Component* associatedComponent)
  61649. {
  61650. AlertWindowInfo info;
  61651. info.title = title;
  61652. info.message = message;
  61653. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  61654. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  61655. info.iconType = iconType;
  61656. info.numButtons = 2;
  61657. info.associatedComponent = associatedComponent;
  61658. return info.run() != 0;
  61659. }
  61660. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  61661. const String& title,
  61662. const String& message,
  61663. const String& button1Text,
  61664. const String& button2Text,
  61665. const String& button3Text,
  61666. Component* associatedComponent)
  61667. {
  61668. AlertWindowInfo info;
  61669. info.title = title;
  61670. info.message = message;
  61671. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  61672. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  61673. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  61674. info.iconType = iconType;
  61675. info.numButtons = 3;
  61676. info.associatedComponent = associatedComponent;
  61677. return info.run();
  61678. }
  61679. END_JUCE_NAMESPACE
  61680. /*** End of inlined file: juce_AlertWindow.cpp ***/
  61681. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  61682. BEGIN_JUCE_NAMESPACE
  61683. CallOutBox::CallOutBox (Component& contentComponent,
  61684. Component& componentToPointTo,
  61685. Component* const parentComponent)
  61686. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  61687. {
  61688. addAndMakeVisible (&content);
  61689. if (parentComponent != 0)
  61690. {
  61691. updatePosition (parentComponent->getLocalBounds(),
  61692. componentToPointTo.getLocalBounds()
  61693. + componentToPointTo.relativePositionToOtherComponent (parentComponent, Point<int>()));
  61694. parentComponent->addAndMakeVisible (this);
  61695. }
  61696. else
  61697. {
  61698. updatePosition (componentToPointTo.getScreenBounds(),
  61699. componentToPointTo.getParentMonitorArea());
  61700. addToDesktop (ComponentPeer::windowIsTemporary);
  61701. }
  61702. }
  61703. CallOutBox::~CallOutBox()
  61704. {
  61705. }
  61706. void CallOutBox::setArrowSize (const float newSize)
  61707. {
  61708. arrowSize = newSize;
  61709. borderSpace = jmax (20, (int) arrowSize);
  61710. refreshPath();
  61711. }
  61712. void CallOutBox::paint (Graphics& g)
  61713. {
  61714. if (background.isNull())
  61715. {
  61716. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  61717. Graphics g (background);
  61718. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  61719. }
  61720. g.setColour (Colours::black);
  61721. g.drawImageAt (background, 0, 0);
  61722. }
  61723. void CallOutBox::resized()
  61724. {
  61725. content.setTopLeftPosition (borderSpace, borderSpace);
  61726. refreshPath();
  61727. }
  61728. void CallOutBox::moved()
  61729. {
  61730. refreshPath();
  61731. }
  61732. void CallOutBox::childBoundsChanged (Component*)
  61733. {
  61734. updatePosition (targetArea, availableArea);
  61735. }
  61736. bool CallOutBox::hitTest (int x, int y)
  61737. {
  61738. return outline.contains ((float) x, (float) y);
  61739. }
  61740. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  61741. void CallOutBox::inputAttemptWhenModal()
  61742. {
  61743. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  61744. if (targetArea.contains (mousePos))
  61745. {
  61746. // if you click on the area that originally popped-up the callout, you expect it
  61747. // to get rid of the box, but deleting the box here allows the click to pass through and
  61748. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  61749. postCommandMessage (callOutBoxDismissCommandId);
  61750. }
  61751. else
  61752. {
  61753. exitModalState (0);
  61754. setVisible (false);
  61755. }
  61756. }
  61757. void CallOutBox::handleCommandMessage (int commandId)
  61758. {
  61759. Component::handleCommandMessage (commandId);
  61760. if (commandId == callOutBoxDismissCommandId)
  61761. {
  61762. exitModalState (0);
  61763. setVisible (false);
  61764. }
  61765. }
  61766. bool CallOutBox::keyPressed (const KeyPress& key)
  61767. {
  61768. if (key.isKeyCode (KeyPress::escapeKey))
  61769. {
  61770. inputAttemptWhenModal();
  61771. return true;
  61772. }
  61773. return false;
  61774. }
  61775. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  61776. {
  61777. targetArea = newAreaToPointTo;
  61778. availableArea = newAreaToFitIn;
  61779. Rectangle<int> bounds (0, 0,
  61780. content.getWidth() + borderSpace * 2,
  61781. content.getHeight() + borderSpace * 2);
  61782. const int hw = bounds.getWidth() / 2;
  61783. const int hh = bounds.getHeight() / 2;
  61784. const float hwReduced = (float) (hw - borderSpace * 3);
  61785. const float hhReduced = (float) (hh - borderSpace * 3);
  61786. const float arrowIndent = borderSpace - arrowSize;
  61787. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  61788. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  61789. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  61790. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  61791. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  61792. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  61793. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  61794. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  61795. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  61796. float nearest = 1.0e9f;
  61797. for (int i = 0; i < 4; ++i)
  61798. {
  61799. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  61800. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  61801. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  61802. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  61803. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  61804. distanceFromCentre *= 2.0f;
  61805. if (distanceFromCentre < nearest)
  61806. {
  61807. nearest = distanceFromCentre;
  61808. targetPoint = targets[i];
  61809. bounds.setPosition ((int) (centre.getX() - hw),
  61810. (int) (centre.getY() - hh));
  61811. }
  61812. }
  61813. setBounds (bounds);
  61814. }
  61815. void CallOutBox::refreshPath()
  61816. {
  61817. repaint();
  61818. background = Image::null;
  61819. outline.clear();
  61820. const float gap = 4.5f;
  61821. const float cornerSize = 9.0f;
  61822. const float cornerSize2 = 2.0f * cornerSize;
  61823. const float arrowBaseWidth = arrowSize * 0.7f;
  61824. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  61825. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  61826. outline.startNewSubPath (left + cornerSize, top);
  61827. if (targetY <= top)
  61828. {
  61829. outline.lineTo (targetX - arrowBaseWidth, top);
  61830. outline.lineTo (targetX, targetY);
  61831. outline.lineTo (targetX + arrowBaseWidth, top);
  61832. }
  61833. outline.lineTo (right - cornerSize, top);
  61834. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  61835. if (targetX >= right)
  61836. {
  61837. outline.lineTo (right, targetY - arrowBaseWidth);
  61838. outline.lineTo (targetX, targetY);
  61839. outline.lineTo (right, targetY + arrowBaseWidth);
  61840. }
  61841. outline.lineTo (right, bottom - cornerSize);
  61842. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  61843. if (targetY >= bottom)
  61844. {
  61845. outline.lineTo (targetX + arrowBaseWidth, bottom);
  61846. outline.lineTo (targetX, targetY);
  61847. outline.lineTo (targetX - arrowBaseWidth, bottom);
  61848. }
  61849. outline.lineTo (left + cornerSize, bottom);
  61850. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  61851. if (targetX <= left)
  61852. {
  61853. outline.lineTo (left, targetY + arrowBaseWidth);
  61854. outline.lineTo (targetX, targetY);
  61855. outline.lineTo (left, targetY - arrowBaseWidth);
  61856. }
  61857. outline.lineTo (left, top + cornerSize);
  61858. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  61859. outline.closeSubPath();
  61860. }
  61861. END_JUCE_NAMESPACE
  61862. /*** End of inlined file: juce_CallOutBox.cpp ***/
  61863. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  61864. BEGIN_JUCE_NAMESPACE
  61865. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  61866. static Array <ComponentPeer*> heavyweightPeers;
  61867. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  61868. : component (component_),
  61869. styleFlags (styleFlags_),
  61870. lastPaintTime (0),
  61871. constrainer (0),
  61872. lastDragAndDropCompUnderMouse (0),
  61873. fakeMouseMessageSent (false),
  61874. isWindowMinimised (false)
  61875. {
  61876. heavyweightPeers.add (this);
  61877. }
  61878. ComponentPeer::~ComponentPeer()
  61879. {
  61880. heavyweightPeers.removeValue (this);
  61881. Desktop::getInstance().triggerFocusCallback();
  61882. }
  61883. int ComponentPeer::getNumPeers() throw()
  61884. {
  61885. return heavyweightPeers.size();
  61886. }
  61887. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  61888. {
  61889. return heavyweightPeers [index];
  61890. }
  61891. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  61892. {
  61893. for (int i = heavyweightPeers.size(); --i >= 0;)
  61894. {
  61895. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  61896. if (peer->getComponent() == component)
  61897. return peer;
  61898. }
  61899. return 0;
  61900. }
  61901. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  61902. {
  61903. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  61904. }
  61905. void ComponentPeer::updateCurrentModifiers() throw()
  61906. {
  61907. ModifierKeys::updateCurrentModifiers();
  61908. }
  61909. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  61910. {
  61911. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61912. jassert (mouse != 0); // not enough sources!
  61913. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  61914. }
  61915. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  61916. {
  61917. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61918. jassert (mouse != 0); // not enough sources!
  61919. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  61920. }
  61921. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  61922. {
  61923. Graphics g (&contextToPaintTo);
  61924. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61925. g.saveState();
  61926. #endif
  61927. JUCE_TRY
  61928. {
  61929. component->paintEntireComponent (g);
  61930. }
  61931. JUCE_CATCH_EXCEPTION
  61932. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61933. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  61934. // clearly when things are being repainted.
  61935. {
  61936. g.restoreState();
  61937. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  61938. (uint8) Random::getSystemRandom().nextInt (255),
  61939. (uint8) Random::getSystemRandom().nextInt (255),
  61940. (uint8) 0x50));
  61941. }
  61942. #endif
  61943. }
  61944. bool ComponentPeer::handleKeyPress (const int keyCode,
  61945. const juce_wchar textCharacter)
  61946. {
  61947. updateCurrentModifiers();
  61948. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61949. ? Component::getCurrentlyFocusedComponent()
  61950. : component;
  61951. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61952. {
  61953. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61954. if (currentModalComp != 0)
  61955. target = currentModalComp;
  61956. }
  61957. const KeyPress keyInfo (keyCode,
  61958. ModifierKeys::getCurrentModifiers().getRawFlags()
  61959. & ModifierKeys::allKeyboardModifiers,
  61960. textCharacter);
  61961. bool keyWasUsed = false;
  61962. while (target != 0)
  61963. {
  61964. const Component::SafePointer<Component> deletionChecker (target);
  61965. if (target->keyListeners_ != 0)
  61966. {
  61967. for (int i = target->keyListeners_->size(); --i >= 0;)
  61968. {
  61969. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  61970. if (keyWasUsed || deletionChecker == 0)
  61971. return keyWasUsed;
  61972. i = jmin (i, target->keyListeners_->size());
  61973. }
  61974. }
  61975. keyWasUsed = target->keyPressed (keyInfo);
  61976. if (keyWasUsed || deletionChecker == 0)
  61977. break;
  61978. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  61979. {
  61980. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  61981. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  61982. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  61983. break;
  61984. }
  61985. target = target->parentComponent_;
  61986. }
  61987. return keyWasUsed;
  61988. }
  61989. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  61990. {
  61991. updateCurrentModifiers();
  61992. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61993. ? Component::getCurrentlyFocusedComponent()
  61994. : component;
  61995. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61996. {
  61997. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61998. if (currentModalComp != 0)
  61999. target = currentModalComp;
  62000. }
  62001. bool keyWasUsed = false;
  62002. while (target != 0)
  62003. {
  62004. const Component::SafePointer<Component> deletionChecker (target);
  62005. keyWasUsed = target->keyStateChanged (isKeyDown);
  62006. if (keyWasUsed || deletionChecker == 0)
  62007. break;
  62008. if (target->keyListeners_ != 0)
  62009. {
  62010. for (int i = target->keyListeners_->size(); --i >= 0;)
  62011. {
  62012. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62013. if (keyWasUsed || deletionChecker == 0)
  62014. return keyWasUsed;
  62015. i = jmin (i, target->keyListeners_->size());
  62016. }
  62017. }
  62018. target = target->parentComponent_;
  62019. }
  62020. return keyWasUsed;
  62021. }
  62022. void ComponentPeer::handleModifierKeysChange()
  62023. {
  62024. updateCurrentModifiers();
  62025. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62026. if (target == 0)
  62027. target = Component::getCurrentlyFocusedComponent();
  62028. if (target == 0)
  62029. target = component;
  62030. if (target != 0)
  62031. target->internalModifierKeysChanged();
  62032. }
  62033. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62034. {
  62035. Component* const c = Component::getCurrentlyFocusedComponent();
  62036. if (component->isParentOf (c))
  62037. {
  62038. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62039. if (ti != 0 && ti->isTextInputActive())
  62040. return ti;
  62041. }
  62042. return 0;
  62043. }
  62044. void ComponentPeer::handleBroughtToFront()
  62045. {
  62046. updateCurrentModifiers();
  62047. if (component != 0)
  62048. component->internalBroughtToFront();
  62049. }
  62050. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62051. {
  62052. constrainer = newConstrainer;
  62053. }
  62054. void ComponentPeer::handleMovedOrResized()
  62055. {
  62056. jassert (component->isValidComponent());
  62057. updateCurrentModifiers();
  62058. const bool nowMinimised = isMinimised();
  62059. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62060. {
  62061. const Component::SafePointer<Component> deletionChecker (component);
  62062. const Rectangle<int> newBounds (getBounds());
  62063. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62064. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62065. if (wasMoved || wasResized)
  62066. {
  62067. component->bounds_ = newBounds;
  62068. if (wasResized)
  62069. component->repaint();
  62070. component->sendMovedResizedMessages (wasMoved, wasResized);
  62071. if (deletionChecker == 0)
  62072. return;
  62073. }
  62074. }
  62075. if (isWindowMinimised != nowMinimised)
  62076. {
  62077. isWindowMinimised = nowMinimised;
  62078. component->minimisationStateChanged (nowMinimised);
  62079. component->sendVisibilityChangeMessage();
  62080. }
  62081. if (! isFullScreen())
  62082. lastNonFullscreenBounds = component->getBounds();
  62083. }
  62084. void ComponentPeer::handleFocusGain()
  62085. {
  62086. updateCurrentModifiers();
  62087. if (component->isParentOf (lastFocusedComponent))
  62088. {
  62089. Component::currentlyFocusedComponent = lastFocusedComponent;
  62090. Desktop::getInstance().triggerFocusCallback();
  62091. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62092. }
  62093. else
  62094. {
  62095. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62096. component->grabKeyboardFocus();
  62097. else
  62098. Component::bringModalComponentToFront();
  62099. }
  62100. }
  62101. void ComponentPeer::handleFocusLoss()
  62102. {
  62103. updateCurrentModifiers();
  62104. if (component->hasKeyboardFocus (true))
  62105. {
  62106. lastFocusedComponent = Component::currentlyFocusedComponent;
  62107. if (lastFocusedComponent != 0)
  62108. {
  62109. Component::currentlyFocusedComponent = 0;
  62110. Desktop::getInstance().triggerFocusCallback();
  62111. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62112. }
  62113. }
  62114. }
  62115. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62116. {
  62117. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62118. ? static_cast <Component*> (lastFocusedComponent)
  62119. : component;
  62120. }
  62121. void ComponentPeer::handleScreenSizeChange()
  62122. {
  62123. updateCurrentModifiers();
  62124. component->parentSizeChanged();
  62125. handleMovedOrResized();
  62126. }
  62127. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62128. {
  62129. lastNonFullscreenBounds = newBounds;
  62130. }
  62131. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62132. {
  62133. return lastNonFullscreenBounds;
  62134. }
  62135. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62136. const StringArray& files,
  62137. FileDragAndDropTarget* const lastOne)
  62138. {
  62139. while (c != 0)
  62140. {
  62141. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62142. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62143. return t;
  62144. c = c->getParentComponent();
  62145. }
  62146. return 0;
  62147. }
  62148. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62149. {
  62150. updateCurrentModifiers();
  62151. FileDragAndDropTarget* lastTarget
  62152. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62153. FileDragAndDropTarget* newTarget = 0;
  62154. Component* const compUnderMouse = component->getComponentAt (position);
  62155. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62156. {
  62157. lastDragAndDropCompUnderMouse = compUnderMouse;
  62158. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62159. if (newTarget != lastTarget)
  62160. {
  62161. if (lastTarget != 0)
  62162. lastTarget->fileDragExit (files);
  62163. dragAndDropTargetComponent = 0;
  62164. if (newTarget != 0)
  62165. {
  62166. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62167. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  62168. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62169. }
  62170. }
  62171. }
  62172. else
  62173. {
  62174. newTarget = lastTarget;
  62175. }
  62176. if (newTarget != 0)
  62177. {
  62178. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62179. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  62180. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62181. }
  62182. }
  62183. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62184. {
  62185. handleFileDragMove (files, Point<int> (-1, -1));
  62186. jassert (dragAndDropTargetComponent == 0);
  62187. lastDragAndDropCompUnderMouse = 0;
  62188. }
  62189. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62190. {
  62191. handleFileDragMove (files, position);
  62192. if (dragAndDropTargetComponent != 0)
  62193. {
  62194. FileDragAndDropTarget* const target
  62195. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62196. dragAndDropTargetComponent = 0;
  62197. lastDragAndDropCompUnderMouse = 0;
  62198. if (target != 0)
  62199. {
  62200. Component* const targetComp = dynamic_cast <Component*> (target);
  62201. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62202. {
  62203. targetComp->internalModalInputAttempt();
  62204. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62205. return;
  62206. }
  62207. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  62208. target->filesDropped (files, pos.getX(), pos.getY());
  62209. }
  62210. }
  62211. }
  62212. void ComponentPeer::handleUserClosingWindow()
  62213. {
  62214. updateCurrentModifiers();
  62215. component->userTriedToCloseWindow();
  62216. }
  62217. void ComponentPeer::bringModalComponentToFront()
  62218. {
  62219. Component::bringModalComponentToFront();
  62220. }
  62221. void ComponentPeer::clearMaskedRegion()
  62222. {
  62223. maskedRegion.clear();
  62224. }
  62225. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62226. {
  62227. maskedRegion.add (x, y, w, h);
  62228. }
  62229. const StringArray ComponentPeer::getAvailableRenderingEngines() throw()
  62230. {
  62231. StringArray s;
  62232. s.add ("Software Renderer");
  62233. return s;
  62234. }
  62235. int ComponentPeer::getCurrentRenderingEngine() throw()
  62236. {
  62237. return 0;
  62238. }
  62239. void ComponentPeer::setCurrentRenderingEngine (int /*index*/) throw()
  62240. {
  62241. }
  62242. END_JUCE_NAMESPACE
  62243. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62244. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62245. BEGIN_JUCE_NAMESPACE
  62246. DialogWindow::DialogWindow (const String& name,
  62247. const Colour& backgroundColour_,
  62248. const bool escapeKeyTriggersCloseButton_,
  62249. const bool addToDesktop_)
  62250. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62251. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62252. {
  62253. }
  62254. DialogWindow::~DialogWindow()
  62255. {
  62256. }
  62257. void DialogWindow::resized()
  62258. {
  62259. DocumentWindow::resized();
  62260. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62261. if (escapeKeyTriggersCloseButton
  62262. && getCloseButton() != 0
  62263. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62264. {
  62265. getCloseButton()->addShortcut (esc);
  62266. }
  62267. }
  62268. class TempDialogWindow : public DialogWindow
  62269. {
  62270. public:
  62271. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  62272. : DialogWindow (title, colour, escapeCloses, true)
  62273. {
  62274. if (! JUCEApplication::isStandaloneApp)
  62275. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62276. }
  62277. ~TempDialogWindow()
  62278. {
  62279. }
  62280. void closeButtonPressed()
  62281. {
  62282. setVisible (false);
  62283. }
  62284. private:
  62285. TempDialogWindow (const TempDialogWindow&);
  62286. TempDialogWindow& operator= (const TempDialogWindow&);
  62287. };
  62288. int DialogWindow::showModalDialog (const String& dialogTitle,
  62289. Component* contentComponent,
  62290. Component* componentToCentreAround,
  62291. const Colour& colour,
  62292. const bool escapeKeyTriggersCloseButton,
  62293. const bool shouldBeResizable,
  62294. const bool useBottomRightCornerResizer)
  62295. {
  62296. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  62297. dw.setContentComponent (contentComponent, true, true);
  62298. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  62299. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62300. const int result = dw.runModalLoop();
  62301. dw.setContentComponent (0, false);
  62302. return result;
  62303. }
  62304. END_JUCE_NAMESPACE
  62305. /*** End of inlined file: juce_DialogWindow.cpp ***/
  62306. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  62307. BEGIN_JUCE_NAMESPACE
  62308. class DocumentWindow::ButtonListenerProxy : public Button::Listener
  62309. {
  62310. public:
  62311. ButtonListenerProxy (DocumentWindow& owner_)
  62312. : owner (owner_)
  62313. {
  62314. }
  62315. void buttonClicked (Button* button)
  62316. {
  62317. if (button == owner.getMinimiseButton())
  62318. owner.minimiseButtonPressed();
  62319. else if (button == owner.getMaximiseButton())
  62320. owner.maximiseButtonPressed();
  62321. else if (button == owner.getCloseButton())
  62322. owner.closeButtonPressed();
  62323. }
  62324. juce_UseDebuggingNewOperator
  62325. private:
  62326. DocumentWindow& owner;
  62327. ButtonListenerProxy (const ButtonListenerProxy&);
  62328. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  62329. };
  62330. DocumentWindow::DocumentWindow (const String& title,
  62331. const Colour& backgroundColour,
  62332. const int requiredButtons_,
  62333. const bool addToDesktop_)
  62334. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62335. titleBarHeight (26),
  62336. menuBarHeight (24),
  62337. requiredButtons (requiredButtons_),
  62338. #if JUCE_MAC
  62339. positionTitleBarButtonsOnLeft (true),
  62340. #else
  62341. positionTitleBarButtonsOnLeft (false),
  62342. #endif
  62343. drawTitleTextCentred (true),
  62344. menuBarModel (0)
  62345. {
  62346. setResizeLimits (128, 128, 32768, 32768);
  62347. lookAndFeelChanged();
  62348. }
  62349. DocumentWindow::~DocumentWindow()
  62350. {
  62351. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62352. titleBarButtons[i] = 0;
  62353. menuBar = 0;
  62354. }
  62355. void DocumentWindow::repaintTitleBar()
  62356. {
  62357. repaint (getTitleBarArea());
  62358. }
  62359. void DocumentWindow::setName (const String& newName)
  62360. {
  62361. if (newName != getName())
  62362. {
  62363. Component::setName (newName);
  62364. repaintTitleBar();
  62365. }
  62366. }
  62367. void DocumentWindow::setIcon (const Image& imageToUse)
  62368. {
  62369. titleBarIcon = imageToUse;
  62370. repaintTitleBar();
  62371. }
  62372. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62373. {
  62374. titleBarHeight = newHeight;
  62375. resized();
  62376. repaintTitleBar();
  62377. }
  62378. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62379. const bool positionTitleBarButtonsOnLeft_)
  62380. {
  62381. requiredButtons = requiredButtons_;
  62382. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62383. lookAndFeelChanged();
  62384. }
  62385. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62386. {
  62387. drawTitleTextCentred = textShouldBeCentred;
  62388. repaintTitleBar();
  62389. }
  62390. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  62391. const int menuBarHeight_)
  62392. {
  62393. if (menuBarModel != menuBarModel_)
  62394. {
  62395. menuBar = 0;
  62396. menuBarModel = menuBarModel_;
  62397. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  62398. : getLookAndFeel().getDefaultMenuBarHeight();
  62399. if (menuBarModel != 0)
  62400. {
  62401. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62402. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  62403. menuBar->setEnabled (isActiveWindow());
  62404. }
  62405. resized();
  62406. }
  62407. }
  62408. void DocumentWindow::closeButtonPressed()
  62409. {
  62410. /* If you've got a close button, you have to override this method to get
  62411. rid of your window!
  62412. If the window is just a pop-up, you should override this method and make
  62413. it delete the window in whatever way is appropriate for your app. E.g. you
  62414. might just want to call "delete this".
  62415. If your app is centred around this window such that the whole app should quit when
  62416. the window is closed, then you will probably want to use this method as an opportunity
  62417. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62418. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62419. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62420. or closing it via the taskbar icon on Windows).
  62421. */
  62422. jassertfalse;
  62423. }
  62424. void DocumentWindow::minimiseButtonPressed()
  62425. {
  62426. setMinimised (true);
  62427. }
  62428. void DocumentWindow::maximiseButtonPressed()
  62429. {
  62430. setFullScreen (! isFullScreen());
  62431. }
  62432. void DocumentWindow::paint (Graphics& g)
  62433. {
  62434. ResizableWindow::paint (g);
  62435. if (resizableBorder == 0)
  62436. {
  62437. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62438. const BorderSize border (getBorderThickness());
  62439. g.fillRect (0, 0, getWidth(), border.getTop());
  62440. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62441. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62442. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62443. }
  62444. const Rectangle<int> titleBarArea (getTitleBarArea());
  62445. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62446. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  62447. int titleSpaceX1 = 6;
  62448. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62449. for (int i = 0; i < 3; ++i)
  62450. {
  62451. if (titleBarButtons[i] != 0)
  62452. {
  62453. if (positionTitleBarButtonsOnLeft)
  62454. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62455. else
  62456. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62457. }
  62458. }
  62459. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62460. titleBarArea.getWidth(),
  62461. titleBarArea.getHeight(),
  62462. titleSpaceX1,
  62463. jmax (1, titleSpaceX2 - titleSpaceX1),
  62464. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62465. ! drawTitleTextCentred);
  62466. }
  62467. void DocumentWindow::resized()
  62468. {
  62469. ResizableWindow::resized();
  62470. if (titleBarButtons[1] != 0)
  62471. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62472. const Rectangle<int> titleBarArea (getTitleBarArea());
  62473. getLookAndFeel()
  62474. .positionDocumentWindowButtons (*this,
  62475. titleBarArea.getX(), titleBarArea.getY(),
  62476. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62477. titleBarButtons[0],
  62478. titleBarButtons[1],
  62479. titleBarButtons[2],
  62480. positionTitleBarButtonsOnLeft);
  62481. if (menuBar != 0)
  62482. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62483. titleBarArea.getWidth(), menuBarHeight);
  62484. }
  62485. const BorderSize DocumentWindow::getBorderThickness()
  62486. {
  62487. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  62488. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62489. }
  62490. const BorderSize DocumentWindow::getContentComponentBorder()
  62491. {
  62492. BorderSize border (getBorderThickness());
  62493. border.setTop (border.getTop()
  62494. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62495. + (menuBar != 0 ? menuBarHeight : 0));
  62496. return border;
  62497. }
  62498. int DocumentWindow::getTitleBarHeight() const
  62499. {
  62500. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62501. }
  62502. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62503. {
  62504. const BorderSize border (getBorderThickness());
  62505. return Rectangle<int> (border.getLeft(), border.getTop(),
  62506. getWidth() - border.getLeftAndRight(),
  62507. getTitleBarHeight());
  62508. }
  62509. Button* DocumentWindow::getCloseButton() const throw()
  62510. {
  62511. return titleBarButtons[2];
  62512. }
  62513. Button* DocumentWindow::getMinimiseButton() const throw()
  62514. {
  62515. return titleBarButtons[0];
  62516. }
  62517. Button* DocumentWindow::getMaximiseButton() const throw()
  62518. {
  62519. return titleBarButtons[1];
  62520. }
  62521. int DocumentWindow::getDesktopWindowStyleFlags() const
  62522. {
  62523. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62524. if ((requiredButtons & minimiseButton) != 0)
  62525. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62526. if ((requiredButtons & maximiseButton) != 0)
  62527. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62528. if ((requiredButtons & closeButton) != 0)
  62529. styleFlags |= ComponentPeer::windowHasCloseButton;
  62530. return styleFlags;
  62531. }
  62532. void DocumentWindow::lookAndFeelChanged()
  62533. {
  62534. int i;
  62535. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62536. titleBarButtons[i] = 0;
  62537. if (! isUsingNativeTitleBar())
  62538. {
  62539. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  62540. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  62541. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  62542. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  62543. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  62544. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  62545. for (i = 0; i < 3; ++i)
  62546. {
  62547. if (titleBarButtons[i] != 0)
  62548. {
  62549. if (buttonListener == 0)
  62550. buttonListener = new ButtonListenerProxy (*this);
  62551. titleBarButtons[i]->addButtonListener (buttonListener);
  62552. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62553. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62554. Component::addAndMakeVisible (titleBarButtons[i]);
  62555. }
  62556. }
  62557. if (getCloseButton() != 0)
  62558. {
  62559. #if JUCE_MAC
  62560. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62561. #else
  62562. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62563. #endif
  62564. }
  62565. }
  62566. activeWindowStatusChanged();
  62567. ResizableWindow::lookAndFeelChanged();
  62568. }
  62569. void DocumentWindow::parentHierarchyChanged()
  62570. {
  62571. lookAndFeelChanged();
  62572. }
  62573. void DocumentWindow::activeWindowStatusChanged()
  62574. {
  62575. ResizableWindow::activeWindowStatusChanged();
  62576. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62577. if (titleBarButtons[i] != 0)
  62578. titleBarButtons[i]->setEnabled (isActiveWindow());
  62579. if (menuBar != 0)
  62580. menuBar->setEnabled (isActiveWindow());
  62581. }
  62582. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62583. {
  62584. if (getTitleBarArea().contains (e.x, e.y)
  62585. && getMaximiseButton() != 0)
  62586. {
  62587. getMaximiseButton()->triggerClick();
  62588. }
  62589. }
  62590. void DocumentWindow::userTriedToCloseWindow()
  62591. {
  62592. closeButtonPressed();
  62593. }
  62594. END_JUCE_NAMESPACE
  62595. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  62596. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  62597. BEGIN_JUCE_NAMESPACE
  62598. ResizableWindow::ResizableWindow (const String& name,
  62599. const bool addToDesktop_)
  62600. : TopLevelWindow (name, addToDesktop_),
  62601. resizeToFitContent (false),
  62602. fullscreen (false),
  62603. lastNonFullScreenPos (50, 50, 256, 256),
  62604. constrainer (0)
  62605. #if JUCE_DEBUG
  62606. , hasBeenResized (false)
  62607. #endif
  62608. {
  62609. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62610. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  62611. if (addToDesktop_)
  62612. Component::addToDesktop (getDesktopWindowStyleFlags());
  62613. }
  62614. ResizableWindow::ResizableWindow (const String& name,
  62615. const Colour& backgroundColour_,
  62616. const bool addToDesktop_)
  62617. : TopLevelWindow (name, addToDesktop_),
  62618. resizeToFitContent (false),
  62619. fullscreen (false),
  62620. lastNonFullScreenPos (50, 50, 256, 256),
  62621. constrainer (0)
  62622. #if JUCE_DEBUG
  62623. , hasBeenResized (false)
  62624. #endif
  62625. {
  62626. setBackgroundColour (backgroundColour_);
  62627. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62628. if (addToDesktop_)
  62629. Component::addToDesktop (getDesktopWindowStyleFlags());
  62630. }
  62631. ResizableWindow::~ResizableWindow()
  62632. {
  62633. resizableCorner = 0;
  62634. resizableBorder = 0;
  62635. delete static_cast <Component*> (contentComponent);
  62636. contentComponent = 0;
  62637. // have you been adding your own components directly to this window..? tut tut tut.
  62638. // Read the instructions for using a ResizableWindow!
  62639. jassert (getNumChildComponents() == 0);
  62640. }
  62641. int ResizableWindow::getDesktopWindowStyleFlags() const
  62642. {
  62643. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  62644. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  62645. styleFlags |= ComponentPeer::windowIsResizable;
  62646. return styleFlags;
  62647. }
  62648. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  62649. const bool deleteOldOne,
  62650. const bool resizeToFit)
  62651. {
  62652. resizeToFitContent = resizeToFit;
  62653. if (newContentComponent != static_cast <Component*> (contentComponent))
  62654. {
  62655. if (deleteOldOne)
  62656. delete static_cast <Component*> (contentComponent); // (avoid using a scoped pointer for this, so that it survives
  62657. // external deletion of the content comp)
  62658. else
  62659. removeChildComponent (contentComponent);
  62660. contentComponent = newContentComponent;
  62661. Component::addAndMakeVisible (contentComponent);
  62662. }
  62663. if (resizeToFit)
  62664. childBoundsChanged (contentComponent);
  62665. resized(); // must always be called to position the new content comp
  62666. }
  62667. void ResizableWindow::setContentComponentSize (int width, int height)
  62668. {
  62669. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  62670. const BorderSize border (getContentComponentBorder());
  62671. setSize (width + border.getLeftAndRight(),
  62672. height + border.getTopAndBottom());
  62673. }
  62674. const BorderSize ResizableWindow::getBorderThickness()
  62675. {
  62676. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  62677. }
  62678. const BorderSize ResizableWindow::getContentComponentBorder()
  62679. {
  62680. return getBorderThickness();
  62681. }
  62682. void ResizableWindow::moved()
  62683. {
  62684. updateLastPos();
  62685. }
  62686. void ResizableWindow::visibilityChanged()
  62687. {
  62688. TopLevelWindow::visibilityChanged();
  62689. updateLastPos();
  62690. }
  62691. void ResizableWindow::resized()
  62692. {
  62693. if (resizableBorder != 0)
  62694. {
  62695. resizableBorder->setVisible (! isFullScreen());
  62696. resizableBorder->setBorderThickness (getBorderThickness());
  62697. resizableBorder->setSize (getWidth(), getHeight());
  62698. resizableBorder->toBack();
  62699. }
  62700. if (resizableCorner != 0)
  62701. {
  62702. resizableCorner->setVisible (! isFullScreen());
  62703. const int resizerSize = 18;
  62704. resizableCorner->setBounds (getWidth() - resizerSize,
  62705. getHeight() - resizerSize,
  62706. resizerSize, resizerSize);
  62707. }
  62708. if (contentComponent != 0)
  62709. contentComponent->setBoundsInset (getContentComponentBorder());
  62710. updateLastPos();
  62711. #if JUCE_DEBUG
  62712. hasBeenResized = true;
  62713. #endif
  62714. }
  62715. void ResizableWindow::childBoundsChanged (Component* child)
  62716. {
  62717. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  62718. {
  62719. // not going to look very good if this component has a zero size..
  62720. jassert (child->getWidth() > 0);
  62721. jassert (child->getHeight() > 0);
  62722. const BorderSize borders (getContentComponentBorder());
  62723. setSize (child->getWidth() + borders.getLeftAndRight(),
  62724. child->getHeight() + borders.getTopAndBottom());
  62725. }
  62726. }
  62727. void ResizableWindow::activeWindowStatusChanged()
  62728. {
  62729. const BorderSize border (getContentComponentBorder());
  62730. Rectangle<int> area (getLocalBounds());
  62731. repaint (area.removeFromTop (border.getTop()));
  62732. repaint (area.removeFromLeft (border.getLeft()));
  62733. repaint (area.removeFromRight (border.getRight()));
  62734. repaint (area.removeFromBottom (border.getBottom()));
  62735. }
  62736. void ResizableWindow::setResizable (const bool shouldBeResizable,
  62737. const bool useBottomRightCornerResizer)
  62738. {
  62739. if (shouldBeResizable)
  62740. {
  62741. if (useBottomRightCornerResizer)
  62742. {
  62743. resizableBorder = 0;
  62744. if (resizableCorner == 0)
  62745. {
  62746. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  62747. resizableCorner->setAlwaysOnTop (true);
  62748. }
  62749. }
  62750. else
  62751. {
  62752. resizableCorner = 0;
  62753. if (resizableBorder == 0)
  62754. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  62755. }
  62756. }
  62757. else
  62758. {
  62759. resizableCorner = 0;
  62760. resizableBorder = 0;
  62761. }
  62762. if (isUsingNativeTitleBar())
  62763. recreateDesktopWindow();
  62764. childBoundsChanged (contentComponent);
  62765. resized();
  62766. }
  62767. bool ResizableWindow::isResizable() const throw()
  62768. {
  62769. return resizableCorner != 0
  62770. || resizableBorder != 0;
  62771. }
  62772. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  62773. const int newMinimumHeight,
  62774. const int newMaximumWidth,
  62775. const int newMaximumHeight) throw()
  62776. {
  62777. // if you've set up a custom constrainer then these settings won't have any effect..
  62778. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  62779. if (constrainer == 0)
  62780. setConstrainer (&defaultConstrainer);
  62781. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  62782. newMaximumWidth, newMaximumHeight);
  62783. setBoundsConstrained (getBounds());
  62784. }
  62785. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  62786. {
  62787. if (constrainer != newConstrainer)
  62788. {
  62789. constrainer = newConstrainer;
  62790. const bool useBottomRightCornerResizer = resizableCorner != 0;
  62791. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  62792. resizableCorner = 0;
  62793. resizableBorder = 0;
  62794. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62795. ComponentPeer* const peer = getPeer();
  62796. if (peer != 0)
  62797. peer->setConstrainer (newConstrainer);
  62798. }
  62799. }
  62800. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  62801. {
  62802. if (constrainer != 0)
  62803. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  62804. else
  62805. setBounds (bounds);
  62806. }
  62807. void ResizableWindow::paint (Graphics& g)
  62808. {
  62809. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  62810. getBorderThickness(), *this);
  62811. if (! isFullScreen())
  62812. {
  62813. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  62814. getBorderThickness(), *this);
  62815. }
  62816. #if JUCE_DEBUG
  62817. /* If this fails, then you've probably written a subclass with a resized()
  62818. callback but forgotten to make it call its parent class's resized() method.
  62819. It's important when you override methods like resized(), moved(),
  62820. etc., that you make sure the base class methods also get called.
  62821. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  62822. because your content should all be inside the content component - and it's the
  62823. content component's resized() method that you should be using to do your
  62824. layout.
  62825. */
  62826. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  62827. #endif
  62828. }
  62829. void ResizableWindow::lookAndFeelChanged()
  62830. {
  62831. resized();
  62832. if (isOnDesktop())
  62833. {
  62834. Component::addToDesktop (getDesktopWindowStyleFlags());
  62835. ComponentPeer* const peer = getPeer();
  62836. if (peer != 0)
  62837. peer->setConstrainer (constrainer);
  62838. }
  62839. }
  62840. const Colour ResizableWindow::getBackgroundColour() const throw()
  62841. {
  62842. return findColour (backgroundColourId, false);
  62843. }
  62844. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  62845. {
  62846. Colour backgroundColour (newColour);
  62847. if (! Desktop::canUseSemiTransparentWindows())
  62848. backgroundColour = newColour.withAlpha (1.0f);
  62849. setColour (backgroundColourId, backgroundColour);
  62850. setOpaque (backgroundColour.isOpaque());
  62851. repaint();
  62852. }
  62853. bool ResizableWindow::isFullScreen() const
  62854. {
  62855. if (isOnDesktop())
  62856. {
  62857. ComponentPeer* const peer = getPeer();
  62858. return peer != 0 && peer->isFullScreen();
  62859. }
  62860. return fullscreen;
  62861. }
  62862. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  62863. {
  62864. if (shouldBeFullScreen != isFullScreen())
  62865. {
  62866. updateLastPos();
  62867. fullscreen = shouldBeFullScreen;
  62868. if (isOnDesktop())
  62869. {
  62870. ComponentPeer* const peer = getPeer();
  62871. if (peer != 0)
  62872. {
  62873. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  62874. const Rectangle<int> lastPos (lastNonFullScreenPos);
  62875. peer->setFullScreen (shouldBeFullScreen);
  62876. if (! shouldBeFullScreen)
  62877. setBounds (lastPos);
  62878. }
  62879. else
  62880. {
  62881. jassertfalse;
  62882. }
  62883. }
  62884. else
  62885. {
  62886. if (shouldBeFullScreen)
  62887. setBounds (0, 0, getParentWidth(), getParentHeight());
  62888. else
  62889. setBounds (lastNonFullScreenPos);
  62890. }
  62891. resized();
  62892. }
  62893. }
  62894. bool ResizableWindow::isMinimised() const
  62895. {
  62896. ComponentPeer* const peer = getPeer();
  62897. return (peer != 0) && peer->isMinimised();
  62898. }
  62899. void ResizableWindow::setMinimised (const bool shouldMinimise)
  62900. {
  62901. if (shouldMinimise != isMinimised())
  62902. {
  62903. ComponentPeer* const peer = getPeer();
  62904. if (peer != 0)
  62905. {
  62906. updateLastPos();
  62907. peer->setMinimised (shouldMinimise);
  62908. }
  62909. else
  62910. {
  62911. jassertfalse;
  62912. }
  62913. }
  62914. }
  62915. void ResizableWindow::updateLastPos()
  62916. {
  62917. if (isShowing() && ! (isFullScreen() || isMinimised()))
  62918. {
  62919. lastNonFullScreenPos = getBounds();
  62920. }
  62921. }
  62922. void ResizableWindow::parentSizeChanged()
  62923. {
  62924. if (isFullScreen() && getParentComponent() != 0)
  62925. {
  62926. setBounds (0, 0, getParentWidth(), getParentHeight());
  62927. }
  62928. }
  62929. const String ResizableWindow::getWindowStateAsString()
  62930. {
  62931. updateLastPos();
  62932. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  62933. }
  62934. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  62935. {
  62936. StringArray tokens;
  62937. tokens.addTokens (s, false);
  62938. tokens.removeEmptyStrings();
  62939. tokens.trim();
  62940. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  62941. const int firstCoord = fs ? 1 : 0;
  62942. if (tokens.size() != firstCoord + 4)
  62943. return false;
  62944. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  62945. tokens[firstCoord + 1].getIntValue(),
  62946. tokens[firstCoord + 2].getIntValue(),
  62947. tokens[firstCoord + 3].getIntValue());
  62948. if (newPos.isEmpty())
  62949. return false;
  62950. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  62951. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  62952. if (peer != 0)
  62953. peer->getFrameSize().addTo (newPos);
  62954. if (! screen.contains (newPos))
  62955. {
  62956. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  62957. jmin (newPos.getHeight(), screen.getHeight()));
  62958. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  62959. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  62960. }
  62961. if (peer != 0)
  62962. {
  62963. peer->getFrameSize().subtractFrom (newPos);
  62964. peer->setNonFullScreenBounds (newPos);
  62965. }
  62966. lastNonFullScreenPos = newPos;
  62967. setFullScreen (fs);
  62968. if (! fs)
  62969. setBoundsConstrained (newPos);
  62970. return true;
  62971. }
  62972. void ResizableWindow::mouseDown (const MouseEvent&)
  62973. {
  62974. if (! isFullScreen())
  62975. dragger.startDraggingComponent (this, constrainer);
  62976. }
  62977. void ResizableWindow::mouseDrag (const MouseEvent& e)
  62978. {
  62979. if (! isFullScreen())
  62980. dragger.dragComponent (this, e);
  62981. }
  62982. #if JUCE_DEBUG
  62983. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  62984. {
  62985. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62986. manages its child components automatically, and if you add your own it'll cause
  62987. trouble. Instead, use setContentComponent() to give it a component which
  62988. will be automatically resized and kept in the right place - then you can add
  62989. subcomponents to the content comp. See the notes for the ResizableWindow class
  62990. for more info.
  62991. If you really know what you're doing and want to avoid this assertion, just call
  62992. Component::addChildComponent directly.
  62993. */
  62994. jassertfalse;
  62995. Component::addChildComponent (child, zOrder);
  62996. }
  62997. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  62998. {
  62999. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63000. manages its child components automatically, and if you add your own it'll cause
  63001. trouble. Instead, use setContentComponent() to give it a component which
  63002. will be automatically resized and kept in the right place - then you can add
  63003. subcomponents to the content comp. See the notes for the ResizableWindow class
  63004. for more info.
  63005. If you really know what you're doing and want to avoid this assertion, just call
  63006. Component::addAndMakeVisible directly.
  63007. */
  63008. jassertfalse;
  63009. Component::addAndMakeVisible (child, zOrder);
  63010. }
  63011. #endif
  63012. END_JUCE_NAMESPACE
  63013. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63014. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63015. BEGIN_JUCE_NAMESPACE
  63016. SplashScreen::SplashScreen()
  63017. {
  63018. setOpaque (true);
  63019. }
  63020. SplashScreen::~SplashScreen()
  63021. {
  63022. }
  63023. void SplashScreen::show (const String& title,
  63024. const Image& backgroundImage_,
  63025. const int minimumTimeToDisplayFor,
  63026. const bool useDropShadow,
  63027. const bool removeOnMouseClick)
  63028. {
  63029. backgroundImage = backgroundImage_;
  63030. jassert (backgroundImage_.isValid());
  63031. if (backgroundImage_.isValid())
  63032. {
  63033. setOpaque (! backgroundImage_.hasAlphaChannel());
  63034. show (title,
  63035. backgroundImage_.getWidth(),
  63036. backgroundImage_.getHeight(),
  63037. minimumTimeToDisplayFor,
  63038. useDropShadow,
  63039. removeOnMouseClick);
  63040. }
  63041. }
  63042. void SplashScreen::show (const String& title,
  63043. const int width,
  63044. const int height,
  63045. const int minimumTimeToDisplayFor,
  63046. const bool useDropShadow,
  63047. const bool removeOnMouseClick)
  63048. {
  63049. setName (title);
  63050. setAlwaysOnTop (true);
  63051. setVisible (true);
  63052. centreWithSize (width, height);
  63053. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63054. toFront (false);
  63055. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63056. repaint();
  63057. originalClickCounter = removeOnMouseClick
  63058. ? Desktop::getMouseButtonClickCounter()
  63059. : std::numeric_limits<int>::max();
  63060. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63061. startTimer (50);
  63062. }
  63063. void SplashScreen::paint (Graphics& g)
  63064. {
  63065. g.setOpacity (1.0f);
  63066. g.drawImage (backgroundImage,
  63067. 0, 0, getWidth(), getHeight(),
  63068. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63069. }
  63070. void SplashScreen::timerCallback()
  63071. {
  63072. if (Time::getCurrentTime() > earliestTimeToDelete
  63073. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63074. {
  63075. delete this;
  63076. }
  63077. }
  63078. END_JUCE_NAMESPACE
  63079. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63080. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63081. BEGIN_JUCE_NAMESPACE
  63082. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63083. const bool hasProgressBar,
  63084. const bool hasCancelButton,
  63085. const int timeOutMsWhenCancelling_,
  63086. const String& cancelButtonText)
  63087. : Thread ("Juce Progress Window"),
  63088. progress (0.0),
  63089. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63090. {
  63091. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63092. .createAlertWindow (title, String::empty, cancelButtonText,
  63093. String::empty, String::empty,
  63094. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63095. if (hasProgressBar)
  63096. alertWindow->addProgressBarComponent (progress);
  63097. }
  63098. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63099. {
  63100. stopThread (timeOutMsWhenCancelling);
  63101. }
  63102. bool ThreadWithProgressWindow::runThread (const int priority)
  63103. {
  63104. startThread (priority);
  63105. startTimer (100);
  63106. {
  63107. const ScopedLock sl (messageLock);
  63108. alertWindow->setMessage (message);
  63109. }
  63110. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63111. stopThread (timeOutMsWhenCancelling);
  63112. alertWindow->setVisible (false);
  63113. return finishedNaturally;
  63114. }
  63115. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63116. {
  63117. progress = newProgress;
  63118. }
  63119. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63120. {
  63121. const ScopedLock sl (messageLock);
  63122. message = newStatusMessage;
  63123. }
  63124. void ThreadWithProgressWindow::timerCallback()
  63125. {
  63126. if (! isThreadRunning())
  63127. {
  63128. // thread has finished normally..
  63129. alertWindow->exitModalState (1);
  63130. alertWindow->setVisible (false);
  63131. }
  63132. else
  63133. {
  63134. const ScopedLock sl (messageLock);
  63135. alertWindow->setMessage (message);
  63136. }
  63137. }
  63138. END_JUCE_NAMESPACE
  63139. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63140. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63141. BEGIN_JUCE_NAMESPACE
  63142. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63143. const int millisecondsBeforeTipAppears_)
  63144. : Component ("tooltip"),
  63145. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63146. mouseClicks (0),
  63147. lastHideTime (0),
  63148. lastComponentUnderMouse (0),
  63149. changedCompsSinceShown (true)
  63150. {
  63151. if (Desktop::getInstance().getMainMouseSource().canHover())
  63152. startTimer (123);
  63153. setAlwaysOnTop (true);
  63154. setOpaque (true);
  63155. if (parentComponent != 0)
  63156. parentComponent->addChildComponent (this);
  63157. }
  63158. TooltipWindow::~TooltipWindow()
  63159. {
  63160. hide();
  63161. }
  63162. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63163. {
  63164. millisecondsBeforeTipAppears = newTimeMs;
  63165. }
  63166. void TooltipWindow::paint (Graphics& g)
  63167. {
  63168. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63169. }
  63170. void TooltipWindow::mouseEnter (const MouseEvent&)
  63171. {
  63172. hide();
  63173. }
  63174. void TooltipWindow::showFor (const String& tip)
  63175. {
  63176. jassert (tip.isNotEmpty());
  63177. tipShowing = tip;
  63178. Point<int> mousePos (Desktop::getMousePosition());
  63179. if (getParentComponent() != 0)
  63180. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  63181. int x, y, w, h;
  63182. getLookAndFeel().getTooltipSize (tip, w, h);
  63183. if (mousePos.getX() > getParentWidth() / 2)
  63184. x = mousePos.getX() - (w + 12);
  63185. else
  63186. x = mousePos.getX() + 24;
  63187. if (mousePos.getY() > getParentHeight() / 2)
  63188. y = mousePos.getY() - (h + 6);
  63189. else
  63190. y = mousePos.getY() + 6;
  63191. setBounds (x, y, w, h);
  63192. setVisible (true);
  63193. if (getParentComponent() == 0)
  63194. {
  63195. addToDesktop (ComponentPeer::windowHasDropShadow
  63196. | ComponentPeer::windowIsTemporary
  63197. | ComponentPeer::windowIgnoresKeyPresses);
  63198. }
  63199. toFront (false);
  63200. }
  63201. const String TooltipWindow::getTipFor (Component* const c)
  63202. {
  63203. if (c != 0
  63204. && Process::isForegroundProcess()
  63205. && ! Component::isMouseButtonDownAnywhere())
  63206. {
  63207. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63208. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63209. return ttc->getTooltip();
  63210. }
  63211. return String::empty;
  63212. }
  63213. void TooltipWindow::hide()
  63214. {
  63215. tipShowing = String::empty;
  63216. removeFromDesktop();
  63217. setVisible (false);
  63218. }
  63219. void TooltipWindow::timerCallback()
  63220. {
  63221. const unsigned int now = Time::getApproximateMillisecondCounter();
  63222. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63223. const String newTip (getTipFor (newComp));
  63224. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63225. lastComponentUnderMouse = newComp;
  63226. lastTipUnderMouse = newTip;
  63227. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63228. const bool mouseWasClicked = clickCount > mouseClicks;
  63229. mouseClicks = clickCount;
  63230. const Point<int> mousePos (Desktop::getMousePosition());
  63231. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63232. lastMousePos = mousePos;
  63233. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63234. lastCompChangeTime = now;
  63235. if (isVisible() || now < lastHideTime + 500)
  63236. {
  63237. // if a tip is currently visible (or has just disappeared), update to a new one
  63238. // immediately if needed..
  63239. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63240. {
  63241. if (isVisible())
  63242. {
  63243. lastHideTime = now;
  63244. hide();
  63245. }
  63246. }
  63247. else if (tipChanged)
  63248. {
  63249. showFor (newTip);
  63250. }
  63251. }
  63252. else
  63253. {
  63254. // if there isn't currently a tip, but one is needed, only let it
  63255. // appear after a timeout..
  63256. if (newTip.isNotEmpty()
  63257. && newTip != tipShowing
  63258. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63259. {
  63260. showFor (newTip);
  63261. }
  63262. }
  63263. }
  63264. END_JUCE_NAMESPACE
  63265. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63266. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63267. BEGIN_JUCE_NAMESPACE
  63268. /** Keeps track of the active top level window.
  63269. */
  63270. class TopLevelWindowManager : public Timer,
  63271. public DeletedAtShutdown
  63272. {
  63273. public:
  63274. TopLevelWindowManager()
  63275. : currentActive (0)
  63276. {
  63277. }
  63278. ~TopLevelWindowManager()
  63279. {
  63280. clearSingletonInstance();
  63281. }
  63282. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  63283. void timerCallback()
  63284. {
  63285. startTimer (jmin (1731, getTimerInterval() * 2));
  63286. TopLevelWindow* active = 0;
  63287. if (Process::isForegroundProcess())
  63288. {
  63289. active = currentActive;
  63290. Component* const c = Component::getCurrentlyFocusedComponent();
  63291. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  63292. if (tlw == 0 && c != 0)
  63293. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  63294. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  63295. if (tlw != 0)
  63296. active = tlw;
  63297. }
  63298. if (active != currentActive)
  63299. {
  63300. currentActive = active;
  63301. for (int i = windows.size(); --i >= 0;)
  63302. {
  63303. TopLevelWindow* const tlw = windows.getUnchecked (i);
  63304. tlw->setWindowActive (isWindowActive (tlw));
  63305. i = jmin (i, windows.size() - 1);
  63306. }
  63307. Desktop::getInstance().triggerFocusCallback();
  63308. }
  63309. }
  63310. bool addWindow (TopLevelWindow* const w)
  63311. {
  63312. windows.add (w);
  63313. startTimer (10);
  63314. return isWindowActive (w);
  63315. }
  63316. void removeWindow (TopLevelWindow* const w)
  63317. {
  63318. startTimer (10);
  63319. if (currentActive == w)
  63320. currentActive = 0;
  63321. windows.removeValue (w);
  63322. if (windows.size() == 0)
  63323. deleteInstance();
  63324. }
  63325. Array <TopLevelWindow*> windows;
  63326. private:
  63327. TopLevelWindow* currentActive;
  63328. bool isWindowActive (TopLevelWindow* const tlw) const
  63329. {
  63330. return (tlw == currentActive
  63331. || tlw->isParentOf (currentActive)
  63332. || tlw->hasKeyboardFocus (true))
  63333. && tlw->isShowing();
  63334. }
  63335. TopLevelWindowManager (const TopLevelWindowManager&);
  63336. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  63337. };
  63338. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63339. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63340. {
  63341. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63342. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63343. }
  63344. TopLevelWindow::TopLevelWindow (const String& name,
  63345. const bool addToDesktop_)
  63346. : Component (name),
  63347. useDropShadow (true),
  63348. useNativeTitleBar (false),
  63349. windowIsActive_ (false)
  63350. {
  63351. setOpaque (true);
  63352. if (addToDesktop_)
  63353. Component::addToDesktop (getDesktopWindowStyleFlags());
  63354. else
  63355. setDropShadowEnabled (true);
  63356. setWantsKeyboardFocus (true);
  63357. setBroughtToFrontOnMouseClick (true);
  63358. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63359. }
  63360. TopLevelWindow::~TopLevelWindow()
  63361. {
  63362. shadower = 0;
  63363. TopLevelWindowManager::getInstance()->removeWindow (this);
  63364. }
  63365. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63366. {
  63367. if (hasKeyboardFocus (true))
  63368. TopLevelWindowManager::getInstance()->timerCallback();
  63369. else
  63370. TopLevelWindowManager::getInstance()->startTimer (10);
  63371. }
  63372. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63373. {
  63374. if (windowIsActive_ != isNowActive)
  63375. {
  63376. windowIsActive_ = isNowActive;
  63377. activeWindowStatusChanged();
  63378. }
  63379. }
  63380. void TopLevelWindow::activeWindowStatusChanged()
  63381. {
  63382. }
  63383. void TopLevelWindow::parentHierarchyChanged()
  63384. {
  63385. setDropShadowEnabled (useDropShadow);
  63386. }
  63387. void TopLevelWindow::visibilityChanged()
  63388. {
  63389. if (isShowing())
  63390. toFront (true);
  63391. }
  63392. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63393. {
  63394. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63395. if (useDropShadow)
  63396. styleFlags |= ComponentPeer::windowHasDropShadow;
  63397. if (useNativeTitleBar)
  63398. styleFlags |= ComponentPeer::windowHasTitleBar;
  63399. return styleFlags;
  63400. }
  63401. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63402. {
  63403. useDropShadow = useShadow;
  63404. if (isOnDesktop())
  63405. {
  63406. shadower = 0;
  63407. Component::addToDesktop (getDesktopWindowStyleFlags());
  63408. }
  63409. else
  63410. {
  63411. if (useShadow && isOpaque())
  63412. {
  63413. if (shadower == 0)
  63414. {
  63415. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63416. if (shadower != 0)
  63417. shadower->setOwner (this);
  63418. }
  63419. }
  63420. else
  63421. {
  63422. shadower = 0;
  63423. }
  63424. }
  63425. }
  63426. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63427. {
  63428. if (useNativeTitleBar != useNativeTitleBar_)
  63429. {
  63430. useNativeTitleBar = useNativeTitleBar_;
  63431. recreateDesktopWindow();
  63432. sendLookAndFeelChange();
  63433. }
  63434. }
  63435. void TopLevelWindow::recreateDesktopWindow()
  63436. {
  63437. if (isOnDesktop())
  63438. {
  63439. Component::addToDesktop (getDesktopWindowStyleFlags());
  63440. toFront (true);
  63441. }
  63442. }
  63443. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63444. {
  63445. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63446. because this class needs to make sure its layout corresponds with settings like whether
  63447. it's got a native title bar or not.
  63448. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63449. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63450. method, then add or remove whatever flags are necessary from this value before returning it.
  63451. */
  63452. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63453. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63454. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63455. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63456. sendLookAndFeelChange();
  63457. }
  63458. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63459. {
  63460. if (c == 0)
  63461. c = TopLevelWindow::getActiveTopLevelWindow();
  63462. if (c == 0)
  63463. {
  63464. centreWithSize (width, height);
  63465. }
  63466. else
  63467. {
  63468. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  63469. (c->getHeight() - height) / 2)));
  63470. Rectangle<int> parentArea (c->getParentMonitorArea());
  63471. if (getParentComponent() != 0)
  63472. {
  63473. p = getParentComponent()->globalPositionToRelative (p);
  63474. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  63475. }
  63476. parentArea.reduce (12, 12);
  63477. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  63478. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  63479. width, height);
  63480. }
  63481. }
  63482. int TopLevelWindow::getNumTopLevelWindows() throw()
  63483. {
  63484. return TopLevelWindowManager::getInstance()->windows.size();
  63485. }
  63486. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63487. {
  63488. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63489. }
  63490. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63491. {
  63492. TopLevelWindow* best = 0;
  63493. int bestNumTWLParents = -1;
  63494. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63495. {
  63496. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63497. if (tlw->isActiveWindow())
  63498. {
  63499. int numTWLParents = 0;
  63500. const Component* c = tlw->getParentComponent();
  63501. while (c != 0)
  63502. {
  63503. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63504. ++numTWLParents;
  63505. c = c->getParentComponent();
  63506. }
  63507. if (bestNumTWLParents < numTWLParents)
  63508. {
  63509. best = tlw;
  63510. bestNumTWLParents = numTWLParents;
  63511. }
  63512. }
  63513. }
  63514. return best;
  63515. }
  63516. END_JUCE_NAMESPACE
  63517. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63518. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  63519. BEGIN_JUCE_NAMESPACE
  63520. namespace RelativeCoordinateHelpers
  63521. {
  63522. static bool isOrigin (const String& name)
  63523. {
  63524. return name.isEmpty()
  63525. || name == RelativeCoordinate::Strings::parentLeft
  63526. || name == RelativeCoordinate::Strings::parentTop;
  63527. }
  63528. static const String getExtentAnchorName (const bool isHorizontal) throw()
  63529. {
  63530. return isHorizontal ? RelativeCoordinate::Strings::parentRight
  63531. : RelativeCoordinate::Strings::parentBottom;
  63532. }
  63533. static const String getObjectName (const String& fullName)
  63534. {
  63535. return fullName.upToFirstOccurrenceOf (".", false, false);
  63536. }
  63537. static const String getEdgeName (const String& fullName)
  63538. {
  63539. return fullName.fromFirstOccurrenceOf (".", false, false);
  63540. }
  63541. static const RelativeCoordinate findCoordinate (const String& name, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  63542. {
  63543. return nameFinder != 0 ? nameFinder->findNamedCoordinate (getObjectName (name), getEdgeName (name))
  63544. : RelativeCoordinate();
  63545. }
  63546. struct RecursionException : public std::runtime_error
  63547. {
  63548. RecursionException() : std::runtime_error ("Recursive RelativeCoordinate expression")
  63549. {
  63550. }
  63551. };
  63552. static void skipWhitespace (const juce_wchar* const s, int& i)
  63553. {
  63554. while (CharacterFunctions::isWhitespace (s[i]))
  63555. ++i;
  63556. }
  63557. static void skipComma (const juce_wchar* const s, int& i)
  63558. {
  63559. skipWhitespace (s, i);
  63560. if (s[i] == ',')
  63561. ++i;
  63562. }
  63563. static const String readAnchorName (const juce_wchar* const s, int& i)
  63564. {
  63565. skipWhitespace (s, i);
  63566. if (CharacterFunctions::isLetter (s[i]) || s[i] == '_')
  63567. {
  63568. int start = i;
  63569. while (CharacterFunctions::isLetterOrDigit (s[i]) || s[i] == '_' || s[i] == '.')
  63570. ++i;
  63571. return String (s + start, i - start);
  63572. }
  63573. return String::empty;
  63574. }
  63575. static double readNumber (const juce_wchar* const s, int& i)
  63576. {
  63577. skipWhitespace (s, i);
  63578. int start = i;
  63579. if (CharacterFunctions::isDigit (s[i]) || s[i] == '.' || s[i] == '-')
  63580. ++i;
  63581. while (CharacterFunctions::isDigit (s[i]) || s[i] == '.')
  63582. ++i;
  63583. if ((s[i] == 'e' || s[i] == 'E')
  63584. && (CharacterFunctions::isDigit (s[i + 1])
  63585. || s[i + 1] == '-'
  63586. || s[i + 1] == '+'))
  63587. {
  63588. i += 2;
  63589. while (CharacterFunctions::isDigit (s[i]))
  63590. ++i;
  63591. }
  63592. const double value = String (s + start, i - start).getDoubleValue();
  63593. while (CharacterFunctions::isWhitespace (s[i]) || s[i] == ',')
  63594. ++i;
  63595. return value;
  63596. }
  63597. static const RelativeCoordinate readNextCoordinate (const juce_wchar* const s, int& i, const bool isHorizontal)
  63598. {
  63599. String anchor1 (readAnchorName (s, i));
  63600. double value = 0;
  63601. if (anchor1.isNotEmpty())
  63602. {
  63603. skipWhitespace (s, i);
  63604. if (s[i] == '+')
  63605. value = readNumber (s, ++i);
  63606. else if (s[i] == '-')
  63607. value = -readNumber (s, ++i);
  63608. return RelativeCoordinate (value, anchor1);
  63609. }
  63610. else
  63611. {
  63612. value = readNumber (s, i);
  63613. skipWhitespace (s, i);
  63614. if (s[i] == '%')
  63615. {
  63616. value /= 100.0;
  63617. skipWhitespace (s, ++i);
  63618. String anchor2;
  63619. if (s[i] == '*')
  63620. {
  63621. anchor1 = readAnchorName (s, ++i);
  63622. skipWhitespace (s, i);
  63623. if (s[i] == '-' && s[i + 1] == '>')
  63624. {
  63625. i += 2;
  63626. anchor2 = readAnchorName (s, i);
  63627. }
  63628. else
  63629. {
  63630. anchor2 = anchor1;
  63631. anchor1 = String::empty;
  63632. }
  63633. }
  63634. else
  63635. {
  63636. anchor1 = String::empty;
  63637. anchor2 = getExtentAnchorName (isHorizontal);
  63638. }
  63639. return RelativeCoordinate (value, anchor1, anchor2);
  63640. }
  63641. return RelativeCoordinate (value);
  63642. }
  63643. }
  63644. static const String limitedAccuracyString (const double n)
  63645. {
  63646. if (! (n < -0.001 || n > 0.001)) // to detect NaN and inf as well as for rounding
  63647. return "0";
  63648. return String (n, 3).trimCharactersAtEnd ("0").trimCharactersAtEnd (".");
  63649. }
  63650. }
  63651. const String RelativeCoordinate::Strings::parent ("parent");
  63652. const String RelativeCoordinate::Strings::left ("left");
  63653. const String RelativeCoordinate::Strings::right ("right");
  63654. const String RelativeCoordinate::Strings::top ("top");
  63655. const String RelativeCoordinate::Strings::bottom ("bottom");
  63656. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  63657. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  63658. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  63659. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  63660. RelativeCoordinate::RelativeCoordinate()
  63661. : value (0)
  63662. {
  63663. }
  63664. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  63665. : value (absoluteDistanceFromOrigin)
  63666. {
  63667. }
  63668. RelativeCoordinate::RelativeCoordinate (const double absoluteDistance, const String& source)
  63669. : anchor1 (source.trim()),
  63670. value (absoluteDistance)
  63671. {
  63672. }
  63673. RelativeCoordinate::RelativeCoordinate (const double relativeProportion, const String& pos1, const String& pos2)
  63674. : anchor1 (pos1.trim()),
  63675. anchor2 (pos2.trim()),
  63676. value (relativeProportion)
  63677. {
  63678. }
  63679. RelativeCoordinate::RelativeCoordinate (const String& s, const bool isHorizontal)
  63680. : value (0)
  63681. {
  63682. int i = 0;
  63683. *this = RelativeCoordinateHelpers::readNextCoordinate (s, i, isHorizontal);
  63684. }
  63685. RelativeCoordinate::~RelativeCoordinate()
  63686. {
  63687. }
  63688. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  63689. {
  63690. return value == other.value && anchor1 == other.anchor1 && anchor2 == other.anchor2;
  63691. }
  63692. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  63693. {
  63694. return ! operator== (other);
  63695. }
  63696. const RelativeCoordinate RelativeCoordinate::getAnchorCoordinate1() const
  63697. {
  63698. return RelativeCoordinate (0.0, anchor1);
  63699. }
  63700. const RelativeCoordinate RelativeCoordinate::getAnchorCoordinate2() const
  63701. {
  63702. return RelativeCoordinate (0.0, anchor2);
  63703. }
  63704. double RelativeCoordinate::resolveAnchor (const String& anchorName, const NamedCoordinateFinder* nameFinder, int recursionCounter)
  63705. {
  63706. if (RelativeCoordinateHelpers::isOrigin (anchorName))
  63707. return 0.0;
  63708. return RelativeCoordinateHelpers::findCoordinate (anchorName, nameFinder).resolve (nameFinder, recursionCounter + 1);
  63709. }
  63710. double RelativeCoordinate::resolve (const NamedCoordinateFinder* nameFinder, int recursionCounter) const
  63711. {
  63712. if (recursionCounter > 150)
  63713. {
  63714. jassertfalse
  63715. throw RelativeCoordinateHelpers::RecursionException();
  63716. }
  63717. const double pos1 = resolveAnchor (anchor1, nameFinder, recursionCounter);
  63718. return isProportional() ? pos1 + (resolveAnchor (anchor2, nameFinder, recursionCounter) - pos1) * value
  63719. : pos1 + value;
  63720. }
  63721. double RelativeCoordinate::resolve (const NamedCoordinateFinder* nameFinder) const
  63722. {
  63723. try
  63724. {
  63725. return resolve (nameFinder, 0);
  63726. }
  63727. catch (RelativeCoordinateHelpers::RecursionException&)
  63728. {}
  63729. return 0.0;
  63730. }
  63731. bool RelativeCoordinate::isRecursive (const NamedCoordinateFinder* nameFinder) const
  63732. {
  63733. try
  63734. {
  63735. (void) resolve (nameFinder, 0);
  63736. }
  63737. catch (RelativeCoordinateHelpers::RecursionException&)
  63738. {
  63739. return true;
  63740. }
  63741. return false;
  63742. }
  63743. void RelativeCoordinate::moveToAbsolute (double newPos, const NamedCoordinateFinder* nameFinder)
  63744. {
  63745. try
  63746. {
  63747. const double pos1 = resolveAnchor (anchor1, nameFinder, 0);
  63748. if (isProportional())
  63749. {
  63750. const double size = resolveAnchor (anchor2, nameFinder, 0) - pos1;
  63751. if (size != 0)
  63752. value = (newPos - pos1) / size;
  63753. }
  63754. else
  63755. {
  63756. value = newPos - pos1;
  63757. }
  63758. }
  63759. catch (RelativeCoordinateHelpers::RecursionException&)
  63760. {}
  63761. }
  63762. void RelativeCoordinate::toggleProportionality (const NamedCoordinateFinder* nameFinder,
  63763. const String& proportionalAnchor1, const String& proportionalAnchor2)
  63764. {
  63765. const double oldValue = resolve (nameFinder);
  63766. anchor1 = proportionalAnchor1;
  63767. anchor2 = isProportional() ? String::empty : proportionalAnchor2;
  63768. moveToAbsolute (oldValue, nameFinder);
  63769. }
  63770. bool RelativeCoordinate::references (const String& coordName, const NamedCoordinateFinder* nameFinder) const
  63771. {
  63772. using namespace RelativeCoordinateHelpers;
  63773. if (isOrigin (anchor1) && ! isProportional())
  63774. return isOrigin (coordName);
  63775. return anchor1 == coordName
  63776. || anchor2 == coordName
  63777. || findCoordinate (anchor1, nameFinder).references (coordName, nameFinder)
  63778. || (isProportional() && findCoordinate (anchor2, nameFinder).references (coordName, nameFinder));
  63779. }
  63780. bool RelativeCoordinate::isDynamic() const
  63781. {
  63782. return anchor2.isNotEmpty() || ! RelativeCoordinateHelpers::isOrigin (anchor1);
  63783. }
  63784. const String RelativeCoordinate::toString() const
  63785. {
  63786. using namespace RelativeCoordinateHelpers;
  63787. if (isProportional())
  63788. {
  63789. const String percent (limitedAccuracyString (value * 100.0));
  63790. if (isOrigin (anchor1))
  63791. {
  63792. if (anchor2 == Strings::parentRight || anchor2 == Strings::parentBottom)
  63793. return percent + "%";
  63794. else
  63795. return percent + "% * " + anchor2;
  63796. }
  63797. else
  63798. return percent + "% * " + anchor1 + " -> " + anchor2;
  63799. }
  63800. else
  63801. {
  63802. if (isOrigin (anchor1))
  63803. return limitedAccuracyString (value);
  63804. else if (value > 0)
  63805. return anchor1 + " + " + limitedAccuracyString (value);
  63806. else if (value < 0)
  63807. return anchor1 + " - " + limitedAccuracyString (-value);
  63808. else
  63809. return anchor1;
  63810. }
  63811. }
  63812. const double RelativeCoordinate::getEditableNumber() const
  63813. {
  63814. return isProportional() ? value * 100.0 : value;
  63815. }
  63816. void RelativeCoordinate::setEditableNumber (const double newValue)
  63817. {
  63818. value = isProportional() ? newValue / 100.0 : newValue;
  63819. }
  63820. const String RelativeCoordinate::getAnchorName1 (const String& returnValueIfOrigin) const
  63821. {
  63822. return RelativeCoordinateHelpers::isOrigin (anchor1) ? returnValueIfOrigin : anchor1;
  63823. }
  63824. const String RelativeCoordinate::getAnchorName2 (const String& returnValueIfOrigin) const
  63825. {
  63826. return RelativeCoordinateHelpers::isOrigin (anchor2) ? returnValueIfOrigin : anchor2;
  63827. }
  63828. void RelativeCoordinate::changeAnchor1 (const String& newAnchorName, const NamedCoordinateFinder* nameFinder)
  63829. {
  63830. jassert (newAnchorName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_."));
  63831. const double oldValue = resolve (nameFinder);
  63832. anchor1 = RelativeCoordinateHelpers::isOrigin (newAnchorName) ? String::empty : newAnchorName;
  63833. moveToAbsolute (oldValue, nameFinder);
  63834. }
  63835. void RelativeCoordinate::changeAnchor2 (const String& newAnchorName, const NamedCoordinateFinder* nameFinder)
  63836. {
  63837. jassert (isProportional());
  63838. jassert (newAnchorName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_."));
  63839. const double oldValue = resolve (nameFinder);
  63840. anchor2 = RelativeCoordinateHelpers::isOrigin (newAnchorName) ? String::empty : newAnchorName;
  63841. moveToAbsolute (oldValue, nameFinder);
  63842. }
  63843. void RelativeCoordinate::renameAnchorIfUsed (const String& oldName, const String& newName, const NamedCoordinateFinder* nameFinder)
  63844. {
  63845. using namespace RelativeCoordinateHelpers;
  63846. jassert (oldName.isNotEmpty());
  63847. jassert (newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  63848. if (newName.isEmpty())
  63849. {
  63850. if (getObjectName (anchor1) == oldName
  63851. || getObjectName (anchor2) == oldName)
  63852. {
  63853. value = resolve (nameFinder);
  63854. anchor1 = String::empty;
  63855. anchor2 = String::empty;
  63856. }
  63857. }
  63858. else
  63859. {
  63860. if (getObjectName (anchor1) == oldName)
  63861. anchor1 = newName + "." + getEdgeName (anchor1);
  63862. if (getObjectName (anchor2) == oldName)
  63863. anchor2 = newName + "." + getEdgeName (anchor2);
  63864. }
  63865. }
  63866. RelativePoint::RelativePoint()
  63867. {
  63868. }
  63869. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  63870. : x (absolutePoint.getX()), y (absolutePoint.getY())
  63871. {
  63872. }
  63873. RelativePoint::RelativePoint (const float x_, const float y_)
  63874. : x (x_), y (y_)
  63875. {
  63876. }
  63877. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  63878. : x (x_), y (y_)
  63879. {
  63880. }
  63881. RelativePoint::RelativePoint (const String& s)
  63882. {
  63883. int i = 0;
  63884. x = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  63885. RelativeCoordinateHelpers::skipComma (s, i);
  63886. y = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  63887. }
  63888. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  63889. {
  63890. return x == other.x && y == other.y;
  63891. }
  63892. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  63893. {
  63894. return ! operator== (other);
  63895. }
  63896. const Point<float> RelativePoint::resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  63897. {
  63898. return Point<float> ((float) x.resolve (nameFinder),
  63899. (float) y.resolve (nameFinder));
  63900. }
  63901. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  63902. {
  63903. x.moveToAbsolute (newPos.getX(), nameFinder);
  63904. y.moveToAbsolute (newPos.getY(), nameFinder);
  63905. }
  63906. const String RelativePoint::toString() const
  63907. {
  63908. return x.toString() + ", " + y.toString();
  63909. }
  63910. void RelativePoint::renameAnchorIfUsed (const String& oldName, const String& newName, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  63911. {
  63912. x.renameAnchorIfUsed (oldName, newName, nameFinder);
  63913. y.renameAnchorIfUsed (oldName, newName, nameFinder);
  63914. }
  63915. bool RelativePoint::isDynamic() const
  63916. {
  63917. return x.isDynamic() || y.isDynamic();
  63918. }
  63919. RelativeRectangle::RelativeRectangle()
  63920. {
  63921. }
  63922. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  63923. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  63924. : left (left_), right (right_), top (top_), bottom (bottom_)
  63925. {
  63926. }
  63927. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  63928. : left (rect.getX()),
  63929. right (rect.getWidth(), componentName + "." + RelativeCoordinate::Strings::left),
  63930. top (rect.getY()),
  63931. bottom (rect.getHeight(), componentName + "." + RelativeCoordinate::Strings::top)
  63932. {
  63933. }
  63934. RelativeRectangle::RelativeRectangle (const String& s)
  63935. {
  63936. int i = 0;
  63937. left = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  63938. RelativeCoordinateHelpers::skipComma (s, i);
  63939. top = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  63940. RelativeCoordinateHelpers::skipComma (s, i);
  63941. right = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  63942. RelativeCoordinateHelpers::skipComma (s, i);
  63943. bottom = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  63944. }
  63945. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  63946. {
  63947. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  63948. }
  63949. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  63950. {
  63951. return ! operator== (other);
  63952. }
  63953. const Rectangle<float> RelativeRectangle::resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  63954. {
  63955. const double l = left.resolve (nameFinder);
  63956. const double r = right.resolve (nameFinder);
  63957. const double t = top.resolve (nameFinder);
  63958. const double b = bottom.resolve (nameFinder);
  63959. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  63960. }
  63961. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  63962. {
  63963. left.moveToAbsolute (newPos.getX(), nameFinder);
  63964. right.moveToAbsolute (newPos.getRight(), nameFinder);
  63965. top.moveToAbsolute (newPos.getY(), nameFinder);
  63966. bottom.moveToAbsolute (newPos.getBottom(), nameFinder);
  63967. }
  63968. const String RelativeRectangle::toString() const
  63969. {
  63970. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  63971. }
  63972. void RelativeRectangle::renameAnchorIfUsed (const String& oldName, const String& newName,
  63973. const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  63974. {
  63975. left.renameAnchorIfUsed (oldName, newName, nameFinder);
  63976. right.renameAnchorIfUsed (oldName, newName, nameFinder);
  63977. top.renameAnchorIfUsed (oldName, newName, nameFinder);
  63978. bottom.renameAnchorIfUsed (oldName, newName, nameFinder);
  63979. }
  63980. RelativePointPath::RelativePointPath()
  63981. : usesNonZeroWinding (true),
  63982. containsDynamicPoints (false)
  63983. {
  63984. }
  63985. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  63986. : usesNonZeroWinding (true),
  63987. containsDynamicPoints (false)
  63988. {
  63989. ValueTree state (DrawablePath::valueTreeType);
  63990. other.writeTo (state, 0);
  63991. parse (state);
  63992. }
  63993. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  63994. : usesNonZeroWinding (true),
  63995. containsDynamicPoints (false)
  63996. {
  63997. parse (drawable);
  63998. }
  63999. RelativePointPath::RelativePointPath (const Path& path)
  64000. {
  64001. usesNonZeroWinding = path.isUsingNonZeroWinding();
  64002. Path::Iterator i (path);
  64003. while (i.next())
  64004. {
  64005. switch (i.elementType)
  64006. {
  64007. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64008. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64009. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64010. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64011. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64012. default: jassertfalse; break;
  64013. }
  64014. }
  64015. }
  64016. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  64017. {
  64018. DrawablePath::ValueTreeWrapper wrapper (state);
  64019. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  64020. ValueTree pathTree (wrapper.getPathState());
  64021. pathTree.removeAllChildren (undoManager);
  64022. for (int i = 0; i < elements.size(); ++i)
  64023. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  64024. }
  64025. void RelativePointPath::parse (const ValueTree& state)
  64026. {
  64027. DrawablePath::ValueTreeWrapper wrapper (state);
  64028. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  64029. RelativePoint points[3];
  64030. const ValueTree pathTree (wrapper.getPathState());
  64031. const int num = pathTree.getNumChildren();
  64032. for (int i = 0; i < num; ++i)
  64033. {
  64034. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  64035. const int numCps = e.getNumControlPoints();
  64036. for (int j = 0; j < numCps; ++j)
  64037. {
  64038. points[j] = e.getControlPoint (j);
  64039. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  64040. }
  64041. const Identifier type (e.getType());
  64042. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  64043. elements.add (new StartSubPath (points[0]));
  64044. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  64045. elements.add (new CloseSubPath());
  64046. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  64047. elements.add (new LineTo (points[0]));
  64048. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  64049. elements.add (new QuadraticTo (points[0], points[1]));
  64050. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  64051. elements.add (new CubicTo (points[0], points[1], points[2]));
  64052. else
  64053. jassertfalse;
  64054. }
  64055. }
  64056. RelativePointPath::~RelativePointPath()
  64057. {
  64058. }
  64059. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64060. {
  64061. elements.swapWithArray (other.elements);
  64062. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64063. }
  64064. void RelativePointPath::createPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder)
  64065. {
  64066. for (int i = 0; i < elements.size(); ++i)
  64067. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64068. }
  64069. bool RelativePointPath::containsAnyDynamicPoints() const
  64070. {
  64071. return containsDynamicPoints;
  64072. }
  64073. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64074. {
  64075. }
  64076. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64077. : ElementBase (startSubPathElement), startPos (pos)
  64078. {
  64079. }
  64080. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64081. {
  64082. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64083. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64084. return v;
  64085. }
  64086. void RelativePointPath::StartSubPath::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  64087. {
  64088. path.startNewSubPath (startPos.resolve (coordFinder));
  64089. }
  64090. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64091. {
  64092. numPoints = 1;
  64093. return &startPos;
  64094. }
  64095. RelativePointPath::CloseSubPath::CloseSubPath()
  64096. : ElementBase (closeSubPathElement)
  64097. {
  64098. }
  64099. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64100. {
  64101. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64102. }
  64103. void RelativePointPath::CloseSubPath::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder*) const
  64104. {
  64105. path.closeSubPath();
  64106. }
  64107. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64108. {
  64109. numPoints = 0;
  64110. return 0;
  64111. }
  64112. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64113. : ElementBase (lineToElement), endPoint (endPoint_)
  64114. {
  64115. }
  64116. const ValueTree RelativePointPath::LineTo::createTree() const
  64117. {
  64118. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64119. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64120. return v;
  64121. }
  64122. void RelativePointPath::LineTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  64123. {
  64124. path.lineTo (endPoint.resolve (coordFinder));
  64125. }
  64126. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64127. {
  64128. numPoints = 1;
  64129. return &endPoint;
  64130. }
  64131. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64132. : ElementBase (quadraticToElement)
  64133. {
  64134. controlPoints[0] = controlPoint;
  64135. controlPoints[1] = endPoint;
  64136. }
  64137. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64138. {
  64139. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64140. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64141. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64142. return v;
  64143. }
  64144. void RelativePointPath::QuadraticTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  64145. {
  64146. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  64147. controlPoints[1].resolve (coordFinder));
  64148. }
  64149. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64150. {
  64151. numPoints = 2;
  64152. return controlPoints;
  64153. }
  64154. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64155. : ElementBase (cubicToElement)
  64156. {
  64157. controlPoints[0] = controlPoint1;
  64158. controlPoints[1] = controlPoint2;
  64159. controlPoints[2] = endPoint;
  64160. }
  64161. const ValueTree RelativePointPath::CubicTo::createTree() const
  64162. {
  64163. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64164. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64165. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64166. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64167. return v;
  64168. }
  64169. void RelativePointPath::CubicTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  64170. {
  64171. path.cubicTo (controlPoints[0].resolve (coordFinder),
  64172. controlPoints[1].resolve (coordFinder),
  64173. controlPoints[2].resolve (coordFinder));
  64174. }
  64175. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64176. {
  64177. numPoints = 3;
  64178. return controlPoints;
  64179. }
  64180. RelativeParallelogram::RelativeParallelogram()
  64181. {
  64182. }
  64183. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64184. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64185. {
  64186. }
  64187. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64188. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64189. {
  64190. }
  64191. RelativeParallelogram::~RelativeParallelogram()
  64192. {
  64193. }
  64194. void RelativeParallelogram::resolveThreePoints (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  64195. {
  64196. points[0] = topLeft.resolve (coordFinder);
  64197. points[1] = topRight.resolve (coordFinder);
  64198. points[2] = bottomLeft.resolve (coordFinder);
  64199. }
  64200. void RelativeParallelogram::resolveFourCorners (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  64201. {
  64202. resolveThreePoints (points, coordFinder);
  64203. points[3] = points[1] + (points[2] - points[0]);
  64204. }
  64205. const Rectangle<float> RelativeParallelogram::getBounds (RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  64206. {
  64207. Point<float> points[4];
  64208. resolveFourCorners (points, coordFinder);
  64209. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64210. }
  64211. void RelativeParallelogram::getPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  64212. {
  64213. Point<float> points[4];
  64214. resolveFourCorners (points, coordFinder);
  64215. path.startNewSubPath (points[0]);
  64216. path.lineTo (points[1]);
  64217. path.lineTo (points[3]);
  64218. path.lineTo (points[2]);
  64219. path.closeSubPath();
  64220. }
  64221. const AffineTransform RelativeParallelogram::resetToPerpendicular (RelativeCoordinate::NamedCoordinateFinder* const coordFinder)
  64222. {
  64223. Point<float> corners[3];
  64224. resolveThreePoints (corners, coordFinder);
  64225. const Line<float> top (corners[0], corners[1]);
  64226. const Line<float> left (corners[0], corners[2]);
  64227. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64228. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64229. topRight.moveToAbsolute (newTopRight, coordFinder);
  64230. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  64231. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64232. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64233. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64234. }
  64235. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64236. {
  64237. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64238. }
  64239. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64240. {
  64241. return ! operator== (other);
  64242. }
  64243. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64244. {
  64245. const Point<float> tr (corners[1] - corners[0]);
  64246. const Point<float> bl (corners[2] - corners[0]);
  64247. target -= corners[0];
  64248. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64249. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64250. }
  64251. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64252. {
  64253. return corners[0]
  64254. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64255. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64256. }
  64257. END_JUCE_NAMESPACE
  64258. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  64259. #endif
  64260. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64261. /*** Start of inlined file: juce_Colour.cpp ***/
  64262. BEGIN_JUCE_NAMESPACE
  64263. namespace ColourHelpers
  64264. {
  64265. static uint8 floatAlphaToInt (const float alpha) throw()
  64266. {
  64267. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64268. }
  64269. static void convertHSBtoRGB (float h, float s, float v,
  64270. uint8& r, uint8& g, uint8& b) throw()
  64271. {
  64272. v = jlimit (0.0f, 1.0f, v);
  64273. v *= 255.0f;
  64274. const uint8 intV = (uint8) roundToInt (v);
  64275. if (s <= 0)
  64276. {
  64277. r = intV;
  64278. g = intV;
  64279. b = intV;
  64280. }
  64281. else
  64282. {
  64283. s = jmin (1.0f, s);
  64284. h = jlimit (0.0f, 1.0f, h);
  64285. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64286. const float f = h - std::floor (h);
  64287. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64288. const float y = v * (1.0f - s * f);
  64289. const float z = v * (1.0f - (s * (1.0f - f)));
  64290. if (h < 1.0f)
  64291. {
  64292. r = intV;
  64293. g = (uint8) roundToInt (z);
  64294. b = x;
  64295. }
  64296. else if (h < 2.0f)
  64297. {
  64298. r = (uint8) roundToInt (y);
  64299. g = intV;
  64300. b = x;
  64301. }
  64302. else if (h < 3.0f)
  64303. {
  64304. r = x;
  64305. g = intV;
  64306. b = (uint8) roundToInt (z);
  64307. }
  64308. else if (h < 4.0f)
  64309. {
  64310. r = x;
  64311. g = (uint8) roundToInt (y);
  64312. b = intV;
  64313. }
  64314. else if (h < 5.0f)
  64315. {
  64316. r = (uint8) roundToInt (z);
  64317. g = x;
  64318. b = intV;
  64319. }
  64320. else if (h < 6.0f)
  64321. {
  64322. r = intV;
  64323. g = x;
  64324. b = (uint8) roundToInt (y);
  64325. }
  64326. else
  64327. {
  64328. r = 0;
  64329. g = 0;
  64330. b = 0;
  64331. }
  64332. }
  64333. }
  64334. }
  64335. Colour::Colour() throw()
  64336. : argb (0)
  64337. {
  64338. }
  64339. Colour::Colour (const Colour& other) throw()
  64340. : argb (other.argb)
  64341. {
  64342. }
  64343. Colour& Colour::operator= (const Colour& other) throw()
  64344. {
  64345. argb = other.argb;
  64346. return *this;
  64347. }
  64348. bool Colour::operator== (const Colour& other) const throw()
  64349. {
  64350. return argb.getARGB() == other.argb.getARGB();
  64351. }
  64352. bool Colour::operator!= (const Colour& other) const throw()
  64353. {
  64354. return argb.getARGB() != other.argb.getARGB();
  64355. }
  64356. Colour::Colour (const uint32 argb_) throw()
  64357. : argb (argb_)
  64358. {
  64359. }
  64360. Colour::Colour (const uint8 red,
  64361. const uint8 green,
  64362. const uint8 blue) throw()
  64363. {
  64364. argb.setARGB (0xff, red, green, blue);
  64365. }
  64366. const Colour Colour::fromRGB (const uint8 red,
  64367. const uint8 green,
  64368. const uint8 blue) throw()
  64369. {
  64370. return Colour (red, green, blue);
  64371. }
  64372. Colour::Colour (const uint8 red,
  64373. const uint8 green,
  64374. const uint8 blue,
  64375. const uint8 alpha) throw()
  64376. {
  64377. argb.setARGB (alpha, red, green, blue);
  64378. }
  64379. const Colour Colour::fromRGBA (const uint8 red,
  64380. const uint8 green,
  64381. const uint8 blue,
  64382. const uint8 alpha) throw()
  64383. {
  64384. return Colour (red, green, blue, alpha);
  64385. }
  64386. Colour::Colour (const uint8 red,
  64387. const uint8 green,
  64388. const uint8 blue,
  64389. const float alpha) throw()
  64390. {
  64391. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  64392. }
  64393. const Colour Colour::fromRGBAFloat (const uint8 red,
  64394. const uint8 green,
  64395. const uint8 blue,
  64396. const float alpha) throw()
  64397. {
  64398. return Colour (red, green, blue, alpha);
  64399. }
  64400. Colour::Colour (const float hue,
  64401. const float saturation,
  64402. const float brightness,
  64403. const float alpha) throw()
  64404. {
  64405. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64406. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64407. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  64408. }
  64409. const Colour Colour::fromHSV (const float hue,
  64410. const float saturation,
  64411. const float brightness,
  64412. const float alpha) throw()
  64413. {
  64414. return Colour (hue, saturation, brightness, alpha);
  64415. }
  64416. Colour::Colour (const float hue,
  64417. const float saturation,
  64418. const float brightness,
  64419. const uint8 alpha) throw()
  64420. {
  64421. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64422. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64423. argb.setARGB (alpha, r, g, b);
  64424. }
  64425. Colour::~Colour() throw()
  64426. {
  64427. }
  64428. const PixelARGB Colour::getPixelARGB() const throw()
  64429. {
  64430. PixelARGB p (argb);
  64431. p.premultiply();
  64432. return p;
  64433. }
  64434. uint32 Colour::getARGB() const throw()
  64435. {
  64436. return argb.getARGB();
  64437. }
  64438. bool Colour::isTransparent() const throw()
  64439. {
  64440. return getAlpha() == 0;
  64441. }
  64442. bool Colour::isOpaque() const throw()
  64443. {
  64444. return getAlpha() == 0xff;
  64445. }
  64446. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  64447. {
  64448. PixelARGB newCol (argb);
  64449. newCol.setAlpha (newAlpha);
  64450. return Colour (newCol.getARGB());
  64451. }
  64452. const Colour Colour::withAlpha (const float newAlpha) const throw()
  64453. {
  64454. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  64455. PixelARGB newCol (argb);
  64456. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  64457. return Colour (newCol.getARGB());
  64458. }
  64459. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  64460. {
  64461. jassert (alphaMultiplier >= 0);
  64462. PixelARGB newCol (argb);
  64463. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  64464. return Colour (newCol.getARGB());
  64465. }
  64466. const Colour Colour::overlaidWith (const Colour& src) const throw()
  64467. {
  64468. const int destAlpha = getAlpha();
  64469. if (destAlpha > 0)
  64470. {
  64471. const int invA = 0xff - (int) src.getAlpha();
  64472. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  64473. if (resA > 0)
  64474. {
  64475. const int da = (invA * destAlpha) / resA;
  64476. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  64477. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  64478. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  64479. (uint8) resA);
  64480. }
  64481. return *this;
  64482. }
  64483. else
  64484. {
  64485. return src;
  64486. }
  64487. }
  64488. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  64489. {
  64490. if (proportionOfOther <= 0)
  64491. return *this;
  64492. if (proportionOfOther >= 1.0f)
  64493. return other;
  64494. PixelARGB c1 (getPixelARGB());
  64495. const PixelARGB c2 (other.getPixelARGB());
  64496. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  64497. c1.unpremultiply();
  64498. return Colour (c1.getARGB());
  64499. }
  64500. float Colour::getFloatRed() const throw()
  64501. {
  64502. return getRed() / 255.0f;
  64503. }
  64504. float Colour::getFloatGreen() const throw()
  64505. {
  64506. return getGreen() / 255.0f;
  64507. }
  64508. float Colour::getFloatBlue() const throw()
  64509. {
  64510. return getBlue() / 255.0f;
  64511. }
  64512. float Colour::getFloatAlpha() const throw()
  64513. {
  64514. return getAlpha() / 255.0f;
  64515. }
  64516. void Colour::getHSB (float& h, float& s, float& v) const throw()
  64517. {
  64518. const int r = getRed();
  64519. const int g = getGreen();
  64520. const int b = getBlue();
  64521. const int hi = jmax (r, g, b);
  64522. const int lo = jmin (r, g, b);
  64523. if (hi != 0)
  64524. {
  64525. s = (hi - lo) / (float) hi;
  64526. if (s != 0)
  64527. {
  64528. const float invDiff = 1.0f / (hi - lo);
  64529. const float red = (hi - r) * invDiff;
  64530. const float green = (hi - g) * invDiff;
  64531. const float blue = (hi - b) * invDiff;
  64532. if (r == hi)
  64533. h = blue - green;
  64534. else if (g == hi)
  64535. h = 2.0f + red - blue;
  64536. else
  64537. h = 4.0f + green - red;
  64538. h *= 1.0f / 6.0f;
  64539. if (h < 0)
  64540. ++h;
  64541. }
  64542. else
  64543. {
  64544. h = 0;
  64545. }
  64546. }
  64547. else
  64548. {
  64549. s = 0;
  64550. h = 0;
  64551. }
  64552. v = hi / 255.0f;
  64553. }
  64554. float Colour::getHue() const throw()
  64555. {
  64556. float h, s, b;
  64557. getHSB (h, s, b);
  64558. return h;
  64559. }
  64560. const Colour Colour::withHue (const float hue) const throw()
  64561. {
  64562. float h, s, b;
  64563. getHSB (h, s, b);
  64564. return Colour (hue, s, b, getAlpha());
  64565. }
  64566. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  64567. {
  64568. float h, s, b;
  64569. getHSB (h, s, b);
  64570. h += amountToRotate;
  64571. h -= std::floor (h);
  64572. return Colour (h, s, b, getAlpha());
  64573. }
  64574. float Colour::getSaturation() const throw()
  64575. {
  64576. float h, s, b;
  64577. getHSB (h, s, b);
  64578. return s;
  64579. }
  64580. const Colour Colour::withSaturation (const float saturation) const throw()
  64581. {
  64582. float h, s, b;
  64583. getHSB (h, s, b);
  64584. return Colour (h, saturation, b, getAlpha());
  64585. }
  64586. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  64587. {
  64588. float h, s, b;
  64589. getHSB (h, s, b);
  64590. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  64591. }
  64592. float Colour::getBrightness() const throw()
  64593. {
  64594. float h, s, b;
  64595. getHSB (h, s, b);
  64596. return b;
  64597. }
  64598. const Colour Colour::withBrightness (const float brightness) const throw()
  64599. {
  64600. float h, s, b;
  64601. getHSB (h, s, b);
  64602. return Colour (h, s, brightness, getAlpha());
  64603. }
  64604. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  64605. {
  64606. float h, s, b;
  64607. getHSB (h, s, b);
  64608. b *= amount;
  64609. if (b > 1.0f)
  64610. b = 1.0f;
  64611. return Colour (h, s, b, getAlpha());
  64612. }
  64613. const Colour Colour::brighter (float amount) const throw()
  64614. {
  64615. amount = 1.0f / (1.0f + amount);
  64616. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  64617. (uint8) (255 - (amount * (255 - getGreen()))),
  64618. (uint8) (255 - (amount * (255 - getBlue()))),
  64619. getAlpha());
  64620. }
  64621. const Colour Colour::darker (float amount) const throw()
  64622. {
  64623. amount = 1.0f / (1.0f + amount);
  64624. return Colour ((uint8) (amount * getRed()),
  64625. (uint8) (amount * getGreen()),
  64626. (uint8) (amount * getBlue()),
  64627. getAlpha());
  64628. }
  64629. const Colour Colour::greyLevel (const float brightness) throw()
  64630. {
  64631. const uint8 level
  64632. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  64633. return Colour (level, level, level);
  64634. }
  64635. const Colour Colour::contrasting (const float amount) const throw()
  64636. {
  64637. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  64638. ? Colours::black
  64639. : Colours::white).withAlpha (amount));
  64640. }
  64641. const Colour Colour::contrasting (const Colour& colour1,
  64642. const Colour& colour2) throw()
  64643. {
  64644. const float b1 = colour1.getBrightness();
  64645. const float b2 = colour2.getBrightness();
  64646. float best = 0.0f;
  64647. float bestDist = 0.0f;
  64648. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  64649. {
  64650. const float d1 = std::abs (i - b1);
  64651. const float d2 = std::abs (i - b2);
  64652. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  64653. if (dist > bestDist)
  64654. {
  64655. best = i;
  64656. bestDist = dist;
  64657. }
  64658. }
  64659. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  64660. .withBrightness (best);
  64661. }
  64662. const String Colour::toString() const
  64663. {
  64664. return String::toHexString ((int) argb.getARGB());
  64665. }
  64666. const Colour Colour::fromString (const String& encodedColourString)
  64667. {
  64668. return Colour ((uint32) encodedColourString.getHexValue32());
  64669. }
  64670. const String Colour::toDisplayString (const bool includeAlphaValue) const
  64671. {
  64672. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  64673. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  64674. .toUpperCase();
  64675. }
  64676. END_JUCE_NAMESPACE
  64677. /*** End of inlined file: juce_Colour.cpp ***/
  64678. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  64679. BEGIN_JUCE_NAMESPACE
  64680. ColourGradient::ColourGradient() throw()
  64681. {
  64682. #if JUCE_DEBUG
  64683. point1.setX (987654.0f);
  64684. #endif
  64685. }
  64686. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  64687. const Colour& colour2, const float x2_, const float y2_,
  64688. const bool isRadial_)
  64689. : point1 (x1_, y1_),
  64690. point2 (x2_, y2_),
  64691. isRadial (isRadial_)
  64692. {
  64693. colours.add (ColourPoint (0.0, colour1));
  64694. colours.add (ColourPoint (1.0, colour2));
  64695. }
  64696. ColourGradient::~ColourGradient()
  64697. {
  64698. }
  64699. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  64700. {
  64701. return point1 == other.point1 && point2 == other.point2
  64702. && isRadial == other.isRadial
  64703. && colours == other.colours;
  64704. }
  64705. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  64706. {
  64707. return ! operator== (other);
  64708. }
  64709. void ColourGradient::clearColours()
  64710. {
  64711. colours.clear();
  64712. }
  64713. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  64714. {
  64715. // must be within the two end-points
  64716. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  64717. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  64718. int i;
  64719. for (i = 0; i < colours.size(); ++i)
  64720. if (colours.getReference(i).position > pos)
  64721. break;
  64722. colours.insert (i, ColourPoint (pos, colour));
  64723. return i;
  64724. }
  64725. void ColourGradient::removeColour (int index)
  64726. {
  64727. jassert (index > 0 && index < colours.size() - 1);
  64728. colours.remove (index);
  64729. }
  64730. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  64731. {
  64732. for (int i = 0; i < colours.size(); ++i)
  64733. {
  64734. Colour& c = colours.getReference(i).colour;
  64735. c = c.withMultipliedAlpha (multiplier);
  64736. }
  64737. }
  64738. int ColourGradient::getNumColours() const throw()
  64739. {
  64740. return colours.size();
  64741. }
  64742. double ColourGradient::getColourPosition (const int index) const throw()
  64743. {
  64744. if (((unsigned int) index) < (unsigned int) colours.size())
  64745. return colours.getReference (index).position;
  64746. return 0;
  64747. }
  64748. const Colour ColourGradient::getColour (const int index) const throw()
  64749. {
  64750. if (((unsigned int) index) < (unsigned int) colours.size())
  64751. return colours.getReference (index).colour;
  64752. return Colour();
  64753. }
  64754. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  64755. {
  64756. if (((unsigned int) index) < (unsigned int) colours.size())
  64757. colours.getReference (index).colour = newColour;
  64758. }
  64759. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  64760. {
  64761. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  64762. if (position <= 0 || colours.size() <= 1)
  64763. return colours.getReference(0).colour;
  64764. int i = colours.size() - 1;
  64765. while (position < colours.getReference(i).position)
  64766. --i;
  64767. const ColourPoint& p1 = colours.getReference (i);
  64768. if (i >= colours.size() - 1)
  64769. return p1.colour;
  64770. const ColourPoint& p2 = colours.getReference (i + 1);
  64771. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  64772. }
  64773. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  64774. {
  64775. #if JUCE_DEBUG
  64776. // trying to use the object without setting its co-ordinates? Have a careful read of
  64777. // the comments for the constructors.
  64778. jassert (point1.getX() != 987654.0f);
  64779. #endif
  64780. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  64781. 3 * (int) point1.transformedBy (transform)
  64782. .getDistanceFrom (point2.transformedBy (transform)));
  64783. lookupTable.malloc (numEntries);
  64784. if (colours.size() >= 2)
  64785. {
  64786. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  64787. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  64788. int index = 0;
  64789. for (int j = 1; j < colours.size(); ++j)
  64790. {
  64791. const ColourPoint& p = colours.getReference (j);
  64792. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  64793. const PixelARGB pix2 (p.colour.getPixelARGB());
  64794. for (int i = 0; i < numToDo; ++i)
  64795. {
  64796. jassert (index >= 0 && index < numEntries);
  64797. lookupTable[index] = pix1;
  64798. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  64799. ++index;
  64800. }
  64801. pix1 = pix2;
  64802. }
  64803. while (index < numEntries)
  64804. lookupTable [index++] = pix1;
  64805. }
  64806. else
  64807. {
  64808. jassertfalse; // no colours specified!
  64809. }
  64810. return numEntries;
  64811. }
  64812. bool ColourGradient::isOpaque() const throw()
  64813. {
  64814. for (int i = 0; i < colours.size(); ++i)
  64815. if (! colours.getReference(i).colour.isOpaque())
  64816. return false;
  64817. return true;
  64818. }
  64819. bool ColourGradient::isInvisible() const throw()
  64820. {
  64821. for (int i = 0; i < colours.size(); ++i)
  64822. if (! colours.getReference(i).colour.isTransparent())
  64823. return false;
  64824. return true;
  64825. }
  64826. END_JUCE_NAMESPACE
  64827. /*** End of inlined file: juce_ColourGradient.cpp ***/
  64828. /*** Start of inlined file: juce_Colours.cpp ***/
  64829. BEGIN_JUCE_NAMESPACE
  64830. const Colour Colours::transparentBlack (0);
  64831. const Colour Colours::transparentWhite (0x00ffffff);
  64832. const Colour Colours::aliceblue (0xfff0f8ff);
  64833. const Colour Colours::antiquewhite (0xfffaebd7);
  64834. const Colour Colours::aqua (0xff00ffff);
  64835. const Colour Colours::aquamarine (0xff7fffd4);
  64836. const Colour Colours::azure (0xfff0ffff);
  64837. const Colour Colours::beige (0xfff5f5dc);
  64838. const Colour Colours::bisque (0xffffe4c4);
  64839. const Colour Colours::black (0xff000000);
  64840. const Colour Colours::blanchedalmond (0xffffebcd);
  64841. const Colour Colours::blue (0xff0000ff);
  64842. const Colour Colours::blueviolet (0xff8a2be2);
  64843. const Colour Colours::brown (0xffa52a2a);
  64844. const Colour Colours::burlywood (0xffdeb887);
  64845. const Colour Colours::cadetblue (0xff5f9ea0);
  64846. const Colour Colours::chartreuse (0xff7fff00);
  64847. const Colour Colours::chocolate (0xffd2691e);
  64848. const Colour Colours::coral (0xffff7f50);
  64849. const Colour Colours::cornflowerblue (0xff6495ed);
  64850. const Colour Colours::cornsilk (0xfffff8dc);
  64851. const Colour Colours::crimson (0xffdc143c);
  64852. const Colour Colours::cyan (0xff00ffff);
  64853. const Colour Colours::darkblue (0xff00008b);
  64854. const Colour Colours::darkcyan (0xff008b8b);
  64855. const Colour Colours::darkgoldenrod (0xffb8860b);
  64856. const Colour Colours::darkgrey (0xff555555);
  64857. const Colour Colours::darkgreen (0xff006400);
  64858. const Colour Colours::darkkhaki (0xffbdb76b);
  64859. const Colour Colours::darkmagenta (0xff8b008b);
  64860. const Colour Colours::darkolivegreen (0xff556b2f);
  64861. const Colour Colours::darkorange (0xffff8c00);
  64862. const Colour Colours::darkorchid (0xff9932cc);
  64863. const Colour Colours::darkred (0xff8b0000);
  64864. const Colour Colours::darksalmon (0xffe9967a);
  64865. const Colour Colours::darkseagreen (0xff8fbc8f);
  64866. const Colour Colours::darkslateblue (0xff483d8b);
  64867. const Colour Colours::darkslategrey (0xff2f4f4f);
  64868. const Colour Colours::darkturquoise (0xff00ced1);
  64869. const Colour Colours::darkviolet (0xff9400d3);
  64870. const Colour Colours::deeppink (0xffff1493);
  64871. const Colour Colours::deepskyblue (0xff00bfff);
  64872. const Colour Colours::dimgrey (0xff696969);
  64873. const Colour Colours::dodgerblue (0xff1e90ff);
  64874. const Colour Colours::firebrick (0xffb22222);
  64875. const Colour Colours::floralwhite (0xfffffaf0);
  64876. const Colour Colours::forestgreen (0xff228b22);
  64877. const Colour Colours::fuchsia (0xffff00ff);
  64878. const Colour Colours::gainsboro (0xffdcdcdc);
  64879. const Colour Colours::gold (0xffffd700);
  64880. const Colour Colours::goldenrod (0xffdaa520);
  64881. const Colour Colours::grey (0xff808080);
  64882. const Colour Colours::green (0xff008000);
  64883. const Colour Colours::greenyellow (0xffadff2f);
  64884. const Colour Colours::honeydew (0xfff0fff0);
  64885. const Colour Colours::hotpink (0xffff69b4);
  64886. const Colour Colours::indianred (0xffcd5c5c);
  64887. const Colour Colours::indigo (0xff4b0082);
  64888. const Colour Colours::ivory (0xfffffff0);
  64889. const Colour Colours::khaki (0xfff0e68c);
  64890. const Colour Colours::lavender (0xffe6e6fa);
  64891. const Colour Colours::lavenderblush (0xfffff0f5);
  64892. const Colour Colours::lemonchiffon (0xfffffacd);
  64893. const Colour Colours::lightblue (0xffadd8e6);
  64894. const Colour Colours::lightcoral (0xfff08080);
  64895. const Colour Colours::lightcyan (0xffe0ffff);
  64896. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  64897. const Colour Colours::lightgreen (0xff90ee90);
  64898. const Colour Colours::lightgrey (0xffd3d3d3);
  64899. const Colour Colours::lightpink (0xffffb6c1);
  64900. const Colour Colours::lightsalmon (0xffffa07a);
  64901. const Colour Colours::lightseagreen (0xff20b2aa);
  64902. const Colour Colours::lightskyblue (0xff87cefa);
  64903. const Colour Colours::lightslategrey (0xff778899);
  64904. const Colour Colours::lightsteelblue (0xffb0c4de);
  64905. const Colour Colours::lightyellow (0xffffffe0);
  64906. const Colour Colours::lime (0xff00ff00);
  64907. const Colour Colours::limegreen (0xff32cd32);
  64908. const Colour Colours::linen (0xfffaf0e6);
  64909. const Colour Colours::magenta (0xffff00ff);
  64910. const Colour Colours::maroon (0xff800000);
  64911. const Colour Colours::mediumaquamarine (0xff66cdaa);
  64912. const Colour Colours::mediumblue (0xff0000cd);
  64913. const Colour Colours::mediumorchid (0xffba55d3);
  64914. const Colour Colours::mediumpurple (0xff9370db);
  64915. const Colour Colours::mediumseagreen (0xff3cb371);
  64916. const Colour Colours::mediumslateblue (0xff7b68ee);
  64917. const Colour Colours::mediumspringgreen (0xff00fa9a);
  64918. const Colour Colours::mediumturquoise (0xff48d1cc);
  64919. const Colour Colours::mediumvioletred (0xffc71585);
  64920. const Colour Colours::midnightblue (0xff191970);
  64921. const Colour Colours::mintcream (0xfff5fffa);
  64922. const Colour Colours::mistyrose (0xffffe4e1);
  64923. const Colour Colours::navajowhite (0xffffdead);
  64924. const Colour Colours::navy (0xff000080);
  64925. const Colour Colours::oldlace (0xfffdf5e6);
  64926. const Colour Colours::olive (0xff808000);
  64927. const Colour Colours::olivedrab (0xff6b8e23);
  64928. const Colour Colours::orange (0xffffa500);
  64929. const Colour Colours::orangered (0xffff4500);
  64930. const Colour Colours::orchid (0xffda70d6);
  64931. const Colour Colours::palegoldenrod (0xffeee8aa);
  64932. const Colour Colours::palegreen (0xff98fb98);
  64933. const Colour Colours::paleturquoise (0xffafeeee);
  64934. const Colour Colours::palevioletred (0xffdb7093);
  64935. const Colour Colours::papayawhip (0xffffefd5);
  64936. const Colour Colours::peachpuff (0xffffdab9);
  64937. const Colour Colours::peru (0xffcd853f);
  64938. const Colour Colours::pink (0xffffc0cb);
  64939. const Colour Colours::plum (0xffdda0dd);
  64940. const Colour Colours::powderblue (0xffb0e0e6);
  64941. const Colour Colours::purple (0xff800080);
  64942. const Colour Colours::red (0xffff0000);
  64943. const Colour Colours::rosybrown (0xffbc8f8f);
  64944. const Colour Colours::royalblue (0xff4169e1);
  64945. const Colour Colours::saddlebrown (0xff8b4513);
  64946. const Colour Colours::salmon (0xfffa8072);
  64947. const Colour Colours::sandybrown (0xfff4a460);
  64948. const Colour Colours::seagreen (0xff2e8b57);
  64949. const Colour Colours::seashell (0xfffff5ee);
  64950. const Colour Colours::sienna (0xffa0522d);
  64951. const Colour Colours::silver (0xffc0c0c0);
  64952. const Colour Colours::skyblue (0xff87ceeb);
  64953. const Colour Colours::slateblue (0xff6a5acd);
  64954. const Colour Colours::slategrey (0xff708090);
  64955. const Colour Colours::snow (0xfffffafa);
  64956. const Colour Colours::springgreen (0xff00ff7f);
  64957. const Colour Colours::steelblue (0xff4682b4);
  64958. const Colour Colours::tan (0xffd2b48c);
  64959. const Colour Colours::teal (0xff008080);
  64960. const Colour Colours::thistle (0xffd8bfd8);
  64961. const Colour Colours::tomato (0xffff6347);
  64962. const Colour Colours::turquoise (0xff40e0d0);
  64963. const Colour Colours::violet (0xffee82ee);
  64964. const Colour Colours::wheat (0xfff5deb3);
  64965. const Colour Colours::white (0xffffffff);
  64966. const Colour Colours::whitesmoke (0xfff5f5f5);
  64967. const Colour Colours::yellow (0xffffff00);
  64968. const Colour Colours::yellowgreen (0xff9acd32);
  64969. const Colour Colours::findColourForName (const String& colourName,
  64970. const Colour& defaultColour)
  64971. {
  64972. static const int presets[] =
  64973. {
  64974. // (first value is the string's hashcode, second is ARGB)
  64975. 0x05978fff, 0xff000000, /* black */
  64976. 0x06bdcc29, 0xffffffff, /* white */
  64977. 0x002e305a, 0xff0000ff, /* blue */
  64978. 0x00308adf, 0xff808080, /* grey */
  64979. 0x05e0cf03, 0xff008000, /* green */
  64980. 0x0001b891, 0xffff0000, /* red */
  64981. 0xd43c6474, 0xffffff00, /* yellow */
  64982. 0x620886da, 0xfff0f8ff, /* aliceblue */
  64983. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  64984. 0x002dcebc, 0xff00ffff, /* aqua */
  64985. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  64986. 0x0590228f, 0xfff0ffff, /* azure */
  64987. 0x05947fe4, 0xfff5f5dc, /* beige */
  64988. 0xad388e35, 0xffffe4c4, /* bisque */
  64989. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  64990. 0x39129959, 0xff8a2be2, /* blueviolet */
  64991. 0x059a8136, 0xffa52a2a, /* brown */
  64992. 0x89cea8f9, 0xffdeb887, /* burlywood */
  64993. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  64994. 0x6b748956, 0xff7fff00, /* chartreuse */
  64995. 0x2903623c, 0xffd2691e, /* chocolate */
  64996. 0x05a74431, 0xffff7f50, /* coral */
  64997. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  64998. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  64999. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65000. 0x002ed323, 0xff00ffff, /* cyan */
  65001. 0x67cc74d0, 0xff00008b, /* darkblue */
  65002. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65003. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65004. 0x67cecf55, 0xff555555, /* darkgrey */
  65005. 0x920b194d, 0xff006400, /* darkgreen */
  65006. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65007. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65008. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65009. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65010. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65011. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65012. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65013. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65014. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65015. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65016. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65017. 0xc8769375, 0xff9400d3, /* darkviolet */
  65018. 0x25832862, 0xffff1493, /* deeppink */
  65019. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65020. 0x634c8b67, 0xff696969, /* dimgrey */
  65021. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65022. 0xef19e3cb, 0xffb22222, /* firebrick */
  65023. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65024. 0xd086fd06, 0xff228b22, /* forestgreen */
  65025. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65026. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65027. 0x00308060, 0xffffd700, /* gold */
  65028. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65029. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65030. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65031. 0x41892743, 0xffff69b4, /* hotpink */
  65032. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65033. 0xb969fed2, 0xff4b0082, /* indigo */
  65034. 0x05fef6a9, 0xfffffff0, /* ivory */
  65035. 0x06149302, 0xfff0e68c, /* khaki */
  65036. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65037. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65038. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65039. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65040. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65041. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65042. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65043. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65044. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65045. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65046. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65047. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65048. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65049. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65050. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65051. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65052. 0x0032afd5, 0xff00ff00, /* lime */
  65053. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65054. 0x06234efa, 0xfffaf0e6, /* linen */
  65055. 0x316858a9, 0xffff00ff, /* magenta */
  65056. 0xbf8ca470, 0xff800000, /* maroon */
  65057. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65058. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65059. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65060. 0x07556b71, 0xff9370db, /* mediumpurple */
  65061. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65062. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65063. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65064. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65065. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65066. 0x168eb32a, 0xff191970, /* midnightblue */
  65067. 0x4306b960, 0xfff5fffa, /* mintcream */
  65068. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65069. 0xe97218a6, 0xffffdead, /* navajowhite */
  65070. 0x00337bb6, 0xff000080, /* navy */
  65071. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65072. 0x064ee1db, 0xff808000, /* olive */
  65073. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65074. 0xc3de262e, 0xffffa500, /* orange */
  65075. 0x58bebba3, 0xffff4500, /* orangered */
  65076. 0xc3def8a3, 0xffda70d6, /* orchid */
  65077. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65078. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65079. 0x74022737, 0xffafeeee, /* paleturquoise */
  65080. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65081. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65082. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65083. 0x003472f8, 0xffcd853f, /* peru */
  65084. 0x00348176, 0xffffc0cb, /* pink */
  65085. 0x00348d94, 0xffdda0dd, /* plum */
  65086. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65087. 0xc5c507bc, 0xff800080, /* purple */
  65088. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65089. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65090. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65091. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65092. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65093. 0x34636c14, 0xff2e8b57, /* seagreen */
  65094. 0x3507fb41, 0xfffff5ee, /* seashell */
  65095. 0xca348772, 0xffa0522d, /* sienna */
  65096. 0xca37d30d, 0xffc0c0c0, /* silver */
  65097. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65098. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65099. 0x44ab37f8, 0xff708090, /* slategrey */
  65100. 0x0035f183, 0xfffffafa, /* snow */
  65101. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65102. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65103. 0x0001bfa1, 0xffd2b48c, /* tan */
  65104. 0x0036425c, 0xff008080, /* teal */
  65105. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65106. 0xcc41600a, 0xffff6347, /* tomato */
  65107. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65108. 0xcf57947f, 0xffee82ee, /* violet */
  65109. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65110. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65111. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65112. };
  65113. const int hash = colourName.trim().toLowerCase().hashCode();
  65114. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65115. if (presets [i] == hash)
  65116. return Colour (presets [i + 1]);
  65117. return defaultColour;
  65118. }
  65119. END_JUCE_NAMESPACE
  65120. /*** End of inlined file: juce_Colours.cpp ***/
  65121. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65122. BEGIN_JUCE_NAMESPACE
  65123. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65124. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65125. const Path& path, const AffineTransform& transform)
  65126. : bounds (bounds_),
  65127. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65128. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65129. needToCheckEmptinesss (true)
  65130. {
  65131. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65132. int* t = table;
  65133. for (int i = bounds.getHeight(); --i >= 0;)
  65134. {
  65135. *t = 0;
  65136. t += lineStrideElements;
  65137. }
  65138. const int topLimit = bounds.getY() << 8;
  65139. const int heightLimit = bounds.getHeight() << 8;
  65140. const int leftLimit = bounds.getX() << 8;
  65141. const int rightLimit = bounds.getRight() << 8;
  65142. PathFlatteningIterator iter (path, transform);
  65143. while (iter.next())
  65144. {
  65145. int y1 = roundToInt (iter.y1 * 256.0f);
  65146. int y2 = roundToInt (iter.y2 * 256.0f);
  65147. if (y1 != y2)
  65148. {
  65149. y1 -= topLimit;
  65150. y2 -= topLimit;
  65151. const int startY = y1;
  65152. int direction = -1;
  65153. if (y1 > y2)
  65154. {
  65155. swapVariables (y1, y2);
  65156. direction = 1;
  65157. }
  65158. if (y1 < 0)
  65159. y1 = 0;
  65160. if (y2 > heightLimit)
  65161. y2 = heightLimit;
  65162. if (y1 < y2)
  65163. {
  65164. const double startX = 256.0f * iter.x1;
  65165. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65166. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65167. do
  65168. {
  65169. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65170. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65171. if (x < leftLimit)
  65172. x = leftLimit;
  65173. else if (x >= rightLimit)
  65174. x = rightLimit - 1;
  65175. addEdgePoint (x, y1 >> 8, direction * step);
  65176. y1 += step;
  65177. }
  65178. while (y1 < y2);
  65179. }
  65180. }
  65181. }
  65182. sanitiseLevels (path.isUsingNonZeroWinding());
  65183. }
  65184. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65185. : bounds (rectangleToAdd),
  65186. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65187. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65188. needToCheckEmptinesss (true)
  65189. {
  65190. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65191. table[0] = 0;
  65192. const int x1 = rectangleToAdd.getX() << 8;
  65193. const int x2 = rectangleToAdd.getRight() << 8;
  65194. int* t = table;
  65195. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65196. {
  65197. t[0] = 2;
  65198. t[1] = x1;
  65199. t[2] = 255;
  65200. t[3] = x2;
  65201. t[4] = 0;
  65202. t += lineStrideElements;
  65203. }
  65204. }
  65205. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65206. : bounds (rectanglesToAdd.getBounds()),
  65207. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65208. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65209. needToCheckEmptinesss (true)
  65210. {
  65211. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65212. int* t = table;
  65213. for (int i = bounds.getHeight(); --i >= 0;)
  65214. {
  65215. *t = 0;
  65216. t += lineStrideElements;
  65217. }
  65218. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65219. {
  65220. const Rectangle<int>* const r = iter.getRectangle();
  65221. const int x1 = r->getX() << 8;
  65222. const int x2 = r->getRight() << 8;
  65223. int y = r->getY() - bounds.getY();
  65224. for (int j = r->getHeight(); --j >= 0;)
  65225. {
  65226. addEdgePoint (x1, y, 255);
  65227. addEdgePoint (x2, y, -255);
  65228. ++y;
  65229. }
  65230. }
  65231. sanitiseLevels (true);
  65232. }
  65233. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65234. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65235. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65236. 2 + (int) rectangleToAdd.getWidth(),
  65237. 2 + (int) rectangleToAdd.getHeight())),
  65238. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65239. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65240. needToCheckEmptinesss (true)
  65241. {
  65242. jassert (! rectangleToAdd.isEmpty());
  65243. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65244. table[0] = 0;
  65245. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65246. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65247. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65248. jassert (y1 < 256);
  65249. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65250. if (x2 <= x1 || y2 <= y1)
  65251. {
  65252. bounds.setHeight (0);
  65253. return;
  65254. }
  65255. int lineY = 0;
  65256. int* t = table;
  65257. if ((y1 >> 8) == (y2 >> 8))
  65258. {
  65259. t[0] = 2;
  65260. t[1] = x1;
  65261. t[2] = y2 - y1;
  65262. t[3] = x2;
  65263. t[4] = 0;
  65264. ++lineY;
  65265. t += lineStrideElements;
  65266. }
  65267. else
  65268. {
  65269. t[0] = 2;
  65270. t[1] = x1;
  65271. t[2] = 255 - (y1 & 255);
  65272. t[3] = x2;
  65273. t[4] = 0;
  65274. ++lineY;
  65275. t += lineStrideElements;
  65276. while (lineY < (y2 >> 8))
  65277. {
  65278. t[0] = 2;
  65279. t[1] = x1;
  65280. t[2] = 255;
  65281. t[3] = x2;
  65282. t[4] = 0;
  65283. ++lineY;
  65284. t += lineStrideElements;
  65285. }
  65286. jassert (lineY < bounds.getHeight());
  65287. t[0] = 2;
  65288. t[1] = x1;
  65289. t[2] = y2 & 255;
  65290. t[3] = x2;
  65291. t[4] = 0;
  65292. ++lineY;
  65293. t += lineStrideElements;
  65294. }
  65295. while (lineY < bounds.getHeight())
  65296. {
  65297. t[0] = 0;
  65298. t += lineStrideElements;
  65299. ++lineY;
  65300. }
  65301. }
  65302. EdgeTable::EdgeTable (const EdgeTable& other)
  65303. {
  65304. operator= (other);
  65305. }
  65306. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65307. {
  65308. bounds = other.bounds;
  65309. maxEdgesPerLine = other.maxEdgesPerLine;
  65310. lineStrideElements = other.lineStrideElements;
  65311. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65312. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65313. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65314. return *this;
  65315. }
  65316. EdgeTable::~EdgeTable()
  65317. {
  65318. }
  65319. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65320. {
  65321. while (--numLines >= 0)
  65322. {
  65323. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  65324. src += srcLineStride;
  65325. dest += destLineStride;
  65326. }
  65327. }
  65328. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  65329. {
  65330. // Convert the table from relative windings to absolute levels..
  65331. int* lineStart = table;
  65332. for (int i = bounds.getHeight(); --i >= 0;)
  65333. {
  65334. int* line = lineStart;
  65335. lineStart += lineStrideElements;
  65336. int num = *line;
  65337. if (num == 0)
  65338. continue;
  65339. int level = 0;
  65340. if (useNonZeroWinding)
  65341. {
  65342. while (--num > 0)
  65343. {
  65344. line += 2;
  65345. level += *line;
  65346. int corrected = abs (level);
  65347. if (corrected >> 8)
  65348. corrected = 255;
  65349. *line = corrected;
  65350. }
  65351. }
  65352. else
  65353. {
  65354. while (--num > 0)
  65355. {
  65356. line += 2;
  65357. level += *line;
  65358. int corrected = abs (level);
  65359. if (corrected >> 8)
  65360. {
  65361. corrected &= 511;
  65362. if (corrected >> 8)
  65363. corrected = 511 - corrected;
  65364. }
  65365. *line = corrected;
  65366. }
  65367. }
  65368. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  65369. }
  65370. }
  65371. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  65372. {
  65373. if (newNumEdgesPerLine != maxEdgesPerLine)
  65374. {
  65375. maxEdgesPerLine = newNumEdgesPerLine;
  65376. jassert (bounds.getHeight() > 0);
  65377. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  65378. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  65379. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  65380. table.swapWith (newTable);
  65381. lineStrideElements = newLineStrideElements;
  65382. }
  65383. }
  65384. void EdgeTable::optimiseTable() throw()
  65385. {
  65386. int maxLineElements = 0;
  65387. for (int i = bounds.getHeight(); --i >= 0;)
  65388. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  65389. remapTableForNumEdges (maxLineElements);
  65390. }
  65391. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  65392. {
  65393. jassert (y >= 0 && y < bounds.getHeight());
  65394. int* line = table + lineStrideElements * y;
  65395. const int numPoints = line[0];
  65396. int n = numPoints << 1;
  65397. if (n > 0)
  65398. {
  65399. while (n > 0)
  65400. {
  65401. const int cx = line [n - 1];
  65402. if (cx <= x)
  65403. {
  65404. if (cx == x)
  65405. {
  65406. line [n] += winding;
  65407. return;
  65408. }
  65409. break;
  65410. }
  65411. n -= 2;
  65412. }
  65413. if (numPoints >= maxEdgesPerLine)
  65414. {
  65415. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65416. jassert (numPoints < maxEdgesPerLine);
  65417. line = table + lineStrideElements * y;
  65418. }
  65419. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  65420. }
  65421. line [n + 1] = x;
  65422. line [n + 2] = winding;
  65423. line[0]++;
  65424. }
  65425. void EdgeTable::translate (float dx, const int dy) throw()
  65426. {
  65427. bounds.translate ((int) std::floor (dx), dy);
  65428. int* lineStart = table;
  65429. const int intDx = (int) (dx * 256.0f);
  65430. for (int i = bounds.getHeight(); --i >= 0;)
  65431. {
  65432. int* line = lineStart;
  65433. lineStart += lineStrideElements;
  65434. int num = *line++;
  65435. while (--num >= 0)
  65436. {
  65437. *line += intDx;
  65438. line += 2;
  65439. }
  65440. }
  65441. }
  65442. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  65443. {
  65444. jassert (y >= 0 && y < bounds.getHeight());
  65445. int* dest = table + lineStrideElements * y;
  65446. if (dest[0] == 0)
  65447. return;
  65448. int otherNumPoints = *otherLine;
  65449. if (otherNumPoints == 0)
  65450. {
  65451. *dest = 0;
  65452. return;
  65453. }
  65454. const int right = bounds.getRight() << 8;
  65455. // optimise for the common case where our line lies entirely within a
  65456. // single pair of points, as happens when clipping to a simple rect.
  65457. if (otherNumPoints == 2 && otherLine[2] >= 255)
  65458. {
  65459. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  65460. return;
  65461. }
  65462. ++otherLine;
  65463. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  65464. int* temp = (int*) alloca (lineSizeBytes);
  65465. memcpy (temp, dest, lineSizeBytes);
  65466. const int* src1 = temp;
  65467. int srcNum1 = *src1++;
  65468. int x1 = *src1++;
  65469. const int* src2 = otherLine;
  65470. int srcNum2 = otherNumPoints;
  65471. int x2 = *src2++;
  65472. int destIndex = 0, destTotal = 0;
  65473. int level1 = 0, level2 = 0;
  65474. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  65475. while (srcNum1 > 0 && srcNum2 > 0)
  65476. {
  65477. int nextX;
  65478. if (x1 < x2)
  65479. {
  65480. nextX = x1;
  65481. level1 = *src1++;
  65482. x1 = *src1++;
  65483. --srcNum1;
  65484. }
  65485. else if (x1 == x2)
  65486. {
  65487. nextX = x1;
  65488. level1 = *src1++;
  65489. level2 = *src2++;
  65490. x1 = *src1++;
  65491. x2 = *src2++;
  65492. --srcNum1;
  65493. --srcNum2;
  65494. }
  65495. else
  65496. {
  65497. nextX = x2;
  65498. level2 = *src2++;
  65499. x2 = *src2++;
  65500. --srcNum2;
  65501. }
  65502. if (nextX > lastX)
  65503. {
  65504. if (nextX >= right)
  65505. break;
  65506. lastX = nextX;
  65507. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  65508. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  65509. if (nextLevel != lastLevel)
  65510. {
  65511. if (destTotal >= maxEdgesPerLine)
  65512. {
  65513. dest[0] = destTotal;
  65514. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65515. dest = table + lineStrideElements * y;
  65516. }
  65517. ++destTotal;
  65518. lastLevel = nextLevel;
  65519. dest[++destIndex] = nextX;
  65520. dest[++destIndex] = nextLevel;
  65521. }
  65522. }
  65523. }
  65524. if (lastLevel > 0)
  65525. {
  65526. if (destTotal >= maxEdgesPerLine)
  65527. {
  65528. dest[0] = destTotal;
  65529. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65530. dest = table + lineStrideElements * y;
  65531. }
  65532. ++destTotal;
  65533. dest[++destIndex] = right;
  65534. dest[++destIndex] = 0;
  65535. }
  65536. dest[0] = destTotal;
  65537. #if JUCE_DEBUG
  65538. int last = std::numeric_limits<int>::min();
  65539. for (int i = 0; i < dest[0]; ++i)
  65540. {
  65541. jassert (dest[i * 2 + 1] > last);
  65542. last = dest[i * 2 + 1];
  65543. }
  65544. jassert (dest [dest[0] * 2] == 0);
  65545. #endif
  65546. }
  65547. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  65548. {
  65549. int* lastItem = dest + (dest[0] * 2 - 1);
  65550. if (x2 < lastItem[0])
  65551. {
  65552. if (x2 <= dest[1])
  65553. {
  65554. dest[0] = 0;
  65555. return;
  65556. }
  65557. while (x2 < lastItem[-2])
  65558. {
  65559. --(dest[0]);
  65560. lastItem -= 2;
  65561. }
  65562. lastItem[0] = x2;
  65563. lastItem[1] = 0;
  65564. }
  65565. if (x1 > dest[1])
  65566. {
  65567. while (lastItem[0] > x1)
  65568. lastItem -= 2;
  65569. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  65570. if (itemsRemoved > 0)
  65571. {
  65572. dest[0] -= itemsRemoved;
  65573. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  65574. }
  65575. dest[1] = x1;
  65576. }
  65577. }
  65578. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  65579. {
  65580. const Rectangle<int> clipped (r.getIntersection (bounds));
  65581. if (clipped.isEmpty())
  65582. {
  65583. needToCheckEmptinesss = false;
  65584. bounds.setHeight (0);
  65585. }
  65586. else
  65587. {
  65588. const int top = clipped.getY() - bounds.getY();
  65589. const int bottom = clipped.getBottom() - bounds.getY();
  65590. if (bottom < bounds.getHeight())
  65591. bounds.setHeight (bottom);
  65592. if (clipped.getRight() < bounds.getRight())
  65593. bounds.setRight (clipped.getRight());
  65594. for (int i = top; --i >= 0;)
  65595. table [lineStrideElements * i] = 0;
  65596. if (clipped.getX() > bounds.getX())
  65597. {
  65598. const int x1 = clipped.getX() << 8;
  65599. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  65600. int* line = table + lineStrideElements * top;
  65601. for (int i = bottom - top; --i >= 0;)
  65602. {
  65603. if (line[0] != 0)
  65604. clipEdgeTableLineToRange (line, x1, x2);
  65605. line += lineStrideElements;
  65606. }
  65607. }
  65608. needToCheckEmptinesss = true;
  65609. }
  65610. }
  65611. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  65612. {
  65613. const Rectangle<int> clipped (r.getIntersection (bounds));
  65614. if (! clipped.isEmpty())
  65615. {
  65616. const int top = clipped.getY() - bounds.getY();
  65617. const int bottom = clipped.getBottom() - bounds.getY();
  65618. //XXX optimise here by shortening the table if it fills top or bottom
  65619. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  65620. clipped.getX() << 8, 0,
  65621. clipped.getRight() << 8, 255,
  65622. std::numeric_limits<int>::max(), 0 };
  65623. for (int i = top; i < bottom; ++i)
  65624. intersectWithEdgeTableLine (i, rectLine);
  65625. needToCheckEmptinesss = true;
  65626. }
  65627. }
  65628. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  65629. {
  65630. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  65631. if (clipped.isEmpty())
  65632. {
  65633. needToCheckEmptinesss = false;
  65634. bounds.setHeight (0);
  65635. }
  65636. else
  65637. {
  65638. const int top = clipped.getY() - bounds.getY();
  65639. const int bottom = clipped.getBottom() - bounds.getY();
  65640. if (bottom < bounds.getHeight())
  65641. bounds.setHeight (bottom);
  65642. if (clipped.getRight() < bounds.getRight())
  65643. bounds.setRight (clipped.getRight());
  65644. int i = 0;
  65645. for (i = top; --i >= 0;)
  65646. table [lineStrideElements * i] = 0;
  65647. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  65648. for (i = top; i < bottom; ++i)
  65649. {
  65650. intersectWithEdgeTableLine (i, otherLine);
  65651. otherLine += other.lineStrideElements;
  65652. }
  65653. needToCheckEmptinesss = true;
  65654. }
  65655. }
  65656. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  65657. {
  65658. y -= bounds.getY();
  65659. if (y < 0 || y >= bounds.getHeight())
  65660. return;
  65661. needToCheckEmptinesss = true;
  65662. if (numPixels <= 0)
  65663. {
  65664. table [lineStrideElements * y] = 0;
  65665. return;
  65666. }
  65667. int* tempLine = (int*) alloca ((numPixels * 2 + 4) * sizeof (int));
  65668. int destIndex = 0, lastLevel = 0;
  65669. while (--numPixels >= 0)
  65670. {
  65671. const int alpha = *mask;
  65672. mask += maskStride;
  65673. if (alpha != lastLevel)
  65674. {
  65675. tempLine[++destIndex] = (x << 8);
  65676. tempLine[++destIndex] = alpha;
  65677. lastLevel = alpha;
  65678. }
  65679. ++x;
  65680. }
  65681. if (lastLevel > 0)
  65682. {
  65683. tempLine[++destIndex] = (x << 8);
  65684. tempLine[++destIndex] = 0;
  65685. }
  65686. tempLine[0] = destIndex >> 1;
  65687. intersectWithEdgeTableLine (y, tempLine);
  65688. }
  65689. bool EdgeTable::isEmpty() throw()
  65690. {
  65691. if (needToCheckEmptinesss)
  65692. {
  65693. needToCheckEmptinesss = false;
  65694. int* t = table;
  65695. for (int i = bounds.getHeight(); --i >= 0;)
  65696. {
  65697. if (t[0] > 1)
  65698. return false;
  65699. t += lineStrideElements;
  65700. }
  65701. bounds.setHeight (0);
  65702. }
  65703. return bounds.getHeight() == 0;
  65704. }
  65705. END_JUCE_NAMESPACE
  65706. /*** End of inlined file: juce_EdgeTable.cpp ***/
  65707. /*** Start of inlined file: juce_FillType.cpp ***/
  65708. BEGIN_JUCE_NAMESPACE
  65709. FillType::FillType() throw()
  65710. : colour (0xff000000), image (0)
  65711. {
  65712. }
  65713. FillType::FillType (const Colour& colour_) throw()
  65714. : colour (colour_), image (0)
  65715. {
  65716. }
  65717. FillType::FillType (const ColourGradient& gradient_)
  65718. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  65719. {
  65720. }
  65721. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  65722. : colour (0xff000000), image (image_), transform (transform_)
  65723. {
  65724. }
  65725. FillType::FillType (const FillType& other)
  65726. : colour (other.colour),
  65727. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  65728. image (other.image), transform (other.transform)
  65729. {
  65730. }
  65731. FillType& FillType::operator= (const FillType& other)
  65732. {
  65733. if (this != &other)
  65734. {
  65735. colour = other.colour;
  65736. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  65737. image = other.image;
  65738. transform = other.transform;
  65739. }
  65740. return *this;
  65741. }
  65742. FillType::~FillType() throw()
  65743. {
  65744. }
  65745. bool FillType::operator== (const FillType& other) const
  65746. {
  65747. return colour == other.colour && image == other.image
  65748. && transform == other.transform
  65749. && (gradient == other.gradient
  65750. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  65751. }
  65752. bool FillType::operator!= (const FillType& other) const
  65753. {
  65754. return ! operator== (other);
  65755. }
  65756. void FillType::setColour (const Colour& newColour) throw()
  65757. {
  65758. gradient = 0;
  65759. image = Image::null;
  65760. colour = newColour;
  65761. }
  65762. void FillType::setGradient (const ColourGradient& newGradient)
  65763. {
  65764. if (gradient != 0)
  65765. {
  65766. *gradient = newGradient;
  65767. }
  65768. else
  65769. {
  65770. image = Image::null;
  65771. gradient = new ColourGradient (newGradient);
  65772. colour = Colours::black;
  65773. }
  65774. }
  65775. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  65776. {
  65777. gradient = 0;
  65778. image = image_;
  65779. transform = transform_;
  65780. colour = Colours::black;
  65781. }
  65782. void FillType::setOpacity (const float newOpacity) throw()
  65783. {
  65784. colour = colour.withAlpha (newOpacity);
  65785. }
  65786. bool FillType::isInvisible() const throw()
  65787. {
  65788. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  65789. }
  65790. END_JUCE_NAMESPACE
  65791. /*** End of inlined file: juce_FillType.cpp ***/
  65792. /*** Start of inlined file: juce_Graphics.cpp ***/
  65793. BEGIN_JUCE_NAMESPACE
  65794. template <typename Type>
  65795. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  65796. {
  65797. const int maxVal = 0x3fffffff;
  65798. return (int) x >= -maxVal && (int) x <= maxVal
  65799. && (int) y >= -maxVal && (int) y <= maxVal
  65800. && (int) w >= -maxVal && (int) w <= maxVal
  65801. && (int) h >= -maxVal && (int) h <= maxVal;
  65802. }
  65803. LowLevelGraphicsContext::LowLevelGraphicsContext()
  65804. {
  65805. }
  65806. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  65807. {
  65808. }
  65809. Graphics::Graphics (const Image& imageToDrawOnto)
  65810. : context (imageToDrawOnto.createLowLevelContext()),
  65811. contextToDelete (context),
  65812. saveStatePending (false)
  65813. {
  65814. }
  65815. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  65816. : context (internalContext),
  65817. saveStatePending (false)
  65818. {
  65819. }
  65820. Graphics::~Graphics()
  65821. {
  65822. }
  65823. void Graphics::resetToDefaultState()
  65824. {
  65825. saveStateIfPending();
  65826. context->setFill (FillType());
  65827. context->setFont (Font());
  65828. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  65829. }
  65830. bool Graphics::isVectorDevice() const
  65831. {
  65832. return context->isVectorDevice();
  65833. }
  65834. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  65835. {
  65836. saveStateIfPending();
  65837. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  65838. }
  65839. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  65840. {
  65841. saveStateIfPending();
  65842. return context->clipToRectangleList (clipRegion);
  65843. }
  65844. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  65845. {
  65846. saveStateIfPending();
  65847. context->clipToPath (path, transform);
  65848. return ! context->isClipEmpty();
  65849. }
  65850. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  65851. {
  65852. saveStateIfPending();
  65853. context->clipToImageAlpha (image, transform);
  65854. return ! context->isClipEmpty();
  65855. }
  65856. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  65857. {
  65858. saveStateIfPending();
  65859. context->excludeClipRectangle (rectangleToExclude);
  65860. }
  65861. bool Graphics::isClipEmpty() const
  65862. {
  65863. return context->isClipEmpty();
  65864. }
  65865. const Rectangle<int> Graphics::getClipBounds() const
  65866. {
  65867. return context->getClipBounds();
  65868. }
  65869. void Graphics::saveState()
  65870. {
  65871. saveStateIfPending();
  65872. saveStatePending = true;
  65873. }
  65874. void Graphics::restoreState()
  65875. {
  65876. if (saveStatePending)
  65877. saveStatePending = false;
  65878. else
  65879. context->restoreState();
  65880. }
  65881. void Graphics::saveStateIfPending()
  65882. {
  65883. if (saveStatePending)
  65884. {
  65885. saveStatePending = false;
  65886. context->saveState();
  65887. }
  65888. }
  65889. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  65890. {
  65891. saveStateIfPending();
  65892. context->setOrigin (newOriginX, newOriginY);
  65893. }
  65894. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  65895. {
  65896. return context->clipRegionIntersects (area);
  65897. }
  65898. void Graphics::setColour (const Colour& newColour)
  65899. {
  65900. saveStateIfPending();
  65901. context->setFill (newColour);
  65902. }
  65903. void Graphics::setOpacity (const float newOpacity)
  65904. {
  65905. saveStateIfPending();
  65906. context->setOpacity (newOpacity);
  65907. }
  65908. void Graphics::setGradientFill (const ColourGradient& gradient)
  65909. {
  65910. setFillType (gradient);
  65911. }
  65912. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  65913. {
  65914. saveStateIfPending();
  65915. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  65916. context->setOpacity (opacity);
  65917. }
  65918. void Graphics::setFillType (const FillType& newFill)
  65919. {
  65920. saveStateIfPending();
  65921. context->setFill (newFill);
  65922. }
  65923. void Graphics::setFont (const Font& newFont)
  65924. {
  65925. saveStateIfPending();
  65926. context->setFont (newFont);
  65927. }
  65928. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  65929. {
  65930. saveStateIfPending();
  65931. Font f (context->getFont());
  65932. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  65933. context->setFont (f);
  65934. }
  65935. const Font Graphics::getCurrentFont() const
  65936. {
  65937. return context->getFont();
  65938. }
  65939. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  65940. {
  65941. if (text.isNotEmpty()
  65942. && startX < context->getClipBounds().getRight())
  65943. {
  65944. GlyphArrangement arr;
  65945. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  65946. arr.draw (*this);
  65947. }
  65948. }
  65949. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  65950. {
  65951. if (text.isNotEmpty())
  65952. {
  65953. GlyphArrangement arr;
  65954. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  65955. arr.draw (*this, transform);
  65956. }
  65957. }
  65958. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  65959. {
  65960. if (text.isNotEmpty()
  65961. && startX < context->getClipBounds().getRight())
  65962. {
  65963. GlyphArrangement arr;
  65964. arr.addJustifiedText (context->getFont(), text,
  65965. (float) startX, (float) baselineY, (float) maximumLineWidth,
  65966. Justification::left);
  65967. arr.draw (*this);
  65968. }
  65969. }
  65970. void Graphics::drawText (const String& text,
  65971. const int x, const int y, const int width, const int height,
  65972. const Justification& justificationType,
  65973. const bool useEllipsesIfTooBig) const
  65974. {
  65975. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  65976. {
  65977. GlyphArrangement arr;
  65978. arr.addCurtailedLineOfText (context->getFont(), text,
  65979. 0.0f, 0.0f, (float) width,
  65980. useEllipsesIfTooBig);
  65981. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  65982. (float) x, (float) y, (float) width, (float) height,
  65983. justificationType);
  65984. arr.draw (*this);
  65985. }
  65986. }
  65987. void Graphics::drawFittedText (const String& text,
  65988. const int x, const int y, const int width, const int height,
  65989. const Justification& justification,
  65990. const int maximumNumberOfLines,
  65991. const float minimumHorizontalScale) const
  65992. {
  65993. if (text.isNotEmpty()
  65994. && width > 0 && height > 0
  65995. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  65996. {
  65997. GlyphArrangement arr;
  65998. arr.addFittedText (context->getFont(), text,
  65999. (float) x, (float) y, (float) width, (float) height,
  66000. justification,
  66001. maximumNumberOfLines,
  66002. minimumHorizontalScale);
  66003. arr.draw (*this);
  66004. }
  66005. }
  66006. void Graphics::fillRect (int x, int y, int width, int height) const
  66007. {
  66008. // passing in a silly number can cause maths problems in rendering!
  66009. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66010. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66011. }
  66012. void Graphics::fillRect (const Rectangle<int>& r) const
  66013. {
  66014. context->fillRect (r, false);
  66015. }
  66016. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66017. {
  66018. // passing in a silly number can cause maths problems in rendering!
  66019. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66020. Path p;
  66021. p.addRectangle (x, y, width, height);
  66022. fillPath (p);
  66023. }
  66024. void Graphics::setPixel (int x, int y) const
  66025. {
  66026. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66027. }
  66028. void Graphics::fillAll() const
  66029. {
  66030. fillRect (context->getClipBounds());
  66031. }
  66032. void Graphics::fillAll (const Colour& colourToUse) const
  66033. {
  66034. if (! colourToUse.isTransparent())
  66035. {
  66036. const Rectangle<int> clip (context->getClipBounds());
  66037. context->saveState();
  66038. context->setFill (colourToUse);
  66039. context->fillRect (clip, false);
  66040. context->restoreState();
  66041. }
  66042. }
  66043. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66044. {
  66045. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66046. context->fillPath (path, transform);
  66047. }
  66048. void Graphics::strokePath (const Path& path,
  66049. const PathStrokeType& strokeType,
  66050. const AffineTransform& transform) const
  66051. {
  66052. Path stroke;
  66053. strokeType.createStrokedPath (stroke, path, transform);
  66054. fillPath (stroke);
  66055. }
  66056. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66057. const int lineThickness) const
  66058. {
  66059. // passing in a silly number can cause maths problems in rendering!
  66060. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66061. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66062. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66063. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66064. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66065. }
  66066. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66067. {
  66068. // passing in a silly number can cause maths problems in rendering!
  66069. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66070. Path p;
  66071. p.addRectangle (x, y, width, lineThickness);
  66072. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66073. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66074. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66075. fillPath (p);
  66076. }
  66077. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66078. {
  66079. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66080. }
  66081. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66082. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66083. const bool useGradient, const bool sharpEdgeOnOutside) const
  66084. {
  66085. // passing in a silly number can cause maths problems in rendering!
  66086. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66087. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66088. {
  66089. context->saveState();
  66090. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66091. const float ramp = oldOpacity / bevelThickness;
  66092. for (int i = bevelThickness; --i >= 0;)
  66093. {
  66094. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66095. : oldOpacity;
  66096. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66097. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66098. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66099. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66100. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66101. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66102. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66103. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66104. }
  66105. context->restoreState();
  66106. }
  66107. }
  66108. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66109. {
  66110. // passing in a silly number can cause maths problems in rendering!
  66111. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66112. Path p;
  66113. p.addEllipse (x, y, width, height);
  66114. fillPath (p);
  66115. }
  66116. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66117. const float lineThickness) const
  66118. {
  66119. // passing in a silly number can cause maths problems in rendering!
  66120. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66121. Path p;
  66122. p.addEllipse (x, y, width, height);
  66123. strokePath (p, PathStrokeType (lineThickness));
  66124. }
  66125. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66126. {
  66127. // passing in a silly number can cause maths problems in rendering!
  66128. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66129. Path p;
  66130. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66131. fillPath (p);
  66132. }
  66133. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66134. {
  66135. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66136. }
  66137. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66138. const float cornerSize, const float lineThickness) const
  66139. {
  66140. // passing in a silly number can cause maths problems in rendering!
  66141. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66142. Path p;
  66143. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66144. strokePath (p, PathStrokeType (lineThickness));
  66145. }
  66146. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66147. {
  66148. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66149. }
  66150. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66151. {
  66152. Path p;
  66153. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66154. fillPath (p);
  66155. }
  66156. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66157. const int checkWidth, const int checkHeight,
  66158. const Colour& colour1, const Colour& colour2) const
  66159. {
  66160. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66161. if (checkWidth > 0 && checkHeight > 0)
  66162. {
  66163. context->saveState();
  66164. if (colour1 == colour2)
  66165. {
  66166. context->setFill (colour1);
  66167. context->fillRect (area, false);
  66168. }
  66169. else
  66170. {
  66171. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66172. if (! clipped.isEmpty())
  66173. {
  66174. context->clipToRectangle (clipped);
  66175. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66176. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66177. const int startX = area.getX() + checkNumX * checkWidth;
  66178. const int startY = area.getY() + checkNumY * checkHeight;
  66179. const int right = clipped.getRight();
  66180. const int bottom = clipped.getBottom();
  66181. for (int i = 0; i < 2; ++i)
  66182. {
  66183. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66184. int cy = i;
  66185. for (int y = startY; y < bottom; y += checkHeight)
  66186. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66187. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66188. }
  66189. }
  66190. }
  66191. context->restoreState();
  66192. }
  66193. }
  66194. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66195. {
  66196. context->drawVerticalLine (x, top, bottom);
  66197. }
  66198. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66199. {
  66200. context->drawHorizontalLine (y, left, right);
  66201. }
  66202. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  66203. {
  66204. context->drawLine (Line<float> (x1, y1, x2, y2));
  66205. }
  66206. void Graphics::drawLine (const float startX, const float startY,
  66207. const float endX, const float endY,
  66208. const float lineThickness) const
  66209. {
  66210. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  66211. }
  66212. void Graphics::drawLine (const Line<float>& line) const
  66213. {
  66214. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  66215. }
  66216. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66217. {
  66218. Path p;
  66219. p.addLineSegment (line, lineThickness);
  66220. fillPath (p);
  66221. }
  66222. void Graphics::drawDashedLine (const float startX, const float startY,
  66223. const float endX, const float endY,
  66224. const float* const dashLengths,
  66225. const int numDashLengths,
  66226. const float lineThickness) const
  66227. {
  66228. const double dx = endX - startX;
  66229. const double dy = endY - startY;
  66230. const double totalLen = juce_hypot (dx, dy);
  66231. if (totalLen >= 0.5)
  66232. {
  66233. const double onePixAlpha = 1.0 / totalLen;
  66234. double alpha = 0.0;
  66235. float x = startX;
  66236. float y = startY;
  66237. int n = 0;
  66238. while (alpha < 1.0f)
  66239. {
  66240. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  66241. n = n % numDashLengths;
  66242. const float oldX = x;
  66243. const float oldY = y;
  66244. x = (float) (startX + dx * alpha);
  66245. y = (float) (startY + dy * alpha);
  66246. if ((n & 1) != 0)
  66247. {
  66248. if (lineThickness != 1.0f)
  66249. drawLine (oldX, oldY, x, y, lineThickness);
  66250. else
  66251. drawLine (oldX, oldY, x, y);
  66252. }
  66253. }
  66254. }
  66255. }
  66256. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66257. {
  66258. saveStateIfPending();
  66259. context->setInterpolationQuality (newQuality);
  66260. }
  66261. void Graphics::drawImageAt (const Image& imageToDraw,
  66262. const int topLeftX, const int topLeftY,
  66263. const bool fillAlphaChannelWithCurrentBrush) const
  66264. {
  66265. const int imageW = imageToDraw.getWidth();
  66266. const int imageH = imageToDraw.getHeight();
  66267. drawImage (imageToDraw,
  66268. topLeftX, topLeftY, imageW, imageH,
  66269. 0, 0, imageW, imageH,
  66270. fillAlphaChannelWithCurrentBrush);
  66271. }
  66272. void Graphics::drawImageWithin (const Image& imageToDraw,
  66273. const int destX, const int destY,
  66274. const int destW, const int destH,
  66275. const RectanglePlacement& placementWithinTarget,
  66276. const bool fillAlphaChannelWithCurrentBrush) const
  66277. {
  66278. // passing in a silly number can cause maths problems in rendering!
  66279. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66280. if (imageToDraw.isValid())
  66281. {
  66282. const int imageW = imageToDraw.getWidth();
  66283. const int imageH = imageToDraw.getHeight();
  66284. if (imageW > 0 && imageH > 0)
  66285. {
  66286. double newX = 0.0, newY = 0.0;
  66287. double newW = imageW;
  66288. double newH = imageH;
  66289. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66290. destX, destY, destW, destH);
  66291. if (newW > 0 && newH > 0)
  66292. {
  66293. drawImage (imageToDraw,
  66294. roundToInt (newX), roundToInt (newY),
  66295. roundToInt (newW), roundToInt (newH),
  66296. 0, 0, imageW, imageH,
  66297. fillAlphaChannelWithCurrentBrush);
  66298. }
  66299. }
  66300. }
  66301. }
  66302. void Graphics::drawImage (const Image& imageToDraw,
  66303. int dx, int dy, int dw, int dh,
  66304. int sx, int sy, int sw, int sh,
  66305. const bool fillAlphaChannelWithCurrentBrush) const
  66306. {
  66307. // passing in a silly number can cause maths problems in rendering!
  66308. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66309. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66310. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66311. {
  66312. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66313. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66314. .translated ((float) dx, (float) dy),
  66315. fillAlphaChannelWithCurrentBrush);
  66316. }
  66317. }
  66318. void Graphics::drawImageTransformed (const Image& imageToDraw,
  66319. const AffineTransform& transform,
  66320. const bool fillAlphaChannelWithCurrentBrush) const
  66321. {
  66322. if (imageToDraw.isValid() && ! context->isClipEmpty())
  66323. {
  66324. if (fillAlphaChannelWithCurrentBrush)
  66325. {
  66326. context->saveState();
  66327. context->clipToImageAlpha (imageToDraw, transform);
  66328. fillAll();
  66329. context->restoreState();
  66330. }
  66331. else
  66332. {
  66333. context->drawImage (imageToDraw, transform, false);
  66334. }
  66335. }
  66336. }
  66337. END_JUCE_NAMESPACE
  66338. /*** End of inlined file: juce_Graphics.cpp ***/
  66339. /*** Start of inlined file: juce_Justification.cpp ***/
  66340. BEGIN_JUCE_NAMESPACE
  66341. Justification::Justification (const Justification& other) throw()
  66342. : flags (other.flags)
  66343. {
  66344. }
  66345. Justification& Justification::operator= (const Justification& other) throw()
  66346. {
  66347. flags = other.flags;
  66348. return *this;
  66349. }
  66350. int Justification::getOnlyVerticalFlags() const throw()
  66351. {
  66352. return flags & (top | bottom | verticallyCentred);
  66353. }
  66354. int Justification::getOnlyHorizontalFlags() const throw()
  66355. {
  66356. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  66357. }
  66358. void Justification::applyToRectangle (int& x, int& y,
  66359. const int w, const int h,
  66360. const int spaceX, const int spaceY,
  66361. const int spaceW, const int spaceH) const throw()
  66362. {
  66363. if ((flags & horizontallyCentred) != 0)
  66364. x = spaceX + ((spaceW - w) >> 1);
  66365. else if ((flags & right) != 0)
  66366. x = spaceX + spaceW - w;
  66367. else
  66368. x = spaceX;
  66369. if ((flags & verticallyCentred) != 0)
  66370. y = spaceY + ((spaceH - h) >> 1);
  66371. else if ((flags & bottom) != 0)
  66372. y = spaceY + spaceH - h;
  66373. else
  66374. y = spaceY;
  66375. }
  66376. END_JUCE_NAMESPACE
  66377. /*** End of inlined file: juce_Justification.cpp ***/
  66378. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66379. BEGIN_JUCE_NAMESPACE
  66380. // this will throw an assertion if you try to draw something that's not
  66381. // possible in postscript
  66382. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  66383. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  66384. #define notPossibleInPostscriptAssert jassertfalse
  66385. #else
  66386. #define notPossibleInPostscriptAssert
  66387. #endif
  66388. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  66389. const String& documentTitle,
  66390. const int totalWidth_,
  66391. const int totalHeight_)
  66392. : out (resultingPostScript),
  66393. totalWidth (totalWidth_),
  66394. totalHeight (totalHeight_),
  66395. needToClip (true)
  66396. {
  66397. stateStack.add (new SavedState());
  66398. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  66399. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  66400. out << "%!PS-Adobe-3.0 EPSF-3.0"
  66401. "\n%%BoundingBox: 0 0 600 824"
  66402. "\n%%Pages: 0"
  66403. "\n%%Creator: Raw Material Software JUCE"
  66404. "\n%%Title: " << documentTitle <<
  66405. "\n%%CreationDate: none"
  66406. "\n%%LanguageLevel: 2"
  66407. "\n%%EndComments"
  66408. "\n%%BeginProlog"
  66409. "\n%%BeginResource: JRes"
  66410. "\n/bd {bind def} bind def"
  66411. "\n/c {setrgbcolor} bd"
  66412. "\n/m {moveto} bd"
  66413. "\n/l {lineto} bd"
  66414. "\n/rl {rlineto} bd"
  66415. "\n/ct {curveto} bd"
  66416. "\n/cp {closepath} bd"
  66417. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  66418. "\n/doclip {initclip newpath} bd"
  66419. "\n/endclip {clip newpath} bd"
  66420. "\n%%EndResource"
  66421. "\n%%EndProlog"
  66422. "\n%%BeginSetup"
  66423. "\n%%EndSetup"
  66424. "\n%%Page: 1 1"
  66425. "\n%%BeginPageSetup"
  66426. "\n%%EndPageSetup\n\n"
  66427. << "40 800 translate\n"
  66428. << scale << ' ' << scale << " scale\n\n";
  66429. }
  66430. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  66431. {
  66432. }
  66433. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  66434. {
  66435. return true;
  66436. }
  66437. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  66438. {
  66439. if (x != 0 || y != 0)
  66440. {
  66441. stateStack.getLast()->xOffset += x;
  66442. stateStack.getLast()->yOffset += y;
  66443. needToClip = true;
  66444. }
  66445. }
  66446. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  66447. {
  66448. needToClip = true;
  66449. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66450. }
  66451. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  66452. {
  66453. needToClip = true;
  66454. return stateStack.getLast()->clip.clipTo (clipRegion);
  66455. }
  66456. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  66457. {
  66458. needToClip = true;
  66459. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66460. }
  66461. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  66462. {
  66463. writeClip();
  66464. Path p (path);
  66465. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66466. writePath (p);
  66467. out << "clip\n";
  66468. }
  66469. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  66470. {
  66471. needToClip = true;
  66472. jassertfalse; // xxx
  66473. }
  66474. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  66475. {
  66476. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66477. }
  66478. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  66479. {
  66480. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  66481. -stateStack.getLast()->yOffset);
  66482. }
  66483. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  66484. {
  66485. return stateStack.getLast()->clip.isEmpty();
  66486. }
  66487. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  66488. : xOffset (0),
  66489. yOffset (0)
  66490. {
  66491. }
  66492. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  66493. {
  66494. }
  66495. void LowLevelGraphicsPostScriptRenderer::saveState()
  66496. {
  66497. stateStack.add (new SavedState (*stateStack.getLast()));
  66498. }
  66499. void LowLevelGraphicsPostScriptRenderer::restoreState()
  66500. {
  66501. jassert (stateStack.size() > 0);
  66502. if (stateStack.size() > 0)
  66503. stateStack.removeLast();
  66504. }
  66505. void LowLevelGraphicsPostScriptRenderer::writeClip()
  66506. {
  66507. if (needToClip)
  66508. {
  66509. needToClip = false;
  66510. out << "doclip ";
  66511. int itemsOnLine = 0;
  66512. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  66513. {
  66514. if (++itemsOnLine == 6)
  66515. {
  66516. itemsOnLine = 0;
  66517. out << '\n';
  66518. }
  66519. const Rectangle<int>& r = *i.getRectangle();
  66520. out << r.getX() << ' ' << -r.getY() << ' '
  66521. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  66522. }
  66523. out << "endclip\n";
  66524. }
  66525. }
  66526. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  66527. {
  66528. Colour c (Colours::white.overlaidWith (colour));
  66529. if (lastColour != c)
  66530. {
  66531. lastColour = c;
  66532. out << String (c.getFloatRed(), 3) << ' '
  66533. << String (c.getFloatGreen(), 3) << ' '
  66534. << String (c.getFloatBlue(), 3) << " c\n";
  66535. }
  66536. }
  66537. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  66538. {
  66539. out << String (x, 2) << ' '
  66540. << String (-y, 2) << ' ';
  66541. }
  66542. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  66543. {
  66544. out << "newpath ";
  66545. float lastX = 0.0f;
  66546. float lastY = 0.0f;
  66547. int itemsOnLine = 0;
  66548. Path::Iterator i (path);
  66549. while (i.next())
  66550. {
  66551. if (++itemsOnLine == 4)
  66552. {
  66553. itemsOnLine = 0;
  66554. out << '\n';
  66555. }
  66556. switch (i.elementType)
  66557. {
  66558. case Path::Iterator::startNewSubPath:
  66559. writeXY (i.x1, i.y1);
  66560. lastX = i.x1;
  66561. lastY = i.y1;
  66562. out << "m ";
  66563. break;
  66564. case Path::Iterator::lineTo:
  66565. writeXY (i.x1, i.y1);
  66566. lastX = i.x1;
  66567. lastY = i.y1;
  66568. out << "l ";
  66569. break;
  66570. case Path::Iterator::quadraticTo:
  66571. {
  66572. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  66573. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  66574. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  66575. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  66576. writeXY (cp1x, cp1y);
  66577. writeXY (cp2x, cp2y);
  66578. writeXY (i.x2, i.y2);
  66579. out << "ct ";
  66580. lastX = i.x2;
  66581. lastY = i.y2;
  66582. }
  66583. break;
  66584. case Path::Iterator::cubicTo:
  66585. writeXY (i.x1, i.y1);
  66586. writeXY (i.x2, i.y2);
  66587. writeXY (i.x3, i.y3);
  66588. out << "ct ";
  66589. lastX = i.x3;
  66590. lastY = i.y3;
  66591. break;
  66592. case Path::Iterator::closePath:
  66593. out << "cp ";
  66594. break;
  66595. default:
  66596. jassertfalse;
  66597. break;
  66598. }
  66599. }
  66600. out << '\n';
  66601. }
  66602. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  66603. {
  66604. out << "[ "
  66605. << trans.mat00 << ' '
  66606. << trans.mat10 << ' '
  66607. << trans.mat01 << ' '
  66608. << trans.mat11 << ' '
  66609. << trans.mat02 << ' '
  66610. << trans.mat12 << " ] concat ";
  66611. }
  66612. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  66613. {
  66614. stateStack.getLast()->fillType = fillType;
  66615. }
  66616. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  66617. {
  66618. }
  66619. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  66620. {
  66621. }
  66622. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  66623. {
  66624. if (stateStack.getLast()->fillType.isColour())
  66625. {
  66626. writeClip();
  66627. writeColour (stateStack.getLast()->fillType.colour);
  66628. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66629. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  66630. }
  66631. else
  66632. {
  66633. Path p;
  66634. p.addRectangle (r);
  66635. fillPath (p, AffineTransform::identity);
  66636. }
  66637. }
  66638. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  66639. {
  66640. if (stateStack.getLast()->fillType.isColour())
  66641. {
  66642. writeClip();
  66643. Path p (path);
  66644. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  66645. (float) stateStack.getLast()->yOffset));
  66646. writePath (p);
  66647. writeColour (stateStack.getLast()->fillType.colour);
  66648. out << "fill\n";
  66649. }
  66650. else if (stateStack.getLast()->fillType.isGradient())
  66651. {
  66652. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  66653. // postscript can't do semi-transparent ones.
  66654. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  66655. writeClip();
  66656. out << "gsave ";
  66657. {
  66658. Path p (path);
  66659. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66660. writePath (p);
  66661. out << "clip\n";
  66662. }
  66663. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  66664. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  66665. // time-being, this just fills it with the average colour..
  66666. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  66667. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  66668. out << "grestore\n";
  66669. }
  66670. }
  66671. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  66672. const int sx, const int sy,
  66673. const int maxW, const int maxH) const
  66674. {
  66675. out << "{<\n";
  66676. const int w = jmin (maxW, im.getWidth());
  66677. const int h = jmin (maxH, im.getHeight());
  66678. int charsOnLine = 0;
  66679. const Image::BitmapData srcData (im, 0, 0, w, h);
  66680. Colour pixel;
  66681. for (int y = h; --y >= 0;)
  66682. {
  66683. for (int x = 0; x < w; ++x)
  66684. {
  66685. const uint8* pixelData = srcData.getPixelPointer (x, y);
  66686. if (x >= sx && y >= sy)
  66687. {
  66688. if (im.isARGB())
  66689. {
  66690. PixelARGB p (*(const PixelARGB*) pixelData);
  66691. p.unpremultiply();
  66692. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  66693. }
  66694. else if (im.isRGB())
  66695. {
  66696. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  66697. }
  66698. else
  66699. {
  66700. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  66701. }
  66702. }
  66703. else
  66704. {
  66705. pixel = Colours::transparentWhite;
  66706. }
  66707. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  66708. out << String::toHexString (pixelValues, 3, 0);
  66709. charsOnLine += 3;
  66710. if (charsOnLine > 100)
  66711. {
  66712. out << '\n';
  66713. charsOnLine = 0;
  66714. }
  66715. }
  66716. }
  66717. out << "\n>}\n";
  66718. }
  66719. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  66720. {
  66721. const int w = sourceImage.getWidth();
  66722. const int h = sourceImage.getHeight();
  66723. writeClip();
  66724. out << "gsave ";
  66725. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  66726. .scaled (1.0f, -1.0f));
  66727. RectangleList imageClip;
  66728. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  66729. out << "newpath ";
  66730. int itemsOnLine = 0;
  66731. for (RectangleList::Iterator i (imageClip); i.next();)
  66732. {
  66733. if (++itemsOnLine == 6)
  66734. {
  66735. out << '\n';
  66736. itemsOnLine = 0;
  66737. }
  66738. const Rectangle<int>& r = *i.getRectangle();
  66739. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  66740. }
  66741. out << " clip newpath\n";
  66742. out << w << ' ' << h << " scale\n";
  66743. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  66744. writeImage (sourceImage, 0, 0, w, h);
  66745. out << "false 3 colorimage grestore\n";
  66746. needToClip = true;
  66747. }
  66748. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  66749. {
  66750. Path p;
  66751. p.addLineSegment (line, 1.0f);
  66752. fillPath (p, AffineTransform::identity);
  66753. }
  66754. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  66755. {
  66756. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  66757. }
  66758. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  66759. {
  66760. drawLine (Line<float> (left, (float) y, right, (float) y));
  66761. }
  66762. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  66763. {
  66764. stateStack.getLast()->font = newFont;
  66765. }
  66766. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  66767. {
  66768. return stateStack.getLast()->font;
  66769. }
  66770. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  66771. {
  66772. Path p;
  66773. Font& font = stateStack.getLast()->font;
  66774. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  66775. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  66776. }
  66777. END_JUCE_NAMESPACE
  66778. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66779. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  66780. BEGIN_JUCE_NAMESPACE
  66781. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  66782. #define JUCE_USE_SSE_INSTRUCTIONS 1
  66783. #endif
  66784. #if JUCE_MSVC
  66785. #pragma warning (push)
  66786. #pragma warning (disable: 4127) // "expression is constant" warning
  66787. #if JUCE_DEBUG
  66788. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  66789. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  66790. #endif
  66791. #endif
  66792. namespace SoftwareRendererClasses
  66793. {
  66794. template <class PixelType, bool replaceExisting = false>
  66795. class SolidColourEdgeTableRenderer
  66796. {
  66797. public:
  66798. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  66799. : data (data_),
  66800. sourceColour (colour)
  66801. {
  66802. if (sizeof (PixelType) == 3)
  66803. {
  66804. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  66805. && sourceColour.getGreen() == sourceColour.getBlue();
  66806. filler[0].set (sourceColour);
  66807. filler[1].set (sourceColour);
  66808. filler[2].set (sourceColour);
  66809. filler[3].set (sourceColour);
  66810. }
  66811. }
  66812. forcedinline void setEdgeTableYPos (const int y) throw()
  66813. {
  66814. linePixels = (PixelType*) data.getLinePointer (y);
  66815. }
  66816. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  66817. {
  66818. if (replaceExisting)
  66819. linePixels[x].set (sourceColour);
  66820. else
  66821. linePixels[x].blend (sourceColour, alphaLevel);
  66822. }
  66823. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  66824. {
  66825. if (replaceExisting)
  66826. linePixels[x].set (sourceColour);
  66827. else
  66828. linePixels[x].blend (sourceColour);
  66829. }
  66830. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  66831. {
  66832. PixelARGB p (sourceColour);
  66833. p.multiplyAlpha (alphaLevel);
  66834. PixelType* dest = linePixels + x;
  66835. if (replaceExisting || p.getAlpha() >= 0xff)
  66836. replaceLine (dest, p, width);
  66837. else
  66838. blendLine (dest, p, width);
  66839. }
  66840. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  66841. {
  66842. PixelType* dest = linePixels + x;
  66843. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  66844. replaceLine (dest, sourceColour, width);
  66845. else
  66846. blendLine (dest, sourceColour, width);
  66847. }
  66848. private:
  66849. const Image::BitmapData& data;
  66850. PixelType* linePixels;
  66851. PixelARGB sourceColour;
  66852. PixelRGB filler [4];
  66853. bool areRGBComponentsEqual;
  66854. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  66855. {
  66856. do
  66857. {
  66858. dest->blend (colour);
  66859. ++dest;
  66860. } while (--width > 0);
  66861. }
  66862. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  66863. {
  66864. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  66865. {
  66866. memset (dest, colour.getRed(), width * 3);
  66867. }
  66868. else
  66869. {
  66870. if (width >> 5)
  66871. {
  66872. const int* const intFiller = (const int*) filler;
  66873. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  66874. {
  66875. dest->set (colour);
  66876. ++dest;
  66877. --width;
  66878. }
  66879. while (width > 4)
  66880. {
  66881. ((int*) dest) [0] = intFiller[0];
  66882. ((int*) dest) [1] = intFiller[1];
  66883. ((int*) dest) [2] = intFiller[2];
  66884. dest = (PixelRGB*) (((uint8*) dest) + 12);
  66885. width -= 4;
  66886. }
  66887. }
  66888. while (--width >= 0)
  66889. {
  66890. dest->set (colour);
  66891. ++dest;
  66892. }
  66893. }
  66894. }
  66895. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  66896. {
  66897. memset (dest, colour.getAlpha(), width);
  66898. }
  66899. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  66900. {
  66901. do
  66902. {
  66903. dest->set (colour);
  66904. ++dest;
  66905. } while (--width > 0);
  66906. }
  66907. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  66908. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  66909. };
  66910. class LinearGradientPixelGenerator
  66911. {
  66912. public:
  66913. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  66914. : lookupTable (lookupTable_), numEntries (numEntries_)
  66915. {
  66916. jassert (numEntries_ >= 0);
  66917. Point<float> p1 (gradient.point1);
  66918. Point<float> p2 (gradient.point2);
  66919. if (! transform.isIdentity())
  66920. {
  66921. const Line<float> l (p2, p1);
  66922. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  66923. p1.applyTransform (transform);
  66924. p2.applyTransform (transform);
  66925. p3.applyTransform (transform);
  66926. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  66927. }
  66928. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  66929. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  66930. if (vertical)
  66931. {
  66932. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  66933. start = roundToInt (p1.getY() * scale);
  66934. }
  66935. else if (horizontal)
  66936. {
  66937. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  66938. start = roundToInt (p1.getX() * scale);
  66939. }
  66940. else
  66941. {
  66942. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  66943. yTerm = p1.getY() - p1.getX() / grad;
  66944. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  66945. grad *= scale;
  66946. }
  66947. }
  66948. forcedinline void setY (const int y) throw()
  66949. {
  66950. if (vertical)
  66951. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  66952. else if (! horizontal)
  66953. start = roundToInt ((y - yTerm) * grad);
  66954. }
  66955. inline const PixelARGB getPixel (const int x) const throw()
  66956. {
  66957. return vertical ? linePix
  66958. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  66959. }
  66960. private:
  66961. const PixelARGB* const lookupTable;
  66962. const int numEntries;
  66963. PixelARGB linePix;
  66964. int start, scale;
  66965. double grad, yTerm;
  66966. bool vertical, horizontal;
  66967. enum { numScaleBits = 12 };
  66968. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  66969. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  66970. };
  66971. class RadialGradientPixelGenerator
  66972. {
  66973. public:
  66974. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  66975. const PixelARGB* const lookupTable_, const int numEntries_)
  66976. : lookupTable (lookupTable_),
  66977. numEntries (numEntries_),
  66978. gx1 (gradient.point1.getX()),
  66979. gy1 (gradient.point1.getY())
  66980. {
  66981. jassert (numEntries_ >= 0);
  66982. const Point<float> diff (gradient.point1 - gradient.point2);
  66983. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  66984. invScale = numEntries / std::sqrt (maxDist);
  66985. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  66986. }
  66987. forcedinline void setY (const int y) throw()
  66988. {
  66989. dy = y - gy1;
  66990. dy *= dy;
  66991. }
  66992. inline const PixelARGB getPixel (const int px) const throw()
  66993. {
  66994. double x = px - gx1;
  66995. x *= x;
  66996. x += dy;
  66997. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  66998. }
  66999. protected:
  67000. const PixelARGB* const lookupTable;
  67001. const int numEntries;
  67002. const double gx1, gy1;
  67003. double maxDist, invScale, dy;
  67004. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  67005. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  67006. };
  67007. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67008. {
  67009. public:
  67010. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67011. const PixelARGB* const lookupTable_, const int numEntries_)
  67012. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67013. inverseTransform (transform.inverted())
  67014. {
  67015. tM10 = inverseTransform.mat10;
  67016. tM00 = inverseTransform.mat00;
  67017. }
  67018. forcedinline void setY (const int y) throw()
  67019. {
  67020. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67021. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67022. }
  67023. inline const PixelARGB getPixel (const int px) const throw()
  67024. {
  67025. double x = px;
  67026. const double y = tM10 * x + lineYM11;
  67027. x = tM00 * x + lineYM01;
  67028. x *= x;
  67029. x += y * y;
  67030. if (x >= maxDist)
  67031. return lookupTable [numEntries];
  67032. else
  67033. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67034. }
  67035. private:
  67036. double tM10, tM00, lineYM01, lineYM11;
  67037. const AffineTransform inverseTransform;
  67038. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  67039. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  67040. };
  67041. template <class PixelType, class GradientType>
  67042. class GradientEdgeTableRenderer : public GradientType
  67043. {
  67044. public:
  67045. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67046. const PixelARGB* const lookupTable_, const int numEntries_)
  67047. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67048. destData (destData_)
  67049. {
  67050. }
  67051. forcedinline void setEdgeTableYPos (const int y) throw()
  67052. {
  67053. linePixels = (PixelType*) destData.getLinePointer (y);
  67054. GradientType::setY (y);
  67055. }
  67056. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67057. {
  67058. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67059. }
  67060. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67061. {
  67062. linePixels[x].blend (GradientType::getPixel (x));
  67063. }
  67064. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67065. {
  67066. PixelType* dest = linePixels + x;
  67067. if (alphaLevel < 0xff)
  67068. {
  67069. do
  67070. {
  67071. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67072. } while (--width > 0);
  67073. }
  67074. else
  67075. {
  67076. do
  67077. {
  67078. (dest++)->blend (GradientType::getPixel (x++));
  67079. } while (--width > 0);
  67080. }
  67081. }
  67082. void handleEdgeTableLineFull (int x, int width) const throw()
  67083. {
  67084. PixelType* dest = linePixels + x;
  67085. do
  67086. {
  67087. (dest++)->blend (GradientType::getPixel (x++));
  67088. } while (--width > 0);
  67089. }
  67090. private:
  67091. const Image::BitmapData& destData;
  67092. PixelType* linePixels;
  67093. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  67094. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  67095. };
  67096. static forcedinline int safeModulo (int n, const int divisor) throw()
  67097. {
  67098. jassert (divisor > 0);
  67099. n %= divisor;
  67100. return (n < 0) ? (n + divisor) : n;
  67101. }
  67102. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67103. class ImageFillEdgeTableRenderer
  67104. {
  67105. public:
  67106. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67107. const Image::BitmapData& srcData_,
  67108. const int extraAlpha_,
  67109. const int x, const int y)
  67110. : destData (destData_),
  67111. srcData (srcData_),
  67112. extraAlpha (extraAlpha_ + 1),
  67113. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  67114. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  67115. {
  67116. }
  67117. forcedinline void setEdgeTableYPos (int y) throw()
  67118. {
  67119. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67120. y -= yOffset;
  67121. if (repeatPattern)
  67122. {
  67123. jassert (y >= 0);
  67124. y %= srcData.height;
  67125. }
  67126. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67127. }
  67128. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67129. {
  67130. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67131. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67132. }
  67133. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67134. {
  67135. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67136. }
  67137. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67138. {
  67139. DestPixelType* dest = linePixels + x;
  67140. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67141. x -= xOffset;
  67142. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67143. if (alphaLevel < 0xfe)
  67144. {
  67145. do
  67146. {
  67147. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67148. } while (--width > 0);
  67149. }
  67150. else
  67151. {
  67152. if (repeatPattern)
  67153. {
  67154. do
  67155. {
  67156. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67157. } while (--width > 0);
  67158. }
  67159. else
  67160. {
  67161. copyRow (dest, sourceLineStart + x, width);
  67162. }
  67163. }
  67164. }
  67165. void handleEdgeTableLineFull (int x, int width) const throw()
  67166. {
  67167. DestPixelType* dest = linePixels + x;
  67168. x -= xOffset;
  67169. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67170. if (extraAlpha < 0xfe)
  67171. {
  67172. do
  67173. {
  67174. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67175. } while (--width > 0);
  67176. }
  67177. else
  67178. {
  67179. if (repeatPattern)
  67180. {
  67181. do
  67182. {
  67183. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67184. } while (--width > 0);
  67185. }
  67186. else
  67187. {
  67188. copyRow (dest, sourceLineStart + x, width);
  67189. }
  67190. }
  67191. }
  67192. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67193. {
  67194. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67195. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67196. uint8* mask = (uint8*) (s + x - xOffset);
  67197. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67198. mask += PixelARGB::indexA;
  67199. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67200. }
  67201. private:
  67202. const Image::BitmapData& destData;
  67203. const Image::BitmapData& srcData;
  67204. const int extraAlpha, xOffset, yOffset;
  67205. DestPixelType* linePixels;
  67206. SrcPixelType* sourceLineStart;
  67207. template <class PixelType1, class PixelType2>
  67208. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67209. {
  67210. do
  67211. {
  67212. dest++ ->blend (*src++);
  67213. } while (--width > 0);
  67214. }
  67215. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67216. {
  67217. memcpy (dest, src, width * sizeof (PixelRGB));
  67218. }
  67219. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  67220. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  67221. };
  67222. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67223. class TransformedImageFillEdgeTableRenderer
  67224. {
  67225. public:
  67226. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67227. const Image::BitmapData& srcData_,
  67228. const AffineTransform& transform,
  67229. const int extraAlpha_,
  67230. const bool betterQuality_)
  67231. : interpolator (transform),
  67232. destData (destData_),
  67233. srcData (srcData_),
  67234. extraAlpha (extraAlpha_ + 1),
  67235. betterQuality (betterQuality_),
  67236. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  67237. pixelOffsetInt (betterQuality_ ? -128 : 0),
  67238. maxX (srcData_.width - 1),
  67239. maxY (srcData_.height - 1),
  67240. scratchSize (2048)
  67241. {
  67242. scratchBuffer.malloc (scratchSize);
  67243. }
  67244. ~TransformedImageFillEdgeTableRenderer()
  67245. {
  67246. }
  67247. forcedinline void setEdgeTableYPos (const int newY) throw()
  67248. {
  67249. y = newY;
  67250. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67251. }
  67252. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  67253. {
  67254. alphaLevel *= extraAlpha;
  67255. alphaLevel >>= 8;
  67256. SrcPixelType p;
  67257. generate (&p, x, 1);
  67258. linePixels[x].blend (p, alphaLevel);
  67259. }
  67260. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67261. {
  67262. SrcPixelType p;
  67263. generate (&p, x, 1);
  67264. linePixels[x].blend (p, extraAlpha);
  67265. }
  67266. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67267. {
  67268. if (width > scratchSize)
  67269. {
  67270. scratchSize = width;
  67271. scratchBuffer.malloc (scratchSize);
  67272. }
  67273. SrcPixelType* span = scratchBuffer;
  67274. generate (span, x, width);
  67275. DestPixelType* dest = linePixels + x;
  67276. alphaLevel *= extraAlpha;
  67277. alphaLevel >>= 8;
  67278. if (alphaLevel < 0xfe)
  67279. {
  67280. do
  67281. {
  67282. dest++ ->blend (*span++, alphaLevel);
  67283. } while (--width > 0);
  67284. }
  67285. else
  67286. {
  67287. do
  67288. {
  67289. dest++ ->blend (*span++);
  67290. } while (--width > 0);
  67291. }
  67292. }
  67293. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67294. {
  67295. handleEdgeTableLine (x, width, 255);
  67296. }
  67297. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67298. {
  67299. if (width > scratchSize)
  67300. {
  67301. scratchSize = width;
  67302. scratchBuffer.malloc (scratchSize);
  67303. }
  67304. y = y_;
  67305. generate (scratchBuffer, x, width);
  67306. et.clipLineToMask (x, y_,
  67307. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67308. sizeof (SrcPixelType), width);
  67309. }
  67310. private:
  67311. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  67312. {
  67313. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67314. do
  67315. {
  67316. int hiResX, hiResY;
  67317. this->interpolator.next (hiResX, hiResY);
  67318. hiResX += pixelOffsetInt;
  67319. hiResY += pixelOffsetInt;
  67320. int loResX = hiResX >> 8;
  67321. int loResY = hiResY >> 8;
  67322. if (repeatPattern)
  67323. {
  67324. loResX = safeModulo (loResX, srcData.width);
  67325. loResY = safeModulo (loResY, srcData.height);
  67326. }
  67327. if (betterQuality
  67328. && ((unsigned int) loResX) < (unsigned int) maxX
  67329. && ((unsigned int) loResY) < (unsigned int) maxY)
  67330. {
  67331. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67332. hiResX &= 255;
  67333. hiResY &= 255;
  67334. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  67335. uint32 weight = (256 - hiResX) * (256 - hiResY);
  67336. c[0] += weight * src[0];
  67337. c[1] += weight * src[1];
  67338. c[2] += weight * src[2];
  67339. c[3] += weight * src[3];
  67340. weight = hiResX * (256 - hiResY);
  67341. c[0] += weight * src[4];
  67342. c[1] += weight * src[5];
  67343. c[2] += weight * src[6];
  67344. c[3] += weight * src[7];
  67345. src += this->srcData.lineStride;
  67346. weight = (256 - hiResX) * hiResY;
  67347. c[0] += weight * src[0];
  67348. c[1] += weight * src[1];
  67349. c[2] += weight * src[2];
  67350. c[3] += weight * src[3];
  67351. weight = hiResX * hiResY;
  67352. c[0] += weight * src[4];
  67353. c[1] += weight * src[5];
  67354. c[2] += weight * src[6];
  67355. c[3] += weight * src[7];
  67356. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67357. (uint8) (c[PixelARGB::indexR] >> 16),
  67358. (uint8) (c[PixelARGB::indexG] >> 16),
  67359. (uint8) (c[PixelARGB::indexB] >> 16));
  67360. }
  67361. else
  67362. {
  67363. if (! repeatPattern)
  67364. {
  67365. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  67366. if (loResX < 0) loResX = 0;
  67367. if (loResY < 0) loResY = 0;
  67368. if (loResX > maxX) loResX = maxX;
  67369. if (loResY > maxY) loResY = maxY;
  67370. }
  67371. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  67372. }
  67373. ++dest;
  67374. } while (--numPixels > 0);
  67375. }
  67376. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  67377. {
  67378. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67379. do
  67380. {
  67381. int hiResX, hiResY;
  67382. this->interpolator.next (hiResX, hiResY);
  67383. hiResX += pixelOffsetInt;
  67384. hiResY += pixelOffsetInt;
  67385. int loResX = hiResX >> 8;
  67386. int loResY = hiResY >> 8;
  67387. if (repeatPattern)
  67388. {
  67389. loResX = safeModulo (loResX, srcData.width);
  67390. loResY = safeModulo (loResY, srcData.height);
  67391. }
  67392. if (betterQuality
  67393. && ((unsigned int) loResX) < (unsigned int) maxX
  67394. && ((unsigned int) loResY) < (unsigned int) maxY)
  67395. {
  67396. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  67397. hiResX &= 255;
  67398. hiResY &= 255;
  67399. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  67400. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  67401. c[0] += weight * src[0];
  67402. c[1] += weight * src[1];
  67403. c[2] += weight * src[2];
  67404. weight = hiResX * (256 - hiResY);
  67405. c[0] += weight * src[3];
  67406. c[1] += weight * src[4];
  67407. c[2] += weight * src[5];
  67408. src += this->srcData.lineStride;
  67409. weight = (256 - hiResX) * hiResY;
  67410. c[0] += weight * src[0];
  67411. c[1] += weight * src[1];
  67412. c[2] += weight * src[2];
  67413. weight = hiResX * hiResY;
  67414. c[0] += weight * src[3];
  67415. c[1] += weight * src[4];
  67416. c[2] += weight * src[5];
  67417. dest->setARGB ((uint8) 255,
  67418. (uint8) (c[PixelRGB::indexR] >> 16),
  67419. (uint8) (c[PixelRGB::indexG] >> 16),
  67420. (uint8) (c[PixelRGB::indexB] >> 16));
  67421. }
  67422. else
  67423. {
  67424. if (! repeatPattern)
  67425. {
  67426. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  67427. if (loResX < 0) loResX = 0;
  67428. if (loResY < 0) loResY = 0;
  67429. if (loResX > maxX) loResX = maxX;
  67430. if (loResY > maxY) loResY = maxY;
  67431. }
  67432. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  67433. }
  67434. ++dest;
  67435. } while (--numPixels > 0);
  67436. }
  67437. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  67438. {
  67439. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67440. do
  67441. {
  67442. int hiResX, hiResY;
  67443. this->interpolator.next (hiResX, hiResY);
  67444. hiResX += pixelOffsetInt;
  67445. hiResY += pixelOffsetInt;
  67446. int loResX = hiResX >> 8;
  67447. int loResY = hiResY >> 8;
  67448. if (repeatPattern)
  67449. {
  67450. loResX = safeModulo (loResX, srcData.width);
  67451. loResY = safeModulo (loResY, srcData.height);
  67452. }
  67453. if (betterQuality
  67454. && ((unsigned int) loResX) < (unsigned int) maxX
  67455. && ((unsigned int) loResY) < (unsigned int) maxY)
  67456. {
  67457. hiResX &= 255;
  67458. hiResY &= 255;
  67459. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  67460. uint32 c = 256 * 128;
  67461. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  67462. c += src[1] * (hiResX * (256 - hiResY));
  67463. src += this->srcData.lineStride;
  67464. c += src[0] * ((256 - hiResX) * hiResY);
  67465. c += src[1] * (hiResX * hiResY);
  67466. *((uint8*) dest) = (uint8) c;
  67467. }
  67468. else
  67469. {
  67470. if (! repeatPattern)
  67471. {
  67472. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  67473. if (loResX < 0) loResX = 0;
  67474. if (loResY < 0) loResY = 0;
  67475. if (loResX > maxX) loResX = maxX;
  67476. if (loResY > maxY) loResY = maxY;
  67477. }
  67478. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  67479. }
  67480. ++dest;
  67481. } while (--numPixels > 0);
  67482. }
  67483. class TransformedImageSpanInterpolator
  67484. {
  67485. public:
  67486. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  67487. : inverseTransform (transform.inverted())
  67488. {}
  67489. void setStartOfLine (float x, float y, const int numPixels) throw()
  67490. {
  67491. float x1 = x, y1 = y;
  67492. x += numPixels;
  67493. inverseTransform.transformPoints (x1, y1, x, y);
  67494. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  67495. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  67496. }
  67497. void next (int& x, int& y) throw()
  67498. {
  67499. x = xBresenham.n;
  67500. xBresenham.stepToNext();
  67501. y = yBresenham.n;
  67502. yBresenham.stepToNext();
  67503. }
  67504. private:
  67505. class BresenhamInterpolator
  67506. {
  67507. public:
  67508. BresenhamInterpolator() throw() {}
  67509. void set (const int n1, const int n2, const int numSteps_) throw()
  67510. {
  67511. numSteps = jmax (1, numSteps_);
  67512. step = (n2 - n1) / numSteps;
  67513. remainder = modulo = (n2 - n1) % numSteps;
  67514. n = n1;
  67515. if (modulo <= 0)
  67516. {
  67517. modulo += numSteps;
  67518. remainder += numSteps;
  67519. --step;
  67520. }
  67521. modulo -= numSteps;
  67522. }
  67523. forcedinline void stepToNext() throw()
  67524. {
  67525. modulo += remainder;
  67526. n += step;
  67527. if (modulo > 0)
  67528. {
  67529. modulo -= numSteps;
  67530. ++n;
  67531. }
  67532. }
  67533. int n;
  67534. private:
  67535. int numSteps, step, modulo, remainder;
  67536. };
  67537. const AffineTransform inverseTransform;
  67538. BresenhamInterpolator xBresenham, yBresenham;
  67539. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  67540. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  67541. };
  67542. TransformedImageSpanInterpolator interpolator;
  67543. const Image::BitmapData& destData;
  67544. const Image::BitmapData& srcData;
  67545. const int extraAlpha;
  67546. const bool betterQuality;
  67547. const float pixelOffset;
  67548. const int pixelOffsetInt, maxX, maxY;
  67549. int y;
  67550. DestPixelType* linePixels;
  67551. HeapBlock <SrcPixelType> scratchBuffer;
  67552. int scratchSize;
  67553. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  67554. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  67555. };
  67556. class ClipRegionBase : public ReferenceCountedObject
  67557. {
  67558. public:
  67559. ClipRegionBase() {}
  67560. virtual ~ClipRegionBase() {}
  67561. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  67562. virtual const Ptr clone() const = 0;
  67563. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  67564. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  67565. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  67566. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  67567. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  67568. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  67569. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  67570. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  67571. virtual const Rectangle<int> getClipBounds() const = 0;
  67572. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  67573. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  67574. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  67575. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  67576. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  67577. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  67578. protected:
  67579. template <class Iterator>
  67580. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  67581. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  67582. {
  67583. switch (destData.pixelFormat)
  67584. {
  67585. case Image::ARGB:
  67586. switch (srcData.pixelFormat)
  67587. {
  67588. case Image::ARGB:
  67589. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67590. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67591. break;
  67592. case Image::RGB:
  67593. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67594. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67595. break;
  67596. default:
  67597. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67598. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67599. break;
  67600. }
  67601. break;
  67602. case Image::RGB:
  67603. switch (srcData.pixelFormat)
  67604. {
  67605. case Image::ARGB:
  67606. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67607. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67608. break;
  67609. case Image::RGB:
  67610. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67611. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67612. break;
  67613. default:
  67614. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67615. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67616. break;
  67617. }
  67618. break;
  67619. default:
  67620. switch (srcData.pixelFormat)
  67621. {
  67622. case Image::ARGB:
  67623. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67624. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67625. break;
  67626. case Image::RGB:
  67627. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67628. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67629. break;
  67630. default:
  67631. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67632. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67633. break;
  67634. }
  67635. break;
  67636. }
  67637. }
  67638. template <class Iterator>
  67639. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  67640. {
  67641. switch (destData.pixelFormat)
  67642. {
  67643. case Image::ARGB:
  67644. switch (srcData.pixelFormat)
  67645. {
  67646. case Image::ARGB:
  67647. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67648. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67649. break;
  67650. case Image::RGB:
  67651. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67652. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67653. break;
  67654. default:
  67655. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67656. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67657. break;
  67658. }
  67659. break;
  67660. case Image::RGB:
  67661. switch (srcData.pixelFormat)
  67662. {
  67663. case Image::ARGB:
  67664. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67665. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67666. break;
  67667. case Image::RGB:
  67668. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67669. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67670. break;
  67671. default:
  67672. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67673. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67674. break;
  67675. }
  67676. break;
  67677. default:
  67678. switch (srcData.pixelFormat)
  67679. {
  67680. case Image::ARGB:
  67681. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67682. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67683. break;
  67684. case Image::RGB:
  67685. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67686. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67687. break;
  67688. default:
  67689. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67690. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67691. break;
  67692. }
  67693. break;
  67694. }
  67695. }
  67696. template <class Iterator, class DestPixelType>
  67697. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  67698. {
  67699. jassert (destData.pixelStride == sizeof (DestPixelType));
  67700. if (replaceContents)
  67701. {
  67702. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  67703. iter.iterate (r);
  67704. }
  67705. else
  67706. {
  67707. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  67708. iter.iterate (r);
  67709. }
  67710. }
  67711. template <class Iterator, class DestPixelType>
  67712. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  67713. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  67714. {
  67715. jassert (destData.pixelStride == sizeof (DestPixelType));
  67716. if (g.isRadial)
  67717. {
  67718. if (isIdentity)
  67719. {
  67720. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  67721. iter.iterate (renderer);
  67722. }
  67723. else
  67724. {
  67725. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  67726. iter.iterate (renderer);
  67727. }
  67728. }
  67729. else
  67730. {
  67731. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  67732. iter.iterate (renderer);
  67733. }
  67734. }
  67735. };
  67736. class ClipRegion_EdgeTable : public ClipRegionBase
  67737. {
  67738. public:
  67739. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  67740. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  67741. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  67742. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  67743. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  67744. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  67745. ~ClipRegion_EdgeTable() {}
  67746. const Ptr clone() const
  67747. {
  67748. return new ClipRegion_EdgeTable (*this);
  67749. }
  67750. const Ptr applyClipTo (const Ptr& target) const
  67751. {
  67752. return target->clipToEdgeTable (edgeTable);
  67753. }
  67754. const Ptr clipToRectangle (const Rectangle<int>& r)
  67755. {
  67756. edgeTable.clipToRectangle (r);
  67757. return edgeTable.isEmpty() ? 0 : this;
  67758. }
  67759. const Ptr clipToRectangleList (const RectangleList& r)
  67760. {
  67761. RectangleList inverse (edgeTable.getMaximumBounds());
  67762. if (inverse.subtract (r))
  67763. for (RectangleList::Iterator iter (inverse); iter.next();)
  67764. edgeTable.excludeRectangle (*iter.getRectangle());
  67765. return edgeTable.isEmpty() ? 0 : this;
  67766. }
  67767. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  67768. {
  67769. edgeTable.excludeRectangle (r);
  67770. return edgeTable.isEmpty() ? 0 : this;
  67771. }
  67772. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  67773. {
  67774. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  67775. edgeTable.clipToEdgeTable (et);
  67776. return edgeTable.isEmpty() ? 0 : this;
  67777. }
  67778. const Ptr clipToEdgeTable (const EdgeTable& et)
  67779. {
  67780. edgeTable.clipToEdgeTable (et);
  67781. return edgeTable.isEmpty() ? 0 : this;
  67782. }
  67783. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  67784. {
  67785. const Image::BitmapData srcData (image, false);
  67786. if (transform.isOnlyTranslation())
  67787. {
  67788. // If our translation doesn't involve any distortion, just use a simple blit..
  67789. const int tx = (int) (transform.getTranslationX() * 256.0f);
  67790. const int ty = (int) (transform.getTranslationY() * 256.0f);
  67791. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  67792. {
  67793. const int imageX = ((tx + 128) >> 8);
  67794. const int imageY = ((ty + 128) >> 8);
  67795. if (image.getFormat() == Image::ARGB)
  67796. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  67797. else
  67798. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  67799. return edgeTable.isEmpty() ? 0 : this;
  67800. }
  67801. }
  67802. if (transform.isSingularity())
  67803. return 0;
  67804. {
  67805. Path p;
  67806. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  67807. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  67808. edgeTable.clipToEdgeTable (et2);
  67809. }
  67810. if (! edgeTable.isEmpty())
  67811. {
  67812. if (image.getFormat() == Image::ARGB)
  67813. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  67814. else
  67815. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  67816. }
  67817. return edgeTable.isEmpty() ? 0 : this;
  67818. }
  67819. bool clipRegionIntersects (const Rectangle<int>& r) const
  67820. {
  67821. return edgeTable.getMaximumBounds().intersects (r);
  67822. }
  67823. const Rectangle<int> getClipBounds() const
  67824. {
  67825. return edgeTable.getMaximumBounds();
  67826. }
  67827. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  67828. {
  67829. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  67830. const Rectangle<int> clipped (totalClip.getIntersection (area));
  67831. if (! clipped.isEmpty())
  67832. {
  67833. ClipRegion_EdgeTable et (clipped);
  67834. et.edgeTable.clipToEdgeTable (edgeTable);
  67835. et.fillAllWithColour (destData, colour, replaceContents);
  67836. }
  67837. }
  67838. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  67839. {
  67840. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  67841. const Rectangle<float> clipped (totalClip.getIntersection (area));
  67842. if (! clipped.isEmpty())
  67843. {
  67844. ClipRegion_EdgeTable et (clipped);
  67845. et.edgeTable.clipToEdgeTable (edgeTable);
  67846. et.fillAllWithColour (destData, colour, false);
  67847. }
  67848. }
  67849. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  67850. {
  67851. switch (destData.pixelFormat)
  67852. {
  67853. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  67854. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  67855. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  67856. }
  67857. }
  67858. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  67859. {
  67860. HeapBlock <PixelARGB> lookupTable;
  67861. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  67862. jassert (numLookupEntries > 0);
  67863. switch (destData.pixelFormat)
  67864. {
  67865. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  67866. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  67867. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  67868. }
  67869. }
  67870. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  67871. {
  67872. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  67873. }
  67874. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  67875. {
  67876. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  67877. }
  67878. EdgeTable edgeTable;
  67879. private:
  67880. template <class SrcPixelType>
  67881. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  67882. {
  67883. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  67884. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  67885. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  67886. edgeTable.getMaximumBounds().getWidth());
  67887. }
  67888. template <class SrcPixelType>
  67889. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  67890. {
  67891. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  67892. edgeTable.clipToRectangle (r);
  67893. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  67894. for (int y = 0; y < r.getHeight(); ++y)
  67895. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  67896. }
  67897. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  67898. };
  67899. class ClipRegion_RectangleList : public ClipRegionBase
  67900. {
  67901. public:
  67902. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  67903. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  67904. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  67905. ~ClipRegion_RectangleList() {}
  67906. const Ptr clone() const
  67907. {
  67908. return new ClipRegion_RectangleList (*this);
  67909. }
  67910. const Ptr applyClipTo (const Ptr& target) const
  67911. {
  67912. return target->clipToRectangleList (clip);
  67913. }
  67914. const Ptr clipToRectangle (const Rectangle<int>& r)
  67915. {
  67916. clip.clipTo (r);
  67917. return clip.isEmpty() ? 0 : this;
  67918. }
  67919. const Ptr clipToRectangleList (const RectangleList& r)
  67920. {
  67921. clip.clipTo (r);
  67922. return clip.isEmpty() ? 0 : this;
  67923. }
  67924. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  67925. {
  67926. clip.subtract (r);
  67927. return clip.isEmpty() ? 0 : this;
  67928. }
  67929. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  67930. {
  67931. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  67932. }
  67933. const Ptr clipToEdgeTable (const EdgeTable& et)
  67934. {
  67935. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  67936. }
  67937. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  67938. {
  67939. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  67940. }
  67941. bool clipRegionIntersects (const Rectangle<int>& r) const
  67942. {
  67943. return clip.intersects (r);
  67944. }
  67945. const Rectangle<int> getClipBounds() const
  67946. {
  67947. return clip.getBounds();
  67948. }
  67949. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  67950. {
  67951. SubRectangleIterator iter (clip, area);
  67952. switch (destData.pixelFormat)
  67953. {
  67954. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  67955. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  67956. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  67957. }
  67958. }
  67959. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  67960. {
  67961. SubRectangleIteratorFloat iter (clip, area);
  67962. switch (destData.pixelFormat)
  67963. {
  67964. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  67965. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  67966. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  67967. }
  67968. }
  67969. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  67970. {
  67971. switch (destData.pixelFormat)
  67972. {
  67973. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  67974. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  67975. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  67976. }
  67977. }
  67978. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  67979. {
  67980. HeapBlock <PixelARGB> lookupTable;
  67981. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  67982. jassert (numLookupEntries > 0);
  67983. switch (destData.pixelFormat)
  67984. {
  67985. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  67986. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  67987. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  67988. }
  67989. }
  67990. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  67991. {
  67992. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  67993. }
  67994. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  67995. {
  67996. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  67997. }
  67998. RectangleList clip;
  67999. template <class Renderer>
  68000. void iterate (Renderer& r) const throw()
  68001. {
  68002. RectangleList::Iterator iter (clip);
  68003. while (iter.next())
  68004. {
  68005. const Rectangle<int> rect (*iter.getRectangle());
  68006. const int x = rect.getX();
  68007. const int w = rect.getWidth();
  68008. jassert (w > 0);
  68009. const int bottom = rect.getBottom();
  68010. for (int y = rect.getY(); y < bottom; ++y)
  68011. {
  68012. r.setEdgeTableYPos (y);
  68013. r.handleEdgeTableLineFull (x, w);
  68014. }
  68015. }
  68016. }
  68017. private:
  68018. class SubRectangleIterator
  68019. {
  68020. public:
  68021. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68022. : clip (clip_), area (area_)
  68023. {
  68024. }
  68025. template <class Renderer>
  68026. void iterate (Renderer& r) const throw()
  68027. {
  68028. RectangleList::Iterator iter (clip);
  68029. while (iter.next())
  68030. {
  68031. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68032. if (! rect.isEmpty())
  68033. {
  68034. const int x = rect.getX();
  68035. const int w = rect.getWidth();
  68036. const int bottom = rect.getBottom();
  68037. for (int y = rect.getY(); y < bottom; ++y)
  68038. {
  68039. r.setEdgeTableYPos (y);
  68040. r.handleEdgeTableLineFull (x, w);
  68041. }
  68042. }
  68043. }
  68044. }
  68045. private:
  68046. const RectangleList& clip;
  68047. const Rectangle<int> area;
  68048. SubRectangleIterator (const SubRectangleIterator&);
  68049. SubRectangleIterator& operator= (const SubRectangleIterator&);
  68050. };
  68051. class SubRectangleIteratorFloat
  68052. {
  68053. public:
  68054. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68055. : clip (clip_), area (area_)
  68056. {
  68057. }
  68058. template <class Renderer>
  68059. void iterate (Renderer& r) const throw()
  68060. {
  68061. int left = roundToInt (area.getX() * 256.0f);
  68062. int top = roundToInt (area.getY() * 256.0f);
  68063. int right = roundToInt (area.getRight() * 256.0f);
  68064. int bottom = roundToInt (area.getBottom() * 256.0f);
  68065. int totalTop, totalLeft, totalBottom, totalRight;
  68066. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68067. if ((top >> 8) == (bottom >> 8))
  68068. {
  68069. topAlpha = bottom - top;
  68070. bottomAlpha = 0;
  68071. totalTop = top >> 8;
  68072. totalBottom = bottom = top = totalTop + 1;
  68073. }
  68074. else
  68075. {
  68076. if ((top & 255) == 0)
  68077. {
  68078. topAlpha = 0;
  68079. top = totalTop = (top >> 8);
  68080. }
  68081. else
  68082. {
  68083. topAlpha = 255 - (top & 255);
  68084. totalTop = (top >> 8);
  68085. top = totalTop + 1;
  68086. }
  68087. bottomAlpha = bottom & 255;
  68088. bottom >>= 8;
  68089. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68090. }
  68091. if ((left >> 8) == (right >> 8))
  68092. {
  68093. leftAlpha = right - left;
  68094. rightAlpha = 0;
  68095. totalLeft = (left >> 8);
  68096. totalRight = right = left = totalLeft + 1;
  68097. }
  68098. else
  68099. {
  68100. if ((left & 255) == 0)
  68101. {
  68102. leftAlpha = 0;
  68103. left = totalLeft = (left >> 8);
  68104. }
  68105. else
  68106. {
  68107. leftAlpha = 255 - (left & 255);
  68108. totalLeft = (left >> 8);
  68109. left = totalLeft + 1;
  68110. }
  68111. rightAlpha = right & 255;
  68112. right >>= 8;
  68113. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68114. }
  68115. RectangleList::Iterator iter (clip);
  68116. while (iter.next())
  68117. {
  68118. const int clipLeft = iter.getRectangle()->getX();
  68119. const int clipRight = iter.getRectangle()->getRight();
  68120. const int clipTop = iter.getRectangle()->getY();
  68121. const int clipBottom = iter.getRectangle()->getBottom();
  68122. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68123. {
  68124. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68125. {
  68126. if (topAlpha != 0 && totalTop >= clipTop)
  68127. {
  68128. r.setEdgeTableYPos (totalTop);
  68129. r.handleEdgeTablePixel (left, topAlpha);
  68130. }
  68131. const int endY = jmin (bottom, clipBottom);
  68132. for (int y = jmax (clipTop, top); y < endY; ++y)
  68133. {
  68134. r.setEdgeTableYPos (y);
  68135. r.handleEdgeTablePixelFull (left);
  68136. }
  68137. if (bottomAlpha != 0 && bottom < clipBottom)
  68138. {
  68139. r.setEdgeTableYPos (bottom);
  68140. r.handleEdgeTablePixel (left, bottomAlpha);
  68141. }
  68142. }
  68143. else
  68144. {
  68145. const int clippedLeft = jmax (left, clipLeft);
  68146. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68147. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68148. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68149. if (topAlpha != 0 && totalTop >= clipTop)
  68150. {
  68151. r.setEdgeTableYPos (totalTop);
  68152. if (doLeftAlpha)
  68153. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68154. if (clippedWidth > 0)
  68155. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68156. if (doRightAlpha)
  68157. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68158. }
  68159. const int endY = jmin (bottom, clipBottom);
  68160. for (int y = jmax (clipTop, top); y < endY; ++y)
  68161. {
  68162. r.setEdgeTableYPos (y);
  68163. if (doLeftAlpha)
  68164. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68165. if (clippedWidth > 0)
  68166. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68167. if (doRightAlpha)
  68168. r.handleEdgeTablePixel (right, rightAlpha);
  68169. }
  68170. if (bottomAlpha != 0 && bottom < clipBottom)
  68171. {
  68172. r.setEdgeTableYPos (bottom);
  68173. if (doLeftAlpha)
  68174. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68175. if (clippedWidth > 0)
  68176. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68177. if (doRightAlpha)
  68178. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68179. }
  68180. }
  68181. }
  68182. }
  68183. }
  68184. private:
  68185. const RectangleList& clip;
  68186. const Rectangle<float>& area;
  68187. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  68188. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  68189. };
  68190. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68191. };
  68192. }
  68193. class LowLevelGraphicsSoftwareRenderer::SavedState
  68194. {
  68195. public:
  68196. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68197. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68198. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68199. {
  68200. }
  68201. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68202. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68203. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68204. {
  68205. }
  68206. SavedState (const SavedState& other)
  68207. : clip (other.clip), xOffset (other.xOffset), yOffset (other.yOffset), font (other.font),
  68208. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  68209. {
  68210. }
  68211. ~SavedState()
  68212. {
  68213. }
  68214. void setOrigin (const int x, const int y) throw()
  68215. {
  68216. xOffset += x;
  68217. yOffset += y;
  68218. }
  68219. bool clipToRectangle (const Rectangle<int>& r)
  68220. {
  68221. if (clip != 0)
  68222. {
  68223. cloneClipIfMultiplyReferenced();
  68224. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68225. }
  68226. return clip != 0;
  68227. }
  68228. bool clipToRectangleList (const RectangleList& r)
  68229. {
  68230. if (clip != 0)
  68231. {
  68232. cloneClipIfMultiplyReferenced();
  68233. RectangleList offsetList (r);
  68234. offsetList.offsetAll (xOffset, yOffset);
  68235. clip = clip->clipToRectangleList (offsetList);
  68236. }
  68237. return clip != 0;
  68238. }
  68239. bool excludeClipRectangle (const Rectangle<int>& r)
  68240. {
  68241. if (clip != 0)
  68242. {
  68243. cloneClipIfMultiplyReferenced();
  68244. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68245. }
  68246. return clip != 0;
  68247. }
  68248. void clipToPath (const Path& p, const AffineTransform& transform)
  68249. {
  68250. if (clip != 0)
  68251. {
  68252. cloneClipIfMultiplyReferenced();
  68253. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  68254. }
  68255. }
  68256. void clipToImageAlpha (const Image& image, const AffineTransform& t)
  68257. {
  68258. if (clip != 0)
  68259. {
  68260. if (image.hasAlphaChannel())
  68261. {
  68262. cloneClipIfMultiplyReferenced();
  68263. clip = clip->clipToImageAlpha (image, t.translated ((float) xOffset, (float) yOffset),
  68264. interpolationQuality != Graphics::lowResamplingQuality);
  68265. }
  68266. else
  68267. {
  68268. Path p;
  68269. p.addRectangle (image.getBounds());
  68270. clipToPath (p, t);
  68271. }
  68272. }
  68273. }
  68274. bool clipRegionIntersects (const Rectangle<int>& r) const
  68275. {
  68276. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68277. }
  68278. const Rectangle<int> getClipBounds() const
  68279. {
  68280. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  68281. }
  68282. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  68283. {
  68284. if (clip != 0)
  68285. {
  68286. if (fillType.isColour())
  68287. {
  68288. Image::BitmapData destData (image, true);
  68289. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68290. }
  68291. else
  68292. {
  68293. const Rectangle<int> totalClip (clip->getClipBounds());
  68294. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68295. if (! clipped.isEmpty())
  68296. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68297. }
  68298. }
  68299. }
  68300. void fillRect (Image& image, const Rectangle<float>& r)
  68301. {
  68302. if (clip != 0)
  68303. {
  68304. if (fillType.isColour())
  68305. {
  68306. Image::BitmapData destData (image, true);
  68307. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68308. }
  68309. else
  68310. {
  68311. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  68312. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  68313. if (! clipped.isEmpty())
  68314. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  68315. }
  68316. }
  68317. }
  68318. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  68319. {
  68320. if (clip != 0)
  68321. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  68322. }
  68323. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  68324. {
  68325. if (clip != 0)
  68326. {
  68327. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  68328. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  68329. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  68330. fillShape (image, shapeToFill, false);
  68331. }
  68332. }
  68333. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  68334. {
  68335. jassert (clip != 0);
  68336. shapeToFill = clip->applyClipTo (shapeToFill);
  68337. if (shapeToFill != 0)
  68338. {
  68339. Image::BitmapData destData (image, true);
  68340. if (fillType.isGradient())
  68341. {
  68342. jassert (! replaceContents); // that option is just for solid colours
  68343. ColourGradient g2 (*(fillType.gradient));
  68344. g2.multiplyOpacity (fillType.getOpacity());
  68345. g2.point1.addXY (-0.5f, -0.5f);
  68346. g2.point2.addXY (-0.5f, -0.5f);
  68347. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  68348. const bool isIdentity = transform.isOnlyTranslation();
  68349. if (isIdentity)
  68350. {
  68351. // If our translation doesn't involve any distortion, we can speed it up..
  68352. g2.point1.applyTransform (transform);
  68353. g2.point2.applyTransform (transform);
  68354. transform = AffineTransform::identity;
  68355. }
  68356. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  68357. }
  68358. else if (fillType.isTiledImage())
  68359. {
  68360. renderImage (image, fillType.image, fillType.transform, shapeToFill);
  68361. }
  68362. else
  68363. {
  68364. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  68365. }
  68366. }
  68367. }
  68368. void renderImage (Image& destImage, const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  68369. {
  68370. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  68371. const Image::BitmapData destData (destImage, true);
  68372. const Image::BitmapData srcData (sourceImage, false);
  68373. const int alpha = fillType.colour.getAlpha();
  68374. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  68375. if (transform.isOnlyTranslation())
  68376. {
  68377. // If our translation doesn't involve any distortion, just use a simple blit..
  68378. int tx = (int) (transform.getTranslationX() * 256.0f);
  68379. int ty = (int) (transform.getTranslationY() * 256.0f);
  68380. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68381. {
  68382. tx = ((tx + 128) >> 8);
  68383. ty = ((ty + 128) >> 8);
  68384. if (tiledFillClipRegion != 0)
  68385. {
  68386. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  68387. }
  68388. else
  68389. {
  68390. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (destImage.getBounds())));
  68391. c = clip->applyClipTo (c);
  68392. if (c != 0)
  68393. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  68394. }
  68395. return;
  68396. }
  68397. }
  68398. if (transform.isSingularity())
  68399. return;
  68400. if (tiledFillClipRegion != 0)
  68401. {
  68402. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  68403. }
  68404. else
  68405. {
  68406. Path p;
  68407. p.addRectangle (sourceImage.getBounds());
  68408. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  68409. c = c->clipToPath (p, transform);
  68410. if (c != 0)
  68411. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  68412. }
  68413. }
  68414. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  68415. int xOffset, yOffset;
  68416. Font font;
  68417. FillType fillType;
  68418. Graphics::ResamplingQuality interpolationQuality;
  68419. private:
  68420. void cloneClipIfMultiplyReferenced()
  68421. {
  68422. if (clip->getReferenceCount() > 1)
  68423. clip = clip->clone();
  68424. }
  68425. SavedState& operator= (const SavedState&);
  68426. };
  68427. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  68428. : image (image_)
  68429. {
  68430. currentState = new SavedState (image_.getBounds(), 0, 0);
  68431. }
  68432. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  68433. const RectangleList& initialClip)
  68434. : image (image_)
  68435. {
  68436. currentState = new SavedState (initialClip, xOffset, yOffset);
  68437. }
  68438. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  68439. {
  68440. }
  68441. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  68442. {
  68443. return false;
  68444. }
  68445. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  68446. {
  68447. currentState->setOrigin (x, y);
  68448. }
  68449. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  68450. {
  68451. return currentState->clipToRectangle (r);
  68452. }
  68453. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  68454. {
  68455. return currentState->clipToRectangleList (clipRegion);
  68456. }
  68457. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  68458. {
  68459. currentState->excludeClipRectangle (r);
  68460. }
  68461. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  68462. {
  68463. currentState->clipToPath (path, transform);
  68464. }
  68465. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  68466. {
  68467. currentState->clipToImageAlpha (sourceImage, transform);
  68468. }
  68469. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  68470. {
  68471. return currentState->clipRegionIntersects (r);
  68472. }
  68473. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  68474. {
  68475. return currentState->getClipBounds();
  68476. }
  68477. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  68478. {
  68479. return currentState->clip == 0;
  68480. }
  68481. void LowLevelGraphicsSoftwareRenderer::saveState()
  68482. {
  68483. stateStack.add (new SavedState (*currentState));
  68484. }
  68485. void LowLevelGraphicsSoftwareRenderer::restoreState()
  68486. {
  68487. SavedState* const top = stateStack.getLast();
  68488. if (top != 0)
  68489. {
  68490. currentState = top;
  68491. stateStack.removeLast (1, false);
  68492. }
  68493. else
  68494. {
  68495. jassertfalse; // trying to pop with an empty stack!
  68496. }
  68497. }
  68498. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  68499. {
  68500. currentState->fillType = fillType;
  68501. }
  68502. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  68503. {
  68504. currentState->fillType.setOpacity (newOpacity);
  68505. }
  68506. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  68507. {
  68508. currentState->interpolationQuality = quality;
  68509. }
  68510. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  68511. {
  68512. currentState->fillRect (image, r, replaceExistingContents);
  68513. }
  68514. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  68515. {
  68516. currentState->fillPath (image, path, transform);
  68517. }
  68518. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  68519. {
  68520. currentState->renderImage (image, sourceImage, transform,
  68521. fillEntireClipAsTiles ? currentState->clip : 0);
  68522. }
  68523. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  68524. {
  68525. Path p;
  68526. p.addLineSegment (line, 1.0f);
  68527. fillPath (p, AffineTransform::identity);
  68528. }
  68529. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  68530. {
  68531. if (bottom > top)
  68532. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  68533. }
  68534. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  68535. {
  68536. if (right > left)
  68537. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  68538. }
  68539. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  68540. {
  68541. public:
  68542. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  68543. ~CachedGlyph() {}
  68544. void draw (SavedState& state, Image& image, const float x, const float y) const
  68545. {
  68546. if (edgeTable != 0)
  68547. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  68548. }
  68549. void generate (const Font& newFont, const int glyphNumber)
  68550. {
  68551. font = newFont;
  68552. glyph = glyphNumber;
  68553. edgeTable = 0;
  68554. Path glyphPath;
  68555. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  68556. if (! glyphPath.isEmpty())
  68557. {
  68558. const float fontHeight = font.getHeight();
  68559. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  68560. .translated (0.0f, -0.5f));
  68561. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  68562. glyphPath, transform);
  68563. }
  68564. }
  68565. int glyph, lastAccessCount;
  68566. Font font;
  68567. juce_UseDebuggingNewOperator
  68568. private:
  68569. ScopedPointer <EdgeTable> edgeTable;
  68570. CachedGlyph (const CachedGlyph&);
  68571. CachedGlyph& operator= (const CachedGlyph&);
  68572. };
  68573. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  68574. {
  68575. public:
  68576. GlyphCache()
  68577. : accessCounter (0), hits (0), misses (0)
  68578. {
  68579. for (int i = 120; --i >= 0;)
  68580. glyphs.add (new CachedGlyph());
  68581. }
  68582. ~GlyphCache()
  68583. {
  68584. clearSingletonInstance();
  68585. }
  68586. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  68587. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  68588. {
  68589. ++accessCounter;
  68590. int oldestCounter = std::numeric_limits<int>::max();
  68591. CachedGlyph* oldest = 0;
  68592. for (int i = glyphs.size(); --i >= 0;)
  68593. {
  68594. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  68595. if (glyph->glyph == glyphNumber && glyph->font == font)
  68596. {
  68597. ++hits;
  68598. glyph->lastAccessCount = accessCounter;
  68599. glyph->draw (state, image, x, y);
  68600. return;
  68601. }
  68602. if (glyph->lastAccessCount <= oldestCounter)
  68603. {
  68604. oldestCounter = glyph->lastAccessCount;
  68605. oldest = glyph;
  68606. }
  68607. }
  68608. if (hits + ++misses > (glyphs.size() << 4))
  68609. {
  68610. if (misses * 2 > hits)
  68611. {
  68612. for (int i = 32; --i >= 0;)
  68613. glyphs.add (new CachedGlyph());
  68614. }
  68615. hits = misses = 0;
  68616. oldest = glyphs.getLast();
  68617. }
  68618. jassert (oldest != 0);
  68619. oldest->lastAccessCount = accessCounter;
  68620. oldest->generate (font, glyphNumber);
  68621. oldest->draw (state, image, x, y);
  68622. }
  68623. juce_UseDebuggingNewOperator
  68624. private:
  68625. friend class OwnedArray <CachedGlyph>;
  68626. OwnedArray <CachedGlyph> glyphs;
  68627. int accessCounter, hits, misses;
  68628. GlyphCache (const GlyphCache&);
  68629. GlyphCache& operator= (const GlyphCache&);
  68630. };
  68631. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  68632. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  68633. {
  68634. currentState->font = newFont;
  68635. }
  68636. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  68637. {
  68638. return currentState->font;
  68639. }
  68640. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  68641. {
  68642. Font& f = currentState->font;
  68643. if (transform.isOnlyTranslation())
  68644. {
  68645. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  68646. transform.getTranslationX(),
  68647. transform.getTranslationY());
  68648. }
  68649. else
  68650. {
  68651. Path p;
  68652. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  68653. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  68654. }
  68655. }
  68656. #if JUCE_MSVC
  68657. #pragma warning (pop)
  68658. #if JUCE_DEBUG
  68659. #pragma optimize ("", on) // resets optimisations to the project defaults
  68660. #endif
  68661. #endif
  68662. END_JUCE_NAMESPACE
  68663. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  68664. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  68665. BEGIN_JUCE_NAMESPACE
  68666. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  68667. : flags (other.flags)
  68668. {
  68669. }
  68670. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  68671. {
  68672. flags = other.flags;
  68673. return *this;
  68674. }
  68675. void RectanglePlacement::applyTo (double& x, double& y,
  68676. double& w, double& h,
  68677. const double dx, const double dy,
  68678. const double dw, const double dh) const throw()
  68679. {
  68680. if (w == 0 || h == 0)
  68681. return;
  68682. if ((flags & stretchToFit) != 0)
  68683. {
  68684. x = dx;
  68685. y = dy;
  68686. w = dw;
  68687. h = dh;
  68688. }
  68689. else
  68690. {
  68691. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  68692. : jmin (dw / w, dh / h);
  68693. if ((flags & onlyReduceInSize) != 0)
  68694. scale = jmin (scale, 1.0);
  68695. if ((flags & onlyIncreaseInSize) != 0)
  68696. scale = jmax (scale, 1.0);
  68697. w *= scale;
  68698. h *= scale;
  68699. if ((flags & xLeft) != 0)
  68700. x = dx;
  68701. else if ((flags & xRight) != 0)
  68702. x = dx + dw - w;
  68703. else
  68704. x = dx + (dw - w) * 0.5;
  68705. if ((flags & yTop) != 0)
  68706. y = dy;
  68707. else if ((flags & yBottom) != 0)
  68708. y = dy + dh - h;
  68709. else
  68710. y = dy + (dh - h) * 0.5;
  68711. }
  68712. }
  68713. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  68714. float w, float h,
  68715. const float dx, const float dy,
  68716. const float dw, const float dh) const throw()
  68717. {
  68718. if (w == 0 || h == 0)
  68719. return AffineTransform::identity;
  68720. const float scaleX = dw / w;
  68721. const float scaleY = dh / h;
  68722. if ((flags & stretchToFit) != 0)
  68723. return AffineTransform::translation (-x, -y)
  68724. .scaled (scaleX, scaleY)
  68725. .translated (dx, dy);
  68726. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  68727. : jmin (scaleX, scaleY);
  68728. if ((flags & onlyReduceInSize) != 0)
  68729. scale = jmin (scale, 1.0f);
  68730. if ((flags & onlyIncreaseInSize) != 0)
  68731. scale = jmax (scale, 1.0f);
  68732. w *= scale;
  68733. h *= scale;
  68734. float newX = dx;
  68735. if ((flags & xRight) != 0)
  68736. newX += dw - w; // right
  68737. else if ((flags & xLeft) == 0)
  68738. newX += (dw - w) / 2.0f; // centre
  68739. float newY = dy;
  68740. if ((flags & yBottom) != 0)
  68741. newY += dh - h; // bottom
  68742. else if ((flags & yTop) == 0)
  68743. newY += (dh - h) / 2.0f; // centre
  68744. return AffineTransform::translation (-x, -y)
  68745. .scaled (scale, scale)
  68746. .translated (newX, newY);
  68747. }
  68748. END_JUCE_NAMESPACE
  68749. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  68750. /*** Start of inlined file: juce_Drawable.cpp ***/
  68751. BEGIN_JUCE_NAMESPACE
  68752. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  68753. const AffineTransform& transform_,
  68754. const float opacity_) throw()
  68755. : g (g_),
  68756. transform (transform_),
  68757. opacity (opacity_)
  68758. {
  68759. }
  68760. Drawable::Drawable()
  68761. : parent (0)
  68762. {
  68763. }
  68764. Drawable::~Drawable()
  68765. {
  68766. }
  68767. void Drawable::draw (Graphics& g, const float opacity, const AffineTransform& transform) const
  68768. {
  68769. render (RenderingContext (g, transform, opacity));
  68770. }
  68771. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  68772. {
  68773. draw (g, opacity, AffineTransform::translation (x, y));
  68774. }
  68775. void Drawable::drawWithin (Graphics& g,
  68776. const int destX,
  68777. const int destY,
  68778. const int destW,
  68779. const int destH,
  68780. const RectanglePlacement& placement,
  68781. const float opacity) const
  68782. {
  68783. if (destW > 0 && destH > 0)
  68784. {
  68785. Rectangle<float> bounds (getBounds());
  68786. draw (g, opacity,
  68787. placement.getTransformToFit (bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
  68788. (float) destX, (float) destY,
  68789. (float) destW, (float) destH));
  68790. }
  68791. }
  68792. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  68793. {
  68794. Drawable* result = 0;
  68795. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  68796. if (image.isValid())
  68797. {
  68798. DrawableImage* const di = new DrawableImage();
  68799. di->setImage (image);
  68800. result = di;
  68801. }
  68802. else
  68803. {
  68804. const String asString (String::createStringFromData (data, (int) numBytes));
  68805. XmlDocument doc (asString);
  68806. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  68807. if (outer != 0 && outer->hasTagName ("svg"))
  68808. {
  68809. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  68810. if (svg != 0)
  68811. result = Drawable::createFromSVG (*svg);
  68812. }
  68813. }
  68814. return result;
  68815. }
  68816. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  68817. {
  68818. MemoryOutputStream mo;
  68819. mo.writeFromInputStream (dataSource, -1);
  68820. return createFromImageData (mo.getData(), mo.getDataSize());
  68821. }
  68822. Drawable* Drawable::createFromImageFile (const File& file)
  68823. {
  68824. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  68825. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  68826. }
  68827. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  68828. {
  68829. return createChildFromValueTree (0, tree, imageProvider);
  68830. }
  68831. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  68832. {
  68833. const Identifier type (tree.getType());
  68834. Drawable* d = 0;
  68835. if (type == DrawablePath::valueTreeType)
  68836. d = new DrawablePath();
  68837. else if (type == DrawableComposite::valueTreeType)
  68838. d = new DrawableComposite();
  68839. else if (type == DrawableImage::valueTreeType)
  68840. d = new DrawableImage();
  68841. else if (type == DrawableText::valueTreeType)
  68842. d = new DrawableText();
  68843. if (d != 0)
  68844. {
  68845. d->parent = parent;
  68846. d->refreshFromValueTree (tree, imageProvider);
  68847. }
  68848. return d;
  68849. }
  68850. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  68851. const Identifier Drawable::ValueTreeWrapperBase::type ("type");
  68852. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint1 ("point1");
  68853. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint2 ("point2");
  68854. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint3 ("point3");
  68855. const Identifier Drawable::ValueTreeWrapperBase::colour ("colour");
  68856. const Identifier Drawable::ValueTreeWrapperBase::radial ("radial");
  68857. const Identifier Drawable::ValueTreeWrapperBase::colours ("colours");
  68858. const Identifier Drawable::ValueTreeWrapperBase::imageId ("imageId");
  68859. const Identifier Drawable::ValueTreeWrapperBase::imageOpacity ("imageOpacity");
  68860. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  68861. : state (state_)
  68862. {
  68863. }
  68864. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  68865. {
  68866. }
  68867. const String Drawable::ValueTreeWrapperBase::getID() const
  68868. {
  68869. return state [idProperty];
  68870. }
  68871. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  68872. {
  68873. if (newID.isEmpty())
  68874. state.removeProperty (idProperty, undoManager);
  68875. else
  68876. state.setProperty (idProperty, newID, undoManager);
  68877. }
  68878. const FillType Drawable::ValueTreeWrapperBase::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2, RelativePoint* const gp3,
  68879. RelativeCoordinate::NamedCoordinateFinder* const nameFinder, ImageProvider* imageProvider)
  68880. {
  68881. const String newType (v[type].toString());
  68882. if (newType == "solid")
  68883. {
  68884. const String colourString (v [colour].toString());
  68885. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  68886. : (uint32) colourString.getHexValue32()));
  68887. }
  68888. else if (newType == "gradient")
  68889. {
  68890. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]), p3 (v [gradientPoint3]);
  68891. ColourGradient g;
  68892. if (gp1 != 0) *gp1 = p1;
  68893. if (gp2 != 0) *gp2 = p2;
  68894. if (gp3 != 0) *gp3 = p3;
  68895. g.point1 = p1.resolve (nameFinder);
  68896. g.point2 = p2.resolve (nameFinder);
  68897. g.isRadial = v[radial];
  68898. StringArray colourSteps;
  68899. colourSteps.addTokens (v[colours].toString(), false);
  68900. for (int i = 0; i < colourSteps.size() / 2; ++i)
  68901. g.addColour (colourSteps[i * 2].getDoubleValue(),
  68902. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  68903. FillType fillType (g);
  68904. if (g.isRadial)
  68905. {
  68906. const Point<float> point3 (p3.resolve (nameFinder));
  68907. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  68908. g.point1.getY() + g.point1.getX() - g.point2.getX());
  68909. fillType.transform = AffineTransform::fromTargetPoints (g.point1.getX(), g.point1.getY(), g.point1.getX(), g.point1.getY(),
  68910. g.point2.getX(), g.point2.getY(), g.point2.getX(), g.point2.getY(),
  68911. point3Source.getX(), point3Source.getY(), point3.getX(), point3.getY());
  68912. }
  68913. return fillType;
  68914. }
  68915. else if (newType == "image")
  68916. {
  68917. Image im;
  68918. if (imageProvider != 0)
  68919. im = imageProvider->getImageForIdentifier (v[imageId]);
  68920. FillType f (im, AffineTransform::identity);
  68921. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  68922. return f;
  68923. }
  68924. jassertfalse;
  68925. return FillType();
  68926. }
  68927. static const Point<float> calcThirdGradientPoint (const FillType& fillType)
  68928. {
  68929. const ColourGradient& g = *fillType.gradient;
  68930. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  68931. g.point1.getY() + g.point1.getX() - g.point2.getX());
  68932. return point3Source.transformedBy (fillType.transform);
  68933. }
  68934. void Drawable::ValueTreeWrapperBase::writeFillType (ValueTree& v, const FillType& fillType,
  68935. const RelativePoint* const gp1, const RelativePoint* const gp2, const RelativePoint* gp3,
  68936. ImageProvider* imageProvider, UndoManager* const undoManager)
  68937. {
  68938. if (fillType.isColour())
  68939. {
  68940. v.setProperty (type, "solid", undoManager);
  68941. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  68942. }
  68943. else if (fillType.isGradient())
  68944. {
  68945. v.setProperty (type, "gradient", undoManager);
  68946. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  68947. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  68948. v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : calcThirdGradientPoint (fillType).toString(), undoManager);
  68949. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  68950. String s;
  68951. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  68952. s << ' ' << fillType.gradient->getColourPosition (i)
  68953. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  68954. v.setProperty (colours, s.trimStart(), undoManager);
  68955. }
  68956. else if (fillType.isTiledImage())
  68957. {
  68958. v.setProperty (type, "image", undoManager);
  68959. if (imageProvider != 0)
  68960. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  68961. if (fillType.getOpacity() < 1.0f)
  68962. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  68963. else
  68964. v.removeProperty (imageOpacity, undoManager);
  68965. }
  68966. else
  68967. {
  68968. jassertfalse;
  68969. }
  68970. }
  68971. END_JUCE_NAMESPACE
  68972. /*** End of inlined file: juce_Drawable.cpp ***/
  68973. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  68974. BEGIN_JUCE_NAMESPACE
  68975. DrawableComposite::DrawableComposite()
  68976. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f))
  68977. {
  68978. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  68979. RelativeCoordinate (100.0),
  68980. RelativeCoordinate (0.0),
  68981. RelativeCoordinate (100.0)));
  68982. }
  68983. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  68984. {
  68985. bounds = other.bounds;
  68986. for (int i = 0; i < other.drawables.size(); ++i)
  68987. drawables.add (other.drawables.getUnchecked(i)->createCopy());
  68988. markersX.addCopiesOf (other.markersX);
  68989. markersY.addCopiesOf (other.markersY);
  68990. }
  68991. DrawableComposite::~DrawableComposite()
  68992. {
  68993. }
  68994. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  68995. {
  68996. if (drawable != 0)
  68997. {
  68998. jassert (! drawables.contains (drawable)); // trying to add a drawable that's already in here!
  68999. jassert (drawable->parent == 0); // A drawable can only live inside one parent at a time!
  69000. drawables.insert (index, drawable);
  69001. drawable->parent = this;
  69002. }
  69003. }
  69004. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  69005. {
  69006. insertDrawable (drawable.createCopy(), index);
  69007. }
  69008. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  69009. {
  69010. drawables.remove (index, deleteDrawable);
  69011. }
  69012. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  69013. {
  69014. for (int i = drawables.size(); --i >= 0;)
  69015. if (drawables.getUnchecked(i)->getName() == name)
  69016. return drawables.getUnchecked(i);
  69017. return 0;
  69018. }
  69019. void DrawableComposite::bringToFront (const int index)
  69020. {
  69021. if (index >= 0 && index < drawables.size() - 1)
  69022. drawables.move (index, -1);
  69023. }
  69024. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  69025. {
  69026. bounds = newBoundingBox;
  69027. }
  69028. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  69029. : name (other.name), position (other.position)
  69030. {
  69031. }
  69032. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  69033. : name (name_), position (position_)
  69034. {
  69035. }
  69036. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  69037. {
  69038. return name != other.name || position != other.position;
  69039. }
  69040. const char* const DrawableComposite::contentLeftMarkerName ("left");
  69041. const char* const DrawableComposite::contentRightMarkerName ("right");
  69042. const char* const DrawableComposite::contentTopMarkerName ("top");
  69043. const char* const DrawableComposite::contentBottomMarkerName ("bottom");
  69044. const RelativeRectangle DrawableComposite::getContentArea() const
  69045. {
  69046. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  69047. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  69048. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  69049. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  69050. }
  69051. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69052. {
  69053. setMarker (contentLeftMarkerName, true, newArea.left);
  69054. setMarker (contentRightMarkerName, true, newArea.right);
  69055. setMarker (contentTopMarkerName, false, newArea.top);
  69056. setMarker (contentBottomMarkerName, false, newArea.bottom);
  69057. }
  69058. void DrawableComposite::resetBoundingBoxToContentArea()
  69059. {
  69060. const RelativeRectangle content (getContentArea());
  69061. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69062. RelativePoint (content.right, content.top),
  69063. RelativePoint (content.left, content.bottom)));
  69064. }
  69065. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69066. {
  69067. const Rectangle<float> bounds (getUntransformedBounds (false));
  69068. setContentArea (RelativeRectangle (RelativeCoordinate (bounds.getX()),
  69069. RelativeCoordinate (bounds.getRight()),
  69070. RelativeCoordinate (bounds.getY()),
  69071. RelativeCoordinate (bounds.getBottom())));
  69072. resetBoundingBoxToContentArea();
  69073. }
  69074. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  69075. {
  69076. return (xAxis ? markersX : markersY).size();
  69077. }
  69078. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  69079. {
  69080. return (xAxis ? markersX : markersY) [index];
  69081. }
  69082. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  69083. {
  69084. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  69085. for (int i = 0; i < markers.size(); ++i)
  69086. {
  69087. Marker* const m = markers.getUnchecked(i);
  69088. if (m->name == name)
  69089. {
  69090. if (m->position != position)
  69091. {
  69092. m->position = position;
  69093. invalidatePoints();
  69094. }
  69095. return;
  69096. }
  69097. }
  69098. (xAxis ? markersX : markersY).add (new Marker (name, position));
  69099. invalidatePoints();
  69100. }
  69101. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  69102. {
  69103. jassert (index >= 2);
  69104. if (index >= 2)
  69105. (xAxis ? markersX : markersY).remove (index);
  69106. }
  69107. const AffineTransform DrawableComposite::calculateTransform() const
  69108. {
  69109. Point<float> resolved[3];
  69110. bounds.resolveThreePoints (resolved, parent);
  69111. const Rectangle<float> content (getContentArea().resolve (parent));
  69112. return AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  69113. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  69114. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY());
  69115. }
  69116. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  69117. {
  69118. if (drawables.size() > 0 && context.opacity > 0)
  69119. {
  69120. if (context.opacity >= 1.0f || drawables.size() == 1)
  69121. {
  69122. Drawable::RenderingContext contextCopy (context);
  69123. contextCopy.transform = calculateTransform().followedBy (context.transform);
  69124. for (int i = 0; i < drawables.size(); ++i)
  69125. drawables.getUnchecked(i)->render (contextCopy);
  69126. }
  69127. else
  69128. {
  69129. // To correctly render a whole composite layer with an overall transparency,
  69130. // we need to render everything opaquely into a temp buffer, then blend that
  69131. // with the target opacity...
  69132. const Rectangle<int> clipBounds (context.g.getClipBounds());
  69133. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  69134. {
  69135. Graphics tempG (tempImage);
  69136. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  69137. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  69138. render (tempContext);
  69139. }
  69140. context.g.setOpacity (context.opacity);
  69141. context.g.drawImageAt (tempImage, clipBounds.getX(), clipBounds.getY());
  69142. }
  69143. }
  69144. }
  69145. const RelativeCoordinate DrawableComposite::findNamedCoordinate (const String& objectName, const String& edge) const
  69146. {
  69147. if (objectName == RelativeCoordinate::Strings::parent)
  69148. {
  69149. if (edge == RelativeCoordinate::Strings::right || edge == RelativeCoordinate::Strings::bottom)
  69150. {
  69151. jassertfalse; // a Drawable doesn't have a fixed right-hand or bottom edge - use a marker instead if you need a point of reference.
  69152. return RelativeCoordinate (100.0);
  69153. }
  69154. }
  69155. int i;
  69156. for (i = 0; i < markersX.size(); ++i)
  69157. {
  69158. Marker* const m = markersX.getUnchecked(i);
  69159. if (m->name == objectName)
  69160. return m->position;
  69161. }
  69162. for (i = 0; i < markersY.size(); ++i)
  69163. {
  69164. Marker* const m = markersY.getUnchecked(i);
  69165. if (m->name == objectName)
  69166. return m->position;
  69167. }
  69168. return RelativeCoordinate();
  69169. }
  69170. const Rectangle<float> DrawableComposite::getUntransformedBounds (const bool includeMarkers) const
  69171. {
  69172. Rectangle<float> bounds;
  69173. int i;
  69174. for (i = 0; i < drawables.size(); ++i)
  69175. bounds = bounds.getUnion (drawables.getUnchecked(i)->getBounds());
  69176. if (includeMarkers)
  69177. {
  69178. if (markersX.size() > 0)
  69179. {
  69180. float minX = std::numeric_limits<float>::max();
  69181. float maxX = std::numeric_limits<float>::min();
  69182. for (i = markersX.size(); --i >= 0;)
  69183. {
  69184. const Marker* m = markersX.getUnchecked(i);
  69185. const float pos = (float) m->position.resolve (this);
  69186. minX = jmin (minX, pos);
  69187. maxX = jmax (maxX, pos);
  69188. }
  69189. if (minX <= maxX)
  69190. {
  69191. if (bounds.getHeight() > 0)
  69192. {
  69193. minX = jmin (minX, bounds.getX());
  69194. maxX = jmax (maxX, bounds.getRight());
  69195. }
  69196. bounds.setLeft (minX);
  69197. bounds.setWidth (maxX - minX);
  69198. }
  69199. }
  69200. if (markersY.size() > 0)
  69201. {
  69202. float minY = std::numeric_limits<float>::max();
  69203. float maxY = std::numeric_limits<float>::min();
  69204. for (i = markersY.size(); --i >= 0;)
  69205. {
  69206. const Marker* m = markersY.getUnchecked(i);
  69207. const float pos = (float) m->position.resolve (this);
  69208. minY = jmin (minY, pos);
  69209. maxY = jmax (maxY, pos);
  69210. }
  69211. if (minY <= maxY)
  69212. {
  69213. if (bounds.getHeight() > 0)
  69214. {
  69215. minY = jmin (minY, bounds.getY());
  69216. maxY = jmax (maxY, bounds.getBottom());
  69217. }
  69218. bounds.setTop (minY);
  69219. bounds.setHeight (maxY - minY);
  69220. }
  69221. }
  69222. }
  69223. return bounds;
  69224. }
  69225. const Rectangle<float> DrawableComposite::getBounds() const
  69226. {
  69227. return getUntransformedBounds (true).transformed (calculateTransform());
  69228. }
  69229. bool DrawableComposite::hitTest (float x, float y) const
  69230. {
  69231. calculateTransform().inverted().transformPoint (x, y);
  69232. for (int i = 0; i < drawables.size(); ++i)
  69233. if (drawables.getUnchecked(i)->hitTest (x, y))
  69234. return true;
  69235. return false;
  69236. }
  69237. Drawable* DrawableComposite::createCopy() const
  69238. {
  69239. return new DrawableComposite (*this);
  69240. }
  69241. void DrawableComposite::invalidatePoints()
  69242. {
  69243. for (int i = 0; i < drawables.size(); ++i)
  69244. drawables.getUnchecked(i)->invalidatePoints();
  69245. }
  69246. const Identifier DrawableComposite::valueTreeType ("Group");
  69247. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  69248. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  69249. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69250. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  69251. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  69252. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  69253. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  69254. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  69255. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  69256. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69257. : ValueTreeWrapperBase (state_)
  69258. {
  69259. jassert (state.hasType (valueTreeType));
  69260. }
  69261. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  69262. {
  69263. return state.getChildWithName (childGroupTag);
  69264. }
  69265. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  69266. {
  69267. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  69268. }
  69269. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  69270. {
  69271. return getChildList().getNumChildren();
  69272. }
  69273. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  69274. {
  69275. return getChildList().getChild (index);
  69276. }
  69277. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  69278. {
  69279. if (getID() == objectId)
  69280. return state;
  69281. if (! recursive)
  69282. {
  69283. return getChildList().getChildWithProperty (idProperty, objectId);
  69284. }
  69285. else
  69286. {
  69287. const ValueTree childList (getChildList());
  69288. for (int i = getNumDrawables(); --i >= 0;)
  69289. {
  69290. const ValueTree& child = childList.getChild (i);
  69291. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  69292. return child;
  69293. if (child.hasType (DrawableComposite::valueTreeType))
  69294. {
  69295. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  69296. if (v.isValid())
  69297. return v;
  69298. }
  69299. }
  69300. return ValueTree::invalid;
  69301. }
  69302. }
  69303. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  69304. {
  69305. return getChildList().indexOf (item);
  69306. }
  69307. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  69308. {
  69309. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  69310. }
  69311. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  69312. {
  69313. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  69314. }
  69315. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  69316. {
  69317. getChildList().removeChild (child, undoManager);
  69318. }
  69319. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  69320. {
  69321. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  69322. state.getProperty (topRight, "100, 0"),
  69323. state.getProperty (bottomLeft, "0, 100"));
  69324. }
  69325. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69326. {
  69327. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69328. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69329. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69330. }
  69331. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  69332. {
  69333. const RelativeRectangle content (getContentArea());
  69334. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69335. RelativePoint (content.right, content.top),
  69336. RelativePoint (content.left, content.bottom)), undoManager);
  69337. }
  69338. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  69339. {
  69340. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  69341. getMarker (true, getMarkerState (true, 1)).position,
  69342. getMarker (false, getMarkerState (false, 0)).position,
  69343. getMarker (false, getMarkerState (false, 1)).position);
  69344. }
  69345. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  69346. {
  69347. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  69348. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  69349. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  69350. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  69351. }
  69352. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  69353. {
  69354. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  69355. }
  69356. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  69357. {
  69358. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  69359. }
  69360. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  69361. {
  69362. return getMarkerList (xAxis).getNumChildren();
  69363. }
  69364. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  69365. {
  69366. return getMarkerList (xAxis).getChild (index);
  69367. }
  69368. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  69369. {
  69370. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  69371. }
  69372. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  69373. {
  69374. return state.isAChildOf (getMarkerList (xAxis));
  69375. }
  69376. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  69377. {
  69378. jassert (containsMarker (xAxis, state));
  69379. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString(), xAxis));
  69380. }
  69381. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  69382. {
  69383. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  69384. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  69385. if (marker.isValid())
  69386. {
  69387. marker.setProperty (posProperty, m.position.toString(), undoManager);
  69388. }
  69389. else
  69390. {
  69391. marker = ValueTree (markerTag);
  69392. marker.setProperty (nameProperty, m.name, 0);
  69393. marker.setProperty (posProperty, m.position.toString(), 0);
  69394. markerList.addChild (marker, -1, undoManager);
  69395. }
  69396. }
  69397. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  69398. {
  69399. if (state [nameProperty].toString() != contentLeftMarkerName
  69400. && state [nameProperty].toString() != contentRightMarkerName
  69401. && state [nameProperty].toString() != contentTopMarkerName
  69402. && state [nameProperty].toString() != contentBottomMarkerName)
  69403. return getMarkerList (xAxis).removeChild (state, undoManager);
  69404. }
  69405. const Rectangle<float> DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69406. {
  69407. const ValueTreeWrapper wrapper (tree);
  69408. setName (wrapper.getID());
  69409. Rectangle<float> damage;
  69410. bool redrawAll = false;
  69411. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  69412. if (bounds != newBounds)
  69413. {
  69414. redrawAll = true;
  69415. damage = getBounds();
  69416. bounds = newBounds;
  69417. }
  69418. const int numMarkersX = wrapper.getNumMarkers (true);
  69419. const int numMarkersY = wrapper.getNumMarkers (false);
  69420. // Remove deleted markers...
  69421. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  69422. {
  69423. if (! redrawAll)
  69424. {
  69425. redrawAll = true;
  69426. damage = getBounds();
  69427. }
  69428. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  69429. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  69430. }
  69431. // Update markers and add new ones..
  69432. int i;
  69433. for (i = 0; i < numMarkersX; ++i)
  69434. {
  69435. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  69436. Marker* m = markersX[i];
  69437. if (m == 0 || newMarker != *m)
  69438. {
  69439. if (! redrawAll)
  69440. {
  69441. redrawAll = true;
  69442. damage = getBounds();
  69443. }
  69444. if (m == 0)
  69445. markersX.add (new Marker (newMarker));
  69446. else
  69447. *m = newMarker;
  69448. }
  69449. }
  69450. for (i = 0; i < numMarkersY; ++i)
  69451. {
  69452. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  69453. Marker* m = markersY[i];
  69454. if (m == 0 || newMarker != *m)
  69455. {
  69456. if (! redrawAll)
  69457. {
  69458. redrawAll = true;
  69459. damage = getBounds();
  69460. }
  69461. if (m == 0)
  69462. markersY.add (new Marker (newMarker));
  69463. else
  69464. *m = newMarker;
  69465. }
  69466. }
  69467. // Remove deleted drawables..
  69468. for (i = drawables.size(); --i >= wrapper.getNumDrawables();)
  69469. {
  69470. Drawable* const d = drawables.getUnchecked(i);
  69471. if (! redrawAll)
  69472. damage = damage.getUnion (d->getBounds());
  69473. d->parent = 0;
  69474. drawables.remove (i);
  69475. }
  69476. // Update drawables and add new ones..
  69477. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  69478. {
  69479. const ValueTree newDrawable (wrapper.getDrawableState (i));
  69480. Drawable* d = drawables[i];
  69481. if (d != 0)
  69482. {
  69483. if (newDrawable.hasType (d->getValueTreeType()))
  69484. {
  69485. const Rectangle<float> area (d->refreshFromValueTree (newDrawable, imageProvider));
  69486. if (! redrawAll)
  69487. damage = damage.getUnion (area);
  69488. }
  69489. else
  69490. {
  69491. if (! redrawAll)
  69492. damage = damage.getUnion (d->getBounds());
  69493. d = createChildFromValueTree (this, newDrawable, imageProvider);
  69494. drawables.set (i, d);
  69495. if (! redrawAll)
  69496. damage = damage.getUnion (d->getBounds());
  69497. }
  69498. }
  69499. else
  69500. {
  69501. d = createChildFromValueTree (this, newDrawable, imageProvider);
  69502. drawables.set (i, d);
  69503. if (! redrawAll)
  69504. damage = damage.getUnion (d->getBounds());
  69505. }
  69506. }
  69507. if (redrawAll)
  69508. damage = damage.getUnion (getBounds());
  69509. else if (! damage.isEmpty())
  69510. damage = damage.transformed (calculateTransform());
  69511. return damage;
  69512. }
  69513. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  69514. {
  69515. ValueTree tree (valueTreeType);
  69516. ValueTreeWrapper v (tree);
  69517. v.setID (getName(), 0);
  69518. v.setBoundingBox (bounds, 0);
  69519. int i;
  69520. for (i = 0; i < drawables.size(); ++i)
  69521. v.addDrawable (drawables.getUnchecked(i)->createValueTree (imageProvider), -1, 0);
  69522. for (i = 0; i < markersX.size(); ++i)
  69523. v.setMarker (true, *markersX.getUnchecked(i), 0);
  69524. for (i = 0; i < markersY.size(); ++i)
  69525. v.setMarker (false, *markersY.getUnchecked(i), 0);
  69526. return tree;
  69527. }
  69528. END_JUCE_NAMESPACE
  69529. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  69530. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  69531. BEGIN_JUCE_NAMESPACE
  69532. DrawableImage::DrawableImage()
  69533. : image (0),
  69534. opacity (1.0f),
  69535. overlayColour (0x00000000)
  69536. {
  69537. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  69538. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  69539. }
  69540. DrawableImage::DrawableImage (const DrawableImage& other)
  69541. : image (other.image),
  69542. opacity (other.opacity),
  69543. overlayColour (other.overlayColour),
  69544. bounds (other.bounds)
  69545. {
  69546. }
  69547. DrawableImage::~DrawableImage()
  69548. {
  69549. }
  69550. void DrawableImage::setImage (const Image& imageToUse)
  69551. {
  69552. image = imageToUse;
  69553. if (image.isValid())
  69554. {
  69555. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  69556. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  69557. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  69558. }
  69559. }
  69560. void DrawableImage::setOpacity (const float newOpacity)
  69561. {
  69562. opacity = newOpacity;
  69563. }
  69564. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  69565. {
  69566. overlayColour = newOverlayColour;
  69567. }
  69568. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  69569. {
  69570. bounds = newBounds;
  69571. }
  69572. const AffineTransform DrawableImage::calculateTransform() const
  69573. {
  69574. if (image.isNull())
  69575. return AffineTransform::identity;
  69576. Point<float> resolved[3];
  69577. bounds.resolveThreePoints (resolved, parent);
  69578. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  69579. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  69580. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  69581. tr.getX(), tr.getY(),
  69582. bl.getX(), bl.getY());
  69583. }
  69584. void DrawableImage::render (const Drawable::RenderingContext& context) const
  69585. {
  69586. if (image.isValid())
  69587. {
  69588. const AffineTransform t (calculateTransform().followedBy (context.transform));
  69589. if (opacity > 0.0f && ! overlayColour.isOpaque())
  69590. {
  69591. context.g.setOpacity (context.opacity * opacity);
  69592. context.g.drawImageTransformed (image, t, false);
  69593. }
  69594. if (! overlayColour.isTransparent())
  69595. {
  69596. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  69597. context.g.drawImageTransformed (image, t, true);
  69598. }
  69599. }
  69600. }
  69601. const Rectangle<float> DrawableImage::getBounds() const
  69602. {
  69603. if (image.isNull())
  69604. return Rectangle<float>();
  69605. return bounds.getBounds (parent);
  69606. }
  69607. bool DrawableImage::hitTest (float x, float y) const
  69608. {
  69609. if (image.isNull())
  69610. return false;
  69611. calculateTransform().inverted().transformPoint (x, y);
  69612. const int ix = roundToInt (x);
  69613. const int iy = roundToInt (y);
  69614. return ix >= 0
  69615. && iy >= 0
  69616. && ix < image.getWidth()
  69617. && iy < image.getHeight()
  69618. && image.getPixelAt (ix, iy).getAlpha() >= 127;
  69619. }
  69620. Drawable* DrawableImage::createCopy() const
  69621. {
  69622. return new DrawableImage (*this);
  69623. }
  69624. void DrawableImage::invalidatePoints()
  69625. {
  69626. }
  69627. const Identifier DrawableImage::valueTreeType ("Image");
  69628. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  69629. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  69630. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  69631. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  69632. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  69633. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69634. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69635. : ValueTreeWrapperBase (state_)
  69636. {
  69637. jassert (state.hasType (valueTreeType));
  69638. }
  69639. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  69640. {
  69641. return state [image];
  69642. }
  69643. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  69644. {
  69645. return state.getPropertyAsValue (image, undoManager);
  69646. }
  69647. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  69648. {
  69649. state.setProperty (image, newIdentifier, undoManager);
  69650. }
  69651. float DrawableImage::ValueTreeWrapper::getOpacity() const
  69652. {
  69653. return (float) state.getProperty (opacity, 1.0);
  69654. }
  69655. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  69656. {
  69657. if (! state.hasProperty (opacity))
  69658. state.setProperty (opacity, 1.0, undoManager);
  69659. return state.getPropertyAsValue (opacity, undoManager);
  69660. }
  69661. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  69662. {
  69663. state.setProperty (opacity, newOpacity, undoManager);
  69664. }
  69665. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  69666. {
  69667. return Colour (state [overlay].toString().getHexValue32());
  69668. }
  69669. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  69670. {
  69671. if (newColour.isTransparent())
  69672. state.removeProperty (overlay, undoManager);
  69673. else
  69674. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  69675. }
  69676. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  69677. {
  69678. return state.getPropertyAsValue (overlay, undoManager);
  69679. }
  69680. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  69681. {
  69682. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  69683. state.getProperty (topRight, "100, 0"),
  69684. state.getProperty (bottomLeft, "0, 100"));
  69685. }
  69686. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69687. {
  69688. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69689. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69690. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69691. }
  69692. const Rectangle<float> DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69693. {
  69694. const ValueTreeWrapper controller (tree);
  69695. setName (controller.getID());
  69696. const float newOpacity = controller.getOpacity();
  69697. const Colour newOverlayColour (controller.getOverlayColour());
  69698. Image newImage;
  69699. const var imageIdentifier (controller.getImageIdentifier());
  69700. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  69701. if (imageProvider != 0)
  69702. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  69703. const RelativeParallelogram newBounds (controller.getBoundingBox());
  69704. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage || bounds != newBounds)
  69705. {
  69706. const Rectangle<float> damage (getBounds());
  69707. opacity = newOpacity;
  69708. overlayColour = newOverlayColour;
  69709. bounds = newBounds;
  69710. image = newImage;
  69711. return damage.getUnion (getBounds());
  69712. }
  69713. return Rectangle<float>();
  69714. }
  69715. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  69716. {
  69717. ValueTree tree (valueTreeType);
  69718. ValueTreeWrapper v (tree);
  69719. v.setID (getName(), 0);
  69720. v.setOpacity (opacity, 0);
  69721. v.setOverlayColour (overlayColour, 0);
  69722. v.setBoundingBox (bounds, 0);
  69723. if (image.isValid())
  69724. {
  69725. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  69726. if (imageProvider != 0)
  69727. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  69728. }
  69729. return tree;
  69730. }
  69731. END_JUCE_NAMESPACE
  69732. /*** End of inlined file: juce_DrawableImage.cpp ***/
  69733. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  69734. BEGIN_JUCE_NAMESPACE
  69735. DrawablePath::DrawablePath()
  69736. : mainFill (Colours::black),
  69737. strokeFill (Colours::black),
  69738. strokeType (0.0f),
  69739. pathNeedsUpdating (true),
  69740. strokeNeedsUpdating (true)
  69741. {
  69742. }
  69743. DrawablePath::DrawablePath (const DrawablePath& other)
  69744. : mainFill (other.mainFill),
  69745. strokeFill (other.strokeFill),
  69746. strokeType (other.strokeType),
  69747. pathNeedsUpdating (true),
  69748. strokeNeedsUpdating (true)
  69749. {
  69750. if (other.relativePath != 0)
  69751. relativePath = new RelativePointPath (*other.relativePath);
  69752. else
  69753. path = other.path;
  69754. }
  69755. DrawablePath::~DrawablePath()
  69756. {
  69757. }
  69758. void DrawablePath::setPath (const Path& newPath)
  69759. {
  69760. path = newPath;
  69761. strokeNeedsUpdating = true;
  69762. }
  69763. void DrawablePath::setFill (const FillType& newFill)
  69764. {
  69765. mainFill = newFill;
  69766. }
  69767. void DrawablePath::setStrokeFill (const FillType& newFill)
  69768. {
  69769. strokeFill = newFill;
  69770. }
  69771. void DrawablePath::setStrokeType (const PathStrokeType& newStrokeType)
  69772. {
  69773. strokeType = newStrokeType;
  69774. strokeNeedsUpdating = true;
  69775. }
  69776. void DrawablePath::setStrokeThickness (const float newThickness)
  69777. {
  69778. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  69779. }
  69780. void DrawablePath::updatePath() const
  69781. {
  69782. if (pathNeedsUpdating)
  69783. {
  69784. pathNeedsUpdating = false;
  69785. if (relativePath != 0)
  69786. {
  69787. path.clear();
  69788. relativePath->createPath (path, parent);
  69789. strokeNeedsUpdating = true;
  69790. }
  69791. }
  69792. }
  69793. void DrawablePath::updateStroke() const
  69794. {
  69795. if (strokeNeedsUpdating)
  69796. {
  69797. strokeNeedsUpdating = false;
  69798. updatePath();
  69799. stroke.clear();
  69800. strokeType.createStrokedPath (stroke, path, AffineTransform::identity, 4.0f);
  69801. }
  69802. }
  69803. const Path& DrawablePath::getPath() const
  69804. {
  69805. updatePath();
  69806. return path;
  69807. }
  69808. const Path& DrawablePath::getStrokePath() const
  69809. {
  69810. updateStroke();
  69811. return stroke;
  69812. }
  69813. bool DrawablePath::isStrokeVisible() const throw()
  69814. {
  69815. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  69816. }
  69817. void DrawablePath::invalidatePoints()
  69818. {
  69819. pathNeedsUpdating = true;
  69820. strokeNeedsUpdating = true;
  69821. }
  69822. void DrawablePath::render (const Drawable::RenderingContext& context) const
  69823. {
  69824. {
  69825. FillType f (mainFill);
  69826. if (f.isGradient())
  69827. f.gradient->multiplyOpacity (context.opacity);
  69828. f.transform = f.transform.followedBy (context.transform);
  69829. context.g.setFillType (f);
  69830. context.g.fillPath (getPath(), context.transform);
  69831. }
  69832. if (isStrokeVisible())
  69833. {
  69834. FillType f (strokeFill);
  69835. if (f.isGradient())
  69836. f.gradient->multiplyOpacity (context.opacity);
  69837. f.transform = f.transform.followedBy (context.transform);
  69838. context.g.setFillType (f);
  69839. context.g.fillPath (getStrokePath(), context.transform);
  69840. }
  69841. }
  69842. const Rectangle<float> DrawablePath::getBounds() const
  69843. {
  69844. if (isStrokeVisible())
  69845. return getStrokePath().getBounds();
  69846. else
  69847. return getPath().getBounds();
  69848. }
  69849. bool DrawablePath::hitTest (float x, float y) const
  69850. {
  69851. return getPath().contains (x, y)
  69852. || (isStrokeVisible() && getStrokePath().contains (x, y));
  69853. }
  69854. Drawable* DrawablePath::createCopy() const
  69855. {
  69856. return new DrawablePath (*this);
  69857. }
  69858. const Identifier DrawablePath::valueTreeType ("Path");
  69859. const Identifier DrawablePath::ValueTreeWrapper::fill ("Fill");
  69860. const Identifier DrawablePath::ValueTreeWrapper::stroke ("Stroke");
  69861. const Identifier DrawablePath::ValueTreeWrapper::path ("Path");
  69862. const Identifier DrawablePath::ValueTreeWrapper::jointStyle ("jointStyle");
  69863. const Identifier DrawablePath::ValueTreeWrapper::capStyle ("capStyle");
  69864. const Identifier DrawablePath::ValueTreeWrapper::strokeWidth ("strokeWidth");
  69865. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  69866. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  69867. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  69868. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  69869. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69870. : ValueTreeWrapperBase (state_)
  69871. {
  69872. jassert (state.hasType (valueTreeType));
  69873. }
  69874. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  69875. {
  69876. return state.getOrCreateChildWithName (path, 0);
  69877. }
  69878. ValueTree DrawablePath::ValueTreeWrapper::getMainFillState()
  69879. {
  69880. ValueTree v (state.getChildWithName (fill));
  69881. if (v.isValid())
  69882. return v;
  69883. setMainFill (Colours::black, 0, 0, 0, 0, 0);
  69884. return getMainFillState();
  69885. }
  69886. ValueTree DrawablePath::ValueTreeWrapper::getStrokeFillState()
  69887. {
  69888. ValueTree v (state.getChildWithName (stroke));
  69889. if (v.isValid())
  69890. return v;
  69891. setStrokeFill (Colours::black, 0, 0, 0, 0, 0);
  69892. return getStrokeFillState();
  69893. }
  69894. const FillType DrawablePath::ValueTreeWrapper::getMainFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  69895. ImageProvider* imageProvider) const
  69896. {
  69897. return readFillType (state.getChildWithName (fill), 0, 0, 0, nameFinder, imageProvider);
  69898. }
  69899. void DrawablePath::ValueTreeWrapper::setMainFill (const FillType& newFill, const RelativePoint* gp1,
  69900. const RelativePoint* gp2, const RelativePoint* gp3,
  69901. ImageProvider* imageProvider, UndoManager* undoManager)
  69902. {
  69903. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  69904. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69905. }
  69906. const FillType DrawablePath::ValueTreeWrapper::getStrokeFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  69907. ImageProvider* imageProvider) const
  69908. {
  69909. return readFillType (state.getChildWithName (stroke), 0, 0, 0, nameFinder, imageProvider);
  69910. }
  69911. void DrawablePath::ValueTreeWrapper::setStrokeFill (const FillType& newFill, const RelativePoint* gp1,
  69912. const RelativePoint* gp2, const RelativePoint* gp3,
  69913. ImageProvider* imageProvider, UndoManager* undoManager)
  69914. {
  69915. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  69916. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69917. }
  69918. const PathStrokeType DrawablePath::ValueTreeWrapper::getStrokeType() const
  69919. {
  69920. const String jointStyleString (state [jointStyle].toString());
  69921. const String capStyleString (state [capStyle].toString());
  69922. return PathStrokeType (state [strokeWidth],
  69923. jointStyleString == "curved" ? PathStrokeType::curved
  69924. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  69925. : PathStrokeType::mitered),
  69926. capStyleString == "square" ? PathStrokeType::square
  69927. : (capStyleString == "round" ? PathStrokeType::rounded
  69928. : PathStrokeType::butt));
  69929. }
  69930. void DrawablePath::ValueTreeWrapper::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  69931. {
  69932. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  69933. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  69934. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  69935. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  69936. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  69937. }
  69938. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  69939. {
  69940. return state [nonZeroWinding];
  69941. }
  69942. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  69943. {
  69944. state.setProperty (nonZeroWinding, b, undoManager);
  69945. }
  69946. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  69947. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  69948. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  69949. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  69950. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  69951. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  69952. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  69953. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  69954. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  69955. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  69956. : state (state_)
  69957. {
  69958. }
  69959. DrawablePath::ValueTreeWrapper::Element::~Element()
  69960. {
  69961. }
  69962. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  69963. {
  69964. return ValueTreeWrapper (state.getParent().getParent());
  69965. }
  69966. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  69967. {
  69968. return Element (state.getSibling (-1));
  69969. }
  69970. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  69971. {
  69972. const Identifier i (state.getType());
  69973. if (i == startSubPathElement || i == lineToElement) return 1;
  69974. if (i == quadraticToElement) return 2;
  69975. if (i == cubicToElement) return 3;
  69976. return 0;
  69977. }
  69978. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  69979. {
  69980. jassert (index >= 0 && index < getNumControlPoints());
  69981. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  69982. }
  69983. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  69984. {
  69985. jassert (index >= 0 && index < getNumControlPoints());
  69986. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  69987. }
  69988. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  69989. {
  69990. jassert (index >= 0 && index < getNumControlPoints());
  69991. return state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  69992. }
  69993. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  69994. {
  69995. const Identifier i (state.getType());
  69996. if (i == startSubPathElement)
  69997. return getControlPoint (0);
  69998. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  69999. return getPreviousElement().getEndPoint();
  70000. }
  70001. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70002. {
  70003. const Identifier i (state.getType());
  70004. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70005. if (i == quadraticToElement) return getControlPoint (1);
  70006. if (i == cubicToElement) return getControlPoint (2);
  70007. jassert (i == closeSubPathElement);
  70008. return RelativePoint();
  70009. }
  70010. float DrawablePath::ValueTreeWrapper::Element::getLength (RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  70011. {
  70012. const Identifier i (state.getType());
  70013. if (i == lineToElement || i == closeSubPathElement)
  70014. return getEndPoint().resolve (nameFinder).getDistanceFrom (getStartPoint().resolve (nameFinder));
  70015. if (i == cubicToElement)
  70016. {
  70017. Path p;
  70018. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70019. p.cubicTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder), getControlPoint (2).resolve (nameFinder));
  70020. return p.getLength();
  70021. }
  70022. if (i == quadraticToElement)
  70023. {
  70024. Path p;
  70025. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70026. p.quadraticTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder));
  70027. return p.getLength();
  70028. }
  70029. jassert (i == startSubPathElement);
  70030. return 0;
  70031. }
  70032. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70033. {
  70034. return state [mode].toString();
  70035. }
  70036. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70037. {
  70038. if (state.hasType (cubicToElement))
  70039. state.setProperty (mode, newMode, undoManager);
  70040. }
  70041. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70042. {
  70043. const Identifier i (state.getType());
  70044. if (i == quadraticToElement || i == cubicToElement)
  70045. {
  70046. ValueTree newState (lineToElement);
  70047. Element e (newState);
  70048. e.setControlPoint (0, getEndPoint(), undoManager);
  70049. state = newState;
  70050. }
  70051. }
  70052. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (RelativeCoordinate::NamedCoordinateFinder* nameFinder, UndoManager* undoManager)
  70053. {
  70054. const Identifier i (state.getType());
  70055. if (i == lineToElement || i == quadraticToElement)
  70056. {
  70057. ValueTree newState (cubicToElement);
  70058. Element e (newState);
  70059. const RelativePoint start (getStartPoint());
  70060. const RelativePoint end (getEndPoint());
  70061. const Point<float> startResolved (start.resolve (nameFinder));
  70062. const Point<float> endResolved (end.resolve (nameFinder));
  70063. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70064. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70065. e.setControlPoint (2, end, undoManager);
  70066. state = newState;
  70067. }
  70068. }
  70069. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70070. {
  70071. const Identifier i (state.getType());
  70072. if (i != startSubPathElement)
  70073. {
  70074. ValueTree newState (startSubPathElement);
  70075. Element e (newState);
  70076. e.setControlPoint (0, getEndPoint(), undoManager);
  70077. state = newState;
  70078. }
  70079. }
  70080. static const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70081. {
  70082. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70083. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70084. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70085. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70086. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70087. return newCp1 + (newCp2 - newCp1) * proportion;
  70088. }
  70089. static const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70090. {
  70091. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70092. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70093. return mid1 + (mid2 - mid1) * proportion;
  70094. }
  70095. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  70096. {
  70097. const Identifier i (state.getType());
  70098. float bestProp = 0;
  70099. if (i == cubicToElement)
  70100. {
  70101. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70102. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70103. float bestDistance = std::numeric_limits<float>::max();
  70104. for (int i = 110; --i >= 0;)
  70105. {
  70106. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70107. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70108. const float distance = centre.getDistanceFrom (targetPoint);
  70109. if (distance < bestDistance)
  70110. {
  70111. bestProp = prop;
  70112. bestDistance = distance;
  70113. }
  70114. }
  70115. }
  70116. else if (i == quadraticToElement)
  70117. {
  70118. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70119. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70120. float bestDistance = std::numeric_limits<float>::max();
  70121. for (int i = 110; --i >= 0;)
  70122. {
  70123. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70124. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70125. const float distance = centre.getDistanceFrom (targetPoint);
  70126. if (distance < bestDistance)
  70127. {
  70128. bestProp = prop;
  70129. bestDistance = distance;
  70130. }
  70131. }
  70132. }
  70133. else if (i == lineToElement)
  70134. {
  70135. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70136. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70137. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70138. }
  70139. return bestProp;
  70140. }
  70141. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, RelativeCoordinate::NamedCoordinateFinder* nameFinder, UndoManager* undoManager)
  70142. {
  70143. ValueTree newTree;
  70144. const Identifier i (state.getType());
  70145. if (i == cubicToElement)
  70146. {
  70147. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70148. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70149. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70150. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70151. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70152. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70153. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70154. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70155. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70156. setControlPoint (0, mid1, undoManager);
  70157. setControlPoint (1, newCp1, undoManager);
  70158. setControlPoint (2, newCentre, undoManager);
  70159. setModeOfEndPoint (roundedMode, undoManager);
  70160. Element newElement (newTree = ValueTree (cubicToElement));
  70161. newElement.setControlPoint (0, newCp2, 0);
  70162. newElement.setControlPoint (1, mid3, 0);
  70163. newElement.setControlPoint (2, rp4, 0);
  70164. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70165. }
  70166. else if (i == quadraticToElement)
  70167. {
  70168. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70169. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70170. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70171. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70172. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70173. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70174. setControlPoint (0, mid1, undoManager);
  70175. setControlPoint (1, newCentre, undoManager);
  70176. setModeOfEndPoint (roundedMode, undoManager);
  70177. Element newElement (newTree = ValueTree (quadraticToElement));
  70178. newElement.setControlPoint (0, mid2, 0);
  70179. newElement.setControlPoint (1, rp3, 0);
  70180. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70181. }
  70182. else if (i == lineToElement)
  70183. {
  70184. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70185. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70186. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70187. setControlPoint (0, newPoint, undoManager);
  70188. Element newElement (newTree = ValueTree (lineToElement));
  70189. newElement.setControlPoint (0, rp2, 0);
  70190. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70191. }
  70192. else if (i == closeSubPathElement)
  70193. {
  70194. }
  70195. return newTree;
  70196. }
  70197. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70198. {
  70199. state.getParent().removeChild (state, undoManager);
  70200. }
  70201. const Rectangle<float> DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70202. {
  70203. Rectangle<float> damageRect;
  70204. ValueTreeWrapper v (tree);
  70205. setName (v.getID());
  70206. bool needsRedraw = false;
  70207. const FillType newFill (v.getMainFill (parent, imageProvider));
  70208. if (mainFill != newFill)
  70209. {
  70210. needsRedraw = true;
  70211. mainFill = newFill;
  70212. }
  70213. const FillType newStrokeFill (v.getStrokeFill (parent, imageProvider));
  70214. if (strokeFill != newStrokeFill)
  70215. {
  70216. needsRedraw = true;
  70217. strokeFill = newStrokeFill;
  70218. }
  70219. const PathStrokeType newStroke (v.getStrokeType());
  70220. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  70221. Path newPath;
  70222. newRelativePath->createPath (newPath, parent);
  70223. if (! newRelativePath->containsAnyDynamicPoints())
  70224. newRelativePath = 0;
  70225. if (strokeType != newStroke || path != newPath)
  70226. {
  70227. damageRect = getBounds();
  70228. path.swapWithPath (newPath);
  70229. strokeNeedsUpdating = true;
  70230. strokeType = newStroke;
  70231. needsRedraw = true;
  70232. }
  70233. relativePath = newRelativePath;
  70234. if (needsRedraw)
  70235. damageRect = damageRect.getUnion (getBounds());
  70236. return damageRect;
  70237. }
  70238. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  70239. {
  70240. ValueTree tree (valueTreeType);
  70241. ValueTreeWrapper v (tree);
  70242. v.setID (getName(), 0);
  70243. v.setMainFill (mainFill, 0, 0, 0, imageProvider, 0);
  70244. v.setStrokeFill (strokeFill, 0, 0, 0, imageProvider, 0);
  70245. v.setStrokeType (strokeType, 0);
  70246. if (relativePath != 0)
  70247. {
  70248. relativePath->writeTo (tree, 0);
  70249. }
  70250. else
  70251. {
  70252. RelativePointPath rp (path);
  70253. rp.writeTo (tree, 0);
  70254. }
  70255. return tree;
  70256. }
  70257. END_JUCE_NAMESPACE
  70258. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70259. /*** Start of inlined file: juce_DrawableText.cpp ***/
  70260. BEGIN_JUCE_NAMESPACE
  70261. DrawableText::DrawableText()
  70262. : colour (Colours::black),
  70263. justification (Justification::centredLeft)
  70264. {
  70265. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  70266. RelativePoint (50.0f, 0.0f),
  70267. RelativePoint (0.0f, 20.0f)));
  70268. setFont (Font (15.0f), true);
  70269. }
  70270. DrawableText::DrawableText (const DrawableText& other)
  70271. : text (other.text),
  70272. font (other.font),
  70273. colour (other.colour),
  70274. justification (other.justification),
  70275. bounds (other.bounds),
  70276. fontSizeControlPoint (other.fontSizeControlPoint)
  70277. {
  70278. }
  70279. DrawableText::~DrawableText()
  70280. {
  70281. }
  70282. void DrawableText::setText (const String& newText)
  70283. {
  70284. text = newText;
  70285. }
  70286. void DrawableText::setColour (const Colour& newColour)
  70287. {
  70288. colour = newColour;
  70289. }
  70290. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  70291. {
  70292. font = newFont;
  70293. if (applySizeAndScale)
  70294. {
  70295. Point<float> corners[3];
  70296. bounds.resolveThreePoints (corners, parent);
  70297. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  70298. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  70299. }
  70300. }
  70301. void DrawableText::setJustification (const Justification& newJustification)
  70302. {
  70303. justification = newJustification;
  70304. }
  70305. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  70306. {
  70307. bounds = newBounds;
  70308. }
  70309. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  70310. {
  70311. fontSizeControlPoint = newPoint;
  70312. }
  70313. void DrawableText::render (const Drawable::RenderingContext& context) const
  70314. {
  70315. Point<float> points[3];
  70316. bounds.resolveThreePoints (points, parent);
  70317. const float w = Line<float> (points[0], points[1]).getLength();
  70318. const float h = Line<float> (points[0], points[2]).getLength();
  70319. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (parent)));
  70320. const float fontHeight = jlimit (1.0f, h, fontCoords.getY());
  70321. const float fontWidth = jlimit (0.01f, w, fontCoords.getX());
  70322. Font f (font);
  70323. f.setHeight (fontHeight);
  70324. f.setHorizontalScale (fontWidth / fontHeight);
  70325. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  70326. GlyphArrangement ga;
  70327. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  70328. ga.draw (context.g,
  70329. AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70330. w, 0, points[1].getX(), points[1].getY(),
  70331. 0, h, points[2].getX(), points[2].getY())
  70332. .followedBy (context.transform));
  70333. }
  70334. const Rectangle<float> DrawableText::getBounds() const
  70335. {
  70336. return bounds.getBounds (parent);
  70337. }
  70338. bool DrawableText::hitTest (float x, float y) const
  70339. {
  70340. Path p;
  70341. bounds.getPath (p, parent);
  70342. return p.contains (x, y);
  70343. }
  70344. Drawable* DrawableText::createCopy() const
  70345. {
  70346. return new DrawableText (*this);
  70347. }
  70348. void DrawableText::invalidatePoints()
  70349. {
  70350. }
  70351. const Identifier DrawableText::valueTreeType ("Text");
  70352. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  70353. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  70354. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  70355. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  70356. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  70357. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  70358. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70359. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  70360. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70361. : ValueTreeWrapperBase (state_)
  70362. {
  70363. jassert (state.hasType (valueTreeType));
  70364. }
  70365. const String DrawableText::ValueTreeWrapper::getText() const
  70366. {
  70367. return state [text].toString();
  70368. }
  70369. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  70370. {
  70371. state.setProperty (text, newText, undoManager);
  70372. }
  70373. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  70374. {
  70375. return state.getPropertyAsValue (text, undoManager);
  70376. }
  70377. const Colour DrawableText::ValueTreeWrapper::getColour() const
  70378. {
  70379. return Colour::fromString (state [colour].toString());
  70380. }
  70381. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  70382. {
  70383. state.setProperty (colour, newColour.toString(), undoManager);
  70384. }
  70385. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  70386. {
  70387. return Justification ((int) state [justification]);
  70388. }
  70389. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  70390. {
  70391. state.setProperty (justification, newJustification.getFlags(), undoManager);
  70392. }
  70393. const Font DrawableText::ValueTreeWrapper::getFont() const
  70394. {
  70395. return Font::fromString (state [font]);
  70396. }
  70397. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  70398. {
  70399. state.setProperty (font, newFont.toString(), undoManager);
  70400. }
  70401. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  70402. {
  70403. return state.getPropertyAsValue (font, undoManager);
  70404. }
  70405. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  70406. {
  70407. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  70408. }
  70409. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70410. {
  70411. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70412. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70413. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70414. }
  70415. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  70416. {
  70417. return state [fontSizeAnchor].toString();
  70418. }
  70419. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  70420. {
  70421. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  70422. }
  70423. const Rectangle<float> DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  70424. {
  70425. ValueTreeWrapper v (tree);
  70426. setName (v.getID());
  70427. const RelativeParallelogram newBounds (v.getBoundingBox());
  70428. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  70429. const Colour newColour (v.getColour());
  70430. const Justification newJustification (v.getJustification());
  70431. const String newText (v.getText());
  70432. const Font newFont (v.getFont());
  70433. if (text != newText || font != newFont || justification != newJustification
  70434. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  70435. {
  70436. const Rectangle<float> damage (getBounds());
  70437. setBoundingBox (newBounds);
  70438. setFontSizeControlPoint (newFontPoint);
  70439. setColour (newColour);
  70440. setFont (newFont, false);
  70441. setJustification (newJustification);
  70442. setText (newText);
  70443. return damage.getUnion (getBounds());
  70444. }
  70445. return Rectangle<float>();
  70446. }
  70447. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  70448. {
  70449. ValueTree tree (valueTreeType);
  70450. ValueTreeWrapper v (tree);
  70451. v.setID (getName(), 0);
  70452. v.setText (text, 0);
  70453. v.setFont (font, 0);
  70454. v.setJustification (justification, 0);
  70455. v.setColour (colour, 0);
  70456. v.setBoundingBox (bounds, 0);
  70457. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  70458. return tree;
  70459. }
  70460. END_JUCE_NAMESPACE
  70461. /*** End of inlined file: juce_DrawableText.cpp ***/
  70462. /*** Start of inlined file: juce_SVGParser.cpp ***/
  70463. BEGIN_JUCE_NAMESPACE
  70464. class SVGState
  70465. {
  70466. public:
  70467. SVGState (const XmlElement* const topLevel)
  70468. : topLevelXml (topLevel),
  70469. elementX (0), elementY (0),
  70470. width (512), height (512),
  70471. viewBoxW (0), viewBoxH (0)
  70472. {
  70473. }
  70474. ~SVGState()
  70475. {
  70476. }
  70477. Drawable* parseSVGElement (const XmlElement& xml)
  70478. {
  70479. if (! xml.hasTagName ("svg"))
  70480. return 0;
  70481. DrawableComposite* const drawable = new DrawableComposite();
  70482. drawable->setName (xml.getStringAttribute ("id"));
  70483. SVGState newState (*this);
  70484. if (xml.hasAttribute ("transform"))
  70485. newState.addTransform (xml);
  70486. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  70487. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  70488. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  70489. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  70490. if (xml.hasAttribute ("viewBox"))
  70491. {
  70492. const String viewParams (xml.getStringAttribute ("viewBox"));
  70493. int i = 0;
  70494. float vx, vy, vw, vh;
  70495. if (parseCoords (viewParams, vx, vy, i, true)
  70496. && parseCoords (viewParams, vw, vh, i, true)
  70497. && vw > 0
  70498. && vh > 0)
  70499. {
  70500. newState.viewBoxW = vw;
  70501. newState.viewBoxH = vh;
  70502. int placementFlags = 0;
  70503. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  70504. if (aspect.containsIgnoreCase ("none"))
  70505. {
  70506. placementFlags = RectanglePlacement::stretchToFit;
  70507. }
  70508. else
  70509. {
  70510. if (aspect.containsIgnoreCase ("slice"))
  70511. placementFlags |= RectanglePlacement::fillDestination;
  70512. if (aspect.containsIgnoreCase ("xMin"))
  70513. placementFlags |= RectanglePlacement::xLeft;
  70514. else if (aspect.containsIgnoreCase ("xMax"))
  70515. placementFlags |= RectanglePlacement::xRight;
  70516. else
  70517. placementFlags |= RectanglePlacement::xMid;
  70518. if (aspect.containsIgnoreCase ("yMin"))
  70519. placementFlags |= RectanglePlacement::yTop;
  70520. else if (aspect.containsIgnoreCase ("yMax"))
  70521. placementFlags |= RectanglePlacement::yBottom;
  70522. else
  70523. placementFlags |= RectanglePlacement::yMid;
  70524. }
  70525. const RectanglePlacement placement (placementFlags);
  70526. newState.transform
  70527. = placement.getTransformToFit (vx, vy, vw, vh,
  70528. 0.0f, 0.0f, newState.width, newState.height)
  70529. .followedBy (newState.transform);
  70530. }
  70531. }
  70532. else
  70533. {
  70534. if (viewBoxW == 0)
  70535. newState.viewBoxW = newState.width;
  70536. if (viewBoxH == 0)
  70537. newState.viewBoxH = newState.height;
  70538. }
  70539. newState.parseSubElements (xml, drawable);
  70540. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  70541. return drawable;
  70542. }
  70543. private:
  70544. const XmlElement* const topLevelXml;
  70545. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  70546. AffineTransform transform;
  70547. String cssStyleText;
  70548. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  70549. {
  70550. forEachXmlChildElement (xml, e)
  70551. {
  70552. Drawable* d = 0;
  70553. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  70554. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  70555. else if (e->hasTagName ("path")) d = parsePath (*e);
  70556. else if (e->hasTagName ("rect")) d = parseRect (*e);
  70557. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  70558. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  70559. else if (e->hasTagName ("line")) d = parseLine (*e);
  70560. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  70561. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  70562. else if (e->hasTagName ("text")) d = parseText (*e);
  70563. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  70564. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  70565. parentDrawable->insertDrawable (d);
  70566. }
  70567. }
  70568. DrawableComposite* parseSwitch (const XmlElement& xml)
  70569. {
  70570. const XmlElement* const group = xml.getChildByName ("g");
  70571. if (group != 0)
  70572. return parseGroupElement (*group);
  70573. return 0;
  70574. }
  70575. DrawableComposite* parseGroupElement (const XmlElement& xml)
  70576. {
  70577. DrawableComposite* const drawable = new DrawableComposite();
  70578. drawable->setName (xml.getStringAttribute ("id"));
  70579. if (xml.hasAttribute ("transform"))
  70580. {
  70581. SVGState newState (*this);
  70582. newState.addTransform (xml);
  70583. newState.parseSubElements (xml, drawable);
  70584. }
  70585. else
  70586. {
  70587. parseSubElements (xml, drawable);
  70588. }
  70589. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  70590. return drawable;
  70591. }
  70592. Drawable* parsePath (const XmlElement& xml) const
  70593. {
  70594. const String d (xml.getStringAttribute ("d").trimStart());
  70595. Path path;
  70596. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  70597. path.setUsingNonZeroWinding (false);
  70598. int index = 0;
  70599. float lastX = 0, lastY = 0;
  70600. float lastX2 = 0, lastY2 = 0;
  70601. juce_wchar lastCommandChar = 0;
  70602. bool isRelative = true;
  70603. bool carryOn = true;
  70604. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  70605. while (d[index] != 0)
  70606. {
  70607. float x, y, x2, y2, x3, y3;
  70608. if (validCommandChars.containsChar (d[index]))
  70609. {
  70610. lastCommandChar = d [index++];
  70611. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  70612. }
  70613. switch (lastCommandChar)
  70614. {
  70615. case 'M':
  70616. case 'm':
  70617. case 'L':
  70618. case 'l':
  70619. if (parseCoords (d, x, y, index, false))
  70620. {
  70621. if (isRelative)
  70622. {
  70623. x += lastX;
  70624. y += lastY;
  70625. }
  70626. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  70627. {
  70628. path.startNewSubPath (x, y);
  70629. lastCommandChar = 'l';
  70630. }
  70631. else
  70632. path.lineTo (x, y);
  70633. lastX2 = lastX;
  70634. lastY2 = lastY;
  70635. lastX = x;
  70636. lastY = y;
  70637. }
  70638. else
  70639. {
  70640. ++index;
  70641. }
  70642. break;
  70643. case 'H':
  70644. case 'h':
  70645. if (parseCoord (d, x, index, false, true))
  70646. {
  70647. if (isRelative)
  70648. x += lastX;
  70649. path.lineTo (x, lastY);
  70650. lastX2 = lastX;
  70651. lastX = x;
  70652. }
  70653. else
  70654. {
  70655. ++index;
  70656. }
  70657. break;
  70658. case 'V':
  70659. case 'v':
  70660. if (parseCoord (d, y, index, false, false))
  70661. {
  70662. if (isRelative)
  70663. y += lastY;
  70664. path.lineTo (lastX, y);
  70665. lastY2 = lastY;
  70666. lastY = y;
  70667. }
  70668. else
  70669. {
  70670. ++index;
  70671. }
  70672. break;
  70673. case 'C':
  70674. case 'c':
  70675. if (parseCoords (d, x, y, index, false)
  70676. && parseCoords (d, x2, y2, index, false)
  70677. && parseCoords (d, x3, y3, index, false))
  70678. {
  70679. if (isRelative)
  70680. {
  70681. x += lastX;
  70682. y += lastY;
  70683. x2 += lastX;
  70684. y2 += lastY;
  70685. x3 += lastX;
  70686. y3 += lastY;
  70687. }
  70688. path.cubicTo (x, y, x2, y2, x3, y3);
  70689. lastX2 = x2;
  70690. lastY2 = y2;
  70691. lastX = x3;
  70692. lastY = y3;
  70693. }
  70694. else
  70695. {
  70696. ++index;
  70697. }
  70698. break;
  70699. case 'S':
  70700. case 's':
  70701. if (parseCoords (d, x, y, index, false)
  70702. && parseCoords (d, x3, y3, index, false))
  70703. {
  70704. if (isRelative)
  70705. {
  70706. x += lastX;
  70707. y += lastY;
  70708. x3 += lastX;
  70709. y3 += lastY;
  70710. }
  70711. x2 = lastX + (lastX - lastX2);
  70712. y2 = lastY + (lastY - lastY2);
  70713. path.cubicTo (x2, y2, x, y, x3, y3);
  70714. lastX2 = x;
  70715. lastY2 = y;
  70716. lastX = x3;
  70717. lastY = y3;
  70718. }
  70719. else
  70720. {
  70721. ++index;
  70722. }
  70723. break;
  70724. case 'Q':
  70725. case 'q':
  70726. if (parseCoords (d, x, y, index, false)
  70727. && parseCoords (d, x2, y2, index, false))
  70728. {
  70729. if (isRelative)
  70730. {
  70731. x += lastX;
  70732. y += lastY;
  70733. x2 += lastX;
  70734. y2 += lastY;
  70735. }
  70736. path.quadraticTo (x, y, x2, y2);
  70737. lastX2 = x;
  70738. lastY2 = y;
  70739. lastX = x2;
  70740. lastY = y2;
  70741. }
  70742. else
  70743. {
  70744. ++index;
  70745. }
  70746. break;
  70747. case 'T':
  70748. case 't':
  70749. if (parseCoords (d, x, y, index, false))
  70750. {
  70751. if (isRelative)
  70752. {
  70753. x += lastX;
  70754. y += lastY;
  70755. }
  70756. x2 = lastX + (lastX - lastX2);
  70757. y2 = lastY + (lastY - lastY2);
  70758. path.quadraticTo (x2, y2, x, y);
  70759. lastX2 = x2;
  70760. lastY2 = y2;
  70761. lastX = x;
  70762. lastY = y;
  70763. }
  70764. else
  70765. {
  70766. ++index;
  70767. }
  70768. break;
  70769. case 'A':
  70770. case 'a':
  70771. if (parseCoords (d, x, y, index, false))
  70772. {
  70773. String num;
  70774. if (parseNextNumber (d, num, index, false))
  70775. {
  70776. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  70777. if (parseNextNumber (d, num, index, false))
  70778. {
  70779. const bool largeArc = num.getIntValue() != 0;
  70780. if (parseNextNumber (d, num, index, false))
  70781. {
  70782. const bool sweep = num.getIntValue() != 0;
  70783. if (parseCoords (d, x2, y2, index, false))
  70784. {
  70785. if (isRelative)
  70786. {
  70787. x2 += lastX;
  70788. y2 += lastY;
  70789. }
  70790. if (lastX != x2 || lastY != y2)
  70791. {
  70792. double centreX, centreY, startAngle, deltaAngle;
  70793. double rx = x, ry = y;
  70794. endpointToCentreParameters (lastX, lastY, x2, y2,
  70795. angle, largeArc, sweep,
  70796. rx, ry, centreX, centreY,
  70797. startAngle, deltaAngle);
  70798. path.addCentredArc ((float) centreX, (float) centreY,
  70799. (float) rx, (float) ry,
  70800. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  70801. false);
  70802. path.lineTo (x2, y2);
  70803. }
  70804. lastX2 = lastX;
  70805. lastY2 = lastY;
  70806. lastX = x2;
  70807. lastY = y2;
  70808. }
  70809. }
  70810. }
  70811. }
  70812. }
  70813. else
  70814. {
  70815. ++index;
  70816. }
  70817. break;
  70818. case 'Z':
  70819. case 'z':
  70820. path.closeSubPath();
  70821. while (CharacterFunctions::isWhitespace (d [index]))
  70822. ++index;
  70823. break;
  70824. default:
  70825. carryOn = false;
  70826. break;
  70827. }
  70828. if (! carryOn)
  70829. break;
  70830. }
  70831. return parseShape (xml, path);
  70832. }
  70833. Drawable* parseRect (const XmlElement& xml) const
  70834. {
  70835. Path rect;
  70836. const bool hasRX = xml.hasAttribute ("rx");
  70837. const bool hasRY = xml.hasAttribute ("ry");
  70838. if (hasRX || hasRY)
  70839. {
  70840. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  70841. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  70842. if (! hasRX)
  70843. rx = ry;
  70844. else if (! hasRY)
  70845. ry = rx;
  70846. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  70847. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  70848. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  70849. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  70850. rx, ry);
  70851. }
  70852. else
  70853. {
  70854. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  70855. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  70856. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  70857. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  70858. }
  70859. return parseShape (xml, rect);
  70860. }
  70861. Drawable* parseCircle (const XmlElement& xml) const
  70862. {
  70863. Path circle;
  70864. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  70865. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  70866. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  70867. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  70868. return parseShape (xml, circle);
  70869. }
  70870. Drawable* parseEllipse (const XmlElement& xml) const
  70871. {
  70872. Path ellipse;
  70873. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  70874. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  70875. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  70876. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  70877. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  70878. return parseShape (xml, ellipse);
  70879. }
  70880. Drawable* parseLine (const XmlElement& xml) const
  70881. {
  70882. Path line;
  70883. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  70884. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  70885. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  70886. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  70887. line.startNewSubPath (x1, y1);
  70888. line.lineTo (x2, y2);
  70889. return parseShape (xml, line);
  70890. }
  70891. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  70892. {
  70893. const String points (xml.getStringAttribute ("points"));
  70894. Path path;
  70895. int index = 0;
  70896. float x, y;
  70897. if (parseCoords (points, x, y, index, true))
  70898. {
  70899. float firstX = x;
  70900. float firstY = y;
  70901. float lastX = 0, lastY = 0;
  70902. path.startNewSubPath (x, y);
  70903. while (parseCoords (points, x, y, index, true))
  70904. {
  70905. lastX = x;
  70906. lastY = y;
  70907. path.lineTo (x, y);
  70908. }
  70909. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  70910. path.closeSubPath();
  70911. }
  70912. return parseShape (xml, path);
  70913. }
  70914. Drawable* parseShape (const XmlElement& xml, Path& path,
  70915. const bool shouldParseTransform = true) const
  70916. {
  70917. if (shouldParseTransform && xml.hasAttribute ("transform"))
  70918. {
  70919. SVGState newState (*this);
  70920. newState.addTransform (xml);
  70921. return newState.parseShape (xml, path, false);
  70922. }
  70923. DrawablePath* dp = new DrawablePath();
  70924. dp->setName (xml.getStringAttribute ("id"));
  70925. dp->setFill (Colours::transparentBlack);
  70926. path.applyTransform (transform);
  70927. dp->setPath (path);
  70928. Path::Iterator iter (path);
  70929. bool containsClosedSubPath = false;
  70930. while (iter.next())
  70931. {
  70932. if (iter.elementType == Path::Iterator::closePath)
  70933. {
  70934. containsClosedSubPath = true;
  70935. break;
  70936. }
  70937. }
  70938. dp->setFill (getPathFillType (path,
  70939. getStyleAttribute (&xml, "fill"),
  70940. getStyleAttribute (&xml, "fill-opacity"),
  70941. getStyleAttribute (&xml, "opacity"),
  70942. containsClosedSubPath ? Colours::black
  70943. : Colours::transparentBlack));
  70944. const String strokeType (getStyleAttribute (&xml, "stroke"));
  70945. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  70946. {
  70947. dp->setStrokeFill (getPathFillType (path, strokeType,
  70948. getStyleAttribute (&xml, "stroke-opacity"),
  70949. getStyleAttribute (&xml, "opacity"),
  70950. Colours::transparentBlack));
  70951. dp->setStrokeType (getStrokeFor (&xml));
  70952. }
  70953. return dp;
  70954. }
  70955. const XmlElement* findLinkedElement (const XmlElement* e) const
  70956. {
  70957. const String id (e->getStringAttribute ("xlink:href"));
  70958. if (! id.startsWithChar ('#'))
  70959. return 0;
  70960. return findElementForId (topLevelXml, id.substring (1));
  70961. }
  70962. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  70963. {
  70964. if (fillXml == 0)
  70965. return;
  70966. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  70967. {
  70968. int index = 0;
  70969. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  70970. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  70971. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  70972. double offset = e->getDoubleAttribute ("offset");
  70973. if (e->getStringAttribute ("offset").containsChar ('%'))
  70974. offset *= 0.01;
  70975. cg.addColour (jlimit (0.0, 1.0, offset), col);
  70976. }
  70977. }
  70978. const FillType getPathFillType (const Path& path,
  70979. const String& fill,
  70980. const String& fillOpacity,
  70981. const String& overallOpacity,
  70982. const Colour& defaultColour) const
  70983. {
  70984. float opacity = 1.0f;
  70985. if (overallOpacity.isNotEmpty())
  70986. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  70987. if (fillOpacity.isNotEmpty())
  70988. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  70989. if (fill.startsWithIgnoreCase ("url"))
  70990. {
  70991. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  70992. .upToLastOccurrenceOf (")", false, false).trim());
  70993. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  70994. if (fillXml != 0
  70995. && (fillXml->hasTagName ("linearGradient")
  70996. || fillXml->hasTagName ("radialGradient")))
  70997. {
  70998. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  70999. ColourGradient gradient;
  71000. addGradientStopsIn (gradient, inheritedFrom);
  71001. addGradientStopsIn (gradient, fillXml);
  71002. if (gradient.getNumColours() > 0)
  71003. {
  71004. gradient.addColour (0.0, gradient.getColour (0));
  71005. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71006. }
  71007. else
  71008. {
  71009. gradient.addColour (0.0, Colours::black);
  71010. gradient.addColour (1.0, Colours::black);
  71011. }
  71012. if (overallOpacity.isNotEmpty())
  71013. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71014. jassert (gradient.getNumColours() > 0);
  71015. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71016. float gradientWidth = viewBoxW;
  71017. float gradientHeight = viewBoxH;
  71018. float dx = 0.0f;
  71019. float dy = 0.0f;
  71020. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71021. if (! userSpace)
  71022. {
  71023. const Rectangle<float> bounds (path.getBounds());
  71024. dx = bounds.getX();
  71025. dy = bounds.getY();
  71026. gradientWidth = bounds.getWidth();
  71027. gradientHeight = bounds.getHeight();
  71028. }
  71029. if (gradient.isRadial)
  71030. {
  71031. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71032. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71033. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71034. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71035. //xxx (the fx, fy focal point isn't handled properly here..)
  71036. }
  71037. else
  71038. {
  71039. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71040. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71041. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71042. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71043. if (gradient.point1 == gradient.point2)
  71044. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71045. }
  71046. FillType type (gradient);
  71047. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71048. .followedBy (transform);
  71049. return type;
  71050. }
  71051. }
  71052. if (fill.equalsIgnoreCase ("none"))
  71053. return Colours::transparentBlack;
  71054. int i = 0;
  71055. const Colour colour (parseColour (fill, i, defaultColour));
  71056. return colour.withMultipliedAlpha (opacity);
  71057. }
  71058. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71059. {
  71060. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71061. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71062. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71063. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71064. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71065. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71066. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71067. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71068. if (join.equalsIgnoreCase ("round"))
  71069. joinStyle = PathStrokeType::curved;
  71070. else if (join.equalsIgnoreCase ("bevel"))
  71071. joinStyle = PathStrokeType::beveled;
  71072. if (cap.equalsIgnoreCase ("round"))
  71073. capStyle = PathStrokeType::rounded;
  71074. else if (cap.equalsIgnoreCase ("square"))
  71075. capStyle = PathStrokeType::square;
  71076. float ox = 0.0f, oy = 0.0f;
  71077. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71078. transform.transformPoints (ox, oy, x, y);
  71079. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  71080. joinStyle, capStyle);
  71081. }
  71082. Drawable* parseText (const XmlElement& xml)
  71083. {
  71084. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71085. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71086. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71087. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71088. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71089. //xxx not done text yet!
  71090. forEachXmlChildElement (xml, e)
  71091. {
  71092. if (e->isTextElement())
  71093. {
  71094. const String text (e->getText());
  71095. Path path;
  71096. Drawable* s = parseShape (*e, path);
  71097. delete s;
  71098. }
  71099. else if (e->hasTagName ("tspan"))
  71100. {
  71101. Drawable* s = parseText (*e);
  71102. delete s;
  71103. }
  71104. }
  71105. return 0;
  71106. }
  71107. void addTransform (const XmlElement& xml)
  71108. {
  71109. transform = parseTransform (xml.getStringAttribute ("transform"))
  71110. .followedBy (transform);
  71111. }
  71112. bool parseCoord (const String& s, float& value, int& index,
  71113. const bool allowUnits, const bool isX) const
  71114. {
  71115. String number;
  71116. if (! parseNextNumber (s, number, index, allowUnits))
  71117. {
  71118. value = 0;
  71119. return false;
  71120. }
  71121. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71122. return true;
  71123. }
  71124. bool parseCoords (const String& s, float& x, float& y,
  71125. int& index, const bool allowUnits) const
  71126. {
  71127. return parseCoord (s, x, index, allowUnits, true)
  71128. && parseCoord (s, y, index, allowUnits, false);
  71129. }
  71130. float getCoordLength (const String& s, const float sizeForProportions) const
  71131. {
  71132. float n = s.getFloatValue();
  71133. const int len = s.length();
  71134. if (len > 2)
  71135. {
  71136. const float dpi = 96.0f;
  71137. const juce_wchar n1 = s [len - 2];
  71138. const juce_wchar n2 = s [len - 1];
  71139. if (n1 == 'i' && n2 == 'n')
  71140. n *= dpi;
  71141. else if (n1 == 'm' && n2 == 'm')
  71142. n *= dpi / 25.4f;
  71143. else if (n1 == 'c' && n2 == 'm')
  71144. n *= dpi / 2.54f;
  71145. else if (n1 == 'p' && n2 == 'c')
  71146. n *= 15.0f;
  71147. else if (n2 == '%')
  71148. n *= 0.01f * sizeForProportions;
  71149. }
  71150. return n;
  71151. }
  71152. void getCoordList (Array <float>& coords, const String& list,
  71153. const bool allowUnits, const bool isX) const
  71154. {
  71155. int index = 0;
  71156. float value;
  71157. while (parseCoord (list, value, index, allowUnits, isX))
  71158. coords.add (value);
  71159. }
  71160. void parseCSSStyle (const XmlElement& xml)
  71161. {
  71162. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71163. }
  71164. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71165. const String& defaultValue = String::empty) const
  71166. {
  71167. if (xml->hasAttribute (attributeName))
  71168. return xml->getStringAttribute (attributeName, defaultValue);
  71169. const String styleAtt (xml->getStringAttribute ("style"));
  71170. if (styleAtt.isNotEmpty())
  71171. {
  71172. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71173. if (value.isNotEmpty())
  71174. return value;
  71175. }
  71176. else if (xml->hasAttribute ("class"))
  71177. {
  71178. const String className ("." + xml->getStringAttribute ("class"));
  71179. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71180. if (index < 0)
  71181. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71182. if (index >= 0)
  71183. {
  71184. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71185. if (openBracket > index)
  71186. {
  71187. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  71188. if (closeBracket > openBracket)
  71189. {
  71190. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  71191. if (value.isNotEmpty())
  71192. return value;
  71193. }
  71194. }
  71195. }
  71196. }
  71197. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71198. if (xml != 0)
  71199. return getStyleAttribute (xml, attributeName, defaultValue);
  71200. return defaultValue;
  71201. }
  71202. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  71203. {
  71204. if (xml->hasAttribute (attributeName))
  71205. return xml->getStringAttribute (attributeName);
  71206. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71207. if (xml != 0)
  71208. return getInheritedAttribute (xml, attributeName);
  71209. return String::empty;
  71210. }
  71211. static bool isIdentifierChar (const juce_wchar c)
  71212. {
  71213. return CharacterFunctions::isLetter (c) || c == '-';
  71214. }
  71215. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  71216. {
  71217. int i = 0;
  71218. for (;;)
  71219. {
  71220. i = list.indexOf (i, attributeName);
  71221. if (i < 0)
  71222. break;
  71223. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  71224. && ! isIdentifierChar (list [i + attributeName.length()]))
  71225. {
  71226. i = list.indexOfChar (i, ':');
  71227. if (i < 0)
  71228. break;
  71229. int end = list.indexOfChar (i, ';');
  71230. if (end < 0)
  71231. end = 0x7ffff;
  71232. return list.substring (i + 1, end).trim();
  71233. }
  71234. ++i;
  71235. }
  71236. return defaultValue;
  71237. }
  71238. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  71239. {
  71240. const juce_wchar* const s = source;
  71241. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71242. ++index;
  71243. int start = index;
  71244. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  71245. ++index;
  71246. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  71247. ++index;
  71248. if ((s[index] == 'e' || s[index] == 'E')
  71249. && (CharacterFunctions::isDigit (s[index + 1])
  71250. || s[index + 1] == '-'
  71251. || s[index + 1] == '+'))
  71252. {
  71253. index += 2;
  71254. while (CharacterFunctions::isDigit (s[index]))
  71255. ++index;
  71256. }
  71257. if (allowUnits)
  71258. {
  71259. while (CharacterFunctions::isLetter (s[index]))
  71260. ++index;
  71261. }
  71262. if (index == start)
  71263. return false;
  71264. value = String (s + start, index - start);
  71265. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71266. ++index;
  71267. return true;
  71268. }
  71269. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  71270. {
  71271. if (s [index] == '#')
  71272. {
  71273. uint32 hex [6];
  71274. zeromem (hex, sizeof (hex));
  71275. int numChars = 0;
  71276. for (int i = 6; --i >= 0;)
  71277. {
  71278. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  71279. if (hexValue >= 0)
  71280. hex [numChars++] = hexValue;
  71281. else
  71282. break;
  71283. }
  71284. if (numChars <= 3)
  71285. return Colour ((uint8) (hex [0] * 0x11),
  71286. (uint8) (hex [1] * 0x11),
  71287. (uint8) (hex [2] * 0x11));
  71288. else
  71289. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  71290. (uint8) ((hex [2] << 4) + hex [3]),
  71291. (uint8) ((hex [4] << 4) + hex [5]));
  71292. }
  71293. else if (s [index] == 'r'
  71294. && s [index + 1] == 'g'
  71295. && s [index + 2] == 'b')
  71296. {
  71297. const int openBracket = s.indexOfChar (index, '(');
  71298. const int closeBracket = s.indexOfChar (openBracket, ')');
  71299. if (openBracket >= 3 && closeBracket > openBracket)
  71300. {
  71301. index = closeBracket;
  71302. StringArray tokens;
  71303. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  71304. tokens.trim();
  71305. tokens.removeEmptyStrings();
  71306. if (tokens[0].containsChar ('%'))
  71307. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  71308. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  71309. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  71310. else
  71311. return Colour ((uint8) tokens[0].getIntValue(),
  71312. (uint8) tokens[1].getIntValue(),
  71313. (uint8) tokens[2].getIntValue());
  71314. }
  71315. }
  71316. return Colours::findColourForName (s, defaultColour);
  71317. }
  71318. static const AffineTransform parseTransform (String t)
  71319. {
  71320. AffineTransform result;
  71321. while (t.isNotEmpty())
  71322. {
  71323. StringArray tokens;
  71324. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  71325. .upToFirstOccurrenceOf (")", false, false),
  71326. ", ", String::empty);
  71327. tokens.removeEmptyStrings (true);
  71328. float numbers [6];
  71329. for (int i = 0; i < 6; ++i)
  71330. numbers[i] = tokens[i].getFloatValue();
  71331. AffineTransform trans;
  71332. if (t.startsWithIgnoreCase ("matrix"))
  71333. {
  71334. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  71335. numbers[1], numbers[3], numbers[5]);
  71336. }
  71337. else if (t.startsWithIgnoreCase ("translate"))
  71338. {
  71339. jassert (tokens.size() == 2);
  71340. trans = AffineTransform::translation (numbers[0], numbers[1]);
  71341. }
  71342. else if (t.startsWithIgnoreCase ("scale"))
  71343. {
  71344. if (tokens.size() == 1)
  71345. trans = AffineTransform::scale (numbers[0], numbers[0]);
  71346. else
  71347. trans = AffineTransform::scale (numbers[0], numbers[1]);
  71348. }
  71349. else if (t.startsWithIgnoreCase ("rotate"))
  71350. {
  71351. if (tokens.size() != 3)
  71352. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  71353. else
  71354. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  71355. numbers[1], numbers[2]);
  71356. }
  71357. else if (t.startsWithIgnoreCase ("skewX"))
  71358. {
  71359. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  71360. 0.0f, 1.0f, 0.0f);
  71361. }
  71362. else if (t.startsWithIgnoreCase ("skewY"))
  71363. {
  71364. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  71365. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  71366. }
  71367. result = trans.followedBy (result);
  71368. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  71369. }
  71370. return result;
  71371. }
  71372. static void endpointToCentreParameters (const double x1, const double y1,
  71373. const double x2, const double y2,
  71374. const double angle,
  71375. const bool largeArc, const bool sweep,
  71376. double& rx, double& ry,
  71377. double& centreX, double& centreY,
  71378. double& startAngle, double& deltaAngle)
  71379. {
  71380. const double midX = (x1 - x2) * 0.5;
  71381. const double midY = (y1 - y2) * 0.5;
  71382. const double cosAngle = cos (angle);
  71383. const double sinAngle = sin (angle);
  71384. const double xp = cosAngle * midX + sinAngle * midY;
  71385. const double yp = cosAngle * midY - sinAngle * midX;
  71386. const double xp2 = xp * xp;
  71387. const double yp2 = yp * yp;
  71388. double rx2 = rx * rx;
  71389. double ry2 = ry * ry;
  71390. const double s = (xp2 / rx2) + (yp2 / ry2);
  71391. double c;
  71392. if (s <= 1.0)
  71393. {
  71394. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  71395. / (( rx2 * yp2) + (ry2 * xp2))));
  71396. if (largeArc == sweep)
  71397. c = -c;
  71398. }
  71399. else
  71400. {
  71401. const double s2 = std::sqrt (s);
  71402. rx *= s2;
  71403. ry *= s2;
  71404. rx2 = rx * rx;
  71405. ry2 = ry * ry;
  71406. c = 0;
  71407. }
  71408. const double cpx = ((rx * yp) / ry) * c;
  71409. const double cpy = ((-ry * xp) / rx) * c;
  71410. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  71411. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  71412. const double ux = (xp - cpx) / rx;
  71413. const double uy = (yp - cpy) / ry;
  71414. const double vx = (-xp - cpx) / rx;
  71415. const double vy = (-yp - cpy) / ry;
  71416. const double length = juce_hypot (ux, uy);
  71417. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  71418. if (uy < 0)
  71419. startAngle = -startAngle;
  71420. startAngle += double_Pi * 0.5;
  71421. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  71422. / (length * juce_hypot (vx, vy))));
  71423. if ((ux * vy) - (uy * vx) < 0)
  71424. deltaAngle = -deltaAngle;
  71425. if (sweep)
  71426. {
  71427. if (deltaAngle < 0)
  71428. deltaAngle += double_Pi * 2.0;
  71429. }
  71430. else
  71431. {
  71432. if (deltaAngle > 0)
  71433. deltaAngle -= double_Pi * 2.0;
  71434. }
  71435. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  71436. }
  71437. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  71438. {
  71439. forEachXmlChildElement (*parent, e)
  71440. {
  71441. if (e->compareAttribute ("id", id))
  71442. return e;
  71443. const XmlElement* const found = findElementForId (e, id);
  71444. if (found != 0)
  71445. return found;
  71446. }
  71447. return 0;
  71448. }
  71449. SVGState& operator= (const SVGState&);
  71450. };
  71451. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  71452. {
  71453. SVGState state (&svgDocument);
  71454. return state.parseSVGElement (svgDocument);
  71455. }
  71456. END_JUCE_NAMESPACE
  71457. /*** End of inlined file: juce_SVGParser.cpp ***/
  71458. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  71459. BEGIN_JUCE_NAMESPACE
  71460. #if JUCE_MSVC && JUCE_DEBUG
  71461. #pragma optimize ("t", on)
  71462. #endif
  71463. DropShadowEffect::DropShadowEffect()
  71464. : offsetX (0),
  71465. offsetY (0),
  71466. radius (4),
  71467. opacity (0.6f)
  71468. {
  71469. }
  71470. DropShadowEffect::~DropShadowEffect()
  71471. {
  71472. }
  71473. void DropShadowEffect::setShadowProperties (const float newRadius,
  71474. const float newOpacity,
  71475. const int newShadowOffsetX,
  71476. const int newShadowOffsetY)
  71477. {
  71478. radius = jmax (1.1f, newRadius);
  71479. offsetX = newShadowOffsetX;
  71480. offsetY = newShadowOffsetY;
  71481. opacity = newOpacity;
  71482. }
  71483. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  71484. {
  71485. const int w = image.getWidth();
  71486. const int h = image.getHeight();
  71487. Image shadowImage (Image::SingleChannel, w, h, false);
  71488. const Image::BitmapData srcData (image, false);
  71489. const Image::BitmapData destData (shadowImage, true);
  71490. const int filter = roundToInt (63.0f / radius);
  71491. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  71492. for (int x = w; --x >= 0;)
  71493. {
  71494. int shadowAlpha = 0;
  71495. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  71496. uint8* shadowPix = destData.data + x;
  71497. for (int y = h; --y >= 0;)
  71498. {
  71499. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  71500. *shadowPix = (uint8) shadowAlpha;
  71501. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  71502. shadowPix += destData.lineStride;
  71503. }
  71504. }
  71505. for (int y = h; --y >= 0;)
  71506. {
  71507. int shadowAlpha = 0;
  71508. uint8* shadowPix = destData.getLinePointer (y);
  71509. for (int x = w; --x >= 0;)
  71510. {
  71511. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  71512. *shadowPix++ = (uint8) shadowAlpha;
  71513. }
  71514. }
  71515. g.setColour (Colours::black.withAlpha (opacity));
  71516. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  71517. g.setOpacity (1.0f);
  71518. g.drawImageAt (image, 0, 0);
  71519. }
  71520. #if JUCE_MSVC && JUCE_DEBUG
  71521. #pragma optimize ("", on) // resets optimisations to the project defaults
  71522. #endif
  71523. END_JUCE_NAMESPACE
  71524. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  71525. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  71526. BEGIN_JUCE_NAMESPACE
  71527. GlowEffect::GlowEffect()
  71528. : radius (2.0f),
  71529. colour (Colours::white)
  71530. {
  71531. }
  71532. GlowEffect::~GlowEffect()
  71533. {
  71534. }
  71535. void GlowEffect::setGlowProperties (const float newRadius,
  71536. const Colour& newColour)
  71537. {
  71538. radius = newRadius;
  71539. colour = newColour;
  71540. }
  71541. void GlowEffect::applyEffect (Image& image, Graphics& g)
  71542. {
  71543. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  71544. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  71545. blurKernel.createGaussianBlur (radius);
  71546. blurKernel.rescaleAllValues (radius);
  71547. blurKernel.applyToImage (temp, image, image.getBounds());
  71548. g.setColour (colour);
  71549. g.drawImageAt (temp, 0, 0, true);
  71550. g.setOpacity (1.0f);
  71551. g.drawImageAt (image, 0, 0, false);
  71552. }
  71553. END_JUCE_NAMESPACE
  71554. /*** End of inlined file: juce_GlowEffect.cpp ***/
  71555. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  71556. BEGIN_JUCE_NAMESPACE
  71557. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  71558. : opacity (opacity_)
  71559. {
  71560. }
  71561. ReduceOpacityEffect::~ReduceOpacityEffect()
  71562. {
  71563. }
  71564. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  71565. {
  71566. opacity = jlimit (0.0f, 1.0f, newOpacity);
  71567. }
  71568. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  71569. {
  71570. g.setOpacity (opacity);
  71571. g.drawImageAt (image, 0, 0);
  71572. }
  71573. END_JUCE_NAMESPACE
  71574. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  71575. /*** Start of inlined file: juce_Font.cpp ***/
  71576. BEGIN_JUCE_NAMESPACE
  71577. namespace FontValues
  71578. {
  71579. static float limitFontHeight (const float height) throw()
  71580. {
  71581. return jlimit (0.1f, 10000.0f, height);
  71582. }
  71583. static const float defaultFontHeight = 14.0f;
  71584. static String fallbackFont;
  71585. }
  71586. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  71587. const float kerning_, const float ascent_, const int styleFlags_,
  71588. Typeface* const typeface_) throw()
  71589. : typefaceName (typefaceName_),
  71590. height (height_),
  71591. horizontalScale (horizontalScale_),
  71592. kerning (kerning_),
  71593. ascent (ascent_),
  71594. styleFlags (styleFlags_),
  71595. typeface (typeface_)
  71596. {
  71597. }
  71598. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  71599. : typefaceName (other.typefaceName),
  71600. height (other.height),
  71601. horizontalScale (other.horizontalScale),
  71602. kerning (other.kerning),
  71603. ascent (other.ascent),
  71604. styleFlags (other.styleFlags),
  71605. typeface (other.typeface)
  71606. {
  71607. }
  71608. Font::Font() throw()
  71609. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  71610. 1.0f, 0, 0, Font::plain, 0))
  71611. {
  71612. }
  71613. Font::Font (const float fontHeight, const int styleFlags_) throw()
  71614. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  71615. 1.0f, 0, 0, styleFlags_, 0))
  71616. {
  71617. }
  71618. Font::Font (const String& typefaceName_,
  71619. const float fontHeight,
  71620. const int styleFlags_) throw()
  71621. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  71622. 1.0f, 0, 0, styleFlags_, 0))
  71623. {
  71624. }
  71625. Font::Font (const Font& other) throw()
  71626. : font (other.font)
  71627. {
  71628. }
  71629. Font& Font::operator= (const Font& other) throw()
  71630. {
  71631. font = other.font;
  71632. return *this;
  71633. }
  71634. Font::~Font() throw()
  71635. {
  71636. }
  71637. Font::Font (const Typeface::Ptr& typeface) throw()
  71638. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  71639. 1.0f, 0, 0, Font::plain, typeface))
  71640. {
  71641. }
  71642. bool Font::operator== (const Font& other) const throw()
  71643. {
  71644. return font == other.font
  71645. || (font->height == other.font->height
  71646. && font->styleFlags == other.font->styleFlags
  71647. && font->horizontalScale == other.font->horizontalScale
  71648. && font->kerning == other.font->kerning
  71649. && font->typefaceName == other.font->typefaceName);
  71650. }
  71651. bool Font::operator!= (const Font& other) const throw()
  71652. {
  71653. return ! operator== (other);
  71654. }
  71655. void Font::dupeInternalIfShared() throw()
  71656. {
  71657. if (font->getReferenceCount() > 1)
  71658. font = new SharedFontInternal (*font);
  71659. }
  71660. const String Font::getDefaultSansSerifFontName() throw()
  71661. {
  71662. static const String name ("<Sans-Serif>");
  71663. return name;
  71664. }
  71665. const String Font::getDefaultSerifFontName() throw()
  71666. {
  71667. static const String name ("<Serif>");
  71668. return name;
  71669. }
  71670. const String Font::getDefaultMonospacedFontName() throw()
  71671. {
  71672. static const String name ("<Monospaced>");
  71673. return name;
  71674. }
  71675. void Font::setTypefaceName (const String& faceName) throw()
  71676. {
  71677. if (faceName != font->typefaceName)
  71678. {
  71679. dupeInternalIfShared();
  71680. font->typefaceName = faceName;
  71681. font->typeface = 0;
  71682. font->ascent = 0;
  71683. }
  71684. }
  71685. const String Font::getFallbackFontName() throw()
  71686. {
  71687. return FontValues::fallbackFont;
  71688. }
  71689. void Font::setFallbackFontName (const String& name) throw()
  71690. {
  71691. FontValues::fallbackFont = name;
  71692. }
  71693. void Font::setHeight (float newHeight) throw()
  71694. {
  71695. newHeight = FontValues::limitFontHeight (newHeight);
  71696. if (font->height != newHeight)
  71697. {
  71698. dupeInternalIfShared();
  71699. font->height = newHeight;
  71700. }
  71701. }
  71702. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  71703. {
  71704. newHeight = FontValues::limitFontHeight (newHeight);
  71705. if (font->height != newHeight)
  71706. {
  71707. dupeInternalIfShared();
  71708. font->horizontalScale *= (font->height / newHeight);
  71709. font->height = newHeight;
  71710. }
  71711. }
  71712. void Font::setStyleFlags (const int newFlags) throw()
  71713. {
  71714. if (font->styleFlags != newFlags)
  71715. {
  71716. dupeInternalIfShared();
  71717. font->styleFlags = newFlags;
  71718. font->typeface = 0;
  71719. font->ascent = 0;
  71720. }
  71721. }
  71722. void Font::setSizeAndStyle (float newHeight,
  71723. const int newStyleFlags,
  71724. const float newHorizontalScale,
  71725. const float newKerningAmount) throw()
  71726. {
  71727. newHeight = FontValues::limitFontHeight (newHeight);
  71728. if (font->height != newHeight
  71729. || font->horizontalScale != newHorizontalScale
  71730. || font->kerning != newKerningAmount)
  71731. {
  71732. dupeInternalIfShared();
  71733. font->height = newHeight;
  71734. font->horizontalScale = newHorizontalScale;
  71735. font->kerning = newKerningAmount;
  71736. }
  71737. setStyleFlags (newStyleFlags);
  71738. }
  71739. void Font::setHorizontalScale (const float scaleFactor) throw()
  71740. {
  71741. dupeInternalIfShared();
  71742. font->horizontalScale = scaleFactor;
  71743. }
  71744. void Font::setExtraKerningFactor (const float extraKerning) throw()
  71745. {
  71746. dupeInternalIfShared();
  71747. font->kerning = extraKerning;
  71748. }
  71749. void Font::setBold (const bool shouldBeBold) throw()
  71750. {
  71751. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  71752. : (font->styleFlags & ~bold));
  71753. }
  71754. bool Font::isBold() const throw()
  71755. {
  71756. return (font->styleFlags & bold) != 0;
  71757. }
  71758. void Font::setItalic (const bool shouldBeItalic) throw()
  71759. {
  71760. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  71761. : (font->styleFlags & ~italic));
  71762. }
  71763. bool Font::isItalic() const throw()
  71764. {
  71765. return (font->styleFlags & italic) != 0;
  71766. }
  71767. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  71768. {
  71769. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  71770. : (font->styleFlags & ~underlined));
  71771. }
  71772. bool Font::isUnderlined() const throw()
  71773. {
  71774. return (font->styleFlags & underlined) != 0;
  71775. }
  71776. float Font::getAscent() const throw()
  71777. {
  71778. if (font->ascent == 0)
  71779. font->ascent = getTypeface()->getAscent();
  71780. return font->height * font->ascent;
  71781. }
  71782. float Font::getDescent() const throw()
  71783. {
  71784. return font->height - getAscent();
  71785. }
  71786. int Font::getStringWidth (const String& text) const throw()
  71787. {
  71788. return roundToInt (getStringWidthFloat (text));
  71789. }
  71790. float Font::getStringWidthFloat (const String& text) const throw()
  71791. {
  71792. float w = getTypeface()->getStringWidth (text);
  71793. if (font->kerning != 0)
  71794. w += font->kerning * text.length();
  71795. return w * font->height * font->horizontalScale;
  71796. }
  71797. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw()
  71798. {
  71799. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  71800. const float scale = font->height * font->horizontalScale;
  71801. const int num = xOffsets.size();
  71802. if (num > 0)
  71803. {
  71804. float* const x = &(xOffsets.getReference(0));
  71805. if (font->kerning != 0)
  71806. {
  71807. for (int i = 0; i < num; ++i)
  71808. x[i] = (x[i] + i * font->kerning) * scale;
  71809. }
  71810. else
  71811. {
  71812. for (int i = 0; i < num; ++i)
  71813. x[i] *= scale;
  71814. }
  71815. }
  71816. }
  71817. void Font::findFonts (Array<Font>& destArray) throw()
  71818. {
  71819. const StringArray names (findAllTypefaceNames());
  71820. for (int i = 0; i < names.size(); ++i)
  71821. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  71822. }
  71823. const String Font::toString() const
  71824. {
  71825. String s (getTypefaceName());
  71826. if (s == getDefaultSansSerifFontName())
  71827. s = String::empty;
  71828. else
  71829. s += "; ";
  71830. s += String (getHeight(), 1);
  71831. if (isBold())
  71832. s += " bold";
  71833. if (isItalic())
  71834. s += " italic";
  71835. return s;
  71836. }
  71837. const Font Font::fromString (const String& fontDescription)
  71838. {
  71839. String name;
  71840. const int separator = fontDescription.indexOfChar (';');
  71841. if (separator > 0)
  71842. name = fontDescription.substring (0, separator).trim();
  71843. if (name.isEmpty())
  71844. name = getDefaultSansSerifFontName();
  71845. String sizeAndStyle (fontDescription.substring (separator + 1));
  71846. float height = sizeAndStyle.getFloatValue();
  71847. if (height <= 0)
  71848. height = 10.0f;
  71849. int flags = Font::plain;
  71850. if (sizeAndStyle.containsIgnoreCase ("bold"))
  71851. flags |= Font::bold;
  71852. if (sizeAndStyle.containsIgnoreCase ("italic"))
  71853. flags |= Font::italic;
  71854. return Font (name, height, flags);
  71855. }
  71856. class TypefaceCache : public DeletedAtShutdown
  71857. {
  71858. public:
  71859. TypefaceCache (int numToCache = 10) throw()
  71860. : counter (1)
  71861. {
  71862. while (--numToCache >= 0)
  71863. faces.add (new CachedFace());
  71864. }
  71865. ~TypefaceCache()
  71866. {
  71867. clearSingletonInstance();
  71868. }
  71869. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  71870. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  71871. {
  71872. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  71873. const String faceName (font.getTypefaceName());
  71874. int i;
  71875. for (i = faces.size(); --i >= 0;)
  71876. {
  71877. CachedFace* const face = faces.getUnchecked(i);
  71878. if (face->flags == flags
  71879. && face->typefaceName == faceName)
  71880. {
  71881. face->lastUsageCount = ++counter;
  71882. return face->typeFace;
  71883. }
  71884. }
  71885. int replaceIndex = 0;
  71886. int bestLastUsageCount = std::numeric_limits<int>::max();
  71887. for (i = faces.size(); --i >= 0;)
  71888. {
  71889. const int lu = faces.getUnchecked(i)->lastUsageCount;
  71890. if (bestLastUsageCount > lu)
  71891. {
  71892. bestLastUsageCount = lu;
  71893. replaceIndex = i;
  71894. }
  71895. }
  71896. CachedFace* const face = faces.getUnchecked (replaceIndex);
  71897. face->typefaceName = faceName;
  71898. face->flags = flags;
  71899. face->lastUsageCount = ++counter;
  71900. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  71901. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  71902. return face->typeFace;
  71903. }
  71904. juce_UseDebuggingNewOperator
  71905. private:
  71906. struct CachedFace
  71907. {
  71908. CachedFace() throw()
  71909. : lastUsageCount (0), flags (-1)
  71910. {
  71911. }
  71912. String typefaceName;
  71913. int lastUsageCount;
  71914. int flags;
  71915. Typeface::Ptr typeFace;
  71916. };
  71917. int counter;
  71918. OwnedArray <CachedFace> faces;
  71919. TypefaceCache (const TypefaceCache&);
  71920. TypefaceCache& operator= (const TypefaceCache&);
  71921. };
  71922. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  71923. Typeface* Font::getTypeface() const throw()
  71924. {
  71925. if (font->typeface == 0)
  71926. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  71927. return font->typeface;
  71928. }
  71929. END_JUCE_NAMESPACE
  71930. /*** End of inlined file: juce_Font.cpp ***/
  71931. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  71932. BEGIN_JUCE_NAMESPACE
  71933. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  71934. const juce_wchar character_, const int glyph_)
  71935. : x (x_),
  71936. y (y_),
  71937. w (w_),
  71938. font (font_),
  71939. character (character_),
  71940. glyph (glyph_)
  71941. {
  71942. }
  71943. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  71944. : x (other.x),
  71945. y (other.y),
  71946. w (other.w),
  71947. font (other.font),
  71948. character (other.character),
  71949. glyph (other.glyph)
  71950. {
  71951. }
  71952. void PositionedGlyph::draw (const Graphics& g) const
  71953. {
  71954. if (! isWhitespace())
  71955. {
  71956. g.getInternalContext()->setFont (font);
  71957. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  71958. }
  71959. }
  71960. void PositionedGlyph::draw (const Graphics& g,
  71961. const AffineTransform& transform) const
  71962. {
  71963. if (! isWhitespace())
  71964. {
  71965. g.getInternalContext()->setFont (font);
  71966. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  71967. .followedBy (transform));
  71968. }
  71969. }
  71970. void PositionedGlyph::createPath (Path& path) const
  71971. {
  71972. if (! isWhitespace())
  71973. {
  71974. Typeface* const t = font.getTypeface();
  71975. if (t != 0)
  71976. {
  71977. Path p;
  71978. t->getOutlineForGlyph (glyph, p);
  71979. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  71980. .translated (x, y));
  71981. }
  71982. }
  71983. }
  71984. bool PositionedGlyph::hitTest (float px, float py) const
  71985. {
  71986. if (getBounds().contains (px, py) && ! isWhitespace())
  71987. {
  71988. Typeface* const t = font.getTypeface();
  71989. if (t != 0)
  71990. {
  71991. Path p;
  71992. t->getOutlineForGlyph (glyph, p);
  71993. AffineTransform::translation (-x, -y)
  71994. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  71995. .transformPoint (px, py);
  71996. return p.contains (px, py);
  71997. }
  71998. }
  71999. return false;
  72000. }
  72001. void PositionedGlyph::moveBy (const float deltaX,
  72002. const float deltaY)
  72003. {
  72004. x += deltaX;
  72005. y += deltaY;
  72006. }
  72007. GlyphArrangement::GlyphArrangement()
  72008. {
  72009. glyphs.ensureStorageAllocated (128);
  72010. }
  72011. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72012. {
  72013. addGlyphArrangement (other);
  72014. }
  72015. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72016. {
  72017. if (this != &other)
  72018. {
  72019. clear();
  72020. addGlyphArrangement (other);
  72021. }
  72022. return *this;
  72023. }
  72024. GlyphArrangement::~GlyphArrangement()
  72025. {
  72026. }
  72027. void GlyphArrangement::clear()
  72028. {
  72029. glyphs.clear();
  72030. }
  72031. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72032. {
  72033. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  72034. return *glyphs [index];
  72035. }
  72036. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72037. {
  72038. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72039. glyphs.addCopiesOf (other.glyphs);
  72040. }
  72041. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72042. {
  72043. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72044. }
  72045. void GlyphArrangement::addLineOfText (const Font& font,
  72046. const String& text,
  72047. const float xOffset,
  72048. const float yOffset)
  72049. {
  72050. addCurtailedLineOfText (font, text,
  72051. xOffset, yOffset,
  72052. 1.0e10f, false);
  72053. }
  72054. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72055. const String& text,
  72056. float xOffset,
  72057. const float yOffset,
  72058. const float maxWidthPixels,
  72059. const bool useEllipsis)
  72060. {
  72061. if (text.isNotEmpty())
  72062. {
  72063. Array <int> newGlyphs;
  72064. Array <float> xOffsets;
  72065. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72066. const int textLen = newGlyphs.size();
  72067. const juce_wchar* const unicodeText = text;
  72068. for (int i = 0; i < textLen; ++i)
  72069. {
  72070. const float thisX = xOffsets.getUnchecked (i);
  72071. const float nextX = xOffsets.getUnchecked (i + 1);
  72072. if (nextX > maxWidthPixels + 1.0f)
  72073. {
  72074. // curtail the string if it's too wide..
  72075. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72076. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72077. break;
  72078. }
  72079. else
  72080. {
  72081. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72082. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72083. }
  72084. }
  72085. }
  72086. }
  72087. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72088. const int startIndex, int endIndex)
  72089. {
  72090. int numDeleted = 0;
  72091. if (glyphs.size() > 0)
  72092. {
  72093. Array<int> dotGlyphs;
  72094. Array<float> dotXs;
  72095. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72096. const float dx = dotXs[1];
  72097. float xOffset = 0.0f, yOffset = 0.0f;
  72098. while (endIndex > startIndex)
  72099. {
  72100. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72101. xOffset = pg->x;
  72102. yOffset = pg->y;
  72103. glyphs.remove (endIndex);
  72104. ++numDeleted;
  72105. if (xOffset + dx * 3 <= maxXPos)
  72106. break;
  72107. }
  72108. for (int i = 3; --i >= 0;)
  72109. {
  72110. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72111. font, '.', dotGlyphs.getFirst()));
  72112. --numDeleted;
  72113. xOffset += dx;
  72114. if (xOffset > maxXPos)
  72115. break;
  72116. }
  72117. }
  72118. return numDeleted;
  72119. }
  72120. void GlyphArrangement::addJustifiedText (const Font& font,
  72121. const String& text,
  72122. float x, float y,
  72123. const float maxLineWidth,
  72124. const Justification& horizontalLayout)
  72125. {
  72126. int lineStartIndex = glyphs.size();
  72127. addLineOfText (font, text, x, y);
  72128. const float originalY = y;
  72129. while (lineStartIndex < glyphs.size())
  72130. {
  72131. int i = lineStartIndex;
  72132. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72133. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72134. ++i;
  72135. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72136. int lastWordBreakIndex = -1;
  72137. while (i < glyphs.size())
  72138. {
  72139. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72140. const juce_wchar c = pg->getCharacter();
  72141. if (c == '\r' || c == '\n')
  72142. {
  72143. ++i;
  72144. if (c == '\r' && i < glyphs.size()
  72145. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72146. ++i;
  72147. break;
  72148. }
  72149. else if (pg->isWhitespace())
  72150. {
  72151. lastWordBreakIndex = i + 1;
  72152. }
  72153. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72154. {
  72155. if (lastWordBreakIndex >= 0)
  72156. i = lastWordBreakIndex;
  72157. break;
  72158. }
  72159. ++i;
  72160. }
  72161. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  72162. float currentLineEndX = currentLineStartX;
  72163. for (int j = i; --j >= lineStartIndex;)
  72164. {
  72165. if (! glyphs.getUnchecked (j)->isWhitespace())
  72166. {
  72167. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  72168. break;
  72169. }
  72170. }
  72171. float deltaX = 0.0f;
  72172. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  72173. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  72174. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  72175. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  72176. else if (horizontalLayout.testFlags (Justification::right))
  72177. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  72178. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  72179. x + deltaX - currentLineStartX, y - originalY);
  72180. lineStartIndex = i;
  72181. y += font.getHeight();
  72182. }
  72183. }
  72184. void GlyphArrangement::addFittedText (const Font& f,
  72185. const String& text,
  72186. const float x, const float y,
  72187. const float width, const float height,
  72188. const Justification& layout,
  72189. int maximumLines,
  72190. const float minimumHorizontalScale)
  72191. {
  72192. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  72193. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  72194. if (text.containsAnyOf ("\r\n"))
  72195. {
  72196. GlyphArrangement ga;
  72197. ga.addJustifiedText (f, text, x, y, width, layout);
  72198. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  72199. float dy = y - bb.getY();
  72200. if (layout.testFlags (Justification::verticallyCentred))
  72201. dy += (height - bb.getHeight()) * 0.5f;
  72202. else if (layout.testFlags (Justification::bottom))
  72203. dy += height - bb.getHeight();
  72204. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  72205. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  72206. for (int i = 0; i < ga.glyphs.size(); ++i)
  72207. glyphs.add (ga.glyphs.getUnchecked (i));
  72208. ga.glyphs.clear (false);
  72209. return;
  72210. }
  72211. int startIndex = glyphs.size();
  72212. addLineOfText (f, text.trim(), x, y);
  72213. if (glyphs.size() > startIndex)
  72214. {
  72215. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72216. - glyphs.getUnchecked (startIndex)->getLeft();
  72217. if (lineWidth <= 0)
  72218. return;
  72219. if (lineWidth * minimumHorizontalScale < width)
  72220. {
  72221. if (lineWidth > width)
  72222. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  72223. width / lineWidth);
  72224. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  72225. x, y, width, height, layout);
  72226. }
  72227. else if (maximumLines <= 1)
  72228. {
  72229. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  72230. x, y, width, height, f, layout, minimumHorizontalScale);
  72231. }
  72232. else
  72233. {
  72234. Font font (f);
  72235. String txt (text.trim());
  72236. const int length = txt.length();
  72237. const int originalStartIndex = startIndex;
  72238. int numLines = 1;
  72239. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  72240. maximumLines = 1;
  72241. maximumLines = jmin (maximumLines, length);
  72242. while (numLines < maximumLines)
  72243. {
  72244. ++numLines;
  72245. const float newFontHeight = height / (float) numLines;
  72246. if (newFontHeight < font.getHeight())
  72247. {
  72248. font.setHeight (jmax (8.0f, newFontHeight));
  72249. removeRangeOfGlyphs (startIndex, -1);
  72250. addLineOfText (font, txt, x, y);
  72251. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72252. - glyphs.getUnchecked (startIndex)->getLeft();
  72253. }
  72254. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  72255. break;
  72256. }
  72257. if (numLines < 1)
  72258. numLines = 1;
  72259. float lineY = y;
  72260. float widthPerLine = lineWidth / numLines;
  72261. int lastLineStartIndex = 0;
  72262. for (int line = 0; line < numLines; ++line)
  72263. {
  72264. int i = startIndex;
  72265. lastLineStartIndex = i;
  72266. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  72267. if (line == numLines - 1)
  72268. {
  72269. widthPerLine = width;
  72270. i = glyphs.size();
  72271. }
  72272. else
  72273. {
  72274. while (i < glyphs.size())
  72275. {
  72276. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  72277. if (lineWidth > widthPerLine)
  72278. {
  72279. // got to a point where the line's too long, so skip forward to find a
  72280. // good place to break it..
  72281. const int searchStartIndex = i;
  72282. while (i < glyphs.size())
  72283. {
  72284. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  72285. {
  72286. if (glyphs.getUnchecked (i)->isWhitespace()
  72287. || glyphs.getUnchecked (i)->getCharacter() == '-')
  72288. {
  72289. ++i;
  72290. break;
  72291. }
  72292. }
  72293. else
  72294. {
  72295. // can't find a suitable break, so try looking backwards..
  72296. i = searchStartIndex;
  72297. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  72298. {
  72299. if (glyphs.getUnchecked (i - back)->isWhitespace()
  72300. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  72301. {
  72302. i -= back - 1;
  72303. break;
  72304. }
  72305. }
  72306. break;
  72307. }
  72308. ++i;
  72309. }
  72310. break;
  72311. }
  72312. ++i;
  72313. }
  72314. int wsStart = i;
  72315. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  72316. --wsStart;
  72317. int wsEnd = i;
  72318. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  72319. ++wsEnd;
  72320. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  72321. i = jmax (wsStart, startIndex + 1);
  72322. }
  72323. i -= fitLineIntoSpace (startIndex, i - startIndex,
  72324. x, lineY, width, font.getHeight(), font,
  72325. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  72326. minimumHorizontalScale);
  72327. startIndex = i;
  72328. lineY += font.getHeight();
  72329. if (startIndex >= glyphs.size())
  72330. break;
  72331. }
  72332. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  72333. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  72334. }
  72335. }
  72336. }
  72337. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  72338. const float dx, const float dy)
  72339. {
  72340. jassert (startIndex >= 0);
  72341. if (dx != 0.0f || dy != 0.0f)
  72342. {
  72343. if (num < 0 || startIndex + num > glyphs.size())
  72344. num = glyphs.size() - startIndex;
  72345. while (--num >= 0)
  72346. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  72347. }
  72348. }
  72349. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  72350. const Justification& justification, float minimumHorizontalScale)
  72351. {
  72352. int numDeleted = 0;
  72353. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  72354. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  72355. if (lineWidth > w)
  72356. {
  72357. if (minimumHorizontalScale < 1.0f)
  72358. {
  72359. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  72360. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  72361. }
  72362. if (lineWidth > w)
  72363. {
  72364. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  72365. numGlyphs -= numDeleted;
  72366. }
  72367. }
  72368. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  72369. return numDeleted;
  72370. }
  72371. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  72372. const float horizontalScaleFactor)
  72373. {
  72374. jassert (startIndex >= 0);
  72375. if (num < 0 || startIndex + num > glyphs.size())
  72376. num = glyphs.size() - startIndex;
  72377. if (num > 0)
  72378. {
  72379. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  72380. while (--num >= 0)
  72381. {
  72382. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  72383. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  72384. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  72385. pg->w *= horizontalScaleFactor;
  72386. }
  72387. }
  72388. }
  72389. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  72390. {
  72391. jassert (startIndex >= 0);
  72392. if (num < 0 || startIndex + num > glyphs.size())
  72393. num = glyphs.size() - startIndex;
  72394. Rectangle<float> result;
  72395. while (--num >= 0)
  72396. {
  72397. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  72398. if (includeWhitespace || ! pg->isWhitespace())
  72399. result = result.getUnion (pg->getBounds());
  72400. }
  72401. return result;
  72402. }
  72403. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  72404. const float x, const float y, const float width, const float height,
  72405. const Justification& justification)
  72406. {
  72407. jassert (num >= 0 && startIndex >= 0);
  72408. if (glyphs.size() > 0 && num > 0)
  72409. {
  72410. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  72411. | Justification::horizontallyCentred)));
  72412. float deltaX = 0.0f;
  72413. if (justification.testFlags (Justification::horizontallyJustified))
  72414. deltaX = x - bb.getX();
  72415. else if (justification.testFlags (Justification::horizontallyCentred))
  72416. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  72417. else if (justification.testFlags (Justification::right))
  72418. deltaX = (x + width) - bb.getRight();
  72419. else
  72420. deltaX = x - bb.getX();
  72421. float deltaY = 0.0f;
  72422. if (justification.testFlags (Justification::top))
  72423. deltaY = y - bb.getY();
  72424. else if (justification.testFlags (Justification::bottom))
  72425. deltaY = (y + height) - bb.getBottom();
  72426. else
  72427. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  72428. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  72429. if (justification.testFlags (Justification::horizontallyJustified))
  72430. {
  72431. int lineStart = 0;
  72432. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  72433. int i;
  72434. for (i = 0; i < num; ++i)
  72435. {
  72436. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  72437. if (glyphY != baseY)
  72438. {
  72439. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  72440. lineStart = i;
  72441. baseY = glyphY;
  72442. }
  72443. }
  72444. if (i > lineStart)
  72445. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  72446. }
  72447. }
  72448. }
  72449. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  72450. {
  72451. if (start + num < glyphs.size()
  72452. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  72453. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  72454. {
  72455. int numSpaces = 0;
  72456. int spacesAtEnd = 0;
  72457. for (int i = 0; i < num; ++i)
  72458. {
  72459. if (glyphs.getUnchecked (start + i)->isWhitespace())
  72460. {
  72461. ++spacesAtEnd;
  72462. ++numSpaces;
  72463. }
  72464. else
  72465. {
  72466. spacesAtEnd = 0;
  72467. }
  72468. }
  72469. numSpaces -= spacesAtEnd;
  72470. if (numSpaces > 0)
  72471. {
  72472. const float startX = glyphs.getUnchecked (start)->getLeft();
  72473. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  72474. const float extraPaddingBetweenWords
  72475. = (targetWidth - (endX - startX)) / (float) numSpaces;
  72476. float deltaX = 0.0f;
  72477. for (int i = 0; i < num; ++i)
  72478. {
  72479. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  72480. if (glyphs.getUnchecked (start + i)->isWhitespace())
  72481. deltaX += extraPaddingBetweenWords;
  72482. }
  72483. }
  72484. }
  72485. }
  72486. void GlyphArrangement::draw (const Graphics& g) const
  72487. {
  72488. for (int i = 0; i < glyphs.size(); ++i)
  72489. {
  72490. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  72491. if (pg->font.isUnderlined())
  72492. {
  72493. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  72494. float nextX = pg->x + pg->w;
  72495. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  72496. nextX = glyphs.getUnchecked (i + 1)->x;
  72497. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  72498. nextX - pg->x, lineThickness);
  72499. }
  72500. pg->draw (g);
  72501. }
  72502. }
  72503. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  72504. {
  72505. for (int i = 0; i < glyphs.size(); ++i)
  72506. {
  72507. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  72508. if (pg->font.isUnderlined())
  72509. {
  72510. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  72511. float nextX = pg->x + pg->w;
  72512. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  72513. nextX = glyphs.getUnchecked (i + 1)->x;
  72514. Path p;
  72515. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  72516. nextX, pg->y + lineThickness * 2.0f),
  72517. lineThickness);
  72518. g.fillPath (p, transform);
  72519. }
  72520. pg->draw (g, transform);
  72521. }
  72522. }
  72523. void GlyphArrangement::createPath (Path& path) const
  72524. {
  72525. for (int i = 0; i < glyphs.size(); ++i)
  72526. glyphs.getUnchecked (i)->createPath (path);
  72527. }
  72528. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  72529. {
  72530. for (int i = 0; i < glyphs.size(); ++i)
  72531. if (glyphs.getUnchecked (i)->hitTest (x, y))
  72532. return i;
  72533. return -1;
  72534. }
  72535. END_JUCE_NAMESPACE
  72536. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  72537. /*** Start of inlined file: juce_TextLayout.cpp ***/
  72538. BEGIN_JUCE_NAMESPACE
  72539. class TextLayout::Token
  72540. {
  72541. public:
  72542. String text;
  72543. Font font;
  72544. int x, y, w, h;
  72545. int line, lineHeight;
  72546. bool isWhitespace, isNewLine;
  72547. Token (const String& t,
  72548. const Font& f,
  72549. const bool isWhitespace_)
  72550. : text (t),
  72551. font (f),
  72552. x(0),
  72553. y(0),
  72554. isWhitespace (isWhitespace_)
  72555. {
  72556. w = font.getStringWidth (t);
  72557. h = roundToInt (f.getHeight());
  72558. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  72559. }
  72560. Token (const Token& other)
  72561. : text (other.text),
  72562. font (other.font),
  72563. x (other.x),
  72564. y (other.y),
  72565. w (other.w),
  72566. h (other.h),
  72567. line (other.line),
  72568. lineHeight (other.lineHeight),
  72569. isWhitespace (other.isWhitespace),
  72570. isNewLine (other.isNewLine)
  72571. {
  72572. }
  72573. ~Token()
  72574. {
  72575. }
  72576. void draw (Graphics& g,
  72577. const int xOffset,
  72578. const int yOffset)
  72579. {
  72580. if (! isWhitespace)
  72581. {
  72582. g.setFont (font);
  72583. g.drawSingleLineText (text.trimEnd(),
  72584. xOffset + x,
  72585. yOffset + y + (lineHeight - h)
  72586. + roundToInt (font.getAscent()));
  72587. }
  72588. }
  72589. juce_UseDebuggingNewOperator
  72590. };
  72591. TextLayout::TextLayout()
  72592. : totalLines (0)
  72593. {
  72594. tokens.ensureStorageAllocated (64);
  72595. }
  72596. TextLayout::TextLayout (const String& text, const Font& font)
  72597. : totalLines (0)
  72598. {
  72599. tokens.ensureStorageAllocated (64);
  72600. appendText (text, font);
  72601. }
  72602. TextLayout::TextLayout (const TextLayout& other)
  72603. : totalLines (0)
  72604. {
  72605. *this = other;
  72606. }
  72607. TextLayout& TextLayout::operator= (const TextLayout& other)
  72608. {
  72609. if (this != &other)
  72610. {
  72611. clear();
  72612. totalLines = other.totalLines;
  72613. tokens.addCopiesOf (other.tokens);
  72614. }
  72615. return *this;
  72616. }
  72617. TextLayout::~TextLayout()
  72618. {
  72619. clear();
  72620. }
  72621. void TextLayout::clear()
  72622. {
  72623. tokens.clear();
  72624. totalLines = 0;
  72625. }
  72626. void TextLayout::appendText (const String& text, const Font& font)
  72627. {
  72628. const juce_wchar* t = text;
  72629. String currentString;
  72630. int lastCharType = 0;
  72631. for (;;)
  72632. {
  72633. const juce_wchar c = *t++;
  72634. if (c == 0)
  72635. break;
  72636. int charType;
  72637. if (c == '\r' || c == '\n')
  72638. {
  72639. charType = 0;
  72640. }
  72641. else if (CharacterFunctions::isWhitespace (c))
  72642. {
  72643. charType = 2;
  72644. }
  72645. else
  72646. {
  72647. charType = 1;
  72648. }
  72649. if (charType == 0 || charType != lastCharType)
  72650. {
  72651. if (currentString.isNotEmpty())
  72652. {
  72653. tokens.add (new Token (currentString, font,
  72654. lastCharType == 2 || lastCharType == 0));
  72655. }
  72656. currentString = String::charToString (c);
  72657. if (c == '\r' && *t == '\n')
  72658. currentString += *t++;
  72659. }
  72660. else
  72661. {
  72662. currentString += c;
  72663. }
  72664. lastCharType = charType;
  72665. }
  72666. if (currentString.isNotEmpty())
  72667. tokens.add (new Token (currentString, font, lastCharType == 2));
  72668. }
  72669. void TextLayout::setText (const String& text, const Font& font)
  72670. {
  72671. clear();
  72672. appendText (text, font);
  72673. }
  72674. void TextLayout::layout (int maxWidth,
  72675. const Justification& justification,
  72676. const bool attemptToBalanceLineLengths)
  72677. {
  72678. if (attemptToBalanceLineLengths)
  72679. {
  72680. const int originalW = maxWidth;
  72681. int bestWidth = maxWidth;
  72682. float bestLineProportion = 0.0f;
  72683. while (maxWidth > originalW / 2)
  72684. {
  72685. layout (maxWidth, justification, false);
  72686. if (getNumLines() <= 1)
  72687. return;
  72688. const int lastLineW = getLineWidth (getNumLines() - 1);
  72689. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  72690. const float prop = lastLineW / (float) lastButOneLineW;
  72691. if (prop > 0.9f)
  72692. return;
  72693. if (prop > bestLineProportion)
  72694. {
  72695. bestLineProportion = prop;
  72696. bestWidth = maxWidth;
  72697. }
  72698. maxWidth -= 10;
  72699. }
  72700. layout (bestWidth, justification, false);
  72701. }
  72702. else
  72703. {
  72704. int x = 0;
  72705. int y = 0;
  72706. int h = 0;
  72707. totalLines = 0;
  72708. int i;
  72709. for (i = 0; i < tokens.size(); ++i)
  72710. {
  72711. Token* const t = tokens.getUnchecked(i);
  72712. t->x = x;
  72713. t->y = y;
  72714. t->line = totalLines;
  72715. x += t->w;
  72716. h = jmax (h, t->h);
  72717. const Token* nextTok = tokens [i + 1];
  72718. if (nextTok == 0)
  72719. break;
  72720. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  72721. {
  72722. // finished a line, so go back and update the heights of the things on it
  72723. for (int j = i; j >= 0; --j)
  72724. {
  72725. Token* const tok = tokens.getUnchecked(j);
  72726. if (tok->line == totalLines)
  72727. tok->lineHeight = h;
  72728. else
  72729. break;
  72730. }
  72731. x = 0;
  72732. y += h;
  72733. h = 0;
  72734. ++totalLines;
  72735. }
  72736. }
  72737. // finished a line, so go back and update the heights of the things on it
  72738. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  72739. {
  72740. Token* const t = tokens.getUnchecked(j);
  72741. if (t->line == totalLines)
  72742. t->lineHeight = h;
  72743. else
  72744. break;
  72745. }
  72746. ++totalLines;
  72747. if (! justification.testFlags (Justification::left))
  72748. {
  72749. int totalW = getWidth();
  72750. for (i = totalLines; --i >= 0;)
  72751. {
  72752. const int lineW = getLineWidth (i);
  72753. int dx = 0;
  72754. if (justification.testFlags (Justification::horizontallyCentred))
  72755. dx = (totalW - lineW) / 2;
  72756. else if (justification.testFlags (Justification::right))
  72757. dx = totalW - lineW;
  72758. for (int j = tokens.size(); --j >= 0;)
  72759. {
  72760. Token* const t = tokens.getUnchecked(j);
  72761. if (t->line == i)
  72762. t->x += dx;
  72763. }
  72764. }
  72765. }
  72766. }
  72767. }
  72768. int TextLayout::getLineWidth (const int lineNumber) const
  72769. {
  72770. int maxW = 0;
  72771. for (int i = tokens.size(); --i >= 0;)
  72772. {
  72773. const Token* const t = tokens.getUnchecked(i);
  72774. if (t->line == lineNumber && ! t->isWhitespace)
  72775. maxW = jmax (maxW, t->x + t->w);
  72776. }
  72777. return maxW;
  72778. }
  72779. int TextLayout::getWidth() const
  72780. {
  72781. int maxW = 0;
  72782. for (int i = tokens.size(); --i >= 0;)
  72783. {
  72784. const Token* const t = tokens.getUnchecked(i);
  72785. if (! t->isWhitespace)
  72786. maxW = jmax (maxW, t->x + t->w);
  72787. }
  72788. return maxW;
  72789. }
  72790. int TextLayout::getHeight() const
  72791. {
  72792. int maxH = 0;
  72793. for (int i = tokens.size(); --i >= 0;)
  72794. {
  72795. const Token* const t = tokens.getUnchecked(i);
  72796. if (! t->isWhitespace)
  72797. maxH = jmax (maxH, t->y + t->h);
  72798. }
  72799. return maxH;
  72800. }
  72801. void TextLayout::draw (Graphics& g,
  72802. const int xOffset,
  72803. const int yOffset) const
  72804. {
  72805. for (int i = tokens.size(); --i >= 0;)
  72806. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  72807. }
  72808. void TextLayout::drawWithin (Graphics& g,
  72809. int x, int y, int w, int h,
  72810. const Justification& justification) const
  72811. {
  72812. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  72813. x, y, w, h);
  72814. draw (g, x, y);
  72815. }
  72816. END_JUCE_NAMESPACE
  72817. /*** End of inlined file: juce_TextLayout.cpp ***/
  72818. /*** Start of inlined file: juce_Typeface.cpp ***/
  72819. BEGIN_JUCE_NAMESPACE
  72820. Typeface::Typeface (const String& name_) throw()
  72821. : name (name_)
  72822. {
  72823. }
  72824. Typeface::~Typeface()
  72825. {
  72826. }
  72827. class CustomTypeface::GlyphInfo
  72828. {
  72829. public:
  72830. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  72831. : character (character_), path (path_), width (width_)
  72832. {
  72833. }
  72834. ~GlyphInfo() throw()
  72835. {
  72836. }
  72837. struct KerningPair
  72838. {
  72839. juce_wchar character2;
  72840. float kerningAmount;
  72841. };
  72842. void addKerningPair (const juce_wchar subsequentCharacter,
  72843. const float extraKerningAmount) throw()
  72844. {
  72845. KerningPair kp;
  72846. kp.character2 = subsequentCharacter;
  72847. kp.kerningAmount = extraKerningAmount;
  72848. kerningPairs.add (kp);
  72849. }
  72850. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  72851. {
  72852. if (subsequentCharacter != 0)
  72853. {
  72854. for (int i = kerningPairs.size(); --i >= 0;)
  72855. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  72856. return width + kerningPairs.getReference(i).kerningAmount;
  72857. }
  72858. return width;
  72859. }
  72860. const juce_wchar character;
  72861. const Path path;
  72862. float width;
  72863. Array <KerningPair> kerningPairs;
  72864. juce_UseDebuggingNewOperator
  72865. private:
  72866. GlyphInfo (const GlyphInfo&);
  72867. GlyphInfo& operator= (const GlyphInfo&);
  72868. };
  72869. CustomTypeface::CustomTypeface()
  72870. : Typeface (String::empty)
  72871. {
  72872. clear();
  72873. }
  72874. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  72875. : Typeface (String::empty)
  72876. {
  72877. clear();
  72878. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  72879. BufferedInputStream in (&gzin, 32768, false);
  72880. name = in.readString();
  72881. isBold = in.readBool();
  72882. isItalic = in.readBool();
  72883. ascent = in.readFloat();
  72884. defaultCharacter = (juce_wchar) in.readShort();
  72885. int i, numChars = in.readInt();
  72886. for (i = 0; i < numChars; ++i)
  72887. {
  72888. const juce_wchar c = (juce_wchar) in.readShort();
  72889. const float width = in.readFloat();
  72890. Path p;
  72891. p.loadPathFromStream (in);
  72892. addGlyph (c, p, width);
  72893. }
  72894. const int numKerningPairs = in.readInt();
  72895. for (i = 0; i < numKerningPairs; ++i)
  72896. {
  72897. const juce_wchar char1 = (juce_wchar) in.readShort();
  72898. const juce_wchar char2 = (juce_wchar) in.readShort();
  72899. addKerningPair (char1, char2, in.readFloat());
  72900. }
  72901. }
  72902. CustomTypeface::~CustomTypeface()
  72903. {
  72904. }
  72905. void CustomTypeface::clear()
  72906. {
  72907. defaultCharacter = 0;
  72908. ascent = 1.0f;
  72909. isBold = isItalic = false;
  72910. zeromem (lookupTable, sizeof (lookupTable));
  72911. glyphs.clear();
  72912. }
  72913. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  72914. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  72915. {
  72916. name = name_;
  72917. defaultCharacter = defaultCharacter_;
  72918. ascent = ascent_;
  72919. isBold = isBold_;
  72920. isItalic = isItalic_;
  72921. }
  72922. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  72923. {
  72924. // Check that you're not trying to add the same character twice..
  72925. jassert (findGlyph (character, false) == 0);
  72926. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  72927. lookupTable [character] = (short) glyphs.size();
  72928. glyphs.add (new GlyphInfo (character, path, width));
  72929. }
  72930. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  72931. {
  72932. if (extraAmount != 0)
  72933. {
  72934. GlyphInfo* const g = findGlyph (char1, true);
  72935. jassert (g != 0); // can only add kerning pairs for characters that exist!
  72936. if (g != 0)
  72937. g->addKerningPair (char2, extraAmount);
  72938. }
  72939. }
  72940. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  72941. {
  72942. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  72943. return glyphs [(int) lookupTable [(int) character]];
  72944. for (int i = 0; i < glyphs.size(); ++i)
  72945. {
  72946. GlyphInfo* const g = glyphs.getUnchecked(i);
  72947. if (g->character == character)
  72948. return g;
  72949. }
  72950. if (loadIfNeeded && loadGlyphIfPossible (character))
  72951. return findGlyph (character, false);
  72952. return 0;
  72953. }
  72954. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  72955. {
  72956. GlyphInfo* glyph = findGlyph (character, true);
  72957. if (glyph == 0)
  72958. {
  72959. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  72960. glyph = findGlyph (L' ', true);
  72961. if (glyph == 0)
  72962. {
  72963. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  72964. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  72965. if (fallbackTypeface != 0 && fallbackTypeface != this)
  72966. {
  72967. //xxx
  72968. }
  72969. if (glyph == 0)
  72970. glyph = findGlyph (defaultCharacter, true);
  72971. }
  72972. }
  72973. return glyph;
  72974. }
  72975. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  72976. {
  72977. return false;
  72978. }
  72979. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  72980. {
  72981. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  72982. for (int i = 0; i < numCharacters; ++i)
  72983. {
  72984. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  72985. Array <int> glyphIndexes;
  72986. Array <float> offsets;
  72987. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  72988. const int glyphIndex = glyphIndexes.getFirst();
  72989. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  72990. {
  72991. const float glyphWidth = offsets[1];
  72992. Path p;
  72993. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  72994. addGlyph (c, p, glyphWidth);
  72995. for (int j = glyphs.size() - 1; --j >= 0;)
  72996. {
  72997. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  72998. glyphIndexes.clearQuick();
  72999. offsets.clearQuick();
  73000. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73001. if (offsets.size() > 1)
  73002. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73003. }
  73004. }
  73005. }
  73006. }
  73007. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73008. {
  73009. GZIPCompressorOutputStream out (&outputStream);
  73010. out.writeString (name);
  73011. out.writeBool (isBold);
  73012. out.writeBool (isItalic);
  73013. out.writeFloat (ascent);
  73014. out.writeShort ((short) (unsigned short) defaultCharacter);
  73015. out.writeInt (glyphs.size());
  73016. int i, numKerningPairs = 0;
  73017. for (i = 0; i < glyphs.size(); ++i)
  73018. {
  73019. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73020. out.writeShort ((short) (unsigned short) g->character);
  73021. out.writeFloat (g->width);
  73022. g->path.writePathToStream (out);
  73023. numKerningPairs += g->kerningPairs.size();
  73024. }
  73025. out.writeInt (numKerningPairs);
  73026. for (i = 0; i < glyphs.size(); ++i)
  73027. {
  73028. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73029. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73030. {
  73031. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73032. out.writeShort ((short) (unsigned short) g->character);
  73033. out.writeShort ((short) (unsigned short) p.character2);
  73034. out.writeFloat (p.kerningAmount);
  73035. }
  73036. }
  73037. return true;
  73038. }
  73039. float CustomTypeface::getAscent() const
  73040. {
  73041. return ascent;
  73042. }
  73043. float CustomTypeface::getDescent() const
  73044. {
  73045. return 1.0f - ascent;
  73046. }
  73047. float CustomTypeface::getStringWidth (const String& text)
  73048. {
  73049. float x = 0;
  73050. const juce_wchar* t = text;
  73051. while (*t != 0)
  73052. {
  73053. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73054. if (glyph != 0)
  73055. x += glyph->getHorizontalSpacing (*t);
  73056. }
  73057. return x;
  73058. }
  73059. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73060. {
  73061. xOffsets.add (0);
  73062. float x = 0;
  73063. const juce_wchar* t = text;
  73064. while (*t != 0)
  73065. {
  73066. const juce_wchar c = *t++;
  73067. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  73068. if (glyph != 0)
  73069. {
  73070. x += glyph->getHorizontalSpacing (*t);
  73071. resultGlyphs.add ((int) glyph->character);
  73072. xOffsets.add (x);
  73073. }
  73074. }
  73075. }
  73076. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73077. {
  73078. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  73079. if (glyph != 0)
  73080. {
  73081. path = glyph->path;
  73082. return true;
  73083. }
  73084. return false;
  73085. }
  73086. END_JUCE_NAMESPACE
  73087. /*** End of inlined file: juce_Typeface.cpp ***/
  73088. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73089. BEGIN_JUCE_NAMESPACE
  73090. AffineTransform::AffineTransform() throw()
  73091. : mat00 (1.0f),
  73092. mat01 (0),
  73093. mat02 (0),
  73094. mat10 (0),
  73095. mat11 (1.0f),
  73096. mat12 (0)
  73097. {
  73098. }
  73099. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73100. : mat00 (other.mat00),
  73101. mat01 (other.mat01),
  73102. mat02 (other.mat02),
  73103. mat10 (other.mat10),
  73104. mat11 (other.mat11),
  73105. mat12 (other.mat12)
  73106. {
  73107. }
  73108. AffineTransform::AffineTransform (const float mat00_,
  73109. const float mat01_,
  73110. const float mat02_,
  73111. const float mat10_,
  73112. const float mat11_,
  73113. const float mat12_) throw()
  73114. : mat00 (mat00_),
  73115. mat01 (mat01_),
  73116. mat02 (mat02_),
  73117. mat10 (mat10_),
  73118. mat11 (mat11_),
  73119. mat12 (mat12_)
  73120. {
  73121. }
  73122. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73123. {
  73124. mat00 = other.mat00;
  73125. mat01 = other.mat01;
  73126. mat02 = other.mat02;
  73127. mat10 = other.mat10;
  73128. mat11 = other.mat11;
  73129. mat12 = other.mat12;
  73130. return *this;
  73131. }
  73132. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73133. {
  73134. return mat00 == other.mat00
  73135. && mat01 == other.mat01
  73136. && mat02 == other.mat02
  73137. && mat10 == other.mat10
  73138. && mat11 == other.mat11
  73139. && mat12 == other.mat12;
  73140. }
  73141. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73142. {
  73143. return ! operator== (other);
  73144. }
  73145. bool AffineTransform::isIdentity() const throw()
  73146. {
  73147. return (mat01 == 0)
  73148. && (mat02 == 0)
  73149. && (mat10 == 0)
  73150. && (mat12 == 0)
  73151. && (mat00 == 1.0f)
  73152. && (mat11 == 1.0f);
  73153. }
  73154. const AffineTransform AffineTransform::identity;
  73155. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  73156. {
  73157. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  73158. other.mat00 * mat01 + other.mat01 * mat11,
  73159. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  73160. other.mat10 * mat00 + other.mat11 * mat10,
  73161. other.mat10 * mat01 + other.mat11 * mat11,
  73162. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  73163. }
  73164. const AffineTransform AffineTransform::followedBy (const float omat00,
  73165. const float omat01,
  73166. const float omat02,
  73167. const float omat10,
  73168. const float omat11,
  73169. const float omat12) const throw()
  73170. {
  73171. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  73172. omat00 * mat01 + omat01 * mat11,
  73173. omat00 * mat02 + omat01 * mat12 + omat02,
  73174. omat10 * mat00 + omat11 * mat10,
  73175. omat10 * mat01 + omat11 * mat11,
  73176. omat10 * mat02 + omat11 * mat12 + omat12);
  73177. }
  73178. const AffineTransform AffineTransform::translated (const float dx,
  73179. const float dy) const throw()
  73180. {
  73181. return AffineTransform (mat00, mat01, mat02 + dx,
  73182. mat10, mat11, mat12 + dy);
  73183. }
  73184. const AffineTransform AffineTransform::translation (const float dx,
  73185. const float dy) throw()
  73186. {
  73187. return AffineTransform (1.0f, 0, dx,
  73188. 0, 1.0f, dy);
  73189. }
  73190. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  73191. {
  73192. const float cosRad = std::cos (rad);
  73193. const float sinRad = std::sin (rad);
  73194. return followedBy (cosRad, -sinRad, 0,
  73195. sinRad, cosRad, 0);
  73196. }
  73197. const AffineTransform AffineTransform::rotation (const float rad) throw()
  73198. {
  73199. const float cosRad = std::cos (rad);
  73200. const float sinRad = std::sin (rad);
  73201. return AffineTransform (cosRad, -sinRad, 0,
  73202. sinRad, cosRad, 0);
  73203. }
  73204. const AffineTransform AffineTransform::rotated (const float angle,
  73205. const float pivotX,
  73206. const float pivotY) const throw()
  73207. {
  73208. return translated (-pivotX, -pivotY)
  73209. .rotated (angle)
  73210. .translated (pivotX, pivotY);
  73211. }
  73212. const AffineTransform AffineTransform::rotation (const float angle,
  73213. const float pivotX,
  73214. const float pivotY) throw()
  73215. {
  73216. return translation (-pivotX, -pivotY)
  73217. .rotated (angle)
  73218. .translated (pivotX, pivotY);
  73219. }
  73220. const AffineTransform AffineTransform::scaled (const float factorX,
  73221. const float factorY) const throw()
  73222. {
  73223. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  73224. factorY * mat10, factorY * mat11, factorY * mat12);
  73225. }
  73226. const AffineTransform AffineTransform::scale (const float factorX,
  73227. const float factorY) throw()
  73228. {
  73229. return AffineTransform (factorX, 0, 0,
  73230. 0, factorY, 0);
  73231. }
  73232. const AffineTransform AffineTransform::sheared (const float shearX,
  73233. const float shearY) const throw()
  73234. {
  73235. return followedBy (1.0f, shearX, 0,
  73236. shearY, 1.0f, 0);
  73237. }
  73238. const AffineTransform AffineTransform::inverted() const throw()
  73239. {
  73240. double determinant = (mat00 * mat11 - mat10 * mat01);
  73241. if (determinant != 0.0)
  73242. {
  73243. determinant = 1.0 / determinant;
  73244. const float dst00 = (float) (mat11 * determinant);
  73245. const float dst10 = (float) (-mat10 * determinant);
  73246. const float dst01 = (float) (-mat01 * determinant);
  73247. const float dst11 = (float) (mat00 * determinant);
  73248. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  73249. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  73250. }
  73251. else
  73252. {
  73253. // singularity..
  73254. return *this;
  73255. }
  73256. }
  73257. bool AffineTransform::isSingularity() const throw()
  73258. {
  73259. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  73260. }
  73261. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  73262. const float x10, const float y10,
  73263. const float x01, const float y01) throw()
  73264. {
  73265. return AffineTransform (x10 - x00, x01 - x00, x00,
  73266. y10 - y00, y01 - y00, y00);
  73267. }
  73268. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  73269. const float sx2, const float sy2, const float tx2, const float ty2,
  73270. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  73271. {
  73272. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  73273. .inverted()
  73274. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  73275. }
  73276. bool AffineTransform::isOnlyTranslation() const throw()
  73277. {
  73278. return (mat01 == 0)
  73279. && (mat10 == 0)
  73280. && (mat00 == 1.0f)
  73281. && (mat11 == 1.0f);
  73282. }
  73283. END_JUCE_NAMESPACE
  73284. /*** End of inlined file: juce_AffineTransform.cpp ***/
  73285. /*** Start of inlined file: juce_BorderSize.cpp ***/
  73286. BEGIN_JUCE_NAMESPACE
  73287. BorderSize::BorderSize() throw()
  73288. : top (0),
  73289. left (0),
  73290. bottom (0),
  73291. right (0)
  73292. {
  73293. }
  73294. BorderSize::BorderSize (const BorderSize& other) throw()
  73295. : top (other.top),
  73296. left (other.left),
  73297. bottom (other.bottom),
  73298. right (other.right)
  73299. {
  73300. }
  73301. BorderSize::BorderSize (const int topGap,
  73302. const int leftGap,
  73303. const int bottomGap,
  73304. const int rightGap) throw()
  73305. : top (topGap),
  73306. left (leftGap),
  73307. bottom (bottomGap),
  73308. right (rightGap)
  73309. {
  73310. }
  73311. BorderSize::BorderSize (const int allGaps) throw()
  73312. : top (allGaps),
  73313. left (allGaps),
  73314. bottom (allGaps),
  73315. right (allGaps)
  73316. {
  73317. }
  73318. BorderSize::~BorderSize() throw()
  73319. {
  73320. }
  73321. void BorderSize::setTop (const int newTopGap) throw()
  73322. {
  73323. top = newTopGap;
  73324. }
  73325. void BorderSize::setLeft (const int newLeftGap) throw()
  73326. {
  73327. left = newLeftGap;
  73328. }
  73329. void BorderSize::setBottom (const int newBottomGap) throw()
  73330. {
  73331. bottom = newBottomGap;
  73332. }
  73333. void BorderSize::setRight (const int newRightGap) throw()
  73334. {
  73335. right = newRightGap;
  73336. }
  73337. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  73338. {
  73339. return Rectangle<int> (r.getX() + left,
  73340. r.getY() + top,
  73341. r.getWidth() - (left + right),
  73342. r.getHeight() - (top + bottom));
  73343. }
  73344. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  73345. {
  73346. r.setBounds (r.getX() + left,
  73347. r.getY() + top,
  73348. r.getWidth() - (left + right),
  73349. r.getHeight() - (top + bottom));
  73350. }
  73351. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  73352. {
  73353. return Rectangle<int> (r.getX() - left,
  73354. r.getY() - top,
  73355. r.getWidth() + (left + right),
  73356. r.getHeight() + (top + bottom));
  73357. }
  73358. void BorderSize::addTo (Rectangle<int>& r) const throw()
  73359. {
  73360. r.setBounds (r.getX() - left,
  73361. r.getY() - top,
  73362. r.getWidth() + (left + right),
  73363. r.getHeight() + (top + bottom));
  73364. }
  73365. bool BorderSize::operator== (const BorderSize& other) const throw()
  73366. {
  73367. return top == other.top
  73368. && left == other.left
  73369. && bottom == other.bottom
  73370. && right == other.right;
  73371. }
  73372. bool BorderSize::operator!= (const BorderSize& other) const throw()
  73373. {
  73374. return ! operator== (other);
  73375. }
  73376. END_JUCE_NAMESPACE
  73377. /*** End of inlined file: juce_BorderSize.cpp ***/
  73378. /*** Start of inlined file: juce_Path.cpp ***/
  73379. BEGIN_JUCE_NAMESPACE
  73380. // tests that some co-ords aren't NaNs
  73381. #define CHECK_COORDS_ARE_VALID(x, y) \
  73382. jassert (x == x && y == y);
  73383. namespace PathHelpers
  73384. {
  73385. static const float ellipseAngularIncrement = 0.05f;
  73386. static const String nextToken (const juce_wchar*& t)
  73387. {
  73388. while (CharacterFunctions::isWhitespace (*t))
  73389. ++t;
  73390. const juce_wchar* const start = t;
  73391. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  73392. ++t;
  73393. return String (start, (int) (t - start));
  73394. }
  73395. }
  73396. const float Path::lineMarker = 100001.0f;
  73397. const float Path::moveMarker = 100002.0f;
  73398. const float Path::quadMarker = 100003.0f;
  73399. const float Path::cubicMarker = 100004.0f;
  73400. const float Path::closeSubPathMarker = 100005.0f;
  73401. Path::Path()
  73402. : numElements (0),
  73403. pathXMin (0),
  73404. pathXMax (0),
  73405. pathYMin (0),
  73406. pathYMax (0),
  73407. useNonZeroWinding (true)
  73408. {
  73409. }
  73410. Path::~Path()
  73411. {
  73412. }
  73413. Path::Path (const Path& other)
  73414. : numElements (other.numElements),
  73415. pathXMin (other.pathXMin),
  73416. pathXMax (other.pathXMax),
  73417. pathYMin (other.pathYMin),
  73418. pathYMax (other.pathYMax),
  73419. useNonZeroWinding (other.useNonZeroWinding)
  73420. {
  73421. if (numElements > 0)
  73422. {
  73423. data.setAllocatedSize ((int) numElements);
  73424. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  73425. }
  73426. }
  73427. Path& Path::operator= (const Path& other)
  73428. {
  73429. if (this != &other)
  73430. {
  73431. data.ensureAllocatedSize ((int) other.numElements);
  73432. numElements = other.numElements;
  73433. pathXMin = other.pathXMin;
  73434. pathXMax = other.pathXMax;
  73435. pathYMin = other.pathYMin;
  73436. pathYMax = other.pathYMax;
  73437. useNonZeroWinding = other.useNonZeroWinding;
  73438. if (numElements > 0)
  73439. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  73440. }
  73441. return *this;
  73442. }
  73443. bool Path::operator== (const Path& other) const throw()
  73444. {
  73445. return ! operator!= (other);
  73446. }
  73447. bool Path::operator!= (const Path& other) const throw()
  73448. {
  73449. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  73450. return true;
  73451. for (size_t i = 0; i < numElements; ++i)
  73452. if (data.elements[i] != other.data.elements[i])
  73453. return true;
  73454. return false;
  73455. }
  73456. void Path::clear() throw()
  73457. {
  73458. numElements = 0;
  73459. pathXMin = 0;
  73460. pathYMin = 0;
  73461. pathYMax = 0;
  73462. pathXMax = 0;
  73463. }
  73464. void Path::swapWithPath (Path& other) throw()
  73465. {
  73466. data.swapWith (other.data);
  73467. swapVariables <size_t> (numElements, other.numElements);
  73468. swapVariables <float> (pathXMin, other.pathXMin);
  73469. swapVariables <float> (pathXMax, other.pathXMax);
  73470. swapVariables <float> (pathYMin, other.pathYMin);
  73471. swapVariables <float> (pathYMax, other.pathYMax);
  73472. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  73473. }
  73474. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  73475. {
  73476. useNonZeroWinding = isNonZero;
  73477. }
  73478. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  73479. const bool preserveProportions) throw()
  73480. {
  73481. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  73482. }
  73483. bool Path::isEmpty() const throw()
  73484. {
  73485. size_t i = 0;
  73486. while (i < numElements)
  73487. {
  73488. const float type = data.elements [i++];
  73489. if (type == moveMarker)
  73490. {
  73491. i += 2;
  73492. }
  73493. else if (type == lineMarker
  73494. || type == quadMarker
  73495. || type == cubicMarker)
  73496. {
  73497. return false;
  73498. }
  73499. }
  73500. return true;
  73501. }
  73502. const Rectangle<float> Path::getBounds() const throw()
  73503. {
  73504. return Rectangle<float> (pathXMin, pathYMin,
  73505. pathXMax - pathXMin,
  73506. pathYMax - pathYMin);
  73507. }
  73508. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  73509. {
  73510. return getBounds().transformed (transform);
  73511. }
  73512. void Path::startNewSubPath (const float x, const float y)
  73513. {
  73514. CHECK_COORDS_ARE_VALID (x, y);
  73515. if (numElements == 0)
  73516. {
  73517. pathXMin = pathXMax = x;
  73518. pathYMin = pathYMax = y;
  73519. }
  73520. else
  73521. {
  73522. pathXMin = jmin (pathXMin, x);
  73523. pathXMax = jmax (pathXMax, x);
  73524. pathYMin = jmin (pathYMin, y);
  73525. pathYMax = jmax (pathYMax, y);
  73526. }
  73527. data.ensureAllocatedSize ((int) numElements + 3);
  73528. data.elements [numElements++] = moveMarker;
  73529. data.elements [numElements++] = x;
  73530. data.elements [numElements++] = y;
  73531. }
  73532. void Path::startNewSubPath (const Point<float>& start)
  73533. {
  73534. startNewSubPath (start.getX(), start.getY());
  73535. }
  73536. void Path::lineTo (const float x, const float y)
  73537. {
  73538. CHECK_COORDS_ARE_VALID (x, y);
  73539. if (numElements == 0)
  73540. startNewSubPath (0, 0);
  73541. data.ensureAllocatedSize ((int) numElements + 3);
  73542. data.elements [numElements++] = lineMarker;
  73543. data.elements [numElements++] = x;
  73544. data.elements [numElements++] = y;
  73545. pathXMin = jmin (pathXMin, x);
  73546. pathXMax = jmax (pathXMax, x);
  73547. pathYMin = jmin (pathYMin, y);
  73548. pathYMax = jmax (pathYMax, y);
  73549. }
  73550. void Path::lineTo (const Point<float>& end)
  73551. {
  73552. lineTo (end.getX(), end.getY());
  73553. }
  73554. void Path::quadraticTo (const float x1, const float y1,
  73555. const float x2, const float y2)
  73556. {
  73557. CHECK_COORDS_ARE_VALID (x1, y1);
  73558. CHECK_COORDS_ARE_VALID (x2, y2);
  73559. if (numElements == 0)
  73560. startNewSubPath (0, 0);
  73561. data.ensureAllocatedSize ((int) numElements + 5);
  73562. data.elements [numElements++] = quadMarker;
  73563. data.elements [numElements++] = x1;
  73564. data.elements [numElements++] = y1;
  73565. data.elements [numElements++] = x2;
  73566. data.elements [numElements++] = y2;
  73567. pathXMin = jmin (pathXMin, x1, x2);
  73568. pathXMax = jmax (pathXMax, x1, x2);
  73569. pathYMin = jmin (pathYMin, y1, y2);
  73570. pathYMax = jmax (pathYMax, y1, y2);
  73571. }
  73572. void Path::quadraticTo (const Point<float>& controlPoint,
  73573. const Point<float>& endPoint)
  73574. {
  73575. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  73576. endPoint.getX(), endPoint.getY());
  73577. }
  73578. void Path::cubicTo (const float x1, const float y1,
  73579. const float x2, const float y2,
  73580. const float x3, const float y3)
  73581. {
  73582. CHECK_COORDS_ARE_VALID (x1, y1);
  73583. CHECK_COORDS_ARE_VALID (x2, y2);
  73584. CHECK_COORDS_ARE_VALID (x3, y3);
  73585. if (numElements == 0)
  73586. startNewSubPath (0, 0);
  73587. data.ensureAllocatedSize ((int) numElements + 7);
  73588. data.elements [numElements++] = cubicMarker;
  73589. data.elements [numElements++] = x1;
  73590. data.elements [numElements++] = y1;
  73591. data.elements [numElements++] = x2;
  73592. data.elements [numElements++] = y2;
  73593. data.elements [numElements++] = x3;
  73594. data.elements [numElements++] = y3;
  73595. pathXMin = jmin (pathXMin, x1, x2, x3);
  73596. pathXMax = jmax (pathXMax, x1, x2, x3);
  73597. pathYMin = jmin (pathYMin, y1, y2, y3);
  73598. pathYMax = jmax (pathYMax, y1, y2, y3);
  73599. }
  73600. void Path::cubicTo (const Point<float>& controlPoint1,
  73601. const Point<float>& controlPoint2,
  73602. const Point<float>& endPoint)
  73603. {
  73604. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  73605. controlPoint2.getX(), controlPoint2.getY(),
  73606. endPoint.getX(), endPoint.getY());
  73607. }
  73608. void Path::closeSubPath()
  73609. {
  73610. if (numElements > 0
  73611. && data.elements [numElements - 1] != closeSubPathMarker)
  73612. {
  73613. data.ensureAllocatedSize ((int) numElements + 1);
  73614. data.elements [numElements++] = closeSubPathMarker;
  73615. }
  73616. }
  73617. const Point<float> Path::getCurrentPosition() const
  73618. {
  73619. size_t i = numElements - 1;
  73620. if (i > 0 && data.elements[i] == closeSubPathMarker)
  73621. {
  73622. while (i >= 0)
  73623. {
  73624. if (data.elements[i] == moveMarker)
  73625. {
  73626. i += 2;
  73627. break;
  73628. }
  73629. --i;
  73630. }
  73631. }
  73632. if (i > 0)
  73633. return Point<float> (data.elements [i - 1], data.elements [i]);
  73634. return Point<float>();
  73635. }
  73636. void Path::addRectangle (const float x, const float y,
  73637. const float w, const float h)
  73638. {
  73639. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  73640. if (w < 0)
  73641. swapVariables (x1, x2);
  73642. if (h < 0)
  73643. swapVariables (y1, y2);
  73644. data.ensureAllocatedSize ((int) numElements + 13);
  73645. if (numElements == 0)
  73646. {
  73647. pathXMin = x1;
  73648. pathXMax = x2;
  73649. pathYMin = y1;
  73650. pathYMax = y2;
  73651. }
  73652. else
  73653. {
  73654. pathXMin = jmin (pathXMin, x1);
  73655. pathXMax = jmax (pathXMax, x2);
  73656. pathYMin = jmin (pathYMin, y1);
  73657. pathYMax = jmax (pathYMax, y2);
  73658. }
  73659. data.elements [numElements++] = moveMarker;
  73660. data.elements [numElements++] = x1;
  73661. data.elements [numElements++] = y2;
  73662. data.elements [numElements++] = lineMarker;
  73663. data.elements [numElements++] = x1;
  73664. data.elements [numElements++] = y1;
  73665. data.elements [numElements++] = lineMarker;
  73666. data.elements [numElements++] = x2;
  73667. data.elements [numElements++] = y1;
  73668. data.elements [numElements++] = lineMarker;
  73669. data.elements [numElements++] = x2;
  73670. data.elements [numElements++] = y2;
  73671. data.elements [numElements++] = closeSubPathMarker;
  73672. }
  73673. void Path::addRectangle (const Rectangle<int>& rectangle)
  73674. {
  73675. addRectangle ((float) rectangle.getX(), (float) rectangle.getY(),
  73676. (float) rectangle.getWidth(), (float) rectangle.getHeight());
  73677. }
  73678. void Path::addRoundedRectangle (const float x, const float y,
  73679. const float w, const float h,
  73680. float csx,
  73681. float csy)
  73682. {
  73683. csx = jmin (csx, w * 0.5f);
  73684. csy = jmin (csy, h * 0.5f);
  73685. const float cs45x = csx * 0.45f;
  73686. const float cs45y = csy * 0.45f;
  73687. const float x2 = x + w;
  73688. const float y2 = y + h;
  73689. startNewSubPath (x + csx, y);
  73690. lineTo (x2 - csx, y);
  73691. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  73692. lineTo (x2, y2 - csy);
  73693. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  73694. lineTo (x + csx, y2);
  73695. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  73696. lineTo (x, y + csy);
  73697. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  73698. closeSubPath();
  73699. }
  73700. void Path::addRoundedRectangle (const float x, const float y,
  73701. const float w, const float h,
  73702. float cs)
  73703. {
  73704. addRoundedRectangle (x, y, w, h, cs, cs);
  73705. }
  73706. void Path::addTriangle (const float x1, const float y1,
  73707. const float x2, const float y2,
  73708. const float x3, const float y3)
  73709. {
  73710. startNewSubPath (x1, y1);
  73711. lineTo (x2, y2);
  73712. lineTo (x3, y3);
  73713. closeSubPath();
  73714. }
  73715. void Path::addQuadrilateral (const float x1, const float y1,
  73716. const float x2, const float y2,
  73717. const float x3, const float y3,
  73718. const float x4, const float y4)
  73719. {
  73720. startNewSubPath (x1, y1);
  73721. lineTo (x2, y2);
  73722. lineTo (x3, y3);
  73723. lineTo (x4, y4);
  73724. closeSubPath();
  73725. }
  73726. void Path::addEllipse (const float x, const float y,
  73727. const float w, const float h)
  73728. {
  73729. const float hw = w * 0.5f;
  73730. const float hw55 = hw * 0.55f;
  73731. const float hh = h * 0.5f;
  73732. const float hh45 = hh * 0.55f;
  73733. const float cx = x + hw;
  73734. const float cy = y + hh;
  73735. startNewSubPath (cx, cy - hh);
  73736. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  73737. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  73738. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  73739. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  73740. closeSubPath();
  73741. }
  73742. void Path::addArc (const float x, const float y,
  73743. const float w, const float h,
  73744. const float fromRadians,
  73745. const float toRadians,
  73746. const bool startAsNewSubPath)
  73747. {
  73748. const float radiusX = w / 2.0f;
  73749. const float radiusY = h / 2.0f;
  73750. addCentredArc (x + radiusX,
  73751. y + radiusY,
  73752. radiusX, radiusY,
  73753. 0.0f,
  73754. fromRadians, toRadians,
  73755. startAsNewSubPath);
  73756. }
  73757. void Path::addCentredArc (const float centreX, const float centreY,
  73758. const float radiusX, const float radiusY,
  73759. const float rotationOfEllipse,
  73760. const float fromRadians,
  73761. const float toRadians,
  73762. const bool startAsNewSubPath)
  73763. {
  73764. if (radiusX > 0.0f && radiusY > 0.0f)
  73765. {
  73766. const Point<float> centre (centreX, centreY);
  73767. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  73768. float angle = fromRadians;
  73769. if (startAsNewSubPath)
  73770. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  73771. if (fromRadians < toRadians)
  73772. {
  73773. if (startAsNewSubPath)
  73774. angle += PathHelpers::ellipseAngularIncrement;
  73775. while (angle < toRadians)
  73776. {
  73777. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  73778. angle += PathHelpers::ellipseAngularIncrement;
  73779. }
  73780. }
  73781. else
  73782. {
  73783. if (startAsNewSubPath)
  73784. angle -= PathHelpers::ellipseAngularIncrement;
  73785. while (angle > toRadians)
  73786. {
  73787. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  73788. angle -= PathHelpers::ellipseAngularIncrement;
  73789. }
  73790. }
  73791. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  73792. }
  73793. }
  73794. void Path::addPieSegment (const float x, const float y,
  73795. const float width, const float height,
  73796. const float fromRadians,
  73797. const float toRadians,
  73798. const float innerCircleProportionalSize)
  73799. {
  73800. float radiusX = width * 0.5f;
  73801. float radiusY = height * 0.5f;
  73802. const Point<float> centre (x + radiusX, y + radiusY);
  73803. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  73804. addArc (x, y, width, height, fromRadians, toRadians);
  73805. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  73806. {
  73807. closeSubPath();
  73808. if (innerCircleProportionalSize > 0)
  73809. {
  73810. radiusX *= innerCircleProportionalSize;
  73811. radiusY *= innerCircleProportionalSize;
  73812. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  73813. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  73814. }
  73815. }
  73816. else
  73817. {
  73818. if (innerCircleProportionalSize > 0)
  73819. {
  73820. radiusX *= innerCircleProportionalSize;
  73821. radiusY *= innerCircleProportionalSize;
  73822. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  73823. }
  73824. else
  73825. {
  73826. lineTo (centre);
  73827. }
  73828. }
  73829. closeSubPath();
  73830. }
  73831. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  73832. {
  73833. const Line<float> reversed (line.reversed());
  73834. lineThickness *= 0.5f;
  73835. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  73836. lineTo (line.getPointAlongLine (0, -lineThickness));
  73837. lineTo (reversed.getPointAlongLine (0, lineThickness));
  73838. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  73839. closeSubPath();
  73840. }
  73841. void Path::addArrow (const Line<float>& line, float lineThickness,
  73842. float arrowheadWidth, float arrowheadLength)
  73843. {
  73844. const Line<float> reversed (line.reversed());
  73845. lineThickness *= 0.5f;
  73846. arrowheadWidth *= 0.5f;
  73847. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  73848. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  73849. lineTo (line.getPointAlongLine (0, -lineThickness));
  73850. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  73851. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  73852. lineTo (line.getEnd());
  73853. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  73854. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  73855. closeSubPath();
  73856. }
  73857. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  73858. const float radius, const float startAngle)
  73859. {
  73860. jassert (numberOfSides > 1); // this would be silly.
  73861. if (numberOfSides > 1)
  73862. {
  73863. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  73864. for (int i = 0; i < numberOfSides; ++i)
  73865. {
  73866. const float angle = startAngle + i * angleBetweenPoints;
  73867. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  73868. if (i == 0)
  73869. startNewSubPath (p);
  73870. else
  73871. lineTo (p);
  73872. }
  73873. closeSubPath();
  73874. }
  73875. }
  73876. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  73877. const float innerRadius, const float outerRadius, const float startAngle)
  73878. {
  73879. jassert (numberOfPoints > 1); // this would be silly.
  73880. if (numberOfPoints > 1)
  73881. {
  73882. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  73883. for (int i = 0; i < numberOfPoints; ++i)
  73884. {
  73885. const float angle = startAngle + i * angleBetweenPoints;
  73886. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  73887. if (i == 0)
  73888. startNewSubPath (p);
  73889. else
  73890. lineTo (p);
  73891. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  73892. }
  73893. closeSubPath();
  73894. }
  73895. }
  73896. void Path::addBubble (float x, float y,
  73897. float w, float h,
  73898. float cs,
  73899. float tipX,
  73900. float tipY,
  73901. int whichSide,
  73902. float arrowPos,
  73903. float arrowWidth)
  73904. {
  73905. if (w > 1.0f && h > 1.0f)
  73906. {
  73907. cs = jmin (cs, w * 0.5f, h * 0.5f);
  73908. const float cs2 = 2.0f * cs;
  73909. startNewSubPath (x + cs, y);
  73910. if (whichSide == 0)
  73911. {
  73912. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  73913. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  73914. lineTo (arrowX1, y);
  73915. lineTo (tipX, tipY);
  73916. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  73917. }
  73918. lineTo (x + w - cs, y);
  73919. if (cs > 0.0f)
  73920. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  73921. if (whichSide == 3)
  73922. {
  73923. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  73924. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  73925. lineTo (x + w, arrowY1);
  73926. lineTo (tipX, tipY);
  73927. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  73928. }
  73929. lineTo (x + w, y + h - cs);
  73930. if (cs > 0.0f)
  73931. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  73932. if (whichSide == 2)
  73933. {
  73934. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  73935. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  73936. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  73937. lineTo (tipX, tipY);
  73938. lineTo (arrowX1, y + h);
  73939. }
  73940. lineTo (x + cs, y + h);
  73941. if (cs > 0.0f)
  73942. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  73943. if (whichSide == 1)
  73944. {
  73945. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  73946. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  73947. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  73948. lineTo (tipX, tipY);
  73949. lineTo (x, arrowY1);
  73950. }
  73951. lineTo (x, y + cs);
  73952. if (cs > 0.0f)
  73953. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  73954. closeSubPath();
  73955. }
  73956. }
  73957. void Path::addPath (const Path& other)
  73958. {
  73959. size_t i = 0;
  73960. while (i < other.numElements)
  73961. {
  73962. const float type = other.data.elements [i++];
  73963. if (type == moveMarker)
  73964. {
  73965. startNewSubPath (other.data.elements [i],
  73966. other.data.elements [i + 1]);
  73967. i += 2;
  73968. }
  73969. else if (type == lineMarker)
  73970. {
  73971. lineTo (other.data.elements [i],
  73972. other.data.elements [i + 1]);
  73973. i += 2;
  73974. }
  73975. else if (type == quadMarker)
  73976. {
  73977. quadraticTo (other.data.elements [i],
  73978. other.data.elements [i + 1],
  73979. other.data.elements [i + 2],
  73980. other.data.elements [i + 3]);
  73981. i += 4;
  73982. }
  73983. else if (type == cubicMarker)
  73984. {
  73985. cubicTo (other.data.elements [i],
  73986. other.data.elements [i + 1],
  73987. other.data.elements [i + 2],
  73988. other.data.elements [i + 3],
  73989. other.data.elements [i + 4],
  73990. other.data.elements [i + 5]);
  73991. i += 6;
  73992. }
  73993. else if (type == closeSubPathMarker)
  73994. {
  73995. closeSubPath();
  73996. }
  73997. else
  73998. {
  73999. // something's gone wrong with the element list!
  74000. jassertfalse;
  74001. }
  74002. }
  74003. }
  74004. void Path::addPath (const Path& other,
  74005. const AffineTransform& transformToApply)
  74006. {
  74007. size_t i = 0;
  74008. while (i < other.numElements)
  74009. {
  74010. const float type = other.data.elements [i++];
  74011. if (type == closeSubPathMarker)
  74012. {
  74013. closeSubPath();
  74014. }
  74015. else
  74016. {
  74017. float x = other.data.elements [i++];
  74018. float y = other.data.elements [i++];
  74019. transformToApply.transformPoint (x, y);
  74020. if (type == moveMarker)
  74021. {
  74022. startNewSubPath (x, y);
  74023. }
  74024. else if (type == lineMarker)
  74025. {
  74026. lineTo (x, y);
  74027. }
  74028. else if (type == quadMarker)
  74029. {
  74030. float x2 = other.data.elements [i++];
  74031. float y2 = other.data.elements [i++];
  74032. transformToApply.transformPoint (x2, y2);
  74033. quadraticTo (x, y, x2, y2);
  74034. }
  74035. else if (type == cubicMarker)
  74036. {
  74037. float x2 = other.data.elements [i++];
  74038. float y2 = other.data.elements [i++];
  74039. float x3 = other.data.elements [i++];
  74040. float y3 = other.data.elements [i++];
  74041. transformToApply.transformPoints (x2, y2, x3, y3);
  74042. cubicTo (x, y, x2, y2, x3, y3);
  74043. }
  74044. else
  74045. {
  74046. // something's gone wrong with the element list!
  74047. jassertfalse;
  74048. }
  74049. }
  74050. }
  74051. }
  74052. void Path::applyTransform (const AffineTransform& transform) throw()
  74053. {
  74054. size_t i = 0;
  74055. pathYMin = pathXMin = 0;
  74056. pathYMax = pathXMax = 0;
  74057. bool setMaxMin = false;
  74058. while (i < numElements)
  74059. {
  74060. const float type = data.elements [i++];
  74061. if (type == moveMarker)
  74062. {
  74063. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74064. if (setMaxMin)
  74065. {
  74066. pathXMin = jmin (pathXMin, data.elements [i]);
  74067. pathXMax = jmax (pathXMax, data.elements [i]);
  74068. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74069. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74070. }
  74071. else
  74072. {
  74073. pathXMin = pathXMax = data.elements [i];
  74074. pathYMin = pathYMax = data.elements [i + 1];
  74075. setMaxMin = true;
  74076. }
  74077. i += 2;
  74078. }
  74079. else if (type == lineMarker)
  74080. {
  74081. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74082. pathXMin = jmin (pathXMin, data.elements [i]);
  74083. pathXMax = jmax (pathXMax, data.elements [i]);
  74084. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74085. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74086. i += 2;
  74087. }
  74088. else if (type == quadMarker)
  74089. {
  74090. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74091. data.elements [i + 2], data.elements [i + 3]);
  74092. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74093. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74094. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74095. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74096. i += 4;
  74097. }
  74098. else if (type == cubicMarker)
  74099. {
  74100. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74101. data.elements [i + 2], data.elements [i + 3],
  74102. data.elements [i + 4], data.elements [i + 5]);
  74103. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74104. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74105. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74106. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74107. i += 6;
  74108. }
  74109. }
  74110. }
  74111. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74112. const float w, const float h,
  74113. const bool preserveProportions,
  74114. const Justification& justification) const
  74115. {
  74116. Rectangle<float> bounds (getBounds());
  74117. if (preserveProportions)
  74118. {
  74119. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74120. return AffineTransform::identity;
  74121. float newW, newH;
  74122. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74123. if (srcRatio > h / w)
  74124. {
  74125. newW = h / srcRatio;
  74126. newH = h;
  74127. }
  74128. else
  74129. {
  74130. newW = w;
  74131. newH = w * srcRatio;
  74132. }
  74133. float newXCentre = x;
  74134. float newYCentre = y;
  74135. if (justification.testFlags (Justification::left))
  74136. newXCentre += newW * 0.5f;
  74137. else if (justification.testFlags (Justification::right))
  74138. newXCentre += w - newW * 0.5f;
  74139. else
  74140. newXCentre += w * 0.5f;
  74141. if (justification.testFlags (Justification::top))
  74142. newYCentre += newH * 0.5f;
  74143. else if (justification.testFlags (Justification::bottom))
  74144. newYCentre += h - newH * 0.5f;
  74145. else
  74146. newYCentre += h * 0.5f;
  74147. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  74148. bounds.getHeight() * -0.5f - bounds.getY())
  74149. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  74150. .translated (newXCentre, newYCentre);
  74151. }
  74152. else
  74153. {
  74154. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  74155. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  74156. .translated (x, y);
  74157. }
  74158. }
  74159. bool Path::contains (const float x, const float y, const float tolerence) const
  74160. {
  74161. if (x <= pathXMin || x >= pathXMax
  74162. || y <= pathYMin || y >= pathYMax)
  74163. return false;
  74164. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74165. int positiveCrossings = 0;
  74166. int negativeCrossings = 0;
  74167. while (i.next())
  74168. {
  74169. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  74170. {
  74171. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  74172. if (intersectX <= x)
  74173. {
  74174. if (i.y1 < i.y2)
  74175. ++positiveCrossings;
  74176. else
  74177. ++negativeCrossings;
  74178. }
  74179. }
  74180. }
  74181. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  74182. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  74183. }
  74184. bool Path::contains (const Point<float>& point, const float tolerence) const
  74185. {
  74186. return contains (point.getX(), point.getY(), tolerence);
  74187. }
  74188. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  74189. {
  74190. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74191. Point<float> intersection;
  74192. while (i.next())
  74193. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74194. return true;
  74195. return false;
  74196. }
  74197. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  74198. {
  74199. Line<float> result (line);
  74200. const bool startInside = contains (line.getStart());
  74201. const bool endInside = contains (line.getEnd());
  74202. if (startInside == endInside)
  74203. {
  74204. if (keepSectionOutsidePath == startInside)
  74205. result = Line<float>();
  74206. }
  74207. else
  74208. {
  74209. PathFlatteningIterator i (*this, AffineTransform::identity);
  74210. Point<float> intersection;
  74211. while (i.next())
  74212. {
  74213. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74214. {
  74215. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  74216. result.setStart (intersection);
  74217. else
  74218. result.setEnd (intersection);
  74219. }
  74220. }
  74221. }
  74222. return result;
  74223. }
  74224. float Path::getLength (const AffineTransform& transform) const
  74225. {
  74226. float length = 0;
  74227. PathFlatteningIterator i (*this, transform);
  74228. while (i.next())
  74229. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  74230. return length;
  74231. }
  74232. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  74233. {
  74234. PathFlatteningIterator i (*this, transform);
  74235. while (i.next())
  74236. {
  74237. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74238. const float lineLength = line.getLength();
  74239. if (distanceFromStart <= lineLength)
  74240. return line.getPointAlongLine (distanceFromStart);
  74241. distanceFromStart -= lineLength;
  74242. }
  74243. return Point<float> (i.x2, i.y2);
  74244. }
  74245. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  74246. const AffineTransform& transform) const
  74247. {
  74248. PathFlatteningIterator i (*this, transform);
  74249. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  74250. float length = 0;
  74251. Point<float> pointOnLine;
  74252. while (i.next())
  74253. {
  74254. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74255. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  74256. if (distance < bestDistance)
  74257. {
  74258. bestDistance = distance;
  74259. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  74260. pointOnPath = pointOnLine;
  74261. }
  74262. length += line.getLength();
  74263. }
  74264. return bestPosition;
  74265. }
  74266. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  74267. {
  74268. if (cornerRadius <= 0.01f)
  74269. return *this;
  74270. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  74271. size_t n = 0;
  74272. bool lastWasLine = false, firstWasLine = false;
  74273. Path p;
  74274. while (n < numElements)
  74275. {
  74276. const float type = data.elements [n++];
  74277. if (type == moveMarker)
  74278. {
  74279. indexOfPathStart = p.numElements;
  74280. indexOfPathStartThis = n - 1;
  74281. const float x = data.elements [n++];
  74282. const float y = data.elements [n++];
  74283. p.startNewSubPath (x, y);
  74284. lastWasLine = false;
  74285. firstWasLine = (data.elements [n] == lineMarker);
  74286. }
  74287. else if (type == lineMarker || type == closeSubPathMarker)
  74288. {
  74289. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  74290. if (type == lineMarker)
  74291. {
  74292. endX = data.elements [n++];
  74293. endY = data.elements [n++];
  74294. if (n > 8)
  74295. {
  74296. startX = data.elements [n - 8];
  74297. startY = data.elements [n - 7];
  74298. joinX = data.elements [n - 5];
  74299. joinY = data.elements [n - 4];
  74300. }
  74301. }
  74302. else
  74303. {
  74304. endX = data.elements [indexOfPathStartThis + 1];
  74305. endY = data.elements [indexOfPathStartThis + 2];
  74306. if (n > 6)
  74307. {
  74308. startX = data.elements [n - 6];
  74309. startY = data.elements [n - 5];
  74310. joinX = data.elements [n - 3];
  74311. joinY = data.elements [n - 2];
  74312. }
  74313. }
  74314. if (lastWasLine)
  74315. {
  74316. const double len1 = juce_hypot (startX - joinX,
  74317. startY - joinY);
  74318. if (len1 > 0)
  74319. {
  74320. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74321. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74322. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74323. }
  74324. const double len2 = juce_hypot (endX - joinX,
  74325. endY - joinY);
  74326. if (len2 > 0)
  74327. {
  74328. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74329. p.quadraticTo (joinX, joinY,
  74330. (float) (joinX + (endX - joinX) * propNeeded),
  74331. (float) (joinY + (endY - joinY) * propNeeded));
  74332. }
  74333. p.lineTo (endX, endY);
  74334. }
  74335. else if (type == lineMarker)
  74336. {
  74337. p.lineTo (endX, endY);
  74338. lastWasLine = true;
  74339. }
  74340. if (type == closeSubPathMarker)
  74341. {
  74342. if (firstWasLine)
  74343. {
  74344. startX = data.elements [n - 3];
  74345. startY = data.elements [n - 2];
  74346. joinX = endX;
  74347. joinY = endY;
  74348. endX = data.elements [indexOfPathStartThis + 4];
  74349. endY = data.elements [indexOfPathStartThis + 5];
  74350. const double len1 = juce_hypot (startX - joinX,
  74351. startY - joinY);
  74352. if (len1 > 0)
  74353. {
  74354. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74355. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74356. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74357. }
  74358. const double len2 = juce_hypot (endX - joinX,
  74359. endY - joinY);
  74360. if (len2 > 0)
  74361. {
  74362. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74363. endX = (float) (joinX + (endX - joinX) * propNeeded);
  74364. endY = (float) (joinY + (endY - joinY) * propNeeded);
  74365. p.quadraticTo (joinX, joinY, endX, endY);
  74366. p.data.elements [indexOfPathStart + 1] = endX;
  74367. p.data.elements [indexOfPathStart + 2] = endY;
  74368. }
  74369. }
  74370. p.closeSubPath();
  74371. }
  74372. }
  74373. else if (type == quadMarker)
  74374. {
  74375. lastWasLine = false;
  74376. const float x1 = data.elements [n++];
  74377. const float y1 = data.elements [n++];
  74378. const float x2 = data.elements [n++];
  74379. const float y2 = data.elements [n++];
  74380. p.quadraticTo (x1, y1, x2, y2);
  74381. }
  74382. else if (type == cubicMarker)
  74383. {
  74384. lastWasLine = false;
  74385. const float x1 = data.elements [n++];
  74386. const float y1 = data.elements [n++];
  74387. const float x2 = data.elements [n++];
  74388. const float y2 = data.elements [n++];
  74389. const float x3 = data.elements [n++];
  74390. const float y3 = data.elements [n++];
  74391. p.cubicTo (x1, y1, x2, y2, x3, y3);
  74392. }
  74393. }
  74394. return p;
  74395. }
  74396. void Path::loadPathFromStream (InputStream& source)
  74397. {
  74398. while (! source.isExhausted())
  74399. {
  74400. switch (source.readByte())
  74401. {
  74402. case 'm':
  74403. {
  74404. const float x = source.readFloat();
  74405. const float y = source.readFloat();
  74406. startNewSubPath (x, y);
  74407. break;
  74408. }
  74409. case 'l':
  74410. {
  74411. const float x = source.readFloat();
  74412. const float y = source.readFloat();
  74413. lineTo (x, y);
  74414. break;
  74415. }
  74416. case 'q':
  74417. {
  74418. const float x1 = source.readFloat();
  74419. const float y1 = source.readFloat();
  74420. const float x2 = source.readFloat();
  74421. const float y2 = source.readFloat();
  74422. quadraticTo (x1, y1, x2, y2);
  74423. break;
  74424. }
  74425. case 'b':
  74426. {
  74427. const float x1 = source.readFloat();
  74428. const float y1 = source.readFloat();
  74429. const float x2 = source.readFloat();
  74430. const float y2 = source.readFloat();
  74431. const float x3 = source.readFloat();
  74432. const float y3 = source.readFloat();
  74433. cubicTo (x1, y1, x2, y2, x3, y3);
  74434. break;
  74435. }
  74436. case 'c':
  74437. closeSubPath();
  74438. break;
  74439. case 'n':
  74440. useNonZeroWinding = true;
  74441. break;
  74442. case 'z':
  74443. useNonZeroWinding = false;
  74444. break;
  74445. case 'e':
  74446. return; // end of path marker
  74447. default:
  74448. jassertfalse; // illegal char in the stream
  74449. break;
  74450. }
  74451. }
  74452. }
  74453. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  74454. {
  74455. MemoryInputStream in (pathData, numberOfBytes, false);
  74456. loadPathFromStream (in);
  74457. }
  74458. void Path::writePathToStream (OutputStream& dest) const
  74459. {
  74460. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  74461. size_t i = 0;
  74462. while (i < numElements)
  74463. {
  74464. const float type = data.elements [i++];
  74465. if (type == moveMarker)
  74466. {
  74467. dest.writeByte ('m');
  74468. dest.writeFloat (data.elements [i++]);
  74469. dest.writeFloat (data.elements [i++]);
  74470. }
  74471. else if (type == lineMarker)
  74472. {
  74473. dest.writeByte ('l');
  74474. dest.writeFloat (data.elements [i++]);
  74475. dest.writeFloat (data.elements [i++]);
  74476. }
  74477. else if (type == quadMarker)
  74478. {
  74479. dest.writeByte ('q');
  74480. dest.writeFloat (data.elements [i++]);
  74481. dest.writeFloat (data.elements [i++]);
  74482. dest.writeFloat (data.elements [i++]);
  74483. dest.writeFloat (data.elements [i++]);
  74484. }
  74485. else if (type == cubicMarker)
  74486. {
  74487. dest.writeByte ('b');
  74488. dest.writeFloat (data.elements [i++]);
  74489. dest.writeFloat (data.elements [i++]);
  74490. dest.writeFloat (data.elements [i++]);
  74491. dest.writeFloat (data.elements [i++]);
  74492. dest.writeFloat (data.elements [i++]);
  74493. dest.writeFloat (data.elements [i++]);
  74494. }
  74495. else if (type == closeSubPathMarker)
  74496. {
  74497. dest.writeByte ('c');
  74498. }
  74499. }
  74500. dest.writeByte ('e'); // marks the end-of-path
  74501. }
  74502. const String Path::toString() const
  74503. {
  74504. MemoryOutputStream s (2048);
  74505. if (! useNonZeroWinding)
  74506. s << 'a';
  74507. size_t i = 0;
  74508. float lastMarker = 0.0f;
  74509. while (i < numElements)
  74510. {
  74511. const float marker = data.elements [i++];
  74512. char markerChar = 0;
  74513. int numCoords = 0;
  74514. if (marker == moveMarker)
  74515. {
  74516. markerChar = 'm';
  74517. numCoords = 2;
  74518. }
  74519. else if (marker == lineMarker)
  74520. {
  74521. markerChar = 'l';
  74522. numCoords = 2;
  74523. }
  74524. else if (marker == quadMarker)
  74525. {
  74526. markerChar = 'q';
  74527. numCoords = 4;
  74528. }
  74529. else if (marker == cubicMarker)
  74530. {
  74531. markerChar = 'c';
  74532. numCoords = 6;
  74533. }
  74534. else
  74535. {
  74536. jassert (marker == closeSubPathMarker);
  74537. markerChar = 'z';
  74538. }
  74539. if (marker != lastMarker)
  74540. {
  74541. if (s.getDataSize() != 0)
  74542. s << ' ';
  74543. s << markerChar;
  74544. lastMarker = marker;
  74545. }
  74546. while (--numCoords >= 0 && i < numElements)
  74547. {
  74548. String coord (data.elements [i++], 3);
  74549. while (coord.endsWithChar ('0') && coord != "0")
  74550. coord = coord.dropLastCharacters (1);
  74551. if (coord.endsWithChar ('.'))
  74552. coord = coord.dropLastCharacters (1);
  74553. if (s.getDataSize() != 0)
  74554. s << ' ';
  74555. s << coord;
  74556. }
  74557. }
  74558. return s.toUTF8();
  74559. }
  74560. void Path::restoreFromString (const String& stringVersion)
  74561. {
  74562. clear();
  74563. setUsingNonZeroWinding (true);
  74564. const juce_wchar* t = stringVersion;
  74565. juce_wchar marker = 'm';
  74566. int numValues = 2;
  74567. float values [6];
  74568. for (;;)
  74569. {
  74570. const String token (PathHelpers::nextToken (t));
  74571. const juce_wchar firstChar = token[0];
  74572. int startNum = 0;
  74573. if (firstChar == 0)
  74574. break;
  74575. if (firstChar == 'm' || firstChar == 'l')
  74576. {
  74577. marker = firstChar;
  74578. numValues = 2;
  74579. }
  74580. else if (firstChar == 'q')
  74581. {
  74582. marker = firstChar;
  74583. numValues = 4;
  74584. }
  74585. else if (firstChar == 'c')
  74586. {
  74587. marker = firstChar;
  74588. numValues = 6;
  74589. }
  74590. else if (firstChar == 'z')
  74591. {
  74592. marker = firstChar;
  74593. numValues = 0;
  74594. }
  74595. else if (firstChar == 'a')
  74596. {
  74597. setUsingNonZeroWinding (false);
  74598. continue;
  74599. }
  74600. else
  74601. {
  74602. ++startNum;
  74603. values [0] = token.getFloatValue();
  74604. }
  74605. for (int i = startNum; i < numValues; ++i)
  74606. values [i] = PathHelpers::nextToken (t).getFloatValue();
  74607. switch (marker)
  74608. {
  74609. case 'm':
  74610. startNewSubPath (values[0], values[1]);
  74611. break;
  74612. case 'l':
  74613. lineTo (values[0], values[1]);
  74614. break;
  74615. case 'q':
  74616. quadraticTo (values[0], values[1],
  74617. values[2], values[3]);
  74618. break;
  74619. case 'c':
  74620. cubicTo (values[0], values[1],
  74621. values[2], values[3],
  74622. values[4], values[5]);
  74623. break;
  74624. case 'z':
  74625. closeSubPath();
  74626. break;
  74627. default:
  74628. jassertfalse; // illegal string format?
  74629. break;
  74630. }
  74631. }
  74632. }
  74633. Path::Iterator::Iterator (const Path& path_)
  74634. : path (path_),
  74635. index (0)
  74636. {
  74637. }
  74638. Path::Iterator::~Iterator()
  74639. {
  74640. }
  74641. bool Path::Iterator::next()
  74642. {
  74643. const float* const elements = path.data.elements;
  74644. if (index < path.numElements)
  74645. {
  74646. const float type = elements [index++];
  74647. if (type == moveMarker)
  74648. {
  74649. elementType = startNewSubPath;
  74650. x1 = elements [index++];
  74651. y1 = elements [index++];
  74652. }
  74653. else if (type == lineMarker)
  74654. {
  74655. elementType = lineTo;
  74656. x1 = elements [index++];
  74657. y1 = elements [index++];
  74658. }
  74659. else if (type == quadMarker)
  74660. {
  74661. elementType = quadraticTo;
  74662. x1 = elements [index++];
  74663. y1 = elements [index++];
  74664. x2 = elements [index++];
  74665. y2 = elements [index++];
  74666. }
  74667. else if (type == cubicMarker)
  74668. {
  74669. elementType = cubicTo;
  74670. x1 = elements [index++];
  74671. y1 = elements [index++];
  74672. x2 = elements [index++];
  74673. y2 = elements [index++];
  74674. x3 = elements [index++];
  74675. y3 = elements [index++];
  74676. }
  74677. else if (type == closeSubPathMarker)
  74678. {
  74679. elementType = closePath;
  74680. }
  74681. return true;
  74682. }
  74683. return false;
  74684. }
  74685. END_JUCE_NAMESPACE
  74686. /*** End of inlined file: juce_Path.cpp ***/
  74687. /*** Start of inlined file: juce_PathIterator.cpp ***/
  74688. BEGIN_JUCE_NAMESPACE
  74689. #if JUCE_MSVC && JUCE_DEBUG
  74690. #pragma optimize ("t", on)
  74691. #endif
  74692. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  74693. const AffineTransform& transform_,
  74694. float tolerence_)
  74695. : x2 (0),
  74696. y2 (0),
  74697. closesSubPath (false),
  74698. subPathIndex (-1),
  74699. path (path_),
  74700. transform (transform_),
  74701. points (path_.data.elements),
  74702. tolerence (tolerence_ * tolerence_),
  74703. subPathCloseX (0),
  74704. subPathCloseY (0),
  74705. isIdentityTransform (transform_.isIdentity()),
  74706. stackBase (32),
  74707. index (0),
  74708. stackSize (32)
  74709. {
  74710. stackPos = stackBase;
  74711. }
  74712. PathFlatteningIterator::~PathFlatteningIterator()
  74713. {
  74714. }
  74715. bool PathFlatteningIterator::next()
  74716. {
  74717. x1 = x2;
  74718. y1 = y2;
  74719. float x3 = 0;
  74720. float y3 = 0;
  74721. float x4 = 0;
  74722. float y4 = 0;
  74723. float type;
  74724. for (;;)
  74725. {
  74726. if (stackPos == stackBase)
  74727. {
  74728. if (index >= path.numElements)
  74729. {
  74730. return false;
  74731. }
  74732. else
  74733. {
  74734. type = points [index++];
  74735. if (type != Path::closeSubPathMarker)
  74736. {
  74737. x2 = points [index++];
  74738. y2 = points [index++];
  74739. if (type == Path::quadMarker)
  74740. {
  74741. x3 = points [index++];
  74742. y3 = points [index++];
  74743. if (! isIdentityTransform)
  74744. transform.transformPoints (x2, y2, x3, y3);
  74745. }
  74746. else if (type == Path::cubicMarker)
  74747. {
  74748. x3 = points [index++];
  74749. y3 = points [index++];
  74750. x4 = points [index++];
  74751. y4 = points [index++];
  74752. if (! isIdentityTransform)
  74753. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  74754. }
  74755. else
  74756. {
  74757. if (! isIdentityTransform)
  74758. transform.transformPoint (x2, y2);
  74759. }
  74760. }
  74761. }
  74762. }
  74763. else
  74764. {
  74765. type = *--stackPos;
  74766. if (type != Path::closeSubPathMarker)
  74767. {
  74768. x2 = *--stackPos;
  74769. y2 = *--stackPos;
  74770. if (type == Path::quadMarker)
  74771. {
  74772. x3 = *--stackPos;
  74773. y3 = *--stackPos;
  74774. }
  74775. else if (type == Path::cubicMarker)
  74776. {
  74777. x3 = *--stackPos;
  74778. y3 = *--stackPos;
  74779. x4 = *--stackPos;
  74780. y4 = *--stackPos;
  74781. }
  74782. }
  74783. }
  74784. if (type == Path::lineMarker)
  74785. {
  74786. ++subPathIndex;
  74787. closesSubPath = (stackPos == stackBase)
  74788. && (index < path.numElements)
  74789. && (points [index] == Path::closeSubPathMarker)
  74790. && x2 == subPathCloseX
  74791. && y2 == subPathCloseY;
  74792. return true;
  74793. }
  74794. else if (type == Path::quadMarker)
  74795. {
  74796. const size_t offset = (size_t) (stackPos - stackBase);
  74797. if (offset >= stackSize - 10)
  74798. {
  74799. stackSize <<= 1;
  74800. stackBase.realloc (stackSize);
  74801. stackPos = stackBase + offset;
  74802. }
  74803. const float dx1 = x1 - x2;
  74804. const float dy1 = y1 - y2;
  74805. const float dx2 = x2 - x3;
  74806. const float dy2 = y2 - y3;
  74807. const float m1x = (x1 + x2) * 0.5f;
  74808. const float m1y = (y1 + y2) * 0.5f;
  74809. const float m2x = (x2 + x3) * 0.5f;
  74810. const float m2y = (y2 + y3) * 0.5f;
  74811. const float m3x = (m1x + m2x) * 0.5f;
  74812. const float m3y = (m1y + m2y) * 0.5f;
  74813. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  74814. {
  74815. *stackPos++ = y3;
  74816. *stackPos++ = x3;
  74817. *stackPos++ = m2y;
  74818. *stackPos++ = m2x;
  74819. *stackPos++ = Path::quadMarker;
  74820. *stackPos++ = m3y;
  74821. *stackPos++ = m3x;
  74822. *stackPos++ = m1y;
  74823. *stackPos++ = m1x;
  74824. *stackPos++ = Path::quadMarker;
  74825. }
  74826. else
  74827. {
  74828. *stackPos++ = y3;
  74829. *stackPos++ = x3;
  74830. *stackPos++ = Path::lineMarker;
  74831. *stackPos++ = m3y;
  74832. *stackPos++ = m3x;
  74833. *stackPos++ = Path::lineMarker;
  74834. }
  74835. jassert (stackPos < stackBase + stackSize);
  74836. }
  74837. else if (type == Path::cubicMarker)
  74838. {
  74839. const size_t offset = (size_t) (stackPos - stackBase);
  74840. if (offset >= stackSize - 16)
  74841. {
  74842. stackSize <<= 1;
  74843. stackBase.realloc (stackSize);
  74844. stackPos = stackBase + offset;
  74845. }
  74846. const float dx1 = x1 - x2;
  74847. const float dy1 = y1 - y2;
  74848. const float dx2 = x2 - x3;
  74849. const float dy2 = y2 - y3;
  74850. const float dx3 = x3 - x4;
  74851. const float dy3 = y3 - y4;
  74852. const float m1x = (x1 + x2) * 0.5f;
  74853. const float m1y = (y1 + y2) * 0.5f;
  74854. const float m2x = (x3 + x2) * 0.5f;
  74855. const float m2y = (y3 + y2) * 0.5f;
  74856. const float m3x = (x3 + x4) * 0.5f;
  74857. const float m3y = (y3 + y4) * 0.5f;
  74858. const float m4x = (m1x + m2x) * 0.5f;
  74859. const float m4y = (m1y + m2y) * 0.5f;
  74860. const float m5x = (m3x + m2x) * 0.5f;
  74861. const float m5y = (m3y + m2y) * 0.5f;
  74862. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  74863. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  74864. {
  74865. *stackPos++ = y4;
  74866. *stackPos++ = x4;
  74867. *stackPos++ = m3y;
  74868. *stackPos++ = m3x;
  74869. *stackPos++ = m5y;
  74870. *stackPos++ = m5x;
  74871. *stackPos++ = Path::cubicMarker;
  74872. *stackPos++ = (m4y + m5y) * 0.5f;
  74873. *stackPos++ = (m4x + m5x) * 0.5f;
  74874. *stackPos++ = m4y;
  74875. *stackPos++ = m4x;
  74876. *stackPos++ = m1y;
  74877. *stackPos++ = m1x;
  74878. *stackPos++ = Path::cubicMarker;
  74879. }
  74880. else
  74881. {
  74882. *stackPos++ = y4;
  74883. *stackPos++ = x4;
  74884. *stackPos++ = Path::lineMarker;
  74885. *stackPos++ = m5y;
  74886. *stackPos++ = m5x;
  74887. *stackPos++ = Path::lineMarker;
  74888. *stackPos++ = m4y;
  74889. *stackPos++ = m4x;
  74890. *stackPos++ = Path::lineMarker;
  74891. }
  74892. }
  74893. else if (type == Path::closeSubPathMarker)
  74894. {
  74895. if (x2 != subPathCloseX || y2 != subPathCloseY)
  74896. {
  74897. x1 = x2;
  74898. y1 = y2;
  74899. x2 = subPathCloseX;
  74900. y2 = subPathCloseY;
  74901. closesSubPath = true;
  74902. return true;
  74903. }
  74904. }
  74905. else
  74906. {
  74907. jassert (type == Path::moveMarker);
  74908. subPathIndex = -1;
  74909. subPathCloseX = x1 = x2;
  74910. subPathCloseY = y1 = y2;
  74911. }
  74912. }
  74913. }
  74914. #if JUCE_MSVC && JUCE_DEBUG
  74915. #pragma optimize ("", on) // resets optimisations to the project defaults
  74916. #endif
  74917. END_JUCE_NAMESPACE
  74918. /*** End of inlined file: juce_PathIterator.cpp ***/
  74919. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  74920. BEGIN_JUCE_NAMESPACE
  74921. PathStrokeType::PathStrokeType (const float strokeThickness,
  74922. const JointStyle jointStyle_,
  74923. const EndCapStyle endStyle_) throw()
  74924. : thickness (strokeThickness),
  74925. jointStyle (jointStyle_),
  74926. endStyle (endStyle_)
  74927. {
  74928. }
  74929. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  74930. : thickness (other.thickness),
  74931. jointStyle (other.jointStyle),
  74932. endStyle (other.endStyle)
  74933. {
  74934. }
  74935. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  74936. {
  74937. thickness = other.thickness;
  74938. jointStyle = other.jointStyle;
  74939. endStyle = other.endStyle;
  74940. return *this;
  74941. }
  74942. PathStrokeType::~PathStrokeType() throw()
  74943. {
  74944. }
  74945. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  74946. {
  74947. return thickness == other.thickness
  74948. && jointStyle == other.jointStyle
  74949. && endStyle == other.endStyle;
  74950. }
  74951. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  74952. {
  74953. return ! operator== (other);
  74954. }
  74955. namespace PathStrokeHelpers
  74956. {
  74957. static bool lineIntersection (const float x1, const float y1,
  74958. const float x2, const float y2,
  74959. const float x3, const float y3,
  74960. const float x4, const float y4,
  74961. float& intersectionX,
  74962. float& intersectionY,
  74963. float& distanceBeyondLine1EndSquared) throw()
  74964. {
  74965. if (x2 != x3 || y2 != y3)
  74966. {
  74967. const float dx1 = x2 - x1;
  74968. const float dy1 = y2 - y1;
  74969. const float dx2 = x4 - x3;
  74970. const float dy2 = y4 - y3;
  74971. const float divisor = dx1 * dy2 - dx2 * dy1;
  74972. if (divisor == 0)
  74973. {
  74974. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  74975. {
  74976. if (dy1 == 0 && dy2 != 0)
  74977. {
  74978. const float along = (y1 - y3) / dy2;
  74979. intersectionX = x3 + along * dx2;
  74980. intersectionY = y1;
  74981. distanceBeyondLine1EndSquared = intersectionX - x2;
  74982. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  74983. if ((x2 > x1) == (intersectionX < x2))
  74984. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  74985. return along >= 0 && along <= 1.0f;
  74986. }
  74987. else if (dy2 == 0 && dy1 != 0)
  74988. {
  74989. const float along = (y3 - y1) / dy1;
  74990. intersectionX = x1 + along * dx1;
  74991. intersectionY = y3;
  74992. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  74993. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  74994. if (along < 1.0f)
  74995. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  74996. return along >= 0 && along <= 1.0f;
  74997. }
  74998. else if (dx1 == 0 && dx2 != 0)
  74999. {
  75000. const float along = (x1 - x3) / dx2;
  75001. intersectionX = x1;
  75002. intersectionY = y3 + along * dy2;
  75003. distanceBeyondLine1EndSquared = intersectionY - y2;
  75004. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75005. if ((y2 > y1) == (intersectionY < y2))
  75006. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75007. return along >= 0 && along <= 1.0f;
  75008. }
  75009. else if (dx2 == 0 && dx1 != 0)
  75010. {
  75011. const float along = (x3 - x1) / dx1;
  75012. intersectionX = x3;
  75013. intersectionY = y1 + along * dy1;
  75014. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75015. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75016. if (along < 1.0f)
  75017. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75018. return along >= 0 && along <= 1.0f;
  75019. }
  75020. }
  75021. intersectionX = 0.5f * (x2 + x3);
  75022. intersectionY = 0.5f * (y2 + y3);
  75023. distanceBeyondLine1EndSquared = 0.0f;
  75024. return false;
  75025. }
  75026. else
  75027. {
  75028. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75029. intersectionX = x1 + along1 * dx1;
  75030. intersectionY = y1 + along1 * dy1;
  75031. if (along1 >= 0 && along1 <= 1.0f)
  75032. {
  75033. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75034. if (along2 >= 0 && along2 <= divisor)
  75035. {
  75036. distanceBeyondLine1EndSquared = 0.0f;
  75037. return true;
  75038. }
  75039. }
  75040. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75041. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75042. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75043. if (along1 < 1.0f)
  75044. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75045. return false;
  75046. }
  75047. }
  75048. intersectionX = x2;
  75049. intersectionY = y2;
  75050. distanceBeyondLine1EndSquared = 0.0f;
  75051. return true;
  75052. }
  75053. static void addEdgeAndJoint (Path& destPath,
  75054. const PathStrokeType::JointStyle style,
  75055. const float maxMiterExtensionSquared, const float width,
  75056. const float x1, const float y1,
  75057. const float x2, const float y2,
  75058. const float x3, const float y3,
  75059. const float x4, const float y4,
  75060. const float midX, const float midY)
  75061. {
  75062. if (style == PathStrokeType::beveled
  75063. || (x3 == x4 && y3 == y4)
  75064. || (x1 == x2 && y1 == y2))
  75065. {
  75066. destPath.lineTo (x2, y2);
  75067. destPath.lineTo (x3, y3);
  75068. }
  75069. else
  75070. {
  75071. float jx, jy, distanceBeyondLine1EndSquared;
  75072. // if they intersect, use this point..
  75073. if (lineIntersection (x1, y1, x2, y2,
  75074. x3, y3, x4, y4,
  75075. jx, jy, distanceBeyondLine1EndSquared))
  75076. {
  75077. destPath.lineTo (jx, jy);
  75078. }
  75079. else
  75080. {
  75081. if (style == PathStrokeType::mitered)
  75082. {
  75083. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75084. && distanceBeyondLine1EndSquared > 0.0f)
  75085. {
  75086. destPath.lineTo (jx, jy);
  75087. }
  75088. else
  75089. {
  75090. // the end sticks out too far, so just use a blunt joint
  75091. destPath.lineTo (x2, y2);
  75092. destPath.lineTo (x3, y3);
  75093. }
  75094. }
  75095. else
  75096. {
  75097. // curved joints
  75098. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75099. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75100. const float angleIncrement = 0.1f;
  75101. destPath.lineTo (x2, y2);
  75102. if (std::abs (angle1 - angle2) > angleIncrement)
  75103. {
  75104. if (angle2 > angle1 + float_Pi
  75105. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75106. {
  75107. if (angle2 > angle1)
  75108. angle2 -= float_Pi * 2.0f;
  75109. jassert (angle1 <= angle2 + float_Pi);
  75110. angle1 -= angleIncrement;
  75111. while (angle1 > angle2)
  75112. {
  75113. destPath.lineTo (midX + width * std::sin (angle1),
  75114. midY + width * std::cos (angle1));
  75115. angle1 -= angleIncrement;
  75116. }
  75117. }
  75118. else
  75119. {
  75120. if (angle1 > angle2)
  75121. angle1 -= float_Pi * 2.0f;
  75122. jassert (angle1 >= angle2 - float_Pi);
  75123. angle1 += angleIncrement;
  75124. while (angle1 < angle2)
  75125. {
  75126. destPath.lineTo (midX + width * std::sin (angle1),
  75127. midY + width * std::cos (angle1));
  75128. angle1 += angleIncrement;
  75129. }
  75130. }
  75131. }
  75132. destPath.lineTo (x3, y3);
  75133. }
  75134. }
  75135. }
  75136. }
  75137. static void addLineEnd (Path& destPath,
  75138. const PathStrokeType::EndCapStyle style,
  75139. const float x1, const float y1,
  75140. const float x2, const float y2,
  75141. const float width)
  75142. {
  75143. if (style == PathStrokeType::butt)
  75144. {
  75145. destPath.lineTo (x2, y2);
  75146. }
  75147. else
  75148. {
  75149. float offx1, offy1, offx2, offy2;
  75150. float dx = x2 - x1;
  75151. float dy = y2 - y1;
  75152. const float len = juce_hypotf (dx, dy);
  75153. if (len == 0)
  75154. {
  75155. offx1 = offx2 = x1;
  75156. offy1 = offy2 = y1;
  75157. }
  75158. else
  75159. {
  75160. const float offset = width / len;
  75161. dx *= offset;
  75162. dy *= offset;
  75163. offx1 = x1 + dy;
  75164. offy1 = y1 - dx;
  75165. offx2 = x2 + dy;
  75166. offy2 = y2 - dx;
  75167. }
  75168. if (style == PathStrokeType::square)
  75169. {
  75170. // sqaure ends
  75171. destPath.lineTo (offx1, offy1);
  75172. destPath.lineTo (offx2, offy2);
  75173. destPath.lineTo (x2, y2);
  75174. }
  75175. else
  75176. {
  75177. // rounded ends
  75178. const float midx = (offx1 + offx2) * 0.5f;
  75179. const float midy = (offy1 + offy2) * 0.5f;
  75180. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  75181. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  75182. midx, midy);
  75183. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  75184. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  75185. x2, y2);
  75186. }
  75187. }
  75188. }
  75189. struct Arrowhead
  75190. {
  75191. float startWidth, startLength;
  75192. float endWidth, endLength;
  75193. };
  75194. static void addArrowhead (Path& destPath,
  75195. const float x1, const float y1,
  75196. const float x2, const float y2,
  75197. const float tipX, const float tipY,
  75198. const float width,
  75199. const float arrowheadWidth)
  75200. {
  75201. Line<float> line (x1, y1, x2, y2);
  75202. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  75203. destPath.lineTo (tipX, tipY);
  75204. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  75205. destPath.lineTo (x2, y2);
  75206. }
  75207. struct LineSection
  75208. {
  75209. float x1, y1, x2, y2; // original line
  75210. float lx1, ly1, lx2, ly2; // the left-hand stroke
  75211. float rx1, ry1, rx2, ry2; // the right-hand stroke
  75212. };
  75213. static void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  75214. {
  75215. while (amountAtEnd > 0 && subPath.size() > 0)
  75216. {
  75217. LineSection& l = subPath.getReference (subPath.size() - 1);
  75218. float dx = l.rx2 - l.rx1;
  75219. float dy = l.ry2 - l.ry1;
  75220. const float len = juce_hypotf (dx, dy);
  75221. if (len <= amountAtEnd && subPath.size() > 1)
  75222. {
  75223. LineSection& prev = subPath.getReference (subPath.size() - 2);
  75224. prev.x2 = l.x2;
  75225. prev.y2 = l.y2;
  75226. subPath.removeLast();
  75227. amountAtEnd -= len;
  75228. }
  75229. else
  75230. {
  75231. const float prop = jmin (0.9999f, amountAtEnd / len);
  75232. dx *= prop;
  75233. dy *= prop;
  75234. l.rx1 += dx;
  75235. l.ry1 += dy;
  75236. l.lx2 += dx;
  75237. l.ly2 += dy;
  75238. break;
  75239. }
  75240. }
  75241. while (amountAtStart > 0 && subPath.size() > 0)
  75242. {
  75243. LineSection& l = subPath.getReference (0);
  75244. float dx = l.rx2 - l.rx1;
  75245. float dy = l.ry2 - l.ry1;
  75246. const float len = juce_hypotf (dx, dy);
  75247. if (len <= amountAtStart && subPath.size() > 1)
  75248. {
  75249. LineSection& next = subPath.getReference (1);
  75250. next.x1 = l.x1;
  75251. next.y1 = l.y1;
  75252. subPath.remove (0);
  75253. amountAtStart -= len;
  75254. }
  75255. else
  75256. {
  75257. const float prop = jmin (0.9999f, amountAtStart / len);
  75258. dx *= prop;
  75259. dy *= prop;
  75260. l.rx2 -= dx;
  75261. l.ry2 -= dy;
  75262. l.lx1 -= dx;
  75263. l.ly1 -= dy;
  75264. break;
  75265. }
  75266. }
  75267. }
  75268. static void addSubPath (Path& destPath, Array<LineSection>& subPath,
  75269. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  75270. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  75271. const Arrowhead* const arrowhead)
  75272. {
  75273. jassert (subPath.size() > 0);
  75274. if (arrowhead != 0)
  75275. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  75276. const LineSection& firstLine = subPath.getReference (0);
  75277. float lastX1 = firstLine.lx1;
  75278. float lastY1 = firstLine.ly1;
  75279. float lastX2 = firstLine.lx2;
  75280. float lastY2 = firstLine.ly2;
  75281. if (isClosed)
  75282. {
  75283. destPath.startNewSubPath (lastX1, lastY1);
  75284. }
  75285. else
  75286. {
  75287. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  75288. if (arrowhead != 0)
  75289. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  75290. width, arrowhead->startWidth);
  75291. else
  75292. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  75293. }
  75294. int i;
  75295. for (i = 1; i < subPath.size(); ++i)
  75296. {
  75297. const LineSection& l = subPath.getReference (i);
  75298. addEdgeAndJoint (destPath, jointStyle,
  75299. maxMiterExtensionSquared, width,
  75300. lastX1, lastY1, lastX2, lastY2,
  75301. l.lx1, l.ly1, l.lx2, l.ly2,
  75302. l.x1, l.y1);
  75303. lastX1 = l.lx1;
  75304. lastY1 = l.ly1;
  75305. lastX2 = l.lx2;
  75306. lastY2 = l.ly2;
  75307. }
  75308. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  75309. if (isClosed)
  75310. {
  75311. const LineSection& l = subPath.getReference (0);
  75312. addEdgeAndJoint (destPath, jointStyle,
  75313. maxMiterExtensionSquared, width,
  75314. lastX1, lastY1, lastX2, lastY2,
  75315. l.lx1, l.ly1, l.lx2, l.ly2,
  75316. l.x1, l.y1);
  75317. destPath.closeSubPath();
  75318. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  75319. }
  75320. else
  75321. {
  75322. destPath.lineTo (lastX2, lastY2);
  75323. if (arrowhead != 0)
  75324. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  75325. width, arrowhead->endWidth);
  75326. else
  75327. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  75328. }
  75329. lastX1 = lastLine.rx1;
  75330. lastY1 = lastLine.ry1;
  75331. lastX2 = lastLine.rx2;
  75332. lastY2 = lastLine.ry2;
  75333. for (i = subPath.size() - 1; --i >= 0;)
  75334. {
  75335. const LineSection& l = subPath.getReference (i);
  75336. addEdgeAndJoint (destPath, jointStyle,
  75337. maxMiterExtensionSquared, width,
  75338. lastX1, lastY1, lastX2, lastY2,
  75339. l.rx1, l.ry1, l.rx2, l.ry2,
  75340. l.x2, l.y2);
  75341. lastX1 = l.rx1;
  75342. lastY1 = l.ry1;
  75343. lastX2 = l.rx2;
  75344. lastY2 = l.ry2;
  75345. }
  75346. if (isClosed)
  75347. {
  75348. addEdgeAndJoint (destPath, jointStyle,
  75349. maxMiterExtensionSquared, width,
  75350. lastX1, lastY1, lastX2, lastY2,
  75351. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  75352. lastLine.x2, lastLine.y2);
  75353. }
  75354. else
  75355. {
  75356. // do the last line
  75357. destPath.lineTo (lastX2, lastY2);
  75358. }
  75359. destPath.closeSubPath();
  75360. }
  75361. static void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  75362. const PathStrokeType::EndCapStyle endStyle,
  75363. Path& destPath, const Path& source,
  75364. const AffineTransform& transform,
  75365. const float extraAccuracy, const Arrowhead* const arrowhead)
  75366. {
  75367. if (thickness <= 0)
  75368. {
  75369. destPath.clear();
  75370. return;
  75371. }
  75372. const Path* sourcePath = &source;
  75373. Path temp;
  75374. if (sourcePath == &destPath)
  75375. {
  75376. destPath.swapWithPath (temp);
  75377. sourcePath = &temp;
  75378. }
  75379. else
  75380. {
  75381. destPath.clear();
  75382. }
  75383. destPath.setUsingNonZeroWinding (true);
  75384. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  75385. const float width = 0.5f * thickness;
  75386. // Iterate the path, creating a list of the
  75387. // left/right-hand lines along either side of it...
  75388. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  75389. Array <LineSection> subPath;
  75390. subPath.ensureStorageAllocated (512);
  75391. LineSection l;
  75392. l.x1 = 0;
  75393. l.y1 = 0;
  75394. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  75395. while (it.next())
  75396. {
  75397. if (it.subPathIndex == 0)
  75398. {
  75399. if (subPath.size() > 0)
  75400. {
  75401. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75402. subPath.clearQuick();
  75403. }
  75404. l.x1 = it.x1;
  75405. l.y1 = it.y1;
  75406. }
  75407. l.x2 = it.x2;
  75408. l.y2 = it.y2;
  75409. float dx = l.x2 - l.x1;
  75410. float dy = l.y2 - l.y1;
  75411. const float hypotSquared = dx*dx + dy*dy;
  75412. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  75413. {
  75414. const float len = std::sqrt (hypotSquared);
  75415. if (len == 0)
  75416. {
  75417. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  75418. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  75419. }
  75420. else
  75421. {
  75422. const float offset = width / len;
  75423. dx *= offset;
  75424. dy *= offset;
  75425. l.rx2 = l.x1 - dy;
  75426. l.ry2 = l.y1 + dx;
  75427. l.lx1 = l.x1 + dy;
  75428. l.ly1 = l.y1 - dx;
  75429. l.lx2 = l.x2 + dy;
  75430. l.ly2 = l.y2 - dx;
  75431. l.rx1 = l.x2 - dy;
  75432. l.ry1 = l.y2 + dx;
  75433. }
  75434. subPath.add (l);
  75435. if (it.closesSubPath)
  75436. {
  75437. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75438. subPath.clearQuick();
  75439. }
  75440. else
  75441. {
  75442. l.x1 = it.x2;
  75443. l.y1 = it.y2;
  75444. }
  75445. }
  75446. }
  75447. if (subPath.size() > 0)
  75448. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75449. }
  75450. }
  75451. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  75452. const AffineTransform& transform, const float extraAccuracy) const
  75453. {
  75454. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  75455. transform, extraAccuracy, 0);
  75456. }
  75457. void PathStrokeType::createDashedStroke (Path& destPath,
  75458. const Path& sourcePath,
  75459. const float* dashLengths,
  75460. int numDashLengths,
  75461. const AffineTransform& transform,
  75462. const float extraAccuracy) const
  75463. {
  75464. if (thickness <= 0)
  75465. return;
  75466. // this should really be an even number..
  75467. jassert ((numDashLengths & 1) == 0);
  75468. Path newDestPath;
  75469. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  75470. bool first = true;
  75471. int dashNum = 0;
  75472. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  75473. float dx = 0.0f, dy = 0.0f;
  75474. for (;;)
  75475. {
  75476. const bool isSolid = ((dashNum & 1) == 0);
  75477. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  75478. jassert (dashLen > 0); // must be a positive increment!
  75479. if (dashLen <= 0)
  75480. break;
  75481. pos += dashLen;
  75482. while (pos > lineEndPos)
  75483. {
  75484. if (! it.next())
  75485. {
  75486. if (isSolid && ! first)
  75487. newDestPath.lineTo (it.x2, it.y2);
  75488. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  75489. return;
  75490. }
  75491. if (isSolid && ! first)
  75492. newDestPath.lineTo (it.x1, it.y1);
  75493. else
  75494. newDestPath.startNewSubPath (it.x1, it.y1);
  75495. dx = it.x2 - it.x1;
  75496. dy = it.y2 - it.y1;
  75497. lineLen = juce_hypotf (dx, dy);
  75498. lineEndPos += lineLen;
  75499. first = it.closesSubPath;
  75500. }
  75501. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  75502. if (isSolid)
  75503. newDestPath.lineTo (it.x1 + dx * alpha,
  75504. it.y1 + dy * alpha);
  75505. else
  75506. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  75507. it.y1 + dy * alpha);
  75508. }
  75509. }
  75510. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  75511. const Path& sourcePath,
  75512. const float arrowheadStartWidth, const float arrowheadStartLength,
  75513. const float arrowheadEndWidth, const float arrowheadEndLength,
  75514. const AffineTransform& transform,
  75515. const float extraAccuracy) const
  75516. {
  75517. PathStrokeHelpers::Arrowhead head;
  75518. head.startWidth = arrowheadStartWidth;
  75519. head.startLength = arrowheadStartLength;
  75520. head.endWidth = arrowheadEndWidth;
  75521. head.endLength = arrowheadEndLength;
  75522. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  75523. destPath, sourcePath, transform, extraAccuracy, &head);
  75524. }
  75525. END_JUCE_NAMESPACE
  75526. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  75527. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  75528. BEGIN_JUCE_NAMESPACE
  75529. PositionedRectangle::PositionedRectangle() throw()
  75530. : x (0.0),
  75531. y (0.0),
  75532. w (0.0),
  75533. h (0.0),
  75534. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  75535. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  75536. wMode (absoluteSize),
  75537. hMode (absoluteSize)
  75538. {
  75539. }
  75540. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  75541. : x (other.x),
  75542. y (other.y),
  75543. w (other.w),
  75544. h (other.h),
  75545. xMode (other.xMode),
  75546. yMode (other.yMode),
  75547. wMode (other.wMode),
  75548. hMode (other.hMode)
  75549. {
  75550. }
  75551. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  75552. {
  75553. x = other.x;
  75554. y = other.y;
  75555. w = other.w;
  75556. h = other.h;
  75557. xMode = other.xMode;
  75558. yMode = other.yMode;
  75559. wMode = other.wMode;
  75560. hMode = other.hMode;
  75561. return *this;
  75562. }
  75563. PositionedRectangle::~PositionedRectangle() throw()
  75564. {
  75565. }
  75566. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  75567. {
  75568. return x == other.x
  75569. && y == other.y
  75570. && w == other.w
  75571. && h == other.h
  75572. && xMode == other.xMode
  75573. && yMode == other.yMode
  75574. && wMode == other.wMode
  75575. && hMode == other.hMode;
  75576. }
  75577. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  75578. {
  75579. return ! operator== (other);
  75580. }
  75581. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  75582. {
  75583. StringArray tokens;
  75584. tokens.addTokens (stringVersion, false);
  75585. decodePosString (tokens [0], xMode, x);
  75586. decodePosString (tokens [1], yMode, y);
  75587. decodeSizeString (tokens [2], wMode, w);
  75588. decodeSizeString (tokens [3], hMode, h);
  75589. }
  75590. const String PositionedRectangle::toString() const throw()
  75591. {
  75592. String s;
  75593. s.preallocateStorage (12);
  75594. addPosDescription (s, xMode, x);
  75595. s << ' ';
  75596. addPosDescription (s, yMode, y);
  75597. s << ' ';
  75598. addSizeDescription (s, wMode, w);
  75599. s << ' ';
  75600. addSizeDescription (s, hMode, h);
  75601. return s;
  75602. }
  75603. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  75604. {
  75605. jassert (! target.isEmpty());
  75606. double x_, y_, w_, h_;
  75607. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  75608. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  75609. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  75610. roundToInt (w_), roundToInt (h_));
  75611. }
  75612. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  75613. double& x_, double& y_,
  75614. double& w_, double& h_) const throw()
  75615. {
  75616. jassert (! target.isEmpty());
  75617. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  75618. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  75619. }
  75620. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  75621. {
  75622. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  75623. }
  75624. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  75625. const Rectangle<int>& target) throw()
  75626. {
  75627. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  75628. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  75629. }
  75630. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  75631. const double newW, const double newH,
  75632. const Rectangle<int>& target) throw()
  75633. {
  75634. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  75635. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  75636. }
  75637. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  75638. {
  75639. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  75640. updateFrom (comp.getBounds(), Rectangle<int>());
  75641. else
  75642. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  75643. }
  75644. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  75645. {
  75646. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  75647. }
  75648. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  75649. {
  75650. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  75651. | absoluteFromParentBottomRight
  75652. | absoluteFromParentCentre
  75653. | proportionOfParentSize));
  75654. }
  75655. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  75656. {
  75657. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  75658. }
  75659. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  75660. {
  75661. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  75662. | absoluteFromParentBottomRight
  75663. | absoluteFromParentCentre
  75664. | proportionOfParentSize));
  75665. }
  75666. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  75667. {
  75668. return (SizeMode) wMode;
  75669. }
  75670. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  75671. {
  75672. return (SizeMode) hMode;
  75673. }
  75674. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  75675. const PositionMode xMode_,
  75676. const AnchorPoint yAnchor,
  75677. const PositionMode yMode_,
  75678. const SizeMode widthMode,
  75679. const SizeMode heightMode,
  75680. const Rectangle<int>& target) throw()
  75681. {
  75682. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  75683. {
  75684. double tx, tw;
  75685. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  75686. xMode = (uint8) (xAnchor | xMode_);
  75687. wMode = (uint8) widthMode;
  75688. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  75689. }
  75690. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  75691. {
  75692. double ty, th;
  75693. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  75694. yMode = (uint8) (yAnchor | yMode_);
  75695. hMode = (uint8) heightMode;
  75696. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  75697. }
  75698. }
  75699. bool PositionedRectangle::isPositionAbsolute() const throw()
  75700. {
  75701. return xMode == absoluteFromParentTopLeft
  75702. && yMode == absoluteFromParentTopLeft
  75703. && wMode == absoluteSize
  75704. && hMode == absoluteSize;
  75705. }
  75706. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  75707. {
  75708. if ((mode & proportionOfParentSize) != 0)
  75709. {
  75710. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  75711. }
  75712. else
  75713. {
  75714. s << (roundToInt (value * 100.0) / 100.0);
  75715. if ((mode & absoluteFromParentBottomRight) != 0)
  75716. s << 'R';
  75717. else if ((mode & absoluteFromParentCentre) != 0)
  75718. s << 'C';
  75719. }
  75720. if ((mode & anchorAtRightOrBottom) != 0)
  75721. s << 'r';
  75722. else if ((mode & anchorAtCentre) != 0)
  75723. s << 'c';
  75724. }
  75725. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  75726. {
  75727. if (mode == proportionalSize)
  75728. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  75729. else if (mode == parentSizeMinusAbsolute)
  75730. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  75731. else
  75732. s << (roundToInt (value * 100.0) / 100.0);
  75733. }
  75734. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  75735. {
  75736. if (s.containsChar ('r'))
  75737. mode = anchorAtRightOrBottom;
  75738. else if (s.containsChar ('c'))
  75739. mode = anchorAtCentre;
  75740. else
  75741. mode = anchorAtLeftOrTop;
  75742. if (s.containsChar ('%'))
  75743. {
  75744. mode |= proportionOfParentSize;
  75745. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  75746. }
  75747. else
  75748. {
  75749. if (s.containsChar ('R'))
  75750. mode |= absoluteFromParentBottomRight;
  75751. else if (s.containsChar ('C'))
  75752. mode |= absoluteFromParentCentre;
  75753. else
  75754. mode |= absoluteFromParentTopLeft;
  75755. value = s.removeCharacters ("rcRC").getDoubleValue();
  75756. }
  75757. }
  75758. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  75759. {
  75760. if (s.containsChar ('%'))
  75761. {
  75762. mode = proportionalSize;
  75763. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  75764. }
  75765. else if (s.containsChar ('M'))
  75766. {
  75767. mode = parentSizeMinusAbsolute;
  75768. value = s.getDoubleValue();
  75769. }
  75770. else
  75771. {
  75772. mode = absoluteSize;
  75773. value = s.getDoubleValue();
  75774. }
  75775. }
  75776. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  75777. const double x_, const double w_,
  75778. const uint8 xMode_, const uint8 wMode_,
  75779. const int parentPos,
  75780. const int parentSize) const throw()
  75781. {
  75782. if (wMode_ == proportionalSize)
  75783. wOut = roundToInt (w_ * parentSize);
  75784. else if (wMode_ == parentSizeMinusAbsolute)
  75785. wOut = jmax (0, parentSize - roundToInt (w_));
  75786. else
  75787. wOut = roundToInt (w_);
  75788. if ((xMode_ & proportionOfParentSize) != 0)
  75789. xOut = parentPos + x_ * parentSize;
  75790. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  75791. xOut = (parentPos + parentSize) - x_;
  75792. else if ((xMode_ & absoluteFromParentCentre) != 0)
  75793. xOut = x_ + (parentPos + parentSize / 2);
  75794. else
  75795. xOut = x_ + parentPos;
  75796. if ((xMode_ & anchorAtRightOrBottom) != 0)
  75797. xOut -= wOut;
  75798. else if ((xMode_ & anchorAtCentre) != 0)
  75799. xOut -= wOut / 2;
  75800. }
  75801. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  75802. double x_, const double w_,
  75803. const uint8 xMode_, const uint8 wMode_,
  75804. const int parentPos,
  75805. const int parentSize) const throw()
  75806. {
  75807. if (wMode_ == proportionalSize)
  75808. {
  75809. if (parentSize > 0)
  75810. wOut = w_ / parentSize;
  75811. }
  75812. else if (wMode_ == parentSizeMinusAbsolute)
  75813. wOut = parentSize - w_;
  75814. else
  75815. wOut = w_;
  75816. if ((xMode_ & anchorAtRightOrBottom) != 0)
  75817. x_ += w_;
  75818. else if ((xMode_ & anchorAtCentre) != 0)
  75819. x_ += w_ / 2;
  75820. if ((xMode_ & proportionOfParentSize) != 0)
  75821. {
  75822. if (parentSize > 0)
  75823. xOut = (x_ - parentPos) / parentSize;
  75824. }
  75825. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  75826. xOut = (parentPos + parentSize) - x_;
  75827. else if ((xMode_ & absoluteFromParentCentre) != 0)
  75828. xOut = x_ - (parentPos + parentSize / 2);
  75829. else
  75830. xOut = x_ - parentPos;
  75831. }
  75832. END_JUCE_NAMESPACE
  75833. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  75834. /*** Start of inlined file: juce_RectangleList.cpp ***/
  75835. BEGIN_JUCE_NAMESPACE
  75836. RectangleList::RectangleList() throw()
  75837. {
  75838. }
  75839. RectangleList::RectangleList (const Rectangle<int>& rect)
  75840. {
  75841. if (! rect.isEmpty())
  75842. rects.add (rect);
  75843. }
  75844. RectangleList::RectangleList (const RectangleList& other)
  75845. : rects (other.rects)
  75846. {
  75847. }
  75848. RectangleList& RectangleList::operator= (const RectangleList& other)
  75849. {
  75850. rects = other.rects;
  75851. return *this;
  75852. }
  75853. RectangleList::~RectangleList()
  75854. {
  75855. }
  75856. void RectangleList::clear()
  75857. {
  75858. rects.clearQuick();
  75859. }
  75860. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  75861. {
  75862. if (((unsigned int) index) < (unsigned int) rects.size())
  75863. return rects.getReference (index);
  75864. return Rectangle<int>();
  75865. }
  75866. bool RectangleList::isEmpty() const throw()
  75867. {
  75868. return rects.size() == 0;
  75869. }
  75870. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  75871. : current (0),
  75872. owner (list),
  75873. index (list.rects.size())
  75874. {
  75875. }
  75876. RectangleList::Iterator::~Iterator()
  75877. {
  75878. }
  75879. bool RectangleList::Iterator::next() throw()
  75880. {
  75881. if (--index >= 0)
  75882. {
  75883. current = & (owner.rects.getReference (index));
  75884. return true;
  75885. }
  75886. return false;
  75887. }
  75888. void RectangleList::add (const Rectangle<int>& rect)
  75889. {
  75890. if (! rect.isEmpty())
  75891. {
  75892. if (rects.size() == 0)
  75893. {
  75894. rects.add (rect);
  75895. }
  75896. else
  75897. {
  75898. bool anyOverlaps = false;
  75899. int i;
  75900. for (i = rects.size(); --i >= 0;)
  75901. {
  75902. Rectangle<int>& ourRect = rects.getReference (i);
  75903. if (rect.intersects (ourRect))
  75904. {
  75905. if (rect.contains (ourRect))
  75906. rects.remove (i);
  75907. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  75908. anyOverlaps = true;
  75909. }
  75910. }
  75911. if (anyOverlaps && rects.size() > 0)
  75912. {
  75913. RectangleList r (rect);
  75914. for (i = rects.size(); --i >= 0;)
  75915. {
  75916. const Rectangle<int>& ourRect = rects.getReference (i);
  75917. if (rect.intersects (ourRect))
  75918. {
  75919. r.subtract (ourRect);
  75920. if (r.rects.size() == 0)
  75921. return;
  75922. }
  75923. }
  75924. for (i = r.getNumRectangles(); --i >= 0;)
  75925. rects.add (r.rects.getReference (i));
  75926. }
  75927. else
  75928. {
  75929. rects.add (rect);
  75930. }
  75931. }
  75932. }
  75933. }
  75934. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  75935. {
  75936. if (! rect.isEmpty())
  75937. rects.add (rect);
  75938. }
  75939. void RectangleList::add (const int x, const int y, const int w, const int h)
  75940. {
  75941. if (rects.size() == 0)
  75942. {
  75943. if (w > 0 && h > 0)
  75944. rects.add (Rectangle<int> (x, y, w, h));
  75945. }
  75946. else
  75947. {
  75948. add (Rectangle<int> (x, y, w, h));
  75949. }
  75950. }
  75951. void RectangleList::add (const RectangleList& other)
  75952. {
  75953. for (int i = 0; i < other.rects.size(); ++i)
  75954. add (other.rects.getReference (i));
  75955. }
  75956. void RectangleList::subtract (const Rectangle<int>& rect)
  75957. {
  75958. const int originalNumRects = rects.size();
  75959. if (originalNumRects > 0)
  75960. {
  75961. const int x1 = rect.x;
  75962. const int y1 = rect.y;
  75963. const int x2 = x1 + rect.w;
  75964. const int y2 = y1 + rect.h;
  75965. for (int i = getNumRectangles(); --i >= 0;)
  75966. {
  75967. Rectangle<int>& r = rects.getReference (i);
  75968. const int rx1 = r.x;
  75969. const int ry1 = r.y;
  75970. const int rx2 = rx1 + r.w;
  75971. const int ry2 = ry1 + r.h;
  75972. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  75973. {
  75974. if (x1 > rx1 && x1 < rx2)
  75975. {
  75976. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  75977. {
  75978. r.w = x1 - rx1;
  75979. }
  75980. else
  75981. {
  75982. r.x = x1;
  75983. r.w = rx2 - x1;
  75984. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  75985. i += 2;
  75986. }
  75987. }
  75988. else if (x2 > rx1 && x2 < rx2)
  75989. {
  75990. r.x = x2;
  75991. r.w = rx2 - x2;
  75992. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  75993. {
  75994. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  75995. i += 2;
  75996. }
  75997. }
  75998. else if (y1 > ry1 && y1 < ry2)
  75999. {
  76000. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76001. {
  76002. r.h = y1 - ry1;
  76003. }
  76004. else
  76005. {
  76006. r.y = y1;
  76007. r.h = ry2 - y1;
  76008. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76009. i += 2;
  76010. }
  76011. }
  76012. else if (y2 > ry1 && y2 < ry2)
  76013. {
  76014. r.y = y2;
  76015. r.h = ry2 - y2;
  76016. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76017. {
  76018. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76019. i += 2;
  76020. }
  76021. }
  76022. else
  76023. {
  76024. rects.remove (i);
  76025. }
  76026. }
  76027. }
  76028. }
  76029. }
  76030. bool RectangleList::subtract (const RectangleList& otherList)
  76031. {
  76032. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76033. subtract (otherList.rects.getReference (i));
  76034. return rects.size() > 0;
  76035. }
  76036. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76037. {
  76038. bool notEmpty = false;
  76039. if (rect.isEmpty())
  76040. {
  76041. clear();
  76042. }
  76043. else
  76044. {
  76045. for (int i = rects.size(); --i >= 0;)
  76046. {
  76047. Rectangle<int>& r = rects.getReference (i);
  76048. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76049. rects.remove (i);
  76050. else
  76051. notEmpty = true;
  76052. }
  76053. }
  76054. return notEmpty;
  76055. }
  76056. bool RectangleList::clipTo (const RectangleList& other)
  76057. {
  76058. if (rects.size() == 0)
  76059. return false;
  76060. RectangleList result;
  76061. for (int j = 0; j < rects.size(); ++j)
  76062. {
  76063. const Rectangle<int>& rect = rects.getReference (j);
  76064. for (int i = other.rects.size(); --i >= 0;)
  76065. {
  76066. Rectangle<int> r (other.rects.getReference (i));
  76067. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76068. result.rects.add (r);
  76069. }
  76070. }
  76071. swapWith (result);
  76072. return ! isEmpty();
  76073. }
  76074. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76075. {
  76076. destRegion.clear();
  76077. if (! rect.isEmpty())
  76078. {
  76079. for (int i = rects.size(); --i >= 0;)
  76080. {
  76081. Rectangle<int> r (rects.getReference (i));
  76082. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76083. destRegion.rects.add (r);
  76084. }
  76085. }
  76086. return destRegion.rects.size() > 0;
  76087. }
  76088. void RectangleList::swapWith (RectangleList& otherList) throw()
  76089. {
  76090. rects.swapWithArray (otherList.rects);
  76091. }
  76092. void RectangleList::consolidate()
  76093. {
  76094. int i;
  76095. for (i = 0; i < getNumRectangles() - 1; ++i)
  76096. {
  76097. Rectangle<int>& r = rects.getReference (i);
  76098. const int rx1 = r.x;
  76099. const int ry1 = r.y;
  76100. const int rx2 = rx1 + r.w;
  76101. const int ry2 = ry1 + r.h;
  76102. for (int j = rects.size(); --j > i;)
  76103. {
  76104. Rectangle<int>& r2 = rects.getReference (j);
  76105. const int jrx1 = r2.x;
  76106. const int jry1 = r2.y;
  76107. const int jrx2 = jrx1 + r2.w;
  76108. const int jry2 = jry1 + r2.h;
  76109. // if the vertical edges of any blocks are touching and their horizontals don't
  76110. // line up, split them horizontally..
  76111. if (jrx1 == rx2 || jrx2 == rx1)
  76112. {
  76113. if (jry1 > ry1 && jry1 < ry2)
  76114. {
  76115. r.h = jry1 - ry1;
  76116. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76117. i = -1;
  76118. break;
  76119. }
  76120. if (jry2 > ry1 && jry2 < ry2)
  76121. {
  76122. r.h = jry2 - ry1;
  76123. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76124. i = -1;
  76125. break;
  76126. }
  76127. else if (ry1 > jry1 && ry1 < jry2)
  76128. {
  76129. r2.h = ry1 - jry1;
  76130. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76131. i = -1;
  76132. break;
  76133. }
  76134. else if (ry2 > jry1 && ry2 < jry2)
  76135. {
  76136. r2.h = ry2 - jry1;
  76137. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76138. i = -1;
  76139. break;
  76140. }
  76141. }
  76142. }
  76143. }
  76144. for (i = 0; i < rects.size() - 1; ++i)
  76145. {
  76146. Rectangle<int>& r = rects.getReference (i);
  76147. for (int j = rects.size(); --j > i;)
  76148. {
  76149. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76150. {
  76151. rects.remove (j);
  76152. i = -1;
  76153. break;
  76154. }
  76155. }
  76156. }
  76157. }
  76158. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76159. {
  76160. for (int i = getNumRectangles(); --i >= 0;)
  76161. if (rects.getReference (i).contains (x, y))
  76162. return true;
  76163. return false;
  76164. }
  76165. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76166. {
  76167. if (rects.size() > 1)
  76168. {
  76169. RectangleList r (rectangleToCheck);
  76170. for (int i = rects.size(); --i >= 0;)
  76171. {
  76172. r.subtract (rects.getReference (i));
  76173. if (r.rects.size() == 0)
  76174. return true;
  76175. }
  76176. }
  76177. else if (rects.size() > 0)
  76178. {
  76179. return rects.getReference (0).contains (rectangleToCheck);
  76180. }
  76181. return false;
  76182. }
  76183. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76184. {
  76185. for (int i = rects.size(); --i >= 0;)
  76186. if (rects.getReference (i).intersects (rectangleToCheck))
  76187. return true;
  76188. return false;
  76189. }
  76190. bool RectangleList::intersects (const RectangleList& other) const throw()
  76191. {
  76192. for (int i = rects.size(); --i >= 0;)
  76193. if (other.intersectsRectangle (rects.getReference (i)))
  76194. return true;
  76195. return false;
  76196. }
  76197. const Rectangle<int> RectangleList::getBounds() const throw()
  76198. {
  76199. if (rects.size() <= 1)
  76200. {
  76201. if (rects.size() == 0)
  76202. return Rectangle<int>();
  76203. else
  76204. return rects.getReference (0);
  76205. }
  76206. else
  76207. {
  76208. const Rectangle<int>& r = rects.getReference (0);
  76209. int minX = r.x;
  76210. int minY = r.y;
  76211. int maxX = minX + r.w;
  76212. int maxY = minY + r.h;
  76213. for (int i = rects.size(); --i > 0;)
  76214. {
  76215. const Rectangle<int>& r2 = rects.getReference (i);
  76216. minX = jmin (minX, r2.x);
  76217. minY = jmin (minY, r2.y);
  76218. maxX = jmax (maxX, r2.getRight());
  76219. maxY = jmax (maxY, r2.getBottom());
  76220. }
  76221. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  76222. }
  76223. }
  76224. void RectangleList::offsetAll (const int dx, const int dy) throw()
  76225. {
  76226. for (int i = rects.size(); --i >= 0;)
  76227. {
  76228. Rectangle<int>& r = rects.getReference (i);
  76229. r.x += dx;
  76230. r.y += dy;
  76231. }
  76232. }
  76233. const Path RectangleList::toPath() const
  76234. {
  76235. Path p;
  76236. for (int i = rects.size(); --i >= 0;)
  76237. {
  76238. const Rectangle<int>& r = rects.getReference (i);
  76239. p.addRectangle ((float) r.x,
  76240. (float) r.y,
  76241. (float) r.w,
  76242. (float) r.h);
  76243. }
  76244. return p;
  76245. }
  76246. END_JUCE_NAMESPACE
  76247. /*** End of inlined file: juce_RectangleList.cpp ***/
  76248. /*** Start of inlined file: juce_Image.cpp ***/
  76249. BEGIN_JUCE_NAMESPACE
  76250. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  76251. : format (format_), width (width_), height (height_)
  76252. {
  76253. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  76254. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  76255. }
  76256. Image::SharedImage::~SharedImage()
  76257. {
  76258. }
  76259. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76260. {
  76261. return imageData + lineStride * y + pixelStride * x;
  76262. }
  76263. class SoftwareSharedImage : public Image::SharedImage
  76264. {
  76265. public:
  76266. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76267. : Image::SharedImage (format_, width_, height_)
  76268. {
  76269. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76270. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76271. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76272. imageData = imageDataAllocated;
  76273. }
  76274. ~SoftwareSharedImage()
  76275. {
  76276. }
  76277. Image::ImageType getType() const
  76278. {
  76279. return Image::SoftwareImage;
  76280. }
  76281. LowLevelGraphicsContext* createLowLevelContext()
  76282. {
  76283. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76284. }
  76285. SharedImage* clone()
  76286. {
  76287. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76288. memcpy (s->imageData, imageData, lineStride * height);
  76289. return s;
  76290. }
  76291. private:
  76292. HeapBlock<uint8> imageDataAllocated;
  76293. };
  76294. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76295. {
  76296. return new SoftwareSharedImage (format, width, height, clearImage);
  76297. }
  76298. class SubsectionSharedImage : public Image::SharedImage
  76299. {
  76300. public:
  76301. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  76302. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  76303. image (image_), area (area_)
  76304. {
  76305. pixelStride = image_->getPixelStride();
  76306. lineStride = image_->getLineStride();
  76307. imageData = image_->getPixelData (area_.getX(), area_.getY());
  76308. }
  76309. ~SubsectionSharedImage() {}
  76310. Image::ImageType getType() const
  76311. {
  76312. return Image::SoftwareImage;
  76313. }
  76314. LowLevelGraphicsContext* createLowLevelContext()
  76315. {
  76316. LowLevelGraphicsContext* g = image->createLowLevelContext();
  76317. g->clipToRectangle (area);
  76318. g->setOrigin (area.getX(), area.getY());
  76319. return g;
  76320. }
  76321. SharedImage* clone()
  76322. {
  76323. return new SubsectionSharedImage (image->clone(), area);
  76324. }
  76325. private:
  76326. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  76327. const Rectangle<int> area;
  76328. SubsectionSharedImage (const SubsectionSharedImage&);
  76329. SubsectionSharedImage& operator= (const SubsectionSharedImage&);
  76330. };
  76331. const Image Image::getClippedImage (const Rectangle<int>& area) const
  76332. {
  76333. if (area.contains (getBounds()))
  76334. return *this;
  76335. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  76336. if (validArea.isEmpty())
  76337. return Image::null;
  76338. return Image (new SubsectionSharedImage (image, validArea));
  76339. }
  76340. Image::Image()
  76341. {
  76342. }
  76343. Image::Image (SharedImage* const instance)
  76344. : image (instance)
  76345. {
  76346. }
  76347. Image::Image (const PixelFormat format,
  76348. const int width, const int height,
  76349. const bool clearImage, const ImageType type)
  76350. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  76351. : new SoftwareSharedImage (format, width, height, clearImage))
  76352. {
  76353. }
  76354. Image::Image (const Image& other)
  76355. : image (other.image)
  76356. {
  76357. }
  76358. Image& Image::operator= (const Image& other)
  76359. {
  76360. image = other.image;
  76361. return *this;
  76362. }
  76363. Image::~Image()
  76364. {
  76365. }
  76366. const Image Image::null;
  76367. LowLevelGraphicsContext* Image::createLowLevelContext() const
  76368. {
  76369. return image == 0 ? 0 : image->createLowLevelContext();
  76370. }
  76371. void Image::duplicateIfShared()
  76372. {
  76373. if (image != 0 && image->getReferenceCount() > 1)
  76374. image = image->clone();
  76375. }
  76376. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  76377. {
  76378. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  76379. return *this;
  76380. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  76381. Graphics g (newImage);
  76382. g.setImageResamplingQuality (quality);
  76383. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  76384. return newImage;
  76385. }
  76386. const Image Image::convertedToFormat (PixelFormat newFormat) const
  76387. {
  76388. if (image == 0 || newFormat == image->format)
  76389. return *this;
  76390. Image newImage (newFormat, image->width, image->height, false, image->getType());
  76391. if (newFormat == SingleChannel)
  76392. {
  76393. if (! hasAlphaChannel())
  76394. {
  76395. newImage.clear (getBounds(), Colours::black);
  76396. }
  76397. else
  76398. {
  76399. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  76400. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  76401. for (int y = 0; y < image->height; ++y)
  76402. {
  76403. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  76404. uint8* dst = destData.getLinePointer (y);
  76405. for (int x = image->width; --x >= 0;)
  76406. {
  76407. *dst++ = src->getAlpha();
  76408. ++src;
  76409. }
  76410. }
  76411. }
  76412. }
  76413. else
  76414. {
  76415. if (hasAlphaChannel())
  76416. newImage.clear (getBounds());
  76417. Graphics g (newImage);
  76418. g.drawImageAt (*this, 0, 0);
  76419. }
  76420. return newImage;
  76421. }
  76422. const var Image::getTag() const
  76423. {
  76424. return image == 0 ? var::null : image->userTag;
  76425. }
  76426. void Image::setTag (const var& newTag)
  76427. {
  76428. if (image != 0)
  76429. image->userTag = newTag;
  76430. }
  76431. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  76432. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76433. pixelFormat (image.getFormat()),
  76434. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76435. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76436. width (w),
  76437. height (h)
  76438. {
  76439. jassert (data != 0);
  76440. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76441. }
  76442. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  76443. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76444. pixelFormat (image.getFormat()),
  76445. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76446. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76447. width (w),
  76448. height (h)
  76449. {
  76450. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76451. }
  76452. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  76453. : data (image.image == 0 ? 0 : image.image->imageData),
  76454. pixelFormat (image.getFormat()),
  76455. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76456. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76457. width (image.getWidth()),
  76458. height (image.getHeight())
  76459. {
  76460. }
  76461. Image::BitmapData::~BitmapData()
  76462. {
  76463. }
  76464. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  76465. {
  76466. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  76467. const uint8* const pixel = getPixelPointer (x, y);
  76468. switch (pixelFormat)
  76469. {
  76470. case Image::ARGB:
  76471. {
  76472. PixelARGB p (*(const PixelARGB*) pixel);
  76473. p.unpremultiply();
  76474. return Colour (p.getARGB());
  76475. }
  76476. case Image::RGB:
  76477. return Colour (((const PixelRGB*) pixel)->getARGB());
  76478. case Image::SingleChannel:
  76479. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  76480. default:
  76481. jassertfalse;
  76482. break;
  76483. }
  76484. return Colour();
  76485. }
  76486. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  76487. {
  76488. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  76489. uint8* const pixel = getPixelPointer (x, y);
  76490. const PixelARGB col (colour.getPixelARGB());
  76491. switch (pixelFormat)
  76492. {
  76493. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  76494. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  76495. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  76496. default: jassertfalse; break;
  76497. }
  76498. }
  76499. void Image::setPixelData (int x, int y, int w, int h,
  76500. const uint8* const sourcePixelData, const int sourceLineStride)
  76501. {
  76502. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  76503. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  76504. {
  76505. const BitmapData dest (*this, x, y, w, h, true);
  76506. for (int i = 0; i < h; ++i)
  76507. {
  76508. memcpy (dest.getLinePointer(i),
  76509. sourcePixelData + sourceLineStride * i,
  76510. w * dest.pixelStride);
  76511. }
  76512. }
  76513. }
  76514. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  76515. {
  76516. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  76517. if (! clipped.isEmpty())
  76518. {
  76519. const PixelARGB col (colourToClearTo.getPixelARGB());
  76520. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  76521. uint8* dest = destData.data;
  76522. int dh = clipped.getHeight();
  76523. while (--dh >= 0)
  76524. {
  76525. uint8* line = dest;
  76526. dest += destData.lineStride;
  76527. if (isARGB())
  76528. {
  76529. for (int x = clipped.getWidth(); --x >= 0;)
  76530. {
  76531. ((PixelARGB*) line)->set (col);
  76532. line += destData.pixelStride;
  76533. }
  76534. }
  76535. else if (isRGB())
  76536. {
  76537. for (int x = clipped.getWidth(); --x >= 0;)
  76538. {
  76539. ((PixelRGB*) line)->set (col);
  76540. line += destData.pixelStride;
  76541. }
  76542. }
  76543. else
  76544. {
  76545. for (int x = clipped.getWidth(); --x >= 0;)
  76546. {
  76547. *line = col.getAlpha();
  76548. line += destData.pixelStride;
  76549. }
  76550. }
  76551. }
  76552. }
  76553. }
  76554. const Colour Image::getPixelAt (const int x, const int y) const
  76555. {
  76556. if (((unsigned int) x) < (unsigned int) getWidth()
  76557. && ((unsigned int) y) < (unsigned int) getHeight())
  76558. {
  76559. const BitmapData srcData (*this, x, y, 1, 1);
  76560. return srcData.getPixelColour (0, 0);
  76561. }
  76562. return Colour();
  76563. }
  76564. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  76565. {
  76566. if (((unsigned int) x) < (unsigned int) getWidth()
  76567. && ((unsigned int) y) < (unsigned int) getHeight())
  76568. {
  76569. const BitmapData destData (*this, x, y, 1, 1, true);
  76570. destData.setPixelColour (0, 0, colour);
  76571. }
  76572. }
  76573. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  76574. {
  76575. if (((unsigned int) x) < (unsigned int) getWidth()
  76576. && ((unsigned int) y) < (unsigned int) getHeight()
  76577. && hasAlphaChannel())
  76578. {
  76579. const BitmapData destData (*this, x, y, 1, 1, true);
  76580. if (isARGB())
  76581. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  76582. else
  76583. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  76584. }
  76585. }
  76586. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  76587. {
  76588. if (hasAlphaChannel())
  76589. {
  76590. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76591. if (isARGB())
  76592. {
  76593. for (int y = 0; y < destData.height; ++y)
  76594. {
  76595. uint8* p = destData.getLinePointer (y);
  76596. for (int x = 0; x < destData.width; ++x)
  76597. {
  76598. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  76599. p += destData.pixelStride;
  76600. }
  76601. }
  76602. }
  76603. else
  76604. {
  76605. for (int y = 0; y < destData.height; ++y)
  76606. {
  76607. uint8* p = destData.getLinePointer (y);
  76608. for (int x = 0; x < destData.width; ++x)
  76609. {
  76610. *p = (uint8) (*p * amountToMultiplyBy);
  76611. p += destData.pixelStride;
  76612. }
  76613. }
  76614. }
  76615. }
  76616. else
  76617. {
  76618. jassertfalse; // can't do this without an alpha-channel!
  76619. }
  76620. }
  76621. void Image::desaturate()
  76622. {
  76623. if (isARGB() || isRGB())
  76624. {
  76625. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76626. if (isARGB())
  76627. {
  76628. for (int y = 0; y < destData.height; ++y)
  76629. {
  76630. uint8* p = destData.getLinePointer (y);
  76631. for (int x = 0; x < destData.width; ++x)
  76632. {
  76633. ((PixelARGB*) p)->desaturate();
  76634. p += destData.pixelStride;
  76635. }
  76636. }
  76637. }
  76638. else
  76639. {
  76640. for (int y = 0; y < destData.height; ++y)
  76641. {
  76642. uint8* p = destData.getLinePointer (y);
  76643. for (int x = 0; x < destData.width; ++x)
  76644. {
  76645. ((PixelRGB*) p)->desaturate();
  76646. p += destData.pixelStride;
  76647. }
  76648. }
  76649. }
  76650. }
  76651. }
  76652. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  76653. {
  76654. if (hasAlphaChannel())
  76655. {
  76656. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  76657. SparseSet<int> pixelsOnRow;
  76658. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  76659. for (int y = 0; y < srcData.height; ++y)
  76660. {
  76661. pixelsOnRow.clear();
  76662. const uint8* lineData = srcData.getLinePointer (y);
  76663. if (isARGB())
  76664. {
  76665. for (int x = 0; x < srcData.width; ++x)
  76666. {
  76667. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  76668. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76669. lineData += srcData.pixelStride;
  76670. }
  76671. }
  76672. else
  76673. {
  76674. for (int x = 0; x < srcData.width; ++x)
  76675. {
  76676. if (*lineData >= threshold)
  76677. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76678. lineData += srcData.pixelStride;
  76679. }
  76680. }
  76681. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  76682. {
  76683. const Range<int> range (pixelsOnRow.getRange (i));
  76684. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  76685. }
  76686. result.consolidate();
  76687. }
  76688. }
  76689. else
  76690. {
  76691. result.add (0, 0, getWidth(), getHeight());
  76692. }
  76693. }
  76694. void Image::moveImageSection (int dx, int dy,
  76695. int sx, int sy,
  76696. int w, int h)
  76697. {
  76698. if (dx < 0)
  76699. {
  76700. w += dx;
  76701. sx -= dx;
  76702. dx = 0;
  76703. }
  76704. if (dy < 0)
  76705. {
  76706. h += dy;
  76707. sy -= dy;
  76708. dy = 0;
  76709. }
  76710. if (sx < 0)
  76711. {
  76712. w += sx;
  76713. dx -= sx;
  76714. sx = 0;
  76715. }
  76716. if (sy < 0)
  76717. {
  76718. h += sy;
  76719. dy -= sy;
  76720. sy = 0;
  76721. }
  76722. const int minX = jmin (dx, sx);
  76723. const int minY = jmin (dy, sy);
  76724. w = jmin (w, getWidth() - jmax (sx, dx));
  76725. h = jmin (h, getHeight() - jmax (sy, dy));
  76726. if (w > 0 && h > 0)
  76727. {
  76728. const int maxX = jmax (dx, sx) + w;
  76729. const int maxY = jmax (dy, sy) + h;
  76730. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  76731. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  76732. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  76733. const int lineSize = destData.pixelStride * w;
  76734. if (dy > sy)
  76735. {
  76736. while (--h >= 0)
  76737. {
  76738. const int offset = h * destData.lineStride;
  76739. memmove (dst + offset, src + offset, lineSize);
  76740. }
  76741. }
  76742. else if (dst != src)
  76743. {
  76744. while (--h >= 0)
  76745. {
  76746. memmove (dst, src, lineSize);
  76747. dst += destData.lineStride;
  76748. src += destData.lineStride;
  76749. }
  76750. }
  76751. }
  76752. }
  76753. END_JUCE_NAMESPACE
  76754. /*** End of inlined file: juce_Image.cpp ***/
  76755. /*** Start of inlined file: juce_ImageCache.cpp ***/
  76756. BEGIN_JUCE_NAMESPACE
  76757. class ImageCache::Pimpl : public Timer,
  76758. public DeletedAtShutdown
  76759. {
  76760. public:
  76761. Pimpl()
  76762. : cacheTimeout (5000)
  76763. {
  76764. }
  76765. ~Pimpl()
  76766. {
  76767. clearSingletonInstance();
  76768. }
  76769. const Image getFromHashCode (const int64 hashCode)
  76770. {
  76771. const ScopedLock sl (lock);
  76772. for (int i = images.size(); --i >= 0;)
  76773. {
  76774. Item* const item = images.getUnchecked(i);
  76775. if (item->hashCode == hashCode)
  76776. return item->image;
  76777. }
  76778. return Image::null;
  76779. }
  76780. void addImageToCache (const Image& image, const int64 hashCode)
  76781. {
  76782. if (image.isValid())
  76783. {
  76784. if (! isTimerRunning())
  76785. startTimer (2000);
  76786. Item* const item = new Item();
  76787. item->hashCode = hashCode;
  76788. item->image = image;
  76789. item->lastUseTime = Time::getApproximateMillisecondCounter();
  76790. const ScopedLock sl (lock);
  76791. images.add (item);
  76792. }
  76793. }
  76794. void timerCallback()
  76795. {
  76796. const uint32 now = Time::getApproximateMillisecondCounter();
  76797. const ScopedLock sl (lock);
  76798. for (int i = images.size(); --i >= 0;)
  76799. {
  76800. Item* const item = images.getUnchecked(i);
  76801. if (item->image.getReferenceCount() <= 1)
  76802. {
  76803. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  76804. images.remove (i);
  76805. }
  76806. else
  76807. {
  76808. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  76809. }
  76810. }
  76811. if (images.size() == 0)
  76812. stopTimer();
  76813. }
  76814. struct Item
  76815. {
  76816. Image image;
  76817. int64 hashCode;
  76818. uint32 lastUseTime;
  76819. };
  76820. int cacheTimeout;
  76821. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  76822. private:
  76823. OwnedArray<Item> images;
  76824. CriticalSection lock;
  76825. Pimpl (const Pimpl&);
  76826. Pimpl& operator= (const Pimpl&);
  76827. };
  76828. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  76829. const Image ImageCache::getFromHashCode (const int64 hashCode)
  76830. {
  76831. if (Pimpl::getInstanceWithoutCreating() != 0)
  76832. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  76833. return Image::null;
  76834. }
  76835. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  76836. {
  76837. Pimpl::getInstance()->addImageToCache (image, hashCode);
  76838. }
  76839. const Image ImageCache::getFromFile (const File& file)
  76840. {
  76841. const int64 hashCode = file.hashCode64();
  76842. Image image (getFromHashCode (hashCode));
  76843. if (image.isNull())
  76844. {
  76845. image = ImageFileFormat::loadFrom (file);
  76846. addImageToCache (image, hashCode);
  76847. }
  76848. return image;
  76849. }
  76850. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  76851. {
  76852. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  76853. Image image (getFromHashCode (hashCode));
  76854. if (image.isNull())
  76855. {
  76856. image = ImageFileFormat::loadFrom (imageData, dataSize);
  76857. addImageToCache (image, hashCode);
  76858. }
  76859. return image;
  76860. }
  76861. void ImageCache::setCacheTimeout (const int millisecs)
  76862. {
  76863. Pimpl::getInstance()->cacheTimeout = millisecs;
  76864. }
  76865. END_JUCE_NAMESPACE
  76866. /*** End of inlined file: juce_ImageCache.cpp ***/
  76867. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  76868. BEGIN_JUCE_NAMESPACE
  76869. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  76870. : values (size_ * size_),
  76871. size (size_)
  76872. {
  76873. clear();
  76874. }
  76875. ImageConvolutionKernel::~ImageConvolutionKernel()
  76876. {
  76877. }
  76878. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  76879. {
  76880. if (((unsigned int) x) < (unsigned int) size
  76881. && ((unsigned int) y) < (unsigned int) size)
  76882. {
  76883. return values [x + y * size];
  76884. }
  76885. else
  76886. {
  76887. jassertfalse;
  76888. return 0;
  76889. }
  76890. }
  76891. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  76892. {
  76893. if (((unsigned int) x) < (unsigned int) size
  76894. && ((unsigned int) y) < (unsigned int) size)
  76895. {
  76896. values [x + y * size] = value;
  76897. }
  76898. else
  76899. {
  76900. jassertfalse;
  76901. }
  76902. }
  76903. void ImageConvolutionKernel::clear()
  76904. {
  76905. for (int i = size * size; --i >= 0;)
  76906. values[i] = 0;
  76907. }
  76908. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  76909. {
  76910. double currentTotal = 0.0;
  76911. for (int i = size * size; --i >= 0;)
  76912. currentTotal += values[i];
  76913. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  76914. }
  76915. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  76916. {
  76917. for (int i = size * size; --i >= 0;)
  76918. values[i] *= multiplier;
  76919. }
  76920. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  76921. {
  76922. const double radiusFactor = -1.0 / (radius * radius * 2);
  76923. const int centre = size >> 1;
  76924. for (int y = size; --y >= 0;)
  76925. {
  76926. for (int x = size; --x >= 0;)
  76927. {
  76928. const int cx = x - centre;
  76929. const int cy = y - centre;
  76930. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  76931. }
  76932. }
  76933. setOverallSum (1.0f);
  76934. }
  76935. void ImageConvolutionKernel::applyToImage (Image& destImage,
  76936. const Image& sourceImage,
  76937. const Rectangle<int>& destinationArea) const
  76938. {
  76939. if (sourceImage == destImage)
  76940. {
  76941. destImage.duplicateIfShared();
  76942. }
  76943. else
  76944. {
  76945. if (sourceImage.getWidth() != destImage.getWidth()
  76946. || sourceImage.getHeight() != destImage.getHeight()
  76947. || sourceImage.getFormat() != destImage.getFormat())
  76948. {
  76949. jassertfalse;
  76950. return;
  76951. }
  76952. }
  76953. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  76954. if (area.isEmpty())
  76955. return;
  76956. const int right = area.getRight();
  76957. const int bottom = area.getBottom();
  76958. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  76959. uint8* line = destData.data;
  76960. const Image::BitmapData srcData (sourceImage, false);
  76961. if (destData.pixelStride == 4)
  76962. {
  76963. for (int y = area.getY(); y < bottom; ++y)
  76964. {
  76965. uint8* dest = line;
  76966. line += destData.lineStride;
  76967. for (int x = area.getX(); x < right; ++x)
  76968. {
  76969. float c1 = 0;
  76970. float c2 = 0;
  76971. float c3 = 0;
  76972. float c4 = 0;
  76973. for (int yy = 0; yy < size; ++yy)
  76974. {
  76975. const int sy = y + yy - (size >> 1);
  76976. if (sy >= srcData.height)
  76977. break;
  76978. if (sy >= 0)
  76979. {
  76980. int sx = x - (size >> 1);
  76981. const uint8* src = srcData.getPixelPointer (sx, sy);
  76982. for (int xx = 0; xx < size; ++xx)
  76983. {
  76984. if (sx >= srcData.width)
  76985. break;
  76986. if (sx >= 0)
  76987. {
  76988. const float kernelMult = values [xx + yy * size];
  76989. c1 += kernelMult * *src++;
  76990. c2 += kernelMult * *src++;
  76991. c3 += kernelMult * *src++;
  76992. c4 += kernelMult * *src++;
  76993. }
  76994. else
  76995. {
  76996. src += 4;
  76997. }
  76998. ++sx;
  76999. }
  77000. }
  77001. }
  77002. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77003. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77004. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77005. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77006. }
  77007. }
  77008. }
  77009. else if (destData.pixelStride == 3)
  77010. {
  77011. for (int y = area.getY(); y < bottom; ++y)
  77012. {
  77013. uint8* dest = line;
  77014. line += destData.lineStride;
  77015. for (int x = area.getX(); x < right; ++x)
  77016. {
  77017. float c1 = 0;
  77018. float c2 = 0;
  77019. float c3 = 0;
  77020. for (int yy = 0; yy < size; ++yy)
  77021. {
  77022. const int sy = y + yy - (size >> 1);
  77023. if (sy >= srcData.height)
  77024. break;
  77025. if (sy >= 0)
  77026. {
  77027. int sx = x - (size >> 1);
  77028. const uint8* src = srcData.getPixelPointer (sx, sy);
  77029. for (int xx = 0; xx < size; ++xx)
  77030. {
  77031. if (sx >= srcData.width)
  77032. break;
  77033. if (sx >= 0)
  77034. {
  77035. const float kernelMult = values [xx + yy * size];
  77036. c1 += kernelMult * *src++;
  77037. c2 += kernelMult * *src++;
  77038. c3 += kernelMult * *src++;
  77039. }
  77040. else
  77041. {
  77042. src += 3;
  77043. }
  77044. ++sx;
  77045. }
  77046. }
  77047. }
  77048. *dest++ = (uint8) roundToInt (c1);
  77049. *dest++ = (uint8) roundToInt (c2);
  77050. *dest++ = (uint8) roundToInt (c3);
  77051. }
  77052. }
  77053. }
  77054. }
  77055. END_JUCE_NAMESPACE
  77056. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77057. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77058. BEGIN_JUCE_NAMESPACE
  77059. /*** Start of inlined file: juce_GIFLoader.h ***/
  77060. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  77061. #define __JUCE_GIFLOADER_JUCEHEADER__
  77062. #ifndef DOXYGEN
  77063. /**
  77064. Used internally by ImageFileFormat - don't use this class directly in your
  77065. application.
  77066. @see ImageFileFormat
  77067. */
  77068. class GIFLoader
  77069. {
  77070. public:
  77071. GIFLoader (InputStream& in);
  77072. ~GIFLoader();
  77073. const Image& getImage() const { return image; }
  77074. private:
  77075. Image image;
  77076. InputStream& input;
  77077. uint8 buffer [300];
  77078. uint8 palette [256][4];
  77079. bool dataBlockIsZero, fresh, finished;
  77080. int currentBit, lastBit, lastByteIndex;
  77081. int codeSize, setCodeSize;
  77082. int maxCode, maxCodeSize;
  77083. int firstcode, oldcode;
  77084. int clearCode, end_code;
  77085. enum { maxGifCode = 1 << 12 };
  77086. int table [2] [maxGifCode];
  77087. int stack [2 * maxGifCode];
  77088. int *sp;
  77089. bool getSizeFromHeader (int& width, int& height);
  77090. bool readPalette (const int numCols);
  77091. int readDataBlock (unsigned char* dest);
  77092. int processExtension (int type, int& transparent);
  77093. int readLZWByte (bool initialise, int input_code_size);
  77094. int getCode (int code_size, bool initialise);
  77095. bool readImage (int interlace, int transparent);
  77096. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  77097. GIFLoader (const GIFLoader&);
  77098. GIFLoader& operator= (const GIFLoader&);
  77099. };
  77100. #endif // DOXYGEN
  77101. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  77102. /*** End of inlined file: juce_GIFLoader.h ***/
  77103. class GIFImageFormat : public ImageFileFormat
  77104. {
  77105. public:
  77106. GIFImageFormat() {}
  77107. ~GIFImageFormat() {}
  77108. const String getFormatName()
  77109. {
  77110. return "GIF";
  77111. }
  77112. bool canUnderstand (InputStream& in)
  77113. {
  77114. const int bytesNeeded = 4;
  77115. char header [bytesNeeded];
  77116. return (in.read (header, bytesNeeded) == bytesNeeded)
  77117. && header[0] == 'G'
  77118. && header[1] == 'I'
  77119. && header[2] == 'F';
  77120. }
  77121. const Image decodeImage (InputStream& in)
  77122. {
  77123. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  77124. return loader->getImage();
  77125. }
  77126. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  77127. {
  77128. return false;
  77129. }
  77130. };
  77131. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77132. {
  77133. static PNGImageFormat png;
  77134. static JPEGImageFormat jpg;
  77135. static GIFImageFormat gif;
  77136. ImageFileFormat* formats[4];
  77137. int numFormats = 0;
  77138. formats [numFormats++] = &png;
  77139. formats [numFormats++] = &jpg;
  77140. formats [numFormats++] = &gif;
  77141. const int64 streamPos = input.getPosition();
  77142. for (int i = 0; i < numFormats; ++i)
  77143. {
  77144. const bool found = formats[i]->canUnderstand (input);
  77145. input.setPosition (streamPos);
  77146. if (found)
  77147. return formats[i];
  77148. }
  77149. return 0;
  77150. }
  77151. const Image ImageFileFormat::loadFrom (InputStream& input)
  77152. {
  77153. ImageFileFormat* const format = findImageFormatForStream (input);
  77154. if (format != 0)
  77155. return format->decodeImage (input);
  77156. return Image::null;
  77157. }
  77158. const Image ImageFileFormat::loadFrom (const File& file)
  77159. {
  77160. InputStream* const in = file.createInputStream();
  77161. if (in != 0)
  77162. {
  77163. BufferedInputStream b (in, 8192, true);
  77164. return loadFrom (b);
  77165. }
  77166. return Image::null;
  77167. }
  77168. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77169. {
  77170. if (rawData != 0 && numBytes > 4)
  77171. {
  77172. MemoryInputStream stream (rawData, numBytes, false);
  77173. return loadFrom (stream);
  77174. }
  77175. return Image::null;
  77176. }
  77177. END_JUCE_NAMESPACE
  77178. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77179. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77180. BEGIN_JUCE_NAMESPACE
  77181. GIFLoader::GIFLoader (InputStream& in)
  77182. : input (in),
  77183. dataBlockIsZero (false),
  77184. fresh (false),
  77185. finished (false)
  77186. {
  77187. currentBit = lastBit = lastByteIndex = 0;
  77188. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77189. firstcode = oldcode = 0;
  77190. clearCode = end_code = 0;
  77191. int imageWidth, imageHeight;
  77192. int transparent = -1;
  77193. if (! getSizeFromHeader (imageWidth, imageHeight))
  77194. return;
  77195. if ((imageWidth <= 0) || (imageHeight <= 0))
  77196. return;
  77197. unsigned char buf [16];
  77198. if (in.read (buf, 3) != 3)
  77199. return;
  77200. int numColours = 2 << (buf[0] & 7);
  77201. if ((buf[0] & 0x80) != 0)
  77202. readPalette (numColours);
  77203. for (;;)
  77204. {
  77205. if (input.read (buf, 1) != 1)
  77206. break;
  77207. if (buf[0] == ';')
  77208. break;
  77209. if (buf[0] == '!')
  77210. {
  77211. if (input.read (buf, 1) != 1)
  77212. break;
  77213. if (processExtension (buf[0], transparent) < 0)
  77214. break;
  77215. continue;
  77216. }
  77217. if (buf[0] != ',')
  77218. continue;
  77219. if (input.read (buf, 9) != 9)
  77220. break;
  77221. imageWidth = makeWord (buf[4], buf[5]);
  77222. imageHeight = makeWord (buf[6], buf[7]);
  77223. numColours = 2 << (buf[8] & 7);
  77224. if ((buf[8] & 0x80) != 0)
  77225. if (! readPalette (numColours))
  77226. break;
  77227. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77228. imageWidth, imageHeight, (transparent >= 0));
  77229. readImage ((buf[8] & 0x40) != 0, transparent);
  77230. break;
  77231. }
  77232. }
  77233. GIFLoader::~GIFLoader()
  77234. {
  77235. }
  77236. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  77237. {
  77238. char b[8];
  77239. if (input.read (b, 6) == 6)
  77240. {
  77241. if ((strncmp ("GIF87a", b, 6) == 0)
  77242. || (strncmp ("GIF89a", b, 6) == 0))
  77243. {
  77244. if (input.read (b, 4) == 4)
  77245. {
  77246. w = makeWord (b[0], b[1]);
  77247. h = makeWord (b[2], b[3]);
  77248. return true;
  77249. }
  77250. }
  77251. }
  77252. return false;
  77253. }
  77254. bool GIFLoader::readPalette (const int numCols)
  77255. {
  77256. unsigned char rgb[4];
  77257. for (int i = 0; i < numCols; ++i)
  77258. {
  77259. input.read (rgb, 3);
  77260. palette [i][0] = rgb[0];
  77261. palette [i][1] = rgb[1];
  77262. palette [i][2] = rgb[2];
  77263. palette [i][3] = 0xff;
  77264. }
  77265. return true;
  77266. }
  77267. int GIFLoader::readDataBlock (unsigned char* const dest)
  77268. {
  77269. unsigned char n;
  77270. if (input.read (&n, 1) == 1)
  77271. {
  77272. dataBlockIsZero = (n == 0);
  77273. if (dataBlockIsZero || (input.read (dest, n) == n))
  77274. return n;
  77275. }
  77276. return -1;
  77277. }
  77278. int GIFLoader::processExtension (const int type, int& transparent)
  77279. {
  77280. unsigned char b [300];
  77281. int n = 0;
  77282. if (type == 0xf9)
  77283. {
  77284. n = readDataBlock (b);
  77285. if (n < 0)
  77286. return 1;
  77287. if ((b[0] & 0x1) != 0)
  77288. transparent = b[3];
  77289. }
  77290. do
  77291. {
  77292. n = readDataBlock (b);
  77293. }
  77294. while (n > 0);
  77295. return n;
  77296. }
  77297. int GIFLoader::getCode (const int codeSize_, const bool initialise)
  77298. {
  77299. if (initialise)
  77300. {
  77301. currentBit = 0;
  77302. lastBit = 0;
  77303. finished = false;
  77304. return 0;
  77305. }
  77306. if ((currentBit + codeSize_) >= lastBit)
  77307. {
  77308. if (finished)
  77309. return -1;
  77310. buffer[0] = buffer [lastByteIndex - 2];
  77311. buffer[1] = buffer [lastByteIndex - 1];
  77312. const int n = readDataBlock (&buffer[2]);
  77313. if (n == 0)
  77314. finished = true;
  77315. lastByteIndex = 2 + n;
  77316. currentBit = (currentBit - lastBit) + 16;
  77317. lastBit = (2 + n) * 8 ;
  77318. }
  77319. int result = 0;
  77320. int i = currentBit;
  77321. for (int j = 0; j < codeSize_; ++j)
  77322. {
  77323. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  77324. ++i;
  77325. }
  77326. currentBit += codeSize_;
  77327. return result;
  77328. }
  77329. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  77330. {
  77331. int code, incode, i;
  77332. if (initialise)
  77333. {
  77334. setCodeSize = inputCodeSize;
  77335. codeSize = setCodeSize + 1;
  77336. clearCode = 1 << setCodeSize;
  77337. end_code = clearCode + 1;
  77338. maxCodeSize = 2 * clearCode;
  77339. maxCode = clearCode + 2;
  77340. getCode (0, true);
  77341. fresh = true;
  77342. for (i = 0; i < clearCode; ++i)
  77343. {
  77344. table[0][i] = 0;
  77345. table[1][i] = i;
  77346. }
  77347. for (; i < maxGifCode; ++i)
  77348. {
  77349. table[0][i] = 0;
  77350. table[1][i] = 0;
  77351. }
  77352. sp = stack;
  77353. return 0;
  77354. }
  77355. else if (fresh)
  77356. {
  77357. fresh = false;
  77358. do
  77359. {
  77360. firstcode = oldcode
  77361. = getCode (codeSize, false);
  77362. }
  77363. while (firstcode == clearCode);
  77364. return firstcode;
  77365. }
  77366. if (sp > stack)
  77367. return *--sp;
  77368. while ((code = getCode (codeSize, false)) >= 0)
  77369. {
  77370. if (code == clearCode)
  77371. {
  77372. for (i = 0; i < clearCode; ++i)
  77373. {
  77374. table[0][i] = 0;
  77375. table[1][i] = i;
  77376. }
  77377. for (; i < maxGifCode; ++i)
  77378. {
  77379. table[0][i] = 0;
  77380. table[1][i] = 0;
  77381. }
  77382. codeSize = setCodeSize + 1;
  77383. maxCodeSize = 2 * clearCode;
  77384. maxCode = clearCode + 2;
  77385. sp = stack;
  77386. firstcode = oldcode = getCode (codeSize, false);
  77387. return firstcode;
  77388. }
  77389. else if (code == end_code)
  77390. {
  77391. if (dataBlockIsZero)
  77392. return -2;
  77393. unsigned char buf [260];
  77394. int n;
  77395. while ((n = readDataBlock (buf)) > 0)
  77396. {}
  77397. if (n != 0)
  77398. return -2;
  77399. }
  77400. incode = code;
  77401. if (code >= maxCode)
  77402. {
  77403. *sp++ = firstcode;
  77404. code = oldcode;
  77405. }
  77406. while (code >= clearCode)
  77407. {
  77408. *sp++ = table[1][code];
  77409. if (code == table[0][code])
  77410. return -2;
  77411. code = table[0][code];
  77412. }
  77413. *sp++ = firstcode = table[1][code];
  77414. if ((code = maxCode) < maxGifCode)
  77415. {
  77416. table[0][code] = oldcode;
  77417. table[1][code] = firstcode;
  77418. ++maxCode;
  77419. if ((maxCode >= maxCodeSize)
  77420. && (maxCodeSize < maxGifCode))
  77421. {
  77422. maxCodeSize <<= 1;
  77423. ++codeSize;
  77424. }
  77425. }
  77426. oldcode = incode;
  77427. if (sp > stack)
  77428. return *--sp;
  77429. }
  77430. return code;
  77431. }
  77432. bool GIFLoader::readImage (const int interlace, const int transparent)
  77433. {
  77434. unsigned char c;
  77435. if (input.read (&c, 1) != 1
  77436. || readLZWByte (true, c) < 0)
  77437. return false;
  77438. if (transparent >= 0)
  77439. {
  77440. palette [transparent][0] = 0;
  77441. palette [transparent][1] = 0;
  77442. palette [transparent][2] = 0;
  77443. palette [transparent][3] = 0;
  77444. }
  77445. int index;
  77446. int xpos = 0, ypos = 0, pass = 0;
  77447. const Image::BitmapData destData (image, true);
  77448. uint8* p = destData.data;
  77449. const bool hasAlpha = image.hasAlphaChannel();
  77450. while ((index = readLZWByte (false, c)) >= 0)
  77451. {
  77452. const uint8* const paletteEntry = palette [index];
  77453. if (hasAlpha)
  77454. {
  77455. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  77456. paletteEntry[0],
  77457. paletteEntry[1],
  77458. paletteEntry[2]);
  77459. ((PixelARGB*) p)->premultiply();
  77460. }
  77461. else
  77462. {
  77463. ((PixelRGB*) p)->setARGB (0,
  77464. paletteEntry[0],
  77465. paletteEntry[1],
  77466. paletteEntry[2]);
  77467. }
  77468. p += destData.pixelStride;
  77469. ++xpos;
  77470. if (xpos == destData.width)
  77471. {
  77472. xpos = 0;
  77473. if (interlace)
  77474. {
  77475. switch (pass)
  77476. {
  77477. case 0:
  77478. case 1: ypos += 8; break;
  77479. case 2: ypos += 4; break;
  77480. case 3: ypos += 2; break;
  77481. }
  77482. while (ypos >= destData.height)
  77483. {
  77484. ++pass;
  77485. switch (pass)
  77486. {
  77487. case 1: ypos = 4; break;
  77488. case 2: ypos = 2; break;
  77489. case 3: ypos = 1; break;
  77490. default: return true;
  77491. }
  77492. }
  77493. }
  77494. else
  77495. {
  77496. ++ypos;
  77497. }
  77498. p = destData.getPixelPointer (xpos, ypos);
  77499. }
  77500. if (ypos >= destData.height)
  77501. break;
  77502. }
  77503. return true;
  77504. }
  77505. END_JUCE_NAMESPACE
  77506. /*** End of inlined file: juce_GIFLoader.cpp ***/
  77507. #endif
  77508. //==============================================================================
  77509. // some files include lots of library code, so leave them to the end to avoid cluttering
  77510. // up the build for the clean files.
  77511. #if JUCE_BUILD_CORE
  77512. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  77513. namespace zlibNamespace
  77514. {
  77515. #if JUCE_INCLUDE_ZLIB_CODE
  77516. #undef OS_CODE
  77517. #undef fdopen
  77518. /*** Start of inlined file: zlib.h ***/
  77519. #ifndef ZLIB_H
  77520. #define ZLIB_H
  77521. /*** Start of inlined file: zconf.h ***/
  77522. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  77523. #ifndef ZCONF_H
  77524. #define ZCONF_H
  77525. // *** Just a few hacks here to make it compile nicely with Juce..
  77526. #define Z_PREFIX 1
  77527. #undef __MACTYPES__
  77528. #ifdef _MSC_VER
  77529. #pragma warning (disable : 4131 4127 4244 4267)
  77530. #endif
  77531. /*
  77532. * If you *really* need a unique prefix for all types and library functions,
  77533. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  77534. */
  77535. #ifdef Z_PREFIX
  77536. # define deflateInit_ z_deflateInit_
  77537. # define deflate z_deflate
  77538. # define deflateEnd z_deflateEnd
  77539. # define inflateInit_ z_inflateInit_
  77540. # define inflate z_inflate
  77541. # define inflateEnd z_inflateEnd
  77542. # define inflatePrime z_inflatePrime
  77543. # define inflateGetHeader z_inflateGetHeader
  77544. # define adler32_combine z_adler32_combine
  77545. # define crc32_combine z_crc32_combine
  77546. # define deflateInit2_ z_deflateInit2_
  77547. # define deflateSetDictionary z_deflateSetDictionary
  77548. # define deflateCopy z_deflateCopy
  77549. # define deflateReset z_deflateReset
  77550. # define deflateParams z_deflateParams
  77551. # define deflateBound z_deflateBound
  77552. # define deflatePrime z_deflatePrime
  77553. # define inflateInit2_ z_inflateInit2_
  77554. # define inflateSetDictionary z_inflateSetDictionary
  77555. # define inflateSync z_inflateSync
  77556. # define inflateSyncPoint z_inflateSyncPoint
  77557. # define inflateCopy z_inflateCopy
  77558. # define inflateReset z_inflateReset
  77559. # define inflateBack z_inflateBack
  77560. # define inflateBackEnd z_inflateBackEnd
  77561. # define compress z_compress
  77562. # define compress2 z_compress2
  77563. # define compressBound z_compressBound
  77564. # define uncompress z_uncompress
  77565. # define adler32 z_adler32
  77566. # define crc32 z_crc32
  77567. # define get_crc_table z_get_crc_table
  77568. # define zError z_zError
  77569. # define alloc_func z_alloc_func
  77570. # define free_func z_free_func
  77571. # define in_func z_in_func
  77572. # define out_func z_out_func
  77573. # define Byte z_Byte
  77574. # define uInt z_uInt
  77575. # define uLong z_uLong
  77576. # define Bytef z_Bytef
  77577. # define charf z_charf
  77578. # define intf z_intf
  77579. # define uIntf z_uIntf
  77580. # define uLongf z_uLongf
  77581. # define voidpf z_voidpf
  77582. # define voidp z_voidp
  77583. #endif
  77584. #if defined(__MSDOS__) && !defined(MSDOS)
  77585. # define MSDOS
  77586. #endif
  77587. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  77588. # define OS2
  77589. #endif
  77590. #if defined(_WINDOWS) && !defined(WINDOWS)
  77591. # define WINDOWS
  77592. #endif
  77593. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  77594. # ifndef WIN32
  77595. # define WIN32
  77596. # endif
  77597. #endif
  77598. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  77599. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  77600. # ifndef SYS16BIT
  77601. # define SYS16BIT
  77602. # endif
  77603. # endif
  77604. #endif
  77605. /*
  77606. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  77607. * than 64k bytes at a time (needed on systems with 16-bit int).
  77608. */
  77609. #ifdef SYS16BIT
  77610. # define MAXSEG_64K
  77611. #endif
  77612. #ifdef MSDOS
  77613. # define UNALIGNED_OK
  77614. #endif
  77615. #ifdef __STDC_VERSION__
  77616. # ifndef STDC
  77617. # define STDC
  77618. # endif
  77619. # if __STDC_VERSION__ >= 199901L
  77620. # ifndef STDC99
  77621. # define STDC99
  77622. # endif
  77623. # endif
  77624. #endif
  77625. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  77626. # define STDC
  77627. #endif
  77628. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  77629. # define STDC
  77630. #endif
  77631. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  77632. # define STDC
  77633. #endif
  77634. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  77635. # define STDC
  77636. #endif
  77637. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  77638. # define STDC
  77639. #endif
  77640. #ifndef STDC
  77641. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  77642. # define const /* note: need a more gentle solution here */
  77643. # endif
  77644. #endif
  77645. /* Some Mac compilers merge all .h files incorrectly: */
  77646. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  77647. # define NO_DUMMY_DECL
  77648. #endif
  77649. /* Maximum value for memLevel in deflateInit2 */
  77650. #ifndef MAX_MEM_LEVEL
  77651. # ifdef MAXSEG_64K
  77652. # define MAX_MEM_LEVEL 8
  77653. # else
  77654. # define MAX_MEM_LEVEL 9
  77655. # endif
  77656. #endif
  77657. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  77658. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  77659. * created by gzip. (Files created by minigzip can still be extracted by
  77660. * gzip.)
  77661. */
  77662. #ifndef MAX_WBITS
  77663. # define MAX_WBITS 15 /* 32K LZ77 window */
  77664. #endif
  77665. /* The memory requirements for deflate are (in bytes):
  77666. (1 << (windowBits+2)) + (1 << (memLevel+9))
  77667. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  77668. plus a few kilobytes for small objects. For example, if you want to reduce
  77669. the default memory requirements from 256K to 128K, compile with
  77670. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  77671. Of course this will generally degrade compression (there's no free lunch).
  77672. The memory requirements for inflate are (in bytes) 1 << windowBits
  77673. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  77674. for small objects.
  77675. */
  77676. /* Type declarations */
  77677. #ifndef OF /* function prototypes */
  77678. # ifdef STDC
  77679. # define OF(args) args
  77680. # else
  77681. # define OF(args) ()
  77682. # endif
  77683. #endif
  77684. /* The following definitions for FAR are needed only for MSDOS mixed
  77685. * model programming (small or medium model with some far allocations).
  77686. * This was tested only with MSC; for other MSDOS compilers you may have
  77687. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  77688. * just define FAR to be empty.
  77689. */
  77690. #ifdef SYS16BIT
  77691. # if defined(M_I86SM) || defined(M_I86MM)
  77692. /* MSC small or medium model */
  77693. # define SMALL_MEDIUM
  77694. # ifdef _MSC_VER
  77695. # define FAR _far
  77696. # else
  77697. # define FAR far
  77698. # endif
  77699. # endif
  77700. # if (defined(__SMALL__) || defined(__MEDIUM__))
  77701. /* Turbo C small or medium model */
  77702. # define SMALL_MEDIUM
  77703. # ifdef __BORLANDC__
  77704. # define FAR _far
  77705. # else
  77706. # define FAR far
  77707. # endif
  77708. # endif
  77709. #endif
  77710. #if defined(WINDOWS) || defined(WIN32)
  77711. /* If building or using zlib as a DLL, define ZLIB_DLL.
  77712. * This is not mandatory, but it offers a little performance increase.
  77713. */
  77714. # ifdef ZLIB_DLL
  77715. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  77716. # ifdef ZLIB_INTERNAL
  77717. # define ZEXTERN extern __declspec(dllexport)
  77718. # else
  77719. # define ZEXTERN extern __declspec(dllimport)
  77720. # endif
  77721. # endif
  77722. # endif /* ZLIB_DLL */
  77723. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  77724. * define ZLIB_WINAPI.
  77725. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  77726. */
  77727. # ifdef ZLIB_WINAPI
  77728. # ifdef FAR
  77729. # undef FAR
  77730. # endif
  77731. # include <windows.h>
  77732. /* No need for _export, use ZLIB.DEF instead. */
  77733. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  77734. # define ZEXPORT WINAPI
  77735. # ifdef WIN32
  77736. # define ZEXPORTVA WINAPIV
  77737. # else
  77738. # define ZEXPORTVA FAR CDECL
  77739. # endif
  77740. # endif
  77741. #endif
  77742. #if defined (__BEOS__)
  77743. # ifdef ZLIB_DLL
  77744. # ifdef ZLIB_INTERNAL
  77745. # define ZEXPORT __declspec(dllexport)
  77746. # define ZEXPORTVA __declspec(dllexport)
  77747. # else
  77748. # define ZEXPORT __declspec(dllimport)
  77749. # define ZEXPORTVA __declspec(dllimport)
  77750. # endif
  77751. # endif
  77752. #endif
  77753. #ifndef ZEXTERN
  77754. # define ZEXTERN extern
  77755. #endif
  77756. #ifndef ZEXPORT
  77757. # define ZEXPORT
  77758. #endif
  77759. #ifndef ZEXPORTVA
  77760. # define ZEXPORTVA
  77761. #endif
  77762. #ifndef FAR
  77763. # define FAR
  77764. #endif
  77765. #if !defined(__MACTYPES__)
  77766. typedef unsigned char Byte; /* 8 bits */
  77767. #endif
  77768. typedef unsigned int uInt; /* 16 bits or more */
  77769. typedef unsigned long uLong; /* 32 bits or more */
  77770. #ifdef SMALL_MEDIUM
  77771. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  77772. # define Bytef Byte FAR
  77773. #else
  77774. typedef Byte FAR Bytef;
  77775. #endif
  77776. typedef char FAR charf;
  77777. typedef int FAR intf;
  77778. typedef uInt FAR uIntf;
  77779. typedef uLong FAR uLongf;
  77780. #ifdef STDC
  77781. typedef void const *voidpc;
  77782. typedef void FAR *voidpf;
  77783. typedef void *voidp;
  77784. #else
  77785. typedef Byte const *voidpc;
  77786. typedef Byte FAR *voidpf;
  77787. typedef Byte *voidp;
  77788. #endif
  77789. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  77790. # include <sys/types.h> /* for off_t */
  77791. # include <unistd.h> /* for SEEK_* and off_t */
  77792. # ifdef VMS
  77793. # include <unixio.h> /* for off_t */
  77794. # endif
  77795. # define z_off_t off_t
  77796. #endif
  77797. #ifndef SEEK_SET
  77798. # define SEEK_SET 0 /* Seek from beginning of file. */
  77799. # define SEEK_CUR 1 /* Seek from current position. */
  77800. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  77801. #endif
  77802. #ifndef z_off_t
  77803. # define z_off_t long
  77804. #endif
  77805. #if defined(__OS400__)
  77806. # define NO_vsnprintf
  77807. #endif
  77808. #if defined(__MVS__)
  77809. # define NO_vsnprintf
  77810. # ifdef FAR
  77811. # undef FAR
  77812. # endif
  77813. #endif
  77814. /* MVS linker does not support external names larger than 8 bytes */
  77815. #if defined(__MVS__)
  77816. # pragma map(deflateInit_,"DEIN")
  77817. # pragma map(deflateInit2_,"DEIN2")
  77818. # pragma map(deflateEnd,"DEEND")
  77819. # pragma map(deflateBound,"DEBND")
  77820. # pragma map(inflateInit_,"ININ")
  77821. # pragma map(inflateInit2_,"ININ2")
  77822. # pragma map(inflateEnd,"INEND")
  77823. # pragma map(inflateSync,"INSY")
  77824. # pragma map(inflateSetDictionary,"INSEDI")
  77825. # pragma map(compressBound,"CMBND")
  77826. # pragma map(inflate_table,"INTABL")
  77827. # pragma map(inflate_fast,"INFA")
  77828. # pragma map(inflate_copyright,"INCOPY")
  77829. #endif
  77830. #endif /* ZCONF_H */
  77831. /*** End of inlined file: zconf.h ***/
  77832. #ifdef __cplusplus
  77833. extern "C" {
  77834. #endif
  77835. #define ZLIB_VERSION "1.2.3"
  77836. #define ZLIB_VERNUM 0x1230
  77837. /*
  77838. The 'zlib' compression library provides in-memory compression and
  77839. decompression functions, including integrity checks of the uncompressed
  77840. data. This version of the library supports only one compression method
  77841. (deflation) but other algorithms will be added later and will have the same
  77842. stream interface.
  77843. Compression can be done in a single step if the buffers are large
  77844. enough (for example if an input file is mmap'ed), or can be done by
  77845. repeated calls of the compression function. In the latter case, the
  77846. application must provide more input and/or consume the output
  77847. (providing more output space) before each call.
  77848. The compressed data format used by default by the in-memory functions is
  77849. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  77850. around a deflate stream, which is itself documented in RFC 1951.
  77851. The library also supports reading and writing files in gzip (.gz) format
  77852. with an interface similar to that of stdio using the functions that start
  77853. with "gz". The gzip format is different from the zlib format. gzip is a
  77854. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  77855. This library can optionally read and write gzip streams in memory as well.
  77856. The zlib format was designed to be compact and fast for use in memory
  77857. and on communications channels. The gzip format was designed for single-
  77858. file compression on file systems, has a larger header than zlib to maintain
  77859. directory information, and uses a different, slower check method than zlib.
  77860. The library does not install any signal handler. The decoder checks
  77861. the consistency of the compressed data, so the library should never
  77862. crash even in case of corrupted input.
  77863. */
  77864. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  77865. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  77866. struct internal_state;
  77867. typedef struct z_stream_s {
  77868. Bytef *next_in; /* next input byte */
  77869. uInt avail_in; /* number of bytes available at next_in */
  77870. uLong total_in; /* total nb of input bytes read so far */
  77871. Bytef *next_out; /* next output byte should be put there */
  77872. uInt avail_out; /* remaining free space at next_out */
  77873. uLong total_out; /* total nb of bytes output so far */
  77874. char *msg; /* last error message, NULL if no error */
  77875. struct internal_state FAR *state; /* not visible by applications */
  77876. alloc_func zalloc; /* used to allocate the internal state */
  77877. free_func zfree; /* used to free the internal state */
  77878. voidpf opaque; /* private data object passed to zalloc and zfree */
  77879. int data_type; /* best guess about the data type: binary or text */
  77880. uLong adler; /* adler32 value of the uncompressed data */
  77881. uLong reserved; /* reserved for future use */
  77882. } z_stream;
  77883. typedef z_stream FAR *z_streamp;
  77884. /*
  77885. gzip header information passed to and from zlib routines. See RFC 1952
  77886. for more details on the meanings of these fields.
  77887. */
  77888. typedef struct gz_header_s {
  77889. int text; /* true if compressed data believed to be text */
  77890. uLong time; /* modification time */
  77891. int xflags; /* extra flags (not used when writing a gzip file) */
  77892. int os; /* operating system */
  77893. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  77894. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  77895. uInt extra_max; /* space at extra (only when reading header) */
  77896. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  77897. uInt name_max; /* space at name (only when reading header) */
  77898. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  77899. uInt comm_max; /* space at comment (only when reading header) */
  77900. int hcrc; /* true if there was or will be a header crc */
  77901. int done; /* true when done reading gzip header (not used
  77902. when writing a gzip file) */
  77903. } gz_header;
  77904. typedef gz_header FAR *gz_headerp;
  77905. /*
  77906. The application must update next_in and avail_in when avail_in has
  77907. dropped to zero. It must update next_out and avail_out when avail_out
  77908. has dropped to zero. The application must initialize zalloc, zfree and
  77909. opaque before calling the init function. All other fields are set by the
  77910. compression library and must not be updated by the application.
  77911. The opaque value provided by the application will be passed as the first
  77912. parameter for calls of zalloc and zfree. This can be useful for custom
  77913. memory management. The compression library attaches no meaning to the
  77914. opaque value.
  77915. zalloc must return Z_NULL if there is not enough memory for the object.
  77916. If zlib is used in a multi-threaded application, zalloc and zfree must be
  77917. thread safe.
  77918. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  77919. exactly 65536 bytes, but will not be required to allocate more than this
  77920. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  77921. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  77922. have their offset normalized to zero. The default allocation function
  77923. provided by this library ensures this (see zutil.c). To reduce memory
  77924. requirements and avoid any allocation of 64K objects, at the expense of
  77925. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  77926. The fields total_in and total_out can be used for statistics or
  77927. progress reports. After compression, total_in holds the total size of
  77928. the uncompressed data and may be saved for use in the decompressor
  77929. (particularly if the decompressor wants to decompress everything in
  77930. a single step).
  77931. */
  77932. /* constants */
  77933. #define Z_NO_FLUSH 0
  77934. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  77935. #define Z_SYNC_FLUSH 2
  77936. #define Z_FULL_FLUSH 3
  77937. #define Z_FINISH 4
  77938. #define Z_BLOCK 5
  77939. /* Allowed flush values; see deflate() and inflate() below for details */
  77940. #define Z_OK 0
  77941. #define Z_STREAM_END 1
  77942. #define Z_NEED_DICT 2
  77943. #define Z_ERRNO (-1)
  77944. #define Z_STREAM_ERROR (-2)
  77945. #define Z_DATA_ERROR (-3)
  77946. #define Z_MEM_ERROR (-4)
  77947. #define Z_BUF_ERROR (-5)
  77948. #define Z_VERSION_ERROR (-6)
  77949. /* Return codes for the compression/decompression functions. Negative
  77950. * values are errors, positive values are used for special but normal events.
  77951. */
  77952. #define Z_NO_COMPRESSION 0
  77953. #define Z_BEST_SPEED 1
  77954. #define Z_BEST_COMPRESSION 9
  77955. #define Z_DEFAULT_COMPRESSION (-1)
  77956. /* compression levels */
  77957. #define Z_FILTERED 1
  77958. #define Z_HUFFMAN_ONLY 2
  77959. #define Z_RLE 3
  77960. #define Z_FIXED 4
  77961. #define Z_DEFAULT_STRATEGY 0
  77962. /* compression strategy; see deflateInit2() below for details */
  77963. #define Z_BINARY 0
  77964. #define Z_TEXT 1
  77965. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  77966. #define Z_UNKNOWN 2
  77967. /* Possible values of the data_type field (though see inflate()) */
  77968. #define Z_DEFLATED 8
  77969. /* The deflate compression method (the only one supported in this version) */
  77970. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  77971. #define zlib_version zlibVersion()
  77972. /* for compatibility with versions < 1.0.2 */
  77973. /* basic functions */
  77974. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  77975. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  77976. If the first character differs, the library code actually used is
  77977. not compatible with the zlib.h header file used by the application.
  77978. This check is automatically made by deflateInit and inflateInit.
  77979. */
  77980. /*
  77981. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  77982. Initializes the internal stream state for compression. The fields
  77983. zalloc, zfree and opaque must be initialized before by the caller.
  77984. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  77985. use default allocation functions.
  77986. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  77987. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  77988. all (the input data is simply copied a block at a time).
  77989. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  77990. compression (currently equivalent to level 6).
  77991. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  77992. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  77993. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  77994. with the version assumed by the caller (ZLIB_VERSION).
  77995. msg is set to null if there is no error message. deflateInit does not
  77996. perform any compression: this will be done by deflate().
  77997. */
  77998. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  77999. /*
  78000. deflate compresses as much data as possible, and stops when the input
  78001. buffer becomes empty or the output buffer becomes full. It may introduce some
  78002. output latency (reading input without producing any output) except when
  78003. forced to flush.
  78004. The detailed semantics are as follows. deflate performs one or both of the
  78005. following actions:
  78006. - Compress more input starting at next_in and update next_in and avail_in
  78007. accordingly. If not all input can be processed (because there is not
  78008. enough room in the output buffer), next_in and avail_in are updated and
  78009. processing will resume at this point for the next call of deflate().
  78010. - Provide more output starting at next_out and update next_out and avail_out
  78011. accordingly. This action is forced if the parameter flush is non zero.
  78012. Forcing flush frequently degrades the compression ratio, so this parameter
  78013. should be set only when necessary (in interactive applications).
  78014. Some output may be provided even if flush is not set.
  78015. Before the call of deflate(), the application should ensure that at least
  78016. one of the actions is possible, by providing more input and/or consuming
  78017. more output, and updating avail_in or avail_out accordingly; avail_out
  78018. should never be zero before the call. The application can consume the
  78019. compressed output when it wants, for example when the output buffer is full
  78020. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78021. and with zero avail_out, it must be called again after making room in the
  78022. output buffer because there might be more output pending.
  78023. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78024. decide how much data to accumualte before producing output, in order to
  78025. maximize compression.
  78026. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78027. flushed to the output buffer and the output is aligned on a byte boundary, so
  78028. that the decompressor can get all input data available so far. (In particular
  78029. avail_in is zero after the call if enough output space has been provided
  78030. before the call.) Flushing may degrade compression for some compression
  78031. algorithms and so it should be used only when necessary.
  78032. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78033. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78034. restart from this point if previous compressed data has been damaged or if
  78035. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78036. compression.
  78037. If deflate returns with avail_out == 0, this function must be called again
  78038. with the same value of the flush parameter and more output space (updated
  78039. avail_out), until the flush is complete (deflate returns with non-zero
  78040. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78041. avail_out is greater than six to avoid repeated flush markers due to
  78042. avail_out == 0 on return.
  78043. If the parameter flush is set to Z_FINISH, pending input is processed,
  78044. pending output is flushed and deflate returns with Z_STREAM_END if there
  78045. was enough output space; if deflate returns with Z_OK, this function must be
  78046. called again with Z_FINISH and more output space (updated avail_out) but no
  78047. more input data, until it returns with Z_STREAM_END or an error. After
  78048. deflate has returned Z_STREAM_END, the only possible operations on the
  78049. stream are deflateReset or deflateEnd.
  78050. Z_FINISH can be used immediately after deflateInit if all the compression
  78051. is to be done in a single step. In this case, avail_out must be at least
  78052. the value returned by deflateBound (see below). If deflate does not return
  78053. Z_STREAM_END, then it must be called again as described above.
  78054. deflate() sets strm->adler to the adler32 checksum of all input read
  78055. so far (that is, total_in bytes).
  78056. deflate() may update strm->data_type if it can make a good guess about
  78057. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78058. binary. This field is only for information purposes and does not affect
  78059. the compression algorithm in any manner.
  78060. deflate() returns Z_OK if some progress has been made (more input
  78061. processed or more output produced), Z_STREAM_END if all input has been
  78062. consumed and all output has been produced (only when flush is set to
  78063. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78064. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78065. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78066. fatal, and deflate() can be called again with more input and more output
  78067. space to continue compressing.
  78068. */
  78069. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78070. /*
  78071. All dynamically allocated data structures for this stream are freed.
  78072. This function discards any unprocessed input and does not flush any
  78073. pending output.
  78074. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78075. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78076. prematurely (some input or output was discarded). In the error case,
  78077. msg may be set but then points to a static string (which must not be
  78078. deallocated).
  78079. */
  78080. /*
  78081. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78082. Initializes the internal stream state for decompression. The fields
  78083. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78084. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78085. value depends on the compression method), inflateInit determines the
  78086. compression method from the zlib header and allocates all data structures
  78087. accordingly; otherwise the allocation will be deferred to the first call of
  78088. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78089. use default allocation functions.
  78090. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78091. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78092. version assumed by the caller. msg is set to null if there is no error
  78093. message. inflateInit does not perform any decompression apart from reading
  78094. the zlib header if present: this will be done by inflate(). (So next_in and
  78095. avail_in may be modified, but next_out and avail_out are unchanged.)
  78096. */
  78097. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78098. /*
  78099. inflate decompresses as much data as possible, and stops when the input
  78100. buffer becomes empty or the output buffer becomes full. It may introduce
  78101. some output latency (reading input without producing any output) except when
  78102. forced to flush.
  78103. The detailed semantics are as follows. inflate performs one or both of the
  78104. following actions:
  78105. - Decompress more input starting at next_in and update next_in and avail_in
  78106. accordingly. If not all input can be processed (because there is not
  78107. enough room in the output buffer), next_in is updated and processing
  78108. will resume at this point for the next call of inflate().
  78109. - Provide more output starting at next_out and update next_out and avail_out
  78110. accordingly. inflate() provides as much output as possible, until there
  78111. is no more input data or no more space in the output buffer (see below
  78112. about the flush parameter).
  78113. Before the call of inflate(), the application should ensure that at least
  78114. one of the actions is possible, by providing more input and/or consuming
  78115. more output, and updating the next_* and avail_* values accordingly.
  78116. The application can consume the uncompressed output when it wants, for
  78117. example when the output buffer is full (avail_out == 0), or after each
  78118. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78119. must be called again after making room in the output buffer because there
  78120. might be more output pending.
  78121. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78122. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78123. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78124. if and when it gets to the next deflate block boundary. When decoding the
  78125. zlib or gzip format, this will cause inflate() to return immediately after
  78126. the header and before the first block. When doing a raw inflate, inflate()
  78127. will go ahead and process the first block, and will return when it gets to
  78128. the end of that block, or when it runs out of data.
  78129. The Z_BLOCK option assists in appending to or combining deflate streams.
  78130. Also to assist in this, on return inflate() will set strm->data_type to the
  78131. number of unused bits in the last byte taken from strm->next_in, plus 64
  78132. if inflate() is currently decoding the last block in the deflate stream,
  78133. plus 128 if inflate() returned immediately after decoding an end-of-block
  78134. code or decoding the complete header up to just before the first byte of the
  78135. deflate stream. The end-of-block will not be indicated until all of the
  78136. uncompressed data from that block has been written to strm->next_out. The
  78137. number of unused bits may in general be greater than seven, except when
  78138. bit 7 of data_type is set, in which case the number of unused bits will be
  78139. less than eight.
  78140. inflate() should normally be called until it returns Z_STREAM_END or an
  78141. error. However if all decompression is to be performed in a single step
  78142. (a single call of inflate), the parameter flush should be set to
  78143. Z_FINISH. In this case all pending input is processed and all pending
  78144. output is flushed; avail_out must be large enough to hold all the
  78145. uncompressed data. (The size of the uncompressed data may have been saved
  78146. by the compressor for this purpose.) The next operation on this stream must
  78147. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78148. is never required, but can be used to inform inflate that a faster approach
  78149. may be used for the single inflate() call.
  78150. In this implementation, inflate() always flushes as much output as
  78151. possible to the output buffer, and always uses the faster approach on the
  78152. first call. So the only effect of the flush parameter in this implementation
  78153. is on the return value of inflate(), as noted below, or when it returns early
  78154. because Z_BLOCK is used.
  78155. If a preset dictionary is needed after this call (see inflateSetDictionary
  78156. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78157. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78158. strm->adler to the adler32 checksum of all output produced so far (that is,
  78159. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78160. below. At the end of the stream, inflate() checks that its computed adler32
  78161. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78162. only if the checksum is correct.
  78163. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78164. deflate data. The header type is detected automatically. Any information
  78165. contained in the gzip header is not retained, so applications that need that
  78166. information should instead use raw inflate, see inflateInit2() below, or
  78167. inflateBack() and perform their own processing of the gzip header and
  78168. trailer.
  78169. inflate() returns Z_OK if some progress has been made (more input processed
  78170. or more output produced), Z_STREAM_END if the end of the compressed data has
  78171. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78172. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78173. corrupted (input stream not conforming to the zlib format or incorrect check
  78174. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78175. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78176. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78177. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78178. inflate() can be called again with more input and more output space to
  78179. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78180. call inflateSync() to look for a good compression block if a partial recovery
  78181. of the data is desired.
  78182. */
  78183. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78184. /*
  78185. All dynamically allocated data structures for this stream are freed.
  78186. This function discards any unprocessed input and does not flush any
  78187. pending output.
  78188. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78189. was inconsistent. In the error case, msg may be set but then points to a
  78190. static string (which must not be deallocated).
  78191. */
  78192. /* Advanced functions */
  78193. /*
  78194. The following functions are needed only in some special applications.
  78195. */
  78196. /*
  78197. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78198. int level,
  78199. int method,
  78200. int windowBits,
  78201. int memLevel,
  78202. int strategy));
  78203. This is another version of deflateInit with more compression options. The
  78204. fields next_in, zalloc, zfree and opaque must be initialized before by
  78205. the caller.
  78206. The method parameter is the compression method. It must be Z_DEFLATED in
  78207. this version of the library.
  78208. The windowBits parameter is the base two logarithm of the window size
  78209. (the size of the history buffer). It should be in the range 8..15 for this
  78210. version of the library. Larger values of this parameter result in better
  78211. compression at the expense of memory usage. The default value is 15 if
  78212. deflateInit is used instead.
  78213. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78214. determines the window size. deflate() will then generate raw deflate data
  78215. with no zlib header or trailer, and will not compute an adler32 check value.
  78216. windowBits can also be greater than 15 for optional gzip encoding. Add
  78217. 16 to windowBits to write a simple gzip header and trailer around the
  78218. compressed data instead of a zlib wrapper. The gzip header will have no
  78219. file name, no extra data, no comment, no modification time (set to zero),
  78220. no header crc, and the operating system will be set to 255 (unknown). If a
  78221. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78222. The memLevel parameter specifies how much memory should be allocated
  78223. for the internal compression state. memLevel=1 uses minimum memory but
  78224. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78225. for optimal speed. The default value is 8. See zconf.h for total memory
  78226. usage as a function of windowBits and memLevel.
  78227. The strategy parameter is used to tune the compression algorithm. Use the
  78228. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78229. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78230. string match), or Z_RLE to limit match distances to one (run-length
  78231. encoding). Filtered data consists mostly of small values with a somewhat
  78232. random distribution. In this case, the compression algorithm is tuned to
  78233. compress them better. The effect of Z_FILTERED is to force more Huffman
  78234. coding and less string matching; it is somewhat intermediate between
  78235. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78236. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78237. parameter only affects the compression ratio but not the correctness of the
  78238. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78239. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78240. applications.
  78241. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78242. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  78243. method). msg is set to null if there is no error message. deflateInit2 does
  78244. not perform any compression: this will be done by deflate().
  78245. */
  78246. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  78247. const Bytef *dictionary,
  78248. uInt dictLength));
  78249. /*
  78250. Initializes the compression dictionary from the given byte sequence
  78251. without producing any compressed output. This function must be called
  78252. immediately after deflateInit, deflateInit2 or deflateReset, before any
  78253. call of deflate. The compressor and decompressor must use exactly the same
  78254. dictionary (see inflateSetDictionary).
  78255. The dictionary should consist of strings (byte sequences) that are likely
  78256. to be encountered later in the data to be compressed, with the most commonly
  78257. used strings preferably put towards the end of the dictionary. Using a
  78258. dictionary is most useful when the data to be compressed is short and can be
  78259. predicted with good accuracy; the data can then be compressed better than
  78260. with the default empty dictionary.
  78261. Depending on the size of the compression data structures selected by
  78262. deflateInit or deflateInit2, a part of the dictionary may in effect be
  78263. discarded, for example if the dictionary is larger than the window size in
  78264. deflate or deflate2. Thus the strings most likely to be useful should be
  78265. put at the end of the dictionary, not at the front. In addition, the
  78266. current implementation of deflate will use at most the window size minus
  78267. 262 bytes of the provided dictionary.
  78268. Upon return of this function, strm->adler is set to the adler32 value
  78269. of the dictionary; the decompressor may later use this value to determine
  78270. which dictionary has been used by the compressor. (The adler32 value
  78271. applies to the whole dictionary even if only a subset of the dictionary is
  78272. actually used by the compressor.) If a raw deflate was requested, then the
  78273. adler32 value is not computed and strm->adler is not set.
  78274. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  78275. parameter is invalid (such as NULL dictionary) or the stream state is
  78276. inconsistent (for example if deflate has already been called for this stream
  78277. or if the compression method is bsort). deflateSetDictionary does not
  78278. perform any compression: this will be done by deflate().
  78279. */
  78280. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  78281. z_streamp source));
  78282. /*
  78283. Sets the destination stream as a complete copy of the source stream.
  78284. This function can be useful when several compression strategies will be
  78285. tried, for example when there are several ways of pre-processing the input
  78286. data with a filter. The streams that will be discarded should then be freed
  78287. by calling deflateEnd. Note that deflateCopy duplicates the internal
  78288. compression state which can be quite large, so this strategy is slow and
  78289. can consume lots of memory.
  78290. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78291. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78292. (such as zalloc being NULL). msg is left unchanged in both source and
  78293. destination.
  78294. */
  78295. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  78296. /*
  78297. This function is equivalent to deflateEnd followed by deflateInit,
  78298. but does not free and reallocate all the internal compression state.
  78299. The stream will keep the same compression level and any other attributes
  78300. that may have been set by deflateInit2.
  78301. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78302. stream state was inconsistent (such as zalloc or state being NULL).
  78303. */
  78304. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78305. int level,
  78306. int strategy));
  78307. /*
  78308. Dynamically update the compression level and compression strategy. The
  78309. interpretation of level and strategy is as in deflateInit2. This can be
  78310. used to switch between compression and straight copy of the input data, or
  78311. to switch to a different kind of input data requiring a different
  78312. strategy. If the compression level is changed, the input available so far
  78313. is compressed with the old level (and may be flushed); the new level will
  78314. take effect only at the next call of deflate().
  78315. Before the call of deflateParams, the stream state must be set as for
  78316. a call of deflate(), since the currently available input may have to
  78317. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78318. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78319. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78320. if strm->avail_out was zero.
  78321. */
  78322. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78323. int good_length,
  78324. int max_lazy,
  78325. int nice_length,
  78326. int max_chain));
  78327. /*
  78328. Fine tune deflate's internal compression parameters. This should only be
  78329. used by someone who understands the algorithm used by zlib's deflate for
  78330. searching for the best matching string, and even then only by the most
  78331. fanatic optimizer trying to squeeze out the last compressed bit for their
  78332. specific input data. Read the deflate.c source code for the meaning of the
  78333. max_lazy, good_length, nice_length, and max_chain parameters.
  78334. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78335. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78336. */
  78337. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78338. uLong sourceLen));
  78339. /*
  78340. deflateBound() returns an upper bound on the compressed size after
  78341. deflation of sourceLen bytes. It must be called after deflateInit()
  78342. or deflateInit2(). This would be used to allocate an output buffer
  78343. for deflation in a single pass, and so would be called before deflate().
  78344. */
  78345. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78346. int bits,
  78347. int value));
  78348. /*
  78349. deflatePrime() inserts bits in the deflate output stream. The intent
  78350. is that this function is used to start off the deflate output with the
  78351. bits leftover from a previous deflate stream when appending to it. As such,
  78352. this function can only be used for raw deflate, and must be used before the
  78353. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78354. less than or equal to 16, and that many of the least significant bits of
  78355. value will be inserted in the output.
  78356. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78357. stream state was inconsistent.
  78358. */
  78359. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  78360. gz_headerp head));
  78361. /*
  78362. deflateSetHeader() provides gzip header information for when a gzip
  78363. stream is requested by deflateInit2(). deflateSetHeader() may be called
  78364. after deflateInit2() or deflateReset() and before the first call of
  78365. deflate(). The text, time, os, extra field, name, and comment information
  78366. in the provided gz_header structure are written to the gzip header (xflag is
  78367. ignored -- the extra flags are set according to the compression level). The
  78368. caller must assure that, if not Z_NULL, name and comment are terminated with
  78369. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  78370. available there. If hcrc is true, a gzip header crc is included. Note that
  78371. the current versions of the command-line version of gzip (up through version
  78372. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  78373. gzip file" and give up.
  78374. If deflateSetHeader is not used, the default gzip header has text false,
  78375. the time set to zero, and os set to 255, with no extra, name, or comment
  78376. fields. The gzip header is returned to the default state by deflateReset().
  78377. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78378. stream state was inconsistent.
  78379. */
  78380. /*
  78381. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  78382. int windowBits));
  78383. This is another version of inflateInit with an extra parameter. The
  78384. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  78385. before by the caller.
  78386. The windowBits parameter is the base two logarithm of the maximum window
  78387. size (the size of the history buffer). It should be in the range 8..15 for
  78388. this version of the library. The default value is 15 if inflateInit is used
  78389. instead. windowBits must be greater than or equal to the windowBits value
  78390. provided to deflateInit2() while compressing, or it must be equal to 15 if
  78391. deflateInit2() was not used. If a compressed stream with a larger window
  78392. size is given as input, inflate() will return with the error code
  78393. Z_DATA_ERROR instead of trying to allocate a larger window.
  78394. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  78395. determines the window size. inflate() will then process raw deflate data,
  78396. not looking for a zlib or gzip header, not generating a check value, and not
  78397. looking for any check values for comparison at the end of the stream. This
  78398. is for use with other formats that use the deflate compressed data format
  78399. such as zip. Those formats provide their own check values. If a custom
  78400. format is developed using the raw deflate format for compressed data, it is
  78401. recommended that a check value such as an adler32 or a crc32 be applied to
  78402. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  78403. most applications, the zlib format should be used as is. Note that comments
  78404. above on the use in deflateInit2() applies to the magnitude of windowBits.
  78405. windowBits can also be greater than 15 for optional gzip decoding. Add
  78406. 32 to windowBits to enable zlib and gzip decoding with automatic header
  78407. detection, or add 16 to decode only the gzip format (the zlib format will
  78408. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  78409. a crc32 instead of an adler32.
  78410. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78411. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  78412. is set to null if there is no error message. inflateInit2 does not perform
  78413. any decompression apart from reading the zlib header if present: this will
  78414. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  78415. and avail_out are unchanged.)
  78416. */
  78417. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  78418. const Bytef *dictionary,
  78419. uInt dictLength));
  78420. /*
  78421. Initializes the decompression dictionary from the given uncompressed byte
  78422. sequence. This function must be called immediately after a call of inflate,
  78423. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  78424. can be determined from the adler32 value returned by that call of inflate.
  78425. The compressor and decompressor must use exactly the same dictionary (see
  78426. deflateSetDictionary). For raw inflate, this function can be called
  78427. immediately after inflateInit2() or inflateReset() and before any call of
  78428. inflate() to set the dictionary. The application must insure that the
  78429. dictionary that was used for compression is provided.
  78430. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  78431. parameter is invalid (such as NULL dictionary) or the stream state is
  78432. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  78433. expected one (incorrect adler32 value). inflateSetDictionary does not
  78434. perform any decompression: this will be done by subsequent calls of
  78435. inflate().
  78436. */
  78437. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  78438. /*
  78439. Skips invalid compressed data until a full flush point (see above the
  78440. description of deflate with Z_FULL_FLUSH) can be found, or until all
  78441. available input is skipped. No output is provided.
  78442. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  78443. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  78444. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  78445. case, the application may save the current current value of total_in which
  78446. indicates where valid compressed data was found. In the error case, the
  78447. application may repeatedly call inflateSync, providing more input each time,
  78448. until success or end of the input data.
  78449. */
  78450. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  78451. z_streamp source));
  78452. /*
  78453. Sets the destination stream as a complete copy of the source stream.
  78454. This function can be useful when randomly accessing a large stream. The
  78455. first pass through the stream can periodically record the inflate state,
  78456. allowing restarting inflate at those points when randomly accessing the
  78457. stream.
  78458. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78459. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78460. (such as zalloc being NULL). msg is left unchanged in both source and
  78461. destination.
  78462. */
  78463. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  78464. /*
  78465. This function is equivalent to inflateEnd followed by inflateInit,
  78466. but does not free and reallocate all the internal decompression state.
  78467. The stream will keep attributes that may have been set by inflateInit2.
  78468. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78469. stream state was inconsistent (such as zalloc or state being NULL).
  78470. */
  78471. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  78472. int bits,
  78473. int value));
  78474. /*
  78475. This function inserts bits in the inflate input stream. The intent is
  78476. that this function is used to start inflating at a bit position in the
  78477. middle of a byte. The provided bits will be used before any bytes are used
  78478. from next_in. This function should only be used with raw inflate, and
  78479. should be used before the first inflate() call after inflateInit2() or
  78480. inflateReset(). bits must be less than or equal to 16, and that many of the
  78481. least significant bits of value will be inserted in the input.
  78482. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78483. stream state was inconsistent.
  78484. */
  78485. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  78486. gz_headerp head));
  78487. /*
  78488. inflateGetHeader() requests that gzip header information be stored in the
  78489. provided gz_header structure. inflateGetHeader() may be called after
  78490. inflateInit2() or inflateReset(), and before the first call of inflate().
  78491. As inflate() processes the gzip stream, head->done is zero until the header
  78492. is completed, at which time head->done is set to one. If a zlib stream is
  78493. being decoded, then head->done is set to -1 to indicate that there will be
  78494. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  78495. force inflate() to return immediately after header processing is complete
  78496. and before any actual data is decompressed.
  78497. The text, time, xflags, and os fields are filled in with the gzip header
  78498. contents. hcrc is set to true if there is a header CRC. (The header CRC
  78499. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  78500. contains the maximum number of bytes to write to extra. Once done is true,
  78501. extra_len contains the actual extra field length, and extra contains the
  78502. extra field, or that field truncated if extra_max is less than extra_len.
  78503. If name is not Z_NULL, then up to name_max characters are written there,
  78504. terminated with a zero unless the length is greater than name_max. If
  78505. comment is not Z_NULL, then up to comm_max characters are written there,
  78506. terminated with a zero unless the length is greater than comm_max. When
  78507. any of extra, name, or comment are not Z_NULL and the respective field is
  78508. not present in the header, then that field is set to Z_NULL to signal its
  78509. absence. This allows the use of deflateSetHeader() with the returned
  78510. structure to duplicate the header. However if those fields are set to
  78511. allocated memory, then the application will need to save those pointers
  78512. elsewhere so that they can be eventually freed.
  78513. If inflateGetHeader is not used, then the header information is simply
  78514. discarded. The header is always checked for validity, including the header
  78515. CRC if present. inflateReset() will reset the process to discard the header
  78516. information. The application would need to call inflateGetHeader() again to
  78517. retrieve the header from the next gzip stream.
  78518. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78519. stream state was inconsistent.
  78520. */
  78521. /*
  78522. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  78523. unsigned char FAR *window));
  78524. Initialize the internal stream state for decompression using inflateBack()
  78525. calls. The fields zalloc, zfree and opaque in strm must be initialized
  78526. before the call. If zalloc and zfree are Z_NULL, then the default library-
  78527. derived memory allocation routines are used. windowBits is the base two
  78528. logarithm of the window size, in the range 8..15. window is a caller
  78529. supplied buffer of that size. Except for special applications where it is
  78530. assured that deflate was used with small window sizes, windowBits must be 15
  78531. and a 32K byte window must be supplied to be able to decompress general
  78532. deflate streams.
  78533. See inflateBack() for the usage of these routines.
  78534. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  78535. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  78536. be allocated, or Z_VERSION_ERROR if the version of the library does not
  78537. match the version of the header file.
  78538. */
  78539. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  78540. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  78541. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  78542. in_func in, void FAR *in_desc,
  78543. out_func out, void FAR *out_desc));
  78544. /*
  78545. inflateBack() does a raw inflate with a single call using a call-back
  78546. interface for input and output. This is more efficient than inflate() for
  78547. file i/o applications in that it avoids copying between the output and the
  78548. sliding window by simply making the window itself the output buffer. This
  78549. function trusts the application to not change the output buffer passed by
  78550. the output function, at least until inflateBack() returns.
  78551. inflateBackInit() must be called first to allocate the internal state
  78552. and to initialize the state with the user-provided window buffer.
  78553. inflateBack() may then be used multiple times to inflate a complete, raw
  78554. deflate stream with each call. inflateBackEnd() is then called to free
  78555. the allocated state.
  78556. A raw deflate stream is one with no zlib or gzip header or trailer.
  78557. This routine would normally be used in a utility that reads zip or gzip
  78558. files and writes out uncompressed files. The utility would decode the
  78559. header and process the trailer on its own, hence this routine expects
  78560. only the raw deflate stream to decompress. This is different from the
  78561. normal behavior of inflate(), which expects either a zlib or gzip header and
  78562. trailer around the deflate stream.
  78563. inflateBack() uses two subroutines supplied by the caller that are then
  78564. called by inflateBack() for input and output. inflateBack() calls those
  78565. routines until it reads a complete deflate stream and writes out all of the
  78566. uncompressed data, or until it encounters an error. The function's
  78567. parameters and return types are defined above in the in_func and out_func
  78568. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  78569. number of bytes of provided input, and a pointer to that input in buf. If
  78570. there is no input available, in() must return zero--buf is ignored in that
  78571. case--and inflateBack() will return a buffer error. inflateBack() will call
  78572. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  78573. should return zero on success, or non-zero on failure. If out() returns
  78574. non-zero, inflateBack() will return with an error. Neither in() nor out()
  78575. are permitted to change the contents of the window provided to
  78576. inflateBackInit(), which is also the buffer that out() uses to write from.
  78577. The length written by out() will be at most the window size. Any non-zero
  78578. amount of input may be provided by in().
  78579. For convenience, inflateBack() can be provided input on the first call by
  78580. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  78581. in() will be called. Therefore strm->next_in must be initialized before
  78582. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  78583. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  78584. must also be initialized, and then if strm->avail_in is not zero, input will
  78585. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  78586. The in_desc and out_desc parameters of inflateBack() is passed as the
  78587. first parameter of in() and out() respectively when they are called. These
  78588. descriptors can be optionally used to pass any information that the caller-
  78589. supplied in() and out() functions need to do their job.
  78590. On return, inflateBack() will set strm->next_in and strm->avail_in to
  78591. pass back any unused input that was provided by the last in() call. The
  78592. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  78593. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  78594. error in the deflate stream (in which case strm->msg is set to indicate the
  78595. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  78596. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  78597. distinguished using strm->next_in which will be Z_NULL only if in() returned
  78598. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  78599. out() returning non-zero. (in() will always be called before out(), so
  78600. strm->next_in is assured to be defined if out() returns non-zero.) Note
  78601. that inflateBack() cannot return Z_OK.
  78602. */
  78603. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  78604. /*
  78605. All memory allocated by inflateBackInit() is freed.
  78606. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  78607. state was inconsistent.
  78608. */
  78609. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  78610. /* Return flags indicating compile-time options.
  78611. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  78612. 1.0: size of uInt
  78613. 3.2: size of uLong
  78614. 5.4: size of voidpf (pointer)
  78615. 7.6: size of z_off_t
  78616. Compiler, assembler, and debug options:
  78617. 8: DEBUG
  78618. 9: ASMV or ASMINF -- use ASM code
  78619. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  78620. 11: 0 (reserved)
  78621. One-time table building (smaller code, but not thread-safe if true):
  78622. 12: BUILDFIXED -- build static block decoding tables when needed
  78623. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  78624. 14,15: 0 (reserved)
  78625. Library content (indicates missing functionality):
  78626. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  78627. deflate code when not needed)
  78628. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  78629. and decode gzip streams (to avoid linking crc code)
  78630. 18-19: 0 (reserved)
  78631. Operation variations (changes in library functionality):
  78632. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  78633. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  78634. 22,23: 0 (reserved)
  78635. The sprintf variant used by gzprintf (zero is best):
  78636. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  78637. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  78638. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  78639. Remainder:
  78640. 27-31: 0 (reserved)
  78641. */
  78642. /* utility functions */
  78643. /*
  78644. The following utility functions are implemented on top of the
  78645. basic stream-oriented functions. To simplify the interface, some
  78646. default options are assumed (compression level and memory usage,
  78647. standard memory allocation functions). The source code of these
  78648. utility functions can easily be modified if you need special options.
  78649. */
  78650. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  78651. const Bytef *source, uLong sourceLen));
  78652. /*
  78653. Compresses the source buffer into the destination buffer. sourceLen is
  78654. the byte length of the source buffer. Upon entry, destLen is the total
  78655. size of the destination buffer, which must be at least the value returned
  78656. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78657. compressed buffer.
  78658. This function can be used to compress a whole file at once if the
  78659. input file is mmap'ed.
  78660. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  78661. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78662. buffer.
  78663. */
  78664. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  78665. const Bytef *source, uLong sourceLen,
  78666. int level));
  78667. /*
  78668. Compresses the source buffer into the destination buffer. The level
  78669. parameter has the same meaning as in deflateInit. sourceLen is the byte
  78670. length of the source buffer. Upon entry, destLen is the total size of the
  78671. destination buffer, which must be at least the value returned by
  78672. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78673. compressed buffer.
  78674. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78675. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  78676. Z_STREAM_ERROR if the level parameter is invalid.
  78677. */
  78678. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  78679. /*
  78680. compressBound() returns an upper bound on the compressed size after
  78681. compress() or compress2() on sourceLen bytes. It would be used before
  78682. a compress() or compress2() call to allocate the destination buffer.
  78683. */
  78684. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  78685. const Bytef *source, uLong sourceLen));
  78686. /*
  78687. Decompresses the source buffer into the destination buffer. sourceLen is
  78688. the byte length of the source buffer. Upon entry, destLen is the total
  78689. size of the destination buffer, which must be large enough to hold the
  78690. entire uncompressed data. (The size of the uncompressed data must have
  78691. been saved previously by the compressor and transmitted to the decompressor
  78692. by some mechanism outside the scope of this compression library.)
  78693. Upon exit, destLen is the actual size of the compressed buffer.
  78694. This function can be used to decompress a whole file at once if the
  78695. input file is mmap'ed.
  78696. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  78697. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78698. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  78699. */
  78700. typedef voidp gzFile;
  78701. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  78702. /*
  78703. Opens a gzip (.gz) file for reading or writing. The mode parameter
  78704. is as in fopen ("rb" or "wb") but can also include a compression level
  78705. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  78706. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  78707. as in "wb1R". (See the description of deflateInit2 for more information
  78708. about the strategy parameter.)
  78709. gzopen can be used to read a file which is not in gzip format; in this
  78710. case gzread will directly read from the file without decompression.
  78711. gzopen returns NULL if the file could not be opened or if there was
  78712. insufficient memory to allocate the (de)compression state; errno
  78713. can be checked to distinguish the two cases (if errno is zero, the
  78714. zlib error is Z_MEM_ERROR). */
  78715. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  78716. /*
  78717. gzdopen() associates a gzFile with the file descriptor fd. File
  78718. descriptors are obtained from calls like open, dup, creat, pipe or
  78719. fileno (in the file has been previously opened with fopen).
  78720. The mode parameter is as in gzopen.
  78721. The next call of gzclose on the returned gzFile will also close the
  78722. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  78723. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  78724. gzdopen returns NULL if there was insufficient memory to allocate
  78725. the (de)compression state.
  78726. */
  78727. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  78728. /*
  78729. Dynamically update the compression level or strategy. See the description
  78730. of deflateInit2 for the meaning of these parameters.
  78731. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  78732. opened for writing.
  78733. */
  78734. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  78735. /*
  78736. Reads the given number of uncompressed bytes from the compressed file.
  78737. If the input file was not in gzip format, gzread copies the given number
  78738. of bytes into the buffer.
  78739. gzread returns the number of uncompressed bytes actually read (0 for
  78740. end of file, -1 for error). */
  78741. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  78742. voidpc buf, unsigned len));
  78743. /*
  78744. Writes the given number of uncompressed bytes into the compressed file.
  78745. gzwrite returns the number of uncompressed bytes actually written
  78746. (0 in case of error).
  78747. */
  78748. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  78749. /*
  78750. Converts, formats, and writes the args to the compressed file under
  78751. control of the format string, as in fprintf. gzprintf returns the number of
  78752. uncompressed bytes actually written (0 in case of error). The number of
  78753. uncompressed bytes written is limited to 4095. The caller should assure that
  78754. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  78755. return an error (0) with nothing written. In this case, there may also be a
  78756. buffer overflow with unpredictable consequences, which is possible only if
  78757. zlib was compiled with the insecure functions sprintf() or vsprintf()
  78758. because the secure snprintf() or vsnprintf() functions were not available.
  78759. */
  78760. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  78761. /*
  78762. Writes the given null-terminated string to the compressed file, excluding
  78763. the terminating null character.
  78764. gzputs returns the number of characters written, or -1 in case of error.
  78765. */
  78766. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  78767. /*
  78768. Reads bytes from the compressed file until len-1 characters are read, or
  78769. a newline character is read and transferred to buf, or an end-of-file
  78770. condition is encountered. The string is then terminated with a null
  78771. character.
  78772. gzgets returns buf, or Z_NULL in case of error.
  78773. */
  78774. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  78775. /*
  78776. Writes c, converted to an unsigned char, into the compressed file.
  78777. gzputc returns the value that was written, or -1 in case of error.
  78778. */
  78779. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  78780. /*
  78781. Reads one byte from the compressed file. gzgetc returns this byte
  78782. or -1 in case of end of file or error.
  78783. */
  78784. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  78785. /*
  78786. Push one character back onto the stream to be read again later.
  78787. Only one character of push-back is allowed. gzungetc() returns the
  78788. character pushed, or -1 on failure. gzungetc() will fail if a
  78789. character has been pushed but not read yet, or if c is -1. The pushed
  78790. character will be discarded if the stream is repositioned with gzseek()
  78791. or gzrewind().
  78792. */
  78793. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  78794. /*
  78795. Flushes all pending output into the compressed file. The parameter
  78796. flush is as in the deflate() function. The return value is the zlib
  78797. error number (see function gzerror below). gzflush returns Z_OK if
  78798. the flush parameter is Z_FINISH and all output could be flushed.
  78799. gzflush should be called only when strictly necessary because it can
  78800. degrade compression.
  78801. */
  78802. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  78803. z_off_t offset, int whence));
  78804. /*
  78805. Sets the starting position for the next gzread or gzwrite on the
  78806. given compressed file. The offset represents a number of bytes in the
  78807. uncompressed data stream. The whence parameter is defined as in lseek(2);
  78808. the value SEEK_END is not supported.
  78809. If the file is opened for reading, this function is emulated but can be
  78810. extremely slow. If the file is opened for writing, only forward seeks are
  78811. supported; gzseek then compresses a sequence of zeroes up to the new
  78812. starting position.
  78813. gzseek returns the resulting offset location as measured in bytes from
  78814. the beginning of the uncompressed stream, or -1 in case of error, in
  78815. particular if the file is opened for writing and the new starting position
  78816. would be before the current position.
  78817. */
  78818. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  78819. /*
  78820. Rewinds the given file. This function is supported only for reading.
  78821. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  78822. */
  78823. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  78824. /*
  78825. Returns the starting position for the next gzread or gzwrite on the
  78826. given compressed file. This position represents a number of bytes in the
  78827. uncompressed data stream.
  78828. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  78829. */
  78830. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  78831. /*
  78832. Returns 1 when EOF has previously been detected reading the given
  78833. input stream, otherwise zero.
  78834. */
  78835. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  78836. /*
  78837. Returns 1 if file is being read directly without decompression, otherwise
  78838. zero.
  78839. */
  78840. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  78841. /*
  78842. Flushes all pending output if necessary, closes the compressed file
  78843. and deallocates all the (de)compression state. The return value is the zlib
  78844. error number (see function gzerror below).
  78845. */
  78846. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  78847. /*
  78848. Returns the error message for the last error which occurred on the
  78849. given compressed file. errnum is set to zlib error number. If an
  78850. error occurred in the file system and not in the compression library,
  78851. errnum is set to Z_ERRNO and the application may consult errno
  78852. to get the exact error code.
  78853. */
  78854. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  78855. /*
  78856. Clears the error and end-of-file flags for file. This is analogous to the
  78857. clearerr() function in stdio. This is useful for continuing to read a gzip
  78858. file that is being written concurrently.
  78859. */
  78860. /* checksum functions */
  78861. /*
  78862. These functions are not related to compression but are exported
  78863. anyway because they might be useful in applications using the
  78864. compression library.
  78865. */
  78866. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  78867. /*
  78868. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  78869. return the updated checksum. If buf is NULL, this function returns
  78870. the required initial value for the checksum.
  78871. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  78872. much faster. Usage example:
  78873. uLong adler = adler32(0L, Z_NULL, 0);
  78874. while (read_buffer(buffer, length) != EOF) {
  78875. adler = adler32(adler, buffer, length);
  78876. }
  78877. if (adler != original_adler) error();
  78878. */
  78879. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  78880. z_off_t len2));
  78881. /*
  78882. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  78883. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  78884. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  78885. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  78886. */
  78887. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  78888. /*
  78889. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  78890. updated CRC-32. If buf is NULL, this function returns the required initial
  78891. value for the for the crc. Pre- and post-conditioning (one's complement) is
  78892. performed within this function so it shouldn't be done by the application.
  78893. Usage example:
  78894. uLong crc = crc32(0L, Z_NULL, 0);
  78895. while (read_buffer(buffer, length) != EOF) {
  78896. crc = crc32(crc, buffer, length);
  78897. }
  78898. if (crc != original_crc) error();
  78899. */
  78900. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  78901. /*
  78902. Combine two CRC-32 check values into one. For two sequences of bytes,
  78903. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  78904. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  78905. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  78906. len2.
  78907. */
  78908. /* various hacks, don't look :) */
  78909. /* deflateInit and inflateInit are macros to allow checking the zlib version
  78910. * and the compiler's view of z_stream:
  78911. */
  78912. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  78913. const char *version, int stream_size));
  78914. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  78915. const char *version, int stream_size));
  78916. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  78917. int windowBits, int memLevel,
  78918. int strategy, const char *version,
  78919. int stream_size));
  78920. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  78921. const char *version, int stream_size));
  78922. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  78923. unsigned char FAR *window,
  78924. const char *version,
  78925. int stream_size));
  78926. #define deflateInit(strm, level) \
  78927. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  78928. #define inflateInit(strm) \
  78929. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  78930. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  78931. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  78932. (strategy), ZLIB_VERSION, sizeof(z_stream))
  78933. #define inflateInit2(strm, windowBits) \
  78934. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  78935. #define inflateBackInit(strm, windowBits, window) \
  78936. inflateBackInit_((strm), (windowBits), (window), \
  78937. ZLIB_VERSION, sizeof(z_stream))
  78938. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  78939. struct internal_state {int dummy;}; /* hack for buggy compilers */
  78940. #endif
  78941. ZEXTERN const char * ZEXPORT zError OF((int));
  78942. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  78943. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  78944. #ifdef __cplusplus
  78945. }
  78946. #endif
  78947. #endif /* ZLIB_H */
  78948. /*** End of inlined file: zlib.h ***/
  78949. #undef OS_CODE
  78950. #else
  78951. #include <zlib.h>
  78952. #endif
  78953. }
  78954. BEGIN_JUCE_NAMESPACE
  78955. // internal helper object that holds the zlib structures so they don't have to be
  78956. // included publicly.
  78957. class GZIPCompressorHelper
  78958. {
  78959. public:
  78960. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  78961. : data (0),
  78962. dataSize (0),
  78963. compLevel (compressionLevel),
  78964. strategy (0),
  78965. setParams (true),
  78966. streamIsValid (false),
  78967. finished (false),
  78968. shouldFinish (false)
  78969. {
  78970. using namespace zlibNamespace;
  78971. zerostruct (stream);
  78972. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  78973. nowrap ? -MAX_WBITS : MAX_WBITS,
  78974. 8, strategy) == Z_OK);
  78975. }
  78976. ~GZIPCompressorHelper()
  78977. {
  78978. using namespace zlibNamespace;
  78979. if (streamIsValid)
  78980. deflateEnd (&stream);
  78981. }
  78982. bool needsInput() const throw()
  78983. {
  78984. return dataSize <= 0;
  78985. }
  78986. void setInput (const uint8* const newData, const int size) throw()
  78987. {
  78988. data = newData;
  78989. dataSize = size;
  78990. }
  78991. int doNextBlock (uint8* const dest, const int destSize) throw()
  78992. {
  78993. using namespace zlibNamespace;
  78994. if (streamIsValid)
  78995. {
  78996. stream.next_in = const_cast <uint8*> (data);
  78997. stream.next_out = dest;
  78998. stream.avail_in = dataSize;
  78999. stream.avail_out = destSize;
  79000. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79001. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79002. setParams = false;
  79003. switch (result)
  79004. {
  79005. case Z_STREAM_END:
  79006. finished = true;
  79007. // Deliberate fall-through..
  79008. case Z_OK:
  79009. data += dataSize - stream.avail_in;
  79010. dataSize = stream.avail_in;
  79011. return destSize - stream.avail_out;
  79012. default:
  79013. break;
  79014. }
  79015. }
  79016. return 0;
  79017. }
  79018. private:
  79019. zlibNamespace::z_stream stream;
  79020. const uint8* data;
  79021. int dataSize, compLevel, strategy;
  79022. bool setParams, streamIsValid;
  79023. public:
  79024. bool finished, shouldFinish;
  79025. };
  79026. const int gzipCompBufferSize = 32768;
  79027. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79028. int compressionLevel,
  79029. const bool deleteDestStream,
  79030. const bool noWrap)
  79031. : destStream (destStream_),
  79032. streamToDelete (deleteDestStream ? destStream_ : 0),
  79033. buffer (gzipCompBufferSize)
  79034. {
  79035. if (compressionLevel < 1 || compressionLevel > 9)
  79036. compressionLevel = -1;
  79037. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  79038. }
  79039. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79040. {
  79041. flush();
  79042. }
  79043. void GZIPCompressorOutputStream::flush()
  79044. {
  79045. if (! helper->finished)
  79046. {
  79047. helper->shouldFinish = true;
  79048. while (! helper->finished)
  79049. doNextBlock();
  79050. }
  79051. destStream->flush();
  79052. }
  79053. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79054. {
  79055. if (! helper->finished)
  79056. {
  79057. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79058. while (! helper->needsInput())
  79059. {
  79060. if (! doNextBlock())
  79061. return false;
  79062. }
  79063. }
  79064. return true;
  79065. }
  79066. bool GZIPCompressorOutputStream::doNextBlock()
  79067. {
  79068. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  79069. if (len > 0)
  79070. return destStream->write (buffer, len);
  79071. else
  79072. return true;
  79073. }
  79074. int64 GZIPCompressorOutputStream::getPosition()
  79075. {
  79076. return destStream->getPosition();
  79077. }
  79078. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79079. {
  79080. jassertfalse; // can't do it!
  79081. return false;
  79082. }
  79083. END_JUCE_NAMESPACE
  79084. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79085. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79086. #if JUCE_MSVC
  79087. #pragma warning (push)
  79088. #pragma warning (disable: 4309 4305)
  79089. #endif
  79090. namespace zlibNamespace
  79091. {
  79092. #if JUCE_INCLUDE_ZLIB_CODE
  79093. extern "C"
  79094. {
  79095. #undef OS_CODE
  79096. #undef fdopen
  79097. #define ZLIB_INTERNAL
  79098. #define NO_DUMMY_DECL
  79099. /*** Start of inlined file: adler32.c ***/
  79100. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79101. #define ZLIB_INTERNAL
  79102. #define BASE 65521UL /* largest prime smaller than 65536 */
  79103. #define NMAX 5552
  79104. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79105. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79106. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79107. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79108. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79109. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79110. /* use NO_DIVIDE if your processor does not do division in hardware */
  79111. #ifdef NO_DIVIDE
  79112. # define MOD(a) \
  79113. do { \
  79114. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79115. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79116. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79117. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79118. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79119. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79120. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79121. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79122. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79123. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79124. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79125. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79126. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79127. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79128. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79129. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79130. if (a >= BASE) a -= BASE; \
  79131. } while (0)
  79132. # define MOD4(a) \
  79133. do { \
  79134. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79135. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79136. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79137. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79138. if (a >= BASE) a -= BASE; \
  79139. } while (0)
  79140. #else
  79141. # define MOD(a) a %= BASE
  79142. # define MOD4(a) a %= BASE
  79143. #endif
  79144. /* ========================================================================= */
  79145. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79146. {
  79147. unsigned long sum2;
  79148. unsigned n;
  79149. /* split Adler-32 into component sums */
  79150. sum2 = (adler >> 16) & 0xffff;
  79151. adler &= 0xffff;
  79152. /* in case user likes doing a byte at a time, keep it fast */
  79153. if (len == 1) {
  79154. adler += buf[0];
  79155. if (adler >= BASE)
  79156. adler -= BASE;
  79157. sum2 += adler;
  79158. if (sum2 >= BASE)
  79159. sum2 -= BASE;
  79160. return adler | (sum2 << 16);
  79161. }
  79162. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79163. if (buf == Z_NULL)
  79164. return 1L;
  79165. /* in case short lengths are provided, keep it somewhat fast */
  79166. if (len < 16) {
  79167. while (len--) {
  79168. adler += *buf++;
  79169. sum2 += adler;
  79170. }
  79171. if (adler >= BASE)
  79172. adler -= BASE;
  79173. MOD4(sum2); /* only added so many BASE's */
  79174. return adler | (sum2 << 16);
  79175. }
  79176. /* do length NMAX blocks -- requires just one modulo operation */
  79177. while (len >= NMAX) {
  79178. len -= NMAX;
  79179. n = NMAX / 16; /* NMAX is divisible by 16 */
  79180. do {
  79181. DO16(buf); /* 16 sums unrolled */
  79182. buf += 16;
  79183. } while (--n);
  79184. MOD(adler);
  79185. MOD(sum2);
  79186. }
  79187. /* do remaining bytes (less than NMAX, still just one modulo) */
  79188. if (len) { /* avoid modulos if none remaining */
  79189. while (len >= 16) {
  79190. len -= 16;
  79191. DO16(buf);
  79192. buf += 16;
  79193. }
  79194. while (len--) {
  79195. adler += *buf++;
  79196. sum2 += adler;
  79197. }
  79198. MOD(adler);
  79199. MOD(sum2);
  79200. }
  79201. /* return recombined sums */
  79202. return adler | (sum2 << 16);
  79203. }
  79204. /* ========================================================================= */
  79205. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79206. {
  79207. unsigned long sum1;
  79208. unsigned long sum2;
  79209. unsigned rem;
  79210. /* the derivation of this formula is left as an exercise for the reader */
  79211. rem = (unsigned)(len2 % BASE);
  79212. sum1 = adler1 & 0xffff;
  79213. sum2 = rem * sum1;
  79214. MOD(sum2);
  79215. sum1 += (adler2 & 0xffff) + BASE - 1;
  79216. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79217. if (sum1 > BASE) sum1 -= BASE;
  79218. if (sum1 > BASE) sum1 -= BASE;
  79219. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79220. if (sum2 > BASE) sum2 -= BASE;
  79221. return sum1 | (sum2 << 16);
  79222. }
  79223. /*** End of inlined file: adler32.c ***/
  79224. /*** Start of inlined file: compress.c ***/
  79225. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79226. #define ZLIB_INTERNAL
  79227. /* ===========================================================================
  79228. Compresses the source buffer into the destination buffer. The level
  79229. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79230. length of the source buffer. Upon entry, destLen is the total size of the
  79231. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79232. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79233. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79234. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79235. Z_STREAM_ERROR if the level parameter is invalid.
  79236. */
  79237. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79238. uLong sourceLen, int level)
  79239. {
  79240. z_stream stream;
  79241. int err;
  79242. stream.next_in = (Bytef*)source;
  79243. stream.avail_in = (uInt)sourceLen;
  79244. #ifdef MAXSEG_64K
  79245. /* Check for source > 64K on 16-bit machine: */
  79246. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79247. #endif
  79248. stream.next_out = dest;
  79249. stream.avail_out = (uInt)*destLen;
  79250. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79251. stream.zalloc = (alloc_func)0;
  79252. stream.zfree = (free_func)0;
  79253. stream.opaque = (voidpf)0;
  79254. err = deflateInit(&stream, level);
  79255. if (err != Z_OK) return err;
  79256. err = deflate(&stream, Z_FINISH);
  79257. if (err != Z_STREAM_END) {
  79258. deflateEnd(&stream);
  79259. return err == Z_OK ? Z_BUF_ERROR : err;
  79260. }
  79261. *destLen = stream.total_out;
  79262. err = deflateEnd(&stream);
  79263. return err;
  79264. }
  79265. /* ===========================================================================
  79266. */
  79267. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  79268. {
  79269. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  79270. }
  79271. /* ===========================================================================
  79272. If the default memLevel or windowBits for deflateInit() is changed, then
  79273. this function needs to be updated.
  79274. */
  79275. uLong ZEXPORT compressBound (uLong sourceLen)
  79276. {
  79277. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  79278. }
  79279. /*** End of inlined file: compress.c ***/
  79280. #undef DO1
  79281. #undef DO8
  79282. /*** Start of inlined file: crc32.c ***/
  79283. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79284. /*
  79285. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  79286. protection on the static variables used to control the first-use generation
  79287. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  79288. first call get_crc_table() to initialize the tables before allowing more than
  79289. one thread to use crc32().
  79290. */
  79291. #ifdef MAKECRCH
  79292. # include <stdio.h>
  79293. # ifndef DYNAMIC_CRC_TABLE
  79294. # define DYNAMIC_CRC_TABLE
  79295. # endif /* !DYNAMIC_CRC_TABLE */
  79296. #endif /* MAKECRCH */
  79297. /*** Start of inlined file: zutil.h ***/
  79298. /* WARNING: this file should *not* be used by applications. It is
  79299. part of the implementation of the compression library and is
  79300. subject to change. Applications should only use zlib.h.
  79301. */
  79302. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79303. #ifndef ZUTIL_H
  79304. #define ZUTIL_H
  79305. #define ZLIB_INTERNAL
  79306. #ifdef STDC
  79307. # ifndef _WIN32_WCE
  79308. # include <stddef.h>
  79309. # endif
  79310. # include <string.h>
  79311. # include <stdlib.h>
  79312. #endif
  79313. #ifdef NO_ERRNO_H
  79314. # ifdef _WIN32_WCE
  79315. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79316. * errno. We define it as a global variable to simplify porting.
  79317. * Its value is always 0 and should not be used. We rename it to
  79318. * avoid conflict with other libraries that use the same workaround.
  79319. */
  79320. # define errno z_errno
  79321. # endif
  79322. extern int errno;
  79323. #else
  79324. # ifndef _WIN32_WCE
  79325. # include <errno.h>
  79326. # endif
  79327. #endif
  79328. #ifndef local
  79329. # define local static
  79330. #endif
  79331. /* compile with -Dlocal if your debugger can't find static symbols */
  79332. typedef unsigned char uch;
  79333. typedef uch FAR uchf;
  79334. typedef unsigned short ush;
  79335. typedef ush FAR ushf;
  79336. typedef unsigned long ulg;
  79337. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79338. /* (size given to avoid silly warnings with Visual C++) */
  79339. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79340. #define ERR_RETURN(strm,err) \
  79341. return (strm->msg = (char*)ERR_MSG(err), (err))
  79342. /* To be used only when the state is known to be valid */
  79343. /* common constants */
  79344. #ifndef DEF_WBITS
  79345. # define DEF_WBITS MAX_WBITS
  79346. #endif
  79347. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79348. #if MAX_MEM_LEVEL >= 8
  79349. # define DEF_MEM_LEVEL 8
  79350. #else
  79351. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79352. #endif
  79353. /* default memLevel */
  79354. #define STORED_BLOCK 0
  79355. #define STATIC_TREES 1
  79356. #define DYN_TREES 2
  79357. /* The three kinds of block type */
  79358. #define MIN_MATCH 3
  79359. #define MAX_MATCH 258
  79360. /* The minimum and maximum match lengths */
  79361. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  79362. /* target dependencies */
  79363. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  79364. # define OS_CODE 0x00
  79365. # if defined(__TURBOC__) || defined(__BORLANDC__)
  79366. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  79367. /* Allow compilation with ANSI keywords only enabled */
  79368. void _Cdecl farfree( void *block );
  79369. void *_Cdecl farmalloc( unsigned long nbytes );
  79370. # else
  79371. # include <alloc.h>
  79372. # endif
  79373. # else /* MSC or DJGPP */
  79374. # include <malloc.h>
  79375. # endif
  79376. #endif
  79377. #ifdef AMIGA
  79378. # define OS_CODE 0x01
  79379. #endif
  79380. #if defined(VAXC) || defined(VMS)
  79381. # define OS_CODE 0x02
  79382. # define F_OPEN(name, mode) \
  79383. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  79384. #endif
  79385. #if defined(ATARI) || defined(atarist)
  79386. # define OS_CODE 0x05
  79387. #endif
  79388. #ifdef OS2
  79389. # define OS_CODE 0x06
  79390. # ifdef M_I86
  79391. #include <malloc.h>
  79392. # endif
  79393. #endif
  79394. #if defined(MACOS) || TARGET_OS_MAC
  79395. # define OS_CODE 0x07
  79396. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  79397. # include <unix.h> /* for fdopen */
  79398. # else
  79399. # ifndef fdopen
  79400. # define fdopen(fd,mode) NULL /* No fdopen() */
  79401. # endif
  79402. # endif
  79403. #endif
  79404. #ifdef TOPS20
  79405. # define OS_CODE 0x0a
  79406. #endif
  79407. #ifdef WIN32
  79408. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  79409. # define OS_CODE 0x0b
  79410. # endif
  79411. #endif
  79412. #ifdef __50SERIES /* Prime/PRIMOS */
  79413. # define OS_CODE 0x0f
  79414. #endif
  79415. #if defined(_BEOS_) || defined(RISCOS)
  79416. # define fdopen(fd,mode) NULL /* No fdopen() */
  79417. #endif
  79418. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  79419. # if defined(_WIN32_WCE)
  79420. # define fdopen(fd,mode) NULL /* No fdopen() */
  79421. # ifndef _PTRDIFF_T_DEFINED
  79422. typedef int ptrdiff_t;
  79423. # define _PTRDIFF_T_DEFINED
  79424. # endif
  79425. # else
  79426. # define fdopen(fd,type) _fdopen(fd,type)
  79427. # endif
  79428. #endif
  79429. /* common defaults */
  79430. #ifndef OS_CODE
  79431. # define OS_CODE 0x03 /* assume Unix */
  79432. #endif
  79433. #ifndef F_OPEN
  79434. # define F_OPEN(name, mode) fopen((name), (mode))
  79435. #endif
  79436. /* functions */
  79437. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  79438. # ifndef HAVE_VSNPRINTF
  79439. # define HAVE_VSNPRINTF
  79440. # endif
  79441. #endif
  79442. #if defined(__CYGWIN__)
  79443. # ifndef HAVE_VSNPRINTF
  79444. # define HAVE_VSNPRINTF
  79445. # endif
  79446. #endif
  79447. #ifndef HAVE_VSNPRINTF
  79448. # ifdef MSDOS
  79449. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  79450. but for now we just assume it doesn't. */
  79451. # define NO_vsnprintf
  79452. # endif
  79453. # ifdef __TURBOC__
  79454. # define NO_vsnprintf
  79455. # endif
  79456. # ifdef WIN32
  79457. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  79458. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  79459. # define vsnprintf _vsnprintf
  79460. # endif
  79461. # endif
  79462. # ifdef __SASC
  79463. # define NO_vsnprintf
  79464. # endif
  79465. #endif
  79466. #ifdef VMS
  79467. # define NO_vsnprintf
  79468. #endif
  79469. #if defined(pyr)
  79470. # define NO_MEMCPY
  79471. #endif
  79472. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  79473. /* Use our own functions for small and medium model with MSC <= 5.0.
  79474. * You may have to use the same strategy for Borland C (untested).
  79475. * The __SC__ check is for Symantec.
  79476. */
  79477. # define NO_MEMCPY
  79478. #endif
  79479. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  79480. # define HAVE_MEMCPY
  79481. #endif
  79482. #ifdef HAVE_MEMCPY
  79483. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  79484. # define zmemcpy _fmemcpy
  79485. # define zmemcmp _fmemcmp
  79486. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  79487. # else
  79488. # define zmemcpy memcpy
  79489. # define zmemcmp memcmp
  79490. # define zmemzero(dest, len) memset(dest, 0, len)
  79491. # endif
  79492. #else
  79493. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  79494. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  79495. extern void zmemzero OF((Bytef* dest, uInt len));
  79496. #endif
  79497. /* Diagnostic functions */
  79498. #ifdef DEBUG
  79499. # include <stdio.h>
  79500. extern int z_verbose;
  79501. extern void z_error OF((const char *m));
  79502. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  79503. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  79504. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  79505. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  79506. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  79507. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  79508. #else
  79509. # define Assert(cond,msg)
  79510. # define Trace(x)
  79511. # define Tracev(x)
  79512. # define Tracevv(x)
  79513. # define Tracec(c,x)
  79514. # define Tracecv(c,x)
  79515. #endif
  79516. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  79517. void zcfree OF((voidpf opaque, voidpf ptr));
  79518. #define ZALLOC(strm, items, size) \
  79519. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  79520. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  79521. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  79522. #endif /* ZUTIL_H */
  79523. /*** End of inlined file: zutil.h ***/
  79524. /* for STDC and FAR definitions */
  79525. #define local static
  79526. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  79527. #ifndef NOBYFOUR
  79528. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  79529. # include <limits.h>
  79530. # define BYFOUR
  79531. # if (UINT_MAX == 0xffffffffUL)
  79532. typedef unsigned int u4;
  79533. # else
  79534. # if (ULONG_MAX == 0xffffffffUL)
  79535. typedef unsigned long u4;
  79536. # else
  79537. # if (USHRT_MAX == 0xffffffffUL)
  79538. typedef unsigned short u4;
  79539. # else
  79540. # undef BYFOUR /* can't find a four-byte integer type! */
  79541. # endif
  79542. # endif
  79543. # endif
  79544. # endif /* STDC */
  79545. #endif /* !NOBYFOUR */
  79546. /* Definitions for doing the crc four data bytes at a time. */
  79547. #ifdef BYFOUR
  79548. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  79549. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  79550. local unsigned long crc32_little OF((unsigned long,
  79551. const unsigned char FAR *, unsigned));
  79552. local unsigned long crc32_big OF((unsigned long,
  79553. const unsigned char FAR *, unsigned));
  79554. # define TBLS 8
  79555. #else
  79556. # define TBLS 1
  79557. #endif /* BYFOUR */
  79558. /* Local functions for crc concatenation */
  79559. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  79560. unsigned long vec));
  79561. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  79562. #ifdef DYNAMIC_CRC_TABLE
  79563. local volatile int crc_table_empty = 1;
  79564. local unsigned long FAR crc_table[TBLS][256];
  79565. local void make_crc_table OF((void));
  79566. #ifdef MAKECRCH
  79567. local void write_table OF((FILE *, const unsigned long FAR *));
  79568. #endif /* MAKECRCH */
  79569. /*
  79570. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  79571. 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.
  79572. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  79573. with the lowest powers in the most significant bit. Then adding polynomials
  79574. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  79575. one. If we call the above polynomial p, and represent a byte as the
  79576. polynomial q, also with the lowest power in the most significant bit (so the
  79577. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  79578. where a mod b means the remainder after dividing a by b.
  79579. This calculation is done using the shift-register method of multiplying and
  79580. taking the remainder. The register is initialized to zero, and for each
  79581. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  79582. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  79583. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  79584. out is a one). We start with the highest power (least significant bit) of
  79585. q and repeat for all eight bits of q.
  79586. The first table is simply the CRC of all possible eight bit values. This is
  79587. all the information needed to generate CRCs on data a byte at a time for all
  79588. combinations of CRC register values and incoming bytes. The remaining tables
  79589. allow for word-at-a-time CRC calculation for both big-endian and little-
  79590. endian machines, where a word is four bytes.
  79591. */
  79592. local void make_crc_table()
  79593. {
  79594. unsigned long c;
  79595. int n, k;
  79596. unsigned long poly; /* polynomial exclusive-or pattern */
  79597. /* terms of polynomial defining this crc (except x^32): */
  79598. static volatile int first = 1; /* flag to limit concurrent making */
  79599. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  79600. /* See if another task is already doing this (not thread-safe, but better
  79601. than nothing -- significantly reduces duration of vulnerability in
  79602. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  79603. if (first) {
  79604. first = 0;
  79605. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  79606. poly = 0UL;
  79607. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  79608. poly |= 1UL << (31 - p[n]);
  79609. /* generate a crc for every 8-bit value */
  79610. for (n = 0; n < 256; n++) {
  79611. c = (unsigned long)n;
  79612. for (k = 0; k < 8; k++)
  79613. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  79614. crc_table[0][n] = c;
  79615. }
  79616. #ifdef BYFOUR
  79617. /* generate crc for each value followed by one, two, and three zeros,
  79618. and then the byte reversal of those as well as the first table */
  79619. for (n = 0; n < 256; n++) {
  79620. c = crc_table[0][n];
  79621. crc_table[4][n] = REV(c);
  79622. for (k = 1; k < 4; k++) {
  79623. c = crc_table[0][c & 0xff] ^ (c >> 8);
  79624. crc_table[k][n] = c;
  79625. crc_table[k + 4][n] = REV(c);
  79626. }
  79627. }
  79628. #endif /* BYFOUR */
  79629. crc_table_empty = 0;
  79630. }
  79631. else { /* not first */
  79632. /* wait for the other guy to finish (not efficient, but rare) */
  79633. while (crc_table_empty)
  79634. ;
  79635. }
  79636. #ifdef MAKECRCH
  79637. /* write out CRC tables to crc32.h */
  79638. {
  79639. FILE *out;
  79640. out = fopen("crc32.h", "w");
  79641. if (out == NULL) return;
  79642. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  79643. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  79644. fprintf(out, "local const unsigned long FAR ");
  79645. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  79646. write_table(out, crc_table[0]);
  79647. # ifdef BYFOUR
  79648. fprintf(out, "#ifdef BYFOUR\n");
  79649. for (k = 1; k < 8; k++) {
  79650. fprintf(out, " },\n {\n");
  79651. write_table(out, crc_table[k]);
  79652. }
  79653. fprintf(out, "#endif\n");
  79654. # endif /* BYFOUR */
  79655. fprintf(out, " }\n};\n");
  79656. fclose(out);
  79657. }
  79658. #endif /* MAKECRCH */
  79659. }
  79660. #ifdef MAKECRCH
  79661. local void write_table(out, table)
  79662. FILE *out;
  79663. const unsigned long FAR *table;
  79664. {
  79665. int n;
  79666. for (n = 0; n < 256; n++)
  79667. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  79668. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  79669. }
  79670. #endif /* MAKECRCH */
  79671. #else /* !DYNAMIC_CRC_TABLE */
  79672. /* ========================================================================
  79673. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  79674. */
  79675. /*** Start of inlined file: crc32.h ***/
  79676. local const unsigned long FAR crc_table[TBLS][256] =
  79677. {
  79678. {
  79679. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  79680. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  79681. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  79682. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  79683. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  79684. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  79685. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  79686. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  79687. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  79688. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  79689. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  79690. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  79691. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  79692. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  79693. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  79694. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  79695. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  79696. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  79697. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  79698. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  79699. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  79700. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  79701. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  79702. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  79703. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  79704. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  79705. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  79706. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  79707. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  79708. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  79709. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  79710. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  79711. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  79712. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  79713. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  79714. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  79715. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  79716. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  79717. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  79718. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  79719. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  79720. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  79721. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  79722. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  79723. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  79724. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  79725. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  79726. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  79727. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  79728. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  79729. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  79730. 0x2d02ef8dUL
  79731. #ifdef BYFOUR
  79732. },
  79733. {
  79734. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  79735. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  79736. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  79737. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  79738. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  79739. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  79740. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  79741. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  79742. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  79743. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  79744. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  79745. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  79746. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  79747. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  79748. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  79749. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  79750. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  79751. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  79752. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  79753. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  79754. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  79755. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  79756. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  79757. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  79758. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  79759. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  79760. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  79761. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  79762. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  79763. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  79764. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  79765. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  79766. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  79767. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  79768. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  79769. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  79770. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  79771. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  79772. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  79773. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  79774. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  79775. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  79776. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  79777. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  79778. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  79779. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  79780. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  79781. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  79782. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  79783. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  79784. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  79785. 0x9324fd72UL
  79786. },
  79787. {
  79788. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  79789. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  79790. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  79791. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  79792. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  79793. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  79794. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  79795. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  79796. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  79797. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  79798. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  79799. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  79800. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  79801. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  79802. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  79803. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  79804. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  79805. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  79806. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  79807. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  79808. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  79809. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  79810. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  79811. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  79812. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  79813. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  79814. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  79815. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  79816. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  79817. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  79818. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  79819. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  79820. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  79821. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  79822. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  79823. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  79824. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  79825. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  79826. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  79827. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  79828. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  79829. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  79830. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  79831. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  79832. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  79833. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  79834. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  79835. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  79836. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  79837. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  79838. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  79839. 0xbe9834edUL
  79840. },
  79841. {
  79842. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  79843. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  79844. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  79845. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  79846. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  79847. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  79848. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  79849. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  79850. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  79851. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  79852. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  79853. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  79854. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  79855. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  79856. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  79857. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  79858. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  79859. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  79860. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  79861. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  79862. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  79863. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  79864. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  79865. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  79866. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  79867. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  79868. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  79869. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  79870. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  79871. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  79872. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  79873. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  79874. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  79875. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  79876. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  79877. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  79878. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  79879. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  79880. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  79881. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  79882. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  79883. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  79884. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  79885. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  79886. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  79887. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  79888. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  79889. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  79890. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  79891. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  79892. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  79893. 0xde0506f1UL
  79894. },
  79895. {
  79896. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  79897. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  79898. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  79899. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  79900. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  79901. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  79902. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  79903. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  79904. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  79905. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  79906. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  79907. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  79908. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  79909. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  79910. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  79911. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  79912. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  79913. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  79914. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  79915. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  79916. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  79917. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  79918. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  79919. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  79920. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  79921. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  79922. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  79923. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  79924. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  79925. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  79926. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  79927. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  79928. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  79929. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  79930. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  79931. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  79932. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  79933. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  79934. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  79935. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  79936. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  79937. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  79938. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  79939. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  79940. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  79941. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  79942. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  79943. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  79944. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  79945. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  79946. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  79947. 0x8def022dUL
  79948. },
  79949. {
  79950. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  79951. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  79952. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  79953. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  79954. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  79955. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  79956. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  79957. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  79958. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  79959. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  79960. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  79961. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  79962. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  79963. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  79964. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  79965. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  79966. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  79967. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  79968. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  79969. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  79970. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  79971. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  79972. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  79973. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  79974. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  79975. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  79976. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  79977. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  79978. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  79979. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  79980. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  79981. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  79982. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  79983. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  79984. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  79985. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  79986. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  79987. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  79988. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  79989. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  79990. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  79991. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  79992. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  79993. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  79994. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  79995. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  79996. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  79997. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  79998. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  79999. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80000. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80001. 0x72fd2493UL
  80002. },
  80003. {
  80004. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80005. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80006. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80007. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80008. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80009. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80010. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80011. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80012. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80013. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80014. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80015. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80016. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80017. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80018. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80019. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80020. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80021. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80022. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80023. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80024. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80025. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80026. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80027. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80028. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80029. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80030. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80031. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80032. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80033. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80034. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80035. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80036. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80037. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80038. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80039. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80040. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80041. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80042. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80043. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80044. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80045. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80046. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80047. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80048. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80049. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80050. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80051. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80052. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80053. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80054. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80055. 0xed3498beUL
  80056. },
  80057. {
  80058. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80059. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80060. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80061. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80062. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80063. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80064. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80065. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80066. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80067. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80068. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80069. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80070. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80071. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80072. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80073. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80074. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80075. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80076. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80077. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80078. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80079. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80080. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80081. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80082. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80083. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80084. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80085. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80086. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80087. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80088. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80089. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80090. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80091. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80092. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80093. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80094. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80095. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80096. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80097. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80098. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80099. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80100. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80101. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80102. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80103. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80104. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80105. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80106. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80107. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80108. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80109. 0xf10605deUL
  80110. #endif
  80111. }
  80112. };
  80113. /*** End of inlined file: crc32.h ***/
  80114. #endif /* DYNAMIC_CRC_TABLE */
  80115. /* =========================================================================
  80116. * This function can be used by asm versions of crc32()
  80117. */
  80118. const unsigned long FAR * ZEXPORT get_crc_table()
  80119. {
  80120. #ifdef DYNAMIC_CRC_TABLE
  80121. if (crc_table_empty)
  80122. make_crc_table();
  80123. #endif /* DYNAMIC_CRC_TABLE */
  80124. return (const unsigned long FAR *)crc_table;
  80125. }
  80126. /* ========================================================================= */
  80127. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80128. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80129. /* ========================================================================= */
  80130. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80131. {
  80132. if (buf == Z_NULL) return 0UL;
  80133. #ifdef DYNAMIC_CRC_TABLE
  80134. if (crc_table_empty)
  80135. make_crc_table();
  80136. #endif /* DYNAMIC_CRC_TABLE */
  80137. #ifdef BYFOUR
  80138. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80139. u4 endian;
  80140. endian = 1;
  80141. if (*((unsigned char *)(&endian)))
  80142. return crc32_little(crc, buf, len);
  80143. else
  80144. return crc32_big(crc, buf, len);
  80145. }
  80146. #endif /* BYFOUR */
  80147. crc = crc ^ 0xffffffffUL;
  80148. while (len >= 8) {
  80149. DO8;
  80150. len -= 8;
  80151. }
  80152. if (len) do {
  80153. DO1;
  80154. } while (--len);
  80155. return crc ^ 0xffffffffUL;
  80156. }
  80157. #ifdef BYFOUR
  80158. /* ========================================================================= */
  80159. #define DOLIT4 c ^= *buf4++; \
  80160. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80161. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80162. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80163. /* ========================================================================= */
  80164. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80165. {
  80166. register u4 c;
  80167. register const u4 FAR *buf4;
  80168. c = (u4)crc;
  80169. c = ~c;
  80170. while (len && ((ptrdiff_t)buf & 3)) {
  80171. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80172. len--;
  80173. }
  80174. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80175. while (len >= 32) {
  80176. DOLIT32;
  80177. len -= 32;
  80178. }
  80179. while (len >= 4) {
  80180. DOLIT4;
  80181. len -= 4;
  80182. }
  80183. buf = (const unsigned char FAR *)buf4;
  80184. if (len) do {
  80185. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80186. } while (--len);
  80187. c = ~c;
  80188. return (unsigned long)c;
  80189. }
  80190. /* ========================================================================= */
  80191. #define DOBIG4 c ^= *++buf4; \
  80192. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80193. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80194. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80195. /* ========================================================================= */
  80196. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80197. {
  80198. register u4 c;
  80199. register const u4 FAR *buf4;
  80200. c = REV((u4)crc);
  80201. c = ~c;
  80202. while (len && ((ptrdiff_t)buf & 3)) {
  80203. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80204. len--;
  80205. }
  80206. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80207. buf4--;
  80208. while (len >= 32) {
  80209. DOBIG32;
  80210. len -= 32;
  80211. }
  80212. while (len >= 4) {
  80213. DOBIG4;
  80214. len -= 4;
  80215. }
  80216. buf4++;
  80217. buf = (const unsigned char FAR *)buf4;
  80218. if (len) do {
  80219. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80220. } while (--len);
  80221. c = ~c;
  80222. return (unsigned long)(REV(c));
  80223. }
  80224. #endif /* BYFOUR */
  80225. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80226. /* ========================================================================= */
  80227. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80228. {
  80229. unsigned long sum;
  80230. sum = 0;
  80231. while (vec) {
  80232. if (vec & 1)
  80233. sum ^= *mat;
  80234. vec >>= 1;
  80235. mat++;
  80236. }
  80237. return sum;
  80238. }
  80239. /* ========================================================================= */
  80240. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80241. {
  80242. int n;
  80243. for (n = 0; n < GF2_DIM; n++)
  80244. square[n] = gf2_matrix_times(mat, mat[n]);
  80245. }
  80246. /* ========================================================================= */
  80247. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80248. {
  80249. int n;
  80250. unsigned long row;
  80251. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  80252. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  80253. /* degenerate case */
  80254. if (len2 == 0)
  80255. return crc1;
  80256. /* put operator for one zero bit in odd */
  80257. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  80258. row = 1;
  80259. for (n = 1; n < GF2_DIM; n++) {
  80260. odd[n] = row;
  80261. row <<= 1;
  80262. }
  80263. /* put operator for two zero bits in even */
  80264. gf2_matrix_square(even, odd);
  80265. /* put operator for four zero bits in odd */
  80266. gf2_matrix_square(odd, even);
  80267. /* apply len2 zeros to crc1 (first square will put the operator for one
  80268. zero byte, eight zero bits, in even) */
  80269. do {
  80270. /* apply zeros operator for this bit of len2 */
  80271. gf2_matrix_square(even, odd);
  80272. if (len2 & 1)
  80273. crc1 = gf2_matrix_times(even, crc1);
  80274. len2 >>= 1;
  80275. /* if no more bits set, then done */
  80276. if (len2 == 0)
  80277. break;
  80278. /* another iteration of the loop with odd and even swapped */
  80279. gf2_matrix_square(odd, even);
  80280. if (len2 & 1)
  80281. crc1 = gf2_matrix_times(odd, crc1);
  80282. len2 >>= 1;
  80283. /* if no more bits set, then done */
  80284. } while (len2 != 0);
  80285. /* return combined crc */
  80286. crc1 ^= crc2;
  80287. return crc1;
  80288. }
  80289. /*** End of inlined file: crc32.c ***/
  80290. /*** Start of inlined file: deflate.c ***/
  80291. /*
  80292. * ALGORITHM
  80293. *
  80294. * The "deflation" process depends on being able to identify portions
  80295. * of the input text which are identical to earlier input (within a
  80296. * sliding window trailing behind the input currently being processed).
  80297. *
  80298. * The most straightforward technique turns out to be the fastest for
  80299. * most input files: try all possible matches and select the longest.
  80300. * The key feature of this algorithm is that insertions into the string
  80301. * dictionary are very simple and thus fast, and deletions are avoided
  80302. * completely. Insertions are performed at each input character, whereas
  80303. * string matches are performed only when the previous match ends. So it
  80304. * is preferable to spend more time in matches to allow very fast string
  80305. * insertions and avoid deletions. The matching algorithm for small
  80306. * strings is inspired from that of Rabin & Karp. A brute force approach
  80307. * is used to find longer strings when a small match has been found.
  80308. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80309. * (by Leonid Broukhis).
  80310. * A previous version of this file used a more sophisticated algorithm
  80311. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80312. * time, but has a larger average cost, uses more memory and is patented.
  80313. * However the F&G algorithm may be faster for some highly redundant
  80314. * files if the parameter max_chain_length (described below) is too large.
  80315. *
  80316. * ACKNOWLEDGEMENTS
  80317. *
  80318. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80319. * I found it in 'freeze' written by Leonid Broukhis.
  80320. * Thanks to many people for bug reports and testing.
  80321. *
  80322. * REFERENCES
  80323. *
  80324. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80325. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80326. *
  80327. * A description of the Rabin and Karp algorithm is given in the book
  80328. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80329. *
  80330. * Fiala,E.R., and Greene,D.H.
  80331. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80332. *
  80333. */
  80334. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80335. /*** Start of inlined file: deflate.h ***/
  80336. /* WARNING: this file should *not* be used by applications. It is
  80337. part of the implementation of the compression library and is
  80338. subject to change. Applications should only use zlib.h.
  80339. */
  80340. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80341. #ifndef DEFLATE_H
  80342. #define DEFLATE_H
  80343. /* define NO_GZIP when compiling if you want to disable gzip header and
  80344. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80345. the crc code when it is not needed. For shared libraries, gzip encoding
  80346. should be left enabled. */
  80347. #ifndef NO_GZIP
  80348. # define GZIP
  80349. #endif
  80350. #define NO_DUMMY_DECL
  80351. /* ===========================================================================
  80352. * Internal compression state.
  80353. */
  80354. #define LENGTH_CODES 29
  80355. /* number of length codes, not counting the special END_BLOCK code */
  80356. #define LITERALS 256
  80357. /* number of literal bytes 0..255 */
  80358. #define L_CODES (LITERALS+1+LENGTH_CODES)
  80359. /* number of Literal or Length codes, including the END_BLOCK code */
  80360. #define D_CODES 30
  80361. /* number of distance codes */
  80362. #define BL_CODES 19
  80363. /* number of codes used to transfer the bit lengths */
  80364. #define HEAP_SIZE (2*L_CODES+1)
  80365. /* maximum heap size */
  80366. #define MAX_BITS 15
  80367. /* All codes must not exceed MAX_BITS bits */
  80368. #define INIT_STATE 42
  80369. #define EXTRA_STATE 69
  80370. #define NAME_STATE 73
  80371. #define COMMENT_STATE 91
  80372. #define HCRC_STATE 103
  80373. #define BUSY_STATE 113
  80374. #define FINISH_STATE 666
  80375. /* Stream status */
  80376. /* Data structure describing a single value and its code string. */
  80377. typedef struct ct_data_s {
  80378. union {
  80379. ush freq; /* frequency count */
  80380. ush code; /* bit string */
  80381. } fc;
  80382. union {
  80383. ush dad; /* father node in Huffman tree */
  80384. ush len; /* length of bit string */
  80385. } dl;
  80386. } FAR ct_data;
  80387. #define Freq fc.freq
  80388. #define Code fc.code
  80389. #define Dad dl.dad
  80390. #define Len dl.len
  80391. typedef struct static_tree_desc_s static_tree_desc;
  80392. typedef struct tree_desc_s {
  80393. ct_data *dyn_tree; /* the dynamic tree */
  80394. int max_code; /* largest code with non zero frequency */
  80395. static_tree_desc *stat_desc; /* the corresponding static tree */
  80396. } FAR tree_desc;
  80397. typedef ush Pos;
  80398. typedef Pos FAR Posf;
  80399. typedef unsigned IPos;
  80400. /* A Pos is an index in the character window. We use short instead of int to
  80401. * save space in the various tables. IPos is used only for parameter passing.
  80402. */
  80403. typedef struct internal_state {
  80404. z_streamp strm; /* pointer back to this zlib stream */
  80405. int status; /* as the name implies */
  80406. Bytef *pending_buf; /* output still pending */
  80407. ulg pending_buf_size; /* size of pending_buf */
  80408. Bytef *pending_out; /* next pending byte to output to the stream */
  80409. uInt pending; /* nb of bytes in the pending buffer */
  80410. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  80411. gz_headerp gzhead; /* gzip header information to write */
  80412. uInt gzindex; /* where in extra, name, or comment */
  80413. Byte method; /* STORED (for zip only) or DEFLATED */
  80414. int last_flush; /* value of flush param for previous deflate call */
  80415. /* used by deflate.c: */
  80416. uInt w_size; /* LZ77 window size (32K by default) */
  80417. uInt w_bits; /* log2(w_size) (8..16) */
  80418. uInt w_mask; /* w_size - 1 */
  80419. Bytef *window;
  80420. /* Sliding window. Input bytes are read into the second half of the window,
  80421. * and move to the first half later to keep a dictionary of at least wSize
  80422. * bytes. With this organization, matches are limited to a distance of
  80423. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  80424. * performed with a length multiple of the block size. Also, it limits
  80425. * the window size to 64K, which is quite useful on MSDOS.
  80426. * To do: use the user input buffer as sliding window.
  80427. */
  80428. ulg window_size;
  80429. /* Actual size of window: 2*wSize, except when the user input buffer
  80430. * is directly used as sliding window.
  80431. */
  80432. Posf *prev;
  80433. /* Link to older string with same hash index. To limit the size of this
  80434. * array to 64K, this link is maintained only for the last 32K strings.
  80435. * An index in this array is thus a window index modulo 32K.
  80436. */
  80437. Posf *head; /* Heads of the hash chains or NIL. */
  80438. uInt ins_h; /* hash index of string to be inserted */
  80439. uInt hash_size; /* number of elements in hash table */
  80440. uInt hash_bits; /* log2(hash_size) */
  80441. uInt hash_mask; /* hash_size-1 */
  80442. uInt hash_shift;
  80443. /* Number of bits by which ins_h must be shifted at each input
  80444. * step. It must be such that after MIN_MATCH steps, the oldest
  80445. * byte no longer takes part in the hash key, that is:
  80446. * hash_shift * MIN_MATCH >= hash_bits
  80447. */
  80448. long block_start;
  80449. /* Window position at the beginning of the current output block. Gets
  80450. * negative when the window is moved backwards.
  80451. */
  80452. uInt match_length; /* length of best match */
  80453. IPos prev_match; /* previous match */
  80454. int match_available; /* set if previous match exists */
  80455. uInt strstart; /* start of string to insert */
  80456. uInt match_start; /* start of matching string */
  80457. uInt lookahead; /* number of valid bytes ahead in window */
  80458. uInt prev_length;
  80459. /* Length of the best match at previous step. Matches not greater than this
  80460. * are discarded. This is used in the lazy match evaluation.
  80461. */
  80462. uInt max_chain_length;
  80463. /* To speed up deflation, hash chains are never searched beyond this
  80464. * length. A higher limit improves compression ratio but degrades the
  80465. * speed.
  80466. */
  80467. uInt max_lazy_match;
  80468. /* Attempt to find a better match only when the current match is strictly
  80469. * smaller than this value. This mechanism is used only for compression
  80470. * levels >= 4.
  80471. */
  80472. # define max_insert_length max_lazy_match
  80473. /* Insert new strings in the hash table only if the match length is not
  80474. * greater than this length. This saves time but degrades compression.
  80475. * max_insert_length is used only for compression levels <= 3.
  80476. */
  80477. int level; /* compression level (1..9) */
  80478. int strategy; /* favor or force Huffman coding*/
  80479. uInt good_match;
  80480. /* Use a faster search when the previous match is longer than this */
  80481. int nice_match; /* Stop searching when current match exceeds this */
  80482. /* used by trees.c: */
  80483. /* Didn't use ct_data typedef below to supress compiler warning */
  80484. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  80485. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  80486. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  80487. struct tree_desc_s l_desc; /* desc. for literal tree */
  80488. struct tree_desc_s d_desc; /* desc. for distance tree */
  80489. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  80490. ush bl_count[MAX_BITS+1];
  80491. /* number of codes at each bit length for an optimal tree */
  80492. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  80493. int heap_len; /* number of elements in the heap */
  80494. int heap_max; /* element of largest frequency */
  80495. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  80496. * The same heap array is used to build all trees.
  80497. */
  80498. uch depth[2*L_CODES+1];
  80499. /* Depth of each subtree used as tie breaker for trees of equal frequency
  80500. */
  80501. uchf *l_buf; /* buffer for literals or lengths */
  80502. uInt lit_bufsize;
  80503. /* Size of match buffer for literals/lengths. There are 4 reasons for
  80504. * limiting lit_bufsize to 64K:
  80505. * - frequencies can be kept in 16 bit counters
  80506. * - if compression is not successful for the first block, all input
  80507. * data is still in the window so we can still emit a stored block even
  80508. * when input comes from standard input. (This can also be done for
  80509. * all blocks if lit_bufsize is not greater than 32K.)
  80510. * - if compression is not successful for a file smaller than 64K, we can
  80511. * even emit a stored file instead of a stored block (saving 5 bytes).
  80512. * This is applicable only for zip (not gzip or zlib).
  80513. * - creating new Huffman trees less frequently may not provide fast
  80514. * adaptation to changes in the input data statistics. (Take for
  80515. * example a binary file with poorly compressible code followed by
  80516. * a highly compressible string table.) Smaller buffer sizes give
  80517. * fast adaptation but have of course the overhead of transmitting
  80518. * trees more frequently.
  80519. * - I can't count above 4
  80520. */
  80521. uInt last_lit; /* running index in l_buf */
  80522. ushf *d_buf;
  80523. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  80524. * the same number of elements. To use different lengths, an extra flag
  80525. * array would be necessary.
  80526. */
  80527. ulg opt_len; /* bit length of current block with optimal trees */
  80528. ulg static_len; /* bit length of current block with static trees */
  80529. uInt matches; /* number of string matches in current block */
  80530. int last_eob_len; /* bit length of EOB code for last block */
  80531. #ifdef DEBUG
  80532. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  80533. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  80534. #endif
  80535. ush bi_buf;
  80536. /* Output buffer. bits are inserted starting at the bottom (least
  80537. * significant bits).
  80538. */
  80539. int bi_valid;
  80540. /* Number of valid bits in bi_buf. All bits above the last valid bit
  80541. * are always zero.
  80542. */
  80543. } FAR deflate_state;
  80544. /* Output a byte on the stream.
  80545. * IN assertion: there is enough room in pending_buf.
  80546. */
  80547. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  80548. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80549. /* Minimum amount of lookahead, except at the end of the input file.
  80550. * See deflate.c for comments about the MIN_MATCH+1.
  80551. */
  80552. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  80553. /* In order to simplify the code, particularly on 16 bit machines, match
  80554. * distances are limited to MAX_DIST instead of WSIZE.
  80555. */
  80556. /* in trees.c */
  80557. void _tr_init OF((deflate_state *s));
  80558. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  80559. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80560. int eof));
  80561. void _tr_align OF((deflate_state *s));
  80562. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80563. int eof));
  80564. #define d_code(dist) \
  80565. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  80566. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  80567. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  80568. * used.
  80569. */
  80570. #ifndef DEBUG
  80571. /* Inline versions of _tr_tally for speed: */
  80572. #if defined(GEN_TREES_H) || !defined(STDC)
  80573. extern uch _length_code[];
  80574. extern uch _dist_code[];
  80575. #else
  80576. extern const uch _length_code[];
  80577. extern const uch _dist_code[];
  80578. #endif
  80579. # define _tr_tally_lit(s, c, flush) \
  80580. { uch cc = (c); \
  80581. s->d_buf[s->last_lit] = 0; \
  80582. s->l_buf[s->last_lit++] = cc; \
  80583. s->dyn_ltree[cc].Freq++; \
  80584. flush = (s->last_lit == s->lit_bufsize-1); \
  80585. }
  80586. # define _tr_tally_dist(s, distance, length, flush) \
  80587. { uch len = (length); \
  80588. ush dist = (distance); \
  80589. s->d_buf[s->last_lit] = dist; \
  80590. s->l_buf[s->last_lit++] = len; \
  80591. dist--; \
  80592. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  80593. s->dyn_dtree[d_code(dist)].Freq++; \
  80594. flush = (s->last_lit == s->lit_bufsize-1); \
  80595. }
  80596. #else
  80597. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  80598. # define _tr_tally_dist(s, distance, length, flush) \
  80599. flush = _tr_tally(s, distance, length)
  80600. #endif
  80601. #endif /* DEFLATE_H */
  80602. /*** End of inlined file: deflate.h ***/
  80603. const char deflate_copyright[] =
  80604. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  80605. /*
  80606. If you use the zlib library in a product, an acknowledgment is welcome
  80607. in the documentation of your product. If for some reason you cannot
  80608. include such an acknowledgment, I would appreciate that you keep this
  80609. copyright string in the executable of your product.
  80610. */
  80611. /* ===========================================================================
  80612. * Function prototypes.
  80613. */
  80614. typedef enum {
  80615. need_more, /* block not completed, need more input or more output */
  80616. block_done, /* block flush performed */
  80617. finish_started, /* finish started, need only more output at next deflate */
  80618. finish_done /* finish done, accept no more input or output */
  80619. } block_state;
  80620. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  80621. /* Compression function. Returns the block state after the call. */
  80622. local void fill_window OF((deflate_state *s));
  80623. local block_state deflate_stored OF((deflate_state *s, int flush));
  80624. local block_state deflate_fast OF((deflate_state *s, int flush));
  80625. #ifndef FASTEST
  80626. local block_state deflate_slow OF((deflate_state *s, int flush));
  80627. #endif
  80628. local void lm_init OF((deflate_state *s));
  80629. local void putShortMSB OF((deflate_state *s, uInt b));
  80630. local void flush_pending OF((z_streamp strm));
  80631. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  80632. #ifndef FASTEST
  80633. #ifdef ASMV
  80634. void match_init OF((void)); /* asm code initialization */
  80635. uInt longest_match OF((deflate_state *s, IPos cur_match));
  80636. #else
  80637. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  80638. #endif
  80639. #endif
  80640. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  80641. #ifdef DEBUG
  80642. local void check_match OF((deflate_state *s, IPos start, IPos match,
  80643. int length));
  80644. #endif
  80645. /* ===========================================================================
  80646. * Local data
  80647. */
  80648. #define NIL 0
  80649. /* Tail of hash chains */
  80650. #ifndef TOO_FAR
  80651. # define TOO_FAR 4096
  80652. #endif
  80653. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  80654. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80655. /* Minimum amount of lookahead, except at the end of the input file.
  80656. * See deflate.c for comments about the MIN_MATCH+1.
  80657. */
  80658. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  80659. * the desired pack level (0..9). The values given below have been tuned to
  80660. * exclude worst case performance for pathological files. Better values may be
  80661. * found for specific files.
  80662. */
  80663. typedef struct config_s {
  80664. ush good_length; /* reduce lazy search above this match length */
  80665. ush max_lazy; /* do not perform lazy search above this match length */
  80666. ush nice_length; /* quit search above this match length */
  80667. ush max_chain;
  80668. compress_func func;
  80669. } config;
  80670. #ifdef FASTEST
  80671. local const config configuration_table[2] = {
  80672. /* good lazy nice chain */
  80673. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80674. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  80675. #else
  80676. local const config configuration_table[10] = {
  80677. /* good lazy nice chain */
  80678. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80679. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  80680. /* 2 */ {4, 5, 16, 8, deflate_fast},
  80681. /* 3 */ {4, 6, 32, 32, deflate_fast},
  80682. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  80683. /* 5 */ {8, 16, 32, 32, deflate_slow},
  80684. /* 6 */ {8, 16, 128, 128, deflate_slow},
  80685. /* 7 */ {8, 32, 128, 256, deflate_slow},
  80686. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  80687. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  80688. #endif
  80689. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  80690. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  80691. * meaning.
  80692. */
  80693. #define EQUAL 0
  80694. /* result of memcmp for equal strings */
  80695. #ifndef NO_DUMMY_DECL
  80696. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  80697. #endif
  80698. /* ===========================================================================
  80699. * Update a hash value with the given input byte
  80700. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  80701. * input characters, so that a running hash key can be computed from the
  80702. * previous key instead of complete recalculation each time.
  80703. */
  80704. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  80705. /* ===========================================================================
  80706. * Insert string str in the dictionary and set match_head to the previous head
  80707. * of the hash chain (the most recent string with same hash key). Return
  80708. * the previous length of the hash chain.
  80709. * If this file is compiled with -DFASTEST, the compression level is forced
  80710. * to 1, and no hash chains are maintained.
  80711. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  80712. * input characters and the first MIN_MATCH bytes of str are valid
  80713. * (except for the last MIN_MATCH-1 bytes of the input file).
  80714. */
  80715. #ifdef FASTEST
  80716. #define INSERT_STRING(s, str, match_head) \
  80717. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80718. match_head = s->head[s->ins_h], \
  80719. s->head[s->ins_h] = (Pos)(str))
  80720. #else
  80721. #define INSERT_STRING(s, str, match_head) \
  80722. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80723. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  80724. s->head[s->ins_h] = (Pos)(str))
  80725. #endif
  80726. /* ===========================================================================
  80727. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  80728. * prev[] will be initialized on the fly.
  80729. */
  80730. #define CLEAR_HASH(s) \
  80731. s->head[s->hash_size-1] = NIL; \
  80732. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  80733. /* ========================================================================= */
  80734. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  80735. {
  80736. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  80737. Z_DEFAULT_STRATEGY, version, stream_size);
  80738. /* To do: ignore strm->next_in if we use it as window */
  80739. }
  80740. /* ========================================================================= */
  80741. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  80742. {
  80743. deflate_state *s;
  80744. int wrap = 1;
  80745. static const char my_version[] = ZLIB_VERSION;
  80746. ushf *overlay;
  80747. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  80748. * output size for (length,distance) codes is <= 24 bits.
  80749. */
  80750. if (version == Z_NULL || version[0] != my_version[0] ||
  80751. stream_size != sizeof(z_stream)) {
  80752. return Z_VERSION_ERROR;
  80753. }
  80754. if (strm == Z_NULL) return Z_STREAM_ERROR;
  80755. strm->msg = Z_NULL;
  80756. if (strm->zalloc == (alloc_func)0) {
  80757. strm->zalloc = zcalloc;
  80758. strm->opaque = (voidpf)0;
  80759. }
  80760. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  80761. #ifdef FASTEST
  80762. if (level != 0) level = 1;
  80763. #else
  80764. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  80765. #endif
  80766. if (windowBits < 0) { /* suppress zlib wrapper */
  80767. wrap = 0;
  80768. windowBits = -windowBits;
  80769. }
  80770. #ifdef GZIP
  80771. else if (windowBits > 15) {
  80772. wrap = 2; /* write gzip wrapper instead */
  80773. windowBits -= 16;
  80774. }
  80775. #endif
  80776. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  80777. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  80778. strategy < 0 || strategy > Z_FIXED) {
  80779. return Z_STREAM_ERROR;
  80780. }
  80781. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  80782. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  80783. if (s == Z_NULL) return Z_MEM_ERROR;
  80784. strm->state = (struct internal_state FAR *)s;
  80785. s->strm = strm;
  80786. s->wrap = wrap;
  80787. s->gzhead = Z_NULL;
  80788. s->w_bits = windowBits;
  80789. s->w_size = 1 << s->w_bits;
  80790. s->w_mask = s->w_size - 1;
  80791. s->hash_bits = memLevel + 7;
  80792. s->hash_size = 1 << s->hash_bits;
  80793. s->hash_mask = s->hash_size - 1;
  80794. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  80795. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  80796. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  80797. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  80798. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  80799. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  80800. s->pending_buf = (uchf *) overlay;
  80801. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  80802. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  80803. s->pending_buf == Z_NULL) {
  80804. s->status = FINISH_STATE;
  80805. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  80806. deflateEnd (strm);
  80807. return Z_MEM_ERROR;
  80808. }
  80809. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  80810. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  80811. s->level = level;
  80812. s->strategy = strategy;
  80813. s->method = (Byte)method;
  80814. return deflateReset(strm);
  80815. }
  80816. /* ========================================================================= */
  80817. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  80818. {
  80819. deflate_state *s;
  80820. uInt length = dictLength;
  80821. uInt n;
  80822. IPos hash_head = 0;
  80823. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  80824. strm->state->wrap == 2 ||
  80825. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  80826. return Z_STREAM_ERROR;
  80827. s = strm->state;
  80828. if (s->wrap)
  80829. strm->adler = adler32(strm->adler, dictionary, dictLength);
  80830. if (length < MIN_MATCH) return Z_OK;
  80831. if (length > MAX_DIST(s)) {
  80832. length = MAX_DIST(s);
  80833. dictionary += dictLength - length; /* use the tail of the dictionary */
  80834. }
  80835. zmemcpy(s->window, dictionary, length);
  80836. s->strstart = length;
  80837. s->block_start = (long)length;
  80838. /* Insert all strings in the hash table (except for the last two bytes).
  80839. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  80840. * call of fill_window.
  80841. */
  80842. s->ins_h = s->window[0];
  80843. UPDATE_HASH(s, s->ins_h, s->window[1]);
  80844. for (n = 0; n <= length - MIN_MATCH; n++) {
  80845. INSERT_STRING(s, n, hash_head);
  80846. }
  80847. if (hash_head) hash_head = 0; /* to make compiler happy */
  80848. return Z_OK;
  80849. }
  80850. /* ========================================================================= */
  80851. int ZEXPORT deflateReset (z_streamp strm)
  80852. {
  80853. deflate_state *s;
  80854. if (strm == Z_NULL || strm->state == Z_NULL ||
  80855. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  80856. return Z_STREAM_ERROR;
  80857. }
  80858. strm->total_in = strm->total_out = 0;
  80859. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  80860. strm->data_type = Z_UNKNOWN;
  80861. s = (deflate_state *)strm->state;
  80862. s->pending = 0;
  80863. s->pending_out = s->pending_buf;
  80864. if (s->wrap < 0) {
  80865. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  80866. }
  80867. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  80868. strm->adler =
  80869. #ifdef GZIP
  80870. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  80871. #endif
  80872. adler32(0L, Z_NULL, 0);
  80873. s->last_flush = Z_NO_FLUSH;
  80874. _tr_init(s);
  80875. lm_init(s);
  80876. return Z_OK;
  80877. }
  80878. /* ========================================================================= */
  80879. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  80880. {
  80881. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80882. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  80883. strm->state->gzhead = head;
  80884. return Z_OK;
  80885. }
  80886. /* ========================================================================= */
  80887. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  80888. {
  80889. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80890. strm->state->bi_valid = bits;
  80891. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  80892. return Z_OK;
  80893. }
  80894. /* ========================================================================= */
  80895. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  80896. {
  80897. deflate_state *s;
  80898. compress_func func;
  80899. int err = Z_OK;
  80900. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80901. s = strm->state;
  80902. #ifdef FASTEST
  80903. if (level != 0) level = 1;
  80904. #else
  80905. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  80906. #endif
  80907. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  80908. return Z_STREAM_ERROR;
  80909. }
  80910. func = configuration_table[s->level].func;
  80911. if (func != configuration_table[level].func && strm->total_in != 0) {
  80912. /* Flush the last buffer: */
  80913. err = deflate(strm, Z_PARTIAL_FLUSH);
  80914. }
  80915. if (s->level != level) {
  80916. s->level = level;
  80917. s->max_lazy_match = configuration_table[level].max_lazy;
  80918. s->good_match = configuration_table[level].good_length;
  80919. s->nice_match = configuration_table[level].nice_length;
  80920. s->max_chain_length = configuration_table[level].max_chain;
  80921. }
  80922. s->strategy = strategy;
  80923. return err;
  80924. }
  80925. /* ========================================================================= */
  80926. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  80927. {
  80928. deflate_state *s;
  80929. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80930. s = strm->state;
  80931. s->good_match = good_length;
  80932. s->max_lazy_match = max_lazy;
  80933. s->nice_match = nice_length;
  80934. s->max_chain_length = max_chain;
  80935. return Z_OK;
  80936. }
  80937. /* =========================================================================
  80938. * For the default windowBits of 15 and memLevel of 8, this function returns
  80939. * a close to exact, as well as small, upper bound on the compressed size.
  80940. * They are coded as constants here for a reason--if the #define's are
  80941. * changed, then this function needs to be changed as well. The return
  80942. * value for 15 and 8 only works for those exact settings.
  80943. *
  80944. * For any setting other than those defaults for windowBits and memLevel,
  80945. * the value returned is a conservative worst case for the maximum expansion
  80946. * resulting from using fixed blocks instead of stored blocks, which deflate
  80947. * can emit on compressed data for some combinations of the parameters.
  80948. *
  80949. * This function could be more sophisticated to provide closer upper bounds
  80950. * for every combination of windowBits and memLevel, as well as wrap.
  80951. * But even the conservative upper bound of about 14% expansion does not
  80952. * seem onerous for output buffer allocation.
  80953. */
  80954. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  80955. {
  80956. deflate_state *s;
  80957. uLong destLen;
  80958. /* conservative upper bound */
  80959. destLen = sourceLen +
  80960. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  80961. /* if can't get parameters, return conservative bound */
  80962. if (strm == Z_NULL || strm->state == Z_NULL)
  80963. return destLen;
  80964. /* if not default parameters, return conservative bound */
  80965. s = strm->state;
  80966. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  80967. return destLen;
  80968. /* default settings: return tight bound for that case */
  80969. return compressBound(sourceLen);
  80970. }
  80971. /* =========================================================================
  80972. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  80973. * IN assertion: the stream state is correct and there is enough room in
  80974. * pending_buf.
  80975. */
  80976. local void putShortMSB (deflate_state *s, uInt b)
  80977. {
  80978. put_byte(s, (Byte)(b >> 8));
  80979. put_byte(s, (Byte)(b & 0xff));
  80980. }
  80981. /* =========================================================================
  80982. * Flush as much pending output as possible. All deflate() output goes
  80983. * through this function so some applications may wish to modify it
  80984. * to avoid allocating a large strm->next_out buffer and copying into it.
  80985. * (See also read_buf()).
  80986. */
  80987. local void flush_pending (z_streamp strm)
  80988. {
  80989. unsigned len = strm->state->pending;
  80990. if (len > strm->avail_out) len = strm->avail_out;
  80991. if (len == 0) return;
  80992. zmemcpy(strm->next_out, strm->state->pending_out, len);
  80993. strm->next_out += len;
  80994. strm->state->pending_out += len;
  80995. strm->total_out += len;
  80996. strm->avail_out -= len;
  80997. strm->state->pending -= len;
  80998. if (strm->state->pending == 0) {
  80999. strm->state->pending_out = strm->state->pending_buf;
  81000. }
  81001. }
  81002. /* ========================================================================= */
  81003. int ZEXPORT deflate (z_streamp strm, int flush)
  81004. {
  81005. int old_flush; /* value of flush param for previous deflate call */
  81006. deflate_state *s;
  81007. if (strm == Z_NULL || strm->state == Z_NULL ||
  81008. flush > Z_FINISH || flush < 0) {
  81009. return Z_STREAM_ERROR;
  81010. }
  81011. s = strm->state;
  81012. if (strm->next_out == Z_NULL ||
  81013. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81014. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81015. ERR_RETURN(strm, Z_STREAM_ERROR);
  81016. }
  81017. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81018. s->strm = strm; /* just in case */
  81019. old_flush = s->last_flush;
  81020. s->last_flush = flush;
  81021. /* Write the header */
  81022. if (s->status == INIT_STATE) {
  81023. #ifdef GZIP
  81024. if (s->wrap == 2) {
  81025. strm->adler = crc32(0L, Z_NULL, 0);
  81026. put_byte(s, 31);
  81027. put_byte(s, 139);
  81028. put_byte(s, 8);
  81029. if (s->gzhead == NULL) {
  81030. put_byte(s, 0);
  81031. put_byte(s, 0);
  81032. put_byte(s, 0);
  81033. put_byte(s, 0);
  81034. put_byte(s, 0);
  81035. put_byte(s, s->level == 9 ? 2 :
  81036. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81037. 4 : 0));
  81038. put_byte(s, OS_CODE);
  81039. s->status = BUSY_STATE;
  81040. }
  81041. else {
  81042. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81043. (s->gzhead->hcrc ? 2 : 0) +
  81044. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81045. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81046. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81047. );
  81048. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81049. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81050. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81051. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81052. put_byte(s, s->level == 9 ? 2 :
  81053. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81054. 4 : 0));
  81055. put_byte(s, s->gzhead->os & 0xff);
  81056. if (s->gzhead->extra != NULL) {
  81057. put_byte(s, s->gzhead->extra_len & 0xff);
  81058. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81059. }
  81060. if (s->gzhead->hcrc)
  81061. strm->adler = crc32(strm->adler, s->pending_buf,
  81062. s->pending);
  81063. s->gzindex = 0;
  81064. s->status = EXTRA_STATE;
  81065. }
  81066. }
  81067. else
  81068. #endif
  81069. {
  81070. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81071. uInt level_flags;
  81072. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81073. level_flags = 0;
  81074. else if (s->level < 6)
  81075. level_flags = 1;
  81076. else if (s->level == 6)
  81077. level_flags = 2;
  81078. else
  81079. level_flags = 3;
  81080. header |= (level_flags << 6);
  81081. if (s->strstart != 0) header |= PRESET_DICT;
  81082. header += 31 - (header % 31);
  81083. s->status = BUSY_STATE;
  81084. putShortMSB(s, header);
  81085. /* Save the adler32 of the preset dictionary: */
  81086. if (s->strstart != 0) {
  81087. putShortMSB(s, (uInt)(strm->adler >> 16));
  81088. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81089. }
  81090. strm->adler = adler32(0L, Z_NULL, 0);
  81091. }
  81092. }
  81093. #ifdef GZIP
  81094. if (s->status == EXTRA_STATE) {
  81095. if (s->gzhead->extra != NULL) {
  81096. uInt beg = s->pending; /* start of bytes to update crc */
  81097. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81098. if (s->pending == s->pending_buf_size) {
  81099. if (s->gzhead->hcrc && s->pending > beg)
  81100. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81101. s->pending - beg);
  81102. flush_pending(strm);
  81103. beg = s->pending;
  81104. if (s->pending == s->pending_buf_size)
  81105. break;
  81106. }
  81107. put_byte(s, s->gzhead->extra[s->gzindex]);
  81108. s->gzindex++;
  81109. }
  81110. if (s->gzhead->hcrc && s->pending > beg)
  81111. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81112. s->pending - beg);
  81113. if (s->gzindex == s->gzhead->extra_len) {
  81114. s->gzindex = 0;
  81115. s->status = NAME_STATE;
  81116. }
  81117. }
  81118. else
  81119. s->status = NAME_STATE;
  81120. }
  81121. if (s->status == NAME_STATE) {
  81122. if (s->gzhead->name != NULL) {
  81123. uInt beg = s->pending; /* start of bytes to update crc */
  81124. int val;
  81125. do {
  81126. if (s->pending == s->pending_buf_size) {
  81127. if (s->gzhead->hcrc && s->pending > beg)
  81128. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81129. s->pending - beg);
  81130. flush_pending(strm);
  81131. beg = s->pending;
  81132. if (s->pending == s->pending_buf_size) {
  81133. val = 1;
  81134. break;
  81135. }
  81136. }
  81137. val = s->gzhead->name[s->gzindex++];
  81138. put_byte(s, val);
  81139. } while (val != 0);
  81140. if (s->gzhead->hcrc && s->pending > beg)
  81141. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81142. s->pending - beg);
  81143. if (val == 0) {
  81144. s->gzindex = 0;
  81145. s->status = COMMENT_STATE;
  81146. }
  81147. }
  81148. else
  81149. s->status = COMMENT_STATE;
  81150. }
  81151. if (s->status == COMMENT_STATE) {
  81152. if (s->gzhead->comment != NULL) {
  81153. uInt beg = s->pending; /* start of bytes to update crc */
  81154. int val;
  81155. do {
  81156. if (s->pending == s->pending_buf_size) {
  81157. if (s->gzhead->hcrc && s->pending > beg)
  81158. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81159. s->pending - beg);
  81160. flush_pending(strm);
  81161. beg = s->pending;
  81162. if (s->pending == s->pending_buf_size) {
  81163. val = 1;
  81164. break;
  81165. }
  81166. }
  81167. val = s->gzhead->comment[s->gzindex++];
  81168. put_byte(s, val);
  81169. } while (val != 0);
  81170. if (s->gzhead->hcrc && s->pending > beg)
  81171. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81172. s->pending - beg);
  81173. if (val == 0)
  81174. s->status = HCRC_STATE;
  81175. }
  81176. else
  81177. s->status = HCRC_STATE;
  81178. }
  81179. if (s->status == HCRC_STATE) {
  81180. if (s->gzhead->hcrc) {
  81181. if (s->pending + 2 > s->pending_buf_size)
  81182. flush_pending(strm);
  81183. if (s->pending + 2 <= s->pending_buf_size) {
  81184. put_byte(s, (Byte)(strm->adler & 0xff));
  81185. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81186. strm->adler = crc32(0L, Z_NULL, 0);
  81187. s->status = BUSY_STATE;
  81188. }
  81189. }
  81190. else
  81191. s->status = BUSY_STATE;
  81192. }
  81193. #endif
  81194. /* Flush as much pending output as possible */
  81195. if (s->pending != 0) {
  81196. flush_pending(strm);
  81197. if (strm->avail_out == 0) {
  81198. /* Since avail_out is 0, deflate will be called again with
  81199. * more output space, but possibly with both pending and
  81200. * avail_in equal to zero. There won't be anything to do,
  81201. * but this is not an error situation so make sure we
  81202. * return OK instead of BUF_ERROR at next call of deflate:
  81203. */
  81204. s->last_flush = -1;
  81205. return Z_OK;
  81206. }
  81207. /* Make sure there is something to do and avoid duplicate consecutive
  81208. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81209. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81210. */
  81211. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81212. flush != Z_FINISH) {
  81213. ERR_RETURN(strm, Z_BUF_ERROR);
  81214. }
  81215. /* User must not provide more input after the first FINISH: */
  81216. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81217. ERR_RETURN(strm, Z_BUF_ERROR);
  81218. }
  81219. /* Start a new block or continue the current one.
  81220. */
  81221. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81222. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81223. block_state bstate;
  81224. bstate = (*(configuration_table[s->level].func))(s, flush);
  81225. if (bstate == finish_started || bstate == finish_done) {
  81226. s->status = FINISH_STATE;
  81227. }
  81228. if (bstate == need_more || bstate == finish_started) {
  81229. if (strm->avail_out == 0) {
  81230. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81231. }
  81232. return Z_OK;
  81233. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81234. * of deflate should use the same flush parameter to make sure
  81235. * that the flush is complete. So we don't have to output an
  81236. * empty block here, this will be done at next call. This also
  81237. * ensures that for a very small output buffer, we emit at most
  81238. * one empty block.
  81239. */
  81240. }
  81241. if (bstate == block_done) {
  81242. if (flush == Z_PARTIAL_FLUSH) {
  81243. _tr_align(s);
  81244. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81245. _tr_stored_block(s, (char*)0, 0L, 0);
  81246. /* For a full flush, this empty block will be recognized
  81247. * as a special marker by inflate_sync().
  81248. */
  81249. if (flush == Z_FULL_FLUSH) {
  81250. CLEAR_HASH(s); /* forget history */
  81251. }
  81252. }
  81253. flush_pending(strm);
  81254. if (strm->avail_out == 0) {
  81255. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  81256. return Z_OK;
  81257. }
  81258. }
  81259. }
  81260. Assert(strm->avail_out > 0, "bug2");
  81261. if (flush != Z_FINISH) return Z_OK;
  81262. if (s->wrap <= 0) return Z_STREAM_END;
  81263. /* Write the trailer */
  81264. #ifdef GZIP
  81265. if (s->wrap == 2) {
  81266. put_byte(s, (Byte)(strm->adler & 0xff));
  81267. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81268. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  81269. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  81270. put_byte(s, (Byte)(strm->total_in & 0xff));
  81271. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  81272. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  81273. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  81274. }
  81275. else
  81276. #endif
  81277. {
  81278. putShortMSB(s, (uInt)(strm->adler >> 16));
  81279. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81280. }
  81281. flush_pending(strm);
  81282. /* If avail_out is zero, the application will call deflate again
  81283. * to flush the rest.
  81284. */
  81285. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  81286. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  81287. }
  81288. /* ========================================================================= */
  81289. int ZEXPORT deflateEnd (z_streamp strm)
  81290. {
  81291. int status;
  81292. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81293. status = strm->state->status;
  81294. if (status != INIT_STATE &&
  81295. status != EXTRA_STATE &&
  81296. status != NAME_STATE &&
  81297. status != COMMENT_STATE &&
  81298. status != HCRC_STATE &&
  81299. status != BUSY_STATE &&
  81300. status != FINISH_STATE) {
  81301. return Z_STREAM_ERROR;
  81302. }
  81303. /* Deallocate in reverse order of allocations: */
  81304. TRY_FREE(strm, strm->state->pending_buf);
  81305. TRY_FREE(strm, strm->state->head);
  81306. TRY_FREE(strm, strm->state->prev);
  81307. TRY_FREE(strm, strm->state->window);
  81308. ZFREE(strm, strm->state);
  81309. strm->state = Z_NULL;
  81310. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81311. }
  81312. /* =========================================================================
  81313. * Copy the source state to the destination state.
  81314. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81315. * doesn't have enough memory anyway to duplicate compression states).
  81316. */
  81317. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81318. {
  81319. #ifdef MAXSEG_64K
  81320. return Z_STREAM_ERROR;
  81321. #else
  81322. deflate_state *ds;
  81323. deflate_state *ss;
  81324. ushf *overlay;
  81325. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81326. return Z_STREAM_ERROR;
  81327. }
  81328. ss = source->state;
  81329. zmemcpy(dest, source, sizeof(z_stream));
  81330. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81331. if (ds == Z_NULL) return Z_MEM_ERROR;
  81332. dest->state = (struct internal_state FAR *) ds;
  81333. zmemcpy(ds, ss, sizeof(deflate_state));
  81334. ds->strm = dest;
  81335. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81336. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81337. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81338. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81339. ds->pending_buf = (uchf *) overlay;
  81340. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81341. ds->pending_buf == Z_NULL) {
  81342. deflateEnd (dest);
  81343. return Z_MEM_ERROR;
  81344. }
  81345. /* following zmemcpy do not work for 16-bit MSDOS */
  81346. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81347. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81348. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81349. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81350. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81351. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81352. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81353. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81354. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81355. ds->bl_desc.dyn_tree = ds->bl_tree;
  81356. return Z_OK;
  81357. #endif /* MAXSEG_64K */
  81358. }
  81359. /* ===========================================================================
  81360. * Read a new buffer from the current input stream, update the adler32
  81361. * and total number of bytes read. All deflate() input goes through
  81362. * this function so some applications may wish to modify it to avoid
  81363. * allocating a large strm->next_in buffer and copying from it.
  81364. * (See also flush_pending()).
  81365. */
  81366. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  81367. {
  81368. unsigned len = strm->avail_in;
  81369. if (len > size) len = size;
  81370. if (len == 0) return 0;
  81371. strm->avail_in -= len;
  81372. if (strm->state->wrap == 1) {
  81373. strm->adler = adler32(strm->adler, strm->next_in, len);
  81374. }
  81375. #ifdef GZIP
  81376. else if (strm->state->wrap == 2) {
  81377. strm->adler = crc32(strm->adler, strm->next_in, len);
  81378. }
  81379. #endif
  81380. zmemcpy(buf, strm->next_in, len);
  81381. strm->next_in += len;
  81382. strm->total_in += len;
  81383. return (int)len;
  81384. }
  81385. /* ===========================================================================
  81386. * Initialize the "longest match" routines for a new zlib stream
  81387. */
  81388. local void lm_init (deflate_state *s)
  81389. {
  81390. s->window_size = (ulg)2L*s->w_size;
  81391. CLEAR_HASH(s);
  81392. /* Set the default configuration parameters:
  81393. */
  81394. s->max_lazy_match = configuration_table[s->level].max_lazy;
  81395. s->good_match = configuration_table[s->level].good_length;
  81396. s->nice_match = configuration_table[s->level].nice_length;
  81397. s->max_chain_length = configuration_table[s->level].max_chain;
  81398. s->strstart = 0;
  81399. s->block_start = 0L;
  81400. s->lookahead = 0;
  81401. s->match_length = s->prev_length = MIN_MATCH-1;
  81402. s->match_available = 0;
  81403. s->ins_h = 0;
  81404. #ifndef FASTEST
  81405. #ifdef ASMV
  81406. match_init(); /* initialize the asm code */
  81407. #endif
  81408. #endif
  81409. }
  81410. #ifndef FASTEST
  81411. /* ===========================================================================
  81412. * Set match_start to the longest match starting at the given string and
  81413. * return its length. Matches shorter or equal to prev_length are discarded,
  81414. * in which case the result is equal to prev_length and match_start is
  81415. * garbage.
  81416. * IN assertions: cur_match is the head of the hash chain for the current
  81417. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  81418. * OUT assertion: the match length is not greater than s->lookahead.
  81419. */
  81420. #ifndef ASMV
  81421. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  81422. * match.S. The code will be functionally equivalent.
  81423. */
  81424. local uInt longest_match(deflate_state *s, IPos cur_match)
  81425. {
  81426. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  81427. register Bytef *scan = s->window + s->strstart; /* current string */
  81428. register Bytef *match; /* matched string */
  81429. register int len; /* length of current match */
  81430. int best_len = s->prev_length; /* best match length so far */
  81431. int nice_match = s->nice_match; /* stop if match long enough */
  81432. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  81433. s->strstart - (IPos)MAX_DIST(s) : NIL;
  81434. /* Stop when cur_match becomes <= limit. To simplify the code,
  81435. * we prevent matches with the string of window index 0.
  81436. */
  81437. Posf *prev = s->prev;
  81438. uInt wmask = s->w_mask;
  81439. #ifdef UNALIGNED_OK
  81440. /* Compare two bytes at a time. Note: this is not always beneficial.
  81441. * Try with and without -DUNALIGNED_OK to check.
  81442. */
  81443. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  81444. register ush scan_start = *(ushf*)scan;
  81445. register ush scan_end = *(ushf*)(scan+best_len-1);
  81446. #else
  81447. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81448. register Byte scan_end1 = scan[best_len-1];
  81449. register Byte scan_end = scan[best_len];
  81450. #endif
  81451. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81452. * It is easy to get rid of this optimization if necessary.
  81453. */
  81454. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81455. /* Do not waste too much time if we already have a good match: */
  81456. if (s->prev_length >= s->good_match) {
  81457. chain_length >>= 2;
  81458. }
  81459. /* Do not look for matches beyond the end of the input. This is necessary
  81460. * to make deflate deterministic.
  81461. */
  81462. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  81463. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81464. do {
  81465. Assert(cur_match < s->strstart, "no future");
  81466. match = s->window + cur_match;
  81467. /* Skip to next match if the match length cannot increase
  81468. * or if the match length is less than 2. Note that the checks below
  81469. * for insufficient lookahead only occur occasionally for performance
  81470. * reasons. Therefore uninitialized memory will be accessed, and
  81471. * conditional jumps will be made that depend on those values.
  81472. * However the length of the match is limited to the lookahead, so
  81473. * the output of deflate is not affected by the uninitialized values.
  81474. */
  81475. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  81476. /* This code assumes sizeof(unsigned short) == 2. Do not use
  81477. * UNALIGNED_OK if your compiler uses a different size.
  81478. */
  81479. if (*(ushf*)(match+best_len-1) != scan_end ||
  81480. *(ushf*)match != scan_start) continue;
  81481. /* It is not necessary to compare scan[2] and match[2] since they are
  81482. * always equal when the other bytes match, given that the hash keys
  81483. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  81484. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  81485. * lookahead only every 4th comparison; the 128th check will be made
  81486. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  81487. * necessary to put more guard bytes at the end of the window, or
  81488. * to check more often for insufficient lookahead.
  81489. */
  81490. Assert(scan[2] == match[2], "scan[2]?");
  81491. scan++, match++;
  81492. do {
  81493. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81494. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81495. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81496. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81497. scan < strend);
  81498. /* The funny "do {}" generates better code on most compilers */
  81499. /* Here, scan <= window+strstart+257 */
  81500. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81501. if (*scan == *match) scan++;
  81502. len = (MAX_MATCH - 1) - (int)(strend-scan);
  81503. scan = strend - (MAX_MATCH-1);
  81504. #else /* UNALIGNED_OK */
  81505. if (match[best_len] != scan_end ||
  81506. match[best_len-1] != scan_end1 ||
  81507. *match != *scan ||
  81508. *++match != scan[1]) continue;
  81509. /* The check at best_len-1 can be removed because it will be made
  81510. * again later. (This heuristic is not always a win.)
  81511. * It is not necessary to compare scan[2] and match[2] since they
  81512. * are always equal when the other bytes match, given that
  81513. * the hash keys are equal and that HASH_BITS >= 8.
  81514. */
  81515. scan += 2, match++;
  81516. Assert(*scan == *match, "match[2]?");
  81517. /* We check for insufficient lookahead only every 8th comparison;
  81518. * the 256th check will be made at strstart+258.
  81519. */
  81520. do {
  81521. } while (*++scan == *++match && *++scan == *++match &&
  81522. *++scan == *++match && *++scan == *++match &&
  81523. *++scan == *++match && *++scan == *++match &&
  81524. *++scan == *++match && *++scan == *++match &&
  81525. scan < strend);
  81526. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81527. len = MAX_MATCH - (int)(strend - scan);
  81528. scan = strend - MAX_MATCH;
  81529. #endif /* UNALIGNED_OK */
  81530. if (len > best_len) {
  81531. s->match_start = cur_match;
  81532. best_len = len;
  81533. if (len >= nice_match) break;
  81534. #ifdef UNALIGNED_OK
  81535. scan_end = *(ushf*)(scan+best_len-1);
  81536. #else
  81537. scan_end1 = scan[best_len-1];
  81538. scan_end = scan[best_len];
  81539. #endif
  81540. }
  81541. } while ((cur_match = prev[cur_match & wmask]) > limit
  81542. && --chain_length != 0);
  81543. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  81544. return s->lookahead;
  81545. }
  81546. #endif /* ASMV */
  81547. #endif /* FASTEST */
  81548. /* ---------------------------------------------------------------------------
  81549. * Optimized version for level == 1 or strategy == Z_RLE only
  81550. */
  81551. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  81552. {
  81553. register Bytef *scan = s->window + s->strstart; /* current string */
  81554. register Bytef *match; /* matched string */
  81555. register int len; /* length of current match */
  81556. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81557. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81558. * It is easy to get rid of this optimization if necessary.
  81559. */
  81560. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81561. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81562. Assert(cur_match < s->strstart, "no future");
  81563. match = s->window + cur_match;
  81564. /* Return failure if the match length is less than 2:
  81565. */
  81566. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  81567. /* The check at best_len-1 can be removed because it will be made
  81568. * again later. (This heuristic is not always a win.)
  81569. * It is not necessary to compare scan[2] and match[2] since they
  81570. * are always equal when the other bytes match, given that
  81571. * the hash keys are equal and that HASH_BITS >= 8.
  81572. */
  81573. scan += 2, match += 2;
  81574. Assert(*scan == *match, "match[2]?");
  81575. /* We check for insufficient lookahead only every 8th comparison;
  81576. * the 256th check will be made at strstart+258.
  81577. */
  81578. do {
  81579. } while (*++scan == *++match && *++scan == *++match &&
  81580. *++scan == *++match && *++scan == *++match &&
  81581. *++scan == *++match && *++scan == *++match &&
  81582. *++scan == *++match && *++scan == *++match &&
  81583. scan < strend);
  81584. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81585. len = MAX_MATCH - (int)(strend - scan);
  81586. if (len < MIN_MATCH) return MIN_MATCH - 1;
  81587. s->match_start = cur_match;
  81588. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  81589. }
  81590. #ifdef DEBUG
  81591. /* ===========================================================================
  81592. * Check that the match at match_start is indeed a match.
  81593. */
  81594. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  81595. {
  81596. /* check that the match is indeed a match */
  81597. if (zmemcmp(s->window + match,
  81598. s->window + start, length) != EQUAL) {
  81599. fprintf(stderr, " start %u, match %u, length %d\n",
  81600. start, match, length);
  81601. do {
  81602. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  81603. } while (--length != 0);
  81604. z_error("invalid match");
  81605. }
  81606. if (z_verbose > 1) {
  81607. fprintf(stderr,"\\[%d,%d]", start-match, length);
  81608. do { putc(s->window[start++], stderr); } while (--length != 0);
  81609. }
  81610. }
  81611. #else
  81612. # define check_match(s, start, match, length)
  81613. #endif /* DEBUG */
  81614. /* ===========================================================================
  81615. * Fill the window when the lookahead becomes insufficient.
  81616. * Updates strstart and lookahead.
  81617. *
  81618. * IN assertion: lookahead < MIN_LOOKAHEAD
  81619. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  81620. * At least one byte has been read, or avail_in == 0; reads are
  81621. * performed for at least two bytes (required for the zip translate_eol
  81622. * option -- not supported here).
  81623. */
  81624. local void fill_window (deflate_state *s)
  81625. {
  81626. register unsigned n, m;
  81627. register Posf *p;
  81628. unsigned more; /* Amount of free space at the end of the window. */
  81629. uInt wsize = s->w_size;
  81630. do {
  81631. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  81632. /* Deal with !@#$% 64K limit: */
  81633. if (sizeof(int) <= 2) {
  81634. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  81635. more = wsize;
  81636. } else if (more == (unsigned)(-1)) {
  81637. /* Very unlikely, but possible on 16 bit machine if
  81638. * strstart == 0 && lookahead == 1 (input done a byte at time)
  81639. */
  81640. more--;
  81641. }
  81642. }
  81643. /* If the window is almost full and there is insufficient lookahead,
  81644. * move the upper half to the lower one to make room in the upper half.
  81645. */
  81646. if (s->strstart >= wsize+MAX_DIST(s)) {
  81647. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  81648. s->match_start -= wsize;
  81649. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  81650. s->block_start -= (long) wsize;
  81651. /* Slide the hash table (could be avoided with 32 bit values
  81652. at the expense of memory usage). We slide even when level == 0
  81653. to keep the hash table consistent if we switch back to level > 0
  81654. later. (Using level 0 permanently is not an optimal usage of
  81655. zlib, so we don't care about this pathological case.)
  81656. */
  81657. /* %%% avoid this when Z_RLE */
  81658. n = s->hash_size;
  81659. p = &s->head[n];
  81660. do {
  81661. m = *--p;
  81662. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81663. } while (--n);
  81664. n = wsize;
  81665. #ifndef FASTEST
  81666. p = &s->prev[n];
  81667. do {
  81668. m = *--p;
  81669. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81670. /* If n is not on any hash chain, prev[n] is garbage but
  81671. * its value will never be used.
  81672. */
  81673. } while (--n);
  81674. #endif
  81675. more += wsize;
  81676. }
  81677. if (s->strm->avail_in == 0) return;
  81678. /* If there was no sliding:
  81679. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  81680. * more == window_size - lookahead - strstart
  81681. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  81682. * => more >= window_size - 2*WSIZE + 2
  81683. * In the BIG_MEM or MMAP case (not yet supported),
  81684. * window_size == input_size + MIN_LOOKAHEAD &&
  81685. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  81686. * Otherwise, window_size == 2*WSIZE so more >= 2.
  81687. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  81688. */
  81689. Assert(more >= 2, "more < 2");
  81690. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  81691. s->lookahead += n;
  81692. /* Initialize the hash value now that we have some input: */
  81693. if (s->lookahead >= MIN_MATCH) {
  81694. s->ins_h = s->window[s->strstart];
  81695. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  81696. #if MIN_MATCH != 3
  81697. Call UPDATE_HASH() MIN_MATCH-3 more times
  81698. #endif
  81699. }
  81700. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  81701. * but this is not important since only literal bytes will be emitted.
  81702. */
  81703. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  81704. }
  81705. /* ===========================================================================
  81706. * Flush the current block, with given end-of-file flag.
  81707. * IN assertion: strstart is set to the end of the current match.
  81708. */
  81709. #define FLUSH_BLOCK_ONLY(s, eof) { \
  81710. _tr_flush_block(s, (s->block_start >= 0L ? \
  81711. (charf *)&s->window[(unsigned)s->block_start] : \
  81712. (charf *)Z_NULL), \
  81713. (ulg)((long)s->strstart - s->block_start), \
  81714. (eof)); \
  81715. s->block_start = s->strstart; \
  81716. flush_pending(s->strm); \
  81717. Tracev((stderr,"[FLUSH]")); \
  81718. }
  81719. /* Same but force premature exit if necessary. */
  81720. #define FLUSH_BLOCK(s, eof) { \
  81721. FLUSH_BLOCK_ONLY(s, eof); \
  81722. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  81723. }
  81724. /* ===========================================================================
  81725. * Copy without compression as much as possible from the input stream, return
  81726. * the current block state.
  81727. * This function does not insert new strings in the dictionary since
  81728. * uncompressible data is probably not useful. This function is used
  81729. * only for the level=0 compression option.
  81730. * NOTE: this function should be optimized to avoid extra copying from
  81731. * window to pending_buf.
  81732. */
  81733. local block_state deflate_stored(deflate_state *s, int flush)
  81734. {
  81735. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  81736. * to pending_buf_size, and each stored block has a 5 byte header:
  81737. */
  81738. ulg max_block_size = 0xffff;
  81739. ulg max_start;
  81740. if (max_block_size > s->pending_buf_size - 5) {
  81741. max_block_size = s->pending_buf_size - 5;
  81742. }
  81743. /* Copy as much as possible from input to output: */
  81744. for (;;) {
  81745. /* Fill the window as much as possible: */
  81746. if (s->lookahead <= 1) {
  81747. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  81748. s->block_start >= (long)s->w_size, "slide too late");
  81749. fill_window(s);
  81750. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  81751. if (s->lookahead == 0) break; /* flush the current block */
  81752. }
  81753. Assert(s->block_start >= 0L, "block gone");
  81754. s->strstart += s->lookahead;
  81755. s->lookahead = 0;
  81756. /* Emit a stored block if pending_buf will be full: */
  81757. max_start = s->block_start + max_block_size;
  81758. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  81759. /* strstart == 0 is possible when wraparound on 16-bit machine */
  81760. s->lookahead = (uInt)(s->strstart - max_start);
  81761. s->strstart = (uInt)max_start;
  81762. FLUSH_BLOCK(s, 0);
  81763. }
  81764. /* Flush if we may have to slide, otherwise block_start may become
  81765. * negative and the data will be gone:
  81766. */
  81767. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  81768. FLUSH_BLOCK(s, 0);
  81769. }
  81770. }
  81771. FLUSH_BLOCK(s, flush == Z_FINISH);
  81772. return flush == Z_FINISH ? finish_done : block_done;
  81773. }
  81774. /* ===========================================================================
  81775. * Compress as much as possible from the input stream, return the current
  81776. * block state.
  81777. * This function does not perform lazy evaluation of matches and inserts
  81778. * new strings in the dictionary only for unmatched strings or for short
  81779. * matches. It is used only for the fast compression options.
  81780. */
  81781. local block_state deflate_fast(deflate_state *s, int flush)
  81782. {
  81783. IPos hash_head = NIL; /* head of the hash chain */
  81784. int bflush; /* set if current block must be flushed */
  81785. for (;;) {
  81786. /* Make sure that we always have enough lookahead, except
  81787. * at the end of the input file. We need MAX_MATCH bytes
  81788. * for the next match, plus MIN_MATCH bytes to insert the
  81789. * string following the next match.
  81790. */
  81791. if (s->lookahead < MIN_LOOKAHEAD) {
  81792. fill_window(s);
  81793. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  81794. return need_more;
  81795. }
  81796. if (s->lookahead == 0) break; /* flush the current block */
  81797. }
  81798. /* Insert the string window[strstart .. strstart+2] in the
  81799. * dictionary, and set hash_head to the head of the hash chain:
  81800. */
  81801. if (s->lookahead >= MIN_MATCH) {
  81802. INSERT_STRING(s, s->strstart, hash_head);
  81803. }
  81804. /* Find the longest match, discarding those <= prev_length.
  81805. * At this point we have always match_length < MIN_MATCH
  81806. */
  81807. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  81808. /* To simplify the code, we prevent matches with the string
  81809. * of window index 0 (in particular we have to avoid a match
  81810. * of the string with itself at the start of the input file).
  81811. */
  81812. #ifdef FASTEST
  81813. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  81814. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  81815. s->match_length = longest_match_fast (s, hash_head);
  81816. }
  81817. #else
  81818. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  81819. s->match_length = longest_match (s, hash_head);
  81820. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  81821. s->match_length = longest_match_fast (s, hash_head);
  81822. }
  81823. #endif
  81824. /* longest_match() or longest_match_fast() sets match_start */
  81825. }
  81826. if (s->match_length >= MIN_MATCH) {
  81827. check_match(s, s->strstart, s->match_start, s->match_length);
  81828. _tr_tally_dist(s, s->strstart - s->match_start,
  81829. s->match_length - MIN_MATCH, bflush);
  81830. s->lookahead -= s->match_length;
  81831. /* Insert new strings in the hash table only if the match length
  81832. * is not too large. This saves time but degrades compression.
  81833. */
  81834. #ifndef FASTEST
  81835. if (s->match_length <= s->max_insert_length &&
  81836. s->lookahead >= MIN_MATCH) {
  81837. s->match_length--; /* string at strstart already in table */
  81838. do {
  81839. s->strstart++;
  81840. INSERT_STRING(s, s->strstart, hash_head);
  81841. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  81842. * always MIN_MATCH bytes ahead.
  81843. */
  81844. } while (--s->match_length != 0);
  81845. s->strstart++;
  81846. } else
  81847. #endif
  81848. {
  81849. s->strstart += s->match_length;
  81850. s->match_length = 0;
  81851. s->ins_h = s->window[s->strstart];
  81852. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  81853. #if MIN_MATCH != 3
  81854. Call UPDATE_HASH() MIN_MATCH-3 more times
  81855. #endif
  81856. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  81857. * matter since it will be recomputed at next deflate call.
  81858. */
  81859. }
  81860. } else {
  81861. /* No match, output a literal byte */
  81862. Tracevv((stderr,"%c", s->window[s->strstart]));
  81863. _tr_tally_lit (s, s->window[s->strstart], bflush);
  81864. s->lookahead--;
  81865. s->strstart++;
  81866. }
  81867. if (bflush) FLUSH_BLOCK(s, 0);
  81868. }
  81869. FLUSH_BLOCK(s, flush == Z_FINISH);
  81870. return flush == Z_FINISH ? finish_done : block_done;
  81871. }
  81872. #ifndef FASTEST
  81873. /* ===========================================================================
  81874. * Same as above, but achieves better compression. We use a lazy
  81875. * evaluation for matches: a match is finally adopted only if there is
  81876. * no better match at the next window position.
  81877. */
  81878. local block_state deflate_slow(deflate_state *s, int flush)
  81879. {
  81880. IPos hash_head = NIL; /* head of hash chain */
  81881. int bflush; /* set if current block must be flushed */
  81882. /* Process the input block. */
  81883. for (;;) {
  81884. /* Make sure that we always have enough lookahead, except
  81885. * at the end of the input file. We need MAX_MATCH bytes
  81886. * for the next match, plus MIN_MATCH bytes to insert the
  81887. * string following the next match.
  81888. */
  81889. if (s->lookahead < MIN_LOOKAHEAD) {
  81890. fill_window(s);
  81891. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  81892. return need_more;
  81893. }
  81894. if (s->lookahead == 0) break; /* flush the current block */
  81895. }
  81896. /* Insert the string window[strstart .. strstart+2] in the
  81897. * dictionary, and set hash_head to the head of the hash chain:
  81898. */
  81899. if (s->lookahead >= MIN_MATCH) {
  81900. INSERT_STRING(s, s->strstart, hash_head);
  81901. }
  81902. /* Find the longest match, discarding those <= prev_length.
  81903. */
  81904. s->prev_length = s->match_length, s->prev_match = s->match_start;
  81905. s->match_length = MIN_MATCH-1;
  81906. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  81907. s->strstart - hash_head <= MAX_DIST(s)) {
  81908. /* To simplify the code, we prevent matches with the string
  81909. * of window index 0 (in particular we have to avoid a match
  81910. * of the string with itself at the start of the input file).
  81911. */
  81912. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  81913. s->match_length = longest_match (s, hash_head);
  81914. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  81915. s->match_length = longest_match_fast (s, hash_head);
  81916. }
  81917. /* longest_match() or longest_match_fast() sets match_start */
  81918. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  81919. #if TOO_FAR <= 32767
  81920. || (s->match_length == MIN_MATCH &&
  81921. s->strstart - s->match_start > TOO_FAR)
  81922. #endif
  81923. )) {
  81924. /* If prev_match is also MIN_MATCH, match_start is garbage
  81925. * but we will ignore the current match anyway.
  81926. */
  81927. s->match_length = MIN_MATCH-1;
  81928. }
  81929. }
  81930. /* If there was a match at the previous step and the current
  81931. * match is not better, output the previous match:
  81932. */
  81933. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  81934. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  81935. /* Do not insert strings in hash table beyond this. */
  81936. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  81937. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  81938. s->prev_length - MIN_MATCH, bflush);
  81939. /* Insert in hash table all strings up to the end of the match.
  81940. * strstart-1 and strstart are already inserted. If there is not
  81941. * enough lookahead, the last two strings are not inserted in
  81942. * the hash table.
  81943. */
  81944. s->lookahead -= s->prev_length-1;
  81945. s->prev_length -= 2;
  81946. do {
  81947. if (++s->strstart <= max_insert) {
  81948. INSERT_STRING(s, s->strstart, hash_head);
  81949. }
  81950. } while (--s->prev_length != 0);
  81951. s->match_available = 0;
  81952. s->match_length = MIN_MATCH-1;
  81953. s->strstart++;
  81954. if (bflush) FLUSH_BLOCK(s, 0);
  81955. } else if (s->match_available) {
  81956. /* If there was no match at the previous position, output a
  81957. * single literal. If there was a match but the current match
  81958. * is longer, truncate the previous match to a single literal.
  81959. */
  81960. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  81961. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  81962. if (bflush) {
  81963. FLUSH_BLOCK_ONLY(s, 0);
  81964. }
  81965. s->strstart++;
  81966. s->lookahead--;
  81967. if (s->strm->avail_out == 0) return need_more;
  81968. } else {
  81969. /* There is no previous match to compare with, wait for
  81970. * the next step to decide.
  81971. */
  81972. s->match_available = 1;
  81973. s->strstart++;
  81974. s->lookahead--;
  81975. }
  81976. }
  81977. Assert (flush != Z_NO_FLUSH, "no flush?");
  81978. if (s->match_available) {
  81979. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  81980. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  81981. s->match_available = 0;
  81982. }
  81983. FLUSH_BLOCK(s, flush == Z_FINISH);
  81984. return flush == Z_FINISH ? finish_done : block_done;
  81985. }
  81986. #endif /* FASTEST */
  81987. #if 0
  81988. /* ===========================================================================
  81989. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  81990. * one. Do not maintain a hash table. (It will be regenerated if this run of
  81991. * deflate switches away from Z_RLE.)
  81992. */
  81993. local block_state deflate_rle(s, flush)
  81994. deflate_state *s;
  81995. int flush;
  81996. {
  81997. int bflush; /* set if current block must be flushed */
  81998. uInt run; /* length of run */
  81999. uInt max; /* maximum length of run */
  82000. uInt prev; /* byte at distance one to match */
  82001. Bytef *scan; /* scan for end of run */
  82002. for (;;) {
  82003. /* Make sure that we always have enough lookahead, except
  82004. * at the end of the input file. We need MAX_MATCH bytes
  82005. * for the longest encodable run.
  82006. */
  82007. if (s->lookahead < MAX_MATCH) {
  82008. fill_window(s);
  82009. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82010. return need_more;
  82011. }
  82012. if (s->lookahead == 0) break; /* flush the current block */
  82013. }
  82014. /* See how many times the previous byte repeats */
  82015. run = 0;
  82016. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82017. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82018. scan = s->window + s->strstart - 1;
  82019. prev = *scan++;
  82020. do {
  82021. if (*scan++ != prev)
  82022. break;
  82023. } while (++run < max);
  82024. }
  82025. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82026. if (run >= MIN_MATCH) {
  82027. check_match(s, s->strstart, s->strstart - 1, run);
  82028. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82029. s->lookahead -= run;
  82030. s->strstart += run;
  82031. } else {
  82032. /* No match, output a literal byte */
  82033. Tracevv((stderr,"%c", s->window[s->strstart]));
  82034. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82035. s->lookahead--;
  82036. s->strstart++;
  82037. }
  82038. if (bflush) FLUSH_BLOCK(s, 0);
  82039. }
  82040. FLUSH_BLOCK(s, flush == Z_FINISH);
  82041. return flush == Z_FINISH ? finish_done : block_done;
  82042. }
  82043. #endif
  82044. /*** End of inlined file: deflate.c ***/
  82045. /*** Start of inlined file: inffast.c ***/
  82046. /*** Start of inlined file: inftrees.h ***/
  82047. /* WARNING: this file should *not* be used by applications. It is
  82048. part of the implementation of the compression library and is
  82049. subject to change. Applications should only use zlib.h.
  82050. */
  82051. #ifndef _INFTREES_H_
  82052. #define _INFTREES_H_
  82053. /* Structure for decoding tables. Each entry provides either the
  82054. information needed to do the operation requested by the code that
  82055. indexed that table entry, or it provides a pointer to another
  82056. table that indexes more bits of the code. op indicates whether
  82057. the entry is a pointer to another table, a literal, a length or
  82058. distance, an end-of-block, or an invalid code. For a table
  82059. pointer, the low four bits of op is the number of index bits of
  82060. that table. For a length or distance, the low four bits of op
  82061. is the number of extra bits to get after the code. bits is
  82062. the number of bits in this code or part of the code to drop off
  82063. of the bit buffer. val is the actual byte to output in the case
  82064. of a literal, the base length or distance, or the offset from
  82065. the current table to the next table. Each entry is four bytes. */
  82066. typedef struct {
  82067. unsigned char op; /* operation, extra bits, table bits */
  82068. unsigned char bits; /* bits in this part of the code */
  82069. unsigned short val; /* offset in table or code value */
  82070. } code;
  82071. /* op values as set by inflate_table():
  82072. 00000000 - literal
  82073. 0000tttt - table link, tttt != 0 is the number of table index bits
  82074. 0001eeee - length or distance, eeee is the number of extra bits
  82075. 01100000 - end of block
  82076. 01000000 - invalid code
  82077. */
  82078. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82079. exhaustive search was 1444 code structures (852 for length/literals
  82080. and 592 for distances, the latter actually the result of an
  82081. exhaustive search). The true maximum is not known, but the value
  82082. below is more than safe. */
  82083. #define ENOUGH 2048
  82084. #define MAXD 592
  82085. /* Type of code to build for inftable() */
  82086. typedef enum {
  82087. CODES,
  82088. LENS,
  82089. DISTS
  82090. } codetype;
  82091. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82092. unsigned codes, code FAR * FAR *table,
  82093. unsigned FAR *bits, unsigned short FAR *work));
  82094. #endif
  82095. /*** End of inlined file: inftrees.h ***/
  82096. /*** Start of inlined file: inflate.h ***/
  82097. /* WARNING: this file should *not* be used by applications. It is
  82098. part of the implementation of the compression library and is
  82099. subject to change. Applications should only use zlib.h.
  82100. */
  82101. #ifndef _INFLATE_H_
  82102. #define _INFLATE_H_
  82103. /* define NO_GZIP when compiling if you want to disable gzip header and
  82104. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82105. the crc code when it is not needed. For shared libraries, gzip decoding
  82106. should be left enabled. */
  82107. #ifndef NO_GZIP
  82108. # define GUNZIP
  82109. #endif
  82110. /* Possible inflate modes between inflate() calls */
  82111. typedef enum {
  82112. HEAD, /* i: waiting for magic header */
  82113. FLAGS, /* i: waiting for method and flags (gzip) */
  82114. TIME, /* i: waiting for modification time (gzip) */
  82115. OS, /* i: waiting for extra flags and operating system (gzip) */
  82116. EXLEN, /* i: waiting for extra length (gzip) */
  82117. EXTRA, /* i: waiting for extra bytes (gzip) */
  82118. NAME, /* i: waiting for end of file name (gzip) */
  82119. COMMENT, /* i: waiting for end of comment (gzip) */
  82120. HCRC, /* i: waiting for header crc (gzip) */
  82121. DICTID, /* i: waiting for dictionary check value */
  82122. DICT, /* waiting for inflateSetDictionary() call */
  82123. TYPE, /* i: waiting for type bits, including last-flag bit */
  82124. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82125. STORED, /* i: waiting for stored size (length and complement) */
  82126. COPY, /* i/o: waiting for input or output to copy stored block */
  82127. TABLE, /* i: waiting for dynamic block table lengths */
  82128. LENLENS, /* i: waiting for code length code lengths */
  82129. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82130. LEN, /* i: waiting for length/lit code */
  82131. LENEXT, /* i: waiting for length extra bits */
  82132. DIST, /* i: waiting for distance code */
  82133. DISTEXT, /* i: waiting for distance extra bits */
  82134. MATCH, /* o: waiting for output space to copy string */
  82135. LIT, /* o: waiting for output space to write literal */
  82136. CHECK, /* i: waiting for 32-bit check value */
  82137. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82138. DONE, /* finished check, done -- remain here until reset */
  82139. BAD, /* got a data error -- remain here until reset */
  82140. MEM, /* got an inflate() memory error -- remain here until reset */
  82141. SYNC /* looking for synchronization bytes to restart inflate() */
  82142. } inflate_mode;
  82143. /*
  82144. State transitions between above modes -
  82145. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82146. Process header:
  82147. HEAD -> (gzip) or (zlib)
  82148. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82149. NAME -> COMMENT -> HCRC -> TYPE
  82150. (zlib) -> DICTID or TYPE
  82151. DICTID -> DICT -> TYPE
  82152. Read deflate blocks:
  82153. TYPE -> STORED or TABLE or LEN or CHECK
  82154. STORED -> COPY -> TYPE
  82155. TABLE -> LENLENS -> CODELENS -> LEN
  82156. Read deflate codes:
  82157. LEN -> LENEXT or LIT or TYPE
  82158. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82159. LIT -> LEN
  82160. Process trailer:
  82161. CHECK -> LENGTH -> DONE
  82162. */
  82163. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82164. struct inflate_state {
  82165. inflate_mode mode; /* current inflate mode */
  82166. int last; /* true if processing last block */
  82167. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82168. int havedict; /* true if dictionary provided */
  82169. int flags; /* gzip header method and flags (0 if zlib) */
  82170. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82171. unsigned long check; /* protected copy of check value */
  82172. unsigned long total; /* protected copy of output count */
  82173. gz_headerp head; /* where to save gzip header information */
  82174. /* sliding window */
  82175. unsigned wbits; /* log base 2 of requested window size */
  82176. unsigned wsize; /* window size or zero if not using window */
  82177. unsigned whave; /* valid bytes in the window */
  82178. unsigned write; /* window write index */
  82179. unsigned char FAR *window; /* allocated sliding window, if needed */
  82180. /* bit accumulator */
  82181. unsigned long hold; /* input bit accumulator */
  82182. unsigned bits; /* number of bits in "in" */
  82183. /* for string and stored block copying */
  82184. unsigned length; /* literal or length of data to copy */
  82185. unsigned offset; /* distance back to copy string from */
  82186. /* for table and code decoding */
  82187. unsigned extra; /* extra bits needed */
  82188. /* fixed and dynamic code tables */
  82189. code const FAR *lencode; /* starting table for length/literal codes */
  82190. code const FAR *distcode; /* starting table for distance codes */
  82191. unsigned lenbits; /* index bits for lencode */
  82192. unsigned distbits; /* index bits for distcode */
  82193. /* dynamic table building */
  82194. unsigned ncode; /* number of code length code lengths */
  82195. unsigned nlen; /* number of length code lengths */
  82196. unsigned ndist; /* number of distance code lengths */
  82197. unsigned have; /* number of code lengths in lens[] */
  82198. code FAR *next; /* next available space in codes[] */
  82199. unsigned short lens[320]; /* temporary storage for code lengths */
  82200. unsigned short work[288]; /* work area for code table building */
  82201. code codes[ENOUGH]; /* space for code tables */
  82202. };
  82203. #endif
  82204. /*** End of inlined file: inflate.h ***/
  82205. /*** Start of inlined file: inffast.h ***/
  82206. /* WARNING: this file should *not* be used by applications. It is
  82207. part of the implementation of the compression library and is
  82208. subject to change. Applications should only use zlib.h.
  82209. */
  82210. void inflate_fast OF((z_streamp strm, unsigned start));
  82211. /*** End of inlined file: inffast.h ***/
  82212. #ifndef ASMINF
  82213. /* Allow machine dependent optimization for post-increment or pre-increment.
  82214. Based on testing to date,
  82215. Pre-increment preferred for:
  82216. - PowerPC G3 (Adler)
  82217. - MIPS R5000 (Randers-Pehrson)
  82218. Post-increment preferred for:
  82219. - none
  82220. No measurable difference:
  82221. - Pentium III (Anderson)
  82222. - M68060 (Nikl)
  82223. */
  82224. #ifdef POSTINC
  82225. # define OFF 0
  82226. # define PUP(a) *(a)++
  82227. #else
  82228. # define OFF 1
  82229. # define PUP(a) *++(a)
  82230. #endif
  82231. /*
  82232. Decode literal, length, and distance codes and write out the resulting
  82233. literal and match bytes until either not enough input or output is
  82234. available, an end-of-block is encountered, or a data error is encountered.
  82235. When large enough input and output buffers are supplied to inflate(), for
  82236. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82237. inflate execution time is spent in this routine.
  82238. Entry assumptions:
  82239. state->mode == LEN
  82240. strm->avail_in >= 6
  82241. strm->avail_out >= 258
  82242. start >= strm->avail_out
  82243. state->bits < 8
  82244. On return, state->mode is one of:
  82245. LEN -- ran out of enough output space or enough available input
  82246. TYPE -- reached end of block code, inflate() to interpret next block
  82247. BAD -- error in block data
  82248. Notes:
  82249. - The maximum input bits used by a length/distance pair is 15 bits for the
  82250. length code, 5 bits for the length extra, 15 bits for the distance code,
  82251. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  82252. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  82253. checking for available input while decoding.
  82254. - The maximum bytes that a single length/distance pair can output is 258
  82255. bytes, which is the maximum length that can be coded. inflate_fast()
  82256. requires strm->avail_out >= 258 for each loop to avoid checking for
  82257. output space.
  82258. */
  82259. void inflate_fast (z_streamp strm, unsigned start)
  82260. {
  82261. struct inflate_state FAR *state;
  82262. unsigned char FAR *in; /* local strm->next_in */
  82263. unsigned char FAR *last; /* while in < last, enough input available */
  82264. unsigned char FAR *out; /* local strm->next_out */
  82265. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  82266. unsigned char FAR *end; /* while out < end, enough space available */
  82267. #ifdef INFLATE_STRICT
  82268. unsigned dmax; /* maximum distance from zlib header */
  82269. #endif
  82270. unsigned wsize; /* window size or zero if not using window */
  82271. unsigned whave; /* valid bytes in the window */
  82272. unsigned write; /* window write index */
  82273. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  82274. unsigned long hold; /* local strm->hold */
  82275. unsigned bits; /* local strm->bits */
  82276. code const FAR *lcode; /* local strm->lencode */
  82277. code const FAR *dcode; /* local strm->distcode */
  82278. unsigned lmask; /* mask for first level of length codes */
  82279. unsigned dmask; /* mask for first level of distance codes */
  82280. code thisx; /* retrieved table entry */
  82281. unsigned op; /* code bits, operation, extra bits, or */
  82282. /* window position, window bytes to copy */
  82283. unsigned len; /* match length, unused bytes */
  82284. unsigned dist; /* match distance */
  82285. unsigned char FAR *from; /* where to copy match from */
  82286. /* copy state to local variables */
  82287. state = (struct inflate_state FAR *)strm->state;
  82288. in = strm->next_in - OFF;
  82289. last = in + (strm->avail_in - 5);
  82290. out = strm->next_out - OFF;
  82291. beg = out - (start - strm->avail_out);
  82292. end = out + (strm->avail_out - 257);
  82293. #ifdef INFLATE_STRICT
  82294. dmax = state->dmax;
  82295. #endif
  82296. wsize = state->wsize;
  82297. whave = state->whave;
  82298. write = state->write;
  82299. window = state->window;
  82300. hold = state->hold;
  82301. bits = state->bits;
  82302. lcode = state->lencode;
  82303. dcode = state->distcode;
  82304. lmask = (1U << state->lenbits) - 1;
  82305. dmask = (1U << state->distbits) - 1;
  82306. /* decode literals and length/distances until end-of-block or not enough
  82307. input data or output space */
  82308. do {
  82309. if (bits < 15) {
  82310. hold += (unsigned long)(PUP(in)) << bits;
  82311. bits += 8;
  82312. hold += (unsigned long)(PUP(in)) << bits;
  82313. bits += 8;
  82314. }
  82315. thisx = lcode[hold & lmask];
  82316. dolen:
  82317. op = (unsigned)(thisx.bits);
  82318. hold >>= op;
  82319. bits -= op;
  82320. op = (unsigned)(thisx.op);
  82321. if (op == 0) { /* literal */
  82322. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82323. "inflate: literal '%c'\n" :
  82324. "inflate: literal 0x%02x\n", thisx.val));
  82325. PUP(out) = (unsigned char)(thisx.val);
  82326. }
  82327. else if (op & 16) { /* length base */
  82328. len = (unsigned)(thisx.val);
  82329. op &= 15; /* number of extra bits */
  82330. if (op) {
  82331. if (bits < op) {
  82332. hold += (unsigned long)(PUP(in)) << bits;
  82333. bits += 8;
  82334. }
  82335. len += (unsigned)hold & ((1U << op) - 1);
  82336. hold >>= op;
  82337. bits -= op;
  82338. }
  82339. Tracevv((stderr, "inflate: length %u\n", len));
  82340. if (bits < 15) {
  82341. hold += (unsigned long)(PUP(in)) << bits;
  82342. bits += 8;
  82343. hold += (unsigned long)(PUP(in)) << bits;
  82344. bits += 8;
  82345. }
  82346. thisx = dcode[hold & dmask];
  82347. dodist:
  82348. op = (unsigned)(thisx.bits);
  82349. hold >>= op;
  82350. bits -= op;
  82351. op = (unsigned)(thisx.op);
  82352. if (op & 16) { /* distance base */
  82353. dist = (unsigned)(thisx.val);
  82354. op &= 15; /* number of extra bits */
  82355. if (bits < op) {
  82356. hold += (unsigned long)(PUP(in)) << bits;
  82357. bits += 8;
  82358. if (bits < op) {
  82359. hold += (unsigned long)(PUP(in)) << bits;
  82360. bits += 8;
  82361. }
  82362. }
  82363. dist += (unsigned)hold & ((1U << op) - 1);
  82364. #ifdef INFLATE_STRICT
  82365. if (dist > dmax) {
  82366. strm->msg = (char *)"invalid distance too far back";
  82367. state->mode = BAD;
  82368. break;
  82369. }
  82370. #endif
  82371. hold >>= op;
  82372. bits -= op;
  82373. Tracevv((stderr, "inflate: distance %u\n", dist));
  82374. op = (unsigned)(out - beg); /* max distance in output */
  82375. if (dist > op) { /* see if copy from window */
  82376. op = dist - op; /* distance back in window */
  82377. if (op > whave) {
  82378. strm->msg = (char *)"invalid distance too far back";
  82379. state->mode = BAD;
  82380. break;
  82381. }
  82382. from = window - OFF;
  82383. if (write == 0) { /* very common case */
  82384. from += wsize - op;
  82385. if (op < len) { /* some from window */
  82386. len -= op;
  82387. do {
  82388. PUP(out) = PUP(from);
  82389. } while (--op);
  82390. from = out - dist; /* rest from output */
  82391. }
  82392. }
  82393. else if (write < op) { /* wrap around window */
  82394. from += wsize + write - op;
  82395. op -= write;
  82396. if (op < len) { /* some from end of window */
  82397. len -= op;
  82398. do {
  82399. PUP(out) = PUP(from);
  82400. } while (--op);
  82401. from = window - OFF;
  82402. if (write < len) { /* some from start of window */
  82403. op = write;
  82404. len -= op;
  82405. do {
  82406. PUP(out) = PUP(from);
  82407. } while (--op);
  82408. from = out - dist; /* rest from output */
  82409. }
  82410. }
  82411. }
  82412. else { /* contiguous in window */
  82413. from += write - op;
  82414. if (op < len) { /* some from window */
  82415. len -= op;
  82416. do {
  82417. PUP(out) = PUP(from);
  82418. } while (--op);
  82419. from = out - dist; /* rest from output */
  82420. }
  82421. }
  82422. while (len > 2) {
  82423. PUP(out) = PUP(from);
  82424. PUP(out) = PUP(from);
  82425. PUP(out) = PUP(from);
  82426. len -= 3;
  82427. }
  82428. if (len) {
  82429. PUP(out) = PUP(from);
  82430. if (len > 1)
  82431. PUP(out) = PUP(from);
  82432. }
  82433. }
  82434. else {
  82435. from = out - dist; /* copy direct from output */
  82436. do { /* minimum length is three */
  82437. PUP(out) = PUP(from);
  82438. PUP(out) = PUP(from);
  82439. PUP(out) = PUP(from);
  82440. len -= 3;
  82441. } while (len > 2);
  82442. if (len) {
  82443. PUP(out) = PUP(from);
  82444. if (len > 1)
  82445. PUP(out) = PUP(from);
  82446. }
  82447. }
  82448. }
  82449. else if ((op & 64) == 0) { /* 2nd level distance code */
  82450. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  82451. goto dodist;
  82452. }
  82453. else {
  82454. strm->msg = (char *)"invalid distance code";
  82455. state->mode = BAD;
  82456. break;
  82457. }
  82458. }
  82459. else if ((op & 64) == 0) { /* 2nd level length code */
  82460. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  82461. goto dolen;
  82462. }
  82463. else if (op & 32) { /* end-of-block */
  82464. Tracevv((stderr, "inflate: end of block\n"));
  82465. state->mode = TYPE;
  82466. break;
  82467. }
  82468. else {
  82469. strm->msg = (char *)"invalid literal/length code";
  82470. state->mode = BAD;
  82471. break;
  82472. }
  82473. } while (in < last && out < end);
  82474. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  82475. len = bits >> 3;
  82476. in -= len;
  82477. bits -= len << 3;
  82478. hold &= (1U << bits) - 1;
  82479. /* update state and return */
  82480. strm->next_in = in + OFF;
  82481. strm->next_out = out + OFF;
  82482. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  82483. strm->avail_out = (unsigned)(out < end ?
  82484. 257 + (end - out) : 257 - (out - end));
  82485. state->hold = hold;
  82486. state->bits = bits;
  82487. return;
  82488. }
  82489. /*
  82490. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  82491. - Using bit fields for code structure
  82492. - Different op definition to avoid & for extra bits (do & for table bits)
  82493. - Three separate decoding do-loops for direct, window, and write == 0
  82494. - Special case for distance > 1 copies to do overlapped load and store copy
  82495. - Explicit branch predictions (based on measured branch probabilities)
  82496. - Deferring match copy and interspersed it with decoding subsequent codes
  82497. - Swapping literal/length else
  82498. - Swapping window/direct else
  82499. - Larger unrolled copy loops (three is about right)
  82500. - Moving len -= 3 statement into middle of loop
  82501. */
  82502. #endif /* !ASMINF */
  82503. /*** End of inlined file: inffast.c ***/
  82504. #undef PULLBYTE
  82505. #undef LOAD
  82506. #undef RESTORE
  82507. #undef INITBITS
  82508. #undef NEEDBITS
  82509. #undef DROPBITS
  82510. #undef BYTEBITS
  82511. /*** Start of inlined file: inflate.c ***/
  82512. /*
  82513. * Change history:
  82514. *
  82515. * 1.2.beta0 24 Nov 2002
  82516. * - First version -- complete rewrite of inflate to simplify code, avoid
  82517. * creation of window when not needed, minimize use of window when it is
  82518. * needed, make inffast.c even faster, implement gzip decoding, and to
  82519. * improve code readability and style over the previous zlib inflate code
  82520. *
  82521. * 1.2.beta1 25 Nov 2002
  82522. * - Use pointers for available input and output checking in inffast.c
  82523. * - Remove input and output counters in inffast.c
  82524. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  82525. * - Remove unnecessary second byte pull from length extra in inffast.c
  82526. * - Unroll direct copy to three copies per loop in inffast.c
  82527. *
  82528. * 1.2.beta2 4 Dec 2002
  82529. * - Change external routine names to reduce potential conflicts
  82530. * - Correct filename to inffixed.h for fixed tables in inflate.c
  82531. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  82532. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  82533. * to avoid negation problem on Alphas (64 bit) in inflate.c
  82534. *
  82535. * 1.2.beta3 22 Dec 2002
  82536. * - Add comments on state->bits assertion in inffast.c
  82537. * - Add comments on op field in inftrees.h
  82538. * - Fix bug in reuse of allocated window after inflateReset()
  82539. * - Remove bit fields--back to byte structure for speed
  82540. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  82541. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  82542. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  82543. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  82544. * - Use local copies of stream next and avail values, as well as local bit
  82545. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  82546. *
  82547. * 1.2.beta4 1 Jan 2003
  82548. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  82549. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  82550. * - Add comments in inffast.c to introduce the inflate_fast() routine
  82551. * - Rearrange window copies in inflate_fast() for speed and simplification
  82552. * - Unroll last copy for window match in inflate_fast()
  82553. * - Use local copies of window variables in inflate_fast() for speed
  82554. * - Pull out common write == 0 case for speed in inflate_fast()
  82555. * - Make op and len in inflate_fast() unsigned for consistency
  82556. * - Add FAR to lcode and dcode declarations in inflate_fast()
  82557. * - Simplified bad distance check in inflate_fast()
  82558. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  82559. * source file infback.c to provide a call-back interface to inflate for
  82560. * programs like gzip and unzip -- uses window as output buffer to avoid
  82561. * window copying
  82562. *
  82563. * 1.2.beta5 1 Jan 2003
  82564. * - Improved inflateBack() interface to allow the caller to provide initial
  82565. * input in strm.
  82566. * - Fixed stored blocks bug in inflateBack()
  82567. *
  82568. * 1.2.beta6 4 Jan 2003
  82569. * - Added comments in inffast.c on effectiveness of POSTINC
  82570. * - Typecasting all around to reduce compiler warnings
  82571. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  82572. * make compilers happy
  82573. * - Changed type of window in inflateBackInit() to unsigned char *
  82574. *
  82575. * 1.2.beta7 27 Jan 2003
  82576. * - Changed many types to unsigned or unsigned short to avoid warnings
  82577. * - Added inflateCopy() function
  82578. *
  82579. * 1.2.0 9 Mar 2003
  82580. * - Changed inflateBack() interface to provide separate opaque descriptors
  82581. * for the in() and out() functions
  82582. * - Changed inflateBack() argument and in_func typedef to swap the length
  82583. * and buffer address return values for the input function
  82584. * - Check next_in and next_out for Z_NULL on entry to inflate()
  82585. *
  82586. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  82587. */
  82588. /*** Start of inlined file: inffast.h ***/
  82589. /* WARNING: this file should *not* be used by applications. It is
  82590. part of the implementation of the compression library and is
  82591. subject to change. Applications should only use zlib.h.
  82592. */
  82593. void inflate_fast OF((z_streamp strm, unsigned start));
  82594. /*** End of inlined file: inffast.h ***/
  82595. #ifdef MAKEFIXED
  82596. # ifndef BUILDFIXED
  82597. # define BUILDFIXED
  82598. # endif
  82599. #endif
  82600. /* function prototypes */
  82601. local void fixedtables OF((struct inflate_state FAR *state));
  82602. local int updatewindow OF((z_streamp strm, unsigned out));
  82603. #ifdef BUILDFIXED
  82604. void makefixed OF((void));
  82605. #endif
  82606. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  82607. unsigned len));
  82608. int ZEXPORT inflateReset (z_streamp strm)
  82609. {
  82610. struct inflate_state FAR *state;
  82611. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82612. state = (struct inflate_state FAR *)strm->state;
  82613. strm->total_in = strm->total_out = state->total = 0;
  82614. strm->msg = Z_NULL;
  82615. strm->adler = 1; /* to support ill-conceived Java test suite */
  82616. state->mode = HEAD;
  82617. state->last = 0;
  82618. state->havedict = 0;
  82619. state->dmax = 32768U;
  82620. state->head = Z_NULL;
  82621. state->wsize = 0;
  82622. state->whave = 0;
  82623. state->write = 0;
  82624. state->hold = 0;
  82625. state->bits = 0;
  82626. state->lencode = state->distcode = state->next = state->codes;
  82627. Tracev((stderr, "inflate: reset\n"));
  82628. return Z_OK;
  82629. }
  82630. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  82631. {
  82632. struct inflate_state FAR *state;
  82633. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82634. state = (struct inflate_state FAR *)strm->state;
  82635. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  82636. value &= (1L << bits) - 1;
  82637. state->hold += value << state->bits;
  82638. state->bits += bits;
  82639. return Z_OK;
  82640. }
  82641. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  82642. {
  82643. struct inflate_state FAR *state;
  82644. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  82645. stream_size != (int)(sizeof(z_stream)))
  82646. return Z_VERSION_ERROR;
  82647. if (strm == Z_NULL) return Z_STREAM_ERROR;
  82648. strm->msg = Z_NULL; /* in case we return an error */
  82649. if (strm->zalloc == (alloc_func)0) {
  82650. strm->zalloc = zcalloc;
  82651. strm->opaque = (voidpf)0;
  82652. }
  82653. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  82654. state = (struct inflate_state FAR *)
  82655. ZALLOC(strm, 1, sizeof(struct inflate_state));
  82656. if (state == Z_NULL) return Z_MEM_ERROR;
  82657. Tracev((stderr, "inflate: allocated\n"));
  82658. strm->state = (struct internal_state FAR *)state;
  82659. if (windowBits < 0) {
  82660. state->wrap = 0;
  82661. windowBits = -windowBits;
  82662. }
  82663. else {
  82664. state->wrap = (windowBits >> 4) + 1;
  82665. #ifdef GUNZIP
  82666. if (windowBits < 48) windowBits &= 15;
  82667. #endif
  82668. }
  82669. if (windowBits < 8 || windowBits > 15) {
  82670. ZFREE(strm, state);
  82671. strm->state = Z_NULL;
  82672. return Z_STREAM_ERROR;
  82673. }
  82674. state->wbits = (unsigned)windowBits;
  82675. state->window = Z_NULL;
  82676. return inflateReset(strm);
  82677. }
  82678. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  82679. {
  82680. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  82681. }
  82682. /*
  82683. Return state with length and distance decoding tables and index sizes set to
  82684. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  82685. If BUILDFIXED is defined, then instead this routine builds the tables the
  82686. first time it's called, and returns those tables the first time and
  82687. thereafter. This reduces the size of the code by about 2K bytes, in
  82688. exchange for a little execution time. However, BUILDFIXED should not be
  82689. used for threaded applications, since the rewriting of the tables and virgin
  82690. may not be thread-safe.
  82691. */
  82692. local void fixedtables (struct inflate_state FAR *state)
  82693. {
  82694. #ifdef BUILDFIXED
  82695. static int virgin = 1;
  82696. static code *lenfix, *distfix;
  82697. static code fixed[544];
  82698. /* build fixed huffman tables if first call (may not be thread safe) */
  82699. if (virgin) {
  82700. unsigned sym, bits;
  82701. static code *next;
  82702. /* literal/length table */
  82703. sym = 0;
  82704. while (sym < 144) state->lens[sym++] = 8;
  82705. while (sym < 256) state->lens[sym++] = 9;
  82706. while (sym < 280) state->lens[sym++] = 7;
  82707. while (sym < 288) state->lens[sym++] = 8;
  82708. next = fixed;
  82709. lenfix = next;
  82710. bits = 9;
  82711. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  82712. /* distance table */
  82713. sym = 0;
  82714. while (sym < 32) state->lens[sym++] = 5;
  82715. distfix = next;
  82716. bits = 5;
  82717. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  82718. /* do this just once */
  82719. virgin = 0;
  82720. }
  82721. #else /* !BUILDFIXED */
  82722. /*** Start of inlined file: inffixed.h ***/
  82723. /* WARNING: this file should *not* be used by applications. It
  82724. is part of the implementation of the compression library and
  82725. is subject to change. Applications should only use zlib.h.
  82726. */
  82727. static const code lenfix[512] = {
  82728. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  82729. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  82730. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  82731. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  82732. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  82733. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  82734. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  82735. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  82736. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  82737. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  82738. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  82739. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  82740. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  82741. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  82742. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  82743. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  82744. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  82745. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  82746. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  82747. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  82748. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  82749. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  82750. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  82751. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  82752. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  82753. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  82754. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  82755. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  82756. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  82757. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  82758. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  82759. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  82760. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  82761. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  82762. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  82763. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  82764. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  82765. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  82766. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  82767. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  82768. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  82769. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  82770. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  82771. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  82772. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  82773. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  82774. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  82775. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  82776. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  82777. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  82778. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  82779. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  82780. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  82781. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  82782. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  82783. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  82784. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  82785. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  82786. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  82787. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  82788. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  82789. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  82790. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  82791. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  82792. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  82793. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  82794. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  82795. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  82796. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  82797. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  82798. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  82799. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  82800. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  82801. {0,9,255}
  82802. };
  82803. static const code distfix[32] = {
  82804. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  82805. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  82806. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  82807. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  82808. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  82809. {22,5,193},{64,5,0}
  82810. };
  82811. /*** End of inlined file: inffixed.h ***/
  82812. #endif /* BUILDFIXED */
  82813. state->lencode = lenfix;
  82814. state->lenbits = 9;
  82815. state->distcode = distfix;
  82816. state->distbits = 5;
  82817. }
  82818. #ifdef MAKEFIXED
  82819. #include <stdio.h>
  82820. /*
  82821. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  82822. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  82823. those tables to stdout, which would be piped to inffixed.h. A small program
  82824. can simply call makefixed to do this:
  82825. void makefixed(void);
  82826. int main(void)
  82827. {
  82828. makefixed();
  82829. return 0;
  82830. }
  82831. Then that can be linked with zlib built with MAKEFIXED defined and run:
  82832. a.out > inffixed.h
  82833. */
  82834. void makefixed()
  82835. {
  82836. unsigned low, size;
  82837. struct inflate_state state;
  82838. fixedtables(&state);
  82839. puts(" /* inffixed.h -- table for decoding fixed codes");
  82840. puts(" * Generated automatically by makefixed().");
  82841. puts(" */");
  82842. puts("");
  82843. puts(" /* WARNING: this file should *not* be used by applications.");
  82844. puts(" It is part of the implementation of this library and is");
  82845. puts(" subject to change. Applications should only use zlib.h.");
  82846. puts(" */");
  82847. puts("");
  82848. size = 1U << 9;
  82849. printf(" static const code lenfix[%u] = {", size);
  82850. low = 0;
  82851. for (;;) {
  82852. if ((low % 7) == 0) printf("\n ");
  82853. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  82854. state.lencode[low].val);
  82855. if (++low == size) break;
  82856. putchar(',');
  82857. }
  82858. puts("\n };");
  82859. size = 1U << 5;
  82860. printf("\n static const code distfix[%u] = {", size);
  82861. low = 0;
  82862. for (;;) {
  82863. if ((low % 6) == 0) printf("\n ");
  82864. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  82865. state.distcode[low].val);
  82866. if (++low == size) break;
  82867. putchar(',');
  82868. }
  82869. puts("\n };");
  82870. }
  82871. #endif /* MAKEFIXED */
  82872. /*
  82873. Update the window with the last wsize (normally 32K) bytes written before
  82874. returning. If window does not exist yet, create it. This is only called
  82875. when a window is already in use, or when output has been written during this
  82876. inflate call, but the end of the deflate stream has not been reached yet.
  82877. It is also called to create a window for dictionary data when a dictionary
  82878. is loaded.
  82879. Providing output buffers larger than 32K to inflate() should provide a speed
  82880. advantage, since only the last 32K of output is copied to the sliding window
  82881. upon return from inflate(), and since all distances after the first 32K of
  82882. output will fall in the output data, making match copies simpler and faster.
  82883. The advantage may be dependent on the size of the processor's data caches.
  82884. */
  82885. local int updatewindow (z_streamp strm, unsigned out)
  82886. {
  82887. struct inflate_state FAR *state;
  82888. unsigned copy, dist;
  82889. state = (struct inflate_state FAR *)strm->state;
  82890. /* if it hasn't been done already, allocate space for the window */
  82891. if (state->window == Z_NULL) {
  82892. state->window = (unsigned char FAR *)
  82893. ZALLOC(strm, 1U << state->wbits,
  82894. sizeof(unsigned char));
  82895. if (state->window == Z_NULL) return 1;
  82896. }
  82897. /* if window not in use yet, initialize */
  82898. if (state->wsize == 0) {
  82899. state->wsize = 1U << state->wbits;
  82900. state->write = 0;
  82901. state->whave = 0;
  82902. }
  82903. /* copy state->wsize or less output bytes into the circular window */
  82904. copy = out - strm->avail_out;
  82905. if (copy >= state->wsize) {
  82906. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  82907. state->write = 0;
  82908. state->whave = state->wsize;
  82909. }
  82910. else {
  82911. dist = state->wsize - state->write;
  82912. if (dist > copy) dist = copy;
  82913. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  82914. copy -= dist;
  82915. if (copy) {
  82916. zmemcpy(state->window, strm->next_out - copy, copy);
  82917. state->write = copy;
  82918. state->whave = state->wsize;
  82919. }
  82920. else {
  82921. state->write += dist;
  82922. if (state->write == state->wsize) state->write = 0;
  82923. if (state->whave < state->wsize) state->whave += dist;
  82924. }
  82925. }
  82926. return 0;
  82927. }
  82928. /* Macros for inflate(): */
  82929. /* check function to use adler32() for zlib or crc32() for gzip */
  82930. #ifdef GUNZIP
  82931. # define UPDATE(check, buf, len) \
  82932. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  82933. #else
  82934. # define UPDATE(check, buf, len) adler32(check, buf, len)
  82935. #endif
  82936. /* check macros for header crc */
  82937. #ifdef GUNZIP
  82938. # define CRC2(check, word) \
  82939. do { \
  82940. hbuf[0] = (unsigned char)(word); \
  82941. hbuf[1] = (unsigned char)((word) >> 8); \
  82942. check = crc32(check, hbuf, 2); \
  82943. } while (0)
  82944. # define CRC4(check, word) \
  82945. do { \
  82946. hbuf[0] = (unsigned char)(word); \
  82947. hbuf[1] = (unsigned char)((word) >> 8); \
  82948. hbuf[2] = (unsigned char)((word) >> 16); \
  82949. hbuf[3] = (unsigned char)((word) >> 24); \
  82950. check = crc32(check, hbuf, 4); \
  82951. } while (0)
  82952. #endif
  82953. /* Load registers with state in inflate() for speed */
  82954. #define LOAD() \
  82955. do { \
  82956. put = strm->next_out; \
  82957. left = strm->avail_out; \
  82958. next = strm->next_in; \
  82959. have = strm->avail_in; \
  82960. hold = state->hold; \
  82961. bits = state->bits; \
  82962. } while (0)
  82963. /* Restore state from registers in inflate() */
  82964. #define RESTORE() \
  82965. do { \
  82966. strm->next_out = put; \
  82967. strm->avail_out = left; \
  82968. strm->next_in = next; \
  82969. strm->avail_in = have; \
  82970. state->hold = hold; \
  82971. state->bits = bits; \
  82972. } while (0)
  82973. /* Clear the input bit accumulator */
  82974. #define INITBITS() \
  82975. do { \
  82976. hold = 0; \
  82977. bits = 0; \
  82978. } while (0)
  82979. /* Get a byte of input into the bit accumulator, or return from inflate()
  82980. if there is no input available. */
  82981. #define PULLBYTE() \
  82982. do { \
  82983. if (have == 0) goto inf_leave; \
  82984. have--; \
  82985. hold += (unsigned long)(*next++) << bits; \
  82986. bits += 8; \
  82987. } while (0)
  82988. /* Assure that there are at least n bits in the bit accumulator. If there is
  82989. not enough available input to do that, then return from inflate(). */
  82990. #define NEEDBITS(n) \
  82991. do { \
  82992. while (bits < (unsigned)(n)) \
  82993. PULLBYTE(); \
  82994. } while (0)
  82995. /* Return the low n bits of the bit accumulator (n < 16) */
  82996. #define BITS(n) \
  82997. ((unsigned)hold & ((1U << (n)) - 1))
  82998. /* Remove n bits from the bit accumulator */
  82999. #define DROPBITS(n) \
  83000. do { \
  83001. hold >>= (n); \
  83002. bits -= (unsigned)(n); \
  83003. } while (0)
  83004. /* Remove zero to seven bits as needed to go to a byte boundary */
  83005. #define BYTEBITS() \
  83006. do { \
  83007. hold >>= bits & 7; \
  83008. bits -= bits & 7; \
  83009. } while (0)
  83010. /* Reverse the bytes in a 32-bit value */
  83011. #define REVERSE(q) \
  83012. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83013. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83014. /*
  83015. inflate() uses a state machine to process as much input data and generate as
  83016. much output data as possible before returning. The state machine is
  83017. structured roughly as follows:
  83018. for (;;) switch (state) {
  83019. ...
  83020. case STATEn:
  83021. if (not enough input data or output space to make progress)
  83022. return;
  83023. ... make progress ...
  83024. state = STATEm;
  83025. break;
  83026. ...
  83027. }
  83028. so when inflate() is called again, the same case is attempted again, and
  83029. if the appropriate resources are provided, the machine proceeds to the
  83030. next state. The NEEDBITS() macro is usually the way the state evaluates
  83031. whether it can proceed or should return. NEEDBITS() does the return if
  83032. the requested bits are not available. The typical use of the BITS macros
  83033. is:
  83034. NEEDBITS(n);
  83035. ... do something with BITS(n) ...
  83036. DROPBITS(n);
  83037. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83038. input left to load n bits into the accumulator, or it continues. BITS(n)
  83039. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83040. the low n bits off the accumulator. INITBITS() clears the accumulator
  83041. and sets the number of available bits to zero. BYTEBITS() discards just
  83042. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83043. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83044. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83045. if there is no input available. The decoding of variable length codes uses
  83046. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83047. code, and no more.
  83048. Some states loop until they get enough input, making sure that enough
  83049. state information is maintained to continue the loop where it left off
  83050. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83051. would all have to actually be part of the saved state in case NEEDBITS()
  83052. returns:
  83053. case STATEw:
  83054. while (want < need) {
  83055. NEEDBITS(n);
  83056. keep[want++] = BITS(n);
  83057. DROPBITS(n);
  83058. }
  83059. state = STATEx;
  83060. case STATEx:
  83061. As shown above, if the next state is also the next case, then the break
  83062. is omitted.
  83063. A state may also return if there is not enough output space available to
  83064. complete that state. Those states are copying stored data, writing a
  83065. literal byte, and copying a matching string.
  83066. When returning, a "goto inf_leave" is used to update the total counters,
  83067. update the check value, and determine whether any progress has been made
  83068. during that inflate() call in order to return the proper return code.
  83069. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83070. When there is a window, goto inf_leave will update the window with the last
  83071. output written. If a goto inf_leave occurs in the middle of decompression
  83072. and there is no window currently, goto inf_leave will create one and copy
  83073. output to the window for the next call of inflate().
  83074. In this implementation, the flush parameter of inflate() only affects the
  83075. return code (per zlib.h). inflate() always writes as much as possible to
  83076. strm->next_out, given the space available and the provided input--the effect
  83077. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83078. the allocation of and copying into a sliding window until necessary, which
  83079. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83080. stream available. So the only thing the flush parameter actually does is:
  83081. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83082. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83083. */
  83084. int ZEXPORT inflate (z_streamp strm, int flush)
  83085. {
  83086. struct inflate_state FAR *state;
  83087. unsigned char FAR *next; /* next input */
  83088. unsigned char FAR *put; /* next output */
  83089. unsigned have, left; /* available input and output */
  83090. unsigned long hold; /* bit buffer */
  83091. unsigned bits; /* bits in bit buffer */
  83092. unsigned in, out; /* save starting available input and output */
  83093. unsigned copy; /* number of stored or match bytes to copy */
  83094. unsigned char FAR *from; /* where to copy match bytes from */
  83095. code thisx; /* current decoding table entry */
  83096. code last; /* parent table entry */
  83097. unsigned len; /* length to copy for repeats, bits to drop */
  83098. int ret; /* return code */
  83099. #ifdef GUNZIP
  83100. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83101. #endif
  83102. static const unsigned short order[19] = /* permutation of code lengths */
  83103. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83104. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83105. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83106. return Z_STREAM_ERROR;
  83107. state = (struct inflate_state FAR *)strm->state;
  83108. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83109. LOAD();
  83110. in = have;
  83111. out = left;
  83112. ret = Z_OK;
  83113. for (;;)
  83114. switch (state->mode) {
  83115. case HEAD:
  83116. if (state->wrap == 0) {
  83117. state->mode = TYPEDO;
  83118. break;
  83119. }
  83120. NEEDBITS(16);
  83121. #ifdef GUNZIP
  83122. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83123. state->check = crc32(0L, Z_NULL, 0);
  83124. CRC2(state->check, hold);
  83125. INITBITS();
  83126. state->mode = FLAGS;
  83127. break;
  83128. }
  83129. state->flags = 0; /* expect zlib header */
  83130. if (state->head != Z_NULL)
  83131. state->head->done = -1;
  83132. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83133. #else
  83134. if (
  83135. #endif
  83136. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83137. strm->msg = (char *)"incorrect header check";
  83138. state->mode = BAD;
  83139. break;
  83140. }
  83141. if (BITS(4) != Z_DEFLATED) {
  83142. strm->msg = (char *)"unknown compression method";
  83143. state->mode = BAD;
  83144. break;
  83145. }
  83146. DROPBITS(4);
  83147. len = BITS(4) + 8;
  83148. if (len > state->wbits) {
  83149. strm->msg = (char *)"invalid window size";
  83150. state->mode = BAD;
  83151. break;
  83152. }
  83153. state->dmax = 1U << len;
  83154. Tracev((stderr, "inflate: zlib header ok\n"));
  83155. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83156. state->mode = hold & 0x200 ? DICTID : TYPE;
  83157. INITBITS();
  83158. break;
  83159. #ifdef GUNZIP
  83160. case FLAGS:
  83161. NEEDBITS(16);
  83162. state->flags = (int)(hold);
  83163. if ((state->flags & 0xff) != Z_DEFLATED) {
  83164. strm->msg = (char *)"unknown compression method";
  83165. state->mode = BAD;
  83166. break;
  83167. }
  83168. if (state->flags & 0xe000) {
  83169. strm->msg = (char *)"unknown header flags set";
  83170. state->mode = BAD;
  83171. break;
  83172. }
  83173. if (state->head != Z_NULL)
  83174. state->head->text = (int)((hold >> 8) & 1);
  83175. if (state->flags & 0x0200) CRC2(state->check, hold);
  83176. INITBITS();
  83177. state->mode = TIME;
  83178. case TIME:
  83179. NEEDBITS(32);
  83180. if (state->head != Z_NULL)
  83181. state->head->time = hold;
  83182. if (state->flags & 0x0200) CRC4(state->check, hold);
  83183. INITBITS();
  83184. state->mode = OS;
  83185. case OS:
  83186. NEEDBITS(16);
  83187. if (state->head != Z_NULL) {
  83188. state->head->xflags = (int)(hold & 0xff);
  83189. state->head->os = (int)(hold >> 8);
  83190. }
  83191. if (state->flags & 0x0200) CRC2(state->check, hold);
  83192. INITBITS();
  83193. state->mode = EXLEN;
  83194. case EXLEN:
  83195. if (state->flags & 0x0400) {
  83196. NEEDBITS(16);
  83197. state->length = (unsigned)(hold);
  83198. if (state->head != Z_NULL)
  83199. state->head->extra_len = (unsigned)hold;
  83200. if (state->flags & 0x0200) CRC2(state->check, hold);
  83201. INITBITS();
  83202. }
  83203. else if (state->head != Z_NULL)
  83204. state->head->extra = Z_NULL;
  83205. state->mode = EXTRA;
  83206. case EXTRA:
  83207. if (state->flags & 0x0400) {
  83208. copy = state->length;
  83209. if (copy > have) copy = have;
  83210. if (copy) {
  83211. if (state->head != Z_NULL &&
  83212. state->head->extra != Z_NULL) {
  83213. len = state->head->extra_len - state->length;
  83214. zmemcpy(state->head->extra + len, next,
  83215. len + copy > state->head->extra_max ?
  83216. state->head->extra_max - len : copy);
  83217. }
  83218. if (state->flags & 0x0200)
  83219. state->check = crc32(state->check, next, copy);
  83220. have -= copy;
  83221. next += copy;
  83222. state->length -= copy;
  83223. }
  83224. if (state->length) goto inf_leave;
  83225. }
  83226. state->length = 0;
  83227. state->mode = NAME;
  83228. case NAME:
  83229. if (state->flags & 0x0800) {
  83230. if (have == 0) goto inf_leave;
  83231. copy = 0;
  83232. do {
  83233. len = (unsigned)(next[copy++]);
  83234. if (state->head != Z_NULL &&
  83235. state->head->name != Z_NULL &&
  83236. state->length < state->head->name_max)
  83237. state->head->name[state->length++] = len;
  83238. } while (len && copy < have);
  83239. if (state->flags & 0x0200)
  83240. state->check = crc32(state->check, next, copy);
  83241. have -= copy;
  83242. next += copy;
  83243. if (len) goto inf_leave;
  83244. }
  83245. else if (state->head != Z_NULL)
  83246. state->head->name = Z_NULL;
  83247. state->length = 0;
  83248. state->mode = COMMENT;
  83249. case COMMENT:
  83250. if (state->flags & 0x1000) {
  83251. if (have == 0) goto inf_leave;
  83252. copy = 0;
  83253. do {
  83254. len = (unsigned)(next[copy++]);
  83255. if (state->head != Z_NULL &&
  83256. state->head->comment != Z_NULL &&
  83257. state->length < state->head->comm_max)
  83258. state->head->comment[state->length++] = len;
  83259. } while (len && copy < have);
  83260. if (state->flags & 0x0200)
  83261. state->check = crc32(state->check, next, copy);
  83262. have -= copy;
  83263. next += copy;
  83264. if (len) goto inf_leave;
  83265. }
  83266. else if (state->head != Z_NULL)
  83267. state->head->comment = Z_NULL;
  83268. state->mode = HCRC;
  83269. case HCRC:
  83270. if (state->flags & 0x0200) {
  83271. NEEDBITS(16);
  83272. if (hold != (state->check & 0xffff)) {
  83273. strm->msg = (char *)"header crc mismatch";
  83274. state->mode = BAD;
  83275. break;
  83276. }
  83277. INITBITS();
  83278. }
  83279. if (state->head != Z_NULL) {
  83280. state->head->hcrc = (int)((state->flags >> 9) & 1);
  83281. state->head->done = 1;
  83282. }
  83283. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  83284. state->mode = TYPE;
  83285. break;
  83286. #endif
  83287. case DICTID:
  83288. NEEDBITS(32);
  83289. strm->adler = state->check = REVERSE(hold);
  83290. INITBITS();
  83291. state->mode = DICT;
  83292. case DICT:
  83293. if (state->havedict == 0) {
  83294. RESTORE();
  83295. return Z_NEED_DICT;
  83296. }
  83297. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83298. state->mode = TYPE;
  83299. case TYPE:
  83300. if (flush == Z_BLOCK) goto inf_leave;
  83301. case TYPEDO:
  83302. if (state->last) {
  83303. BYTEBITS();
  83304. state->mode = CHECK;
  83305. break;
  83306. }
  83307. NEEDBITS(3);
  83308. state->last = BITS(1);
  83309. DROPBITS(1);
  83310. switch (BITS(2)) {
  83311. case 0: /* stored block */
  83312. Tracev((stderr, "inflate: stored block%s\n",
  83313. state->last ? " (last)" : ""));
  83314. state->mode = STORED;
  83315. break;
  83316. case 1: /* fixed block */
  83317. fixedtables(state);
  83318. Tracev((stderr, "inflate: fixed codes block%s\n",
  83319. state->last ? " (last)" : ""));
  83320. state->mode = LEN; /* decode codes */
  83321. break;
  83322. case 2: /* dynamic block */
  83323. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83324. state->last ? " (last)" : ""));
  83325. state->mode = TABLE;
  83326. break;
  83327. case 3:
  83328. strm->msg = (char *)"invalid block type";
  83329. state->mode = BAD;
  83330. }
  83331. DROPBITS(2);
  83332. break;
  83333. case STORED:
  83334. BYTEBITS(); /* go to byte boundary */
  83335. NEEDBITS(32);
  83336. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83337. strm->msg = (char *)"invalid stored block lengths";
  83338. state->mode = BAD;
  83339. break;
  83340. }
  83341. state->length = (unsigned)hold & 0xffff;
  83342. Tracev((stderr, "inflate: stored length %u\n",
  83343. state->length));
  83344. INITBITS();
  83345. state->mode = COPY;
  83346. case COPY:
  83347. copy = state->length;
  83348. if (copy) {
  83349. if (copy > have) copy = have;
  83350. if (copy > left) copy = left;
  83351. if (copy == 0) goto inf_leave;
  83352. zmemcpy(put, next, copy);
  83353. have -= copy;
  83354. next += copy;
  83355. left -= copy;
  83356. put += copy;
  83357. state->length -= copy;
  83358. break;
  83359. }
  83360. Tracev((stderr, "inflate: stored end\n"));
  83361. state->mode = TYPE;
  83362. break;
  83363. case TABLE:
  83364. NEEDBITS(14);
  83365. state->nlen = BITS(5) + 257;
  83366. DROPBITS(5);
  83367. state->ndist = BITS(5) + 1;
  83368. DROPBITS(5);
  83369. state->ncode = BITS(4) + 4;
  83370. DROPBITS(4);
  83371. #ifndef PKZIP_BUG_WORKAROUND
  83372. if (state->nlen > 286 || state->ndist > 30) {
  83373. strm->msg = (char *)"too many length or distance symbols";
  83374. state->mode = BAD;
  83375. break;
  83376. }
  83377. #endif
  83378. Tracev((stderr, "inflate: table sizes ok\n"));
  83379. state->have = 0;
  83380. state->mode = LENLENS;
  83381. case LENLENS:
  83382. while (state->have < state->ncode) {
  83383. NEEDBITS(3);
  83384. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  83385. DROPBITS(3);
  83386. }
  83387. while (state->have < 19)
  83388. state->lens[order[state->have++]] = 0;
  83389. state->next = state->codes;
  83390. state->lencode = (code const FAR *)(state->next);
  83391. state->lenbits = 7;
  83392. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  83393. &(state->lenbits), state->work);
  83394. if (ret) {
  83395. strm->msg = (char *)"invalid code lengths set";
  83396. state->mode = BAD;
  83397. break;
  83398. }
  83399. Tracev((stderr, "inflate: code lengths ok\n"));
  83400. state->have = 0;
  83401. state->mode = CODELENS;
  83402. case CODELENS:
  83403. while (state->have < state->nlen + state->ndist) {
  83404. for (;;) {
  83405. thisx = state->lencode[BITS(state->lenbits)];
  83406. if ((unsigned)(thisx.bits) <= bits) break;
  83407. PULLBYTE();
  83408. }
  83409. if (thisx.val < 16) {
  83410. NEEDBITS(thisx.bits);
  83411. DROPBITS(thisx.bits);
  83412. state->lens[state->have++] = thisx.val;
  83413. }
  83414. else {
  83415. if (thisx.val == 16) {
  83416. NEEDBITS(thisx.bits + 2);
  83417. DROPBITS(thisx.bits);
  83418. if (state->have == 0) {
  83419. strm->msg = (char *)"invalid bit length repeat";
  83420. state->mode = BAD;
  83421. break;
  83422. }
  83423. len = state->lens[state->have - 1];
  83424. copy = 3 + BITS(2);
  83425. DROPBITS(2);
  83426. }
  83427. else if (thisx.val == 17) {
  83428. NEEDBITS(thisx.bits + 3);
  83429. DROPBITS(thisx.bits);
  83430. len = 0;
  83431. copy = 3 + BITS(3);
  83432. DROPBITS(3);
  83433. }
  83434. else {
  83435. NEEDBITS(thisx.bits + 7);
  83436. DROPBITS(thisx.bits);
  83437. len = 0;
  83438. copy = 11 + BITS(7);
  83439. DROPBITS(7);
  83440. }
  83441. if (state->have + copy > state->nlen + state->ndist) {
  83442. strm->msg = (char *)"invalid bit length repeat";
  83443. state->mode = BAD;
  83444. break;
  83445. }
  83446. while (copy--)
  83447. state->lens[state->have++] = (unsigned short)len;
  83448. }
  83449. }
  83450. /* handle error breaks in while */
  83451. if (state->mode == BAD) break;
  83452. /* build code tables */
  83453. state->next = state->codes;
  83454. state->lencode = (code const FAR *)(state->next);
  83455. state->lenbits = 9;
  83456. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  83457. &(state->lenbits), state->work);
  83458. if (ret) {
  83459. strm->msg = (char *)"invalid literal/lengths set";
  83460. state->mode = BAD;
  83461. break;
  83462. }
  83463. state->distcode = (code const FAR *)(state->next);
  83464. state->distbits = 6;
  83465. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  83466. &(state->next), &(state->distbits), state->work);
  83467. if (ret) {
  83468. strm->msg = (char *)"invalid distances set";
  83469. state->mode = BAD;
  83470. break;
  83471. }
  83472. Tracev((stderr, "inflate: codes ok\n"));
  83473. state->mode = LEN;
  83474. case LEN:
  83475. if (have >= 6 && left >= 258) {
  83476. RESTORE();
  83477. inflate_fast(strm, out);
  83478. LOAD();
  83479. break;
  83480. }
  83481. for (;;) {
  83482. thisx = state->lencode[BITS(state->lenbits)];
  83483. if ((unsigned)(thisx.bits) <= bits) break;
  83484. PULLBYTE();
  83485. }
  83486. if (thisx.op && (thisx.op & 0xf0) == 0) {
  83487. last = thisx;
  83488. for (;;) {
  83489. thisx = state->lencode[last.val +
  83490. (BITS(last.bits + last.op) >> last.bits)];
  83491. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83492. PULLBYTE();
  83493. }
  83494. DROPBITS(last.bits);
  83495. }
  83496. DROPBITS(thisx.bits);
  83497. state->length = (unsigned)thisx.val;
  83498. if ((int)(thisx.op) == 0) {
  83499. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83500. "inflate: literal '%c'\n" :
  83501. "inflate: literal 0x%02x\n", thisx.val));
  83502. state->mode = LIT;
  83503. break;
  83504. }
  83505. if (thisx.op & 32) {
  83506. Tracevv((stderr, "inflate: end of block\n"));
  83507. state->mode = TYPE;
  83508. break;
  83509. }
  83510. if (thisx.op & 64) {
  83511. strm->msg = (char *)"invalid literal/length code";
  83512. state->mode = BAD;
  83513. break;
  83514. }
  83515. state->extra = (unsigned)(thisx.op) & 15;
  83516. state->mode = LENEXT;
  83517. case LENEXT:
  83518. if (state->extra) {
  83519. NEEDBITS(state->extra);
  83520. state->length += BITS(state->extra);
  83521. DROPBITS(state->extra);
  83522. }
  83523. Tracevv((stderr, "inflate: length %u\n", state->length));
  83524. state->mode = DIST;
  83525. case DIST:
  83526. for (;;) {
  83527. thisx = state->distcode[BITS(state->distbits)];
  83528. if ((unsigned)(thisx.bits) <= bits) break;
  83529. PULLBYTE();
  83530. }
  83531. if ((thisx.op & 0xf0) == 0) {
  83532. last = thisx;
  83533. for (;;) {
  83534. thisx = state->distcode[last.val +
  83535. (BITS(last.bits + last.op) >> last.bits)];
  83536. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83537. PULLBYTE();
  83538. }
  83539. DROPBITS(last.bits);
  83540. }
  83541. DROPBITS(thisx.bits);
  83542. if (thisx.op & 64) {
  83543. strm->msg = (char *)"invalid distance code";
  83544. state->mode = BAD;
  83545. break;
  83546. }
  83547. state->offset = (unsigned)thisx.val;
  83548. state->extra = (unsigned)(thisx.op) & 15;
  83549. state->mode = DISTEXT;
  83550. case DISTEXT:
  83551. if (state->extra) {
  83552. NEEDBITS(state->extra);
  83553. state->offset += BITS(state->extra);
  83554. DROPBITS(state->extra);
  83555. }
  83556. #ifdef INFLATE_STRICT
  83557. if (state->offset > state->dmax) {
  83558. strm->msg = (char *)"invalid distance too far back";
  83559. state->mode = BAD;
  83560. break;
  83561. }
  83562. #endif
  83563. if (state->offset > state->whave + out - left) {
  83564. strm->msg = (char *)"invalid distance too far back";
  83565. state->mode = BAD;
  83566. break;
  83567. }
  83568. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  83569. state->mode = MATCH;
  83570. case MATCH:
  83571. if (left == 0) goto inf_leave;
  83572. copy = out - left;
  83573. if (state->offset > copy) { /* copy from window */
  83574. copy = state->offset - copy;
  83575. if (copy > state->write) {
  83576. copy -= state->write;
  83577. from = state->window + (state->wsize - copy);
  83578. }
  83579. else
  83580. from = state->window + (state->write - copy);
  83581. if (copy > state->length) copy = state->length;
  83582. }
  83583. else { /* copy from output */
  83584. from = put - state->offset;
  83585. copy = state->length;
  83586. }
  83587. if (copy > left) copy = left;
  83588. left -= copy;
  83589. state->length -= copy;
  83590. do {
  83591. *put++ = *from++;
  83592. } while (--copy);
  83593. if (state->length == 0) state->mode = LEN;
  83594. break;
  83595. case LIT:
  83596. if (left == 0) goto inf_leave;
  83597. *put++ = (unsigned char)(state->length);
  83598. left--;
  83599. state->mode = LEN;
  83600. break;
  83601. case CHECK:
  83602. if (state->wrap) {
  83603. NEEDBITS(32);
  83604. out -= left;
  83605. strm->total_out += out;
  83606. state->total += out;
  83607. if (out)
  83608. strm->adler = state->check =
  83609. UPDATE(state->check, put - out, out);
  83610. out = left;
  83611. if ((
  83612. #ifdef GUNZIP
  83613. state->flags ? hold :
  83614. #endif
  83615. REVERSE(hold)) != state->check) {
  83616. strm->msg = (char *)"incorrect data check";
  83617. state->mode = BAD;
  83618. break;
  83619. }
  83620. INITBITS();
  83621. Tracev((stderr, "inflate: check matches trailer\n"));
  83622. }
  83623. #ifdef GUNZIP
  83624. state->mode = LENGTH;
  83625. case LENGTH:
  83626. if (state->wrap && state->flags) {
  83627. NEEDBITS(32);
  83628. if (hold != (state->total & 0xffffffffUL)) {
  83629. strm->msg = (char *)"incorrect length check";
  83630. state->mode = BAD;
  83631. break;
  83632. }
  83633. INITBITS();
  83634. Tracev((stderr, "inflate: length matches trailer\n"));
  83635. }
  83636. #endif
  83637. state->mode = DONE;
  83638. case DONE:
  83639. ret = Z_STREAM_END;
  83640. goto inf_leave;
  83641. case BAD:
  83642. ret = Z_DATA_ERROR;
  83643. goto inf_leave;
  83644. case MEM:
  83645. return Z_MEM_ERROR;
  83646. case SYNC:
  83647. default:
  83648. return Z_STREAM_ERROR;
  83649. }
  83650. /*
  83651. Return from inflate(), updating the total counts and the check value.
  83652. If there was no progress during the inflate() call, return a buffer
  83653. error. Call updatewindow() to create and/or update the window state.
  83654. Note: a memory error from inflate() is non-recoverable.
  83655. */
  83656. inf_leave:
  83657. RESTORE();
  83658. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  83659. if (updatewindow(strm, out)) {
  83660. state->mode = MEM;
  83661. return Z_MEM_ERROR;
  83662. }
  83663. in -= strm->avail_in;
  83664. out -= strm->avail_out;
  83665. strm->total_in += in;
  83666. strm->total_out += out;
  83667. state->total += out;
  83668. if (state->wrap && out)
  83669. strm->adler = state->check =
  83670. UPDATE(state->check, strm->next_out - out, out);
  83671. strm->data_type = state->bits + (state->last ? 64 : 0) +
  83672. (state->mode == TYPE ? 128 : 0);
  83673. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  83674. ret = Z_BUF_ERROR;
  83675. return ret;
  83676. }
  83677. int ZEXPORT inflateEnd (z_streamp strm)
  83678. {
  83679. struct inflate_state FAR *state;
  83680. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  83681. return Z_STREAM_ERROR;
  83682. state = (struct inflate_state FAR *)strm->state;
  83683. if (state->window != Z_NULL) ZFREE(strm, state->window);
  83684. ZFREE(strm, strm->state);
  83685. strm->state = Z_NULL;
  83686. Tracev((stderr, "inflate: end\n"));
  83687. return Z_OK;
  83688. }
  83689. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  83690. {
  83691. struct inflate_state FAR *state;
  83692. unsigned long id_;
  83693. /* check state */
  83694. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83695. state = (struct inflate_state FAR *)strm->state;
  83696. if (state->wrap != 0 && state->mode != DICT)
  83697. return Z_STREAM_ERROR;
  83698. /* check for correct dictionary id */
  83699. if (state->mode == DICT) {
  83700. id_ = adler32(0L, Z_NULL, 0);
  83701. id_ = adler32(id_, dictionary, dictLength);
  83702. if (id_ != state->check)
  83703. return Z_DATA_ERROR;
  83704. }
  83705. /* copy dictionary to window */
  83706. if (updatewindow(strm, strm->avail_out)) {
  83707. state->mode = MEM;
  83708. return Z_MEM_ERROR;
  83709. }
  83710. if (dictLength > state->wsize) {
  83711. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  83712. state->wsize);
  83713. state->whave = state->wsize;
  83714. }
  83715. else {
  83716. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  83717. dictLength);
  83718. state->whave = dictLength;
  83719. }
  83720. state->havedict = 1;
  83721. Tracev((stderr, "inflate: dictionary set\n"));
  83722. return Z_OK;
  83723. }
  83724. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  83725. {
  83726. struct inflate_state FAR *state;
  83727. /* check state */
  83728. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83729. state = (struct inflate_state FAR *)strm->state;
  83730. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  83731. /* save header structure */
  83732. state->head = head;
  83733. head->done = 0;
  83734. return Z_OK;
  83735. }
  83736. /*
  83737. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  83738. or when out of input. When called, *have is the number of pattern bytes
  83739. found in order so far, in 0..3. On return *have is updated to the new
  83740. state. If on return *have equals four, then the pattern was found and the
  83741. return value is how many bytes were read including the last byte of the
  83742. pattern. If *have is less than four, then the pattern has not been found
  83743. yet and the return value is len. In the latter case, syncsearch() can be
  83744. called again with more data and the *have state. *have is initialized to
  83745. zero for the first call.
  83746. */
  83747. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  83748. {
  83749. unsigned got;
  83750. unsigned next;
  83751. got = *have;
  83752. next = 0;
  83753. while (next < len && got < 4) {
  83754. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  83755. got++;
  83756. else if (buf[next])
  83757. got = 0;
  83758. else
  83759. got = 4 - got;
  83760. next++;
  83761. }
  83762. *have = got;
  83763. return next;
  83764. }
  83765. int ZEXPORT inflateSync (z_streamp strm)
  83766. {
  83767. unsigned len; /* number of bytes to look at or looked at */
  83768. unsigned long in, out; /* temporary to save total_in and total_out */
  83769. unsigned char buf[4]; /* to restore bit buffer to byte string */
  83770. struct inflate_state FAR *state;
  83771. /* check parameters */
  83772. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83773. state = (struct inflate_state FAR *)strm->state;
  83774. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  83775. /* if first time, start search in bit buffer */
  83776. if (state->mode != SYNC) {
  83777. state->mode = SYNC;
  83778. state->hold <<= state->bits & 7;
  83779. state->bits -= state->bits & 7;
  83780. len = 0;
  83781. while (state->bits >= 8) {
  83782. buf[len++] = (unsigned char)(state->hold);
  83783. state->hold >>= 8;
  83784. state->bits -= 8;
  83785. }
  83786. state->have = 0;
  83787. syncsearch(&(state->have), buf, len);
  83788. }
  83789. /* search available input */
  83790. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  83791. strm->avail_in -= len;
  83792. strm->next_in += len;
  83793. strm->total_in += len;
  83794. /* return no joy or set up to restart inflate() on a new block */
  83795. if (state->have != 4) return Z_DATA_ERROR;
  83796. in = strm->total_in; out = strm->total_out;
  83797. inflateReset(strm);
  83798. strm->total_in = in; strm->total_out = out;
  83799. state->mode = TYPE;
  83800. return Z_OK;
  83801. }
  83802. /*
  83803. Returns true if inflate is currently at the end of a block generated by
  83804. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  83805. implementation to provide an additional safety check. PPP uses
  83806. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  83807. block. When decompressing, PPP checks that at the end of input packet,
  83808. inflate is waiting for these length bytes.
  83809. */
  83810. int ZEXPORT inflateSyncPoint (z_streamp strm)
  83811. {
  83812. struct inflate_state FAR *state;
  83813. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83814. state = (struct inflate_state FAR *)strm->state;
  83815. return state->mode == STORED && state->bits == 0;
  83816. }
  83817. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  83818. {
  83819. struct inflate_state FAR *state;
  83820. struct inflate_state FAR *copy;
  83821. unsigned char FAR *window;
  83822. unsigned wsize;
  83823. /* check input */
  83824. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  83825. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  83826. return Z_STREAM_ERROR;
  83827. state = (struct inflate_state FAR *)source->state;
  83828. /* allocate space */
  83829. copy = (struct inflate_state FAR *)
  83830. ZALLOC(source, 1, sizeof(struct inflate_state));
  83831. if (copy == Z_NULL) return Z_MEM_ERROR;
  83832. window = Z_NULL;
  83833. if (state->window != Z_NULL) {
  83834. window = (unsigned char FAR *)
  83835. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  83836. if (window == Z_NULL) {
  83837. ZFREE(source, copy);
  83838. return Z_MEM_ERROR;
  83839. }
  83840. }
  83841. /* copy state */
  83842. zmemcpy(dest, source, sizeof(z_stream));
  83843. zmemcpy(copy, state, sizeof(struct inflate_state));
  83844. if (state->lencode >= state->codes &&
  83845. state->lencode <= state->codes + ENOUGH - 1) {
  83846. copy->lencode = copy->codes + (state->lencode - state->codes);
  83847. copy->distcode = copy->codes + (state->distcode - state->codes);
  83848. }
  83849. copy->next = copy->codes + (state->next - state->codes);
  83850. if (window != Z_NULL) {
  83851. wsize = 1U << state->wbits;
  83852. zmemcpy(window, state->window, wsize);
  83853. }
  83854. copy->window = window;
  83855. dest->state = (struct internal_state FAR *)copy;
  83856. return Z_OK;
  83857. }
  83858. /*** End of inlined file: inflate.c ***/
  83859. /*** Start of inlined file: inftrees.c ***/
  83860. #define MAXBITS 15
  83861. const char inflate_copyright[] =
  83862. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  83863. /*
  83864. If you use the zlib library in a product, an acknowledgment is welcome
  83865. in the documentation of your product. If for some reason you cannot
  83866. include such an acknowledgment, I would appreciate that you keep this
  83867. copyright string in the executable of your product.
  83868. */
  83869. /*
  83870. Build a set of tables to decode the provided canonical Huffman code.
  83871. The code lengths are lens[0..codes-1]. The result starts at *table,
  83872. whose indices are 0..2^bits-1. work is a writable array of at least
  83873. lens shorts, which is used as a work area. type is the type of code
  83874. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  83875. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  83876. on return points to the next available entry's address. bits is the
  83877. requested root table index bits, and on return it is the actual root
  83878. table index bits. It will differ if the request is greater than the
  83879. longest code or if it is less than the shortest code.
  83880. */
  83881. int inflate_table (codetype type,
  83882. unsigned short FAR *lens,
  83883. unsigned codes,
  83884. code FAR * FAR *table,
  83885. unsigned FAR *bits,
  83886. unsigned short FAR *work)
  83887. {
  83888. unsigned len; /* a code's length in bits */
  83889. unsigned sym; /* index of code symbols */
  83890. unsigned min, max; /* minimum and maximum code lengths */
  83891. unsigned root; /* number of index bits for root table */
  83892. unsigned curr; /* number of index bits for current table */
  83893. unsigned drop; /* code bits to drop for sub-table */
  83894. int left; /* number of prefix codes available */
  83895. unsigned used; /* code entries in table used */
  83896. unsigned huff; /* Huffman code */
  83897. unsigned incr; /* for incrementing code, index */
  83898. unsigned fill; /* index for replicating entries */
  83899. unsigned low; /* low bits for current root entry */
  83900. unsigned mask; /* mask for low root bits */
  83901. code thisx; /* table entry for duplication */
  83902. code FAR *next; /* next available space in table */
  83903. const unsigned short FAR *base; /* base value table to use */
  83904. const unsigned short FAR *extra; /* extra bits table to use */
  83905. int end; /* use base and extra for symbol > end */
  83906. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  83907. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  83908. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  83909. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  83910. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  83911. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  83912. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  83913. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  83914. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  83915. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  83916. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  83917. 8193, 12289, 16385, 24577, 0, 0};
  83918. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  83919. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  83920. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  83921. 28, 28, 29, 29, 64, 64};
  83922. /*
  83923. Process a set of code lengths to create a canonical Huffman code. The
  83924. code lengths are lens[0..codes-1]. Each length corresponds to the
  83925. symbols 0..codes-1. The Huffman code is generated by first sorting the
  83926. symbols by length from short to long, and retaining the symbol order
  83927. for codes with equal lengths. Then the code starts with all zero bits
  83928. for the first code of the shortest length, and the codes are integer
  83929. increments for the same length, and zeros are appended as the length
  83930. increases. For the deflate format, these bits are stored backwards
  83931. from their more natural integer increment ordering, and so when the
  83932. decoding tables are built in the large loop below, the integer codes
  83933. are incremented backwards.
  83934. This routine assumes, but does not check, that all of the entries in
  83935. lens[] are in the range 0..MAXBITS. The caller must assure this.
  83936. 1..MAXBITS is interpreted as that code length. zero means that that
  83937. symbol does not occur in this code.
  83938. The codes are sorted by computing a count of codes for each length,
  83939. creating from that a table of starting indices for each length in the
  83940. sorted table, and then entering the symbols in order in the sorted
  83941. table. The sorted table is work[], with that space being provided by
  83942. the caller.
  83943. The length counts are used for other purposes as well, i.e. finding
  83944. the minimum and maximum length codes, determining if there are any
  83945. codes at all, checking for a valid set of lengths, and looking ahead
  83946. at length counts to determine sub-table sizes when building the
  83947. decoding tables.
  83948. */
  83949. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  83950. for (len = 0; len <= MAXBITS; len++)
  83951. count[len] = 0;
  83952. for (sym = 0; sym < codes; sym++)
  83953. count[lens[sym]]++;
  83954. /* bound code lengths, force root to be within code lengths */
  83955. root = *bits;
  83956. for (max = MAXBITS; max >= 1; max--)
  83957. if (count[max] != 0) break;
  83958. if (root > max) root = max;
  83959. if (max == 0) { /* no symbols to code at all */
  83960. thisx.op = (unsigned char)64; /* invalid code marker */
  83961. thisx.bits = (unsigned char)1;
  83962. thisx.val = (unsigned short)0;
  83963. *(*table)++ = thisx; /* make a table to force an error */
  83964. *(*table)++ = thisx;
  83965. *bits = 1;
  83966. return 0; /* no symbols, but wait for decoding to report error */
  83967. }
  83968. for (min = 1; min <= MAXBITS; min++)
  83969. if (count[min] != 0) break;
  83970. if (root < min) root = min;
  83971. /* check for an over-subscribed or incomplete set of lengths */
  83972. left = 1;
  83973. for (len = 1; len <= MAXBITS; len++) {
  83974. left <<= 1;
  83975. left -= count[len];
  83976. if (left < 0) return -1; /* over-subscribed */
  83977. }
  83978. if (left > 0 && (type == CODES || max != 1))
  83979. return -1; /* incomplete set */
  83980. /* generate offsets into symbol table for each length for sorting */
  83981. offs[1] = 0;
  83982. for (len = 1; len < MAXBITS; len++)
  83983. offs[len + 1] = offs[len] + count[len];
  83984. /* sort symbols by length, by symbol order within each length */
  83985. for (sym = 0; sym < codes; sym++)
  83986. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  83987. /*
  83988. Create and fill in decoding tables. In this loop, the table being
  83989. filled is at next and has curr index bits. The code being used is huff
  83990. with length len. That code is converted to an index by dropping drop
  83991. bits off of the bottom. For codes where len is less than drop + curr,
  83992. those top drop + curr - len bits are incremented through all values to
  83993. fill the table with replicated entries.
  83994. root is the number of index bits for the root table. When len exceeds
  83995. root, sub-tables are created pointed to by the root entry with an index
  83996. of the low root bits of huff. This is saved in low to check for when a
  83997. new sub-table should be started. drop is zero when the root table is
  83998. being filled, and drop is root when sub-tables are being filled.
  83999. When a new sub-table is needed, it is necessary to look ahead in the
  84000. code lengths to determine what size sub-table is needed. The length
  84001. counts are used for this, and so count[] is decremented as codes are
  84002. entered in the tables.
  84003. used keeps track of how many table entries have been allocated from the
  84004. provided *table space. It is checked when a LENS table is being made
  84005. against the space in *table, ENOUGH, minus the maximum space needed by
  84006. the worst case distance code, MAXD. This should never happen, but the
  84007. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84008. This assumes that when type == LENS, bits == 9.
  84009. sym increments through all symbols, and the loop terminates when
  84010. all codes of length max, i.e. all codes, have been processed. This
  84011. routine permits incomplete codes, so another loop after this one fills
  84012. in the rest of the decoding tables with invalid code markers.
  84013. */
  84014. /* set up for code type */
  84015. switch (type) {
  84016. case CODES:
  84017. base = extra = work; /* dummy value--not used */
  84018. end = 19;
  84019. break;
  84020. case LENS:
  84021. base = lbase;
  84022. base -= 257;
  84023. extra = lext;
  84024. extra -= 257;
  84025. end = 256;
  84026. break;
  84027. default: /* DISTS */
  84028. base = dbase;
  84029. extra = dext;
  84030. end = -1;
  84031. }
  84032. /* initialize state for loop */
  84033. huff = 0; /* starting code */
  84034. sym = 0; /* starting code symbol */
  84035. len = min; /* starting code length */
  84036. next = *table; /* current table to fill in */
  84037. curr = root; /* current table index bits */
  84038. drop = 0; /* current bits to drop from code for index */
  84039. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84040. used = 1U << root; /* use root table entries */
  84041. mask = used - 1; /* mask for comparing low */
  84042. /* check available table space */
  84043. if (type == LENS && used >= ENOUGH - MAXD)
  84044. return 1;
  84045. /* process all codes and make table entries */
  84046. for (;;) {
  84047. /* create table entry */
  84048. thisx.bits = (unsigned char)(len - drop);
  84049. if ((int)(work[sym]) < end) {
  84050. thisx.op = (unsigned char)0;
  84051. thisx.val = work[sym];
  84052. }
  84053. else if ((int)(work[sym]) > end) {
  84054. thisx.op = (unsigned char)(extra[work[sym]]);
  84055. thisx.val = base[work[sym]];
  84056. }
  84057. else {
  84058. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84059. thisx.val = 0;
  84060. }
  84061. /* replicate for those indices with low len bits equal to huff */
  84062. incr = 1U << (len - drop);
  84063. fill = 1U << curr;
  84064. min = fill; /* save offset to next table */
  84065. do {
  84066. fill -= incr;
  84067. next[(huff >> drop) + fill] = thisx;
  84068. } while (fill != 0);
  84069. /* backwards increment the len-bit code huff */
  84070. incr = 1U << (len - 1);
  84071. while (huff & incr)
  84072. incr >>= 1;
  84073. if (incr != 0) {
  84074. huff &= incr - 1;
  84075. huff += incr;
  84076. }
  84077. else
  84078. huff = 0;
  84079. /* go to next symbol, update count, len */
  84080. sym++;
  84081. if (--(count[len]) == 0) {
  84082. if (len == max) break;
  84083. len = lens[work[sym]];
  84084. }
  84085. /* create new sub-table if needed */
  84086. if (len > root && (huff & mask) != low) {
  84087. /* if first time, transition to sub-tables */
  84088. if (drop == 0)
  84089. drop = root;
  84090. /* increment past last table */
  84091. next += min; /* here min is 1 << curr */
  84092. /* determine length of next table */
  84093. curr = len - drop;
  84094. left = (int)(1 << curr);
  84095. while (curr + drop < max) {
  84096. left -= count[curr + drop];
  84097. if (left <= 0) break;
  84098. curr++;
  84099. left <<= 1;
  84100. }
  84101. /* check for enough space */
  84102. used += 1U << curr;
  84103. if (type == LENS && used >= ENOUGH - MAXD)
  84104. return 1;
  84105. /* point entry in root table to sub-table */
  84106. low = huff & mask;
  84107. (*table)[low].op = (unsigned char)curr;
  84108. (*table)[low].bits = (unsigned char)root;
  84109. (*table)[low].val = (unsigned short)(next - *table);
  84110. }
  84111. }
  84112. /*
  84113. Fill in rest of table for incomplete codes. This loop is similar to the
  84114. loop above in incrementing huff for table indices. It is assumed that
  84115. len is equal to curr + drop, so there is no loop needed to increment
  84116. through high index bits. When the current sub-table is filled, the loop
  84117. drops back to the root table to fill in any remaining entries there.
  84118. */
  84119. thisx.op = (unsigned char)64; /* invalid code marker */
  84120. thisx.bits = (unsigned char)(len - drop);
  84121. thisx.val = (unsigned short)0;
  84122. while (huff != 0) {
  84123. /* when done with sub-table, drop back to root table */
  84124. if (drop != 0 && (huff & mask) != low) {
  84125. drop = 0;
  84126. len = root;
  84127. next = *table;
  84128. thisx.bits = (unsigned char)len;
  84129. }
  84130. /* put invalid code marker in table */
  84131. next[huff >> drop] = thisx;
  84132. /* backwards increment the len-bit code huff */
  84133. incr = 1U << (len - 1);
  84134. while (huff & incr)
  84135. incr >>= 1;
  84136. if (incr != 0) {
  84137. huff &= incr - 1;
  84138. huff += incr;
  84139. }
  84140. else
  84141. huff = 0;
  84142. }
  84143. /* set return parameters */
  84144. *table += used;
  84145. *bits = root;
  84146. return 0;
  84147. }
  84148. /*** End of inlined file: inftrees.c ***/
  84149. /*** Start of inlined file: trees.c ***/
  84150. /*
  84151. * ALGORITHM
  84152. *
  84153. * The "deflation" process uses several Huffman trees. The more
  84154. * common source values are represented by shorter bit sequences.
  84155. *
  84156. * Each code tree is stored in a compressed form which is itself
  84157. * a Huffman encoding of the lengths of all the code strings (in
  84158. * ascending order by source values). The actual code strings are
  84159. * reconstructed from the lengths in the inflate process, as described
  84160. * in the deflate specification.
  84161. *
  84162. * REFERENCES
  84163. *
  84164. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84165. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84166. *
  84167. * Storer, James A.
  84168. * Data Compression: Methods and Theory, pp. 49-50.
  84169. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84170. *
  84171. * Sedgewick, R.
  84172. * Algorithms, p290.
  84173. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84174. */
  84175. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84176. /* #define GEN_TREES_H */
  84177. #ifdef DEBUG
  84178. # include <ctype.h>
  84179. #endif
  84180. /* ===========================================================================
  84181. * Constants
  84182. */
  84183. #define MAX_BL_BITS 7
  84184. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84185. #define END_BLOCK 256
  84186. /* end of block literal code */
  84187. #define REP_3_6 16
  84188. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84189. #define REPZ_3_10 17
  84190. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84191. #define REPZ_11_138 18
  84192. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84193. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84194. = {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};
  84195. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84196. = {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};
  84197. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84198. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84199. local const uch bl_order[BL_CODES]
  84200. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84201. /* The lengths of the bit length codes are sent in order of decreasing
  84202. * probability, to avoid transmitting the lengths for unused bit length codes.
  84203. */
  84204. #define Buf_size (8 * 2*sizeof(char))
  84205. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84206. * more than 16 bits on some systems.)
  84207. */
  84208. /* ===========================================================================
  84209. * Local data. These are initialized only once.
  84210. */
  84211. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84212. #if defined(GEN_TREES_H) || !defined(STDC)
  84213. /* non ANSI compilers may not accept trees.h */
  84214. local ct_data static_ltree[L_CODES+2];
  84215. /* The static literal tree. Since the bit lengths are imposed, there is no
  84216. * need for the L_CODES extra codes used during heap construction. However
  84217. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84218. * below).
  84219. */
  84220. local ct_data static_dtree[D_CODES];
  84221. /* The static distance tree. (Actually a trivial tree since all codes use
  84222. * 5 bits.)
  84223. */
  84224. uch _dist_code[DIST_CODE_LEN];
  84225. /* Distance codes. The first 256 values correspond to the distances
  84226. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84227. * the 15 bit distances.
  84228. */
  84229. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84230. /* length code for each normalized match length (0 == MIN_MATCH) */
  84231. local int base_length[LENGTH_CODES];
  84232. /* First normalized length for each code (0 = MIN_MATCH) */
  84233. local int base_dist[D_CODES];
  84234. /* First normalized distance for each code (0 = distance of 1) */
  84235. #else
  84236. /*** Start of inlined file: trees.h ***/
  84237. local const ct_data static_ltree[L_CODES+2] = {
  84238. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84239. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84240. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84241. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84242. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84243. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84244. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84245. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84246. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84247. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84248. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84249. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84250. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  84251. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  84252. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  84253. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  84254. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  84255. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  84256. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  84257. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  84258. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  84259. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  84260. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  84261. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  84262. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  84263. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  84264. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  84265. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  84266. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  84267. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  84268. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  84269. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  84270. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  84271. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  84272. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  84273. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  84274. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  84275. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  84276. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  84277. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  84278. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  84279. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  84280. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  84281. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  84282. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  84283. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  84284. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  84285. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  84286. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  84287. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  84288. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  84289. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  84290. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  84291. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  84292. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  84293. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  84294. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  84295. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  84296. };
  84297. local const ct_data static_dtree[D_CODES] = {
  84298. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  84299. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  84300. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  84301. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  84302. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  84303. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  84304. };
  84305. const uch _dist_code[DIST_CODE_LEN] = {
  84306. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84307. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84308. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84309. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84310. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84311. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84312. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84313. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84314. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84315. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84316. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84317. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84318. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84319. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84320. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84321. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84322. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84323. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84324. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84325. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84326. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84327. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84328. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84329. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84330. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84331. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84332. };
  84333. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84334. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84335. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84336. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84337. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84338. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84339. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84340. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84341. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84342. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84343. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84344. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84345. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84346. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84347. };
  84348. local const int base_length[LENGTH_CODES] = {
  84349. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84350. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84351. };
  84352. local const int base_dist[D_CODES] = {
  84353. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84354. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84355. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84356. };
  84357. /*** End of inlined file: trees.h ***/
  84358. #endif /* GEN_TREES_H */
  84359. struct static_tree_desc_s {
  84360. const ct_data *static_tree; /* static tree or NULL */
  84361. const intf *extra_bits; /* extra bits for each code or NULL */
  84362. int extra_base; /* base index for extra_bits */
  84363. int elems; /* max number of elements in the tree */
  84364. int max_length; /* max bit length for the codes */
  84365. };
  84366. local static_tree_desc static_l_desc =
  84367. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  84368. local static_tree_desc static_d_desc =
  84369. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  84370. local static_tree_desc static_bl_desc =
  84371. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  84372. /* ===========================================================================
  84373. * Local (static) routines in this file.
  84374. */
  84375. local void tr_static_init OF((void));
  84376. local void init_block OF((deflate_state *s));
  84377. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  84378. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  84379. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  84380. local void build_tree OF((deflate_state *s, tree_desc *desc));
  84381. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84382. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84383. local int build_bl_tree OF((deflate_state *s));
  84384. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  84385. int blcodes));
  84386. local void compress_block OF((deflate_state *s, ct_data *ltree,
  84387. ct_data *dtree));
  84388. local void set_data_type OF((deflate_state *s));
  84389. local unsigned bi_reverse OF((unsigned value, int length));
  84390. local void bi_windup OF((deflate_state *s));
  84391. local void bi_flush OF((deflate_state *s));
  84392. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  84393. int header));
  84394. #ifdef GEN_TREES_H
  84395. local void gen_trees_header OF((void));
  84396. #endif
  84397. #ifndef DEBUG
  84398. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  84399. /* Send a code of the given tree. c and tree must not have side effects */
  84400. #else /* DEBUG */
  84401. # define send_code(s, c, tree) \
  84402. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  84403. send_bits(s, tree[c].Code, tree[c].Len); }
  84404. #endif
  84405. /* ===========================================================================
  84406. * Output a short LSB first on the stream.
  84407. * IN assertion: there is enough room in pendingBuf.
  84408. */
  84409. #define put_short(s, w) { \
  84410. put_byte(s, (uch)((w) & 0xff)); \
  84411. put_byte(s, (uch)((ush)(w) >> 8)); \
  84412. }
  84413. /* ===========================================================================
  84414. * Send a value on a given number of bits.
  84415. * IN assertion: length <= 16 and value fits in length bits.
  84416. */
  84417. #ifdef DEBUG
  84418. local void send_bits OF((deflate_state *s, int value, int length));
  84419. local void send_bits (deflate_state *s, int value, int length)
  84420. {
  84421. Tracevv((stderr," l %2d v %4x ", length, value));
  84422. Assert(length > 0 && length <= 15, "invalid length");
  84423. s->bits_sent += (ulg)length;
  84424. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  84425. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  84426. * unused bits in value.
  84427. */
  84428. if (s->bi_valid > (int)Buf_size - length) {
  84429. s->bi_buf |= (value << s->bi_valid);
  84430. put_short(s, s->bi_buf);
  84431. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  84432. s->bi_valid += length - Buf_size;
  84433. } else {
  84434. s->bi_buf |= value << s->bi_valid;
  84435. s->bi_valid += length;
  84436. }
  84437. }
  84438. #else /* !DEBUG */
  84439. #define send_bits(s, value, length) \
  84440. { int len = length;\
  84441. if (s->bi_valid > (int)Buf_size - len) {\
  84442. int val = value;\
  84443. s->bi_buf |= (val << s->bi_valid);\
  84444. put_short(s, s->bi_buf);\
  84445. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  84446. s->bi_valid += len - Buf_size;\
  84447. } else {\
  84448. s->bi_buf |= (value) << s->bi_valid;\
  84449. s->bi_valid += len;\
  84450. }\
  84451. }
  84452. #endif /* DEBUG */
  84453. /* the arguments must not have side effects */
  84454. /* ===========================================================================
  84455. * Initialize the various 'constant' tables.
  84456. */
  84457. local void tr_static_init()
  84458. {
  84459. #if defined(GEN_TREES_H) || !defined(STDC)
  84460. static int static_init_done = 0;
  84461. int n; /* iterates over tree elements */
  84462. int bits; /* bit counter */
  84463. int length; /* length value */
  84464. int code; /* code value */
  84465. int dist; /* distance index */
  84466. ush bl_count[MAX_BITS+1];
  84467. /* number of codes at each bit length for an optimal tree */
  84468. if (static_init_done) return;
  84469. /* For some embedded targets, global variables are not initialized: */
  84470. static_l_desc.static_tree = static_ltree;
  84471. static_l_desc.extra_bits = extra_lbits;
  84472. static_d_desc.static_tree = static_dtree;
  84473. static_d_desc.extra_bits = extra_dbits;
  84474. static_bl_desc.extra_bits = extra_blbits;
  84475. /* Initialize the mapping length (0..255) -> length code (0..28) */
  84476. length = 0;
  84477. for (code = 0; code < LENGTH_CODES-1; code++) {
  84478. base_length[code] = length;
  84479. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  84480. _length_code[length++] = (uch)code;
  84481. }
  84482. }
  84483. Assert (length == 256, "tr_static_init: length != 256");
  84484. /* Note that the length 255 (match length 258) can be represented
  84485. * in two different ways: code 284 + 5 bits or code 285, so we
  84486. * overwrite length_code[255] to use the best encoding:
  84487. */
  84488. _length_code[length-1] = (uch)code;
  84489. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  84490. dist = 0;
  84491. for (code = 0 ; code < 16; code++) {
  84492. base_dist[code] = dist;
  84493. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  84494. _dist_code[dist++] = (uch)code;
  84495. }
  84496. }
  84497. Assert (dist == 256, "tr_static_init: dist != 256");
  84498. dist >>= 7; /* from now on, all distances are divided by 128 */
  84499. for ( ; code < D_CODES; code++) {
  84500. base_dist[code] = dist << 7;
  84501. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  84502. _dist_code[256 + dist++] = (uch)code;
  84503. }
  84504. }
  84505. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  84506. /* Construct the codes of the static literal tree */
  84507. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  84508. n = 0;
  84509. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  84510. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  84511. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  84512. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  84513. /* Codes 286 and 287 do not exist, but we must include them in the
  84514. * tree construction to get a canonical Huffman tree (longest code
  84515. * all ones)
  84516. */
  84517. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  84518. /* The static distance tree is trivial: */
  84519. for (n = 0; n < D_CODES; n++) {
  84520. static_dtree[n].Len = 5;
  84521. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  84522. }
  84523. static_init_done = 1;
  84524. # ifdef GEN_TREES_H
  84525. gen_trees_header();
  84526. # endif
  84527. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  84528. }
  84529. /* ===========================================================================
  84530. * Genererate the file trees.h describing the static trees.
  84531. */
  84532. #ifdef GEN_TREES_H
  84533. # ifndef DEBUG
  84534. # include <stdio.h>
  84535. # endif
  84536. # define SEPARATOR(i, last, width) \
  84537. ((i) == (last)? "\n};\n\n" : \
  84538. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  84539. void gen_trees_header()
  84540. {
  84541. FILE *header = fopen("trees.h", "w");
  84542. int i;
  84543. Assert (header != NULL, "Can't open trees.h");
  84544. fprintf(header,
  84545. "/* header created automatically with -DGEN_TREES_H */\n\n");
  84546. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  84547. for (i = 0; i < L_CODES+2; i++) {
  84548. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  84549. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  84550. }
  84551. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  84552. for (i = 0; i < D_CODES; i++) {
  84553. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  84554. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  84555. }
  84556. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  84557. for (i = 0; i < DIST_CODE_LEN; i++) {
  84558. fprintf(header, "%2u%s", _dist_code[i],
  84559. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  84560. }
  84561. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  84562. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  84563. fprintf(header, "%2u%s", _length_code[i],
  84564. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  84565. }
  84566. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  84567. for (i = 0; i < LENGTH_CODES; i++) {
  84568. fprintf(header, "%1u%s", base_length[i],
  84569. SEPARATOR(i, LENGTH_CODES-1, 20));
  84570. }
  84571. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  84572. for (i = 0; i < D_CODES; i++) {
  84573. fprintf(header, "%5u%s", base_dist[i],
  84574. SEPARATOR(i, D_CODES-1, 10));
  84575. }
  84576. fclose(header);
  84577. }
  84578. #endif /* GEN_TREES_H */
  84579. /* ===========================================================================
  84580. * Initialize the tree data structures for a new zlib stream.
  84581. */
  84582. void _tr_init(deflate_state *s)
  84583. {
  84584. tr_static_init();
  84585. s->l_desc.dyn_tree = s->dyn_ltree;
  84586. s->l_desc.stat_desc = &static_l_desc;
  84587. s->d_desc.dyn_tree = s->dyn_dtree;
  84588. s->d_desc.stat_desc = &static_d_desc;
  84589. s->bl_desc.dyn_tree = s->bl_tree;
  84590. s->bl_desc.stat_desc = &static_bl_desc;
  84591. s->bi_buf = 0;
  84592. s->bi_valid = 0;
  84593. s->last_eob_len = 8; /* enough lookahead for inflate */
  84594. #ifdef DEBUG
  84595. s->compressed_len = 0L;
  84596. s->bits_sent = 0L;
  84597. #endif
  84598. /* Initialize the first block of the first file: */
  84599. init_block(s);
  84600. }
  84601. /* ===========================================================================
  84602. * Initialize a new block.
  84603. */
  84604. local void init_block (deflate_state *s)
  84605. {
  84606. int n; /* iterates over tree elements */
  84607. /* Initialize the trees. */
  84608. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  84609. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  84610. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  84611. s->dyn_ltree[END_BLOCK].Freq = 1;
  84612. s->opt_len = s->static_len = 0L;
  84613. s->last_lit = s->matches = 0;
  84614. }
  84615. #define SMALLEST 1
  84616. /* Index within the heap array of least frequent node in the Huffman tree */
  84617. /* ===========================================================================
  84618. * Remove the smallest element from the heap and recreate the heap with
  84619. * one less element. Updates heap and heap_len.
  84620. */
  84621. #define pqremove(s, tree, top) \
  84622. {\
  84623. top = s->heap[SMALLEST]; \
  84624. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  84625. pqdownheap(s, tree, SMALLEST); \
  84626. }
  84627. /* ===========================================================================
  84628. * Compares to subtrees, using the tree depth as tie breaker when
  84629. * the subtrees have equal frequency. This minimizes the worst case length.
  84630. */
  84631. #define smaller(tree, n, m, depth) \
  84632. (tree[n].Freq < tree[m].Freq || \
  84633. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  84634. /* ===========================================================================
  84635. * Restore the heap property by moving down the tree starting at node k,
  84636. * exchanging a node with the smallest of its two sons if necessary, stopping
  84637. * when the heap property is re-established (each father smaller than its
  84638. * two sons).
  84639. */
  84640. local void pqdownheap (deflate_state *s,
  84641. ct_data *tree, /* the tree to restore */
  84642. int k) /* node to move down */
  84643. {
  84644. int v = s->heap[k];
  84645. int j = k << 1; /* left son of k */
  84646. while (j <= s->heap_len) {
  84647. /* Set j to the smallest of the two sons: */
  84648. if (j < s->heap_len &&
  84649. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  84650. j++;
  84651. }
  84652. /* Exit if v is smaller than both sons */
  84653. if (smaller(tree, v, s->heap[j], s->depth)) break;
  84654. /* Exchange v with the smallest son */
  84655. s->heap[k] = s->heap[j]; k = j;
  84656. /* And continue down the tree, setting j to the left son of k */
  84657. j <<= 1;
  84658. }
  84659. s->heap[k] = v;
  84660. }
  84661. /* ===========================================================================
  84662. * Compute the optimal bit lengths for a tree and update the total bit length
  84663. * for the current block.
  84664. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  84665. * above are the tree nodes sorted by increasing frequency.
  84666. * OUT assertions: the field len is set to the optimal bit length, the
  84667. * array bl_count contains the frequencies for each bit length.
  84668. * The length opt_len is updated; static_len is also updated if stree is
  84669. * not null.
  84670. */
  84671. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  84672. {
  84673. ct_data *tree = desc->dyn_tree;
  84674. int max_code = desc->max_code;
  84675. const ct_data *stree = desc->stat_desc->static_tree;
  84676. const intf *extra = desc->stat_desc->extra_bits;
  84677. int base = desc->stat_desc->extra_base;
  84678. int max_length = desc->stat_desc->max_length;
  84679. int h; /* heap index */
  84680. int n, m; /* iterate over the tree elements */
  84681. int bits; /* bit length */
  84682. int xbits; /* extra bits */
  84683. ush f; /* frequency */
  84684. int overflow = 0; /* number of elements with bit length too large */
  84685. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  84686. /* In a first pass, compute the optimal bit lengths (which may
  84687. * overflow in the case of the bit length tree).
  84688. */
  84689. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  84690. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  84691. n = s->heap[h];
  84692. bits = tree[tree[n].Dad].Len + 1;
  84693. if (bits > max_length) bits = max_length, overflow++;
  84694. tree[n].Len = (ush)bits;
  84695. /* We overwrite tree[n].Dad which is no longer needed */
  84696. if (n > max_code) continue; /* not a leaf node */
  84697. s->bl_count[bits]++;
  84698. xbits = 0;
  84699. if (n >= base) xbits = extra[n-base];
  84700. f = tree[n].Freq;
  84701. s->opt_len += (ulg)f * (bits + xbits);
  84702. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  84703. }
  84704. if (overflow == 0) return;
  84705. Trace((stderr,"\nbit length overflow\n"));
  84706. /* This happens for example on obj2 and pic of the Calgary corpus */
  84707. /* Find the first bit length which could increase: */
  84708. do {
  84709. bits = max_length-1;
  84710. while (s->bl_count[bits] == 0) bits--;
  84711. s->bl_count[bits]--; /* move one leaf down the tree */
  84712. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  84713. s->bl_count[max_length]--;
  84714. /* The brother of the overflow item also moves one step up,
  84715. * but this does not affect bl_count[max_length]
  84716. */
  84717. overflow -= 2;
  84718. } while (overflow > 0);
  84719. /* Now recompute all bit lengths, scanning in increasing frequency.
  84720. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  84721. * lengths instead of fixing only the wrong ones. This idea is taken
  84722. * from 'ar' written by Haruhiko Okumura.)
  84723. */
  84724. for (bits = max_length; bits != 0; bits--) {
  84725. n = s->bl_count[bits];
  84726. while (n != 0) {
  84727. m = s->heap[--h];
  84728. if (m > max_code) continue;
  84729. if ((unsigned) tree[m].Len != (unsigned) bits) {
  84730. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  84731. s->opt_len += ((long)bits - (long)tree[m].Len)
  84732. *(long)tree[m].Freq;
  84733. tree[m].Len = (ush)bits;
  84734. }
  84735. n--;
  84736. }
  84737. }
  84738. }
  84739. /* ===========================================================================
  84740. * Generate the codes for a given tree and bit counts (which need not be
  84741. * optimal).
  84742. * IN assertion: the array bl_count contains the bit length statistics for
  84743. * the given tree and the field len is set for all tree elements.
  84744. * OUT assertion: the field code is set for all tree elements of non
  84745. * zero code length.
  84746. */
  84747. local void gen_codes (ct_data *tree, /* the tree to decorate */
  84748. int max_code, /* largest code with non zero frequency */
  84749. ushf *bl_count) /* number of codes at each bit length */
  84750. {
  84751. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  84752. ush code = 0; /* running code value */
  84753. int bits; /* bit index */
  84754. int n; /* code index */
  84755. /* The distribution counts are first used to generate the code values
  84756. * without bit reversal.
  84757. */
  84758. for (bits = 1; bits <= MAX_BITS; bits++) {
  84759. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  84760. }
  84761. /* Check that the bit counts in bl_count are consistent. The last code
  84762. * must be all ones.
  84763. */
  84764. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  84765. "inconsistent bit counts");
  84766. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  84767. for (n = 0; n <= max_code; n++) {
  84768. int len = tree[n].Len;
  84769. if (len == 0) continue;
  84770. /* Now reverse the bits */
  84771. tree[n].Code = bi_reverse(next_code[len]++, len);
  84772. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  84773. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  84774. }
  84775. }
  84776. /* ===========================================================================
  84777. * Construct one Huffman tree and assigns the code bit strings and lengths.
  84778. * Update the total bit length for the current block.
  84779. * IN assertion: the field freq is set for all tree elements.
  84780. * OUT assertions: the fields len and code are set to the optimal bit length
  84781. * and corresponding code. The length opt_len is updated; static_len is
  84782. * also updated if stree is not null. The field max_code is set.
  84783. */
  84784. local void build_tree (deflate_state *s,
  84785. tree_desc *desc) /* the tree descriptor */
  84786. {
  84787. ct_data *tree = desc->dyn_tree;
  84788. const ct_data *stree = desc->stat_desc->static_tree;
  84789. int elems = desc->stat_desc->elems;
  84790. int n, m; /* iterate over heap elements */
  84791. int max_code = -1; /* largest code with non zero frequency */
  84792. int node; /* new node being created */
  84793. /* Construct the initial heap, with least frequent element in
  84794. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  84795. * heap[0] is not used.
  84796. */
  84797. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  84798. for (n = 0; n < elems; n++) {
  84799. if (tree[n].Freq != 0) {
  84800. s->heap[++(s->heap_len)] = max_code = n;
  84801. s->depth[n] = 0;
  84802. } else {
  84803. tree[n].Len = 0;
  84804. }
  84805. }
  84806. /* The pkzip format requires that at least one distance code exists,
  84807. * and that at least one bit should be sent even if there is only one
  84808. * possible code. So to avoid special checks later on we force at least
  84809. * two codes of non zero frequency.
  84810. */
  84811. while (s->heap_len < 2) {
  84812. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  84813. tree[node].Freq = 1;
  84814. s->depth[node] = 0;
  84815. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  84816. /* node is 0 or 1 so it does not have extra bits */
  84817. }
  84818. desc->max_code = max_code;
  84819. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  84820. * establish sub-heaps of increasing lengths:
  84821. */
  84822. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  84823. /* Construct the Huffman tree by repeatedly combining the least two
  84824. * frequent nodes.
  84825. */
  84826. node = elems; /* next internal node of the tree */
  84827. do {
  84828. pqremove(s, tree, n); /* n = node of least frequency */
  84829. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  84830. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  84831. s->heap[--(s->heap_max)] = m;
  84832. /* Create a new node father of n and m */
  84833. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  84834. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  84835. s->depth[n] : s->depth[m]) + 1);
  84836. tree[n].Dad = tree[m].Dad = (ush)node;
  84837. #ifdef DUMP_BL_TREE
  84838. if (tree == s->bl_tree) {
  84839. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  84840. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  84841. }
  84842. #endif
  84843. /* and insert the new node in the heap */
  84844. s->heap[SMALLEST] = node++;
  84845. pqdownheap(s, tree, SMALLEST);
  84846. } while (s->heap_len >= 2);
  84847. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  84848. /* At this point, the fields freq and dad are set. We can now
  84849. * generate the bit lengths.
  84850. */
  84851. gen_bitlen(s, (tree_desc *)desc);
  84852. /* The field len is now set, we can generate the bit codes */
  84853. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  84854. }
  84855. /* ===========================================================================
  84856. * Scan a literal or distance tree to determine the frequencies of the codes
  84857. * in the bit length tree.
  84858. */
  84859. local void scan_tree (deflate_state *s,
  84860. ct_data *tree, /* the tree to be scanned */
  84861. int max_code) /* and its largest code of non zero frequency */
  84862. {
  84863. int n; /* iterates over all tree elements */
  84864. int prevlen = -1; /* last emitted length */
  84865. int curlen; /* length of current code */
  84866. int nextlen = tree[0].Len; /* length of next code */
  84867. int count = 0; /* repeat count of the current code */
  84868. int max_count = 7; /* max repeat count */
  84869. int min_count = 4; /* min repeat count */
  84870. if (nextlen == 0) max_count = 138, min_count = 3;
  84871. tree[max_code+1].Len = (ush)0xffff; /* guard */
  84872. for (n = 0; n <= max_code; n++) {
  84873. curlen = nextlen; nextlen = tree[n+1].Len;
  84874. if (++count < max_count && curlen == nextlen) {
  84875. continue;
  84876. } else if (count < min_count) {
  84877. s->bl_tree[curlen].Freq += count;
  84878. } else if (curlen != 0) {
  84879. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  84880. s->bl_tree[REP_3_6].Freq++;
  84881. } else if (count <= 10) {
  84882. s->bl_tree[REPZ_3_10].Freq++;
  84883. } else {
  84884. s->bl_tree[REPZ_11_138].Freq++;
  84885. }
  84886. count = 0; prevlen = curlen;
  84887. if (nextlen == 0) {
  84888. max_count = 138, min_count = 3;
  84889. } else if (curlen == nextlen) {
  84890. max_count = 6, min_count = 3;
  84891. } else {
  84892. max_count = 7, min_count = 4;
  84893. }
  84894. }
  84895. }
  84896. /* ===========================================================================
  84897. * Send a literal or distance tree in compressed form, using the codes in
  84898. * bl_tree.
  84899. */
  84900. local void send_tree (deflate_state *s,
  84901. ct_data *tree, /* the tree to be scanned */
  84902. int max_code) /* and its largest code of non zero frequency */
  84903. {
  84904. int n; /* iterates over all tree elements */
  84905. int prevlen = -1; /* last emitted length */
  84906. int curlen; /* length of current code */
  84907. int nextlen = tree[0].Len; /* length of next code */
  84908. int count = 0; /* repeat count of the current code */
  84909. int max_count = 7; /* max repeat count */
  84910. int min_count = 4; /* min repeat count */
  84911. /* tree[max_code+1].Len = -1; */ /* guard already set */
  84912. if (nextlen == 0) max_count = 138, min_count = 3;
  84913. for (n = 0; n <= max_code; n++) {
  84914. curlen = nextlen; nextlen = tree[n+1].Len;
  84915. if (++count < max_count && curlen == nextlen) {
  84916. continue;
  84917. } else if (count < min_count) {
  84918. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  84919. } else if (curlen != 0) {
  84920. if (curlen != prevlen) {
  84921. send_code(s, curlen, s->bl_tree); count--;
  84922. }
  84923. Assert(count >= 3 && count <= 6, " 3_6?");
  84924. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  84925. } else if (count <= 10) {
  84926. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  84927. } else {
  84928. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  84929. }
  84930. count = 0; prevlen = curlen;
  84931. if (nextlen == 0) {
  84932. max_count = 138, min_count = 3;
  84933. } else if (curlen == nextlen) {
  84934. max_count = 6, min_count = 3;
  84935. } else {
  84936. max_count = 7, min_count = 4;
  84937. }
  84938. }
  84939. }
  84940. /* ===========================================================================
  84941. * Construct the Huffman tree for the bit lengths and return the index in
  84942. * bl_order of the last bit length code to send.
  84943. */
  84944. local int build_bl_tree (deflate_state *s)
  84945. {
  84946. int max_blindex; /* index of last bit length code of non zero freq */
  84947. /* Determine the bit length frequencies for literal and distance trees */
  84948. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  84949. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  84950. /* Build the bit length tree: */
  84951. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  84952. /* opt_len now includes the length of the tree representations, except
  84953. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  84954. */
  84955. /* Determine the number of bit length codes to send. The pkzip format
  84956. * requires that at least 4 bit length codes be sent. (appnote.txt says
  84957. * 3 but the actual value used is 4.)
  84958. */
  84959. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  84960. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  84961. }
  84962. /* Update opt_len to include the bit length tree and counts */
  84963. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  84964. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  84965. s->opt_len, s->static_len));
  84966. return max_blindex;
  84967. }
  84968. /* ===========================================================================
  84969. * Send the header for a block using dynamic Huffman trees: the counts, the
  84970. * lengths of the bit length codes, the literal tree and the distance tree.
  84971. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  84972. */
  84973. local void send_all_trees (deflate_state *s,
  84974. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  84975. {
  84976. int rank; /* index in bl_order */
  84977. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  84978. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  84979. "too many codes");
  84980. Tracev((stderr, "\nbl counts: "));
  84981. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  84982. send_bits(s, dcodes-1, 5);
  84983. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  84984. for (rank = 0; rank < blcodes; rank++) {
  84985. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  84986. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  84987. }
  84988. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  84989. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  84990. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  84991. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  84992. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  84993. }
  84994. /* ===========================================================================
  84995. * Send a stored block
  84996. */
  84997. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  84998. {
  84999. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85000. #ifdef DEBUG
  85001. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85002. s->compressed_len += (stored_len + 4) << 3;
  85003. #endif
  85004. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85005. }
  85006. /* ===========================================================================
  85007. * Send one empty static block to give enough lookahead for inflate.
  85008. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85009. * The current inflate code requires 9 bits of lookahead. If the
  85010. * last two codes for the previous block (real code plus EOB) were coded
  85011. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85012. * the last real code. In this case we send two empty static blocks instead
  85013. * of one. (There are no problems if the previous block is stored or fixed.)
  85014. * To simplify the code, we assume the worst case of last real code encoded
  85015. * on one bit only.
  85016. */
  85017. void _tr_align (deflate_state *s)
  85018. {
  85019. send_bits(s, STATIC_TREES<<1, 3);
  85020. send_code(s, END_BLOCK, static_ltree);
  85021. #ifdef DEBUG
  85022. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85023. #endif
  85024. bi_flush(s);
  85025. /* Of the 10 bits for the empty block, we have already sent
  85026. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85027. * the EOB of the previous block) was thus at least one plus the length
  85028. * of the EOB plus what we have just sent of the empty static block.
  85029. */
  85030. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85031. send_bits(s, STATIC_TREES<<1, 3);
  85032. send_code(s, END_BLOCK, static_ltree);
  85033. #ifdef DEBUG
  85034. s->compressed_len += 10L;
  85035. #endif
  85036. bi_flush(s);
  85037. }
  85038. s->last_eob_len = 7;
  85039. }
  85040. /* ===========================================================================
  85041. * Determine the best encoding for the current block: dynamic trees, static
  85042. * trees or store, and output the encoded block to the zip file.
  85043. */
  85044. void _tr_flush_block (deflate_state *s,
  85045. charf *buf, /* input block, or NULL if too old */
  85046. ulg stored_len, /* length of input block */
  85047. int eof) /* true if this is the last block for a file */
  85048. {
  85049. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85050. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85051. /* Build the Huffman trees unless a stored block is forced */
  85052. if (s->level > 0) {
  85053. /* Check if the file is binary or text */
  85054. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85055. set_data_type(s);
  85056. /* Construct the literal and distance trees */
  85057. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85058. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85059. s->static_len));
  85060. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85061. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85062. s->static_len));
  85063. /* At this point, opt_len and static_len are the total bit lengths of
  85064. * the compressed block data, excluding the tree representations.
  85065. */
  85066. /* Build the bit length tree for the above two trees, and get the index
  85067. * in bl_order of the last bit length code to send.
  85068. */
  85069. max_blindex = build_bl_tree(s);
  85070. /* Determine the best encoding. Compute the block lengths in bytes. */
  85071. opt_lenb = (s->opt_len+3+7)>>3;
  85072. static_lenb = (s->static_len+3+7)>>3;
  85073. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85074. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85075. s->last_lit));
  85076. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85077. } else {
  85078. Assert(buf != (char*)0, "lost buf");
  85079. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85080. }
  85081. #ifdef FORCE_STORED
  85082. if (buf != (char*)0) { /* force stored block */
  85083. #else
  85084. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85085. /* 4: two words for the lengths */
  85086. #endif
  85087. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85088. * Otherwise we can't have processed more than WSIZE input bytes since
  85089. * the last block flush, because compression would have been
  85090. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85091. * transform a block into a stored block.
  85092. */
  85093. _tr_stored_block(s, buf, stored_len, eof);
  85094. #ifdef FORCE_STATIC
  85095. } else if (static_lenb >= 0) { /* force static trees */
  85096. #else
  85097. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85098. #endif
  85099. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85100. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85101. #ifdef DEBUG
  85102. s->compressed_len += 3 + s->static_len;
  85103. #endif
  85104. } else {
  85105. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85106. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85107. max_blindex+1);
  85108. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85109. #ifdef DEBUG
  85110. s->compressed_len += 3 + s->opt_len;
  85111. #endif
  85112. }
  85113. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85114. /* The above check is made mod 2^32, for files larger than 512 MB
  85115. * and uLong implemented on 32 bits.
  85116. */
  85117. init_block(s);
  85118. if (eof) {
  85119. bi_windup(s);
  85120. #ifdef DEBUG
  85121. s->compressed_len += 7; /* align on byte boundary */
  85122. #endif
  85123. }
  85124. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85125. s->compressed_len-7*eof));
  85126. }
  85127. /* ===========================================================================
  85128. * Save the match info and tally the frequency counts. Return true if
  85129. * the current block must be flushed.
  85130. */
  85131. int _tr_tally (deflate_state *s,
  85132. unsigned dist, /* distance of matched string */
  85133. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85134. {
  85135. s->d_buf[s->last_lit] = (ush)dist;
  85136. s->l_buf[s->last_lit++] = (uch)lc;
  85137. if (dist == 0) {
  85138. /* lc is the unmatched char */
  85139. s->dyn_ltree[lc].Freq++;
  85140. } else {
  85141. s->matches++;
  85142. /* Here, lc is the match length - MIN_MATCH */
  85143. dist--; /* dist = match distance - 1 */
  85144. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85145. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85146. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85147. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85148. s->dyn_dtree[d_code(dist)].Freq++;
  85149. }
  85150. #ifdef TRUNCATE_BLOCK
  85151. /* Try to guess if it is profitable to stop the current block here */
  85152. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85153. /* Compute an upper bound for the compressed length */
  85154. ulg out_length = (ulg)s->last_lit*8L;
  85155. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85156. int dcode;
  85157. for (dcode = 0; dcode < D_CODES; dcode++) {
  85158. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85159. (5L+extra_dbits[dcode]);
  85160. }
  85161. out_length >>= 3;
  85162. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85163. s->last_lit, in_length, out_length,
  85164. 100L - out_length*100L/in_length));
  85165. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85166. }
  85167. #endif
  85168. return (s->last_lit == s->lit_bufsize-1);
  85169. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85170. * on 16 bit machines and because stored blocks are restricted to
  85171. * 64K-1 bytes.
  85172. */
  85173. }
  85174. /* ===========================================================================
  85175. * Send the block data compressed using the given Huffman trees
  85176. */
  85177. local void compress_block (deflate_state *s,
  85178. ct_data *ltree, /* literal tree */
  85179. ct_data *dtree) /* distance tree */
  85180. {
  85181. unsigned dist; /* distance of matched string */
  85182. int lc; /* match length or unmatched char (if dist == 0) */
  85183. unsigned lx = 0; /* running index in l_buf */
  85184. unsigned code; /* the code to send */
  85185. int extra; /* number of extra bits to send */
  85186. if (s->last_lit != 0) do {
  85187. dist = s->d_buf[lx];
  85188. lc = s->l_buf[lx++];
  85189. if (dist == 0) {
  85190. send_code(s, lc, ltree); /* send a literal byte */
  85191. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85192. } else {
  85193. /* Here, lc is the match length - MIN_MATCH */
  85194. code = _length_code[lc];
  85195. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85196. extra = extra_lbits[code];
  85197. if (extra != 0) {
  85198. lc -= base_length[code];
  85199. send_bits(s, lc, extra); /* send the extra length bits */
  85200. }
  85201. dist--; /* dist is now the match distance - 1 */
  85202. code = d_code(dist);
  85203. Assert (code < D_CODES, "bad d_code");
  85204. send_code(s, code, dtree); /* send the distance code */
  85205. extra = extra_dbits[code];
  85206. if (extra != 0) {
  85207. dist -= base_dist[code];
  85208. send_bits(s, dist, extra); /* send the extra distance bits */
  85209. }
  85210. } /* literal or match pair ? */
  85211. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85212. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85213. "pendingBuf overflow");
  85214. } while (lx < s->last_lit);
  85215. send_code(s, END_BLOCK, ltree);
  85216. s->last_eob_len = ltree[END_BLOCK].Len;
  85217. }
  85218. /* ===========================================================================
  85219. * Set the data type to BINARY or TEXT, using a crude approximation:
  85220. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85221. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85222. * IN assertion: the fields Freq of dyn_ltree are set.
  85223. */
  85224. local void set_data_type (deflate_state *s)
  85225. {
  85226. int n;
  85227. for (n = 0; n < 9; n++)
  85228. if (s->dyn_ltree[n].Freq != 0)
  85229. break;
  85230. if (n == 9)
  85231. for (n = 14; n < 32; n++)
  85232. if (s->dyn_ltree[n].Freq != 0)
  85233. break;
  85234. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85235. }
  85236. /* ===========================================================================
  85237. * Reverse the first len bits of a code, using straightforward code (a faster
  85238. * method would use a table)
  85239. * IN assertion: 1 <= len <= 15
  85240. */
  85241. local unsigned bi_reverse (unsigned code, int len)
  85242. {
  85243. register unsigned res = 0;
  85244. do {
  85245. res |= code & 1;
  85246. code >>= 1, res <<= 1;
  85247. } while (--len > 0);
  85248. return res >> 1;
  85249. }
  85250. /* ===========================================================================
  85251. * Flush the bit buffer, keeping at most 7 bits in it.
  85252. */
  85253. local void bi_flush (deflate_state *s)
  85254. {
  85255. if (s->bi_valid == 16) {
  85256. put_short(s, s->bi_buf);
  85257. s->bi_buf = 0;
  85258. s->bi_valid = 0;
  85259. } else if (s->bi_valid >= 8) {
  85260. put_byte(s, (Byte)s->bi_buf);
  85261. s->bi_buf >>= 8;
  85262. s->bi_valid -= 8;
  85263. }
  85264. }
  85265. /* ===========================================================================
  85266. * Flush the bit buffer and align the output on a byte boundary
  85267. */
  85268. local void bi_windup (deflate_state *s)
  85269. {
  85270. if (s->bi_valid > 8) {
  85271. put_short(s, s->bi_buf);
  85272. } else if (s->bi_valid > 0) {
  85273. put_byte(s, (Byte)s->bi_buf);
  85274. }
  85275. s->bi_buf = 0;
  85276. s->bi_valid = 0;
  85277. #ifdef DEBUG
  85278. s->bits_sent = (s->bits_sent+7) & ~7;
  85279. #endif
  85280. }
  85281. /* ===========================================================================
  85282. * Copy a stored block, storing first the length and its
  85283. * one's complement if requested.
  85284. */
  85285. local void copy_block(deflate_state *s,
  85286. charf *buf, /* the input data */
  85287. unsigned len, /* its length */
  85288. int header) /* true if block header must be written */
  85289. {
  85290. bi_windup(s); /* align on byte boundary */
  85291. s->last_eob_len = 8; /* enough lookahead for inflate */
  85292. if (header) {
  85293. put_short(s, (ush)len);
  85294. put_short(s, (ush)~len);
  85295. #ifdef DEBUG
  85296. s->bits_sent += 2*16;
  85297. #endif
  85298. }
  85299. #ifdef DEBUG
  85300. s->bits_sent += (ulg)len<<3;
  85301. #endif
  85302. while (len--) {
  85303. put_byte(s, *buf++);
  85304. }
  85305. }
  85306. /*** End of inlined file: trees.c ***/
  85307. /*** Start of inlined file: zutil.c ***/
  85308. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85309. #ifndef NO_DUMMY_DECL
  85310. struct internal_state {int dummy;}; /* for buggy compilers */
  85311. #endif
  85312. const char * const z_errmsg[10] = {
  85313. "need dictionary", /* Z_NEED_DICT 2 */
  85314. "stream end", /* Z_STREAM_END 1 */
  85315. "", /* Z_OK 0 */
  85316. "file error", /* Z_ERRNO (-1) */
  85317. "stream error", /* Z_STREAM_ERROR (-2) */
  85318. "data error", /* Z_DATA_ERROR (-3) */
  85319. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85320. "buffer error", /* Z_BUF_ERROR (-5) */
  85321. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85322. ""};
  85323. /*const char * ZEXPORT zlibVersion()
  85324. {
  85325. return ZLIB_VERSION;
  85326. }
  85327. uLong ZEXPORT zlibCompileFlags()
  85328. {
  85329. uLong flags;
  85330. flags = 0;
  85331. switch (sizeof(uInt)) {
  85332. case 2: break;
  85333. case 4: flags += 1; break;
  85334. case 8: flags += 2; break;
  85335. default: flags += 3;
  85336. }
  85337. switch (sizeof(uLong)) {
  85338. case 2: break;
  85339. case 4: flags += 1 << 2; break;
  85340. case 8: flags += 2 << 2; break;
  85341. default: flags += 3 << 2;
  85342. }
  85343. switch (sizeof(voidpf)) {
  85344. case 2: break;
  85345. case 4: flags += 1 << 4; break;
  85346. case 8: flags += 2 << 4; break;
  85347. default: flags += 3 << 4;
  85348. }
  85349. switch (sizeof(z_off_t)) {
  85350. case 2: break;
  85351. case 4: flags += 1 << 6; break;
  85352. case 8: flags += 2 << 6; break;
  85353. default: flags += 3 << 6;
  85354. }
  85355. #ifdef DEBUG
  85356. flags += 1 << 8;
  85357. #endif
  85358. #if defined(ASMV) || defined(ASMINF)
  85359. flags += 1 << 9;
  85360. #endif
  85361. #ifdef ZLIB_WINAPI
  85362. flags += 1 << 10;
  85363. #endif
  85364. #ifdef BUILDFIXED
  85365. flags += 1 << 12;
  85366. #endif
  85367. #ifdef DYNAMIC_CRC_TABLE
  85368. flags += 1 << 13;
  85369. #endif
  85370. #ifdef NO_GZCOMPRESS
  85371. flags += 1L << 16;
  85372. #endif
  85373. #ifdef NO_GZIP
  85374. flags += 1L << 17;
  85375. #endif
  85376. #ifdef PKZIP_BUG_WORKAROUND
  85377. flags += 1L << 20;
  85378. #endif
  85379. #ifdef FASTEST
  85380. flags += 1L << 21;
  85381. #endif
  85382. #ifdef STDC
  85383. # ifdef NO_vsnprintf
  85384. flags += 1L << 25;
  85385. # ifdef HAS_vsprintf_void
  85386. flags += 1L << 26;
  85387. # endif
  85388. # else
  85389. # ifdef HAS_vsnprintf_void
  85390. flags += 1L << 26;
  85391. # endif
  85392. # endif
  85393. #else
  85394. flags += 1L << 24;
  85395. # ifdef NO_snprintf
  85396. flags += 1L << 25;
  85397. # ifdef HAS_sprintf_void
  85398. flags += 1L << 26;
  85399. # endif
  85400. # else
  85401. # ifdef HAS_snprintf_void
  85402. flags += 1L << 26;
  85403. # endif
  85404. # endif
  85405. #endif
  85406. return flags;
  85407. }*/
  85408. #ifdef DEBUG
  85409. # ifndef verbose
  85410. # define verbose 0
  85411. # endif
  85412. int z_verbose = verbose;
  85413. void z_error (const char *m)
  85414. {
  85415. fprintf(stderr, "%s\n", m);
  85416. exit(1);
  85417. }
  85418. #endif
  85419. /* exported to allow conversion of error code to string for compress() and
  85420. * uncompress()
  85421. */
  85422. const char * ZEXPORT zError(int err)
  85423. {
  85424. return ERR_MSG(err);
  85425. }
  85426. #if defined(_WIN32_WCE)
  85427. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  85428. * errno. We define it as a global variable to simplify porting.
  85429. * Its value is always 0 and should not be used.
  85430. */
  85431. int errno = 0;
  85432. #endif
  85433. #ifndef HAVE_MEMCPY
  85434. void zmemcpy(dest, source, len)
  85435. Bytef* dest;
  85436. const Bytef* source;
  85437. uInt len;
  85438. {
  85439. if (len == 0) return;
  85440. do {
  85441. *dest++ = *source++; /* ??? to be unrolled */
  85442. } while (--len != 0);
  85443. }
  85444. int zmemcmp(s1, s2, len)
  85445. const Bytef* s1;
  85446. const Bytef* s2;
  85447. uInt len;
  85448. {
  85449. uInt j;
  85450. for (j = 0; j < len; j++) {
  85451. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  85452. }
  85453. return 0;
  85454. }
  85455. void zmemzero(dest, len)
  85456. Bytef* dest;
  85457. uInt len;
  85458. {
  85459. if (len == 0) return;
  85460. do {
  85461. *dest++ = 0; /* ??? to be unrolled */
  85462. } while (--len != 0);
  85463. }
  85464. #endif
  85465. #ifdef SYS16BIT
  85466. #ifdef __TURBOC__
  85467. /* Turbo C in 16-bit mode */
  85468. # define MY_ZCALLOC
  85469. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  85470. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  85471. * must fix the pointer. Warning: the pointer must be put back to its
  85472. * original form in order to free it, use zcfree().
  85473. */
  85474. #define MAX_PTR 10
  85475. /* 10*64K = 640K */
  85476. local int next_ptr = 0;
  85477. typedef struct ptr_table_s {
  85478. voidpf org_ptr;
  85479. voidpf new_ptr;
  85480. } ptr_table;
  85481. local ptr_table table[MAX_PTR];
  85482. /* This table is used to remember the original form of pointers
  85483. * to large buffers (64K). Such pointers are normalized with a zero offset.
  85484. * Since MSDOS is not a preemptive multitasking OS, this table is not
  85485. * protected from concurrent access. This hack doesn't work anyway on
  85486. * a protected system like OS/2. Use Microsoft C instead.
  85487. */
  85488. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85489. {
  85490. voidpf buf = opaque; /* just to make some compilers happy */
  85491. ulg bsize = (ulg)items*size;
  85492. /* If we allocate less than 65520 bytes, we assume that farmalloc
  85493. * will return a usable pointer which doesn't have to be normalized.
  85494. */
  85495. if (bsize < 65520L) {
  85496. buf = farmalloc(bsize);
  85497. if (*(ush*)&buf != 0) return buf;
  85498. } else {
  85499. buf = farmalloc(bsize + 16L);
  85500. }
  85501. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  85502. table[next_ptr].org_ptr = buf;
  85503. /* Normalize the pointer to seg:0 */
  85504. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  85505. *(ush*)&buf = 0;
  85506. table[next_ptr++].new_ptr = buf;
  85507. return buf;
  85508. }
  85509. void zcfree (voidpf opaque, voidpf ptr)
  85510. {
  85511. int n;
  85512. if (*(ush*)&ptr != 0) { /* object < 64K */
  85513. farfree(ptr);
  85514. return;
  85515. }
  85516. /* Find the original pointer */
  85517. for (n = 0; n < next_ptr; n++) {
  85518. if (ptr != table[n].new_ptr) continue;
  85519. farfree(table[n].org_ptr);
  85520. while (++n < next_ptr) {
  85521. table[n-1] = table[n];
  85522. }
  85523. next_ptr--;
  85524. return;
  85525. }
  85526. ptr = opaque; /* just to make some compilers happy */
  85527. Assert(0, "zcfree: ptr not found");
  85528. }
  85529. #endif /* __TURBOC__ */
  85530. #ifdef M_I86
  85531. /* Microsoft C in 16-bit mode */
  85532. # define MY_ZCALLOC
  85533. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  85534. # define _halloc halloc
  85535. # define _hfree hfree
  85536. #endif
  85537. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85538. {
  85539. if (opaque) opaque = 0; /* to make compiler happy */
  85540. return _halloc((long)items, size);
  85541. }
  85542. void zcfree (voidpf opaque, voidpf ptr)
  85543. {
  85544. if (opaque) opaque = 0; /* to make compiler happy */
  85545. _hfree(ptr);
  85546. }
  85547. #endif /* M_I86 */
  85548. #endif /* SYS16BIT */
  85549. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  85550. #ifndef STDC
  85551. extern voidp malloc OF((uInt size));
  85552. extern voidp calloc OF((uInt items, uInt size));
  85553. extern void free OF((voidpf ptr));
  85554. #endif
  85555. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85556. {
  85557. if (opaque) items += size - size; /* make compiler happy */
  85558. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  85559. (voidpf)calloc(items, size);
  85560. }
  85561. void zcfree (voidpf opaque, voidpf ptr)
  85562. {
  85563. free(ptr);
  85564. if (opaque) return; /* make compiler happy */
  85565. }
  85566. #endif /* MY_ZCALLOC */
  85567. /*** End of inlined file: zutil.c ***/
  85568. #undef Byte
  85569. }
  85570. #else
  85571. #include <zlib.h>
  85572. #endif
  85573. }
  85574. #if JUCE_MSVC
  85575. #pragma warning (pop)
  85576. #endif
  85577. BEGIN_JUCE_NAMESPACE
  85578. // internal helper object that holds the zlib structures so they don't have to be
  85579. // included publicly.
  85580. class GZIPDecompressHelper
  85581. {
  85582. public:
  85583. GZIPDecompressHelper (const bool noWrap)
  85584. : finished (true),
  85585. needsDictionary (false),
  85586. error (true),
  85587. streamIsValid (false),
  85588. data (0),
  85589. dataSize (0)
  85590. {
  85591. using namespace zlibNamespace;
  85592. zerostruct (stream);
  85593. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  85594. finished = error = ! streamIsValid;
  85595. }
  85596. ~GZIPDecompressHelper()
  85597. {
  85598. using namespace zlibNamespace;
  85599. if (streamIsValid)
  85600. inflateEnd (&stream);
  85601. }
  85602. bool needsInput() const throw() { return dataSize <= 0; }
  85603. void setInput (uint8* const data_, const int size) throw()
  85604. {
  85605. data = data_;
  85606. dataSize = size;
  85607. }
  85608. int doNextBlock (uint8* const dest, const int destSize)
  85609. {
  85610. using namespace zlibNamespace;
  85611. if (streamIsValid && data != 0 && ! finished)
  85612. {
  85613. stream.next_in = data;
  85614. stream.next_out = dest;
  85615. stream.avail_in = dataSize;
  85616. stream.avail_out = destSize;
  85617. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  85618. {
  85619. case Z_STREAM_END:
  85620. finished = true;
  85621. // deliberate fall-through
  85622. case Z_OK:
  85623. data += dataSize - stream.avail_in;
  85624. dataSize = stream.avail_in;
  85625. return destSize - stream.avail_out;
  85626. case Z_NEED_DICT:
  85627. needsDictionary = true;
  85628. data += dataSize - stream.avail_in;
  85629. dataSize = stream.avail_in;
  85630. break;
  85631. case Z_DATA_ERROR:
  85632. case Z_MEM_ERROR:
  85633. error = true;
  85634. default:
  85635. break;
  85636. }
  85637. }
  85638. return 0;
  85639. }
  85640. bool finished, needsDictionary, error, streamIsValid;
  85641. private:
  85642. zlibNamespace::z_stream stream;
  85643. uint8* data;
  85644. int dataSize;
  85645. GZIPDecompressHelper (const GZIPDecompressHelper&);
  85646. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  85647. };
  85648. const int gzipDecompBufferSize = 32768;
  85649. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  85650. const bool deleteSourceWhenDestroyed,
  85651. const bool noWrap_,
  85652. const int64 uncompressedStreamLength_)
  85653. : sourceStream (sourceStream_),
  85654. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  85655. uncompressedStreamLength (uncompressedStreamLength_),
  85656. noWrap (noWrap_),
  85657. isEof (false),
  85658. activeBufferSize (0),
  85659. originalSourcePos (sourceStream_->getPosition()),
  85660. currentPos (0),
  85661. buffer (gzipDecompBufferSize),
  85662. helper (new GZIPDecompressHelper (noWrap_))
  85663. {
  85664. }
  85665. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  85666. {
  85667. }
  85668. int64 GZIPDecompressorInputStream::getTotalLength()
  85669. {
  85670. return uncompressedStreamLength;
  85671. }
  85672. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  85673. {
  85674. if ((howMany > 0) && ! isEof)
  85675. {
  85676. jassert (destBuffer != 0);
  85677. if (destBuffer != 0)
  85678. {
  85679. int numRead = 0;
  85680. uint8* d = static_cast <uint8*> (destBuffer);
  85681. while (! helper->error)
  85682. {
  85683. const int n = helper->doNextBlock (d, howMany);
  85684. currentPos += n;
  85685. if (n == 0)
  85686. {
  85687. if (helper->finished || helper->needsDictionary)
  85688. {
  85689. isEof = true;
  85690. return numRead;
  85691. }
  85692. if (helper->needsInput())
  85693. {
  85694. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  85695. if (activeBufferSize > 0)
  85696. {
  85697. helper->setInput (buffer, activeBufferSize);
  85698. }
  85699. else
  85700. {
  85701. isEof = true;
  85702. return numRead;
  85703. }
  85704. }
  85705. }
  85706. else
  85707. {
  85708. numRead += n;
  85709. howMany -= n;
  85710. d += n;
  85711. if (howMany <= 0)
  85712. return numRead;
  85713. }
  85714. }
  85715. }
  85716. }
  85717. return 0;
  85718. }
  85719. bool GZIPDecompressorInputStream::isExhausted()
  85720. {
  85721. return helper->error || isEof;
  85722. }
  85723. int64 GZIPDecompressorInputStream::getPosition()
  85724. {
  85725. return currentPos;
  85726. }
  85727. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  85728. {
  85729. if (newPos < currentPos)
  85730. {
  85731. // to go backwards, reset the stream and start again..
  85732. isEof = false;
  85733. activeBufferSize = 0;
  85734. currentPos = 0;
  85735. helper = new GZIPDecompressHelper (noWrap);
  85736. sourceStream->setPosition (originalSourcePos);
  85737. }
  85738. skipNextBytes (newPos - currentPos);
  85739. return true;
  85740. }
  85741. END_JUCE_NAMESPACE
  85742. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  85743. #endif
  85744. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  85745. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  85746. #if JUCE_USE_FLAC
  85747. #if JUCE_WINDOWS
  85748. #include <windows.h>
  85749. #endif
  85750. namespace FlacNamespace
  85751. {
  85752. #if JUCE_INCLUDE_FLAC_CODE
  85753. #if JUCE_MSVC
  85754. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  85755. #endif
  85756. #define FLAC__NO_DLL 1
  85757. #if ! defined (SIZE_MAX)
  85758. #define SIZE_MAX 0xffffffff
  85759. #endif
  85760. #define __STDC_LIMIT_MACROS 1
  85761. /*** Start of inlined file: all.h ***/
  85762. #ifndef FLAC__ALL_H
  85763. #define FLAC__ALL_H
  85764. /*** Start of inlined file: export.h ***/
  85765. #ifndef FLAC__EXPORT_H
  85766. #define FLAC__EXPORT_H
  85767. /** \file include/FLAC/export.h
  85768. *
  85769. * \brief
  85770. * This module contains #defines and symbols for exporting function
  85771. * calls, and providing version information and compiled-in features.
  85772. *
  85773. * See the \link flac_export export \endlink module.
  85774. */
  85775. /** \defgroup flac_export FLAC/export.h: export symbols
  85776. * \ingroup flac
  85777. *
  85778. * \brief
  85779. * This module contains #defines and symbols for exporting function
  85780. * calls, and providing version information and compiled-in features.
  85781. *
  85782. * If you are compiling with MSVC and will link to the static library
  85783. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  85784. * make sure the symbols are exported properly.
  85785. *
  85786. * \{
  85787. */
  85788. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  85789. #define FLAC_API
  85790. #else
  85791. #ifdef FLAC_API_EXPORTS
  85792. #define FLAC_API _declspec(dllexport)
  85793. #else
  85794. #define FLAC_API _declspec(dllimport)
  85795. #endif
  85796. #endif
  85797. /** These #defines will mirror the libtool-based library version number, see
  85798. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  85799. */
  85800. #define FLAC_API_VERSION_CURRENT 10
  85801. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  85802. #define FLAC_API_VERSION_AGE 2 /**< see above */
  85803. #ifdef __cplusplus
  85804. extern "C" {
  85805. #endif
  85806. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  85807. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  85808. #ifdef __cplusplus
  85809. }
  85810. #endif
  85811. /* \} */
  85812. #endif
  85813. /*** End of inlined file: export.h ***/
  85814. /*** Start of inlined file: assert.h ***/
  85815. #ifndef FLAC__ASSERT_H
  85816. #define FLAC__ASSERT_H
  85817. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  85818. #ifdef DEBUG
  85819. #include <assert.h>
  85820. #define FLAC__ASSERT(x) assert(x)
  85821. #define FLAC__ASSERT_DECLARATION(x) x
  85822. #else
  85823. #define FLAC__ASSERT(x)
  85824. #define FLAC__ASSERT_DECLARATION(x)
  85825. #endif
  85826. #endif
  85827. /*** End of inlined file: assert.h ***/
  85828. /*** Start of inlined file: callback.h ***/
  85829. #ifndef FLAC__CALLBACK_H
  85830. #define FLAC__CALLBACK_H
  85831. /*** Start of inlined file: ordinals.h ***/
  85832. #ifndef FLAC__ORDINALS_H
  85833. #define FLAC__ORDINALS_H
  85834. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  85835. #include <inttypes.h>
  85836. #endif
  85837. typedef signed char FLAC__int8;
  85838. typedef unsigned char FLAC__uint8;
  85839. #if defined(_MSC_VER) || defined(__BORLANDC__)
  85840. typedef __int16 FLAC__int16;
  85841. typedef __int32 FLAC__int32;
  85842. typedef __int64 FLAC__int64;
  85843. typedef unsigned __int16 FLAC__uint16;
  85844. typedef unsigned __int32 FLAC__uint32;
  85845. typedef unsigned __int64 FLAC__uint64;
  85846. #elif defined(__EMX__)
  85847. typedef short FLAC__int16;
  85848. typedef long FLAC__int32;
  85849. typedef long long FLAC__int64;
  85850. typedef unsigned short FLAC__uint16;
  85851. typedef unsigned long FLAC__uint32;
  85852. typedef unsigned long long FLAC__uint64;
  85853. #else
  85854. typedef int16_t FLAC__int16;
  85855. typedef int32_t FLAC__int32;
  85856. typedef int64_t FLAC__int64;
  85857. typedef uint16_t FLAC__uint16;
  85858. typedef uint32_t FLAC__uint32;
  85859. typedef uint64_t FLAC__uint64;
  85860. #endif
  85861. typedef int FLAC__bool;
  85862. typedef FLAC__uint8 FLAC__byte;
  85863. #ifdef true
  85864. #undef true
  85865. #endif
  85866. #ifdef false
  85867. #undef false
  85868. #endif
  85869. #ifndef __cplusplus
  85870. #define true 1
  85871. #define false 0
  85872. #endif
  85873. #endif
  85874. /*** End of inlined file: ordinals.h ***/
  85875. #include <stdlib.h> /* for size_t */
  85876. /** \file include/FLAC/callback.h
  85877. *
  85878. * \brief
  85879. * This module defines the structures for describing I/O callbacks
  85880. * to the other FLAC interfaces.
  85881. *
  85882. * See the detailed documentation for callbacks in the
  85883. * \link flac_callbacks callbacks \endlink module.
  85884. */
  85885. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  85886. * \ingroup flac
  85887. *
  85888. * \brief
  85889. * This module defines the structures for describing I/O callbacks
  85890. * to the other FLAC interfaces.
  85891. *
  85892. * The purpose of the I/O callback functions is to create a common way
  85893. * for the metadata interfaces to handle I/O.
  85894. *
  85895. * Originally the metadata interfaces required filenames as the way of
  85896. * specifying FLAC files to operate on. This is problematic in some
  85897. * environments so there is an additional option to specify a set of
  85898. * callbacks for doing I/O on the FLAC file, instead of the filename.
  85899. *
  85900. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  85901. * opaque structure for a data source.
  85902. *
  85903. * The callback function prototypes are similar (but not identical) to the
  85904. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  85905. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  85906. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  85907. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  85908. * is required. \warning You generally CANNOT directly use fseek or ftell
  85909. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  85910. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  85911. * large files. You will have to find an equivalent function (e.g. ftello),
  85912. * or write a wrapper. The same is true for feof() since this is usually
  85913. * implemented as a macro, not as a function whose address can be taken.
  85914. *
  85915. * \{
  85916. */
  85917. #ifdef __cplusplus
  85918. extern "C" {
  85919. #endif
  85920. /** This is the opaque handle type used by the callbacks. Typically
  85921. * this is a \c FILE* or address of a file descriptor.
  85922. */
  85923. typedef void* FLAC__IOHandle;
  85924. /** Signature for the read callback.
  85925. * The signature and semantics match POSIX fread() implementations
  85926. * and can generally be used interchangeably.
  85927. *
  85928. * \param ptr The address of the read buffer.
  85929. * \param size The size of the records to be read.
  85930. * \param nmemb The number of records to be read.
  85931. * \param handle The handle to the data source.
  85932. * \retval size_t
  85933. * The number of records read.
  85934. */
  85935. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  85936. /** Signature for the write callback.
  85937. * The signature and semantics match POSIX fwrite() implementations
  85938. * and can generally be used interchangeably.
  85939. *
  85940. * \param ptr The address of the write buffer.
  85941. * \param size The size of the records to be written.
  85942. * \param nmemb The number of records to be written.
  85943. * \param handle The handle to the data source.
  85944. * \retval size_t
  85945. * The number of records written.
  85946. */
  85947. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  85948. /** Signature for the seek callback.
  85949. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  85950. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  85951. * and 32-bits wide.
  85952. *
  85953. * \param handle The handle to the data source.
  85954. * \param offset The new position, relative to \a whence
  85955. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  85956. * \retval int
  85957. * \c 0 on success, \c -1 on error.
  85958. */
  85959. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  85960. /** Signature for the tell callback.
  85961. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  85962. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  85963. * and 32-bits wide.
  85964. *
  85965. * \param handle The handle to the data source.
  85966. * \retval FLAC__int64
  85967. * The current position on success, \c -1 on error.
  85968. */
  85969. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  85970. /** Signature for the EOF callback.
  85971. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  85972. * on many systems, feof() is a macro, so in this case a wrapper function
  85973. * must be provided instead.
  85974. *
  85975. * \param handle The handle to the data source.
  85976. * \retval int
  85977. * \c 0 if not at end of file, nonzero if at end of file.
  85978. */
  85979. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  85980. /** Signature for the close callback.
  85981. * The signature and semantics match POSIX fclose() implementations
  85982. * and can generally be used interchangeably.
  85983. *
  85984. * \param handle The handle to the data source.
  85985. * \retval int
  85986. * \c 0 on success, \c EOF on error.
  85987. */
  85988. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  85989. /** A structure for holding a set of callbacks.
  85990. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  85991. * describe which of the callbacks are required. The ones that are not
  85992. * required may be set to NULL.
  85993. *
  85994. * If the seek requirement for an interface is optional, you can signify that
  85995. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  85996. */
  85997. typedef struct {
  85998. FLAC__IOCallback_Read read;
  85999. FLAC__IOCallback_Write write;
  86000. FLAC__IOCallback_Seek seek;
  86001. FLAC__IOCallback_Tell tell;
  86002. FLAC__IOCallback_Eof eof;
  86003. FLAC__IOCallback_Close close;
  86004. } FLAC__IOCallbacks;
  86005. /* \} */
  86006. #ifdef __cplusplus
  86007. }
  86008. #endif
  86009. #endif
  86010. /*** End of inlined file: callback.h ***/
  86011. /*** Start of inlined file: format.h ***/
  86012. #ifndef FLAC__FORMAT_H
  86013. #define FLAC__FORMAT_H
  86014. #ifdef __cplusplus
  86015. extern "C" {
  86016. #endif
  86017. /** \file include/FLAC/format.h
  86018. *
  86019. * \brief
  86020. * This module contains structure definitions for the representation
  86021. * of FLAC format components in memory. These are the basic
  86022. * structures used by the rest of the interfaces.
  86023. *
  86024. * See the detailed documentation in the
  86025. * \link flac_format format \endlink module.
  86026. */
  86027. /** \defgroup flac_format FLAC/format.h: format components
  86028. * \ingroup flac
  86029. *
  86030. * \brief
  86031. * This module contains structure definitions for the representation
  86032. * of FLAC format components in memory. These are the basic
  86033. * structures used by the rest of the interfaces.
  86034. *
  86035. * First, you should be familiar with the
  86036. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86037. * follow directly from the specification. As a user of libFLAC, the
  86038. * interesting parts really are the structures that describe the frame
  86039. * header and metadata blocks.
  86040. *
  86041. * The format structures here are very primitive, designed to store
  86042. * information in an efficient way. Reading information from the
  86043. * structures is easy but creating or modifying them directly is
  86044. * more complex. For the most part, as a user of a library, editing
  86045. * is not necessary; however, for metadata blocks it is, so there are
  86046. * convenience functions provided in the \link flac_metadata metadata
  86047. * module \endlink to simplify the manipulation of metadata blocks.
  86048. *
  86049. * \note
  86050. * It's not the best convention, but symbols ending in _LEN are in bits
  86051. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86052. * global variables because they are usually used when declaring byte
  86053. * arrays and some compilers require compile-time knowledge of array
  86054. * sizes when declared on the stack.
  86055. *
  86056. * \{
  86057. */
  86058. /*
  86059. Most of the values described in this file are defined by the FLAC
  86060. format specification. There is nothing to tune here.
  86061. */
  86062. /** The largest legal metadata type code. */
  86063. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86064. /** The minimum block size, in samples, permitted by the format. */
  86065. #define FLAC__MIN_BLOCK_SIZE (16u)
  86066. /** The maximum block size, in samples, permitted by the format. */
  86067. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86068. /** The maximum block size, in samples, permitted by the FLAC subset for
  86069. * sample rates up to 48kHz. */
  86070. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86071. /** The maximum number of channels permitted by the format. */
  86072. #define FLAC__MAX_CHANNELS (8u)
  86073. /** The minimum sample resolution permitted by the format. */
  86074. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86075. /** The maximum sample resolution permitted by the format. */
  86076. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86077. /** The maximum sample resolution permitted by libFLAC.
  86078. *
  86079. * \warning
  86080. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86081. * the reference encoder/decoder is currently limited to 24 bits because
  86082. * of prevalent 32-bit math, so make sure and use this value when
  86083. * appropriate.
  86084. */
  86085. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86086. /** The maximum sample rate permitted by the format. The value is
  86087. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86088. * as to why.
  86089. */
  86090. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86091. /** The maximum LPC order permitted by the format. */
  86092. #define FLAC__MAX_LPC_ORDER (32u)
  86093. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86094. * up to 48kHz. */
  86095. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86096. /** The minimum quantized linear predictor coefficient precision
  86097. * permitted by the format.
  86098. */
  86099. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86100. /** The maximum quantized linear predictor coefficient precision
  86101. * permitted by the format.
  86102. */
  86103. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86104. /** The maximum order of the fixed predictors permitted by the format. */
  86105. #define FLAC__MAX_FIXED_ORDER (4u)
  86106. /** The maximum Rice partition order permitted by the format. */
  86107. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86108. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86109. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86110. /** The version string of the release, stamped onto the libraries and binaries.
  86111. *
  86112. * \note
  86113. * This does not correspond to the shared library version number, which
  86114. * is used to determine binary compatibility.
  86115. */
  86116. extern FLAC_API const char *FLAC__VERSION_STRING;
  86117. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86118. * This is a NUL-terminated ASCII string; when inserted into the
  86119. * VORBIS_COMMENT the trailing null is stripped.
  86120. */
  86121. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86122. /** The byte string representation of the beginning of a FLAC stream. */
  86123. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86124. /** The 32-bit integer big-endian representation of the beginning of
  86125. * a FLAC stream.
  86126. */
  86127. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86128. /** The length of the FLAC signature in bits. */
  86129. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86130. /** The length of the FLAC signature in bytes. */
  86131. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86132. /*****************************************************************************
  86133. *
  86134. * Subframe structures
  86135. *
  86136. *****************************************************************************/
  86137. /*****************************************************************************/
  86138. /** An enumeration of the available entropy coding methods. */
  86139. typedef enum {
  86140. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86141. /**< Residual is coded by partitioning into contexts, each with it's own
  86142. * 4-bit Rice parameter. */
  86143. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86144. /**< Residual is coded by partitioning into contexts, each with it's own
  86145. * 5-bit Rice parameter. */
  86146. } FLAC__EntropyCodingMethodType;
  86147. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86148. *
  86149. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86150. * give the string equivalent. The contents should not be modified.
  86151. */
  86152. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86153. /** Contents of a Rice partitioned residual
  86154. */
  86155. typedef struct {
  86156. unsigned *parameters;
  86157. /**< The Rice parameters for each context. */
  86158. unsigned *raw_bits;
  86159. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86160. * partitions and zero for unescaped partitions.
  86161. */
  86162. unsigned capacity_by_order;
  86163. /**< The capacity of the \a parameters and \a raw_bits arrays
  86164. * specified as an order, i.e. the number of array elements
  86165. * allocated is 2 ^ \a capacity_by_order.
  86166. */
  86167. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86168. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86169. */
  86170. typedef struct {
  86171. unsigned order;
  86172. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86173. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86174. /**< The context's Rice parameters and/or raw bits. */
  86175. } FLAC__EntropyCodingMethod_PartitionedRice;
  86176. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86177. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86178. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86179. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86180. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86181. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86182. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86183. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86184. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86185. */
  86186. typedef struct {
  86187. FLAC__EntropyCodingMethodType type;
  86188. union {
  86189. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86190. } data;
  86191. } FLAC__EntropyCodingMethod;
  86192. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86193. /*****************************************************************************/
  86194. /** An enumeration of the available subframe types. */
  86195. typedef enum {
  86196. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86197. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86198. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86199. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86200. } FLAC__SubframeType;
  86201. /** Maps a FLAC__SubframeType to a C string.
  86202. *
  86203. * Using a FLAC__SubframeType as the index to this array will
  86204. * give the string equivalent. The contents should not be modified.
  86205. */
  86206. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86207. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86208. */
  86209. typedef struct {
  86210. FLAC__int32 value; /**< The constant signal value. */
  86211. } FLAC__Subframe_Constant;
  86212. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86213. */
  86214. typedef struct {
  86215. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86216. } FLAC__Subframe_Verbatim;
  86217. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86218. */
  86219. typedef struct {
  86220. FLAC__EntropyCodingMethod entropy_coding_method;
  86221. /**< The residual coding method. */
  86222. unsigned order;
  86223. /**< The polynomial order. */
  86224. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86225. /**< Warmup samples to prime the predictor, length == order. */
  86226. const FLAC__int32 *residual;
  86227. /**< The residual signal, length == (blocksize minus order) samples. */
  86228. } FLAC__Subframe_Fixed;
  86229. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86230. */
  86231. typedef struct {
  86232. FLAC__EntropyCodingMethod entropy_coding_method;
  86233. /**< The residual coding method. */
  86234. unsigned order;
  86235. /**< The FIR order. */
  86236. unsigned qlp_coeff_precision;
  86237. /**< Quantized FIR filter coefficient precision in bits. */
  86238. int quantization_level;
  86239. /**< The qlp coeff shift needed. */
  86240. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86241. /**< FIR filter coefficients. */
  86242. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  86243. /**< Warmup samples to prime the predictor, length == order. */
  86244. const FLAC__int32 *residual;
  86245. /**< The residual signal, length == (blocksize minus order) samples. */
  86246. } FLAC__Subframe_LPC;
  86247. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  86248. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  86249. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  86250. */
  86251. typedef struct {
  86252. FLAC__SubframeType type;
  86253. union {
  86254. FLAC__Subframe_Constant constant;
  86255. FLAC__Subframe_Fixed fixed;
  86256. FLAC__Subframe_LPC lpc;
  86257. FLAC__Subframe_Verbatim verbatim;
  86258. } data;
  86259. unsigned wasted_bits;
  86260. } FLAC__Subframe;
  86261. /** == 1 (bit)
  86262. *
  86263. * This used to be a zero-padding bit (hence the name
  86264. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  86265. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  86266. * to mean something else.
  86267. */
  86268. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  86269. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  86270. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  86271. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  86272. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  86273. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  86274. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  86275. /*****************************************************************************/
  86276. /*****************************************************************************
  86277. *
  86278. * Frame structures
  86279. *
  86280. *****************************************************************************/
  86281. /** An enumeration of the available channel assignments. */
  86282. typedef enum {
  86283. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  86284. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  86285. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  86286. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  86287. } FLAC__ChannelAssignment;
  86288. /** Maps a FLAC__ChannelAssignment to a C string.
  86289. *
  86290. * Using a FLAC__ChannelAssignment as the index to this array will
  86291. * give the string equivalent. The contents should not be modified.
  86292. */
  86293. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  86294. /** An enumeration of the possible frame numbering methods. */
  86295. typedef enum {
  86296. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  86297. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  86298. } FLAC__FrameNumberType;
  86299. /** Maps a FLAC__FrameNumberType to a C string.
  86300. *
  86301. * Using a FLAC__FrameNumberType as the index to this array will
  86302. * give the string equivalent. The contents should not be modified.
  86303. */
  86304. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86305. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86306. */
  86307. typedef struct {
  86308. unsigned blocksize;
  86309. /**< The number of samples per subframe. */
  86310. unsigned sample_rate;
  86311. /**< The sample rate in Hz. */
  86312. unsigned channels;
  86313. /**< The number of channels (== number of subframes). */
  86314. FLAC__ChannelAssignment channel_assignment;
  86315. /**< The channel assignment for the frame. */
  86316. unsigned bits_per_sample;
  86317. /**< The sample resolution. */
  86318. FLAC__FrameNumberType number_type;
  86319. /**< The numbering scheme used for the frame. As a convenience, the
  86320. * decoder will always convert a frame number to a sample number because
  86321. * the rules are complex. */
  86322. union {
  86323. FLAC__uint32 frame_number;
  86324. FLAC__uint64 sample_number;
  86325. } number;
  86326. /**< The frame number or sample number of first sample in frame;
  86327. * use the \a number_type value to determine which to use. */
  86328. FLAC__uint8 crc;
  86329. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86330. * of the raw frame header bytes, meaning everything before the CRC byte
  86331. * including the sync code.
  86332. */
  86333. } FLAC__FrameHeader;
  86334. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86335. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86336. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86337. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86338. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86339. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86340. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86341. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86342. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86343. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86344. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86345. */
  86346. typedef struct {
  86347. FLAC__uint16 crc;
  86348. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86349. * 0) of the bytes before the crc, back to and including the frame header
  86350. * sync code.
  86351. */
  86352. } FLAC__FrameFooter;
  86353. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86354. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86355. */
  86356. typedef struct {
  86357. FLAC__FrameHeader header;
  86358. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  86359. FLAC__FrameFooter footer;
  86360. } FLAC__Frame;
  86361. /*****************************************************************************/
  86362. /*****************************************************************************
  86363. *
  86364. * Meta-data structures
  86365. *
  86366. *****************************************************************************/
  86367. /** An enumeration of the available metadata block types. */
  86368. typedef enum {
  86369. FLAC__METADATA_TYPE_STREAMINFO = 0,
  86370. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  86371. FLAC__METADATA_TYPE_PADDING = 1,
  86372. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  86373. FLAC__METADATA_TYPE_APPLICATION = 2,
  86374. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  86375. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  86376. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  86377. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  86378. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  86379. FLAC__METADATA_TYPE_CUESHEET = 5,
  86380. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  86381. FLAC__METADATA_TYPE_PICTURE = 6,
  86382. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  86383. FLAC__METADATA_TYPE_UNDEFINED = 7
  86384. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  86385. } FLAC__MetadataType;
  86386. /** Maps a FLAC__MetadataType to a C string.
  86387. *
  86388. * Using a FLAC__MetadataType as the index to this array will
  86389. * give the string equivalent. The contents should not be modified.
  86390. */
  86391. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  86392. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  86393. */
  86394. typedef struct {
  86395. unsigned min_blocksize, max_blocksize;
  86396. unsigned min_framesize, max_framesize;
  86397. unsigned sample_rate;
  86398. unsigned channels;
  86399. unsigned bits_per_sample;
  86400. FLAC__uint64 total_samples;
  86401. FLAC__byte md5sum[16];
  86402. } FLAC__StreamMetadata_StreamInfo;
  86403. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86404. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86405. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86406. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86407. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  86408. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  86409. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  86410. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  86411. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  86412. /** The total stream length of the STREAMINFO block in bytes. */
  86413. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  86414. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  86415. */
  86416. typedef struct {
  86417. int dummy;
  86418. /**< Conceptually this is an empty struct since we don't store the
  86419. * padding bytes. Empty structs are not allowed by some C compilers,
  86420. * hence the dummy.
  86421. */
  86422. } FLAC__StreamMetadata_Padding;
  86423. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  86424. */
  86425. typedef struct {
  86426. FLAC__byte id[4];
  86427. FLAC__byte *data;
  86428. } FLAC__StreamMetadata_Application;
  86429. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  86430. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  86431. */
  86432. typedef struct {
  86433. FLAC__uint64 sample_number;
  86434. /**< The sample number of the target frame. */
  86435. FLAC__uint64 stream_offset;
  86436. /**< The offset, in bytes, of the target frame with respect to
  86437. * beginning of the first frame. */
  86438. unsigned frame_samples;
  86439. /**< The number of samples in the target frame. */
  86440. } FLAC__StreamMetadata_SeekPoint;
  86441. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  86442. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  86443. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  86444. /** The total stream length of a seek point in bytes. */
  86445. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  86446. /** The value used in the \a sample_number field of
  86447. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  86448. * point (== 0xffffffffffffffff).
  86449. */
  86450. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  86451. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  86452. *
  86453. * \note From the format specification:
  86454. * - The seek points must be sorted by ascending sample number.
  86455. * - Each seek point's sample number must be the first sample of the
  86456. * target frame.
  86457. * - Each seek point's sample number must be unique within the table.
  86458. * - Existence of a SEEKTABLE block implies a correct setting of
  86459. * total_samples in the stream_info block.
  86460. * - Behavior is undefined when more than one SEEKTABLE block is
  86461. * present in a stream.
  86462. */
  86463. typedef struct {
  86464. unsigned num_points;
  86465. FLAC__StreamMetadata_SeekPoint *points;
  86466. } FLAC__StreamMetadata_SeekTable;
  86467. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86468. *
  86469. * For convenience, the APIs maintain a trailing NUL character at the end of
  86470. * \a entry which is not counted toward \a length, i.e.
  86471. * \code strlen(entry) == length \endcode
  86472. */
  86473. typedef struct {
  86474. FLAC__uint32 length;
  86475. FLAC__byte *entry;
  86476. } FLAC__StreamMetadata_VorbisComment_Entry;
  86477. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  86478. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86479. */
  86480. typedef struct {
  86481. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  86482. FLAC__uint32 num_comments;
  86483. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  86484. } FLAC__StreamMetadata_VorbisComment;
  86485. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  86486. /** FLAC CUESHEET track index structure. (See the
  86487. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  86488. * the full description of each field.)
  86489. */
  86490. typedef struct {
  86491. FLAC__uint64 offset;
  86492. /**< Offset in samples, relative to the track offset, of the index
  86493. * point.
  86494. */
  86495. FLAC__byte number;
  86496. /**< The index point number. */
  86497. } FLAC__StreamMetadata_CueSheet_Index;
  86498. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  86499. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  86500. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  86501. /** FLAC CUESHEET track structure. (See the
  86502. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  86503. * the full description of each field.)
  86504. */
  86505. typedef struct {
  86506. FLAC__uint64 offset;
  86507. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  86508. FLAC__byte number;
  86509. /**< The track number. */
  86510. char isrc[13];
  86511. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  86512. unsigned type:1;
  86513. /**< The track type: 0 for audio, 1 for non-audio. */
  86514. unsigned pre_emphasis:1;
  86515. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  86516. FLAC__byte num_indices;
  86517. /**< The number of track index points. */
  86518. FLAC__StreamMetadata_CueSheet_Index *indices;
  86519. /**< NULL if num_indices == 0, else pointer to array of index points. */
  86520. } FLAC__StreamMetadata_CueSheet_Track;
  86521. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  86522. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  86523. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  86524. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  86525. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  86526. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  86527. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  86528. /** FLAC CUESHEET structure. (See the
  86529. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  86530. * for the full description of each field.)
  86531. */
  86532. typedef struct {
  86533. char media_catalog_number[129];
  86534. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  86535. * general, the media catalog number may be 0 to 128 bytes long; any
  86536. * unused characters should be right-padded with NUL characters.
  86537. */
  86538. FLAC__uint64 lead_in;
  86539. /**< The number of lead-in samples. */
  86540. FLAC__bool is_cd;
  86541. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  86542. unsigned num_tracks;
  86543. /**< The number of tracks. */
  86544. FLAC__StreamMetadata_CueSheet_Track *tracks;
  86545. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  86546. } FLAC__StreamMetadata_CueSheet;
  86547. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  86548. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  86549. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  86550. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  86551. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  86552. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  86553. typedef enum {
  86554. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  86555. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  86556. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  86557. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  86558. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  86559. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  86560. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  86561. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  86562. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  86563. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  86564. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  86565. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  86566. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  86567. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  86568. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  86569. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  86570. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  86571. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  86572. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  86573. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  86574. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  86575. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  86576. } FLAC__StreamMetadata_Picture_Type;
  86577. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  86578. *
  86579. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  86580. * will give the string equivalent. The contents should not be
  86581. * modified.
  86582. */
  86583. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  86584. /** FLAC PICTURE structure. (See the
  86585. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  86586. * for the full description of each field.)
  86587. */
  86588. typedef struct {
  86589. FLAC__StreamMetadata_Picture_Type type;
  86590. /**< The kind of picture stored. */
  86591. char *mime_type;
  86592. /**< Picture data's MIME type, in ASCII printable characters
  86593. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  86594. * use picture data of MIME type \c image/jpeg or \c image/png. A
  86595. * MIME type of '-->' is also allowed, in which case the picture
  86596. * data should be a complete URL. In file storage, the MIME type is
  86597. * stored as a 32-bit length followed by the ASCII string with no NUL
  86598. * terminator, but is converted to a plain C string in this structure
  86599. * for convenience.
  86600. */
  86601. FLAC__byte *description;
  86602. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  86603. * the description is stored as a 32-bit length followed by the UTF-8
  86604. * string with no NUL terminator, but is converted to a plain C string
  86605. * in this structure for convenience.
  86606. */
  86607. FLAC__uint32 width;
  86608. /**< Picture's width in pixels. */
  86609. FLAC__uint32 height;
  86610. /**< Picture's height in pixels. */
  86611. FLAC__uint32 depth;
  86612. /**< Picture's color depth in bits-per-pixel. */
  86613. FLAC__uint32 colors;
  86614. /**< For indexed palettes (like GIF), picture's number of colors (the
  86615. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  86616. */
  86617. FLAC__uint32 data_length;
  86618. /**< Length of binary picture data in bytes. */
  86619. FLAC__byte *data;
  86620. /**< Binary picture data. */
  86621. } FLAC__StreamMetadata_Picture;
  86622. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  86623. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  86624. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  86625. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  86626. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  86627. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  86628. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  86629. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  86630. /** Structure that is used when a metadata block of unknown type is loaded.
  86631. * The contents are opaque. The structure is used only internally to
  86632. * correctly handle unknown metadata.
  86633. */
  86634. typedef struct {
  86635. FLAC__byte *data;
  86636. } FLAC__StreamMetadata_Unknown;
  86637. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  86638. */
  86639. typedef struct {
  86640. FLAC__MetadataType type;
  86641. /**< The type of the metadata block; used determine which member of the
  86642. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  86643. * then \a data.unknown must be used. */
  86644. FLAC__bool is_last;
  86645. /**< \c true if this metadata block is the last, else \a false */
  86646. unsigned length;
  86647. /**< Length, in bytes, of the block data as it appears in the stream. */
  86648. union {
  86649. FLAC__StreamMetadata_StreamInfo stream_info;
  86650. FLAC__StreamMetadata_Padding padding;
  86651. FLAC__StreamMetadata_Application application;
  86652. FLAC__StreamMetadata_SeekTable seek_table;
  86653. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  86654. FLAC__StreamMetadata_CueSheet cue_sheet;
  86655. FLAC__StreamMetadata_Picture picture;
  86656. FLAC__StreamMetadata_Unknown unknown;
  86657. } data;
  86658. /**< Polymorphic block data; use the \a type value to determine which
  86659. * to use. */
  86660. } FLAC__StreamMetadata;
  86661. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  86662. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  86663. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  86664. /** The total stream length of a metadata block header in bytes. */
  86665. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  86666. /*****************************************************************************/
  86667. /*****************************************************************************
  86668. *
  86669. * Utility functions
  86670. *
  86671. *****************************************************************************/
  86672. /** Tests that a sample rate is valid for FLAC.
  86673. *
  86674. * \param sample_rate The sample rate to test for compliance.
  86675. * \retval FLAC__bool
  86676. * \c true if the given sample rate conforms to the specification, else
  86677. * \c false.
  86678. */
  86679. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  86680. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  86681. * for valid sample rates are slightly more complex since the rate has to
  86682. * be expressible completely in the frame header.
  86683. *
  86684. * \param sample_rate The sample rate to test for compliance.
  86685. * \retval FLAC__bool
  86686. * \c true if the given sample rate conforms to the specification for the
  86687. * subset, else \c false.
  86688. */
  86689. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  86690. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  86691. * comment specification.
  86692. *
  86693. * Vorbis comment names must be composed only of characters from
  86694. * [0x20-0x3C,0x3E-0x7D].
  86695. *
  86696. * \param name A NUL-terminated string to be checked.
  86697. * \assert
  86698. * \code name != NULL \endcode
  86699. * \retval FLAC__bool
  86700. * \c false if entry name is illegal, else \c true.
  86701. */
  86702. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  86703. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  86704. * comment specification.
  86705. *
  86706. * Vorbis comment values must be valid UTF-8 sequences.
  86707. *
  86708. * \param value A string to be checked.
  86709. * \param length A the length of \a value in bytes. May be
  86710. * \c (unsigned)(-1) to indicate that \a value is a plain
  86711. * UTF-8 NUL-terminated string.
  86712. * \assert
  86713. * \code value != NULL \endcode
  86714. * \retval FLAC__bool
  86715. * \c false if entry name is illegal, else \c true.
  86716. */
  86717. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  86718. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  86719. * comment specification.
  86720. *
  86721. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  86722. * 'value' must be legal according to
  86723. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  86724. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  86725. *
  86726. * \param entry An entry to be checked.
  86727. * \param length The length of \a entry in bytes.
  86728. * \assert
  86729. * \code value != NULL \endcode
  86730. * \retval FLAC__bool
  86731. * \c false if entry name is illegal, else \c true.
  86732. */
  86733. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  86734. /** Check a seek table to see if it conforms to the FLAC specification.
  86735. * See the format specification for limits on the contents of the
  86736. * seek table.
  86737. *
  86738. * \param seek_table A pointer to a seek table to be checked.
  86739. * \assert
  86740. * \code seek_table != NULL \endcode
  86741. * \retval FLAC__bool
  86742. * \c false if seek table is illegal, else \c true.
  86743. */
  86744. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  86745. /** Sort a seek table's seek points according to the format specification.
  86746. * This includes a "unique-ification" step to remove duplicates, i.e.
  86747. * seek points with identical \a sample_number values. Duplicate seek
  86748. * points are converted into placeholder points and sorted to the end of
  86749. * the table.
  86750. *
  86751. * \param seek_table A pointer to a seek table to be sorted.
  86752. * \assert
  86753. * \code seek_table != NULL \endcode
  86754. * \retval unsigned
  86755. * The number of duplicate seek points converted into placeholders.
  86756. */
  86757. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  86758. /** Check a cue sheet to see if it conforms to the FLAC specification.
  86759. * See the format specification for limits on the contents of the
  86760. * cue sheet.
  86761. *
  86762. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  86763. * \param check_cd_da_subset If \c true, check CUESHEET against more
  86764. * stringent requirements for a CD-DA (audio) disc.
  86765. * \param violation Address of a pointer to a string. If there is a
  86766. * violation, a pointer to a string explanation of the
  86767. * violation will be returned here. \a violation may be
  86768. * \c NULL if you don't need the returned string. Do not
  86769. * free the returned string; it will always point to static
  86770. * data.
  86771. * \assert
  86772. * \code cue_sheet != NULL \endcode
  86773. * \retval FLAC__bool
  86774. * \c false if cue sheet is illegal, else \c true.
  86775. */
  86776. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  86777. /** Check picture data to see if it conforms to the FLAC specification.
  86778. * See the format specification for limits on the contents of the
  86779. * PICTURE block.
  86780. *
  86781. * \param picture A pointer to existing picture data to be checked.
  86782. * \param violation Address of a pointer to a string. If there is a
  86783. * violation, a pointer to a string explanation of the
  86784. * violation will be returned here. \a violation may be
  86785. * \c NULL if you don't need the returned string. Do not
  86786. * free the returned string; it will always point to static
  86787. * data.
  86788. * \assert
  86789. * \code picture != NULL \endcode
  86790. * \retval FLAC__bool
  86791. * \c false if picture data is illegal, else \c true.
  86792. */
  86793. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  86794. /* \} */
  86795. #ifdef __cplusplus
  86796. }
  86797. #endif
  86798. #endif
  86799. /*** End of inlined file: format.h ***/
  86800. /*** Start of inlined file: metadata.h ***/
  86801. #ifndef FLAC__METADATA_H
  86802. #define FLAC__METADATA_H
  86803. #include <sys/types.h> /* for off_t */
  86804. /* --------------------------------------------------------------------
  86805. (For an example of how all these routines are used, see the source
  86806. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  86807. metaflac in src/metaflac/)
  86808. ------------------------------------------------------------------*/
  86809. /** \file include/FLAC/metadata.h
  86810. *
  86811. * \brief
  86812. * This module provides functions for creating and manipulating FLAC
  86813. * metadata blocks in memory, and three progressively more powerful
  86814. * interfaces for traversing and editing metadata in FLAC files.
  86815. *
  86816. * See the detailed documentation for each interface in the
  86817. * \link flac_metadata metadata \endlink module.
  86818. */
  86819. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  86820. * \ingroup flac
  86821. *
  86822. * \brief
  86823. * This module provides functions for creating and manipulating FLAC
  86824. * metadata blocks in memory, and three progressively more powerful
  86825. * interfaces for traversing and editing metadata in native FLAC files.
  86826. * Note that currently only the Chain interface (level 2) supports Ogg
  86827. * FLAC files, and it is read-only i.e. no writing back changed
  86828. * metadata to file.
  86829. *
  86830. * There are three metadata interfaces of increasing complexity:
  86831. *
  86832. * Level 0:
  86833. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  86834. * PICTURE blocks.
  86835. *
  86836. * Level 1:
  86837. * Read-write access to all metadata blocks. This level is write-
  86838. * efficient in most cases (more on this below), and uses less memory
  86839. * than level 2.
  86840. *
  86841. * Level 2:
  86842. * Read-write access to all metadata blocks. This level is write-
  86843. * efficient in all cases, but uses more memory since all metadata for
  86844. * the whole file is read into memory and manipulated before writing
  86845. * out again.
  86846. *
  86847. * What do we mean by efficient? Since FLAC metadata appears at the
  86848. * beginning of the file, when writing metadata back to a FLAC file
  86849. * it is possible to grow or shrink the metadata such that the entire
  86850. * file must be rewritten. However, if the size remains the same during
  86851. * changes or PADDING blocks are utilized, only the metadata needs to be
  86852. * overwritten, which is much faster.
  86853. *
  86854. * Efficient means the whole file is rewritten at most one time, and only
  86855. * when necessary. Level 1 is not efficient only in the case that you
  86856. * cause more than one metadata block to grow or shrink beyond what can
  86857. * be accomodated by padding. In this case you should probably use level
  86858. * 2, which allows you to edit all the metadata for a file in memory and
  86859. * write it out all at once.
  86860. *
  86861. * All levels know how to skip over and not disturb an ID3v2 tag at the
  86862. * front of the file.
  86863. *
  86864. * All levels access files via their filenames. In addition, level 2
  86865. * has additional alternative read and write functions that take an I/O
  86866. * handle and callbacks, for situations where access by filename is not
  86867. * possible.
  86868. *
  86869. * In addition to the three interfaces, this module defines functions for
  86870. * creating and manipulating various metadata objects in memory. As we see
  86871. * from the Format module, FLAC metadata blocks in memory are very primitive
  86872. * structures for storing information in an efficient way. Reading
  86873. * information from the structures is easy but creating or modifying them
  86874. * directly is more complex. The metadata object routines here facilitate
  86875. * this by taking care of the consistency and memory management drudgery.
  86876. *
  86877. * Unless you will be using the level 1 or 2 interfaces to modify existing
  86878. * metadata however, you will not probably not need these.
  86879. *
  86880. * From a dependency standpoint, none of the encoders or decoders require
  86881. * the metadata module. This is so that embedded users can strip out the
  86882. * metadata module from libFLAC to reduce the size and complexity.
  86883. */
  86884. #ifdef __cplusplus
  86885. extern "C" {
  86886. #endif
  86887. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  86888. * \ingroup flac_metadata
  86889. *
  86890. * \brief
  86891. * The level 0 interface consists of individual routines to read the
  86892. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  86893. * only a filename.
  86894. *
  86895. * They try to skip any ID3v2 tag at the head of the file.
  86896. *
  86897. * \{
  86898. */
  86899. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  86900. * will try to skip any ID3v2 tag at the head of the file.
  86901. *
  86902. * \param filename The path to the FLAC file to read.
  86903. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  86904. * FLAC__StreamMetadata is a simple structure with no
  86905. * memory allocation involved, you pass the address of
  86906. * an existing structure. It need not be initialized.
  86907. * \assert
  86908. * \code filename != NULL \endcode
  86909. * \code streaminfo != NULL \endcode
  86910. * \retval FLAC__bool
  86911. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  86912. * \c false if there was a memory allocation error, a file decoder error,
  86913. * or the file contained no STREAMINFO block. (A memory allocation error
  86914. * is possible because this function must set up a file decoder.)
  86915. */
  86916. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  86917. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  86918. * function will try to skip any ID3v2 tag at the head of the file.
  86919. *
  86920. * \param filename The path to the FLAC file to read.
  86921. * \param tags The address where the returned pointer will be
  86922. * stored. The \a tags object must be deleted by
  86923. * the caller using FLAC__metadata_object_delete().
  86924. * \assert
  86925. * \code filename != NULL \endcode
  86926. * \code tags != NULL \endcode
  86927. * \retval FLAC__bool
  86928. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  86929. * and \a *tags will be set to the address of the metadata structure.
  86930. * Returns \c false if there was a memory allocation error, a file
  86931. * decoder error, or the file contained no VORBIS_COMMENT block, and
  86932. * \a *tags will be set to \c NULL.
  86933. */
  86934. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  86935. /** Read the CUESHEET metadata block of the given FLAC file. This
  86936. * function will try to skip any ID3v2 tag at the head of the file.
  86937. *
  86938. * \param filename The path to the FLAC file to read.
  86939. * \param cuesheet The address where the returned pointer will be
  86940. * stored. The \a cuesheet object must be deleted by
  86941. * the caller using FLAC__metadata_object_delete().
  86942. * \assert
  86943. * \code filename != NULL \endcode
  86944. * \code cuesheet != NULL \endcode
  86945. * \retval FLAC__bool
  86946. * \c true if a valid CUESHEET block was read from \a filename,
  86947. * and \a *cuesheet will be set to the address of the metadata
  86948. * structure. Returns \c false if there was a memory allocation
  86949. * error, a file decoder error, or the file contained no CUESHEET
  86950. * block, and \a *cuesheet will be set to \c NULL.
  86951. */
  86952. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  86953. /** Read a PICTURE metadata block of the given FLAC file. This
  86954. * function will try to skip any ID3v2 tag at the head of the file.
  86955. * Since there can be more than one PICTURE block in a file, this
  86956. * function takes a number of parameters that act as constraints to
  86957. * the search. The PICTURE block with the largest area matching all
  86958. * the constraints will be returned, or \a *picture will be set to
  86959. * \c NULL if there was no such block.
  86960. *
  86961. * \param filename The path to the FLAC file to read.
  86962. * \param picture The address where the returned pointer will be
  86963. * stored. The \a picture object must be deleted by
  86964. * the caller using FLAC__metadata_object_delete().
  86965. * \param type The desired picture type. Use \c -1 to mean
  86966. * "any type".
  86967. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  86968. * string will be matched exactly. Use \c NULL to
  86969. * mean "any MIME type".
  86970. * \param description The desired description. The string will be
  86971. * matched exactly. Use \c NULL to mean "any
  86972. * description".
  86973. * \param max_width The maximum width in pixels desired. Use
  86974. * \c (unsigned)(-1) to mean "any width".
  86975. * \param max_height The maximum height in pixels desired. Use
  86976. * \c (unsigned)(-1) to mean "any height".
  86977. * \param max_depth The maximum color depth in bits-per-pixel desired.
  86978. * Use \c (unsigned)(-1) to mean "any depth".
  86979. * \param max_colors The maximum number of colors desired. Use
  86980. * \c (unsigned)(-1) to mean "any number of colors".
  86981. * \assert
  86982. * \code filename != NULL \endcode
  86983. * \code picture != NULL \endcode
  86984. * \retval FLAC__bool
  86985. * \c true if a valid PICTURE block was read from \a filename,
  86986. * and \a *picture will be set to the address of the metadata
  86987. * structure. Returns \c false if there was a memory allocation
  86988. * error, a file decoder error, or the file contained no PICTURE
  86989. * block, and \a *picture will be set to \c NULL.
  86990. */
  86991. 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);
  86992. /* \} */
  86993. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  86994. * \ingroup flac_metadata
  86995. *
  86996. * \brief
  86997. * The level 1 interface provides read-write access to FLAC file metadata and
  86998. * operates directly on the FLAC file.
  86999. *
  87000. * The general usage of this interface is:
  87001. *
  87002. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87003. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87004. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87005. * see if the file is writable, or only read access is allowed.
  87006. * - Use FLAC__metadata_simple_iterator_next() and
  87007. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87008. * This is does not read the actual blocks themselves.
  87009. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87010. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87011. * forward from the front of the file.
  87012. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87013. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87014. * the current iterator position. The returned object is yours to modify
  87015. * and free.
  87016. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87017. * back. You must have write permission to the original file. Make sure to
  87018. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87019. * below.
  87020. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87021. * Use the object creation functions from
  87022. * \link flac_metadata_object here \endlink to generate new objects.
  87023. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87024. * currently referred to by the iterator, or replace it with padding.
  87025. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87026. * finished.
  87027. *
  87028. * \note
  87029. * The FLAC file remains open the whole time between
  87030. * FLAC__metadata_simple_iterator_init() and
  87031. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87032. * the file during this time.
  87033. *
  87034. * \note
  87035. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87036. * FLAC__StreamMetadata objects. These are managed automatically.
  87037. *
  87038. * \note
  87039. * If any of the modification functions
  87040. * (FLAC__metadata_simple_iterator_set_block(),
  87041. * FLAC__metadata_simple_iterator_delete_block(),
  87042. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87043. * you should delete the iterator as it may no longer be valid.
  87044. *
  87045. * \{
  87046. */
  87047. struct FLAC__Metadata_SimpleIterator;
  87048. /** The opaque structure definition for the level 1 iterator type.
  87049. * See the
  87050. * \link flac_metadata_level1 metadata level 1 module \endlink
  87051. * for a detailed description.
  87052. */
  87053. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87054. /** Status type for FLAC__Metadata_SimpleIterator.
  87055. *
  87056. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87057. */
  87058. typedef enum {
  87059. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87060. /**< The iterator is in the normal OK state */
  87061. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87062. /**< The data passed into a function violated the function's usage criteria */
  87063. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87064. /**< The iterator could not open the target file */
  87065. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87066. /**< The iterator could not find the FLAC signature at the start of the file */
  87067. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87068. /**< The iterator tried to write to a file that was not writable */
  87069. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87070. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87071. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87072. /**< The iterator encountered an error while reading the FLAC file */
  87073. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87074. /**< The iterator encountered an error while seeking in the FLAC file */
  87075. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87076. /**< The iterator encountered an error while writing the FLAC file */
  87077. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87078. /**< The iterator encountered an error renaming the FLAC file */
  87079. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87080. /**< The iterator encountered an error removing the temporary file */
  87081. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87082. /**< Memory allocation failed */
  87083. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87084. /**< The caller violated an assertion or an unexpected error occurred */
  87085. } FLAC__Metadata_SimpleIteratorStatus;
  87086. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87087. *
  87088. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87089. * will give the string equivalent. The contents should not be modified.
  87090. */
  87091. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87092. /** Create a new iterator instance.
  87093. *
  87094. * \retval FLAC__Metadata_SimpleIterator*
  87095. * \c NULL if there was an error allocating memory, else the new instance.
  87096. */
  87097. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87098. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87099. *
  87100. * \param iterator A pointer to an existing iterator.
  87101. * \assert
  87102. * \code iterator != NULL \endcode
  87103. */
  87104. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87105. /** Get the current status of the iterator. Call this after a function
  87106. * returns \c false to get the reason for the error. Also resets the status
  87107. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87108. *
  87109. * \param iterator A pointer to an existing iterator.
  87110. * \assert
  87111. * \code iterator != NULL \endcode
  87112. * \retval FLAC__Metadata_SimpleIteratorStatus
  87113. * The current status of the iterator.
  87114. */
  87115. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87116. /** Initialize the iterator to point to the first metadata block in the
  87117. * given FLAC file.
  87118. *
  87119. * \param iterator A pointer to an existing iterator.
  87120. * \param filename The path to the FLAC file.
  87121. * \param read_only If \c true, the FLAC file will be opened
  87122. * in read-only mode; if \c false, the FLAC
  87123. * file will be opened for edit even if no
  87124. * edits are performed.
  87125. * \param preserve_file_stats If \c true, the owner and modification
  87126. * time will be preserved even if the FLAC
  87127. * file is written to.
  87128. * \assert
  87129. * \code iterator != NULL \endcode
  87130. * \code filename != NULL \endcode
  87131. * \retval FLAC__bool
  87132. * \c false if a memory allocation error occurs, the file can't be
  87133. * opened, or another error occurs, else \c true.
  87134. */
  87135. 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);
  87136. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87137. * FLAC__metadata_simple_iterator_set_block() and
  87138. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87139. *
  87140. * \param iterator A pointer to an existing iterator.
  87141. * \assert
  87142. * \code iterator != NULL \endcode
  87143. * \retval FLAC__bool
  87144. * See above.
  87145. */
  87146. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87147. /** Moves the iterator forward one metadata block, returning \c false if
  87148. * already at the end.
  87149. *
  87150. * \param iterator A pointer to an existing initialized iterator.
  87151. * \assert
  87152. * \code iterator != NULL \endcode
  87153. * \a iterator has been successfully initialized with
  87154. * FLAC__metadata_simple_iterator_init()
  87155. * \retval FLAC__bool
  87156. * \c false if already at the last metadata block of the chain, else
  87157. * \c true.
  87158. */
  87159. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87160. /** Moves the iterator backward one metadata block, returning \c false if
  87161. * already at the beginning.
  87162. *
  87163. * \param iterator A pointer to an existing initialized iterator.
  87164. * \assert
  87165. * \code iterator != NULL \endcode
  87166. * \a iterator has been successfully initialized with
  87167. * FLAC__metadata_simple_iterator_init()
  87168. * \retval FLAC__bool
  87169. * \c false if already at the first metadata block of the chain, else
  87170. * \c true.
  87171. */
  87172. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87173. /** Returns a flag telling if the current metadata block is the last.
  87174. *
  87175. * \param iterator A pointer to an existing initialized iterator.
  87176. * \assert
  87177. * \code iterator != NULL \endcode
  87178. * \a iterator has been successfully initialized with
  87179. * FLAC__metadata_simple_iterator_init()
  87180. * \retval FLAC__bool
  87181. * \c true if the current metadata block is the last in the file,
  87182. * else \c false.
  87183. */
  87184. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87185. /** Get the offset of the metadata block at the current position. This
  87186. * avoids reading the actual block data which can save time for large
  87187. * blocks.
  87188. *
  87189. * \param iterator A pointer to an existing initialized iterator.
  87190. * \assert
  87191. * \code iterator != NULL \endcode
  87192. * \a iterator has been successfully initialized with
  87193. * FLAC__metadata_simple_iterator_init()
  87194. * \retval off_t
  87195. * The offset of the metadata block at the current iterator position.
  87196. * This is the byte offset relative to the beginning of the file of
  87197. * the current metadata block's header.
  87198. */
  87199. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87200. /** Get the type of the metadata block at the current position. This
  87201. * avoids reading the actual block data which can save time for large
  87202. * blocks.
  87203. *
  87204. * \param iterator A pointer to an existing initialized iterator.
  87205. * \assert
  87206. * \code iterator != NULL \endcode
  87207. * \a iterator has been successfully initialized with
  87208. * FLAC__metadata_simple_iterator_init()
  87209. * \retval FLAC__MetadataType
  87210. * The type of the metadata block at the current iterator position.
  87211. */
  87212. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87213. /** Get the length of the metadata block at the current position. This
  87214. * avoids reading the actual block data which can save time for large
  87215. * blocks.
  87216. *
  87217. * \param iterator A pointer to an existing initialized iterator.
  87218. * \assert
  87219. * \code iterator != NULL \endcode
  87220. * \a iterator has been successfully initialized with
  87221. * FLAC__metadata_simple_iterator_init()
  87222. * \retval unsigned
  87223. * The length of the metadata block at the current iterator position.
  87224. * The is same length as that in the
  87225. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87226. * i.e. the length of the metadata body that follows the header.
  87227. */
  87228. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87229. /** Get the application ID of the \c APPLICATION block at the current
  87230. * position. This avoids reading the actual block data which can save
  87231. * time for large blocks.
  87232. *
  87233. * \param iterator A pointer to an existing initialized iterator.
  87234. * \param id A pointer to a buffer of at least \c 4 bytes where
  87235. * the ID will be stored.
  87236. * \assert
  87237. * \code iterator != NULL \endcode
  87238. * \code id != NULL \endcode
  87239. * \a iterator has been successfully initialized with
  87240. * FLAC__metadata_simple_iterator_init()
  87241. * \retval FLAC__bool
  87242. * \c true if the ID was successfully read, else \c false, in which
  87243. * case you should check FLAC__metadata_simple_iterator_status() to
  87244. * find out why. If the status is
  87245. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  87246. * current metadata block is not an \c APPLICATION block. Otherwise
  87247. * if the status is
  87248. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  87249. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  87250. * occurred and the iterator can no longer be used.
  87251. */
  87252. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  87253. /** Get the metadata block at the current position. You can modify the
  87254. * block but must use FLAC__metadata_simple_iterator_set_block() to
  87255. * write it back to the FLAC file.
  87256. *
  87257. * You must call FLAC__metadata_object_delete() on the returned object
  87258. * when you are finished with it.
  87259. *
  87260. * \param iterator A pointer to an existing initialized iterator.
  87261. * \assert
  87262. * \code iterator != NULL \endcode
  87263. * \a iterator has been successfully initialized with
  87264. * FLAC__metadata_simple_iterator_init()
  87265. * \retval FLAC__StreamMetadata*
  87266. * The current metadata block, or \c NULL if there was a memory
  87267. * allocation error.
  87268. */
  87269. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  87270. /** Write a block back to the FLAC file. This function tries to be
  87271. * as efficient as possible; how the block is actually written is
  87272. * shown by the following:
  87273. *
  87274. * Existing block is a STREAMINFO block and the new block is a
  87275. * STREAMINFO block: the new block is written in place. Make sure
  87276. * you know what you're doing when changing the values of a
  87277. * STREAMINFO block.
  87278. *
  87279. * Existing block is a STREAMINFO block and the new block is a
  87280. * not a STREAMINFO block: this is an error since the first block
  87281. * must be a STREAMINFO block. Returns \c false without altering the
  87282. * file.
  87283. *
  87284. * Existing block is not a STREAMINFO block and the new block is a
  87285. * STREAMINFO block: this is an error since there may be only one
  87286. * STREAMINFO block. Returns \c false without altering the file.
  87287. *
  87288. * Existing block and new block are the same length: the existing
  87289. * block will be replaced by the new block, written in place.
  87290. *
  87291. * Existing block is longer than new block: if use_padding is \c true,
  87292. * the existing block will be overwritten in place with the new
  87293. * block followed by a PADDING block, if possible, to make the total
  87294. * size the same as the existing block. Remember that a padding
  87295. * block requires at least four bytes so if the difference in size
  87296. * between the new block and existing block is less than that, the
  87297. * entire file will have to be rewritten, using the new block's
  87298. * exact size. If use_padding is \c false, the entire file will be
  87299. * rewritten, replacing the existing block by the new block.
  87300. *
  87301. * Existing block is shorter than new block: if use_padding is \c true,
  87302. * the function will try and expand the new block into the following
  87303. * PADDING block, if it exists and doing so won't shrink the PADDING
  87304. * block to less than 4 bytes. If there is no following PADDING
  87305. * block, or it will shrink to less than 4 bytes, or use_padding is
  87306. * \c false, the entire file is rewritten, replacing the existing block
  87307. * with the new block. Note that in this case any following PADDING
  87308. * block is preserved as is.
  87309. *
  87310. * After writing the block, the iterator will remain in the same
  87311. * place, i.e. pointing to the new block.
  87312. *
  87313. * \param iterator A pointer to an existing initialized iterator.
  87314. * \param block The block to set.
  87315. * \param use_padding See above.
  87316. * \assert
  87317. * \code iterator != NULL \endcode
  87318. * \a iterator has been successfully initialized with
  87319. * FLAC__metadata_simple_iterator_init()
  87320. * \code block != NULL \endcode
  87321. * \retval FLAC__bool
  87322. * \c true if successful, else \c false.
  87323. */
  87324. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87325. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87326. * except that instead of writing over an existing block, it appends
  87327. * a block after the existing block. \a use_padding is again used to
  87328. * tell the function to try an expand into following padding in an
  87329. * attempt to avoid rewriting the entire file.
  87330. *
  87331. * This function will fail and return \c false if given a STREAMINFO
  87332. * block.
  87333. *
  87334. * After writing the block, the iterator will be pointing to the
  87335. * new block.
  87336. *
  87337. * \param iterator A pointer to an existing initialized iterator.
  87338. * \param block The block to set.
  87339. * \param use_padding See above.
  87340. * \assert
  87341. * \code iterator != NULL \endcode
  87342. * \a iterator has been successfully initialized with
  87343. * FLAC__metadata_simple_iterator_init()
  87344. * \code block != NULL \endcode
  87345. * \retval FLAC__bool
  87346. * \c true if successful, else \c false.
  87347. */
  87348. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87349. /** Deletes the block at the current position. This will cause the
  87350. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87351. * in which case the block will be replaced by an equal-sized PADDING
  87352. * block. The iterator will be left pointing to the block before the
  87353. * one just deleted.
  87354. *
  87355. * You may not delete the STREAMINFO block.
  87356. *
  87357. * \param iterator A pointer to an existing initialized iterator.
  87358. * \param use_padding See above.
  87359. * \assert
  87360. * \code iterator != NULL \endcode
  87361. * \a iterator has been successfully initialized with
  87362. * FLAC__metadata_simple_iterator_init()
  87363. * \retval FLAC__bool
  87364. * \c true if successful, else \c false.
  87365. */
  87366. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  87367. /* \} */
  87368. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  87369. * \ingroup flac_metadata
  87370. *
  87371. * \brief
  87372. * The level 2 interface provides read-write access to FLAC file metadata;
  87373. * all metadata is read into memory, operated on in memory, and then written
  87374. * to file, which is more efficient than level 1 when editing multiple blocks.
  87375. *
  87376. * Currently Ogg FLAC is supported for read only, via
  87377. * FLAC__metadata_chain_read_ogg() but a subsequent
  87378. * FLAC__metadata_chain_write() will fail.
  87379. *
  87380. * The general usage of this interface is:
  87381. *
  87382. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  87383. * linked list of FLAC metadata blocks.
  87384. * - Read all metadata into the the chain from a FLAC file using
  87385. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  87386. * check the status.
  87387. * - Optionally, consolidate the padding using
  87388. * FLAC__metadata_chain_merge_padding() or
  87389. * FLAC__metadata_chain_sort_padding().
  87390. * - Create a new iterator using FLAC__metadata_iterator_new()
  87391. * - Initialize the iterator to point to the first element in the chain
  87392. * using FLAC__metadata_iterator_init()
  87393. * - Traverse the chain using FLAC__metadata_iterator_next and
  87394. * FLAC__metadata_iterator_prev().
  87395. * - Get a block for reading or modification using
  87396. * FLAC__metadata_iterator_get_block(). The pointer to the object
  87397. * inside the chain is returned, so the block is yours to modify.
  87398. * Changes will be reflected in the FLAC file when you write the
  87399. * chain. You can also add and delete blocks (see functions below).
  87400. * - When done, write out the chain using FLAC__metadata_chain_write().
  87401. * Make sure to read the whole comment to the function below.
  87402. * - Delete the chain using FLAC__metadata_chain_delete().
  87403. *
  87404. * \note
  87405. * Even though the FLAC file is not open while the chain is being
  87406. * manipulated, you must not alter the file externally during
  87407. * this time. The chain assumes the FLAC file will not change
  87408. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  87409. * and FLAC__metadata_chain_write().
  87410. *
  87411. * \note
  87412. * Do not modify the is_last, length, or type fields of returned
  87413. * FLAC__StreamMetadata objects. These are managed automatically.
  87414. *
  87415. * \note
  87416. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  87417. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  87418. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  87419. * become owned by the chain and they will be deleted when the chain is
  87420. * deleted.
  87421. *
  87422. * \{
  87423. */
  87424. struct FLAC__Metadata_Chain;
  87425. /** The opaque structure definition for the level 2 chain type.
  87426. */
  87427. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  87428. struct FLAC__Metadata_Iterator;
  87429. /** The opaque structure definition for the level 2 iterator type.
  87430. */
  87431. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  87432. typedef enum {
  87433. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  87434. /**< The chain is in the normal OK state */
  87435. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  87436. /**< The data passed into a function violated the function's usage criteria */
  87437. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  87438. /**< The chain could not open the target file */
  87439. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  87440. /**< The chain could not find the FLAC signature at the start of the file */
  87441. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  87442. /**< The chain tried to write to a file that was not writable */
  87443. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  87444. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  87445. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  87446. /**< The chain encountered an error while reading the FLAC file */
  87447. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  87448. /**< The chain encountered an error while seeking in the FLAC file */
  87449. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  87450. /**< The chain encountered an error while writing the FLAC file */
  87451. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  87452. /**< The chain encountered an error renaming the FLAC file */
  87453. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  87454. /**< The chain encountered an error removing the temporary file */
  87455. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  87456. /**< Memory allocation failed */
  87457. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  87458. /**< The caller violated an assertion or an unexpected error occurred */
  87459. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  87460. /**< One or more of the required callbacks was NULL */
  87461. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  87462. /**< FLAC__metadata_chain_write() was called on a chain read by
  87463. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87464. * or
  87465. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  87466. * was called on a chain read by
  87467. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87468. * Matching read/write methods must always be used. */
  87469. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  87470. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  87471. * chain write requires a tempfile; use
  87472. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  87473. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  87474. * called when the chain write does not require a tempfile; use
  87475. * FLAC__metadata_chain_write_with_callbacks() instead.
  87476. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  87477. * before writing via callbacks. */
  87478. } FLAC__Metadata_ChainStatus;
  87479. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  87480. *
  87481. * Using a FLAC__Metadata_ChainStatus as the index to this array
  87482. * will give the string equivalent. The contents should not be modified.
  87483. */
  87484. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  87485. /*********** FLAC__Metadata_Chain ***********/
  87486. /** Create a new chain instance.
  87487. *
  87488. * \retval FLAC__Metadata_Chain*
  87489. * \c NULL if there was an error allocating memory, else the new instance.
  87490. */
  87491. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  87492. /** Free a chain instance. Deletes the object pointed to by \a chain.
  87493. *
  87494. * \param chain A pointer to an existing chain.
  87495. * \assert
  87496. * \code chain != NULL \endcode
  87497. */
  87498. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  87499. /** Get the current status of the chain. Call this after a function
  87500. * returns \c false to get the reason for the error. Also resets the
  87501. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  87502. *
  87503. * \param chain A pointer to an existing chain.
  87504. * \assert
  87505. * \code chain != NULL \endcode
  87506. * \retval FLAC__Metadata_ChainStatus
  87507. * The current status of the chain.
  87508. */
  87509. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  87510. /** Read all metadata from a FLAC file into the chain.
  87511. *
  87512. * \param chain A pointer to an existing chain.
  87513. * \param filename The path to the FLAC file to read.
  87514. * \assert
  87515. * \code chain != NULL \endcode
  87516. * \code filename != NULL \endcode
  87517. * \retval FLAC__bool
  87518. * \c true if a valid list of metadata blocks was read from
  87519. * \a filename, else \c false. On failure, check the status with
  87520. * FLAC__metadata_chain_status().
  87521. */
  87522. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  87523. /** Read all metadata from an Ogg FLAC file into the chain.
  87524. *
  87525. * \note Ogg FLAC metadata data writing is not supported yet and
  87526. * FLAC__metadata_chain_write() will fail.
  87527. *
  87528. * \param chain A pointer to an existing chain.
  87529. * \param filename The path to the Ogg FLAC file to read.
  87530. * \assert
  87531. * \code chain != NULL \endcode
  87532. * \code filename != NULL \endcode
  87533. * \retval FLAC__bool
  87534. * \c true if a valid list of metadata blocks was read from
  87535. * \a filename, else \c false. On failure, check the status with
  87536. * FLAC__metadata_chain_status().
  87537. */
  87538. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  87539. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  87540. *
  87541. * The \a handle need only be open for reading, but must be seekable.
  87542. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87543. * for Windows).
  87544. *
  87545. * \param chain A pointer to an existing chain.
  87546. * \param handle The I/O handle of the FLAC stream to read. The
  87547. * handle will NOT be closed after the metadata is read;
  87548. * that is the duty of the caller.
  87549. * \param callbacks
  87550. * A set of callbacks to use for I/O. The mandatory
  87551. * callbacks are \a read, \a seek, and \a tell.
  87552. * \assert
  87553. * \code chain != NULL \endcode
  87554. * \retval FLAC__bool
  87555. * \c true if a valid list of metadata blocks was read from
  87556. * \a handle, else \c false. On failure, check the status with
  87557. * FLAC__metadata_chain_status().
  87558. */
  87559. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87560. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  87561. *
  87562. * The \a handle need only be open for reading, but must be seekable.
  87563. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87564. * for Windows).
  87565. *
  87566. * \note Ogg FLAC metadata data writing is not supported yet and
  87567. * FLAC__metadata_chain_write() will fail.
  87568. *
  87569. * \param chain A pointer to an existing chain.
  87570. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  87571. * handle will NOT be closed after the metadata is read;
  87572. * that is the duty of the caller.
  87573. * \param callbacks
  87574. * A set of callbacks to use for I/O. The mandatory
  87575. * callbacks are \a read, \a seek, and \a tell.
  87576. * \assert
  87577. * \code chain != NULL \endcode
  87578. * \retval FLAC__bool
  87579. * \c true if a valid list of metadata blocks was read from
  87580. * \a handle, else \c false. On failure, check the status with
  87581. * FLAC__metadata_chain_status().
  87582. */
  87583. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87584. /** Checks if writing the given chain would require the use of a
  87585. * temporary file, or if it could be written in place.
  87586. *
  87587. * Under certain conditions, padding can be utilized so that writing
  87588. * edited metadata back to the FLAC file does not require rewriting the
  87589. * entire file. If rewriting is required, then a temporary workfile is
  87590. * required. When writing metadata using callbacks, you must check
  87591. * this function to know whether to call
  87592. * FLAC__metadata_chain_write_with_callbacks() or
  87593. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  87594. * writing with FLAC__metadata_chain_write(), the temporary file is
  87595. * handled internally.
  87596. *
  87597. * \param chain A pointer to an existing chain.
  87598. * \param use_padding
  87599. * Whether or not padding will be allowed to be used
  87600. * during the write. The value of \a use_padding given
  87601. * here must match the value later passed to
  87602. * FLAC__metadata_chain_write_with_callbacks() or
  87603. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  87604. * \assert
  87605. * \code chain != NULL \endcode
  87606. * \retval FLAC__bool
  87607. * \c true if writing the current chain would require a tempfile, or
  87608. * \c false if metadata can be written in place.
  87609. */
  87610. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  87611. /** Write all metadata out to the FLAC file. This function tries to be as
  87612. * efficient as possible; how the metadata is actually written is shown by
  87613. * the following:
  87614. *
  87615. * If the current chain is the same size as the existing metadata, the new
  87616. * data is written in place.
  87617. *
  87618. * If the current chain is longer than the existing metadata, and
  87619. * \a use_padding is \c true, and the last block is a PADDING block of
  87620. * sufficient length, the function will truncate the final padding block
  87621. * so that the overall size of the metadata is the same as the existing
  87622. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  87623. * the above conditions are met, the entire FLAC file must be rewritten.
  87624. * If you want to use padding this way it is a good idea to call
  87625. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  87626. * amount of padding to work with, unless you need to preserve ordering
  87627. * of the PADDING blocks for some reason.
  87628. *
  87629. * If the current chain is shorter than the existing metadata, and
  87630. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  87631. * is extended to make the overall size the same as the existing data. If
  87632. * \a use_padding is \c true and the last block is not a PADDING block, a new
  87633. * PADDING block is added to the end of the new data to make it the same
  87634. * size as the existing data (if possible, see the note to
  87635. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  87636. * and the new data is written in place. If none of the above apply or
  87637. * \a use_padding is \c false, the entire FLAC file is rewritten.
  87638. *
  87639. * If \a preserve_file_stats is \c true, the owner and modification time will
  87640. * be preserved even if the FLAC file is written.
  87641. *
  87642. * For this write function to be used, the chain must have been read with
  87643. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  87644. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  87645. *
  87646. * \param chain A pointer to an existing chain.
  87647. * \param use_padding See above.
  87648. * \param preserve_file_stats See above.
  87649. * \assert
  87650. * \code chain != NULL \endcode
  87651. * \retval FLAC__bool
  87652. * \c true if the write succeeded, else \c false. On failure,
  87653. * check the status with FLAC__metadata_chain_status().
  87654. */
  87655. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  87656. /** Write all metadata out to a FLAC stream via callbacks.
  87657. *
  87658. * (See FLAC__metadata_chain_write() for the details on how padding is
  87659. * used to write metadata in place if possible.)
  87660. *
  87661. * The \a handle must be open for updating and be seekable. The
  87662. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  87663. * for Windows).
  87664. *
  87665. * For this write function to be used, the chain must have been read with
  87666. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87667. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87668. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87669. * \c false.
  87670. *
  87671. * \param chain A pointer to an existing chain.
  87672. * \param use_padding See FLAC__metadata_chain_write()
  87673. * \param handle The I/O handle of the FLAC stream to write. The
  87674. * handle will NOT be closed after the metadata is
  87675. * written; that is the duty of the caller.
  87676. * \param callbacks A set of callbacks to use for I/O. The mandatory
  87677. * callbacks are \a write and \a seek.
  87678. * \assert
  87679. * \code chain != NULL \endcode
  87680. * \retval FLAC__bool
  87681. * \c true if the write succeeded, else \c false. On failure,
  87682. * check the status with FLAC__metadata_chain_status().
  87683. */
  87684. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87685. /** Write all metadata out to a FLAC stream via callbacks.
  87686. *
  87687. * (See FLAC__metadata_chain_write() for the details on how padding is
  87688. * used to write metadata in place if possible.)
  87689. *
  87690. * This version of the write-with-callbacks function must be used when
  87691. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  87692. * this function, you must supply an I/O handle corresponding to the
  87693. * FLAC file to edit, and a temporary handle to which the new FLAC
  87694. * file will be written. It is the caller's job to move this temporary
  87695. * FLAC file on top of the original FLAC file to complete the metadata
  87696. * edit.
  87697. *
  87698. * The \a handle must be open for reading and be seekable. The
  87699. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87700. * for Windows).
  87701. *
  87702. * The \a temp_handle must be open for writing. The
  87703. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  87704. * for Windows). It should be an empty stream, or at least positioned
  87705. * at the start-of-file (in which case it is the caller's duty to
  87706. * truncate it on return).
  87707. *
  87708. * For this write function to be used, the chain must have been read with
  87709. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87710. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87711. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87712. * \c true.
  87713. *
  87714. * \param chain A pointer to an existing chain.
  87715. * \param use_padding See FLAC__metadata_chain_write()
  87716. * \param handle The I/O handle of the original FLAC stream to read.
  87717. * The handle will NOT be closed after the metadata is
  87718. * written; that is the duty of the caller.
  87719. * \param callbacks A set of callbacks to use for I/O on \a handle.
  87720. * The mandatory callbacks are \a read, \a seek, and
  87721. * \a eof.
  87722. * \param temp_handle The I/O handle of the FLAC stream to write. The
  87723. * handle will NOT be closed after the metadata is
  87724. * written; that is the duty of the caller.
  87725. * \param temp_callbacks
  87726. * A set of callbacks to use for I/O on temp_handle.
  87727. * The only mandatory callback is \a write.
  87728. * \assert
  87729. * \code chain != NULL \endcode
  87730. * \retval FLAC__bool
  87731. * \c true if the write succeeded, else \c false. On failure,
  87732. * check the status with FLAC__metadata_chain_status().
  87733. */
  87734. 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);
  87735. /** Merge adjacent PADDING blocks into a single block.
  87736. *
  87737. * \note This function does not write to the FLAC file, it only
  87738. * modifies the chain.
  87739. *
  87740. * \warning Any iterator on the current chain will become invalid after this
  87741. * call. You should delete the iterator and get a new one.
  87742. *
  87743. * \param chain A pointer to an existing chain.
  87744. * \assert
  87745. * \code chain != NULL \endcode
  87746. */
  87747. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  87748. /** This function will move all PADDING blocks to the end on the metadata,
  87749. * then merge them into a single block.
  87750. *
  87751. * \note This function does not write to the FLAC file, it only
  87752. * modifies the chain.
  87753. *
  87754. * \warning Any iterator on the current chain will become invalid after this
  87755. * call. You should delete the iterator and get a new one.
  87756. *
  87757. * \param chain A pointer to an existing chain.
  87758. * \assert
  87759. * \code chain != NULL \endcode
  87760. */
  87761. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  87762. /*********** FLAC__Metadata_Iterator ***********/
  87763. /** Create a new iterator instance.
  87764. *
  87765. * \retval FLAC__Metadata_Iterator*
  87766. * \c NULL if there was an error allocating memory, else the new instance.
  87767. */
  87768. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  87769. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87770. *
  87771. * \param iterator A pointer to an existing iterator.
  87772. * \assert
  87773. * \code iterator != NULL \endcode
  87774. */
  87775. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  87776. /** Initialize the iterator to point to the first metadata block in the
  87777. * given chain.
  87778. *
  87779. * \param iterator A pointer to an existing iterator.
  87780. * \param chain A pointer to an existing and initialized (read) chain.
  87781. * \assert
  87782. * \code iterator != NULL \endcode
  87783. * \code chain != NULL \endcode
  87784. */
  87785. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  87786. /** Moves the iterator forward one metadata block, returning \c false if
  87787. * already at the end.
  87788. *
  87789. * \param iterator A pointer to an existing initialized iterator.
  87790. * \assert
  87791. * \code iterator != NULL \endcode
  87792. * \a iterator has been successfully initialized with
  87793. * FLAC__metadata_iterator_init()
  87794. * \retval FLAC__bool
  87795. * \c false if already at the last metadata block of the chain, else
  87796. * \c true.
  87797. */
  87798. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  87799. /** Moves the iterator backward one metadata block, returning \c false if
  87800. * already at the beginning.
  87801. *
  87802. * \param iterator A pointer to an existing initialized iterator.
  87803. * \assert
  87804. * \code iterator != NULL \endcode
  87805. * \a iterator has been successfully initialized with
  87806. * FLAC__metadata_iterator_init()
  87807. * \retval FLAC__bool
  87808. * \c false if already at the first metadata block of the chain, else
  87809. * \c true.
  87810. */
  87811. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  87812. /** Get the type of the metadata block at the current position.
  87813. *
  87814. * \param iterator A pointer to an existing initialized iterator.
  87815. * \assert
  87816. * \code iterator != NULL \endcode
  87817. * \a iterator has been successfully initialized with
  87818. * FLAC__metadata_iterator_init()
  87819. * \retval FLAC__MetadataType
  87820. * The type of the metadata block at the current iterator position.
  87821. */
  87822. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  87823. /** Get the metadata block at the current position. You can modify
  87824. * the block in place but must write the chain before the changes
  87825. * are reflected to the FLAC file. You do not need to call
  87826. * FLAC__metadata_iterator_set_block() to reflect the changes;
  87827. * the pointer returned by FLAC__metadata_iterator_get_block()
  87828. * points directly into the chain.
  87829. *
  87830. * \warning
  87831. * Do not call FLAC__metadata_object_delete() on the returned object;
  87832. * to delete a block use FLAC__metadata_iterator_delete_block().
  87833. *
  87834. * \param iterator A pointer to an existing initialized iterator.
  87835. * \assert
  87836. * \code iterator != NULL \endcode
  87837. * \a iterator has been successfully initialized with
  87838. * FLAC__metadata_iterator_init()
  87839. * \retval FLAC__StreamMetadata*
  87840. * The current metadata block.
  87841. */
  87842. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  87843. /** Set the metadata block at the current position, replacing the existing
  87844. * block. The new block passed in becomes owned by the chain and it will be
  87845. * deleted when the chain is deleted.
  87846. *
  87847. * \param iterator A pointer to an existing initialized iterator.
  87848. * \param block A pointer to a metadata block.
  87849. * \assert
  87850. * \code iterator != NULL \endcode
  87851. * \a iterator has been successfully initialized with
  87852. * FLAC__metadata_iterator_init()
  87853. * \code block != NULL \endcode
  87854. * \retval FLAC__bool
  87855. * \c false if the conditions in the above description are not met, or
  87856. * a memory allocation error occurs, otherwise \c true.
  87857. */
  87858. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87859. /** Removes the current block from the chain. If \a replace_with_padding is
  87860. * \c true, the block will instead be replaced with a padding block of equal
  87861. * size. You can not delete the STREAMINFO block. The iterator will be
  87862. * left pointing to the block before the one just "deleted", even if
  87863. * \a replace_with_padding is \c true.
  87864. *
  87865. * \param iterator A pointer to an existing initialized iterator.
  87866. * \param replace_with_padding See above.
  87867. * \assert
  87868. * \code iterator != NULL \endcode
  87869. * \a iterator has been successfully initialized with
  87870. * FLAC__metadata_iterator_init()
  87871. * \retval FLAC__bool
  87872. * \c false if the conditions in the above description are not met,
  87873. * otherwise \c true.
  87874. */
  87875. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  87876. /** Insert a new block before the current block. You cannot insert a block
  87877. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  87878. * as there can be only one, the one that already exists at the head when you
  87879. * read in a chain. The chain takes ownership of the new block and it will be
  87880. * deleted when the chain is deleted. The iterator will be left pointing to
  87881. * the new block.
  87882. *
  87883. * \param iterator A pointer to an existing initialized iterator.
  87884. * \param block A pointer to a metadata block to insert.
  87885. * \assert
  87886. * \code iterator != NULL \endcode
  87887. * \a iterator has been successfully initialized with
  87888. * FLAC__metadata_iterator_init()
  87889. * \retval FLAC__bool
  87890. * \c false if the conditions in the above description are not met, or
  87891. * a memory allocation error occurs, otherwise \c true.
  87892. */
  87893. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87894. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  87895. * block as there can be only one, the one that already exists at the head when
  87896. * you read in a chain. The chain takes ownership of the new block and it will
  87897. * be deleted when the chain is deleted. The iterator will be left pointing to
  87898. * the new block.
  87899. *
  87900. * \param iterator A pointer to an existing initialized iterator.
  87901. * \param block A pointer to a metadata block to insert.
  87902. * \assert
  87903. * \code iterator != NULL \endcode
  87904. * \a iterator has been successfully initialized with
  87905. * FLAC__metadata_iterator_init()
  87906. * \retval FLAC__bool
  87907. * \c false if the conditions in the above description are not met, or
  87908. * a memory allocation error occurs, otherwise \c true.
  87909. */
  87910. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87911. /* \} */
  87912. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  87913. * \ingroup flac_metadata
  87914. *
  87915. * \brief
  87916. * This module contains methods for manipulating FLAC metadata objects.
  87917. *
  87918. * Since many are variable length we have to be careful about the memory
  87919. * management. We decree that all pointers to data in the object are
  87920. * owned by the object and memory-managed by the object.
  87921. *
  87922. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  87923. * functions to create all instances. When using the
  87924. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  87925. * \a copy to \c true to have the function make it's own copy of the data, or
  87926. * to \c false to give the object ownership of your data. In the latter case
  87927. * your pointer must be freeable by free() and will be free()d when the object
  87928. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  87929. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  87930. * the length argument is 0 and the \a copy argument is \c false.
  87931. *
  87932. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  87933. * will return \c NULL in the case of a memory allocation error, otherwise a new
  87934. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  87935. * case of a memory allocation error.
  87936. *
  87937. * We don't have the convenience of C++ here, so note that the library relies
  87938. * on you to keep the types straight. In other words, if you pass, for
  87939. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  87940. * FLAC__metadata_object_application_set_data(), you will get an assertion
  87941. * failure.
  87942. *
  87943. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  87944. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  87945. * toward the length or stored in the stream, but it can make working with plain
  87946. * comments (those that don't contain embedded-NULs in the value) easier.
  87947. * Entries passed into these functions have trailing NULs added if missing, and
  87948. * returned entries are guaranteed to have a trailing NUL.
  87949. *
  87950. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  87951. * comment entry/name/value will first validate that it complies with the Vorbis
  87952. * comment specification and return false if it does not.
  87953. *
  87954. * There is no need to recalculate the length field on metadata blocks you
  87955. * have modified. They will be calculated automatically before they are
  87956. * written back to a file.
  87957. *
  87958. * \{
  87959. */
  87960. /** Create a new metadata object instance of the given type.
  87961. *
  87962. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  87963. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  87964. * the vendor string set (but zero comments).
  87965. *
  87966. * Do not pass in a value greater than or equal to
  87967. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  87968. * doing.
  87969. *
  87970. * \param type Type of object to create
  87971. * \retval FLAC__StreamMetadata*
  87972. * \c NULL if there was an error allocating memory or the type code is
  87973. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  87974. */
  87975. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  87976. /** Create a copy of an existing metadata object.
  87977. *
  87978. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  87979. * object is also copied. The caller takes ownership of the new block and
  87980. * is responsible for freeing it with FLAC__metadata_object_delete().
  87981. *
  87982. * \param object Pointer to object to copy.
  87983. * \assert
  87984. * \code object != NULL \endcode
  87985. * \retval FLAC__StreamMetadata*
  87986. * \c NULL if there was an error allocating memory, else the new instance.
  87987. */
  87988. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  87989. /** Free a metadata object. Deletes the object pointed to by \a object.
  87990. *
  87991. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  87992. * object is also deleted.
  87993. *
  87994. * \param object A pointer to an existing object.
  87995. * \assert
  87996. * \code object != NULL \endcode
  87997. */
  87998. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  87999. /** Compares two metadata objects.
  88000. *
  88001. * The compare is "deep", i.e. dynamically allocated data within the
  88002. * object is also compared.
  88003. *
  88004. * \param block1 A pointer to an existing object.
  88005. * \param block2 A pointer to an existing object.
  88006. * \assert
  88007. * \code block1 != NULL \endcode
  88008. * \code block2 != NULL \endcode
  88009. * \retval FLAC__bool
  88010. * \c true if objects are identical, else \c false.
  88011. */
  88012. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88013. /** Sets the application data of an APPLICATION block.
  88014. *
  88015. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88016. * takes ownership of the pointer. The existing data will be freed if this
  88017. * function is successful, otherwise the original data will remain if \a copy
  88018. * is \c true and malloc() fails.
  88019. *
  88020. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88021. *
  88022. * \param object A pointer to an existing APPLICATION object.
  88023. * \param data A pointer to the data to set.
  88024. * \param length The length of \a data in bytes.
  88025. * \param copy See above.
  88026. * \assert
  88027. * \code object != NULL \endcode
  88028. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88029. * \code (data != NULL && length > 0) ||
  88030. * (data == NULL && length == 0 && copy == false) \endcode
  88031. * \retval FLAC__bool
  88032. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88033. */
  88034. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88035. /** Resize the seekpoint array.
  88036. *
  88037. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88038. * points will be added to the end.
  88039. *
  88040. * \param object A pointer to an existing SEEKTABLE object.
  88041. * \param new_num_points The desired length of the array; may be \c 0.
  88042. * \assert
  88043. * \code object != NULL \endcode
  88044. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88045. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88046. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88047. * \retval FLAC__bool
  88048. * \c false if memory allocation error, else \c true.
  88049. */
  88050. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88051. /** Set a seekpoint in a seektable.
  88052. *
  88053. * \param object A pointer to an existing SEEKTABLE object.
  88054. * \param point_num Index into seekpoint array to set.
  88055. * \param point The point to set.
  88056. * \assert
  88057. * \code object != NULL \endcode
  88058. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88059. * \code object->data.seek_table.num_points > point_num \endcode
  88060. */
  88061. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88062. /** Insert a seekpoint into a seektable.
  88063. *
  88064. * \param object A pointer to an existing SEEKTABLE object.
  88065. * \param point_num Index into seekpoint array to set.
  88066. * \param point The point to set.
  88067. * \assert
  88068. * \code object != NULL \endcode
  88069. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88070. * \code object->data.seek_table.num_points >= point_num \endcode
  88071. * \retval FLAC__bool
  88072. * \c false if memory allocation error, else \c true.
  88073. */
  88074. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88075. /** Delete a seekpoint from a seektable.
  88076. *
  88077. * \param object A pointer to an existing SEEKTABLE object.
  88078. * \param point_num Index into seekpoint array to set.
  88079. * \assert
  88080. * \code object != NULL \endcode
  88081. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88082. * \code object->data.seek_table.num_points > point_num \endcode
  88083. * \retval FLAC__bool
  88084. * \c false if memory allocation error, else \c true.
  88085. */
  88086. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88087. /** Check a seektable to see if it conforms to the FLAC specification.
  88088. * See the format specification for limits on the contents of the
  88089. * seektable.
  88090. *
  88091. * \param object A pointer to an existing SEEKTABLE object.
  88092. * \assert
  88093. * \code object != NULL \endcode
  88094. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88095. * \retval FLAC__bool
  88096. * \c false if seek table is illegal, else \c true.
  88097. */
  88098. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88099. /** Append a number of placeholder points to the end of a seek table.
  88100. *
  88101. * \note
  88102. * As with the other ..._seektable_template_... functions, you should
  88103. * call FLAC__metadata_object_seektable_template_sort() when finished
  88104. * to make the seek table legal.
  88105. *
  88106. * \param object A pointer to an existing SEEKTABLE object.
  88107. * \param num The number of placeholder points to append.
  88108. * \assert
  88109. * \code object != NULL \endcode
  88110. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88111. * \retval FLAC__bool
  88112. * \c false if memory allocation fails, else \c true.
  88113. */
  88114. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88115. /** Append a specific seek point template to the end of a seek table.
  88116. *
  88117. * \note
  88118. * As with the other ..._seektable_template_... functions, you should
  88119. * call FLAC__metadata_object_seektable_template_sort() when finished
  88120. * to make the seek table legal.
  88121. *
  88122. * \param object A pointer to an existing SEEKTABLE object.
  88123. * \param sample_number The sample number of the seek point template.
  88124. * \assert
  88125. * \code object != NULL \endcode
  88126. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88127. * \retval FLAC__bool
  88128. * \c false if memory allocation fails, else \c true.
  88129. */
  88130. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88131. /** Append specific seek point templates to the end of a seek table.
  88132. *
  88133. * \note
  88134. * As with the other ..._seektable_template_... functions, you should
  88135. * call FLAC__metadata_object_seektable_template_sort() when finished
  88136. * to make the seek table legal.
  88137. *
  88138. * \param object A pointer to an existing SEEKTABLE object.
  88139. * \param sample_numbers An array of sample numbers for the seek points.
  88140. * \param num The number of seek point templates to append.
  88141. * \assert
  88142. * \code object != NULL \endcode
  88143. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88144. * \retval FLAC__bool
  88145. * \c false if memory allocation fails, else \c true.
  88146. */
  88147. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88148. /** Append a set of evenly-spaced seek point templates to the end of a
  88149. * seek table.
  88150. *
  88151. * \note
  88152. * As with the other ..._seektable_template_... functions, you should
  88153. * call FLAC__metadata_object_seektable_template_sort() when finished
  88154. * to make the seek table legal.
  88155. *
  88156. * \param object A pointer to an existing SEEKTABLE object.
  88157. * \param num The number of placeholder points to append.
  88158. * \param total_samples The total number of samples to be encoded;
  88159. * the seekpoints will be spaced approximately
  88160. * \a total_samples / \a num samples apart.
  88161. * \assert
  88162. * \code object != NULL \endcode
  88163. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88164. * \code total_samples > 0 \endcode
  88165. * \retval FLAC__bool
  88166. * \c false if memory allocation fails, else \c true.
  88167. */
  88168. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88169. /** Append a set of evenly-spaced seek point templates to the end of a
  88170. * seek table.
  88171. *
  88172. * \note
  88173. * As with the other ..._seektable_template_... functions, you should
  88174. * call FLAC__metadata_object_seektable_template_sort() when finished
  88175. * to make the seek table legal.
  88176. *
  88177. * \param object A pointer to an existing SEEKTABLE object.
  88178. * \param samples The number of samples apart to space the placeholder
  88179. * points. The first point will be at sample \c 0, the
  88180. * second at sample \a samples, then 2*\a samples, and
  88181. * so on. As long as \a samples and \a total_samples
  88182. * are greater than \c 0, there will always be at least
  88183. * one seekpoint at sample \c 0.
  88184. * \param total_samples The total number of samples to be encoded;
  88185. * the seekpoints will be spaced
  88186. * \a samples samples apart.
  88187. * \assert
  88188. * \code object != NULL \endcode
  88189. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88190. * \code samples > 0 \endcode
  88191. * \code total_samples > 0 \endcode
  88192. * \retval FLAC__bool
  88193. * \c false if memory allocation fails, else \c true.
  88194. */
  88195. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88196. /** Sort a seek table's seek points according to the format specification,
  88197. * removing duplicates.
  88198. *
  88199. * \param object A pointer to a seek table to be sorted.
  88200. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88201. * If \c true, duplicates are deleted and the seek table is
  88202. * shrunk appropriately; the number of placeholder points
  88203. * present in the seek table will be the same after the call
  88204. * as before.
  88205. * \assert
  88206. * \code object != NULL \endcode
  88207. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88208. * \retval FLAC__bool
  88209. * \c false if realloc() fails, else \c true.
  88210. */
  88211. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88212. /** Sets the vendor string in a VORBIS_COMMENT block.
  88213. *
  88214. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88215. * one already.
  88216. *
  88217. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88218. * takes ownership of the \c entry.entry pointer.
  88219. *
  88220. * \note If this function returns \c false, the caller still owns the
  88221. * pointer.
  88222. *
  88223. * \param object A pointer to an existing VORBIS_COMMENT object.
  88224. * \param entry The entry to set the vendor string to.
  88225. * \param copy See above.
  88226. * \assert
  88227. * \code object != NULL \endcode
  88228. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88229. * \code (entry.entry != NULL && entry.length > 0) ||
  88230. * (entry.entry == NULL && entry.length == 0) \endcode
  88231. * \retval FLAC__bool
  88232. * \c false if memory allocation fails or \a entry does not comply with the
  88233. * Vorbis comment specification, else \c true.
  88234. */
  88235. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88236. /** Resize the comment array.
  88237. *
  88238. * If the size shrinks, elements will truncated; if it grows, new empty
  88239. * fields will be added to the end.
  88240. *
  88241. * \param object A pointer to an existing VORBIS_COMMENT object.
  88242. * \param new_num_comments The desired length of the array; may be \c 0.
  88243. * \assert
  88244. * \code object != NULL \endcode
  88245. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88246. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  88247. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  88248. * \retval FLAC__bool
  88249. * \c false if memory allocation fails, else \c true.
  88250. */
  88251. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  88252. /** Sets a comment in a VORBIS_COMMENT block.
  88253. *
  88254. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88255. * one already.
  88256. *
  88257. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88258. * takes ownership of the \c entry.entry pointer.
  88259. *
  88260. * \note If this function returns \c false, the caller still owns the
  88261. * pointer.
  88262. *
  88263. * \param object A pointer to an existing VORBIS_COMMENT object.
  88264. * \param comment_num Index into comment array to set.
  88265. * \param entry The entry to set the comment to.
  88266. * \param copy See above.
  88267. * \assert
  88268. * \code object != NULL \endcode
  88269. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88270. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  88271. * \code (entry.entry != NULL && entry.length > 0) ||
  88272. * (entry.entry == NULL && entry.length == 0) \endcode
  88273. * \retval FLAC__bool
  88274. * \c false if memory allocation fails or \a entry does not comply with the
  88275. * Vorbis comment specification, else \c true.
  88276. */
  88277. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88278. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  88279. *
  88280. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88281. * one already.
  88282. *
  88283. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88284. * takes ownership of the \c entry.entry pointer.
  88285. *
  88286. * \note If this function returns \c false, the caller still owns the
  88287. * pointer.
  88288. *
  88289. * \param object A pointer to an existing VORBIS_COMMENT object.
  88290. * \param comment_num The index at which to insert the comment. The comments
  88291. * at and after \a comment_num move right one position.
  88292. * To append a comment to the end, set \a comment_num to
  88293. * \c object->data.vorbis_comment.num_comments .
  88294. * \param entry The comment to insert.
  88295. * \param copy See above.
  88296. * \assert
  88297. * \code object != NULL \endcode
  88298. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88299. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  88300. * \code (entry.entry != NULL && entry.length > 0) ||
  88301. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88302. * \retval FLAC__bool
  88303. * \c false if memory allocation fails or \a entry does not comply with the
  88304. * Vorbis comment specification, else \c true.
  88305. */
  88306. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88307. /** Appends a comment to a VORBIS_COMMENT block.
  88308. *
  88309. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88310. * one already.
  88311. *
  88312. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88313. * takes ownership of the \c entry.entry pointer.
  88314. *
  88315. * \note If this function returns \c false, the caller still owns the
  88316. * pointer.
  88317. *
  88318. * \param object A pointer to an existing VORBIS_COMMENT object.
  88319. * \param entry The comment to insert.
  88320. * \param copy See above.
  88321. * \assert
  88322. * \code object != NULL \endcode
  88323. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88324. * \code (entry.entry != NULL && entry.length > 0) ||
  88325. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88326. * \retval FLAC__bool
  88327. * \c false if memory allocation fails or \a entry does not comply with the
  88328. * Vorbis comment specification, else \c true.
  88329. */
  88330. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88331. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88332. *
  88333. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88334. * one already.
  88335. *
  88336. * Depending on the the value of \a all, either all or just the first comment
  88337. * whose field name(s) match the given entry's name will be replaced by the
  88338. * given entry. If no comments match, \a entry will simply be appended.
  88339. *
  88340. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88341. * takes ownership of the \c entry.entry pointer.
  88342. *
  88343. * \note If this function returns \c false, the caller still owns the
  88344. * pointer.
  88345. *
  88346. * \param object A pointer to an existing VORBIS_COMMENT object.
  88347. * \param entry The comment to insert.
  88348. * \param all If \c true, all comments whose field name matches
  88349. * \a entry's field name will be removed, and \a entry will
  88350. * be inserted at the position of the first matching
  88351. * comment. If \c false, only the first comment whose
  88352. * field name matches \a entry's field name will be
  88353. * replaced with \a entry.
  88354. * \param copy See above.
  88355. * \assert
  88356. * \code object != NULL \endcode
  88357. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88358. * \code (entry.entry != NULL && entry.length > 0) ||
  88359. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88360. * \retval FLAC__bool
  88361. * \c false if memory allocation fails or \a entry does not comply with the
  88362. * Vorbis comment specification, else \c true.
  88363. */
  88364. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  88365. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  88366. *
  88367. * \param object A pointer to an existing VORBIS_COMMENT object.
  88368. * \param comment_num The index of the comment to delete.
  88369. * \assert
  88370. * \code object != NULL \endcode
  88371. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88372. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  88373. * \retval FLAC__bool
  88374. * \c false if realloc() fails, else \c true.
  88375. */
  88376. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  88377. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  88378. *
  88379. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  88380. * memory and shall be owned by the caller. For convenience the entry will
  88381. * have a terminating NUL.
  88382. *
  88383. * \param entry A pointer to a Vorbis comment entry. The entry's
  88384. * \c entry pointer should not point to allocated
  88385. * memory as it will be overwritten.
  88386. * \param field_name The field name in ASCII, \c NUL terminated.
  88387. * \param field_value The field value in UTF-8, \c NUL terminated.
  88388. * \assert
  88389. * \code entry != NULL \endcode
  88390. * \code field_name != NULL \endcode
  88391. * \code field_value != NULL \endcode
  88392. * \retval FLAC__bool
  88393. * \c false if malloc() fails, or if \a field_name or \a field_value does
  88394. * not comply with the Vorbis comment specification, else \c true.
  88395. */
  88396. 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);
  88397. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  88398. *
  88399. * The returned pointers to name and value will be allocated by malloc()
  88400. * and shall be owned by the caller.
  88401. *
  88402. * \param entry An existing Vorbis comment entry.
  88403. * \param field_name The address of where the returned pointer to the
  88404. * field name will be stored.
  88405. * \param field_value The address of where the returned pointer to the
  88406. * field value will be stored.
  88407. * \assert
  88408. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88409. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  88410. * \code field_name != NULL \endcode
  88411. * \code field_value != NULL \endcode
  88412. * \retval FLAC__bool
  88413. * \c false if memory allocation fails or \a entry does not comply with the
  88414. * Vorbis comment specification, else \c true.
  88415. */
  88416. 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);
  88417. /** Check if the given Vorbis comment entry's field name matches the given
  88418. * field name.
  88419. *
  88420. * \param entry An existing Vorbis comment entry.
  88421. * \param field_name The field name to check.
  88422. * \param field_name_length The length of \a field_name, not including the
  88423. * terminating \c NUL.
  88424. * \assert
  88425. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88426. * \retval FLAC__bool
  88427. * \c true if the field names match, else \c false
  88428. */
  88429. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  88430. /** Find a Vorbis comment with the given field name.
  88431. *
  88432. * The search begins at entry number \a offset; use an offset of 0 to
  88433. * search from the beginning of the comment array.
  88434. *
  88435. * \param object A pointer to an existing VORBIS_COMMENT object.
  88436. * \param offset The offset into the comment array from where to start
  88437. * the search.
  88438. * \param field_name The field name of the comment to find.
  88439. * \assert
  88440. * \code object != NULL \endcode
  88441. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88442. * \code field_name != NULL \endcode
  88443. * \retval int
  88444. * The offset in the comment array of the first comment whose field
  88445. * name matches \a field_name, or \c -1 if no match was found.
  88446. */
  88447. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  88448. /** Remove first Vorbis comment matching the given field name.
  88449. *
  88450. * \param object A pointer to an existing VORBIS_COMMENT object.
  88451. * \param field_name The field name of comment to delete.
  88452. * \assert
  88453. * \code object != NULL \endcode
  88454. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88455. * \retval int
  88456. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88457. * \c 1 for one matching entry deleted.
  88458. */
  88459. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  88460. /** Remove all Vorbis comments matching the given field name.
  88461. *
  88462. * \param object A pointer to an existing VORBIS_COMMENT object.
  88463. * \param field_name The field name of comments to delete.
  88464. * \assert
  88465. * \code object != NULL \endcode
  88466. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88467. * \retval int
  88468. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88469. * else the number of matching entries deleted.
  88470. */
  88471. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  88472. /** Create a new CUESHEET track instance.
  88473. *
  88474. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  88475. *
  88476. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88477. * \c NULL if there was an error allocating memory, else the new instance.
  88478. */
  88479. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  88480. /** Create a copy of an existing CUESHEET track object.
  88481. *
  88482. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88483. * object is also copied. The caller takes ownership of the new object and
  88484. * is responsible for freeing it with
  88485. * FLAC__metadata_object_cuesheet_track_delete().
  88486. *
  88487. * \param object Pointer to object to copy.
  88488. * \assert
  88489. * \code object != NULL \endcode
  88490. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88491. * \c NULL if there was an error allocating memory, else the new instance.
  88492. */
  88493. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  88494. /** Delete a CUESHEET track object
  88495. *
  88496. * \param object A pointer to an existing CUESHEET track object.
  88497. * \assert
  88498. * \code object != NULL \endcode
  88499. */
  88500. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  88501. /** Resize a track's index point array.
  88502. *
  88503. * If the size shrinks, elements will truncated; if it grows, new blank
  88504. * indices will be added to the end.
  88505. *
  88506. * \param object A pointer to an existing CUESHEET object.
  88507. * \param track_num The index of the track to modify. NOTE: this is not
  88508. * necessarily the same as the track's \a number field.
  88509. * \param new_num_indices The desired length of the array; may be \c 0.
  88510. * \assert
  88511. * \code object != NULL \endcode
  88512. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88513. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88514. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  88515. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  88516. * \retval FLAC__bool
  88517. * \c false if memory allocation error, else \c true.
  88518. */
  88519. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  88520. /** Insert an index point in a CUESHEET track at the given index.
  88521. *
  88522. * \param object A pointer to an existing CUESHEET object.
  88523. * \param track_num The index of the track to modify. NOTE: this is not
  88524. * necessarily the same as the track's \a number field.
  88525. * \param index_num The index into the track's index array at which to
  88526. * insert the index point. NOTE: this is not necessarily
  88527. * the same as the index point's \a number field. The
  88528. * indices at and after \a index_num move right one
  88529. * position. To append an index point to the end, set
  88530. * \a index_num to
  88531. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88532. * \param index The index point to insert.
  88533. * \assert
  88534. * \code object != NULL \endcode
  88535. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88536. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88537. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88538. * \retval FLAC__bool
  88539. * \c false if realloc() fails, else \c true.
  88540. */
  88541. 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);
  88542. /** Insert a blank index point in a CUESHEET track at the given index.
  88543. *
  88544. * A blank index point is one in which all field values are zero.
  88545. *
  88546. * \param object A pointer to an existing CUESHEET object.
  88547. * \param track_num The index of the track to modify. NOTE: this is not
  88548. * necessarily the same as the track's \a number field.
  88549. * \param index_num The index into the track's index array at which to
  88550. * insert the index point. NOTE: this is not necessarily
  88551. * the same as the index point's \a number field. The
  88552. * indices at and after \a index_num move right one
  88553. * position. To append an index point to the end, set
  88554. * \a index_num to
  88555. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88556. * \assert
  88557. * \code object != NULL \endcode
  88558. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88559. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88560. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88561. * \retval FLAC__bool
  88562. * \c false if realloc() fails, else \c true.
  88563. */
  88564. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88565. /** Delete an index point in a CUESHEET track at the given index.
  88566. *
  88567. * \param object A pointer to an existing CUESHEET object.
  88568. * \param track_num The index into the track array of the track to
  88569. * modify. NOTE: this is not necessarily the same
  88570. * as the track's \a number field.
  88571. * \param index_num The index into the track's index array of the index
  88572. * to delete. NOTE: this is not necessarily the same
  88573. * as the index's \a number field.
  88574. * \assert
  88575. * \code object != NULL \endcode
  88576. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88577. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88578. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  88579. * \retval FLAC__bool
  88580. * \c false if realloc() fails, else \c true.
  88581. */
  88582. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88583. /** Resize the track array.
  88584. *
  88585. * If the size shrinks, elements will truncated; if it grows, new blank
  88586. * tracks will be added to the end.
  88587. *
  88588. * \param object A pointer to an existing CUESHEET object.
  88589. * \param new_num_tracks The desired length of the array; may be \c 0.
  88590. * \assert
  88591. * \code object != NULL \endcode
  88592. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88593. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  88594. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  88595. * \retval FLAC__bool
  88596. * \c false if memory allocation error, else \c true.
  88597. */
  88598. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  88599. /** Sets a track in a CUESHEET block.
  88600. *
  88601. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88602. * takes ownership of the \a track pointer.
  88603. *
  88604. * \param object A pointer to an existing CUESHEET object.
  88605. * \param track_num Index into track array to set. NOTE: this is not
  88606. * necessarily the same as the track's \a number field.
  88607. * \param track The track to set the track to. You may safely pass in
  88608. * a const pointer if \a copy is \c true.
  88609. * \param copy See above.
  88610. * \assert
  88611. * \code object != NULL \endcode
  88612. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88613. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  88614. * \code (track->indices != NULL && track->num_indices > 0) ||
  88615. * (track->indices == NULL && track->num_indices == 0)
  88616. * \retval FLAC__bool
  88617. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88618. */
  88619. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88620. /** Insert a track in a CUESHEET block at the given index.
  88621. *
  88622. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88623. * takes ownership of the \a track pointer.
  88624. *
  88625. * \param object A pointer to an existing CUESHEET object.
  88626. * \param track_num The index at which to insert the track. NOTE: this
  88627. * is not necessarily the same as the track's \a number
  88628. * field. The tracks at and after \a track_num move right
  88629. * one position. To append a track to the end, set
  88630. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88631. * \param track The track to insert. You may safely pass in a const
  88632. * pointer if \a copy is \c true.
  88633. * \param copy See above.
  88634. * \assert
  88635. * \code object != NULL \endcode
  88636. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88637. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88638. * \retval FLAC__bool
  88639. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88640. */
  88641. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88642. /** Insert a blank track in a CUESHEET block at the given index.
  88643. *
  88644. * A blank track is one in which all field values are zero.
  88645. *
  88646. * \param object A pointer to an existing CUESHEET object.
  88647. * \param track_num The index at which to insert the track. NOTE: this
  88648. * is not necessarily the same as the track's \a number
  88649. * field. The tracks at and after \a track_num move right
  88650. * one position. To append a track to the end, set
  88651. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88652. * \assert
  88653. * \code object != NULL \endcode
  88654. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88655. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88656. * \retval FLAC__bool
  88657. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88658. */
  88659. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  88660. /** Delete a track in a CUESHEET block at the given index.
  88661. *
  88662. * \param object A pointer to an existing CUESHEET object.
  88663. * \param track_num The index into the track array of the track to
  88664. * delete. NOTE: this is not necessarily the same
  88665. * as the track's \a number field.
  88666. * \assert
  88667. * \code object != NULL \endcode
  88668. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88669. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88670. * \retval FLAC__bool
  88671. * \c false if realloc() fails, else \c true.
  88672. */
  88673. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  88674. /** Check a cue sheet to see if it conforms to the FLAC specification.
  88675. * See the format specification for limits on the contents of the
  88676. * cue sheet.
  88677. *
  88678. * \param object A pointer to an existing CUESHEET object.
  88679. * \param check_cd_da_subset If \c true, check CUESHEET against more
  88680. * stringent requirements for a CD-DA (audio) disc.
  88681. * \param violation Address of a pointer to a string. If there is a
  88682. * violation, a pointer to a string explanation of the
  88683. * violation will be returned here. \a violation may be
  88684. * \c NULL if you don't need the returned string. Do not
  88685. * free the returned string; it will always point to static
  88686. * data.
  88687. * \assert
  88688. * \code object != NULL \endcode
  88689. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88690. * \retval FLAC__bool
  88691. * \c false if cue sheet is illegal, else \c true.
  88692. */
  88693. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  88694. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  88695. * assumes the cue sheet corresponds to a CD; the result is undefined
  88696. * if the cuesheet's is_cd bit is not set.
  88697. *
  88698. * \param object A pointer to an existing CUESHEET object.
  88699. * \assert
  88700. * \code object != NULL \endcode
  88701. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88702. * \retval FLAC__uint32
  88703. * The unsigned integer representation of the CDDB/freedb ID
  88704. */
  88705. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  88706. /** Sets the MIME type of a PICTURE block.
  88707. *
  88708. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88709. * takes ownership of the pointer. The existing string will be freed if this
  88710. * function is successful, otherwise the original string will remain if \a copy
  88711. * is \c true and malloc() fails.
  88712. *
  88713. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  88714. *
  88715. * \param object A pointer to an existing PICTURE object.
  88716. * \param mime_type A pointer to the MIME type string. The string must be
  88717. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  88718. * is done.
  88719. * \param copy See above.
  88720. * \assert
  88721. * \code object != NULL \endcode
  88722. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88723. * \code (mime_type != NULL) \endcode
  88724. * \retval FLAC__bool
  88725. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88726. */
  88727. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  88728. /** Sets the description of a PICTURE block.
  88729. *
  88730. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88731. * takes ownership of the pointer. The existing string will be freed if this
  88732. * function is successful, otherwise the original string will remain if \a copy
  88733. * is \c true and malloc() fails.
  88734. *
  88735. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  88736. *
  88737. * \param object A pointer to an existing PICTURE object.
  88738. * \param description A pointer to the description string. The string must be
  88739. * valid UTF-8, NUL-terminated. No validation is done.
  88740. * \param copy See above.
  88741. * \assert
  88742. * \code object != NULL \endcode
  88743. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88744. * \code (description != NULL) \endcode
  88745. * \retval FLAC__bool
  88746. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88747. */
  88748. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  88749. /** Sets the picture data of a PICTURE block.
  88750. *
  88751. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88752. * takes ownership of the pointer. Also sets the \a data_length field of the
  88753. * metadata object to what is passed in as the \a length parameter. The
  88754. * existing data will be freed if this function is successful, otherwise the
  88755. * original data and data_length will remain if \a copy is \c true and
  88756. * malloc() fails.
  88757. *
  88758. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88759. *
  88760. * \param object A pointer to an existing PICTURE object.
  88761. * \param data A pointer to the data to set.
  88762. * \param length The length of \a data in bytes.
  88763. * \param copy See above.
  88764. * \assert
  88765. * \code object != NULL \endcode
  88766. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88767. * \code (data != NULL && length > 0) ||
  88768. * (data == NULL && length == 0 && copy == false) \endcode
  88769. * \retval FLAC__bool
  88770. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88771. */
  88772. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  88773. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  88774. * See the format specification for limits on the contents of the
  88775. * PICTURE block.
  88776. *
  88777. * \param object A pointer to existing PICTURE block to be checked.
  88778. * \param violation Address of a pointer to a string. If there is a
  88779. * violation, a pointer to a string explanation of the
  88780. * violation will be returned here. \a violation may be
  88781. * \c NULL if you don't need the returned string. Do not
  88782. * free the returned string; it will always point to static
  88783. * data.
  88784. * \assert
  88785. * \code object != NULL \endcode
  88786. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88787. * \retval FLAC__bool
  88788. * \c false if PICTURE block is illegal, else \c true.
  88789. */
  88790. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  88791. /* \} */
  88792. #ifdef __cplusplus
  88793. }
  88794. #endif
  88795. #endif
  88796. /*** End of inlined file: metadata.h ***/
  88797. /*** Start of inlined file: stream_decoder.h ***/
  88798. #ifndef FLAC__STREAM_DECODER_H
  88799. #define FLAC__STREAM_DECODER_H
  88800. #include <stdio.h> /* for FILE */
  88801. #ifdef __cplusplus
  88802. extern "C" {
  88803. #endif
  88804. /** \file include/FLAC/stream_decoder.h
  88805. *
  88806. * \brief
  88807. * This module contains the functions which implement the stream
  88808. * decoder.
  88809. *
  88810. * See the detailed documentation in the
  88811. * \link flac_stream_decoder stream decoder \endlink module.
  88812. */
  88813. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  88814. * \ingroup flac
  88815. *
  88816. * \brief
  88817. * This module describes the decoder layers provided by libFLAC.
  88818. *
  88819. * The stream decoder can be used to decode complete streams either from
  88820. * the client via callbacks, or directly from a file, depending on how
  88821. * it is initialized. When decoding via callbacks, the client provides
  88822. * callbacks for reading FLAC data and writing decoded samples, and
  88823. * handling metadata and errors. If the client also supplies seek-related
  88824. * callback, the decoder function for sample-accurate seeking within the
  88825. * FLAC input is also available. When decoding from a file, the client
  88826. * needs only supply a filename or open \c FILE* and write/metadata/error
  88827. * callbacks; the rest of the callbacks are supplied internally. For more
  88828. * info see the \link flac_stream_decoder stream decoder \endlink module.
  88829. */
  88830. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  88831. * \ingroup flac_decoder
  88832. *
  88833. * \brief
  88834. * This module contains the functions which implement the stream
  88835. * decoder.
  88836. *
  88837. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  88838. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  88839. *
  88840. * The basic usage of this decoder is as follows:
  88841. * - The program creates an instance of a decoder using
  88842. * FLAC__stream_decoder_new().
  88843. * - The program overrides the default settings using
  88844. * FLAC__stream_decoder_set_*() functions.
  88845. * - The program initializes the instance to validate the settings and
  88846. * prepare for decoding using
  88847. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  88848. * or FLAC__stream_decoder_init_file() for native FLAC,
  88849. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  88850. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  88851. * - The program calls the FLAC__stream_decoder_process_*() functions
  88852. * to decode data, which subsequently calls the callbacks.
  88853. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  88854. * which flushes the input and output and resets the decoder to the
  88855. * uninitialized state.
  88856. * - The instance may be used again or deleted with
  88857. * FLAC__stream_decoder_delete().
  88858. *
  88859. * In more detail, the program will create a new instance by calling
  88860. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  88861. * functions to override the default decoder options, and call
  88862. * one of the FLAC__stream_decoder_init_*() functions.
  88863. *
  88864. * There are three initialization functions for native FLAC, one for
  88865. * setting up the decoder to decode FLAC data from the client via
  88866. * callbacks, and two for decoding directly from a FLAC file.
  88867. *
  88868. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  88869. * You must also supply several callbacks for handling I/O. Some (like
  88870. * seeking) are optional, depending on the capabilities of the input.
  88871. *
  88872. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  88873. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  88874. * \c FILE* or filename and fewer callbacks; the decoder will handle
  88875. * the other callbacks internally.
  88876. *
  88877. * There are three similarly-named init functions for decoding from Ogg
  88878. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  88879. * library has been built with Ogg support.
  88880. *
  88881. * Once the decoder is initialized, your program will call one of several
  88882. * functions to start the decoding process:
  88883. *
  88884. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  88885. * most one metadata block or audio frame and return, calling either the
  88886. * metadata callback or write callback, respectively, once. If the decoder
  88887. * loses sync it will return with only the error callback being called.
  88888. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  88889. * to process the stream from the current location and stop upon reaching
  88890. * the first audio frame. The client will get one metadata, write, or error
  88891. * callback per metadata block, audio frame, or sync error, respectively.
  88892. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  88893. * to process the stream from the current location until the read callback
  88894. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  88895. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  88896. * write, or error callback per metadata block, audio frame, or sync error,
  88897. * respectively.
  88898. *
  88899. * When the decoder has finished decoding (normally or through an abort),
  88900. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  88901. * ensures the decoder is in the correct state and frees memory. Then the
  88902. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  88903. * again to decode another stream.
  88904. *
  88905. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  88906. * At any point after the stream decoder has been initialized, the client can
  88907. * call this function to seek to an exact sample within the stream.
  88908. * Subsequently, the first time the write callback is called it will be
  88909. * passed a (possibly partial) block starting at that sample.
  88910. *
  88911. * If the client cannot seek via the callback interface provided, but still
  88912. * has another way of seeking, it can flush the decoder using
  88913. * FLAC__stream_decoder_flush() and start feeding data from the new position
  88914. * through the read callback.
  88915. *
  88916. * The stream decoder also provides MD5 signature checking. If this is
  88917. * turned on before initialization, FLAC__stream_decoder_finish() will
  88918. * report when the decoded MD5 signature does not match the one stored
  88919. * in the STREAMINFO block. MD5 checking is automatically turned off
  88920. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  88921. * in the STREAMINFO block or when a seek is attempted.
  88922. *
  88923. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  88924. * attention. By default, the decoder only calls the metadata_callback for
  88925. * the STREAMINFO block. These functions allow you to tell the decoder
  88926. * explicitly which blocks to parse and return via the metadata_callback
  88927. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  88928. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  88929. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  88930. * which blocks to return. Remember that metadata blocks can potentially
  88931. * be big (for example, cover art) so filtering out the ones you don't
  88932. * use can reduce the memory requirements of the decoder. Also note the
  88933. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  88934. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  88935. * filtering APPLICATION blocks based on the application ID.
  88936. *
  88937. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  88938. * they still can legally be filtered from the metadata_callback.
  88939. *
  88940. * \note
  88941. * The "set" functions may only be called when the decoder is in the
  88942. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  88943. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  88944. * before FLAC__stream_decoder_init_*(). If this is the case they will
  88945. * return \c true, otherwise \c false.
  88946. *
  88947. * \note
  88948. * FLAC__stream_decoder_finish() resets all settings to the constructor
  88949. * defaults, including the callbacks.
  88950. *
  88951. * \{
  88952. */
  88953. /** State values for a FLAC__StreamDecoder
  88954. *
  88955. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  88956. */
  88957. typedef enum {
  88958. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  88959. /**< The decoder is ready to search for metadata. */
  88960. FLAC__STREAM_DECODER_READ_METADATA,
  88961. /**< The decoder is ready to or is in the process of reading metadata. */
  88962. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  88963. /**< The decoder is ready to or is in the process of searching for the
  88964. * frame sync code.
  88965. */
  88966. FLAC__STREAM_DECODER_READ_FRAME,
  88967. /**< The decoder is ready to or is in the process of reading a frame. */
  88968. FLAC__STREAM_DECODER_END_OF_STREAM,
  88969. /**< The decoder has reached the end of the stream. */
  88970. FLAC__STREAM_DECODER_OGG_ERROR,
  88971. /**< An error occurred in the underlying Ogg layer. */
  88972. FLAC__STREAM_DECODER_SEEK_ERROR,
  88973. /**< An error occurred while seeking. The decoder must be flushed
  88974. * with FLAC__stream_decoder_flush() or reset with
  88975. * FLAC__stream_decoder_reset() before decoding can continue.
  88976. */
  88977. FLAC__STREAM_DECODER_ABORTED,
  88978. /**< The decoder was aborted by the read callback. */
  88979. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  88980. /**< An error occurred allocating memory. The decoder is in an invalid
  88981. * state and can no longer be used.
  88982. */
  88983. FLAC__STREAM_DECODER_UNINITIALIZED
  88984. /**< The decoder is in the uninitialized state; one of the
  88985. * FLAC__stream_decoder_init_*() functions must be called before samples
  88986. * can be processed.
  88987. */
  88988. } FLAC__StreamDecoderState;
  88989. /** Maps a FLAC__StreamDecoderState to a C string.
  88990. *
  88991. * Using a FLAC__StreamDecoderState as the index to this array
  88992. * will give the string equivalent. The contents should not be modified.
  88993. */
  88994. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  88995. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  88996. */
  88997. typedef enum {
  88998. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  88999. /**< Initialization was successful. */
  89000. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89001. /**< The library was not compiled with support for the given container
  89002. * format.
  89003. */
  89004. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89005. /**< A required callback was not supplied. */
  89006. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89007. /**< An error occurred allocating memory. */
  89008. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89009. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89010. * FLAC__stream_decoder_init_ogg_file(). */
  89011. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89012. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89013. * already initialized, usually because
  89014. * FLAC__stream_decoder_finish() was not called.
  89015. */
  89016. } FLAC__StreamDecoderInitStatus;
  89017. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89018. *
  89019. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89020. * will give the string equivalent. The contents should not be modified.
  89021. */
  89022. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89023. /** Return values for the FLAC__StreamDecoder read callback.
  89024. */
  89025. typedef enum {
  89026. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89027. /**< The read was OK and decoding can continue. */
  89028. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89029. /**< The read was attempted while at the end of the stream. Note that
  89030. * the client must only return this value when the read callback was
  89031. * called when already at the end of the stream. Otherwise, if the read
  89032. * itself moves to the end of the stream, the client should still return
  89033. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89034. * the next read callback it should return
  89035. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89036. * of \c 0.
  89037. */
  89038. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89039. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89040. } FLAC__StreamDecoderReadStatus;
  89041. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89042. *
  89043. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89044. * will give the string equivalent. The contents should not be modified.
  89045. */
  89046. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89047. /** Return values for the FLAC__StreamDecoder seek callback.
  89048. */
  89049. typedef enum {
  89050. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89051. /**< The seek was OK and decoding can continue. */
  89052. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89053. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89054. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89055. /**< Client does not support seeking. */
  89056. } FLAC__StreamDecoderSeekStatus;
  89057. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89058. *
  89059. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89060. * will give the string equivalent. The contents should not be modified.
  89061. */
  89062. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89063. /** Return values for the FLAC__StreamDecoder tell callback.
  89064. */
  89065. typedef enum {
  89066. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89067. /**< The tell was OK and decoding can continue. */
  89068. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89069. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89070. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89071. /**< Client does not support telling the position. */
  89072. } FLAC__StreamDecoderTellStatus;
  89073. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89074. *
  89075. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89076. * will give the string equivalent. The contents should not be modified.
  89077. */
  89078. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89079. /** Return values for the FLAC__StreamDecoder length callback.
  89080. */
  89081. typedef enum {
  89082. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89083. /**< The length call was OK and decoding can continue. */
  89084. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89085. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89086. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89087. /**< Client does not support reporting the length. */
  89088. } FLAC__StreamDecoderLengthStatus;
  89089. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89090. *
  89091. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89092. * will give the string equivalent. The contents should not be modified.
  89093. */
  89094. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89095. /** Return values for the FLAC__StreamDecoder write callback.
  89096. */
  89097. typedef enum {
  89098. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89099. /**< The write was OK and decoding can continue. */
  89100. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89101. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89102. } FLAC__StreamDecoderWriteStatus;
  89103. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89104. *
  89105. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89106. * will give the string equivalent. The contents should not be modified.
  89107. */
  89108. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89109. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89110. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89111. * all. The rest could be caused by bad sync (false synchronization on
  89112. * data that is not the start of a frame) or corrupted data. The error
  89113. * itself is the decoder's best guess at what happened assuming a correct
  89114. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89115. * could be caused by a correct sync on the start of a frame, but some
  89116. * data in the frame header was corrupted. Or it could be the result of
  89117. * syncing on a point the stream that looked like the starting of a frame
  89118. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89119. * could be because the decoder encountered a valid frame made by a future
  89120. * version of the encoder which it cannot parse, or because of a false
  89121. * sync making it appear as though an encountered frame was generated by
  89122. * a future encoder.
  89123. */
  89124. typedef enum {
  89125. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89126. /**< An error in the stream caused the decoder to lose synchronization. */
  89127. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89128. /**< The decoder encountered a corrupted frame header. */
  89129. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89130. /**< The frame's data did not match the CRC in the footer. */
  89131. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89132. /**< The decoder encountered reserved fields in use in the stream. */
  89133. } FLAC__StreamDecoderErrorStatus;
  89134. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89135. *
  89136. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89137. * will give the string equivalent. The contents should not be modified.
  89138. */
  89139. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89140. /***********************************************************************
  89141. *
  89142. * class FLAC__StreamDecoder
  89143. *
  89144. ***********************************************************************/
  89145. struct FLAC__StreamDecoderProtected;
  89146. struct FLAC__StreamDecoderPrivate;
  89147. /** The opaque structure definition for the stream decoder type.
  89148. * See the \link flac_stream_decoder stream decoder module \endlink
  89149. * for a detailed description.
  89150. */
  89151. typedef struct {
  89152. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89153. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89154. } FLAC__StreamDecoder;
  89155. /** Signature for the read callback.
  89156. *
  89157. * A function pointer matching this signature must be passed to
  89158. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89159. * called when the decoder needs more input data. The address of the
  89160. * buffer to be filled is supplied, along with the number of bytes the
  89161. * buffer can hold. The callback may choose to supply less data and
  89162. * modify the byte count but must be careful not to overflow the buffer.
  89163. * The callback then returns a status code chosen from
  89164. * FLAC__StreamDecoderReadStatus.
  89165. *
  89166. * Here is an example of a read callback for stdio streams:
  89167. * \code
  89168. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89169. * {
  89170. * FILE *file = ((MyClientData*)client_data)->file;
  89171. * if(*bytes > 0) {
  89172. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89173. * if(ferror(file))
  89174. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89175. * else if(*bytes == 0)
  89176. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89177. * else
  89178. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89179. * }
  89180. * else
  89181. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89182. * }
  89183. * \endcode
  89184. *
  89185. * \note In general, FLAC__StreamDecoder functions which change the
  89186. * state should not be called on the \a decoder while in the callback.
  89187. *
  89188. * \param decoder The decoder instance calling the callback.
  89189. * \param buffer A pointer to a location for the callee to store
  89190. * data to be decoded.
  89191. * \param bytes A pointer to the size of the buffer. On entry
  89192. * to the callback, it contains the maximum number
  89193. * of bytes that may be stored in \a buffer. The
  89194. * callee must set it to the actual number of bytes
  89195. * stored (0 in case of error or end-of-stream) before
  89196. * returning.
  89197. * \param client_data The callee's client data set through
  89198. * FLAC__stream_decoder_init_*().
  89199. * \retval FLAC__StreamDecoderReadStatus
  89200. * The callee's return status. Note that the callback should return
  89201. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89202. * zero bytes were read and there is no more data to be read.
  89203. */
  89204. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89205. /** Signature for the seek callback.
  89206. *
  89207. * A function pointer matching this signature may be passed to
  89208. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89209. * called when the decoder needs to seek the input stream. The decoder
  89210. * will pass the absolute byte offset to seek to, 0 meaning the
  89211. * beginning of the stream.
  89212. *
  89213. * Here is an example of a seek callback for stdio streams:
  89214. * \code
  89215. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89216. * {
  89217. * FILE *file = ((MyClientData*)client_data)->file;
  89218. * if(file == stdin)
  89219. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89220. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89221. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89222. * else
  89223. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89224. * }
  89225. * \endcode
  89226. *
  89227. * \note In general, FLAC__StreamDecoder functions which change the
  89228. * state should not be called on the \a decoder while in the callback.
  89229. *
  89230. * \param decoder The decoder instance calling the callback.
  89231. * \param absolute_byte_offset The offset from the beginning of the stream
  89232. * to seek to.
  89233. * \param client_data The callee's client data set through
  89234. * FLAC__stream_decoder_init_*().
  89235. * \retval FLAC__StreamDecoderSeekStatus
  89236. * The callee's return status.
  89237. */
  89238. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89239. /** Signature for the tell callback.
  89240. *
  89241. * A function pointer matching this signature may be passed to
  89242. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89243. * called when the decoder wants to know the current position of the
  89244. * stream. The callback should return the byte offset from the
  89245. * beginning of the stream.
  89246. *
  89247. * Here is an example of a tell callback for stdio streams:
  89248. * \code
  89249. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  89250. * {
  89251. * FILE *file = ((MyClientData*)client_data)->file;
  89252. * off_t pos;
  89253. * if(file == stdin)
  89254. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  89255. * else if((pos = ftello(file)) < 0)
  89256. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  89257. * else {
  89258. * *absolute_byte_offset = (FLAC__uint64)pos;
  89259. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  89260. * }
  89261. * }
  89262. * \endcode
  89263. *
  89264. * \note In general, FLAC__StreamDecoder functions which change the
  89265. * state should not be called on the \a decoder while in the callback.
  89266. *
  89267. * \param decoder The decoder instance calling the callback.
  89268. * \param absolute_byte_offset A pointer to storage for the current offset
  89269. * from the beginning of the stream.
  89270. * \param client_data The callee's client data set through
  89271. * FLAC__stream_decoder_init_*().
  89272. * \retval FLAC__StreamDecoderTellStatus
  89273. * The callee's return status.
  89274. */
  89275. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  89276. /** Signature for the length callback.
  89277. *
  89278. * A function pointer matching this signature may be passed to
  89279. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89280. * called when the decoder wants to know the total length of the stream
  89281. * in bytes.
  89282. *
  89283. * Here is an example of a length callback for stdio streams:
  89284. * \code
  89285. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  89286. * {
  89287. * FILE *file = ((MyClientData*)client_data)->file;
  89288. * struct stat filestats;
  89289. *
  89290. * if(file == stdin)
  89291. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  89292. * else if(fstat(fileno(file), &filestats) != 0)
  89293. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  89294. * else {
  89295. * *stream_length = (FLAC__uint64)filestats.st_size;
  89296. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  89297. * }
  89298. * }
  89299. * \endcode
  89300. *
  89301. * \note In general, FLAC__StreamDecoder functions which change the
  89302. * state should not be called on the \a decoder while in the callback.
  89303. *
  89304. * \param decoder The decoder instance calling the callback.
  89305. * \param stream_length A pointer to storage for the length of the stream
  89306. * in bytes.
  89307. * \param client_data The callee's client data set through
  89308. * FLAC__stream_decoder_init_*().
  89309. * \retval FLAC__StreamDecoderLengthStatus
  89310. * The callee's return status.
  89311. */
  89312. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89313. /** Signature for the EOF callback.
  89314. *
  89315. * A function pointer matching this signature may be passed to
  89316. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89317. * called when the decoder needs to know if the end of the stream has
  89318. * been reached.
  89319. *
  89320. * Here is an example of a EOF callback for stdio streams:
  89321. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89322. * \code
  89323. * {
  89324. * FILE *file = ((MyClientData*)client_data)->file;
  89325. * return feof(file)? true : false;
  89326. * }
  89327. * \endcode
  89328. *
  89329. * \note In general, FLAC__StreamDecoder functions which change the
  89330. * state should not be called on the \a decoder while in the callback.
  89331. *
  89332. * \param decoder The decoder instance calling the callback.
  89333. * \param client_data The callee's client data set through
  89334. * FLAC__stream_decoder_init_*().
  89335. * \retval FLAC__bool
  89336. * \c true if the currently at the end of the stream, else \c false.
  89337. */
  89338. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89339. /** Signature for the write callback.
  89340. *
  89341. * A function pointer matching this signature must be passed to one of
  89342. * the FLAC__stream_decoder_init_*() functions.
  89343. * The supplied function will be called when the decoder has decoded a
  89344. * single audio frame. The decoder will pass the frame metadata as well
  89345. * as an array of pointers (one for each channel) pointing to the
  89346. * decoded audio.
  89347. *
  89348. * \note In general, FLAC__StreamDecoder functions which change the
  89349. * state should not be called on the \a decoder while in the callback.
  89350. *
  89351. * \param decoder The decoder instance calling the callback.
  89352. * \param frame The description of the decoded frame. See
  89353. * FLAC__Frame.
  89354. * \param buffer An array of pointers to decoded channels of data.
  89355. * Each pointer will point to an array of signed
  89356. * samples of length \a frame->header.blocksize.
  89357. * Channels will be ordered according to the FLAC
  89358. * specification; see the documentation for the
  89359. * <A HREF="../format.html#frame_header">frame header</A>.
  89360. * \param client_data The callee's client data set through
  89361. * FLAC__stream_decoder_init_*().
  89362. * \retval FLAC__StreamDecoderWriteStatus
  89363. * The callee's return status.
  89364. */
  89365. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  89366. /** Signature for the metadata callback.
  89367. *
  89368. * A function pointer matching this signature must be passed to one of
  89369. * the FLAC__stream_decoder_init_*() functions.
  89370. * The supplied function will be called when the decoder has decoded a
  89371. * metadata block. In a valid FLAC file there will always be one
  89372. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  89373. * These will be supplied by the decoder in the same order as they
  89374. * appear in the stream and always before the first audio frame (i.e.
  89375. * write callback). The metadata block that is passed in must not be
  89376. * modified, and it doesn't live beyond the callback, so you should make
  89377. * a copy of it with FLAC__metadata_object_clone() if you will need it
  89378. * elsewhere. Since metadata blocks can potentially be large, by
  89379. * default the decoder only calls the metadata callback for the
  89380. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  89381. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  89382. *
  89383. * \note In general, FLAC__StreamDecoder functions which change the
  89384. * state should not be called on the \a decoder while in the callback.
  89385. *
  89386. * \param decoder The decoder instance calling the callback.
  89387. * \param metadata The decoded metadata block.
  89388. * \param client_data The callee's client data set through
  89389. * FLAC__stream_decoder_init_*().
  89390. */
  89391. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  89392. /** Signature for the error callback.
  89393. *
  89394. * A function pointer matching this signature must be passed to one of
  89395. * the FLAC__stream_decoder_init_*() functions.
  89396. * The supplied function will be called whenever an error occurs during
  89397. * decoding.
  89398. *
  89399. * \note In general, FLAC__StreamDecoder functions which change the
  89400. * state should not be called on the \a decoder while in the callback.
  89401. *
  89402. * \param decoder The decoder instance calling the callback.
  89403. * \param status The error encountered by the decoder.
  89404. * \param client_data The callee's client data set through
  89405. * FLAC__stream_decoder_init_*().
  89406. */
  89407. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  89408. /***********************************************************************
  89409. *
  89410. * Class constructor/destructor
  89411. *
  89412. ***********************************************************************/
  89413. /** Create a new stream decoder instance. The instance is created with
  89414. * default settings; see the individual FLAC__stream_decoder_set_*()
  89415. * functions for each setting's default.
  89416. *
  89417. * \retval FLAC__StreamDecoder*
  89418. * \c NULL if there was an error allocating memory, else the new instance.
  89419. */
  89420. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  89421. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  89422. *
  89423. * \param decoder A pointer to an existing decoder.
  89424. * \assert
  89425. * \code decoder != NULL \endcode
  89426. */
  89427. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  89428. /***********************************************************************
  89429. *
  89430. * Public class method prototypes
  89431. *
  89432. ***********************************************************************/
  89433. /** Set the serial number for the FLAC stream within the Ogg container.
  89434. * The default behavior is to use the serial number of the first Ogg
  89435. * page. Setting a serial number here will explicitly specify which
  89436. * stream is to be decoded.
  89437. *
  89438. * \note
  89439. * This does not need to be set for native FLAC decoding.
  89440. *
  89441. * \default \c use serial number of first page
  89442. * \param decoder A decoder instance to set.
  89443. * \param serial_number See above.
  89444. * \assert
  89445. * \code decoder != NULL \endcode
  89446. * \retval FLAC__bool
  89447. * \c false if the decoder is already initialized, else \c true.
  89448. */
  89449. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  89450. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  89451. * compute the MD5 signature of the unencoded audio data while decoding
  89452. * and compare it to the signature from the STREAMINFO block, if it
  89453. * exists, during FLAC__stream_decoder_finish().
  89454. *
  89455. * MD5 signature checking will be turned off (until the next
  89456. * FLAC__stream_decoder_reset()) if there is no signature in the
  89457. * STREAMINFO block or when a seek is attempted.
  89458. *
  89459. * Clients that do not use the MD5 check should leave this off to speed
  89460. * up decoding.
  89461. *
  89462. * \default \c false
  89463. * \param decoder A decoder instance to set.
  89464. * \param value Flag value (see above).
  89465. * \assert
  89466. * \code decoder != NULL \endcode
  89467. * \retval FLAC__bool
  89468. * \c false if the decoder is already initialized, else \c true.
  89469. */
  89470. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  89471. /** Direct the decoder to pass on all metadata blocks of type \a type.
  89472. *
  89473. * \default By default, only the \c STREAMINFO block is returned via the
  89474. * metadata callback.
  89475. * \param decoder A decoder instance to set.
  89476. * \param type See above.
  89477. * \assert
  89478. * \code decoder != NULL \endcode
  89479. * \a type is valid
  89480. * \retval FLAC__bool
  89481. * \c false if the decoder is already initialized, else \c true.
  89482. */
  89483. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89484. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  89485. * given \a id.
  89486. *
  89487. * \default By default, only the \c STREAMINFO block is returned via the
  89488. * metadata callback.
  89489. * \param decoder A decoder instance to set.
  89490. * \param id See above.
  89491. * \assert
  89492. * \code decoder != NULL \endcode
  89493. * \code id != NULL \endcode
  89494. * \retval FLAC__bool
  89495. * \c false if the decoder is already initialized, else \c true.
  89496. */
  89497. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89498. /** Direct the decoder to pass on all metadata blocks of any type.
  89499. *
  89500. * \default By default, only the \c STREAMINFO block is returned via the
  89501. * metadata callback.
  89502. * \param decoder A decoder instance to set.
  89503. * \assert
  89504. * \code decoder != NULL \endcode
  89505. * \retval FLAC__bool
  89506. * \c false if the decoder is already initialized, else \c true.
  89507. */
  89508. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  89509. /** Direct the decoder to filter out all metadata blocks of type \a type.
  89510. *
  89511. * \default By default, only the \c STREAMINFO block is returned via the
  89512. * metadata callback.
  89513. * \param decoder A decoder instance to set.
  89514. * \param type See above.
  89515. * \assert
  89516. * \code decoder != NULL \endcode
  89517. * \a type is valid
  89518. * \retval FLAC__bool
  89519. * \c false if the decoder is already initialized, else \c true.
  89520. */
  89521. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89522. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  89523. * the given \a id.
  89524. *
  89525. * \default By default, only the \c STREAMINFO block is returned via the
  89526. * metadata callback.
  89527. * \param decoder A decoder instance to set.
  89528. * \param id See above.
  89529. * \assert
  89530. * \code decoder != NULL \endcode
  89531. * \code id != NULL \endcode
  89532. * \retval FLAC__bool
  89533. * \c false if the decoder is already initialized, else \c true.
  89534. */
  89535. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89536. /** Direct the decoder to filter out all metadata blocks of any type.
  89537. *
  89538. * \default By default, only the \c STREAMINFO block is returned via the
  89539. * metadata callback.
  89540. * \param decoder A decoder instance to set.
  89541. * \assert
  89542. * \code decoder != NULL \endcode
  89543. * \retval FLAC__bool
  89544. * \c false if the decoder is already initialized, else \c true.
  89545. */
  89546. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  89547. /** Get the current decoder state.
  89548. *
  89549. * \param decoder A decoder instance to query.
  89550. * \assert
  89551. * \code decoder != NULL \endcode
  89552. * \retval FLAC__StreamDecoderState
  89553. * The current decoder state.
  89554. */
  89555. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  89556. /** Get the current decoder state as a C string.
  89557. *
  89558. * \param decoder A decoder instance to query.
  89559. * \assert
  89560. * \code decoder != NULL \endcode
  89561. * \retval const char *
  89562. * The decoder state as a C string. Do not modify the contents.
  89563. */
  89564. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  89565. /** Get the "MD5 signature checking" flag.
  89566. * This is the value of the setting, not whether or not the decoder is
  89567. * currently checking the MD5 (remember, it can be turned off automatically
  89568. * by a seek). When the decoder is reset the flag will be restored to the
  89569. * value returned by this function.
  89570. *
  89571. * \param decoder A decoder instance to query.
  89572. * \assert
  89573. * \code decoder != NULL \endcode
  89574. * \retval FLAC__bool
  89575. * See above.
  89576. */
  89577. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  89578. /** Get the total number of samples in the stream being decoded.
  89579. * Will only be valid after decoding has started and will contain the
  89580. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  89581. *
  89582. * \param decoder A decoder instance to query.
  89583. * \assert
  89584. * \code decoder != NULL \endcode
  89585. * \retval unsigned
  89586. * See above.
  89587. */
  89588. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  89589. /** Get the current number of channels in the stream being decoded.
  89590. * Will only be valid after decoding has started and will contain the
  89591. * value from the most recently decoded frame header.
  89592. *
  89593. * \param decoder A decoder instance to query.
  89594. * \assert
  89595. * \code decoder != NULL \endcode
  89596. * \retval unsigned
  89597. * See above.
  89598. */
  89599. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  89600. /** Get the current channel assignment in the stream being decoded.
  89601. * Will only be valid after decoding has started and will contain the
  89602. * value from the most recently decoded frame header.
  89603. *
  89604. * \param decoder A decoder instance to query.
  89605. * \assert
  89606. * \code decoder != NULL \endcode
  89607. * \retval FLAC__ChannelAssignment
  89608. * See above.
  89609. */
  89610. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  89611. /** Get the current sample resolution in the stream being decoded.
  89612. * Will only be valid after decoding has started and will contain the
  89613. * value from the most recently decoded frame header.
  89614. *
  89615. * \param decoder A decoder instance to query.
  89616. * \assert
  89617. * \code decoder != NULL \endcode
  89618. * \retval unsigned
  89619. * See above.
  89620. */
  89621. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  89622. /** Get the current sample rate in Hz of the stream being decoded.
  89623. * Will only be valid after decoding has started and will contain the
  89624. * value from the most recently decoded frame header.
  89625. *
  89626. * \param decoder A decoder instance to query.
  89627. * \assert
  89628. * \code decoder != NULL \endcode
  89629. * \retval unsigned
  89630. * See above.
  89631. */
  89632. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  89633. /** Get the current blocksize of the stream being decoded.
  89634. * Will only be valid after decoding has started and will contain the
  89635. * value from the most recently decoded frame header.
  89636. *
  89637. * \param decoder A decoder instance to query.
  89638. * \assert
  89639. * \code decoder != NULL \endcode
  89640. * \retval unsigned
  89641. * See above.
  89642. */
  89643. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  89644. /** Returns the decoder's current read position within the stream.
  89645. * The position is the byte offset from the start of the stream.
  89646. * Bytes before this position have been fully decoded. Note that
  89647. * there may still be undecoded bytes in the decoder's read FIFO.
  89648. * The returned position is correct even after a seek.
  89649. *
  89650. * \warning This function currently only works for native FLAC,
  89651. * not Ogg FLAC streams.
  89652. *
  89653. * \param decoder A decoder instance to query.
  89654. * \param position Address at which to return the desired position.
  89655. * \assert
  89656. * \code decoder != NULL \endcode
  89657. * \code position != NULL \endcode
  89658. * \retval FLAC__bool
  89659. * \c true if successful, \c false if the stream is not native FLAC,
  89660. * or there was an error from the 'tell' callback or it returned
  89661. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  89662. */
  89663. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  89664. /** Initialize the decoder instance to decode native FLAC streams.
  89665. *
  89666. * This flavor of initialization sets up the decoder to decode from a
  89667. * native FLAC stream. I/O is performed via callbacks to the client.
  89668. * For decoding from a plain file via filename or open FILE*,
  89669. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  89670. * provide a simpler interface.
  89671. *
  89672. * This function should be called after FLAC__stream_decoder_new() and
  89673. * FLAC__stream_decoder_set_*() but before any of the
  89674. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89675. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89676. * if initialization succeeded.
  89677. *
  89678. * \param decoder An uninitialized decoder instance.
  89679. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89680. * pointer must not be \c NULL.
  89681. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89682. * pointer may be \c NULL if seeking is not
  89683. * supported. If \a seek_callback is not \c NULL then a
  89684. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89685. * Alternatively, a dummy seek callback that just
  89686. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89687. * may also be supplied, all though this is slightly
  89688. * less efficient for the decoder.
  89689. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89690. * pointer may be \c NULL if not supported by the client. If
  89691. * \a seek_callback is not \c NULL then a
  89692. * \a tell_callback must also be supplied.
  89693. * Alternatively, a dummy tell callback that just
  89694. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89695. * may also be supplied, all though this is slightly
  89696. * less efficient for the decoder.
  89697. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89698. * pointer may be \c NULL if not supported by the client. If
  89699. * \a seek_callback is not \c NULL then a
  89700. * \a length_callback must also be supplied.
  89701. * Alternatively, a dummy length callback that just
  89702. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89703. * may also be supplied, all though this is slightly
  89704. * less efficient for the decoder.
  89705. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89706. * pointer may be \c NULL if not supported by the client. If
  89707. * \a seek_callback is not \c NULL then a
  89708. * \a eof_callback must also be supplied.
  89709. * Alternatively, a dummy length callback that just
  89710. * returns \c false
  89711. * may also be supplied, all though this is slightly
  89712. * less efficient for the decoder.
  89713. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89714. * pointer must not be \c NULL.
  89715. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89716. * pointer may be \c NULL if the callback is not
  89717. * desired.
  89718. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89719. * pointer must not be \c NULL.
  89720. * \param client_data This value will be supplied to callbacks in their
  89721. * \a client_data argument.
  89722. * \assert
  89723. * \code decoder != NULL \endcode
  89724. * \retval FLAC__StreamDecoderInitStatus
  89725. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89726. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89727. */
  89728. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  89729. FLAC__StreamDecoder *decoder,
  89730. FLAC__StreamDecoderReadCallback read_callback,
  89731. FLAC__StreamDecoderSeekCallback seek_callback,
  89732. FLAC__StreamDecoderTellCallback tell_callback,
  89733. FLAC__StreamDecoderLengthCallback length_callback,
  89734. FLAC__StreamDecoderEofCallback eof_callback,
  89735. FLAC__StreamDecoderWriteCallback write_callback,
  89736. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89737. FLAC__StreamDecoderErrorCallback error_callback,
  89738. void *client_data
  89739. );
  89740. /** Initialize the decoder instance to decode Ogg FLAC streams.
  89741. *
  89742. * This flavor of initialization sets up the decoder to decode from a
  89743. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  89744. * client. For decoding from a plain file via filename or open FILE*,
  89745. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  89746. * provide a simpler interface.
  89747. *
  89748. * This function should be called after FLAC__stream_decoder_new() and
  89749. * FLAC__stream_decoder_set_*() but before any of the
  89750. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89751. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89752. * if initialization succeeded.
  89753. *
  89754. * \note Support for Ogg FLAC in the library is optional. If this
  89755. * library has been built without support for Ogg FLAC, this function
  89756. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89757. *
  89758. * \param decoder An uninitialized decoder instance.
  89759. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89760. * pointer must not be \c NULL.
  89761. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89762. * pointer may be \c NULL if seeking is not
  89763. * supported. If \a seek_callback is not \c NULL then a
  89764. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89765. * Alternatively, a dummy seek callback that just
  89766. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89767. * may also be supplied, all though this is slightly
  89768. * less efficient for the decoder.
  89769. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89770. * pointer may be \c NULL if not supported by the client. If
  89771. * \a seek_callback is not \c NULL then a
  89772. * \a tell_callback must also be supplied.
  89773. * Alternatively, a dummy tell callback that just
  89774. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89775. * may also be supplied, all though this is slightly
  89776. * less efficient for the decoder.
  89777. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89778. * pointer may be \c NULL if not supported by the client. If
  89779. * \a seek_callback is not \c NULL then a
  89780. * \a length_callback must also be supplied.
  89781. * Alternatively, a dummy length callback that just
  89782. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89783. * may also be supplied, all though this is slightly
  89784. * less efficient for the decoder.
  89785. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89786. * pointer may be \c NULL if not supported by the client. If
  89787. * \a seek_callback is not \c NULL then a
  89788. * \a eof_callback must also be supplied.
  89789. * Alternatively, a dummy length callback that just
  89790. * returns \c false
  89791. * may also be supplied, all though this is slightly
  89792. * less efficient for the decoder.
  89793. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89794. * pointer must not be \c NULL.
  89795. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89796. * pointer may be \c NULL if the callback is not
  89797. * desired.
  89798. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89799. * pointer must not be \c NULL.
  89800. * \param client_data This value will be supplied to callbacks in their
  89801. * \a client_data argument.
  89802. * \assert
  89803. * \code decoder != NULL \endcode
  89804. * \retval FLAC__StreamDecoderInitStatus
  89805. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89806. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89807. */
  89808. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  89809. FLAC__StreamDecoder *decoder,
  89810. FLAC__StreamDecoderReadCallback read_callback,
  89811. FLAC__StreamDecoderSeekCallback seek_callback,
  89812. FLAC__StreamDecoderTellCallback tell_callback,
  89813. FLAC__StreamDecoderLengthCallback length_callback,
  89814. FLAC__StreamDecoderEofCallback eof_callback,
  89815. FLAC__StreamDecoderWriteCallback write_callback,
  89816. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89817. FLAC__StreamDecoderErrorCallback error_callback,
  89818. void *client_data
  89819. );
  89820. /** Initialize the decoder instance to decode native FLAC files.
  89821. *
  89822. * This flavor of initialization sets up the decoder to decode from a
  89823. * plain native FLAC file. For non-stdio streams, you must use
  89824. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  89825. *
  89826. * This function should be called after FLAC__stream_decoder_new() and
  89827. * FLAC__stream_decoder_set_*() but before any of the
  89828. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89829. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89830. * if initialization succeeded.
  89831. *
  89832. * \param decoder An uninitialized decoder instance.
  89833. * \param file An open FLAC file. The file should have been
  89834. * opened with mode \c "rb" and rewound. The file
  89835. * becomes owned by the decoder and should not be
  89836. * manipulated by the client while decoding.
  89837. * Unless \a file is \c stdin, it will be closed
  89838. * when FLAC__stream_decoder_finish() is called.
  89839. * Note however that seeking will not work when
  89840. * decoding from \c stdout since it is not seekable.
  89841. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89842. * pointer must not be \c NULL.
  89843. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89844. * pointer may be \c NULL if the callback is not
  89845. * desired.
  89846. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89847. * pointer must not be \c NULL.
  89848. * \param client_data This value will be supplied to callbacks in their
  89849. * \a client_data argument.
  89850. * \assert
  89851. * \code decoder != NULL \endcode
  89852. * \code file != NULL \endcode
  89853. * \retval FLAC__StreamDecoderInitStatus
  89854. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89855. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89856. */
  89857. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  89858. FLAC__StreamDecoder *decoder,
  89859. FILE *file,
  89860. FLAC__StreamDecoderWriteCallback write_callback,
  89861. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89862. FLAC__StreamDecoderErrorCallback error_callback,
  89863. void *client_data
  89864. );
  89865. /** Initialize the decoder instance to decode Ogg FLAC files.
  89866. *
  89867. * This flavor of initialization sets up the decoder to decode from a
  89868. * plain Ogg FLAC file. For non-stdio streams, you must use
  89869. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  89870. *
  89871. * This function should be called after FLAC__stream_decoder_new() and
  89872. * FLAC__stream_decoder_set_*() but before any of the
  89873. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89874. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89875. * if initialization succeeded.
  89876. *
  89877. * \note Support for Ogg FLAC in the library is optional. If this
  89878. * library has been built without support for Ogg FLAC, this function
  89879. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89880. *
  89881. * \param decoder An uninitialized decoder instance.
  89882. * \param file An open FLAC file. The file should have been
  89883. * opened with mode \c "rb" and rewound. The file
  89884. * becomes owned by the decoder and should not be
  89885. * manipulated by the client while decoding.
  89886. * Unless \a file is \c stdin, it will be closed
  89887. * when FLAC__stream_decoder_finish() is called.
  89888. * Note however that seeking will not work when
  89889. * decoding from \c stdout since it is not seekable.
  89890. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89891. * pointer must not be \c NULL.
  89892. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89893. * pointer may be \c NULL if the callback is not
  89894. * desired.
  89895. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89896. * pointer must not be \c NULL.
  89897. * \param client_data This value will be supplied to callbacks in their
  89898. * \a client_data argument.
  89899. * \assert
  89900. * \code decoder != NULL \endcode
  89901. * \code file != NULL \endcode
  89902. * \retval FLAC__StreamDecoderInitStatus
  89903. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89904. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89905. */
  89906. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  89907. FLAC__StreamDecoder *decoder,
  89908. FILE *file,
  89909. FLAC__StreamDecoderWriteCallback write_callback,
  89910. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89911. FLAC__StreamDecoderErrorCallback error_callback,
  89912. void *client_data
  89913. );
  89914. /** Initialize the decoder instance to decode native FLAC files.
  89915. *
  89916. * This flavor of initialization sets up the decoder to decode from a plain
  89917. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  89918. * example, with Unicode filenames on Windows), you must use
  89919. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  89920. * and provide callbacks for the I/O.
  89921. *
  89922. * This function should be called after FLAC__stream_decoder_new() and
  89923. * FLAC__stream_decoder_set_*() but before any of the
  89924. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89925. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89926. * if initialization succeeded.
  89927. *
  89928. * \param decoder An uninitialized decoder instance.
  89929. * \param filename The name of the file to decode from. The file will
  89930. * be opened with fopen(). Use \c NULL to decode from
  89931. * \c stdin. Note that \c stdin is not seekable.
  89932. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89933. * pointer must not be \c NULL.
  89934. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89935. * pointer may be \c NULL if the callback is not
  89936. * desired.
  89937. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89938. * pointer must not be \c NULL.
  89939. * \param client_data This value will be supplied to callbacks in their
  89940. * \a client_data argument.
  89941. * \assert
  89942. * \code decoder != NULL \endcode
  89943. * \retval FLAC__StreamDecoderInitStatus
  89944. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89945. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89946. */
  89947. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  89948. FLAC__StreamDecoder *decoder,
  89949. const char *filename,
  89950. FLAC__StreamDecoderWriteCallback write_callback,
  89951. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89952. FLAC__StreamDecoderErrorCallback error_callback,
  89953. void *client_data
  89954. );
  89955. /** Initialize the decoder instance to decode Ogg FLAC files.
  89956. *
  89957. * This flavor of initialization sets up the decoder to decode from a plain
  89958. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  89959. * example, with Unicode filenames on Windows), you must use
  89960. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  89961. * and provide callbacks for the I/O.
  89962. *
  89963. * This function should be called after FLAC__stream_decoder_new() and
  89964. * FLAC__stream_decoder_set_*() but before any of the
  89965. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89966. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89967. * if initialization succeeded.
  89968. *
  89969. * \note Support for Ogg FLAC in the library is optional. If this
  89970. * library has been built without support for Ogg FLAC, this function
  89971. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89972. *
  89973. * \param decoder An uninitialized decoder instance.
  89974. * \param filename The name of the file to decode from. The file will
  89975. * be opened with fopen(). Use \c NULL to decode from
  89976. * \c stdin. Note that \c stdin is not seekable.
  89977. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89978. * pointer must not be \c NULL.
  89979. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89980. * pointer may be \c NULL if the callback is not
  89981. * desired.
  89982. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89983. * pointer must not be \c NULL.
  89984. * \param client_data This value will be supplied to callbacks in their
  89985. * \a client_data argument.
  89986. * \assert
  89987. * \code decoder != NULL \endcode
  89988. * \retval FLAC__StreamDecoderInitStatus
  89989. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89990. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89991. */
  89992. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  89993. FLAC__StreamDecoder *decoder,
  89994. const char *filename,
  89995. FLAC__StreamDecoderWriteCallback write_callback,
  89996. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89997. FLAC__StreamDecoderErrorCallback error_callback,
  89998. void *client_data
  89999. );
  90000. /** Finish the decoding process.
  90001. * Flushes the decoding buffer, releases resources, resets the decoder
  90002. * settings to their defaults, and returns the decoder state to
  90003. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90004. *
  90005. * In the event of a prematurely-terminated decode, it is not strictly
  90006. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90007. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90008. * with a FLAC__stream_decoder_finish().
  90009. *
  90010. * \param decoder An uninitialized decoder instance.
  90011. * \assert
  90012. * \code decoder != NULL \endcode
  90013. * \retval FLAC__bool
  90014. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90015. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90016. * signature does not match the one computed by the decoder; else
  90017. * \c true.
  90018. */
  90019. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90020. /** Flush the stream input.
  90021. * The decoder's input buffer will be cleared and the state set to
  90022. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90023. * off MD5 checking.
  90024. *
  90025. * \param decoder A decoder instance.
  90026. * \assert
  90027. * \code decoder != NULL \endcode
  90028. * \retval FLAC__bool
  90029. * \c true if successful, else \c false if a memory allocation
  90030. * error occurs (in which case the state will be set to
  90031. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90032. */
  90033. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90034. /** Reset the decoding process.
  90035. * The decoder's input buffer will be cleared and the state set to
  90036. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90037. * FLAC__stream_decoder_finish() except that the settings are
  90038. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90039. * before decoding again. MD5 checking will be restored to its original
  90040. * setting.
  90041. *
  90042. * If the decoder is seekable, or was initialized with
  90043. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90044. * the decoder will also attempt to seek to the beginning of the file.
  90045. * If this rewind fails, this function will return \c false. It follows
  90046. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90047. * \c stdin.
  90048. *
  90049. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90050. * and is not seekable (i.e. no seek callback was provided or the seek
  90051. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90052. * is the duty of the client to start feeding data from the beginning of
  90053. * the stream on the next FLAC__stream_decoder_process() or
  90054. * FLAC__stream_decoder_process_interleaved() call.
  90055. *
  90056. * \param decoder A decoder instance.
  90057. * \assert
  90058. * \code decoder != NULL \endcode
  90059. * \retval FLAC__bool
  90060. * \c true if successful, else \c false if a memory allocation occurs
  90061. * (in which case the state will be set to
  90062. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90063. * occurs (the state will be unchanged).
  90064. */
  90065. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90066. /** Decode one metadata block or audio frame.
  90067. * This version instructs the decoder to decode a either a single metadata
  90068. * block or a single frame and stop, unless the callbacks return a fatal
  90069. * error or the read callback returns
  90070. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90071. *
  90072. * As the decoder needs more input it will call the read callback.
  90073. * Depending on what was decoded, the metadata or write callback will be
  90074. * called with the decoded metadata block or audio frame.
  90075. *
  90076. * Unless there is a fatal read error or end of stream, this function
  90077. * will return once one whole frame is decoded. In other words, if the
  90078. * stream is not synchronized or points to a corrupt frame header, the
  90079. * decoder will continue to try and resync until it gets to a valid
  90080. * frame, then decode one frame, then return. If the decoder points to
  90081. * a frame whose frame CRC in the frame footer does not match the
  90082. * computed frame CRC, this function will issue a
  90083. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90084. * error callback, and return, having decoded one complete, although
  90085. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90086. * correct length to the write callback.)
  90087. *
  90088. * \param decoder An initialized decoder instance.
  90089. * \assert
  90090. * \code decoder != NULL \endcode
  90091. * \retval FLAC__bool
  90092. * \c false if any fatal read, write, or memory allocation error
  90093. * occurred (meaning decoding must stop), else \c true; for more
  90094. * information about the decoder, check the decoder state with
  90095. * FLAC__stream_decoder_get_state().
  90096. */
  90097. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90098. /** Decode until the end of the metadata.
  90099. * This version instructs the decoder to decode from the current position
  90100. * and continue until all the metadata has been read, or until the
  90101. * callbacks return a fatal error or the read callback returns
  90102. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90103. *
  90104. * As the decoder needs more input it will call the read callback.
  90105. * As each metadata block is decoded, the metadata callback will be called
  90106. * with the decoded metadata.
  90107. *
  90108. * \param decoder An initialized decoder instance.
  90109. * \assert
  90110. * \code decoder != NULL \endcode
  90111. * \retval FLAC__bool
  90112. * \c false if any fatal read, write, or memory allocation error
  90113. * occurred (meaning decoding must stop), else \c true; for more
  90114. * information about the decoder, check the decoder state with
  90115. * FLAC__stream_decoder_get_state().
  90116. */
  90117. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90118. /** Decode until the end of the stream.
  90119. * This version instructs the decoder to decode from the current position
  90120. * and continue until the end of stream (the read callback returns
  90121. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90122. * callbacks return a fatal error.
  90123. *
  90124. * As the decoder needs more input it will call the read callback.
  90125. * As each metadata block and frame is decoded, the metadata or write
  90126. * callback will be called with the decoded metadata or frame.
  90127. *
  90128. * \param decoder An initialized decoder instance.
  90129. * \assert
  90130. * \code decoder != NULL \endcode
  90131. * \retval FLAC__bool
  90132. * \c false if any fatal read, write, or memory allocation error
  90133. * occurred (meaning decoding must stop), else \c true; for more
  90134. * information about the decoder, check the decoder state with
  90135. * FLAC__stream_decoder_get_state().
  90136. */
  90137. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90138. /** Skip one audio frame.
  90139. * This version instructs the decoder to 'skip' a single frame and stop,
  90140. * unless the callbacks return a fatal error or the read callback returns
  90141. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90142. *
  90143. * The decoding flow is the same as what occurs when
  90144. * FLAC__stream_decoder_process_single() is called to process an audio
  90145. * frame, except that this function does not decode the parsed data into
  90146. * PCM or call the write callback. The integrity of the frame is still
  90147. * checked the same way as in the other process functions.
  90148. *
  90149. * This function will return once one whole frame is skipped, in the
  90150. * same way that FLAC__stream_decoder_process_single() will return once
  90151. * one whole frame is decoded.
  90152. *
  90153. * This function can be used in more quickly determining FLAC frame
  90154. * boundaries when decoding of the actual data is not needed, for
  90155. * example when an application is separating a FLAC stream into frames
  90156. * for editing or storing in a container. To do this, the application
  90157. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90158. * to the next frame, then use
  90159. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90160. * boundary.
  90161. *
  90162. * This function should only be called when the stream has advanced
  90163. * past all the metadata, otherwise it will return \c false.
  90164. *
  90165. * \param decoder An initialized decoder instance not in a metadata
  90166. * state.
  90167. * \assert
  90168. * \code decoder != NULL \endcode
  90169. * \retval FLAC__bool
  90170. * \c false if any fatal read, write, or memory allocation error
  90171. * occurred (meaning decoding must stop), or if the decoder
  90172. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90173. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90174. * information about the decoder, check the decoder state with
  90175. * FLAC__stream_decoder_get_state().
  90176. */
  90177. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90178. /** Flush the input and seek to an absolute sample.
  90179. * Decoding will resume at the given sample. Note that because of
  90180. * this, the next write callback may contain a partial block. The
  90181. * client must support seeking the input or this function will fail
  90182. * and return \c false. Furthermore, if the decoder state is
  90183. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90184. * with FLAC__stream_decoder_flush() or reset with
  90185. * FLAC__stream_decoder_reset() before decoding can continue.
  90186. *
  90187. * \param decoder A decoder instance.
  90188. * \param sample The target sample number to seek to.
  90189. * \assert
  90190. * \code decoder != NULL \endcode
  90191. * \retval FLAC__bool
  90192. * \c true if successful, else \c false.
  90193. */
  90194. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90195. /* \} */
  90196. #ifdef __cplusplus
  90197. }
  90198. #endif
  90199. #endif
  90200. /*** End of inlined file: stream_decoder.h ***/
  90201. /*** Start of inlined file: stream_encoder.h ***/
  90202. #ifndef FLAC__STREAM_ENCODER_H
  90203. #define FLAC__STREAM_ENCODER_H
  90204. #include <stdio.h> /* for FILE */
  90205. #ifdef __cplusplus
  90206. extern "C" {
  90207. #endif
  90208. /** \file include/FLAC/stream_encoder.h
  90209. *
  90210. * \brief
  90211. * This module contains the functions which implement the stream
  90212. * encoder.
  90213. *
  90214. * See the detailed documentation in the
  90215. * \link flac_stream_encoder stream encoder \endlink module.
  90216. */
  90217. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90218. * \ingroup flac
  90219. *
  90220. * \brief
  90221. * This module describes the encoder layers provided by libFLAC.
  90222. *
  90223. * The stream encoder can be used to encode complete streams either to the
  90224. * client via callbacks, or directly to a file, depending on how it is
  90225. * initialized. When encoding via callbacks, the client provides a write
  90226. * callback which will be called whenever FLAC data is ready to be written.
  90227. * If the client also supplies a seek callback, the encoder will also
  90228. * automatically handle the writing back of metadata discovered while
  90229. * encoding, like stream info, seek points offsets, etc. When encoding to
  90230. * a file, the client needs only supply a filename or open \c FILE* and an
  90231. * optional progress callback for periodic notification of progress; the
  90232. * write and seek callbacks are supplied internally. For more info see the
  90233. * \link flac_stream_encoder stream encoder \endlink module.
  90234. */
  90235. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90236. * \ingroup flac_encoder
  90237. *
  90238. * \brief
  90239. * This module contains the functions which implement the stream
  90240. * encoder.
  90241. *
  90242. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  90243. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  90244. *
  90245. * The basic usage of this encoder is as follows:
  90246. * - The program creates an instance of an encoder using
  90247. * FLAC__stream_encoder_new().
  90248. * - The program overrides the default settings using
  90249. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  90250. * functions should be called:
  90251. * - FLAC__stream_encoder_set_channels()
  90252. * - FLAC__stream_encoder_set_bits_per_sample()
  90253. * - FLAC__stream_encoder_set_sample_rate()
  90254. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  90255. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  90256. * - If the application wants to control the compression level or set its own
  90257. * metadata, then the following should also be called:
  90258. * - FLAC__stream_encoder_set_compression_level()
  90259. * - FLAC__stream_encoder_set_verify()
  90260. * - FLAC__stream_encoder_set_metadata()
  90261. * - The rest of the set functions should only be called if the client needs
  90262. * exact control over how the audio is compressed; thorough understanding
  90263. * of the FLAC format is necessary to achieve good results.
  90264. * - The program initializes the instance to validate the settings and
  90265. * prepare for encoding using
  90266. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  90267. * or FLAC__stream_encoder_init_file() for native FLAC
  90268. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  90269. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  90270. * - The program calls FLAC__stream_encoder_process() or
  90271. * FLAC__stream_encoder_process_interleaved() to encode data, which
  90272. * subsequently calls the callbacks when there is encoder data ready
  90273. * to be written.
  90274. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  90275. * which causes the encoder to encode any data still in its input pipe,
  90276. * update the metadata with the final encoding statistics if output
  90277. * seeking is possible, and finally reset the encoder to the
  90278. * uninitialized state.
  90279. * - The instance may be used again or deleted with
  90280. * FLAC__stream_encoder_delete().
  90281. *
  90282. * In more detail, the stream encoder functions similarly to the
  90283. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  90284. * callbacks and more options. Typically the client will create a new
  90285. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  90286. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  90287. * calling one of the FLAC__stream_encoder_init_*() functions.
  90288. *
  90289. * Unlike the decoders, the stream encoder has many options that can
  90290. * affect the speed and compression ratio. When setting these parameters
  90291. * you should have some basic knowledge of the format (see the
  90292. * <A HREF="../documentation.html#format">user-level documentation</A>
  90293. * or the <A HREF="../format.html">formal description</A>). The
  90294. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  90295. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  90296. * functions will do this, so make sure to pay attention to the state
  90297. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  90298. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  90299. * before FLAC__stream_encoder_init_*() will take on the defaults from
  90300. * the constructor.
  90301. *
  90302. * There are three initialization functions for native FLAC, one for
  90303. * setting up the encoder to encode FLAC data to the client via
  90304. * callbacks, and two for encoding directly to a file.
  90305. *
  90306. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90307. * You must also supply a write callback which will be called anytime
  90308. * there is raw encoded data to write. If the client can seek the output
  90309. * it is best to also supply seek and tell callbacks, as this allows the
  90310. * encoder to go back after encoding is finished to write back
  90311. * information that was collected while encoding, like seek point offsets,
  90312. * frame sizes, etc.
  90313. *
  90314. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90315. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90316. * filename or open \c FILE*; the encoder will handle all the callbacks
  90317. * internally. You may also supply a progress callback for periodic
  90318. * notification of the encoding progress.
  90319. *
  90320. * There are three similarly-named init functions for encoding to Ogg
  90321. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90322. * library has been built with Ogg support.
  90323. *
  90324. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90325. * call the write callback several times, once with the \c fLaC signature,
  90326. * and once for each encoded metadata block. Note that for Ogg FLAC
  90327. * encoding you will usually get at least twice the number of callbacks than
  90328. * with native FLAC, one for the Ogg page header and one for the page body.
  90329. *
  90330. * After initializing the instance, the client may feed audio data to the
  90331. * encoder in one of two ways:
  90332. *
  90333. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90334. * will pass an array of pointers to buffers, one for each channel, to
  90335. * the encoder, each of the same length. The samples need not be
  90336. * block-aligned, but each channel should have the same number of samples.
  90337. * - Channel interleaved, through
  90338. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90339. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90340. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90341. * Again, the samples need not be block-aligned but they must be
  90342. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90343. * the last value channelN_sampleM.
  90344. *
  90345. * Note that for either process call, each sample in the buffers should be a
  90346. * signed integer, right-justified to the resolution set by
  90347. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90348. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90349. *
  90350. * When the client is finished encoding data, it calls
  90351. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90352. * data still in its input pipe, and call the metadata callback with the
  90353. * final encoding statistics. Then the instance may be deleted with
  90354. * FLAC__stream_encoder_delete() or initialized again to encode another
  90355. * stream.
  90356. *
  90357. * For programs that write their own metadata, but that do not know the
  90358. * actual metadata until after encoding, it is advantageous to instruct
  90359. * the encoder to write a PADDING block of the correct size, so that
  90360. * instead of rewriting the whole stream after encoding, the program can
  90361. * just overwrite the PADDING block. If only the maximum size of the
  90362. * metadata is known, the program can write a slightly larger padding
  90363. * block, then split it after encoding.
  90364. *
  90365. * Make sure you understand how lengths are calculated. All FLAC metadata
  90366. * blocks have a 4 byte header which contains the type and length. This
  90367. * length does not include the 4 bytes of the header. See the format page
  90368. * for the specification of metadata blocks and their lengths.
  90369. *
  90370. * \note
  90371. * If you are writing the FLAC data to a file via callbacks, make sure it
  90372. * is open for update (e.g. mode "w+" for stdio streams). This is because
  90373. * after the first encoding pass, the encoder will try to seek back to the
  90374. * beginning of the stream, to the STREAMINFO block, to write some data
  90375. * there. (If using FLAC__stream_encoder_init*_file() or
  90376. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  90377. *
  90378. * \note
  90379. * The "set" functions may only be called when the encoder is in the
  90380. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  90381. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  90382. * before FLAC__stream_encoder_init_*(). If this is the case they will
  90383. * return \c true, otherwise \c false.
  90384. *
  90385. * \note
  90386. * FLAC__stream_encoder_finish() resets all settings to the constructor
  90387. * defaults.
  90388. *
  90389. * \{
  90390. */
  90391. /** State values for a FLAC__StreamEncoder.
  90392. *
  90393. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  90394. *
  90395. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  90396. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  90397. * must be deleted with FLAC__stream_encoder_delete().
  90398. */
  90399. typedef enum {
  90400. FLAC__STREAM_ENCODER_OK = 0,
  90401. /**< The encoder is in the normal OK state and samples can be processed. */
  90402. FLAC__STREAM_ENCODER_UNINITIALIZED,
  90403. /**< The encoder is in the uninitialized state; one of the
  90404. * FLAC__stream_encoder_init_*() functions must be called before samples
  90405. * can be processed.
  90406. */
  90407. FLAC__STREAM_ENCODER_OGG_ERROR,
  90408. /**< An error occurred in the underlying Ogg layer. */
  90409. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  90410. /**< An error occurred in the underlying verify stream decoder;
  90411. * check FLAC__stream_encoder_get_verify_decoder_state().
  90412. */
  90413. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  90414. /**< The verify decoder detected a mismatch between the original
  90415. * audio signal and the decoded audio signal.
  90416. */
  90417. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  90418. /**< One of the callbacks returned a fatal error. */
  90419. FLAC__STREAM_ENCODER_IO_ERROR,
  90420. /**< An I/O error occurred while opening/reading/writing a file.
  90421. * Check \c errno.
  90422. */
  90423. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  90424. /**< An error occurred while writing the stream; usually, the
  90425. * write_callback returned an error.
  90426. */
  90427. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  90428. /**< Memory allocation failed. */
  90429. } FLAC__StreamEncoderState;
  90430. /** Maps a FLAC__StreamEncoderState to a C string.
  90431. *
  90432. * Using a FLAC__StreamEncoderState as the index to this array
  90433. * will give the string equivalent. The contents should not be modified.
  90434. */
  90435. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  90436. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  90437. */
  90438. typedef enum {
  90439. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  90440. /**< Initialization was successful. */
  90441. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  90442. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  90443. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  90444. /**< The library was not compiled with support for the given container
  90445. * format.
  90446. */
  90447. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  90448. /**< A required callback was not supplied. */
  90449. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  90450. /**< The encoder has an invalid setting for number of channels. */
  90451. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  90452. /**< The encoder has an invalid setting for bits-per-sample.
  90453. * FLAC supports 4-32 bps but the reference encoder currently supports
  90454. * only up to 24 bps.
  90455. */
  90456. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  90457. /**< The encoder has an invalid setting for the input sample rate. */
  90458. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  90459. /**< The encoder has an invalid setting for the block size. */
  90460. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  90461. /**< The encoder has an invalid setting for the maximum LPC order. */
  90462. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  90463. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  90464. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  90465. /**< The specified block size is less than the maximum LPC order. */
  90466. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  90467. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  90468. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  90469. /**< The metadata input to the encoder is invalid, in one of the following ways:
  90470. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  90471. * - One of the metadata blocks contains an undefined type
  90472. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  90473. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  90474. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  90475. */
  90476. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  90477. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  90478. * already initialized, usually because
  90479. * FLAC__stream_encoder_finish() was not called.
  90480. */
  90481. } FLAC__StreamEncoderInitStatus;
  90482. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  90483. *
  90484. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  90485. * will give the string equivalent. The contents should not be modified.
  90486. */
  90487. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  90488. /** Return values for the FLAC__StreamEncoder read callback.
  90489. */
  90490. typedef enum {
  90491. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  90492. /**< The read was OK and decoding can continue. */
  90493. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  90494. /**< The read was attempted at the end of the stream. */
  90495. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  90496. /**< An unrecoverable error occurred. */
  90497. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  90498. /**< Client does not support reading back from the output. */
  90499. } FLAC__StreamEncoderReadStatus;
  90500. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  90501. *
  90502. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  90503. * will give the string equivalent. The contents should not be modified.
  90504. */
  90505. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  90506. /** Return values for the FLAC__StreamEncoder write callback.
  90507. */
  90508. typedef enum {
  90509. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  90510. /**< The write was OK and encoding can continue. */
  90511. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  90512. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  90513. } FLAC__StreamEncoderWriteStatus;
  90514. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  90515. *
  90516. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  90517. * will give the string equivalent. The contents should not be modified.
  90518. */
  90519. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  90520. /** Return values for the FLAC__StreamEncoder seek callback.
  90521. */
  90522. typedef enum {
  90523. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  90524. /**< The seek was OK and encoding can continue. */
  90525. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  90526. /**< An unrecoverable error occurred. */
  90527. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  90528. /**< Client does not support seeking. */
  90529. } FLAC__StreamEncoderSeekStatus;
  90530. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  90531. *
  90532. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  90533. * will give the string equivalent. The contents should not be modified.
  90534. */
  90535. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  90536. /** Return values for the FLAC__StreamEncoder tell callback.
  90537. */
  90538. typedef enum {
  90539. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  90540. /**< The tell was OK and encoding can continue. */
  90541. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  90542. /**< An unrecoverable error occurred. */
  90543. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  90544. /**< Client does not support seeking. */
  90545. } FLAC__StreamEncoderTellStatus;
  90546. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  90547. *
  90548. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  90549. * will give the string equivalent. The contents should not be modified.
  90550. */
  90551. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  90552. /***********************************************************************
  90553. *
  90554. * class FLAC__StreamEncoder
  90555. *
  90556. ***********************************************************************/
  90557. struct FLAC__StreamEncoderProtected;
  90558. struct FLAC__StreamEncoderPrivate;
  90559. /** The opaque structure definition for the stream encoder type.
  90560. * See the \link flac_stream_encoder stream encoder module \endlink
  90561. * for a detailed description.
  90562. */
  90563. typedef struct {
  90564. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  90565. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  90566. } FLAC__StreamEncoder;
  90567. /** Signature for the read callback.
  90568. *
  90569. * A function pointer matching this signature must be passed to
  90570. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  90571. * The supplied function will be called when the encoder needs to read back
  90572. * encoded data. This happens during the metadata callback, when the encoder
  90573. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  90574. * while encoding. The address of the buffer to be filled is supplied, along
  90575. * with the number of bytes the buffer can hold. The callback may choose to
  90576. * supply less data and modify the byte count but must be careful not to
  90577. * overflow the buffer. The callback then returns a status code chosen from
  90578. * FLAC__StreamEncoderReadStatus.
  90579. *
  90580. * Here is an example of a read callback for stdio streams:
  90581. * \code
  90582. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  90583. * {
  90584. * FILE *file = ((MyClientData*)client_data)->file;
  90585. * if(*bytes > 0) {
  90586. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  90587. * if(ferror(file))
  90588. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90589. * else if(*bytes == 0)
  90590. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  90591. * else
  90592. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  90593. * }
  90594. * else
  90595. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90596. * }
  90597. * \endcode
  90598. *
  90599. * \note In general, FLAC__StreamEncoder functions which change the
  90600. * state should not be called on the \a encoder while in the callback.
  90601. *
  90602. * \param encoder The encoder instance calling the callback.
  90603. * \param buffer A pointer to a location for the callee to store
  90604. * data to be encoded.
  90605. * \param bytes A pointer to the size of the buffer. On entry
  90606. * to the callback, it contains the maximum number
  90607. * of bytes that may be stored in \a buffer. The
  90608. * callee must set it to the actual number of bytes
  90609. * stored (0 in case of error or end-of-stream) before
  90610. * returning.
  90611. * \param client_data The callee's client data set through
  90612. * FLAC__stream_encoder_set_client_data().
  90613. * \retval FLAC__StreamEncoderReadStatus
  90614. * The callee's return status.
  90615. */
  90616. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  90617. /** Signature for the write callback.
  90618. *
  90619. * A function pointer matching this signature must be passed to
  90620. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90621. * by the encoder anytime there is raw encoded data ready to write. It may
  90622. * include metadata mixed with encoded audio frames and the data is not
  90623. * guaranteed to be aligned on frame or metadata block boundaries.
  90624. *
  90625. * The only duty of the callback is to write out the \a bytes worth of data
  90626. * in \a buffer to the current position in the output stream. The arguments
  90627. * \a samples and \a current_frame are purely informational. If \a samples
  90628. * is greater than \c 0, then \a current_frame will hold the current frame
  90629. * number that is being written; otherwise it indicates that the write
  90630. * callback is being called to write metadata.
  90631. *
  90632. * \note
  90633. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  90634. * write callback will be called twice when writing each audio
  90635. * frame; once for the page header, and once for the page body.
  90636. * When writing the page header, the \a samples argument to the
  90637. * write callback will be \c 0.
  90638. *
  90639. * \note In general, FLAC__StreamEncoder functions which change the
  90640. * state should not be called on the \a encoder while in the callback.
  90641. *
  90642. * \param encoder The encoder instance calling the callback.
  90643. * \param buffer An array of encoded data of length \a bytes.
  90644. * \param bytes The byte length of \a buffer.
  90645. * \param samples The number of samples encoded by \a buffer.
  90646. * \c 0 has a special meaning; see above.
  90647. * \param current_frame The number of the current frame being encoded.
  90648. * \param client_data The callee's client data set through
  90649. * FLAC__stream_encoder_init_*().
  90650. * \retval FLAC__StreamEncoderWriteStatus
  90651. * The callee's return status.
  90652. */
  90653. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  90654. /** Signature for the seek callback.
  90655. *
  90656. * A function pointer matching this signature may be passed to
  90657. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90658. * when the encoder needs to seek the output stream. The encoder will pass
  90659. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  90660. *
  90661. * Here is an example of a seek callback for stdio streams:
  90662. * \code
  90663. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  90664. * {
  90665. * FILE *file = ((MyClientData*)client_data)->file;
  90666. * if(file == stdin)
  90667. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  90668. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  90669. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  90670. * else
  90671. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  90672. * }
  90673. * \endcode
  90674. *
  90675. * \note In general, FLAC__StreamEncoder functions which change the
  90676. * state should not be called on the \a encoder while in the callback.
  90677. *
  90678. * \param encoder The encoder instance calling the callback.
  90679. * \param absolute_byte_offset The offset from the beginning of the stream
  90680. * to seek to.
  90681. * \param client_data The callee's client data set through
  90682. * FLAC__stream_encoder_init_*().
  90683. * \retval FLAC__StreamEncoderSeekStatus
  90684. * The callee's return status.
  90685. */
  90686. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  90687. /** Signature for the tell callback.
  90688. *
  90689. * A function pointer matching this signature may be passed to
  90690. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90691. * when the encoder needs to know the current position of the output stream.
  90692. *
  90693. * \warning
  90694. * The callback must return the true current byte offset of the output to
  90695. * which the encoder is writing. If you are buffering the output, make
  90696. * sure and take this into account. If you are writing directly to a
  90697. * FILE* from your write callback, ftell() is sufficient. If you are
  90698. * writing directly to a file descriptor from your write callback, you
  90699. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  90700. * these points to rewrite metadata after encoding.
  90701. *
  90702. * Here is an example of a tell callback for stdio streams:
  90703. * \code
  90704. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  90705. * {
  90706. * FILE *file = ((MyClientData*)client_data)->file;
  90707. * off_t pos;
  90708. * if(file == stdin)
  90709. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  90710. * else if((pos = ftello(file)) < 0)
  90711. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  90712. * else {
  90713. * *absolute_byte_offset = (FLAC__uint64)pos;
  90714. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  90715. * }
  90716. * }
  90717. * \endcode
  90718. *
  90719. * \note In general, FLAC__StreamEncoder functions which change the
  90720. * state should not be called on the \a encoder while in the callback.
  90721. *
  90722. * \param encoder The encoder instance calling the callback.
  90723. * \param absolute_byte_offset The address at which to store the current
  90724. * position of the output.
  90725. * \param client_data The callee's client data set through
  90726. * FLAC__stream_encoder_init_*().
  90727. * \retval FLAC__StreamEncoderTellStatus
  90728. * The callee's return status.
  90729. */
  90730. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  90731. /** Signature for the metadata callback.
  90732. *
  90733. * A function pointer matching this signature may be passed to
  90734. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90735. * once at the end of encoding with the populated STREAMINFO structure. This
  90736. * is so the client can seek back to the beginning of the file and write the
  90737. * STREAMINFO block with the correct statistics after encoding (like
  90738. * minimum/maximum frame size and total samples).
  90739. *
  90740. * \note In general, FLAC__StreamEncoder functions which change the
  90741. * state should not be called on the \a encoder while in the callback.
  90742. *
  90743. * \param encoder The encoder instance calling the callback.
  90744. * \param metadata The final populated STREAMINFO block.
  90745. * \param client_data The callee's client data set through
  90746. * FLAC__stream_encoder_init_*().
  90747. */
  90748. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  90749. /** Signature for the progress callback.
  90750. *
  90751. * A function pointer matching this signature may be passed to
  90752. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  90753. * The supplied function will be called when the encoder has finished
  90754. * writing a frame. The \c total_frames_estimate argument to the
  90755. * callback will be based on the value from
  90756. * FLAC__stream_encoder_set_total_samples_estimate().
  90757. *
  90758. * \note In general, FLAC__StreamEncoder functions which change the
  90759. * state should not be called on the \a encoder while in the callback.
  90760. *
  90761. * \param encoder The encoder instance calling the callback.
  90762. * \param bytes_written Bytes written so far.
  90763. * \param samples_written Samples written so far.
  90764. * \param frames_written Frames written so far.
  90765. * \param total_frames_estimate The estimate of the total number of
  90766. * frames to be written.
  90767. * \param client_data The callee's client data set through
  90768. * FLAC__stream_encoder_init_*().
  90769. */
  90770. 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);
  90771. /***********************************************************************
  90772. *
  90773. * Class constructor/destructor
  90774. *
  90775. ***********************************************************************/
  90776. /** Create a new stream encoder instance. The instance is created with
  90777. * default settings; see the individual FLAC__stream_encoder_set_*()
  90778. * functions for each setting's default.
  90779. *
  90780. * \retval FLAC__StreamEncoder*
  90781. * \c NULL if there was an error allocating memory, else the new instance.
  90782. */
  90783. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  90784. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  90785. *
  90786. * \param encoder A pointer to an existing encoder.
  90787. * \assert
  90788. * \code encoder != NULL \endcode
  90789. */
  90790. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  90791. /***********************************************************************
  90792. *
  90793. * Public class method prototypes
  90794. *
  90795. ***********************************************************************/
  90796. /** Set the serial number for the FLAC stream to use in the Ogg container.
  90797. *
  90798. * \note
  90799. * This does not need to be set for native FLAC encoding.
  90800. *
  90801. * \note
  90802. * It is recommended to set a serial number explicitly as the default of '0'
  90803. * may collide with other streams.
  90804. *
  90805. * \default \c 0
  90806. * \param encoder An encoder instance to set.
  90807. * \param serial_number See above.
  90808. * \assert
  90809. * \code encoder != NULL \endcode
  90810. * \retval FLAC__bool
  90811. * \c false if the encoder is already initialized, else \c true.
  90812. */
  90813. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  90814. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  90815. * encoded output by feeding it through an internal decoder and comparing
  90816. * the original signal against the decoded signal. If a mismatch occurs,
  90817. * the process call will return \c false. Note that this will slow the
  90818. * encoding process by the extra time required for decoding and comparison.
  90819. *
  90820. * \default \c false
  90821. * \param encoder An encoder instance to set.
  90822. * \param value Flag value (see above).
  90823. * \assert
  90824. * \code encoder != NULL \endcode
  90825. * \retval FLAC__bool
  90826. * \c false if the encoder is already initialized, else \c true.
  90827. */
  90828. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90829. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  90830. * the encoder will comply with the Subset and will check the
  90831. * settings during FLAC__stream_encoder_init_*() to see if all settings
  90832. * comply. If \c false, the settings may take advantage of the full
  90833. * range that the format allows.
  90834. *
  90835. * Make sure you know what it entails before setting this to \c false.
  90836. *
  90837. * \default \c true
  90838. * \param encoder An encoder instance to set.
  90839. * \param value Flag value (see above).
  90840. * \assert
  90841. * \code encoder != NULL \endcode
  90842. * \retval FLAC__bool
  90843. * \c false if the encoder is already initialized, else \c true.
  90844. */
  90845. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90846. /** Set the number of channels to be encoded.
  90847. *
  90848. * \default \c 2
  90849. * \param encoder An encoder instance to set.
  90850. * \param value See above.
  90851. * \assert
  90852. * \code encoder != NULL \endcode
  90853. * \retval FLAC__bool
  90854. * \c false if the encoder is already initialized, else \c true.
  90855. */
  90856. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  90857. /** Set the sample resolution of the input to be encoded.
  90858. *
  90859. * \warning
  90860. * Do not feed the encoder data that is wider than the value you
  90861. * set here or you will generate an invalid stream.
  90862. *
  90863. * \default \c 16
  90864. * \param encoder An encoder instance to set.
  90865. * \param value See above.
  90866. * \assert
  90867. * \code encoder != NULL \endcode
  90868. * \retval FLAC__bool
  90869. * \c false if the encoder is already initialized, else \c true.
  90870. */
  90871. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  90872. /** Set the sample rate (in Hz) of the input to be encoded.
  90873. *
  90874. * \default \c 44100
  90875. * \param encoder An encoder instance to set.
  90876. * \param value See above.
  90877. * \assert
  90878. * \code encoder != NULL \endcode
  90879. * \retval FLAC__bool
  90880. * \c false if the encoder is already initialized, else \c true.
  90881. */
  90882. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  90883. /** Set the compression level
  90884. *
  90885. * The compression level is roughly proportional to the amount of effort
  90886. * the encoder expends to compress the file. A higher level usually
  90887. * means more computation but higher compression. The default level is
  90888. * suitable for most applications.
  90889. *
  90890. * Currently the levels range from \c 0 (fastest, least compression) to
  90891. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  90892. * treated as \c 8.
  90893. *
  90894. * This function automatically calls the following other \c _set_
  90895. * functions with appropriate values, so the client does not need to
  90896. * unless it specifically wants to override them:
  90897. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  90898. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  90899. * - FLAC__stream_encoder_set_apodization()
  90900. * - FLAC__stream_encoder_set_max_lpc_order()
  90901. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  90902. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  90903. * - FLAC__stream_encoder_set_do_escape_coding()
  90904. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  90905. * - FLAC__stream_encoder_set_min_residual_partition_order()
  90906. * - FLAC__stream_encoder_set_max_residual_partition_order()
  90907. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  90908. *
  90909. * The actual values set for each level are:
  90910. * <table>
  90911. * <tr>
  90912. * <td><b>level</b><td>
  90913. * <td>do mid-side stereo<td>
  90914. * <td>loose mid-side stereo<td>
  90915. * <td>apodization<td>
  90916. * <td>max lpc order<td>
  90917. * <td>qlp coeff precision<td>
  90918. * <td>qlp coeff prec search<td>
  90919. * <td>escape coding<td>
  90920. * <td>exhaustive model search<td>
  90921. * <td>min residual partition order<td>
  90922. * <td>max residual partition order<td>
  90923. * <td>rice parameter search dist<td>
  90924. * </tr>
  90925. * <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>
  90926. * <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>
  90927. * <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>
  90928. * <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>
  90929. * <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>
  90930. * <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>
  90931. * <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>
  90932. * <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>
  90933. * <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>
  90934. * </table>
  90935. *
  90936. * \default \c 5
  90937. * \param encoder An encoder instance to set.
  90938. * \param value See above.
  90939. * \assert
  90940. * \code encoder != NULL \endcode
  90941. * \retval FLAC__bool
  90942. * \c false if the encoder is already initialized, else \c true.
  90943. */
  90944. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  90945. /** Set the blocksize to use while encoding.
  90946. *
  90947. * The number of samples to use per frame. Use \c 0 to let the encoder
  90948. * estimate a blocksize; this is usually best.
  90949. *
  90950. * \default \c 0
  90951. * \param encoder An encoder instance to set.
  90952. * \param value See above.
  90953. * \assert
  90954. * \code encoder != NULL \endcode
  90955. * \retval FLAC__bool
  90956. * \c false if the encoder is already initialized, else \c true.
  90957. */
  90958. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  90959. /** Set to \c true to enable mid-side encoding on stereo input. The
  90960. * number of channels must be 2 for this to have any effect. Set to
  90961. * \c false to use only independent channel coding.
  90962. *
  90963. * \default \c false
  90964. * \param encoder An encoder instance to set.
  90965. * \param value Flag value (see above).
  90966. * \assert
  90967. * \code encoder != NULL \endcode
  90968. * \retval FLAC__bool
  90969. * \c false if the encoder is already initialized, else \c true.
  90970. */
  90971. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90972. /** Set to \c true to enable adaptive switching between mid-side and
  90973. * left-right encoding on stereo input. Set to \c false to use
  90974. * exhaustive searching. Setting this to \c true requires
  90975. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  90976. * \c true in order to have any effect.
  90977. *
  90978. * \default \c false
  90979. * \param encoder An encoder instance to set.
  90980. * \param value Flag value (see above).
  90981. * \assert
  90982. * \code encoder != NULL \endcode
  90983. * \retval FLAC__bool
  90984. * \c false if the encoder is already initialized, else \c true.
  90985. */
  90986. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90987. /** Sets the apodization function(s) the encoder will use when windowing
  90988. * audio data for LPC analysis.
  90989. *
  90990. * The \a specification is a plain ASCII string which specifies exactly
  90991. * which functions to use. There may be more than one (up to 32),
  90992. * separated by \c ';' characters. Some functions take one or more
  90993. * comma-separated arguments in parentheses.
  90994. *
  90995. * The available functions are \c bartlett, \c bartlett_hann,
  90996. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  90997. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  90998. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  90999. *
  91000. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91001. * (0<STDDEV<=0.5).
  91002. *
  91003. * For \c tukey(P), P specifies the fraction of the window that is
  91004. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91005. * corresponds to \c hann.
  91006. *
  91007. * Example specifications are \c "blackman" or
  91008. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91009. *
  91010. * Any function that is specified erroneously is silently dropped. Up
  91011. * to 32 functions are kept, the rest are dropped. If the specification
  91012. * is empty the encoder defaults to \c "tukey(0.5)".
  91013. *
  91014. * When more than one function is specified, then for every subframe the
  91015. * encoder will try each of them separately and choose the window that
  91016. * results in the smallest compressed subframe.
  91017. *
  91018. * Note that each function specified causes the encoder to occupy a
  91019. * floating point array in which to store the window.
  91020. *
  91021. * \default \c "tukey(0.5)"
  91022. * \param encoder An encoder instance to set.
  91023. * \param specification See above.
  91024. * \assert
  91025. * \code encoder != NULL \endcode
  91026. * \code specification != NULL \endcode
  91027. * \retval FLAC__bool
  91028. * \c false if the encoder is already initialized, else \c true.
  91029. */
  91030. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91031. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91032. *
  91033. * \default \c 0
  91034. * \param encoder An encoder instance to set.
  91035. * \param value See above.
  91036. * \assert
  91037. * \code encoder != NULL \endcode
  91038. * \retval FLAC__bool
  91039. * \c false if the encoder is already initialized, else \c true.
  91040. */
  91041. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91042. /** Set the precision, in bits, of the quantized linear predictor
  91043. * coefficients, or \c 0 to let the encoder select it based on the
  91044. * blocksize.
  91045. *
  91046. * \note
  91047. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91048. * be less than 32.
  91049. *
  91050. * \default \c 0
  91051. * \param encoder An encoder instance to set.
  91052. * \param value See above.
  91053. * \assert
  91054. * \code encoder != NULL \endcode
  91055. * \retval FLAC__bool
  91056. * \c false if the encoder is already initialized, else \c true.
  91057. */
  91058. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91059. /** Set to \c false to use only the specified quantized linear predictor
  91060. * coefficient precision, or \c true to search neighboring precision
  91061. * values and use the best one.
  91062. *
  91063. * \default \c false
  91064. * \param encoder An encoder instance to set.
  91065. * \param value See above.
  91066. * \assert
  91067. * \code encoder != NULL \endcode
  91068. * \retval FLAC__bool
  91069. * \c false if the encoder is already initialized, else \c true.
  91070. */
  91071. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91072. /** Deprecated. Setting this value has no effect.
  91073. *
  91074. * \default \c false
  91075. * \param encoder An encoder instance to set.
  91076. * \param value See above.
  91077. * \assert
  91078. * \code encoder != NULL \endcode
  91079. * \retval FLAC__bool
  91080. * \c false if the encoder is already initialized, else \c true.
  91081. */
  91082. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91083. /** Set to \c false to let the encoder estimate the best model order
  91084. * based on the residual signal energy, or \c true to force the
  91085. * encoder to evaluate all order models and select the best.
  91086. *
  91087. * \default \c false
  91088. * \param encoder An encoder instance to set.
  91089. * \param value See above.
  91090. * \assert
  91091. * \code encoder != NULL \endcode
  91092. * \retval FLAC__bool
  91093. * \c false if the encoder is already initialized, else \c true.
  91094. */
  91095. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91096. /** Set the minimum partition order to search when coding the residual.
  91097. * This is used in tandem with
  91098. * FLAC__stream_encoder_set_max_residual_partition_order().
  91099. *
  91100. * The partition order determines the context size in the residual.
  91101. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91102. *
  91103. * Set both min and max values to \c 0 to force a single context,
  91104. * whose Rice parameter is based on the residual signal variance.
  91105. * Otherwise, set a min and max order, and the encoder will search
  91106. * all orders, using the mean of each context for its Rice parameter,
  91107. * and use the best.
  91108. *
  91109. * \default \c 0
  91110. * \param encoder An encoder instance to set.
  91111. * \param value See above.
  91112. * \assert
  91113. * \code encoder != NULL \endcode
  91114. * \retval FLAC__bool
  91115. * \c false if the encoder is already initialized, else \c true.
  91116. */
  91117. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91118. /** Set the maximum partition order to search when coding the residual.
  91119. * This is used in tandem with
  91120. * FLAC__stream_encoder_set_min_residual_partition_order().
  91121. *
  91122. * The partition order determines the context size in the residual.
  91123. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91124. *
  91125. * Set both min and max values to \c 0 to force a single context,
  91126. * whose Rice parameter is based on the residual signal variance.
  91127. * Otherwise, set a min and max order, and the encoder will search
  91128. * all orders, using the mean of each context for its Rice parameter,
  91129. * and use the best.
  91130. *
  91131. * \default \c 0
  91132. * \param encoder An encoder instance to set.
  91133. * \param value See above.
  91134. * \assert
  91135. * \code encoder != NULL \endcode
  91136. * \retval FLAC__bool
  91137. * \c false if the encoder is already initialized, else \c true.
  91138. */
  91139. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91140. /** Deprecated. Setting this value has no effect.
  91141. *
  91142. * \default \c 0
  91143. * \param encoder An encoder instance to set.
  91144. * \param value See above.
  91145. * \assert
  91146. * \code encoder != NULL \endcode
  91147. * \retval FLAC__bool
  91148. * \c false if the encoder is already initialized, else \c true.
  91149. */
  91150. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91151. /** Set an estimate of the total samples that will be encoded.
  91152. * This is merely an estimate and may be set to \c 0 if unknown.
  91153. * This value will be written to the STREAMINFO block before encoding,
  91154. * and can remove the need for the caller to rewrite the value later
  91155. * if the value is known before encoding.
  91156. *
  91157. * \default \c 0
  91158. * \param encoder An encoder instance to set.
  91159. * \param value See above.
  91160. * \assert
  91161. * \code encoder != NULL \endcode
  91162. * \retval FLAC__bool
  91163. * \c false if the encoder is already initialized, else \c true.
  91164. */
  91165. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91166. /** Set the metadata blocks to be emitted to the stream before encoding.
  91167. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91168. * array of pointers to metadata blocks. The array is non-const since
  91169. * the encoder may need to change the \a is_last flag inside them, and
  91170. * in some cases update seek point offsets. Otherwise, the encoder will
  91171. * not modify or free the blocks. It is up to the caller to free the
  91172. * metadata blocks after encoding finishes.
  91173. *
  91174. * \note
  91175. * The encoder stores only copies of the pointers in the \a metadata array;
  91176. * the metadata blocks themselves must survive at least until after
  91177. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91178. *
  91179. * \note
  91180. * The STREAMINFO block is always written and no STREAMINFO block may
  91181. * occur in the supplied array.
  91182. *
  91183. * \note
  91184. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91185. * in the \a metadata array, but the client has specified that it does not
  91186. * support seeking, then the SEEKTABLE will be written verbatim. However
  91187. * by itself this is not very useful as the client will not know the stream
  91188. * offsets for the seekpoints ahead of time. In order to get a proper
  91189. * seektable the client must support seeking. See next note.
  91190. *
  91191. * \note
  91192. * SEEKTABLE blocks are handled specially. Since you will not know
  91193. * the values for the seek point stream offsets, you should pass in
  91194. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91195. * required sample numbers (or placeholder points), with \c 0 for the
  91196. * \a frame_samples and \a stream_offset fields for each point. If the
  91197. * client has specified that it supports seeking by providing a seek
  91198. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91199. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91200. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91201. * then while it is encoding the encoder will fill the stream offsets in
  91202. * for you and when encoding is finished, it will seek back and write the
  91203. * real values into the SEEKTABLE block in the stream. There are helper
  91204. * routines for manipulating seektable template blocks; see metadata.h:
  91205. * FLAC__metadata_object_seektable_template_*(). If the client does
  91206. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91207. * will slow down or remove the ability to seek in the FLAC stream.
  91208. *
  91209. * \note
  91210. * The encoder instance \b will modify the first \c SEEKTABLE block
  91211. * as it transforms the template to a valid seektable while encoding,
  91212. * but it is still up to the caller to free all metadata blocks after
  91213. * encoding.
  91214. *
  91215. * \note
  91216. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91217. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91218. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91219. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91220. * block is present in the \a metadata array, libFLAC will write an
  91221. * empty one, containing only the vendor string.
  91222. *
  91223. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91224. * the second metadata block of the stream. The encoder already supplies
  91225. * the STREAMINFO block automatically. If \a metadata does not contain a
  91226. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91227. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91228. * first, the init function will reorder \a metadata by moving the
  91229. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91230. * blocks will remain as they were.
  91231. *
  91232. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91233. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91234. * return \c false.
  91235. *
  91236. * \default \c NULL, 0
  91237. * \param encoder An encoder instance to set.
  91238. * \param metadata See above.
  91239. * \param num_blocks See above.
  91240. * \assert
  91241. * \code encoder != NULL \endcode
  91242. * \retval FLAC__bool
  91243. * \c false if the encoder is already initialized, else \c true.
  91244. * \c false if the encoder is already initialized, or if
  91245. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  91246. */
  91247. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  91248. /** Get the current encoder state.
  91249. *
  91250. * \param encoder An encoder instance to query.
  91251. * \assert
  91252. * \code encoder != NULL \endcode
  91253. * \retval FLAC__StreamEncoderState
  91254. * The current encoder state.
  91255. */
  91256. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  91257. /** Get the state of the verify stream decoder.
  91258. * Useful when the stream encoder state is
  91259. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  91260. *
  91261. * \param encoder An encoder instance to query.
  91262. * \assert
  91263. * \code encoder != NULL \endcode
  91264. * \retval FLAC__StreamDecoderState
  91265. * The verify stream decoder state.
  91266. */
  91267. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  91268. /** Get the current encoder state as a C string.
  91269. * This version automatically resolves
  91270. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  91271. * verify decoder's state.
  91272. *
  91273. * \param encoder A encoder instance to query.
  91274. * \assert
  91275. * \code encoder != NULL \endcode
  91276. * \retval const char *
  91277. * The encoder state as a C string. Do not modify the contents.
  91278. */
  91279. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  91280. /** Get relevant values about the nature of a verify decoder error.
  91281. * Useful when the stream encoder state is
  91282. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  91283. * be addresses in which the stats will be returned, or NULL if value
  91284. * is not desired.
  91285. *
  91286. * \param encoder An encoder instance to query.
  91287. * \param absolute_sample The absolute sample number of the mismatch.
  91288. * \param frame_number The number of the frame in which the mismatch occurred.
  91289. * \param channel The channel in which the mismatch occurred.
  91290. * \param sample The number of the sample (relative to the frame) in
  91291. * which the mismatch occurred.
  91292. * \param expected The expected value for the sample in question.
  91293. * \param got The actual value returned by the decoder.
  91294. * \assert
  91295. * \code encoder != NULL \endcode
  91296. */
  91297. 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);
  91298. /** Get the "verify" flag.
  91299. *
  91300. * \param encoder An encoder instance to query.
  91301. * \assert
  91302. * \code encoder != NULL \endcode
  91303. * \retval FLAC__bool
  91304. * See FLAC__stream_encoder_set_verify().
  91305. */
  91306. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91307. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91308. *
  91309. * \param encoder An encoder instance to query.
  91310. * \assert
  91311. * \code encoder != NULL \endcode
  91312. * \retval FLAC__bool
  91313. * See FLAC__stream_encoder_set_streamable_subset().
  91314. */
  91315. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91316. /** Get the number of input channels being processed.
  91317. *
  91318. * \param encoder An encoder instance to query.
  91319. * \assert
  91320. * \code encoder != NULL \endcode
  91321. * \retval unsigned
  91322. * See FLAC__stream_encoder_set_channels().
  91323. */
  91324. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91325. /** Get the input sample resolution setting.
  91326. *
  91327. * \param encoder An encoder instance to query.
  91328. * \assert
  91329. * \code encoder != NULL \endcode
  91330. * \retval unsigned
  91331. * See FLAC__stream_encoder_set_bits_per_sample().
  91332. */
  91333. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91334. /** Get the input sample rate setting.
  91335. *
  91336. * \param encoder An encoder instance to query.
  91337. * \assert
  91338. * \code encoder != NULL \endcode
  91339. * \retval unsigned
  91340. * See FLAC__stream_encoder_set_sample_rate().
  91341. */
  91342. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91343. /** Get the blocksize setting.
  91344. *
  91345. * \param encoder An encoder instance to query.
  91346. * \assert
  91347. * \code encoder != NULL \endcode
  91348. * \retval unsigned
  91349. * See FLAC__stream_encoder_set_blocksize().
  91350. */
  91351. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91352. /** Get the "mid/side stereo coding" flag.
  91353. *
  91354. * \param encoder An encoder instance to query.
  91355. * \assert
  91356. * \code encoder != NULL \endcode
  91357. * \retval FLAC__bool
  91358. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  91359. */
  91360. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91361. /** Get the "adaptive mid/side switching" flag.
  91362. *
  91363. * \param encoder An encoder instance to query.
  91364. * \assert
  91365. * \code encoder != NULL \endcode
  91366. * \retval FLAC__bool
  91367. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  91368. */
  91369. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91370. /** Get the maximum LPC order setting.
  91371. *
  91372. * \param encoder An encoder instance to query.
  91373. * \assert
  91374. * \code encoder != NULL \endcode
  91375. * \retval unsigned
  91376. * See FLAC__stream_encoder_set_max_lpc_order().
  91377. */
  91378. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  91379. /** Get the quantized linear predictor coefficient precision setting.
  91380. *
  91381. * \param encoder An encoder instance to query.
  91382. * \assert
  91383. * \code encoder != NULL \endcode
  91384. * \retval unsigned
  91385. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  91386. */
  91387. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  91388. /** Get the qlp coefficient precision search flag.
  91389. *
  91390. * \param encoder An encoder instance to query.
  91391. * \assert
  91392. * \code encoder != NULL \endcode
  91393. * \retval FLAC__bool
  91394. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  91395. */
  91396. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  91397. /** Get the "escape coding" flag.
  91398. *
  91399. * \param encoder An encoder instance to query.
  91400. * \assert
  91401. * \code encoder != NULL \endcode
  91402. * \retval FLAC__bool
  91403. * See FLAC__stream_encoder_set_do_escape_coding().
  91404. */
  91405. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  91406. /** Get the exhaustive model search flag.
  91407. *
  91408. * \param encoder An encoder instance to query.
  91409. * \assert
  91410. * \code encoder != NULL \endcode
  91411. * \retval FLAC__bool
  91412. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  91413. */
  91414. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  91415. /** Get the minimum residual partition order setting.
  91416. *
  91417. * \param encoder An encoder instance to query.
  91418. * \assert
  91419. * \code encoder != NULL \endcode
  91420. * \retval unsigned
  91421. * See FLAC__stream_encoder_set_min_residual_partition_order().
  91422. */
  91423. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91424. /** Get maximum residual partition order setting.
  91425. *
  91426. * \param encoder An encoder instance to query.
  91427. * \assert
  91428. * \code encoder != NULL \endcode
  91429. * \retval unsigned
  91430. * See FLAC__stream_encoder_set_max_residual_partition_order().
  91431. */
  91432. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91433. /** Get the Rice parameter search distance setting.
  91434. *
  91435. * \param encoder An encoder instance to query.
  91436. * \assert
  91437. * \code encoder != NULL \endcode
  91438. * \retval unsigned
  91439. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  91440. */
  91441. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  91442. /** Get the previously set estimate of the total samples to be encoded.
  91443. * The encoder merely mimics back the value given to
  91444. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  91445. * other way of knowing how many samples the client will encode.
  91446. *
  91447. * \param encoder An encoder instance to set.
  91448. * \assert
  91449. * \code encoder != NULL \endcode
  91450. * \retval FLAC__uint64
  91451. * See FLAC__stream_encoder_get_total_samples_estimate().
  91452. */
  91453. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  91454. /** Initialize the encoder instance to encode native FLAC streams.
  91455. *
  91456. * This flavor of initialization sets up the encoder to encode to a
  91457. * native FLAC stream. I/O is performed via callbacks to the client.
  91458. * For encoding to a plain file via filename or open \c FILE*,
  91459. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  91460. * provide a simpler interface.
  91461. *
  91462. * This function should be called after FLAC__stream_encoder_new() and
  91463. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91464. * or FLAC__stream_encoder_process_interleaved().
  91465. * initialization succeeded.
  91466. *
  91467. * The call to FLAC__stream_encoder_init_stream() currently will also
  91468. * immediately call the write callback several times, once with the \c fLaC
  91469. * signature, and once for each encoded metadata block.
  91470. *
  91471. * \param encoder An uninitialized encoder instance.
  91472. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91473. * pointer must not be \c NULL.
  91474. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91475. * pointer may be \c NULL if seeking is not
  91476. * supported. The encoder uses seeking to go back
  91477. * and write some some stream statistics to the
  91478. * STREAMINFO block; this is recommended but not
  91479. * necessary to create a valid FLAC stream. If
  91480. * \a seek_callback is not \c NULL then a
  91481. * \a tell_callback must also be supplied.
  91482. * Alternatively, a dummy seek callback that just
  91483. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91484. * may also be supplied, all though this is slightly
  91485. * less efficient for the encoder.
  91486. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91487. * pointer may be \c NULL if seeking is not
  91488. * supported. If \a seek_callback is \c NULL then
  91489. * this argument will be ignored. If
  91490. * \a seek_callback is not \c NULL then a
  91491. * \a tell_callback must also be supplied.
  91492. * Alternatively, a dummy tell callback that just
  91493. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91494. * may also be supplied, all though this is slightly
  91495. * less efficient for the encoder.
  91496. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91497. * pointer may be \c NULL if the callback is not
  91498. * desired. If the client provides a seek callback,
  91499. * this function is not necessary as the encoder
  91500. * will automatically seek back and update the
  91501. * STREAMINFO block. It may also be \c NULL if the
  91502. * client does not support seeking, since it will
  91503. * have no way of going back to update the
  91504. * STREAMINFO. However the client can still supply
  91505. * a callback if it would like to know the details
  91506. * from the STREAMINFO.
  91507. * \param client_data This value will be supplied to callbacks in their
  91508. * \a client_data argument.
  91509. * \assert
  91510. * \code encoder != NULL \endcode
  91511. * \retval FLAC__StreamEncoderInitStatus
  91512. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91513. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91514. */
  91515. 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);
  91516. /** Initialize the encoder instance to encode Ogg FLAC streams.
  91517. *
  91518. * This flavor of initialization sets up the encoder to encode to a FLAC
  91519. * stream in an Ogg container. I/O is performed via callbacks to the
  91520. * client. For encoding to a plain file via filename or open \c FILE*,
  91521. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  91522. * provide a simpler interface.
  91523. *
  91524. * This function should be called after FLAC__stream_encoder_new() and
  91525. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91526. * or FLAC__stream_encoder_process_interleaved().
  91527. * initialization succeeded.
  91528. *
  91529. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  91530. * immediately call the write callback several times to write the metadata
  91531. * packets.
  91532. *
  91533. * \param encoder An uninitialized encoder instance.
  91534. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  91535. * pointer must not be \c NULL if \a seek_callback
  91536. * is non-NULL since they are both needed to be
  91537. * able to write data back to the Ogg FLAC stream
  91538. * in the post-encode phase.
  91539. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91540. * pointer must not be \c NULL.
  91541. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91542. * pointer may be \c NULL if seeking is not
  91543. * supported. The encoder uses seeking to go back
  91544. * and write some some stream statistics to the
  91545. * STREAMINFO block; this is recommended but not
  91546. * necessary to create a valid FLAC stream. If
  91547. * \a seek_callback is not \c NULL then a
  91548. * \a tell_callback must also be supplied.
  91549. * Alternatively, a dummy seek callback that just
  91550. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91551. * may also be supplied, all though this is slightly
  91552. * less efficient for the encoder.
  91553. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91554. * pointer may be \c NULL if seeking is not
  91555. * supported. If \a seek_callback is \c NULL then
  91556. * this argument will be ignored. If
  91557. * \a seek_callback is not \c NULL then a
  91558. * \a tell_callback must also be supplied.
  91559. * Alternatively, a dummy tell callback that just
  91560. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91561. * may also be supplied, all though this is slightly
  91562. * less efficient for the encoder.
  91563. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91564. * pointer may be \c NULL if the callback is not
  91565. * desired. If the client provides a seek callback,
  91566. * this function is not necessary as the encoder
  91567. * will automatically seek back and update the
  91568. * STREAMINFO block. It may also be \c NULL if the
  91569. * client does not support seeking, since it will
  91570. * have no way of going back to update the
  91571. * STREAMINFO. However the client can still supply
  91572. * a callback if it would like to know the details
  91573. * from the STREAMINFO.
  91574. * \param client_data This value will be supplied to callbacks in their
  91575. * \a client_data argument.
  91576. * \assert
  91577. * \code encoder != NULL \endcode
  91578. * \retval FLAC__StreamEncoderInitStatus
  91579. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91580. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91581. */
  91582. 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);
  91583. /** Initialize the encoder instance to encode native FLAC files.
  91584. *
  91585. * This flavor of initialization sets up the encoder to encode to a
  91586. * plain native FLAC file. For non-stdio streams, you must use
  91587. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  91588. *
  91589. * This function should be called after FLAC__stream_encoder_new() and
  91590. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91591. * or FLAC__stream_encoder_process_interleaved().
  91592. * initialization succeeded.
  91593. *
  91594. * \param encoder An uninitialized encoder instance.
  91595. * \param file An open file. The file should have been opened
  91596. * with mode \c "w+b" and rewound. The file
  91597. * becomes owned by the encoder and should not be
  91598. * manipulated by the client while encoding.
  91599. * Unless \a file is \c stdout, it will be closed
  91600. * when FLAC__stream_encoder_finish() is called.
  91601. * Note however that a proper SEEKTABLE cannot be
  91602. * created when encoding to \c stdout since it is
  91603. * not seekable.
  91604. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91605. * pointer may be \c NULL if the callback is not
  91606. * desired.
  91607. * \param client_data This value will be supplied to callbacks in their
  91608. * \a client_data argument.
  91609. * \assert
  91610. * \code encoder != NULL \endcode
  91611. * \code file != NULL \endcode
  91612. * \retval FLAC__StreamEncoderInitStatus
  91613. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91614. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91615. */
  91616. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91617. /** Initialize the encoder instance to encode Ogg FLAC files.
  91618. *
  91619. * This flavor of initialization sets up the encoder to encode to a
  91620. * plain Ogg FLAC file. For non-stdio streams, you must use
  91621. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  91622. *
  91623. * This function should be called after FLAC__stream_encoder_new() and
  91624. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91625. * or FLAC__stream_encoder_process_interleaved().
  91626. * initialization succeeded.
  91627. *
  91628. * \param encoder An uninitialized encoder instance.
  91629. * \param file An open file. The file should have been opened
  91630. * with mode \c "w+b" and rewound. The file
  91631. * becomes owned by the encoder and should not be
  91632. * manipulated by the client while encoding.
  91633. * Unless \a file is \c stdout, it will be closed
  91634. * when FLAC__stream_encoder_finish() is called.
  91635. * Note however that a proper SEEKTABLE cannot be
  91636. * created when encoding to \c stdout since it is
  91637. * not seekable.
  91638. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91639. * pointer may be \c NULL if the callback is not
  91640. * desired.
  91641. * \param client_data This value will be supplied to callbacks in their
  91642. * \a client_data argument.
  91643. * \assert
  91644. * \code encoder != NULL \endcode
  91645. * \code file != NULL \endcode
  91646. * \retval FLAC__StreamEncoderInitStatus
  91647. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91648. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91649. */
  91650. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91651. /** Initialize the encoder instance to encode native FLAC files.
  91652. *
  91653. * This flavor of initialization sets up the encoder to encode to a plain
  91654. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91655. * with Unicode filenames on Windows), you must use
  91656. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  91657. * and provide callbacks for the I/O.
  91658. *
  91659. * This function should be called after FLAC__stream_encoder_new() and
  91660. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91661. * or FLAC__stream_encoder_process_interleaved().
  91662. * initialization succeeded.
  91663. *
  91664. * \param encoder An uninitialized encoder instance.
  91665. * \param filename The name of the file to encode to. The file will
  91666. * be opened with fopen(). Use \c NULL to encode to
  91667. * \c stdout. Note however that a proper SEEKTABLE
  91668. * cannot be created when encoding to \c stdout since
  91669. * it is not seekable.
  91670. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91671. * pointer may be \c NULL if the callback is not
  91672. * desired.
  91673. * \param client_data This value will be supplied to callbacks in their
  91674. * \a client_data argument.
  91675. * \assert
  91676. * \code encoder != NULL \endcode
  91677. * \retval FLAC__StreamEncoderInitStatus
  91678. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91679. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91680. */
  91681. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91682. /** Initialize the encoder instance to encode Ogg FLAC files.
  91683. *
  91684. * This flavor of initialization sets up the encoder to encode to a plain
  91685. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91686. * with Unicode filenames on Windows), you must use
  91687. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  91688. * and provide callbacks for the I/O.
  91689. *
  91690. * This function should be called after FLAC__stream_encoder_new() and
  91691. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91692. * or FLAC__stream_encoder_process_interleaved().
  91693. * initialization succeeded.
  91694. *
  91695. * \param encoder An uninitialized encoder instance.
  91696. * \param filename The name of the file to encode to. The file will
  91697. * be opened with fopen(). Use \c NULL to encode to
  91698. * \c stdout. Note however that a proper SEEKTABLE
  91699. * cannot be created when encoding to \c stdout since
  91700. * it is not seekable.
  91701. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91702. * pointer may be \c NULL if the callback is not
  91703. * desired.
  91704. * \param client_data This value will be supplied to callbacks in their
  91705. * \a client_data argument.
  91706. * \assert
  91707. * \code encoder != NULL \endcode
  91708. * \retval FLAC__StreamEncoderInitStatus
  91709. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91710. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91711. */
  91712. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91713. /** Finish the encoding process.
  91714. * Flushes the encoding buffer, releases resources, resets the encoder
  91715. * settings to their defaults, and returns the encoder state to
  91716. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  91717. * one or more write callbacks before returning, and will generate
  91718. * a metadata callback.
  91719. *
  91720. * Note that in the course of processing the last frame, errors can
  91721. * occur, so the caller should be sure to check the return value to
  91722. * ensure the file was encoded properly.
  91723. *
  91724. * In the event of a prematurely-terminated encode, it is not strictly
  91725. * necessary to call this immediately before FLAC__stream_encoder_delete()
  91726. * but it is good practice to match every FLAC__stream_encoder_init_*()
  91727. * with a FLAC__stream_encoder_finish().
  91728. *
  91729. * \param encoder An uninitialized encoder instance.
  91730. * \assert
  91731. * \code encoder != NULL \endcode
  91732. * \retval FLAC__bool
  91733. * \c false if an error occurred processing the last frame; or if verify
  91734. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  91735. * verify mismatch; else \c true. If \c false, caller should check the
  91736. * state with FLAC__stream_encoder_get_state() for more information
  91737. * about the error.
  91738. */
  91739. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  91740. /** Submit data for encoding.
  91741. * This version allows you to supply the input data via an array of
  91742. * pointers, each pointer pointing to an array of \a samples samples
  91743. * representing one channel. The samples need not be block-aligned,
  91744. * but each channel should have the same number of samples. Each sample
  91745. * should be a signed integer, right-justified to the resolution set by
  91746. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  91747. * resolution is 16 bits per sample, the samples should all be in the
  91748. * range [-32768,32767].
  91749. *
  91750. * For applications where channel order is important, channels must
  91751. * follow the order as described in the
  91752. * <A HREF="../format.html#frame_header">frame header</A>.
  91753. *
  91754. * \param encoder An initialized encoder instance in the OK state.
  91755. * \param buffer An array of pointers to each channel's signal.
  91756. * \param samples The number of samples in one channel.
  91757. * \assert
  91758. * \code encoder != NULL \endcode
  91759. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  91760. * \retval FLAC__bool
  91761. * \c true if successful, else \c false; in this case, check the
  91762. * encoder state with FLAC__stream_encoder_get_state() to see what
  91763. * went wrong.
  91764. */
  91765. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  91766. /** Submit data for encoding.
  91767. * This version allows you to supply the input data where the channels
  91768. * are interleaved into a single array (i.e. channel0_sample0,
  91769. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  91770. * The samples need not be block-aligned but they must be
  91771. * sample-aligned, i.e. the first value should be channel0_sample0
  91772. * and the last value channelN_sampleM. Each sample should be a signed
  91773. * integer, right-justified to the resolution set by
  91774. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  91775. * resolution is 16 bits per sample, the samples should all be in the
  91776. * range [-32768,32767].
  91777. *
  91778. * For applications where channel order is important, channels must
  91779. * follow the order as described in the
  91780. * <A HREF="../format.html#frame_header">frame header</A>.
  91781. *
  91782. * \param encoder An initialized encoder instance in the OK state.
  91783. * \param buffer An array of channel-interleaved data (see above).
  91784. * \param samples The number of samples in one channel, the same as for
  91785. * FLAC__stream_encoder_process(). For example, if
  91786. * encoding two channels, \c 1000 \a samples corresponds
  91787. * to a \a buffer of 2000 values.
  91788. * \assert
  91789. * \code encoder != NULL \endcode
  91790. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  91791. * \retval FLAC__bool
  91792. * \c true if successful, else \c false; in this case, check the
  91793. * encoder state with FLAC__stream_encoder_get_state() to see what
  91794. * went wrong.
  91795. */
  91796. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  91797. /* \} */
  91798. #ifdef __cplusplus
  91799. }
  91800. #endif
  91801. #endif
  91802. /*** End of inlined file: stream_encoder.h ***/
  91803. #ifdef _MSC_VER
  91804. /* OPT: an MSVC built-in would be better */
  91805. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  91806. {
  91807. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  91808. return (x>>16) | (x<<16);
  91809. }
  91810. #endif
  91811. #if defined(_MSC_VER) && defined(_X86_)
  91812. /* OPT: an MSVC built-in would be better */
  91813. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  91814. {
  91815. __asm {
  91816. mov edx, start
  91817. mov ecx, len
  91818. test ecx, ecx
  91819. loop1:
  91820. jz done1
  91821. mov eax, [edx]
  91822. bswap eax
  91823. mov [edx], eax
  91824. add edx, 4
  91825. dec ecx
  91826. jmp short loop1
  91827. done1:
  91828. }
  91829. }
  91830. #endif
  91831. /** \mainpage
  91832. *
  91833. * \section intro Introduction
  91834. *
  91835. * This is the documentation for the FLAC C and C++ APIs. It is
  91836. * highly interconnected; this introduction should give you a top
  91837. * level idea of the structure and how to find the information you
  91838. * need. As a prerequisite you should have at least a basic
  91839. * knowledge of the FLAC format, documented
  91840. * <A HREF="../format.html">here</A>.
  91841. *
  91842. * \section c_api FLAC C API
  91843. *
  91844. * The FLAC C API is the interface to libFLAC, a set of structures
  91845. * describing the components of FLAC streams, and functions for
  91846. * encoding and decoding streams, as well as manipulating FLAC
  91847. * metadata in files. The public include files will be installed
  91848. * in your include area (for example /usr/include/FLAC/...).
  91849. *
  91850. * By writing a little code and linking against libFLAC, it is
  91851. * relatively easy to add FLAC support to another program. The
  91852. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  91853. * Complete source code of libFLAC as well as the command-line
  91854. * encoder and plugins is available and is a useful source of
  91855. * examples.
  91856. *
  91857. * Aside from encoders and decoders, libFLAC provides a powerful
  91858. * metadata interface for manipulating metadata in FLAC files. It
  91859. * allows the user to add, delete, and modify FLAC metadata blocks
  91860. * and it can automatically take advantage of PADDING blocks to avoid
  91861. * rewriting the entire FLAC file when changing the size of the
  91862. * metadata.
  91863. *
  91864. * libFLAC usually only requires the standard C library and C math
  91865. * library. In particular, threading is not used so there is no
  91866. * dependency on a thread library. However, libFLAC does not use
  91867. * global variables and should be thread-safe.
  91868. *
  91869. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  91870. * However the metadata editing interfaces currently have limited
  91871. * read-only support for Ogg FLAC files.
  91872. *
  91873. * \section cpp_api FLAC C++ API
  91874. *
  91875. * The FLAC C++ API is a set of classes that encapsulate the
  91876. * structures and functions in libFLAC. They provide slightly more
  91877. * functionality with respect to metadata but are otherwise
  91878. * equivalent. For the most part, they share the same usage as
  91879. * their counterparts in libFLAC, and the FLAC C API documentation
  91880. * can be used as a supplement. The public include files
  91881. * for the C++ API will be installed in your include area (for
  91882. * example /usr/include/FLAC++/...).
  91883. *
  91884. * libFLAC++ is also licensed under
  91885. * <A HREF="../license.html">Xiph's BSD license</A>.
  91886. *
  91887. * \section getting_started Getting Started
  91888. *
  91889. * A good starting point for learning the API is to browse through
  91890. * the <A HREF="modules.html">modules</A>. Modules are logical
  91891. * groupings of related functions or classes, which correspond roughly
  91892. * to header files or sections of header files. Each module includes a
  91893. * detailed description of the general usage of its functions or
  91894. * classes.
  91895. *
  91896. * From there you can go on to look at the documentation of
  91897. * individual functions. You can see different views of the individual
  91898. * functions through the links in top bar across this page.
  91899. *
  91900. * If you prefer a more hands-on approach, you can jump right to some
  91901. * <A HREF="../documentation_example_code.html">example code</A>.
  91902. *
  91903. * \section porting_guide Porting Guide
  91904. *
  91905. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  91906. * has been introduced which gives detailed instructions on how to
  91907. * port your code to newer versions of FLAC.
  91908. *
  91909. * \section embedded_developers Embedded Developers
  91910. *
  91911. * libFLAC has grown larger over time as more functionality has been
  91912. * included, but much of it may be unnecessary for a particular embedded
  91913. * implementation. Unused parts may be pruned by some simple editing of
  91914. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  91915. * metadata interface are all independent from each other.
  91916. *
  91917. * It is easiest to just describe the dependencies:
  91918. *
  91919. * - All modules depend on the \link flac_format Format \endlink module.
  91920. * - The decoders and encoders depend on the bitbuffer.
  91921. * - The decoder is independent of the encoder. The encoder uses the
  91922. * decoder because of the verify feature, but this can be removed if
  91923. * not needed.
  91924. * - Parts of the metadata interface require the stream decoder (but not
  91925. * the encoder).
  91926. * - Ogg support is selectable through the compile time macro
  91927. * \c FLAC__HAS_OGG.
  91928. *
  91929. * For example, if your application only requires the stream decoder, no
  91930. * encoder, and no metadata interface, you can remove the stream encoder
  91931. * and the metadata interface, which will greatly reduce the size of the
  91932. * library.
  91933. *
  91934. * Also, there are several places in the libFLAC code with comments marked
  91935. * with "OPT:" where a #define can be changed to enable code that might be
  91936. * faster on a specific platform. Experimenting with these can yield faster
  91937. * binaries.
  91938. */
  91939. /** \defgroup porting Porting Guide for New Versions
  91940. *
  91941. * This module describes differences in the library interfaces from
  91942. * version to version. It assists in the porting of code that uses
  91943. * the libraries to newer versions of FLAC.
  91944. *
  91945. * One simple facility for making porting easier that has been added
  91946. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  91947. * library's includes (e.g. \c include/FLAC/export.h). The
  91948. * \c #defines mirror the libraries'
  91949. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  91950. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  91951. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  91952. * These can be used to support multiple versions of an API during the
  91953. * transition phase, e.g.
  91954. *
  91955. * \code
  91956. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  91957. * legacy code
  91958. * #else
  91959. * new code
  91960. * #endif
  91961. * \endcode
  91962. *
  91963. * The the source will work for multiple versions and the legacy code can
  91964. * easily be removed when the transition is complete.
  91965. *
  91966. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  91967. * include/FLAC/export.h), which can be used to determine whether or not
  91968. * the library has been compiled with support for Ogg FLAC. This is
  91969. * simpler than trying to call an Ogg init function and catching the
  91970. * error.
  91971. */
  91972. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  91973. * \ingroup porting
  91974. *
  91975. * \brief
  91976. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  91977. *
  91978. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  91979. * been simplified. First, libOggFLAC has been merged into libFLAC and
  91980. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  91981. * decoding layers and three encoding layers have been merged into a
  91982. * single stream decoder and stream encoder. That is, the functionality
  91983. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  91984. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  91985. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  91986. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  91987. * is there is now a single API that can be used to encode or decode
  91988. * streams to/from native FLAC or Ogg FLAC and the single API can work
  91989. * on both seekable and non-seekable streams.
  91990. *
  91991. * Instead of creating an encoder or decoder of a certain layer, now the
  91992. * client will always create a FLAC__StreamEncoder or
  91993. * FLAC__StreamDecoder. The old layers are now differentiated by the
  91994. * initialization function. For example, for the decoder,
  91995. * FLAC__stream_decoder_init() has been replaced by
  91996. * FLAC__stream_decoder_init_stream(). This init function takes
  91997. * callbacks for the I/O, and the seeking callbacks are optional. This
  91998. * allows the client to use the same object for seekable and
  91999. * non-seekable streams. For decoding a FLAC file directly, the client
  92000. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92001. * and fewer callbacks; most of the other callbacks are supplied
  92002. * internally. For situations where fopen()ing by filename is not
  92003. * possible (e.g. Unicode filenames on Windows) the client can instead
  92004. * open the file itself and supply the FILE* to
  92005. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92006. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92007. * Since the callbacks and client data are now passed to the init
  92008. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92009. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92010. * rest of the calls to the decoder are the same as before.
  92011. *
  92012. * There are counterpart init functions for Ogg FLAC, e.g.
  92013. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92014. * and callbacks are the same as for native FLAC.
  92015. *
  92016. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92017. * been set up like so:
  92018. *
  92019. * \code
  92020. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92021. * if(decoder == NULL) do_something;
  92022. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92023. * [... other settings ...]
  92024. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92025. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92026. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92027. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92028. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92029. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92030. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92031. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92032. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92033. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92034. * \endcode
  92035. *
  92036. * In FLAC 1.1.3 it is like this:
  92037. *
  92038. * \code
  92039. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92040. * if(decoder == NULL) do_something;
  92041. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92042. * [... other settings ...]
  92043. * if(FLAC__stream_decoder_init_stream(
  92044. * decoder,
  92045. * my_read_callback,
  92046. * my_seek_callback, // or NULL
  92047. * my_tell_callback, // or NULL
  92048. * my_length_callback, // or NULL
  92049. * my_eof_callback, // or NULL
  92050. * my_write_callback,
  92051. * my_metadata_callback, // or NULL
  92052. * my_error_callback,
  92053. * my_client_data
  92054. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92055. * \endcode
  92056. *
  92057. * or you could do;
  92058. *
  92059. * \code
  92060. * [...]
  92061. * FILE *file = fopen("somefile.flac","rb");
  92062. * if(file == NULL) do_somthing;
  92063. * if(FLAC__stream_decoder_init_FILE(
  92064. * decoder,
  92065. * file,
  92066. * my_write_callback,
  92067. * my_metadata_callback, // or NULL
  92068. * my_error_callback,
  92069. * my_client_data
  92070. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92071. * \endcode
  92072. *
  92073. * or just:
  92074. *
  92075. * \code
  92076. * [...]
  92077. * if(FLAC__stream_decoder_init_file(
  92078. * decoder,
  92079. * "somefile.flac",
  92080. * my_write_callback,
  92081. * my_metadata_callback, // or NULL
  92082. * my_error_callback,
  92083. * my_client_data
  92084. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92085. * \endcode
  92086. *
  92087. * Another small change to the decoder is in how it handles unparseable
  92088. * streams. Before, when the decoder found an unparseable stream
  92089. * (reserved for when the decoder encounters a stream from a future
  92090. * encoder that it can't parse), it changed the state to
  92091. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92092. * drops sync and calls the error callback with a new error code
  92093. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92094. * more robust. If your error callback does not discriminate on the the
  92095. * error state, your code does not need to be changed.
  92096. *
  92097. * The encoder now has a new setting:
  92098. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92099. * method used to window the data before LPC analysis. You only need to
  92100. * add a call to this function if the default is not suitable. There
  92101. * are also two new convenience functions that may be useful:
  92102. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92103. * FLAC__metadata_get_cuesheet().
  92104. *
  92105. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92106. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92107. * is now \c size_t instead of \c unsigned.
  92108. */
  92109. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92110. * \ingroup porting
  92111. *
  92112. * \brief
  92113. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92114. *
  92115. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92116. * There was a slight change in the implementation of
  92117. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92118. * of the \a metadata array of pointers so the client no longer needs
  92119. * to maintain it after the call. The objects themselves that are
  92120. * pointed to by the array are still not copied though and must be
  92121. * maintained until the call to FLAC__stream_encoder_finish().
  92122. */
  92123. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92124. * \ingroup porting
  92125. *
  92126. * \brief
  92127. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92128. *
  92129. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92130. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92131. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92132. *
  92133. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92134. * has changed to reflect the conversion of one of the reserved bits
  92135. * into active use. It used to be \c 2 and now is \c 1. However the
  92136. * FLAC frame header length has not changed, so to skip the proper
  92137. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92138. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92139. */
  92140. /** \defgroup flac FLAC C API
  92141. *
  92142. * The FLAC C API is the interface to libFLAC, a set of structures
  92143. * describing the components of FLAC streams, and functions for
  92144. * encoding and decoding streams, as well as manipulating FLAC
  92145. * metadata in files.
  92146. *
  92147. * You should start with the format components as all other modules
  92148. * are dependent on it.
  92149. */
  92150. #endif
  92151. /*** End of inlined file: all.h ***/
  92152. /*** Start of inlined file: bitmath.c ***/
  92153. /*** Start of inlined file: juce_FlacHeader.h ***/
  92154. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92155. // tasks..
  92156. #define VERSION "1.2.1"
  92157. #define FLAC__NO_DLL 1
  92158. #if JUCE_MSVC
  92159. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92160. #endif
  92161. #if JUCE_MAC
  92162. #define FLAC__SYS_DARWIN 1
  92163. #endif
  92164. /*** End of inlined file: juce_FlacHeader.h ***/
  92165. #if JUCE_USE_FLAC
  92166. #if HAVE_CONFIG_H
  92167. # include <config.h>
  92168. #endif
  92169. /*** Start of inlined file: bitmath.h ***/
  92170. #ifndef FLAC__PRIVATE__BITMATH_H
  92171. #define FLAC__PRIVATE__BITMATH_H
  92172. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92173. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92174. unsigned FLAC__bitmath_silog2(int v);
  92175. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92176. #endif
  92177. /*** End of inlined file: bitmath.h ***/
  92178. /* An example of what FLAC__bitmath_ilog2() computes:
  92179. *
  92180. * ilog2( 0) = assertion failure
  92181. * ilog2( 1) = 0
  92182. * ilog2( 2) = 1
  92183. * ilog2( 3) = 1
  92184. * ilog2( 4) = 2
  92185. * ilog2( 5) = 2
  92186. * ilog2( 6) = 2
  92187. * ilog2( 7) = 2
  92188. * ilog2( 8) = 3
  92189. * ilog2( 9) = 3
  92190. * ilog2(10) = 3
  92191. * ilog2(11) = 3
  92192. * ilog2(12) = 3
  92193. * ilog2(13) = 3
  92194. * ilog2(14) = 3
  92195. * ilog2(15) = 3
  92196. * ilog2(16) = 4
  92197. * ilog2(17) = 4
  92198. * ilog2(18) = 4
  92199. */
  92200. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92201. {
  92202. unsigned l = 0;
  92203. FLAC__ASSERT(v > 0);
  92204. while(v >>= 1)
  92205. l++;
  92206. return l;
  92207. }
  92208. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92209. {
  92210. unsigned l = 0;
  92211. FLAC__ASSERT(v > 0);
  92212. while(v >>= 1)
  92213. l++;
  92214. return l;
  92215. }
  92216. /* An example of what FLAC__bitmath_silog2() computes:
  92217. *
  92218. * silog2(-10) = 5
  92219. * silog2(- 9) = 5
  92220. * silog2(- 8) = 4
  92221. * silog2(- 7) = 4
  92222. * silog2(- 6) = 4
  92223. * silog2(- 5) = 4
  92224. * silog2(- 4) = 3
  92225. * silog2(- 3) = 3
  92226. * silog2(- 2) = 2
  92227. * silog2(- 1) = 2
  92228. * silog2( 0) = 0
  92229. * silog2( 1) = 2
  92230. * silog2( 2) = 3
  92231. * silog2( 3) = 3
  92232. * silog2( 4) = 4
  92233. * silog2( 5) = 4
  92234. * silog2( 6) = 4
  92235. * silog2( 7) = 4
  92236. * silog2( 8) = 5
  92237. * silog2( 9) = 5
  92238. * silog2( 10) = 5
  92239. */
  92240. unsigned FLAC__bitmath_silog2(int v)
  92241. {
  92242. while(1) {
  92243. if(v == 0) {
  92244. return 0;
  92245. }
  92246. else if(v > 0) {
  92247. unsigned l = 0;
  92248. while(v) {
  92249. l++;
  92250. v >>= 1;
  92251. }
  92252. return l+1;
  92253. }
  92254. else if(v == -1) {
  92255. return 2;
  92256. }
  92257. else {
  92258. v++;
  92259. v = -v;
  92260. }
  92261. }
  92262. }
  92263. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  92264. {
  92265. while(1) {
  92266. if(v == 0) {
  92267. return 0;
  92268. }
  92269. else if(v > 0) {
  92270. unsigned l = 0;
  92271. while(v) {
  92272. l++;
  92273. v >>= 1;
  92274. }
  92275. return l+1;
  92276. }
  92277. else if(v == -1) {
  92278. return 2;
  92279. }
  92280. else {
  92281. v++;
  92282. v = -v;
  92283. }
  92284. }
  92285. }
  92286. #endif
  92287. /*** End of inlined file: bitmath.c ***/
  92288. /*** Start of inlined file: bitreader.c ***/
  92289. /*** Start of inlined file: juce_FlacHeader.h ***/
  92290. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92291. // tasks..
  92292. #define VERSION "1.2.1"
  92293. #define FLAC__NO_DLL 1
  92294. #if JUCE_MSVC
  92295. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92296. #endif
  92297. #if JUCE_MAC
  92298. #define FLAC__SYS_DARWIN 1
  92299. #endif
  92300. /*** End of inlined file: juce_FlacHeader.h ***/
  92301. #if JUCE_USE_FLAC
  92302. #if HAVE_CONFIG_H
  92303. # include <config.h>
  92304. #endif
  92305. #include <stdlib.h> /* for malloc() */
  92306. #include <string.h> /* for memcpy(), memset() */
  92307. #ifdef _MSC_VER
  92308. #include <winsock.h> /* for ntohl() */
  92309. #elif defined FLAC__SYS_DARWIN
  92310. #include <machine/endian.h> /* for ntohl() */
  92311. #elif defined __MINGW32__
  92312. #include <winsock.h> /* for ntohl() */
  92313. #else
  92314. #include <netinet/in.h> /* for ntohl() */
  92315. #endif
  92316. /*** Start of inlined file: bitreader.h ***/
  92317. #ifndef FLAC__PRIVATE__BITREADER_H
  92318. #define FLAC__PRIVATE__BITREADER_H
  92319. #include <stdio.h> /* for FILE */
  92320. /*** Start of inlined file: cpu.h ***/
  92321. #ifndef FLAC__PRIVATE__CPU_H
  92322. #define FLAC__PRIVATE__CPU_H
  92323. #ifdef HAVE_CONFIG_H
  92324. #include <config.h>
  92325. #endif
  92326. typedef enum {
  92327. FLAC__CPUINFO_TYPE_IA32,
  92328. FLAC__CPUINFO_TYPE_PPC,
  92329. FLAC__CPUINFO_TYPE_UNKNOWN
  92330. } FLAC__CPUInfo_Type;
  92331. typedef struct {
  92332. FLAC__bool cpuid;
  92333. FLAC__bool bswap;
  92334. FLAC__bool cmov;
  92335. FLAC__bool mmx;
  92336. FLAC__bool fxsr;
  92337. FLAC__bool sse;
  92338. FLAC__bool sse2;
  92339. FLAC__bool sse3;
  92340. FLAC__bool ssse3;
  92341. FLAC__bool _3dnow;
  92342. FLAC__bool ext3dnow;
  92343. FLAC__bool extmmx;
  92344. } FLAC__CPUInfo_IA32;
  92345. typedef struct {
  92346. FLAC__bool altivec;
  92347. FLAC__bool ppc64;
  92348. } FLAC__CPUInfo_PPC;
  92349. typedef struct {
  92350. FLAC__bool use_asm;
  92351. FLAC__CPUInfo_Type type;
  92352. union {
  92353. FLAC__CPUInfo_IA32 ia32;
  92354. FLAC__CPUInfo_PPC ppc;
  92355. } data;
  92356. } FLAC__CPUInfo;
  92357. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92358. #ifndef FLAC__NO_ASM
  92359. #ifdef FLAC__CPU_IA32
  92360. #ifdef FLAC__HAS_NASM
  92361. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  92362. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  92363. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  92364. #endif
  92365. #endif
  92366. #endif
  92367. #endif
  92368. /*** End of inlined file: cpu.h ***/
  92369. /*
  92370. * opaque structure definition
  92371. */
  92372. struct FLAC__BitReader;
  92373. typedef struct FLAC__BitReader FLAC__BitReader;
  92374. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92375. /*
  92376. * construction, deletion, initialization, etc functions
  92377. */
  92378. FLAC__BitReader *FLAC__bitreader_new(void);
  92379. void FLAC__bitreader_delete(FLAC__BitReader *br);
  92380. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  92381. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  92382. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  92383. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  92384. /*
  92385. * CRC functions
  92386. */
  92387. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  92388. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  92389. /*
  92390. * info functions
  92391. */
  92392. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  92393. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  92394. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  92395. /*
  92396. * read functions
  92397. */
  92398. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  92399. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  92400. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  92401. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  92402. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  92403. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  92404. 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! */
  92405. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  92406. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92407. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92408. #ifndef FLAC__NO_ASM
  92409. # ifdef FLAC__CPU_IA32
  92410. # ifdef FLAC__HAS_NASM
  92411. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92412. # endif
  92413. # endif
  92414. #endif
  92415. #if 0 /* UNUSED */
  92416. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92417. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  92418. #endif
  92419. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  92420. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  92421. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  92422. #endif
  92423. /*** End of inlined file: bitreader.h ***/
  92424. /*** Start of inlined file: crc.h ***/
  92425. #ifndef FLAC__PRIVATE__CRC_H
  92426. #define FLAC__PRIVATE__CRC_H
  92427. /* 8 bit CRC generator, MSB shifted first
  92428. ** polynomial = x^8 + x^2 + x^1 + x^0
  92429. ** init = 0
  92430. */
  92431. extern FLAC__byte const FLAC__crc8_table[256];
  92432. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  92433. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  92434. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  92435. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  92436. /* 16 bit CRC generator, MSB shifted first
  92437. ** polynomial = x^16 + x^15 + x^2 + x^0
  92438. ** init = 0
  92439. */
  92440. extern unsigned FLAC__crc16_table[256];
  92441. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  92442. /* this alternate may be faster on some systems/compilers */
  92443. #if 0
  92444. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  92445. #endif
  92446. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  92447. #endif
  92448. /*** End of inlined file: crc.h ***/
  92449. /* Things should be fastest when this matches the machine word size */
  92450. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  92451. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  92452. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  92453. typedef FLAC__uint32 brword;
  92454. #define FLAC__BYTES_PER_WORD 4
  92455. #define FLAC__BITS_PER_WORD 32
  92456. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  92457. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  92458. #if WORDS_BIGENDIAN
  92459. #define SWAP_BE_WORD_TO_HOST(x) (x)
  92460. #else
  92461. #if defined (_MSC_VER) && defined (_X86_)
  92462. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  92463. #else
  92464. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  92465. #endif
  92466. #endif
  92467. /* counts the # of zero MSBs in a word */
  92468. #define COUNT_ZERO_MSBS(word) ( \
  92469. (word) <= 0xffff ? \
  92470. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  92471. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  92472. )
  92473. /* this alternate might be slightly faster on some systems/compilers: */
  92474. #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])) )
  92475. /*
  92476. * This should be at least twice as large as the largest number of words
  92477. * required to represent any 'number' (in any encoding) you are going to
  92478. * read. With FLAC this is on the order of maybe a few hundred bits.
  92479. * If the buffer is smaller than that, the decoder won't be able to read
  92480. * in a whole number that is in a variable length encoding (e.g. Rice).
  92481. * But to be practical it should be at least 1K bytes.
  92482. *
  92483. * Increase this number to decrease the number of read callbacks, at the
  92484. * expense of using more memory. Or decrease for the reverse effect,
  92485. * keeping in mind the limit from the first paragraph. The optimal size
  92486. * also depends on the CPU cache size and other factors; some twiddling
  92487. * may be necessary to squeeze out the best performance.
  92488. */
  92489. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  92490. static const unsigned char byte_to_unary_table[] = {
  92491. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  92492. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  92493. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92494. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92495. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92496. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92497. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92498. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  92507. };
  92508. #ifdef min
  92509. #undef min
  92510. #endif
  92511. #define min(x,y) ((x)<(y)?(x):(y))
  92512. #ifdef max
  92513. #undef max
  92514. #endif
  92515. #define max(x,y) ((x)>(y)?(x):(y))
  92516. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92517. #ifdef _MSC_VER
  92518. #define FLAC__U64L(x) x
  92519. #else
  92520. #define FLAC__U64L(x) x##LLU
  92521. #endif
  92522. #ifndef FLaC__INLINE
  92523. #define FLaC__INLINE
  92524. #endif
  92525. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  92526. struct FLAC__BitReader {
  92527. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  92528. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  92529. brword *buffer;
  92530. unsigned capacity; /* in words */
  92531. unsigned words; /* # of completed words in buffer */
  92532. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  92533. unsigned consumed_words; /* #words ... */
  92534. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  92535. unsigned read_crc16; /* the running frame CRC */
  92536. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  92537. FLAC__BitReaderReadCallback read_callback;
  92538. void *client_data;
  92539. FLAC__CPUInfo cpu_info;
  92540. };
  92541. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  92542. {
  92543. register unsigned crc = br->read_crc16;
  92544. #if FLAC__BYTES_PER_WORD == 4
  92545. switch(br->crc16_align) {
  92546. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  92547. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92548. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92549. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92550. }
  92551. #elif FLAC__BYTES_PER_WORD == 8
  92552. switch(br->crc16_align) {
  92553. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  92554. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  92555. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  92556. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  92557. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  92558. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92559. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92560. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92561. }
  92562. #else
  92563. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  92564. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  92565. br->read_crc16 = crc;
  92566. #endif
  92567. br->crc16_align = 0;
  92568. }
  92569. /* would be static except it needs to be called by asm routines */
  92570. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  92571. {
  92572. unsigned start, end;
  92573. size_t bytes;
  92574. FLAC__byte *target;
  92575. /* first shift the unconsumed buffer data toward the front as much as possible */
  92576. if(br->consumed_words > 0) {
  92577. start = br->consumed_words;
  92578. end = br->words + (br->bytes? 1:0);
  92579. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  92580. br->words -= start;
  92581. br->consumed_words = 0;
  92582. }
  92583. /*
  92584. * set the target for reading, taking into account word alignment and endianness
  92585. */
  92586. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  92587. if(bytes == 0)
  92588. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  92589. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  92590. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  92591. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  92592. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  92593. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  92594. * ^^-------target, bytes=3
  92595. * on LE machines, have to byteswap the odd tail word so nothing is
  92596. * overwritten:
  92597. */
  92598. #if WORDS_BIGENDIAN
  92599. #else
  92600. if(br->bytes)
  92601. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  92602. #endif
  92603. /* now it looks like:
  92604. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  92605. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  92606. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  92607. * ^^-------target, bytes=3
  92608. */
  92609. /* read in the data; note that the callback may return a smaller number of bytes */
  92610. if(!br->read_callback(target, &bytes, br->client_data))
  92611. return false;
  92612. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  92613. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92614. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92615. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  92616. * now have to byteswap on LE machines:
  92617. */
  92618. #if WORDS_BIGENDIAN
  92619. #else
  92620. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  92621. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  92622. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  92623. start = br->words;
  92624. local_swap32_block_(br->buffer + start, end - start);
  92625. }
  92626. else
  92627. # endif
  92628. for(start = br->words; start < end; start++)
  92629. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  92630. #endif
  92631. /* now it looks like:
  92632. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92633. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92634. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  92635. * finally we'll update the reader values:
  92636. */
  92637. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  92638. br->words = end / FLAC__BYTES_PER_WORD;
  92639. br->bytes = end % FLAC__BYTES_PER_WORD;
  92640. return true;
  92641. }
  92642. /***********************************************************************
  92643. *
  92644. * Class constructor/destructor
  92645. *
  92646. ***********************************************************************/
  92647. FLAC__BitReader *FLAC__bitreader_new(void)
  92648. {
  92649. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  92650. /* calloc() implies:
  92651. memset(br, 0, sizeof(FLAC__BitReader));
  92652. br->buffer = 0;
  92653. br->capacity = 0;
  92654. br->words = br->bytes = 0;
  92655. br->consumed_words = br->consumed_bits = 0;
  92656. br->read_callback = 0;
  92657. br->client_data = 0;
  92658. */
  92659. return br;
  92660. }
  92661. void FLAC__bitreader_delete(FLAC__BitReader *br)
  92662. {
  92663. FLAC__ASSERT(0 != br);
  92664. FLAC__bitreader_free(br);
  92665. free(br);
  92666. }
  92667. /***********************************************************************
  92668. *
  92669. * Public class methods
  92670. *
  92671. ***********************************************************************/
  92672. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  92673. {
  92674. FLAC__ASSERT(0 != br);
  92675. br->words = br->bytes = 0;
  92676. br->consumed_words = br->consumed_bits = 0;
  92677. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  92678. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  92679. if(br->buffer == 0)
  92680. return false;
  92681. br->read_callback = rcb;
  92682. br->client_data = cd;
  92683. br->cpu_info = cpu;
  92684. return true;
  92685. }
  92686. void FLAC__bitreader_free(FLAC__BitReader *br)
  92687. {
  92688. FLAC__ASSERT(0 != br);
  92689. if(0 != br->buffer)
  92690. free(br->buffer);
  92691. br->buffer = 0;
  92692. br->capacity = 0;
  92693. br->words = br->bytes = 0;
  92694. br->consumed_words = br->consumed_bits = 0;
  92695. br->read_callback = 0;
  92696. br->client_data = 0;
  92697. }
  92698. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  92699. {
  92700. br->words = br->bytes = 0;
  92701. br->consumed_words = br->consumed_bits = 0;
  92702. return true;
  92703. }
  92704. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  92705. {
  92706. unsigned i, j;
  92707. if(br == 0) {
  92708. fprintf(out, "bitreader is NULL\n");
  92709. }
  92710. else {
  92711. 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);
  92712. for(i = 0; i < br->words; i++) {
  92713. fprintf(out, "%08X: ", i);
  92714. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  92715. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92716. fprintf(out, ".");
  92717. else
  92718. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  92719. fprintf(out, "\n");
  92720. }
  92721. if(br->bytes > 0) {
  92722. fprintf(out, "%08X: ", i);
  92723. for(j = 0; j < br->bytes*8; j++)
  92724. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92725. fprintf(out, ".");
  92726. else
  92727. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  92728. fprintf(out, "\n");
  92729. }
  92730. }
  92731. }
  92732. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  92733. {
  92734. FLAC__ASSERT(0 != br);
  92735. FLAC__ASSERT(0 != br->buffer);
  92736. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  92737. br->read_crc16 = (unsigned)seed;
  92738. br->crc16_align = br->consumed_bits;
  92739. }
  92740. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  92741. {
  92742. FLAC__ASSERT(0 != br);
  92743. FLAC__ASSERT(0 != br->buffer);
  92744. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  92745. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  92746. /* CRC any tail bytes in a partially-consumed word */
  92747. if(br->consumed_bits) {
  92748. const brword tail = br->buffer[br->consumed_words];
  92749. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  92750. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  92751. }
  92752. return br->read_crc16;
  92753. }
  92754. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  92755. {
  92756. return ((br->consumed_bits & 7) == 0);
  92757. }
  92758. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  92759. {
  92760. return 8 - (br->consumed_bits & 7);
  92761. }
  92762. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  92763. {
  92764. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  92765. }
  92766. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  92767. {
  92768. FLAC__ASSERT(0 != br);
  92769. FLAC__ASSERT(0 != br->buffer);
  92770. FLAC__ASSERT(bits <= 32);
  92771. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  92772. FLAC__ASSERT(br->consumed_words <= br->words);
  92773. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  92774. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  92775. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  92776. *val = 0;
  92777. return true;
  92778. }
  92779. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  92780. if(!bitreader_read_from_client_(br))
  92781. return false;
  92782. }
  92783. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  92784. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  92785. if(br->consumed_bits) {
  92786. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92787. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  92788. const brword word = br->buffer[br->consumed_words];
  92789. if(bits < n) {
  92790. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  92791. br->consumed_bits += bits;
  92792. return true;
  92793. }
  92794. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  92795. bits -= n;
  92796. crc16_update_word_(br, word);
  92797. br->consumed_words++;
  92798. br->consumed_bits = 0;
  92799. 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 */
  92800. *val <<= bits;
  92801. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  92802. br->consumed_bits = bits;
  92803. }
  92804. return true;
  92805. }
  92806. else {
  92807. const brword word = br->buffer[br->consumed_words];
  92808. if(bits < FLAC__BITS_PER_WORD) {
  92809. *val = word >> (FLAC__BITS_PER_WORD-bits);
  92810. br->consumed_bits = bits;
  92811. return true;
  92812. }
  92813. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  92814. *val = word;
  92815. crc16_update_word_(br, word);
  92816. br->consumed_words++;
  92817. return true;
  92818. }
  92819. }
  92820. else {
  92821. /* in this case we're starting our read at a partial tail word;
  92822. * the reader has guaranteed that we have at least 'bits' bits
  92823. * available to read, which makes this case simpler.
  92824. */
  92825. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  92826. if(br->consumed_bits) {
  92827. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92828. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  92829. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  92830. br->consumed_bits += bits;
  92831. return true;
  92832. }
  92833. else {
  92834. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  92835. br->consumed_bits += bits;
  92836. return true;
  92837. }
  92838. }
  92839. }
  92840. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  92841. {
  92842. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  92843. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  92844. return false;
  92845. /* sign-extend: */
  92846. *val <<= (32-bits);
  92847. *val >>= (32-bits);
  92848. return true;
  92849. }
  92850. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  92851. {
  92852. FLAC__uint32 hi, lo;
  92853. if(bits > 32) {
  92854. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  92855. return false;
  92856. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  92857. return false;
  92858. *val = hi;
  92859. *val <<= 32;
  92860. *val |= lo;
  92861. }
  92862. else {
  92863. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  92864. return false;
  92865. *val = lo;
  92866. }
  92867. return true;
  92868. }
  92869. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  92870. {
  92871. FLAC__uint32 x8, x32 = 0;
  92872. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  92873. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  92874. return false;
  92875. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92876. return false;
  92877. x32 |= (x8 << 8);
  92878. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92879. return false;
  92880. x32 |= (x8 << 16);
  92881. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92882. return false;
  92883. x32 |= (x8 << 24);
  92884. *val = x32;
  92885. return true;
  92886. }
  92887. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  92888. {
  92889. /*
  92890. * OPT: a faster implementation is possible but probably not that useful
  92891. * since this is only called a couple of times in the metadata readers.
  92892. */
  92893. FLAC__ASSERT(0 != br);
  92894. FLAC__ASSERT(0 != br->buffer);
  92895. if(bits > 0) {
  92896. const unsigned n = br->consumed_bits & 7;
  92897. unsigned m;
  92898. FLAC__uint32 x;
  92899. if(n != 0) {
  92900. m = min(8-n, bits);
  92901. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  92902. return false;
  92903. bits -= m;
  92904. }
  92905. m = bits / 8;
  92906. if(m > 0) {
  92907. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  92908. return false;
  92909. bits %= 8;
  92910. }
  92911. if(bits > 0) {
  92912. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  92913. return false;
  92914. }
  92915. }
  92916. return true;
  92917. }
  92918. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  92919. {
  92920. FLAC__uint32 x;
  92921. FLAC__ASSERT(0 != br);
  92922. FLAC__ASSERT(0 != br->buffer);
  92923. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  92924. /* step 1: skip over partial head word to get word aligned */
  92925. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  92926. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92927. return false;
  92928. nvals--;
  92929. }
  92930. if(0 == nvals)
  92931. return true;
  92932. /* step 2: skip whole words in chunks */
  92933. while(nvals >= FLAC__BYTES_PER_WORD) {
  92934. if(br->consumed_words < br->words) {
  92935. br->consumed_words++;
  92936. nvals -= FLAC__BYTES_PER_WORD;
  92937. }
  92938. else if(!bitreader_read_from_client_(br))
  92939. return false;
  92940. }
  92941. /* step 3: skip any remainder from partial tail bytes */
  92942. while(nvals) {
  92943. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92944. return false;
  92945. nvals--;
  92946. }
  92947. return true;
  92948. }
  92949. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  92950. {
  92951. FLAC__uint32 x;
  92952. FLAC__ASSERT(0 != br);
  92953. FLAC__ASSERT(0 != br->buffer);
  92954. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  92955. /* step 1: read from partial head word to get word aligned */
  92956. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  92957. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92958. return false;
  92959. *val++ = (FLAC__byte)x;
  92960. nvals--;
  92961. }
  92962. if(0 == nvals)
  92963. return true;
  92964. /* step 2: read whole words in chunks */
  92965. while(nvals >= FLAC__BYTES_PER_WORD) {
  92966. if(br->consumed_words < br->words) {
  92967. const brword word = br->buffer[br->consumed_words++];
  92968. #if FLAC__BYTES_PER_WORD == 4
  92969. val[0] = (FLAC__byte)(word >> 24);
  92970. val[1] = (FLAC__byte)(word >> 16);
  92971. val[2] = (FLAC__byte)(word >> 8);
  92972. val[3] = (FLAC__byte)word;
  92973. #elif FLAC__BYTES_PER_WORD == 8
  92974. val[0] = (FLAC__byte)(word >> 56);
  92975. val[1] = (FLAC__byte)(word >> 48);
  92976. val[2] = (FLAC__byte)(word >> 40);
  92977. val[3] = (FLAC__byte)(word >> 32);
  92978. val[4] = (FLAC__byte)(word >> 24);
  92979. val[5] = (FLAC__byte)(word >> 16);
  92980. val[6] = (FLAC__byte)(word >> 8);
  92981. val[7] = (FLAC__byte)word;
  92982. #else
  92983. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  92984. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  92985. #endif
  92986. val += FLAC__BYTES_PER_WORD;
  92987. nvals -= FLAC__BYTES_PER_WORD;
  92988. }
  92989. else if(!bitreader_read_from_client_(br))
  92990. return false;
  92991. }
  92992. /* step 3: read any remainder from partial tail bytes */
  92993. while(nvals) {
  92994. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92995. return false;
  92996. *val++ = (FLAC__byte)x;
  92997. nvals--;
  92998. }
  92999. return true;
  93000. }
  93001. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93002. #if 0 /* slow but readable version */
  93003. {
  93004. unsigned bit;
  93005. FLAC__ASSERT(0 != br);
  93006. FLAC__ASSERT(0 != br->buffer);
  93007. *val = 0;
  93008. while(1) {
  93009. if(!FLAC__bitreader_read_bit(br, &bit))
  93010. return false;
  93011. if(bit)
  93012. break;
  93013. else
  93014. *val++;
  93015. }
  93016. return true;
  93017. }
  93018. #else
  93019. {
  93020. unsigned i;
  93021. FLAC__ASSERT(0 != br);
  93022. FLAC__ASSERT(0 != br->buffer);
  93023. *val = 0;
  93024. while(1) {
  93025. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93026. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93027. if(b) {
  93028. i = COUNT_ZERO_MSBS(b);
  93029. *val += i;
  93030. i++;
  93031. br->consumed_bits += i;
  93032. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93033. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93034. br->consumed_words++;
  93035. br->consumed_bits = 0;
  93036. }
  93037. return true;
  93038. }
  93039. else {
  93040. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93041. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93042. br->consumed_words++;
  93043. br->consumed_bits = 0;
  93044. /* didn't find stop bit yet, have to keep going... */
  93045. }
  93046. }
  93047. /* at this point we've eaten up all the whole words; have to try
  93048. * reading through any tail bytes before calling the read callback.
  93049. * this is a repeat of the above logic adjusted for the fact we
  93050. * don't have a whole word. note though if the client is feeding
  93051. * us data a byte at a time (unlikely), br->consumed_bits may not
  93052. * be zero.
  93053. */
  93054. if(br->bytes) {
  93055. const unsigned end = br->bytes * 8;
  93056. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93057. if(b) {
  93058. i = COUNT_ZERO_MSBS(b);
  93059. *val += i;
  93060. i++;
  93061. br->consumed_bits += i;
  93062. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93063. return true;
  93064. }
  93065. else {
  93066. *val += end - br->consumed_bits;
  93067. br->consumed_bits += end;
  93068. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93069. /* didn't find stop bit yet, have to keep going... */
  93070. }
  93071. }
  93072. if(!bitreader_read_from_client_(br))
  93073. return false;
  93074. }
  93075. }
  93076. #endif
  93077. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93078. {
  93079. FLAC__uint32 lsbs = 0, msbs = 0;
  93080. unsigned uval;
  93081. FLAC__ASSERT(0 != br);
  93082. FLAC__ASSERT(0 != br->buffer);
  93083. FLAC__ASSERT(parameter <= 31);
  93084. /* read the unary MSBs and end bit */
  93085. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93086. return false;
  93087. /* read the binary LSBs */
  93088. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93089. return false;
  93090. /* compose the value */
  93091. uval = (msbs << parameter) | lsbs;
  93092. if(uval & 1)
  93093. *val = -((int)(uval >> 1)) - 1;
  93094. else
  93095. *val = (int)(uval >> 1);
  93096. return true;
  93097. }
  93098. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93099. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93100. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93101. /* OPT: possibly faster version for use with MSVC */
  93102. #ifdef _MSC_VER
  93103. {
  93104. unsigned i;
  93105. unsigned uval = 0;
  93106. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93107. /* try and get br->consumed_words and br->consumed_bits into register;
  93108. * must remember to flush them back to *br before calling other
  93109. * bitwriter functions that use them, and before returning */
  93110. register unsigned cwords;
  93111. register unsigned cbits;
  93112. FLAC__ASSERT(0 != br);
  93113. FLAC__ASSERT(0 != br->buffer);
  93114. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93115. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93116. FLAC__ASSERT(parameter < 32);
  93117. /* 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 */
  93118. if(nvals == 0)
  93119. return true;
  93120. cbits = br->consumed_bits;
  93121. cwords = br->consumed_words;
  93122. while(1) {
  93123. /* read unary part */
  93124. while(1) {
  93125. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93126. brword b = br->buffer[cwords] << cbits;
  93127. if(b) {
  93128. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93129. __asm {
  93130. bsr eax, b
  93131. not eax
  93132. and eax, 31
  93133. mov i, eax
  93134. }
  93135. #else
  93136. i = COUNT_ZERO_MSBS(b);
  93137. #endif
  93138. uval += i;
  93139. bits = parameter;
  93140. i++;
  93141. cbits += i;
  93142. if(cbits == FLAC__BITS_PER_WORD) {
  93143. crc16_update_word_(br, br->buffer[cwords]);
  93144. cwords++;
  93145. cbits = 0;
  93146. }
  93147. goto break1;
  93148. }
  93149. else {
  93150. uval += FLAC__BITS_PER_WORD - cbits;
  93151. crc16_update_word_(br, br->buffer[cwords]);
  93152. cwords++;
  93153. cbits = 0;
  93154. /* didn't find stop bit yet, have to keep going... */
  93155. }
  93156. }
  93157. /* at this point we've eaten up all the whole words; have to try
  93158. * reading through any tail bytes before calling the read callback.
  93159. * this is a repeat of the above logic adjusted for the fact we
  93160. * don't have a whole word. note though if the client is feeding
  93161. * us data a byte at a time (unlikely), br->consumed_bits may not
  93162. * be zero.
  93163. */
  93164. if(br->bytes) {
  93165. const unsigned end = br->bytes * 8;
  93166. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93167. if(b) {
  93168. i = COUNT_ZERO_MSBS(b);
  93169. uval += i;
  93170. bits = parameter;
  93171. i++;
  93172. cbits += i;
  93173. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93174. goto break1;
  93175. }
  93176. else {
  93177. uval += end - cbits;
  93178. cbits += end;
  93179. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93180. /* didn't find stop bit yet, have to keep going... */
  93181. }
  93182. }
  93183. /* flush registers and read; bitreader_read_from_client_() does
  93184. * not touch br->consumed_bits at all but we still need to set
  93185. * it in case it fails and we have to return false.
  93186. */
  93187. br->consumed_bits = cbits;
  93188. br->consumed_words = cwords;
  93189. if(!bitreader_read_from_client_(br))
  93190. return false;
  93191. cwords = br->consumed_words;
  93192. }
  93193. break1:
  93194. /* read binary part */
  93195. FLAC__ASSERT(cwords <= br->words);
  93196. if(bits) {
  93197. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93198. /* flush registers and read; bitreader_read_from_client_() does
  93199. * not touch br->consumed_bits at all but we still need to set
  93200. * it in case it fails and we have to return false.
  93201. */
  93202. br->consumed_bits = cbits;
  93203. br->consumed_words = cwords;
  93204. if(!bitreader_read_from_client_(br))
  93205. return false;
  93206. cwords = br->consumed_words;
  93207. }
  93208. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93209. if(cbits) {
  93210. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93211. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93212. const brword word = br->buffer[cwords];
  93213. if(bits < n) {
  93214. uval <<= bits;
  93215. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93216. cbits += bits;
  93217. goto break2;
  93218. }
  93219. uval <<= n;
  93220. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93221. bits -= n;
  93222. crc16_update_word_(br, word);
  93223. cwords++;
  93224. cbits = 0;
  93225. 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 */
  93226. uval <<= bits;
  93227. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93228. cbits = bits;
  93229. }
  93230. goto break2;
  93231. }
  93232. else {
  93233. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93234. uval <<= bits;
  93235. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93236. cbits = bits;
  93237. goto break2;
  93238. }
  93239. }
  93240. else {
  93241. /* in this case we're starting our read at a partial tail word;
  93242. * the reader has guaranteed that we have at least 'bits' bits
  93243. * available to read, which makes this case simpler.
  93244. */
  93245. uval <<= bits;
  93246. if(cbits) {
  93247. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93248. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  93249. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  93250. cbits += bits;
  93251. goto break2;
  93252. }
  93253. else {
  93254. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93255. cbits += bits;
  93256. goto break2;
  93257. }
  93258. }
  93259. }
  93260. break2:
  93261. /* compose the value */
  93262. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93263. /* are we done? */
  93264. --nvals;
  93265. if(nvals == 0) {
  93266. br->consumed_bits = cbits;
  93267. br->consumed_words = cwords;
  93268. return true;
  93269. }
  93270. uval = 0;
  93271. ++vals;
  93272. }
  93273. }
  93274. #else
  93275. {
  93276. unsigned i;
  93277. unsigned uval = 0;
  93278. /* try and get br->consumed_words and br->consumed_bits into register;
  93279. * must remember to flush them back to *br before calling other
  93280. * bitwriter functions that use them, and before returning */
  93281. register unsigned cwords;
  93282. register unsigned cbits;
  93283. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  93284. FLAC__ASSERT(0 != br);
  93285. FLAC__ASSERT(0 != br->buffer);
  93286. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93287. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93288. FLAC__ASSERT(parameter < 32);
  93289. /* 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 */
  93290. if(nvals == 0)
  93291. return true;
  93292. cbits = br->consumed_bits;
  93293. cwords = br->consumed_words;
  93294. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93295. while(1) {
  93296. /* read unary part */
  93297. while(1) {
  93298. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93299. brword b = br->buffer[cwords] << cbits;
  93300. if(b) {
  93301. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  93302. asm volatile (
  93303. "bsrl %1, %0;"
  93304. "notl %0;"
  93305. "andl $31, %0;"
  93306. : "=r"(i)
  93307. : "r"(b)
  93308. );
  93309. #else
  93310. i = COUNT_ZERO_MSBS(b);
  93311. #endif
  93312. uval += i;
  93313. cbits += i;
  93314. cbits++; /* skip over stop bit */
  93315. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93316. crc16_update_word_(br, br->buffer[cwords]);
  93317. cwords++;
  93318. cbits = 0;
  93319. }
  93320. goto break1;
  93321. }
  93322. else {
  93323. uval += FLAC__BITS_PER_WORD - cbits;
  93324. crc16_update_word_(br, br->buffer[cwords]);
  93325. cwords++;
  93326. cbits = 0;
  93327. /* didn't find stop bit yet, have to keep going... */
  93328. }
  93329. }
  93330. /* at this point we've eaten up all the whole words; have to try
  93331. * reading through any tail bytes before calling the read callback.
  93332. * this is a repeat of the above logic adjusted for the fact we
  93333. * don't have a whole word. note though if the client is feeding
  93334. * us data a byte at a time (unlikely), br->consumed_bits may not
  93335. * be zero.
  93336. */
  93337. if(br->bytes) {
  93338. const unsigned end = br->bytes * 8;
  93339. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93340. if(b) {
  93341. i = COUNT_ZERO_MSBS(b);
  93342. uval += i;
  93343. cbits += i;
  93344. cbits++; /* skip over stop bit */
  93345. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93346. goto break1;
  93347. }
  93348. else {
  93349. uval += end - cbits;
  93350. cbits += end;
  93351. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93352. /* didn't find stop bit yet, have to keep going... */
  93353. }
  93354. }
  93355. /* flush registers and read; bitreader_read_from_client_() does
  93356. * not touch br->consumed_bits at all but we still need to set
  93357. * it in case it fails and we have to return false.
  93358. */
  93359. br->consumed_bits = cbits;
  93360. br->consumed_words = cwords;
  93361. if(!bitreader_read_from_client_(br))
  93362. return false;
  93363. cwords = br->consumed_words;
  93364. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  93365. /* + uval to offset our count by the # of unary bits already
  93366. * consumed before the read, because we will add these back
  93367. * in all at once at break1
  93368. */
  93369. }
  93370. break1:
  93371. ucbits -= uval;
  93372. ucbits--; /* account for stop bit */
  93373. /* read binary part */
  93374. FLAC__ASSERT(cwords <= br->words);
  93375. if(parameter) {
  93376. while(ucbits < parameter) {
  93377. /* flush registers and read; bitreader_read_from_client_() does
  93378. * not touch br->consumed_bits at all but we still need to set
  93379. * it in case it fails and we have to return false.
  93380. */
  93381. br->consumed_bits = cbits;
  93382. br->consumed_words = cwords;
  93383. if(!bitreader_read_from_client_(br))
  93384. return false;
  93385. cwords = br->consumed_words;
  93386. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93387. }
  93388. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93389. if(cbits) {
  93390. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  93391. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93392. const brword word = br->buffer[cwords];
  93393. if(parameter < n) {
  93394. uval <<= parameter;
  93395. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  93396. cbits += parameter;
  93397. }
  93398. else {
  93399. uval <<= n;
  93400. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93401. crc16_update_word_(br, word);
  93402. cwords++;
  93403. cbits = parameter - n;
  93404. 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 */
  93405. uval <<= cbits;
  93406. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  93407. }
  93408. }
  93409. }
  93410. else {
  93411. cbits = parameter;
  93412. uval <<= parameter;
  93413. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93414. }
  93415. }
  93416. else {
  93417. /* in this case we're starting our read at a partial tail word;
  93418. * the reader has guaranteed that we have at least 'parameter'
  93419. * bits available to read, which makes this case simpler.
  93420. */
  93421. uval <<= parameter;
  93422. if(cbits) {
  93423. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93424. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  93425. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  93426. cbits += parameter;
  93427. }
  93428. else {
  93429. cbits = parameter;
  93430. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93431. }
  93432. }
  93433. }
  93434. ucbits -= parameter;
  93435. /* compose the value */
  93436. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93437. /* are we done? */
  93438. --nvals;
  93439. if(nvals == 0) {
  93440. br->consumed_bits = cbits;
  93441. br->consumed_words = cwords;
  93442. return true;
  93443. }
  93444. uval = 0;
  93445. ++vals;
  93446. }
  93447. }
  93448. #endif
  93449. #if 0 /* UNUSED */
  93450. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93451. {
  93452. FLAC__uint32 lsbs = 0, msbs = 0;
  93453. unsigned bit, uval, k;
  93454. FLAC__ASSERT(0 != br);
  93455. FLAC__ASSERT(0 != br->buffer);
  93456. k = FLAC__bitmath_ilog2(parameter);
  93457. /* read the unary MSBs and end bit */
  93458. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93459. return false;
  93460. /* read the binary LSBs */
  93461. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93462. return false;
  93463. if(parameter == 1u<<k) {
  93464. /* compose the value */
  93465. uval = (msbs << k) | lsbs;
  93466. }
  93467. else {
  93468. unsigned d = (1 << (k+1)) - parameter;
  93469. if(lsbs >= d) {
  93470. if(!FLAC__bitreader_read_bit(br, &bit))
  93471. return false;
  93472. lsbs <<= 1;
  93473. lsbs |= bit;
  93474. lsbs -= d;
  93475. }
  93476. /* compose the value */
  93477. uval = msbs * parameter + lsbs;
  93478. }
  93479. /* unfold unsigned to signed */
  93480. if(uval & 1)
  93481. *val = -((int)(uval >> 1)) - 1;
  93482. else
  93483. *val = (int)(uval >> 1);
  93484. return true;
  93485. }
  93486. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  93487. {
  93488. FLAC__uint32 lsbs, msbs = 0;
  93489. unsigned bit, k;
  93490. FLAC__ASSERT(0 != br);
  93491. FLAC__ASSERT(0 != br->buffer);
  93492. k = FLAC__bitmath_ilog2(parameter);
  93493. /* read the unary MSBs and end bit */
  93494. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93495. return false;
  93496. /* read the binary LSBs */
  93497. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93498. return false;
  93499. if(parameter == 1u<<k) {
  93500. /* compose the value */
  93501. *val = (msbs << k) | lsbs;
  93502. }
  93503. else {
  93504. unsigned d = (1 << (k+1)) - parameter;
  93505. if(lsbs >= d) {
  93506. if(!FLAC__bitreader_read_bit(br, &bit))
  93507. return false;
  93508. lsbs <<= 1;
  93509. lsbs |= bit;
  93510. lsbs -= d;
  93511. }
  93512. /* compose the value */
  93513. *val = msbs * parameter + lsbs;
  93514. }
  93515. return true;
  93516. }
  93517. #endif /* UNUSED */
  93518. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93519. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  93520. {
  93521. FLAC__uint32 v = 0;
  93522. FLAC__uint32 x;
  93523. unsigned i;
  93524. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93525. return false;
  93526. if(raw)
  93527. raw[(*rawlen)++] = (FLAC__byte)x;
  93528. if(!(x & 0x80)) { /* 0xxxxxxx */
  93529. v = x;
  93530. i = 0;
  93531. }
  93532. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93533. v = x & 0x1F;
  93534. i = 1;
  93535. }
  93536. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93537. v = x & 0x0F;
  93538. i = 2;
  93539. }
  93540. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93541. v = x & 0x07;
  93542. i = 3;
  93543. }
  93544. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93545. v = x & 0x03;
  93546. i = 4;
  93547. }
  93548. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93549. v = x & 0x01;
  93550. i = 5;
  93551. }
  93552. else {
  93553. *val = 0xffffffff;
  93554. return true;
  93555. }
  93556. for( ; i; i--) {
  93557. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93558. return false;
  93559. if(raw)
  93560. raw[(*rawlen)++] = (FLAC__byte)x;
  93561. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93562. *val = 0xffffffff;
  93563. return true;
  93564. }
  93565. v <<= 6;
  93566. v |= (x & 0x3F);
  93567. }
  93568. *val = v;
  93569. return true;
  93570. }
  93571. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93572. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  93573. {
  93574. FLAC__uint64 v = 0;
  93575. FLAC__uint32 x;
  93576. unsigned i;
  93577. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93578. return false;
  93579. if(raw)
  93580. raw[(*rawlen)++] = (FLAC__byte)x;
  93581. if(!(x & 0x80)) { /* 0xxxxxxx */
  93582. v = x;
  93583. i = 0;
  93584. }
  93585. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93586. v = x & 0x1F;
  93587. i = 1;
  93588. }
  93589. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93590. v = x & 0x0F;
  93591. i = 2;
  93592. }
  93593. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93594. v = x & 0x07;
  93595. i = 3;
  93596. }
  93597. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93598. v = x & 0x03;
  93599. i = 4;
  93600. }
  93601. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93602. v = x & 0x01;
  93603. i = 5;
  93604. }
  93605. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  93606. v = 0;
  93607. i = 6;
  93608. }
  93609. else {
  93610. *val = FLAC__U64L(0xffffffffffffffff);
  93611. return true;
  93612. }
  93613. for( ; i; i--) {
  93614. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93615. return false;
  93616. if(raw)
  93617. raw[(*rawlen)++] = (FLAC__byte)x;
  93618. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93619. *val = FLAC__U64L(0xffffffffffffffff);
  93620. return true;
  93621. }
  93622. v <<= 6;
  93623. v |= (x & 0x3F);
  93624. }
  93625. *val = v;
  93626. return true;
  93627. }
  93628. #endif
  93629. /*** End of inlined file: bitreader.c ***/
  93630. /*** Start of inlined file: bitwriter.c ***/
  93631. /*** Start of inlined file: juce_FlacHeader.h ***/
  93632. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93633. // tasks..
  93634. #define VERSION "1.2.1"
  93635. #define FLAC__NO_DLL 1
  93636. #if JUCE_MSVC
  93637. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93638. #endif
  93639. #if JUCE_MAC
  93640. #define FLAC__SYS_DARWIN 1
  93641. #endif
  93642. /*** End of inlined file: juce_FlacHeader.h ***/
  93643. #if JUCE_USE_FLAC
  93644. #if HAVE_CONFIG_H
  93645. # include <config.h>
  93646. #endif
  93647. #include <stdlib.h> /* for malloc() */
  93648. #include <string.h> /* for memcpy(), memset() */
  93649. #ifdef _MSC_VER
  93650. #include <winsock.h> /* for ntohl() */
  93651. #elif defined FLAC__SYS_DARWIN
  93652. #include <machine/endian.h> /* for ntohl() */
  93653. #elif defined __MINGW32__
  93654. #include <winsock.h> /* for ntohl() */
  93655. #else
  93656. #include <netinet/in.h> /* for ntohl() */
  93657. #endif
  93658. #if 0 /* UNUSED */
  93659. #endif
  93660. /*** Start of inlined file: bitwriter.h ***/
  93661. #ifndef FLAC__PRIVATE__BITWRITER_H
  93662. #define FLAC__PRIVATE__BITWRITER_H
  93663. #include <stdio.h> /* for FILE */
  93664. /*
  93665. * opaque structure definition
  93666. */
  93667. struct FLAC__BitWriter;
  93668. typedef struct FLAC__BitWriter FLAC__BitWriter;
  93669. /*
  93670. * construction, deletion, initialization, etc functions
  93671. */
  93672. FLAC__BitWriter *FLAC__bitwriter_new(void);
  93673. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  93674. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  93675. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  93676. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  93677. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  93678. /*
  93679. * CRC functions
  93680. *
  93681. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  93682. */
  93683. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  93684. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  93685. /*
  93686. * info functions
  93687. */
  93688. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  93689. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  93690. /*
  93691. * direct buffer access
  93692. *
  93693. * there may be no calls on the bitwriter between get and release.
  93694. * the bitwriter continues to own the returned buffer.
  93695. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  93696. */
  93697. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  93698. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  93699. /*
  93700. * write functions
  93701. */
  93702. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  93703. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  93704. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  93705. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  93706. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  93707. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  93708. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  93709. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  93710. #if 0 /* UNUSED */
  93711. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  93712. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  93713. #endif
  93714. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  93715. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  93716. #if 0 /* UNUSED */
  93717. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  93718. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  93719. #endif
  93720. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  93721. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  93722. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  93723. #endif
  93724. /*** End of inlined file: bitwriter.h ***/
  93725. /*** Start of inlined file: alloc.h ***/
  93726. #ifndef FLAC__SHARE__ALLOC_H
  93727. #define FLAC__SHARE__ALLOC_H
  93728. #if HAVE_CONFIG_H
  93729. # include <config.h>
  93730. #endif
  93731. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  93732. * before #including this file, otherwise SIZE_MAX might not be defined
  93733. */
  93734. #include <limits.h> /* for SIZE_MAX */
  93735. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  93736. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  93737. #endif
  93738. #include <stdlib.h> /* for size_t, malloc(), etc */
  93739. #ifndef SIZE_MAX
  93740. # ifndef SIZE_T_MAX
  93741. # ifdef _MSC_VER
  93742. # define SIZE_T_MAX UINT_MAX
  93743. # else
  93744. # error
  93745. # endif
  93746. # endif
  93747. # define SIZE_MAX SIZE_T_MAX
  93748. #endif
  93749. #ifndef FLaC__INLINE
  93750. #define FLaC__INLINE
  93751. #endif
  93752. /* avoid malloc()ing 0 bytes, see:
  93753. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  93754. */
  93755. static FLaC__INLINE void *safe_malloc_(size_t size)
  93756. {
  93757. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93758. if(!size)
  93759. size++;
  93760. return malloc(size);
  93761. }
  93762. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  93763. {
  93764. if(!nmemb || !size)
  93765. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93766. return calloc(nmemb, size);
  93767. }
  93768. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  93769. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  93770. {
  93771. size2 += size1;
  93772. if(size2 < size1)
  93773. return 0;
  93774. return safe_malloc_(size2);
  93775. }
  93776. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  93777. {
  93778. size2 += size1;
  93779. if(size2 < size1)
  93780. return 0;
  93781. size3 += size2;
  93782. if(size3 < size2)
  93783. return 0;
  93784. return safe_malloc_(size3);
  93785. }
  93786. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  93787. {
  93788. size2 += size1;
  93789. if(size2 < size1)
  93790. return 0;
  93791. size3 += size2;
  93792. if(size3 < size2)
  93793. return 0;
  93794. size4 += size3;
  93795. if(size4 < size3)
  93796. return 0;
  93797. return safe_malloc_(size4);
  93798. }
  93799. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  93800. #if 0
  93801. needs support for cases where sizeof(size_t) != 4
  93802. {
  93803. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  93804. if(sizeof(size_t) == 4) {
  93805. if ((double)size1 * (double)size2 < 4294967296.0)
  93806. return malloc(size1*size2);
  93807. }
  93808. return 0;
  93809. }
  93810. #else
  93811. /* better? */
  93812. {
  93813. if(!size1 || !size2)
  93814. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93815. if(size1 > SIZE_MAX / size2)
  93816. return 0;
  93817. return malloc(size1*size2);
  93818. }
  93819. #endif
  93820. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  93821. {
  93822. if(!size1 || !size2 || !size3)
  93823. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93824. if(size1 > SIZE_MAX / size2)
  93825. return 0;
  93826. size1 *= size2;
  93827. if(size1 > SIZE_MAX / size3)
  93828. return 0;
  93829. return malloc(size1*size3);
  93830. }
  93831. /* size1*size2 + size3 */
  93832. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  93833. {
  93834. if(!size1 || !size2)
  93835. return safe_malloc_(size3);
  93836. if(size1 > SIZE_MAX / size2)
  93837. return 0;
  93838. return safe_malloc_add_2op_(size1*size2, size3);
  93839. }
  93840. /* size1 * (size2 + size3) */
  93841. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  93842. {
  93843. if(!size1 || (!size2 && !size3))
  93844. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93845. size2 += size3;
  93846. if(size2 < size3)
  93847. return 0;
  93848. return safe_malloc_mul_2op_(size1, size2);
  93849. }
  93850. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  93851. {
  93852. size2 += size1;
  93853. if(size2 < size1)
  93854. return 0;
  93855. return realloc(ptr, size2);
  93856. }
  93857. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  93858. {
  93859. size2 += size1;
  93860. if(size2 < size1)
  93861. return 0;
  93862. size3 += size2;
  93863. if(size3 < size2)
  93864. return 0;
  93865. return realloc(ptr, size3);
  93866. }
  93867. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  93868. {
  93869. size2 += size1;
  93870. if(size2 < size1)
  93871. return 0;
  93872. size3 += size2;
  93873. if(size3 < size2)
  93874. return 0;
  93875. size4 += size3;
  93876. if(size4 < size3)
  93877. return 0;
  93878. return realloc(ptr, size4);
  93879. }
  93880. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  93881. {
  93882. if(!size1 || !size2)
  93883. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  93884. if(size1 > SIZE_MAX / size2)
  93885. return 0;
  93886. return realloc(ptr, size1*size2);
  93887. }
  93888. /* size1 * (size2 + size3) */
  93889. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  93890. {
  93891. if(!size1 || (!size2 && !size3))
  93892. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  93893. size2 += size3;
  93894. if(size2 < size3)
  93895. return 0;
  93896. return safe_realloc_mul_2op_(ptr, size1, size2);
  93897. }
  93898. #endif
  93899. /*** End of inlined file: alloc.h ***/
  93900. /* Things should be fastest when this matches the machine word size */
  93901. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  93902. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  93903. typedef FLAC__uint32 bwword;
  93904. #define FLAC__BYTES_PER_WORD 4
  93905. #define FLAC__BITS_PER_WORD 32
  93906. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93907. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  93908. #if WORDS_BIGENDIAN
  93909. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93910. #else
  93911. #ifdef _MSC_VER
  93912. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93913. #else
  93914. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93915. #endif
  93916. #endif
  93917. /*
  93918. * The default capacity here doesn't matter too much. The buffer always grows
  93919. * to hold whatever is written to it. Usually the encoder will stop adding at
  93920. * a frame or metadata block, then write that out and clear the buffer for the
  93921. * next one.
  93922. */
  93923. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  93924. /* When growing, increment 4K at a time */
  93925. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  93926. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  93927. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  93928. #ifdef min
  93929. #undef min
  93930. #endif
  93931. #define min(x,y) ((x)<(y)?(x):(y))
  93932. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93933. #ifdef _MSC_VER
  93934. #define FLAC__U64L(x) x
  93935. #else
  93936. #define FLAC__U64L(x) x##LLU
  93937. #endif
  93938. #ifndef FLaC__INLINE
  93939. #define FLaC__INLINE
  93940. #endif
  93941. struct FLAC__BitWriter {
  93942. bwword *buffer;
  93943. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  93944. unsigned capacity; /* capacity of buffer in words */
  93945. unsigned words; /* # of complete words in buffer */
  93946. unsigned bits; /* # of used bits in accum */
  93947. };
  93948. /* * WATCHOUT: The current implementation only grows the buffer. */
  93949. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  93950. {
  93951. unsigned new_capacity;
  93952. bwword *new_buffer;
  93953. FLAC__ASSERT(0 != bw);
  93954. FLAC__ASSERT(0 != bw->buffer);
  93955. /* calculate total words needed to store 'bits_to_add' additional bits */
  93956. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  93957. /* it's possible (due to pessimism in the growth estimation that
  93958. * leads to this call) that we don't actually need to grow
  93959. */
  93960. if(bw->capacity >= new_capacity)
  93961. return true;
  93962. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  93963. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  93964. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  93965. /* make sure we got everything right */
  93966. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  93967. FLAC__ASSERT(new_capacity > bw->capacity);
  93968. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  93969. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  93970. if(new_buffer == 0)
  93971. return false;
  93972. bw->buffer = new_buffer;
  93973. bw->capacity = new_capacity;
  93974. return true;
  93975. }
  93976. /***********************************************************************
  93977. *
  93978. * Class constructor/destructor
  93979. *
  93980. ***********************************************************************/
  93981. FLAC__BitWriter *FLAC__bitwriter_new(void)
  93982. {
  93983. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  93984. /* note that calloc() sets all members to 0 for us */
  93985. return bw;
  93986. }
  93987. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  93988. {
  93989. FLAC__ASSERT(0 != bw);
  93990. FLAC__bitwriter_free(bw);
  93991. free(bw);
  93992. }
  93993. /***********************************************************************
  93994. *
  93995. * Public class methods
  93996. *
  93997. ***********************************************************************/
  93998. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  93999. {
  94000. FLAC__ASSERT(0 != bw);
  94001. bw->words = bw->bits = 0;
  94002. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94003. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94004. if(bw->buffer == 0)
  94005. return false;
  94006. return true;
  94007. }
  94008. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94009. {
  94010. FLAC__ASSERT(0 != bw);
  94011. if(0 != bw->buffer)
  94012. free(bw->buffer);
  94013. bw->buffer = 0;
  94014. bw->capacity = 0;
  94015. bw->words = bw->bits = 0;
  94016. }
  94017. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94018. {
  94019. bw->words = bw->bits = 0;
  94020. }
  94021. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94022. {
  94023. unsigned i, j;
  94024. if(bw == 0) {
  94025. fprintf(out, "bitwriter is NULL\n");
  94026. }
  94027. else {
  94028. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94029. for(i = 0; i < bw->words; i++) {
  94030. fprintf(out, "%08X: ", i);
  94031. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94032. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94033. fprintf(out, "\n");
  94034. }
  94035. if(bw->bits > 0) {
  94036. fprintf(out, "%08X: ", i);
  94037. for(j = 0; j < bw->bits; j++)
  94038. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94039. fprintf(out, "\n");
  94040. }
  94041. }
  94042. }
  94043. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94044. {
  94045. const FLAC__byte *buffer;
  94046. size_t bytes;
  94047. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94048. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94049. return false;
  94050. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94051. FLAC__bitwriter_release_buffer(bw);
  94052. return true;
  94053. }
  94054. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94055. {
  94056. const FLAC__byte *buffer;
  94057. size_t bytes;
  94058. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94059. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94060. return false;
  94061. *crc = FLAC__crc8(buffer, bytes);
  94062. FLAC__bitwriter_release_buffer(bw);
  94063. return true;
  94064. }
  94065. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94066. {
  94067. return ((bw->bits & 7) == 0);
  94068. }
  94069. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94070. {
  94071. return FLAC__TOTAL_BITS(bw);
  94072. }
  94073. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94074. {
  94075. FLAC__ASSERT((bw->bits & 7) == 0);
  94076. /* double protection */
  94077. if(bw->bits & 7)
  94078. return false;
  94079. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94080. if(bw->bits) {
  94081. FLAC__ASSERT(bw->words <= bw->capacity);
  94082. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94083. return false;
  94084. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94085. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94086. }
  94087. /* now we can just return what we have */
  94088. *buffer = (FLAC__byte*)bw->buffer;
  94089. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94090. return true;
  94091. }
  94092. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94093. {
  94094. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94095. * get-mode' flag could be added everywhere and then cleared here
  94096. */
  94097. (void)bw;
  94098. }
  94099. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94100. {
  94101. unsigned n;
  94102. FLAC__ASSERT(0 != bw);
  94103. FLAC__ASSERT(0 != bw->buffer);
  94104. if(bits == 0)
  94105. return true;
  94106. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94107. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94108. return false;
  94109. /* first part gets to word alignment */
  94110. if(bw->bits) {
  94111. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94112. bw->accum <<= n;
  94113. bits -= n;
  94114. bw->bits += n;
  94115. if(bw->bits == FLAC__BITS_PER_WORD) {
  94116. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94117. bw->bits = 0;
  94118. }
  94119. else
  94120. return true;
  94121. }
  94122. /* do whole words */
  94123. while(bits >= FLAC__BITS_PER_WORD) {
  94124. bw->buffer[bw->words++] = 0;
  94125. bits -= FLAC__BITS_PER_WORD;
  94126. }
  94127. /* do any leftovers */
  94128. if(bits > 0) {
  94129. bw->accum = 0;
  94130. bw->bits = bits;
  94131. }
  94132. return true;
  94133. }
  94134. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94135. {
  94136. register unsigned left;
  94137. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94138. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94139. FLAC__ASSERT(0 != bw);
  94140. FLAC__ASSERT(0 != bw->buffer);
  94141. FLAC__ASSERT(bits <= 32);
  94142. if(bits == 0)
  94143. return true;
  94144. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94145. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94146. return false;
  94147. left = FLAC__BITS_PER_WORD - bw->bits;
  94148. if(bits < left) {
  94149. bw->accum <<= bits;
  94150. bw->accum |= val;
  94151. bw->bits += bits;
  94152. }
  94153. 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 */
  94154. bw->accum <<= left;
  94155. bw->accum |= val >> (bw->bits = bits - left);
  94156. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94157. bw->accum = val;
  94158. }
  94159. else {
  94160. bw->accum = val;
  94161. bw->bits = 0;
  94162. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94163. }
  94164. return true;
  94165. }
  94166. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94167. {
  94168. /* zero-out unused bits */
  94169. if(bits < 32)
  94170. val &= (~(0xffffffff << bits));
  94171. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94172. }
  94173. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94174. {
  94175. /* this could be a little faster but it's not used for much */
  94176. if(bits > 32) {
  94177. return
  94178. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94179. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94180. }
  94181. else
  94182. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94183. }
  94184. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94185. {
  94186. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94187. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94188. return false;
  94189. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94190. return false;
  94191. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94192. return false;
  94193. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94194. return false;
  94195. return true;
  94196. }
  94197. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94198. {
  94199. unsigned i;
  94200. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94201. for(i = 0; i < nvals; i++) {
  94202. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94203. return false;
  94204. }
  94205. return true;
  94206. }
  94207. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94208. {
  94209. if(val < 32)
  94210. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94211. else
  94212. return
  94213. FLAC__bitwriter_write_zeroes(bw, val) &&
  94214. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94215. }
  94216. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94217. {
  94218. FLAC__uint32 uval;
  94219. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94220. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94221. uval = (val<<1) ^ (val>>31);
  94222. return 1 + parameter + (uval >> parameter);
  94223. }
  94224. #if 0 /* UNUSED */
  94225. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94226. {
  94227. unsigned bits, msbs, uval;
  94228. unsigned k;
  94229. FLAC__ASSERT(parameter > 0);
  94230. /* fold signed to unsigned */
  94231. if(val < 0)
  94232. uval = (unsigned)(((-(++val)) << 1) + 1);
  94233. else
  94234. uval = (unsigned)(val << 1);
  94235. k = FLAC__bitmath_ilog2(parameter);
  94236. if(parameter == 1u<<k) {
  94237. FLAC__ASSERT(k <= 30);
  94238. msbs = uval >> k;
  94239. bits = 1 + k + msbs;
  94240. }
  94241. else {
  94242. unsigned q, r, d;
  94243. d = (1 << (k+1)) - parameter;
  94244. q = uval / parameter;
  94245. r = uval - (q * parameter);
  94246. bits = 1 + q + k;
  94247. if(r >= d)
  94248. bits++;
  94249. }
  94250. return bits;
  94251. }
  94252. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  94253. {
  94254. unsigned bits, msbs;
  94255. unsigned k;
  94256. FLAC__ASSERT(parameter > 0);
  94257. k = FLAC__bitmath_ilog2(parameter);
  94258. if(parameter == 1u<<k) {
  94259. FLAC__ASSERT(k <= 30);
  94260. msbs = uval >> k;
  94261. bits = 1 + k + msbs;
  94262. }
  94263. else {
  94264. unsigned q, r, d;
  94265. d = (1 << (k+1)) - parameter;
  94266. q = uval / parameter;
  94267. r = uval - (q * parameter);
  94268. bits = 1 + q + k;
  94269. if(r >= d)
  94270. bits++;
  94271. }
  94272. return bits;
  94273. }
  94274. #endif /* UNUSED */
  94275. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  94276. {
  94277. unsigned total_bits, interesting_bits, msbs;
  94278. FLAC__uint32 uval, pattern;
  94279. FLAC__ASSERT(0 != bw);
  94280. FLAC__ASSERT(0 != bw->buffer);
  94281. FLAC__ASSERT(parameter < 8*sizeof(uval));
  94282. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94283. uval = (val<<1) ^ (val>>31);
  94284. msbs = uval >> parameter;
  94285. interesting_bits = 1 + parameter;
  94286. total_bits = interesting_bits + msbs;
  94287. pattern = 1 << parameter; /* the unary end bit */
  94288. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  94289. if(total_bits <= 32)
  94290. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  94291. else
  94292. return
  94293. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  94294. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  94295. }
  94296. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  94297. {
  94298. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  94299. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  94300. FLAC__uint32 uval;
  94301. unsigned left;
  94302. const unsigned lsbits = 1 + parameter;
  94303. unsigned msbits;
  94304. FLAC__ASSERT(0 != bw);
  94305. FLAC__ASSERT(0 != bw->buffer);
  94306. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94307. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94308. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94309. while(nvals) {
  94310. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94311. uval = (*vals<<1) ^ (*vals>>31);
  94312. msbits = uval >> parameter;
  94313. #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) */
  94314. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94315. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94316. bw->bits = bw->bits + msbits + lsbits;
  94317. uval |= mask1; /* set stop bit */
  94318. uval &= mask2; /* mask off unused top bits */
  94319. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94320. bw->accum <<= msbits;
  94321. bw->accum <<= lsbits;
  94322. bw->accum |= uval;
  94323. if(bw->bits == FLAC__BITS_PER_WORD) {
  94324. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94325. bw->bits = 0;
  94326. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94327. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94328. FLAC__ASSERT(bw->capacity == bw->words);
  94329. return false;
  94330. }
  94331. }
  94332. }
  94333. else {
  94334. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94335. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94336. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94337. bw->bits = bw->bits + msbits + lsbits;
  94338. uval |= mask1; /* set stop bit */
  94339. uval &= mask2; /* mask off unused top bits */
  94340. bw->accum <<= msbits + lsbits;
  94341. bw->accum |= uval;
  94342. }
  94343. else {
  94344. #endif
  94345. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94346. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94347. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94348. return false;
  94349. if(msbits) {
  94350. /* first part gets to word alignment */
  94351. if(bw->bits) {
  94352. left = FLAC__BITS_PER_WORD - bw->bits;
  94353. if(msbits < left) {
  94354. bw->accum <<= msbits;
  94355. bw->bits += msbits;
  94356. goto break1;
  94357. }
  94358. else {
  94359. bw->accum <<= left;
  94360. msbits -= left;
  94361. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94362. bw->bits = 0;
  94363. }
  94364. }
  94365. /* do whole words */
  94366. while(msbits >= FLAC__BITS_PER_WORD) {
  94367. bw->buffer[bw->words++] = 0;
  94368. msbits -= FLAC__BITS_PER_WORD;
  94369. }
  94370. /* do any leftovers */
  94371. if(msbits > 0) {
  94372. bw->accum = 0;
  94373. bw->bits = msbits;
  94374. }
  94375. }
  94376. break1:
  94377. uval |= mask1; /* set stop bit */
  94378. uval &= mask2; /* mask off unused top bits */
  94379. left = FLAC__BITS_PER_WORD - bw->bits;
  94380. if(lsbits < left) {
  94381. bw->accum <<= lsbits;
  94382. bw->accum |= uval;
  94383. bw->bits += lsbits;
  94384. }
  94385. else {
  94386. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  94387. * be > lsbits (because of previous assertions) so it would have
  94388. * triggered the (lsbits<left) case above.
  94389. */
  94390. FLAC__ASSERT(bw->bits);
  94391. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  94392. bw->accum <<= left;
  94393. bw->accum |= uval >> (bw->bits = lsbits - left);
  94394. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94395. bw->accum = uval;
  94396. }
  94397. #if 1
  94398. }
  94399. #endif
  94400. vals++;
  94401. nvals--;
  94402. }
  94403. return true;
  94404. }
  94405. #if 0 /* UNUSED */
  94406. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  94407. {
  94408. unsigned total_bits, msbs, uval;
  94409. unsigned k;
  94410. FLAC__ASSERT(0 != bw);
  94411. FLAC__ASSERT(0 != bw->buffer);
  94412. FLAC__ASSERT(parameter > 0);
  94413. /* fold signed to unsigned */
  94414. if(val < 0)
  94415. uval = (unsigned)(((-(++val)) << 1) + 1);
  94416. else
  94417. uval = (unsigned)(val << 1);
  94418. k = FLAC__bitmath_ilog2(parameter);
  94419. if(parameter == 1u<<k) {
  94420. unsigned pattern;
  94421. FLAC__ASSERT(k <= 30);
  94422. msbs = uval >> k;
  94423. total_bits = 1 + k + msbs;
  94424. pattern = 1 << k; /* the unary end bit */
  94425. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94426. if(total_bits <= 32) {
  94427. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94428. return false;
  94429. }
  94430. else {
  94431. /* write the unary MSBs */
  94432. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94433. return false;
  94434. /* write the unary end bit and binary LSBs */
  94435. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94436. return false;
  94437. }
  94438. }
  94439. else {
  94440. unsigned q, r, d;
  94441. d = (1 << (k+1)) - parameter;
  94442. q = uval / parameter;
  94443. r = uval - (q * parameter);
  94444. /* write the unary MSBs */
  94445. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94446. return false;
  94447. /* write the unary end bit */
  94448. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94449. return false;
  94450. /* write the binary LSBs */
  94451. if(r >= d) {
  94452. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94453. return false;
  94454. }
  94455. else {
  94456. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94457. return false;
  94458. }
  94459. }
  94460. return true;
  94461. }
  94462. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  94463. {
  94464. unsigned total_bits, msbs;
  94465. unsigned k;
  94466. FLAC__ASSERT(0 != bw);
  94467. FLAC__ASSERT(0 != bw->buffer);
  94468. FLAC__ASSERT(parameter > 0);
  94469. k = FLAC__bitmath_ilog2(parameter);
  94470. if(parameter == 1u<<k) {
  94471. unsigned pattern;
  94472. FLAC__ASSERT(k <= 30);
  94473. msbs = uval >> k;
  94474. total_bits = 1 + k + msbs;
  94475. pattern = 1 << k; /* the unary end bit */
  94476. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94477. if(total_bits <= 32) {
  94478. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94479. return false;
  94480. }
  94481. else {
  94482. /* write the unary MSBs */
  94483. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94484. return false;
  94485. /* write the unary end bit and binary LSBs */
  94486. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94487. return false;
  94488. }
  94489. }
  94490. else {
  94491. unsigned q, r, d;
  94492. d = (1 << (k+1)) - parameter;
  94493. q = uval / parameter;
  94494. r = uval - (q * parameter);
  94495. /* write the unary MSBs */
  94496. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94497. return false;
  94498. /* write the unary end bit */
  94499. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94500. return false;
  94501. /* write the binary LSBs */
  94502. if(r >= d) {
  94503. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94504. return false;
  94505. }
  94506. else {
  94507. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94508. return false;
  94509. }
  94510. }
  94511. return true;
  94512. }
  94513. #endif /* UNUSED */
  94514. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  94515. {
  94516. FLAC__bool ok = 1;
  94517. FLAC__ASSERT(0 != bw);
  94518. FLAC__ASSERT(0 != bw->buffer);
  94519. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  94520. if(val < 0x80) {
  94521. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  94522. }
  94523. else if(val < 0x800) {
  94524. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  94525. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94526. }
  94527. else if(val < 0x10000) {
  94528. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  94529. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94530. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94531. }
  94532. else if(val < 0x200000) {
  94533. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  94534. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94535. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94536. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94537. }
  94538. else if(val < 0x4000000) {
  94539. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  94540. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94541. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94542. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94543. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94544. }
  94545. else {
  94546. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  94547. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  94548. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94549. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94550. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94551. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94552. }
  94553. return ok;
  94554. }
  94555. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  94556. {
  94557. FLAC__bool ok = 1;
  94558. FLAC__ASSERT(0 != bw);
  94559. FLAC__ASSERT(0 != bw->buffer);
  94560. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  94561. if(val < 0x80) {
  94562. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  94563. }
  94564. else if(val < 0x800) {
  94565. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  94566. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94567. }
  94568. else if(val < 0x10000) {
  94569. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  94570. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94571. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94572. }
  94573. else if(val < 0x200000) {
  94574. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  94575. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94576. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94577. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94578. }
  94579. else if(val < 0x4000000) {
  94580. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  94581. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94582. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94583. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94584. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94585. }
  94586. else if(val < 0x80000000) {
  94587. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  94588. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94589. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94590. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94591. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94592. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94593. }
  94594. else {
  94595. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  94596. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  94597. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94598. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94599. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94600. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94601. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94602. }
  94603. return ok;
  94604. }
  94605. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  94606. {
  94607. /* 0-pad to byte boundary */
  94608. if(bw->bits & 7u)
  94609. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  94610. else
  94611. return true;
  94612. }
  94613. #endif
  94614. /*** End of inlined file: bitwriter.c ***/
  94615. /*** Start of inlined file: cpu.c ***/
  94616. /*** Start of inlined file: juce_FlacHeader.h ***/
  94617. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94618. // tasks..
  94619. #define VERSION "1.2.1"
  94620. #define FLAC__NO_DLL 1
  94621. #if JUCE_MSVC
  94622. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94623. #endif
  94624. #if JUCE_MAC
  94625. #define FLAC__SYS_DARWIN 1
  94626. #endif
  94627. /*** End of inlined file: juce_FlacHeader.h ***/
  94628. #if JUCE_USE_FLAC
  94629. #if HAVE_CONFIG_H
  94630. # include <config.h>
  94631. #endif
  94632. #include <stdlib.h>
  94633. #include <stdio.h>
  94634. #if defined FLAC__CPU_IA32
  94635. # include <signal.h>
  94636. #elif defined FLAC__CPU_PPC
  94637. # if !defined FLAC__NO_ASM
  94638. # if defined FLAC__SYS_DARWIN
  94639. # include <sys/sysctl.h>
  94640. # include <mach/mach.h>
  94641. # include <mach/mach_host.h>
  94642. # include <mach/host_info.h>
  94643. # include <mach/machine.h>
  94644. # ifndef CPU_SUBTYPE_POWERPC_970
  94645. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  94646. # endif
  94647. # else /* FLAC__SYS_DARWIN */
  94648. # include <signal.h>
  94649. # include <setjmp.h>
  94650. static sigjmp_buf jmpbuf;
  94651. static volatile sig_atomic_t canjump = 0;
  94652. static void sigill_handler (int sig)
  94653. {
  94654. if (!canjump) {
  94655. signal (sig, SIG_DFL);
  94656. raise (sig);
  94657. }
  94658. canjump = 0;
  94659. siglongjmp (jmpbuf, 1);
  94660. }
  94661. # endif /* FLAC__SYS_DARWIN */
  94662. # endif /* FLAC__NO_ASM */
  94663. #endif /* FLAC__CPU_PPC */
  94664. #if defined (__NetBSD__) || defined(__OpenBSD__)
  94665. #include <sys/param.h>
  94666. #include <sys/sysctl.h>
  94667. #include <machine/cpu.h>
  94668. #endif
  94669. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  94670. #include <sys/types.h>
  94671. #include <sys/sysctl.h>
  94672. #endif
  94673. #if defined(__APPLE__)
  94674. /* how to get sysctlbyname()? */
  94675. #endif
  94676. /* these are flags in EDX of CPUID AX=00000001 */
  94677. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  94678. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  94679. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  94680. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  94681. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  94682. /* these are flags in ECX of CPUID AX=00000001 */
  94683. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  94684. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  94685. /* these are flags in EDX of CPUID AX=80000001 */
  94686. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  94687. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  94688. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  94689. /*
  94690. * Extra stuff needed for detection of OS support for SSE on IA-32
  94691. */
  94692. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  94693. # if defined(__linux__)
  94694. /*
  94695. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  94696. * modify the return address to jump over the offending SSE instruction
  94697. * and also the operation following it that indicates the instruction
  94698. * executed successfully. In this way we use no global variables and
  94699. * stay thread-safe.
  94700. *
  94701. * 3 + 3 + 6:
  94702. * 3 bytes for "xorps xmm0,xmm0"
  94703. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  94704. * 6 bytes extra in case our estimate is wrong
  94705. * 12 bytes puts us in the NOP "landing zone"
  94706. */
  94707. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  94708. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  94709. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  94710. {
  94711. (void)signal;
  94712. sc.eip += 3 + 3 + 6;
  94713. }
  94714. # else
  94715. # include <sys/ucontext.h>
  94716. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  94717. {
  94718. (void)signal, (void)si;
  94719. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  94720. }
  94721. # endif
  94722. # elif defined(_MSC_VER)
  94723. # include <windows.h>
  94724. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  94725. # ifdef USE_TRY_CATCH_FLAVOR
  94726. # else
  94727. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  94728. {
  94729. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  94730. ep->ContextRecord->Eip += 3 + 3 + 6;
  94731. return EXCEPTION_CONTINUE_EXECUTION;
  94732. }
  94733. return EXCEPTION_CONTINUE_SEARCH;
  94734. }
  94735. # endif
  94736. # endif
  94737. #endif
  94738. void FLAC__cpu_info(FLAC__CPUInfo *info)
  94739. {
  94740. /*
  94741. * IA32-specific
  94742. */
  94743. #ifdef FLAC__CPU_IA32
  94744. info->type = FLAC__CPUINFO_TYPE_IA32;
  94745. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  94746. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  94747. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  94748. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  94749. info->data.ia32.cmov = false;
  94750. info->data.ia32.mmx = false;
  94751. info->data.ia32.fxsr = false;
  94752. info->data.ia32.sse = false;
  94753. info->data.ia32.sse2 = false;
  94754. info->data.ia32.sse3 = false;
  94755. info->data.ia32.ssse3 = false;
  94756. info->data.ia32._3dnow = false;
  94757. info->data.ia32.ext3dnow = false;
  94758. info->data.ia32.extmmx = false;
  94759. if(info->data.ia32.cpuid) {
  94760. /* http://www.sandpile.org/ia32/cpuid.htm */
  94761. FLAC__uint32 flags_edx, flags_ecx;
  94762. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  94763. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  94764. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  94765. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  94766. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  94767. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  94768. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  94769. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  94770. #ifdef FLAC__USE_3DNOW
  94771. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  94772. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  94773. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  94774. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  94775. #else
  94776. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  94777. #endif
  94778. #ifdef DEBUG
  94779. fprintf(stderr, "CPU info (IA-32):\n");
  94780. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  94781. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  94782. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  94783. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  94784. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  94785. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  94786. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  94787. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  94788. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  94789. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  94790. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  94791. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  94792. #endif
  94793. /*
  94794. * now have to check for OS support of SSE/SSE2
  94795. */
  94796. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  94797. #if defined FLAC__NO_SSE_OS
  94798. /* assume user knows better than us; turn it off */
  94799. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94800. #elif defined FLAC__SSE_OS
  94801. /* assume user knows better than us; leave as detected above */
  94802. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  94803. int sse = 0;
  94804. size_t len;
  94805. /* at least one of these must work: */
  94806. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  94807. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  94808. if(!sse)
  94809. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94810. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  94811. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  94812. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  94813. size_t len = sizeof(val);
  94814. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  94815. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94816. else { /* double-check SSE2 */
  94817. mib[1] = CPU_SSE2;
  94818. len = sizeof(val);
  94819. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  94820. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94821. }
  94822. # else
  94823. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94824. # endif
  94825. #elif defined(__linux__)
  94826. int sse = 0;
  94827. struct sigaction sigill_save;
  94828. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  94829. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  94830. #else
  94831. struct sigaction sigill_sse;
  94832. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  94833. __sigemptyset(&sigill_sse.sa_mask);
  94834. 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 */
  94835. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  94836. #endif
  94837. {
  94838. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  94839. /* see sigill_handler_sse_os() for an explanation of the following: */
  94840. asm volatile (
  94841. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  94842. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  94843. "incl %0\n\t" /* SIGILL handler will jump over this */
  94844. /* landing zone */
  94845. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  94846. "nop\n\t"
  94847. "nop\n\t"
  94848. "nop\n\t"
  94849. "nop\n\t"
  94850. "nop\n\t"
  94851. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  94852. "nop\n\t"
  94853. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  94854. : "=r"(sse)
  94855. : "r"(sse)
  94856. );
  94857. sigaction(SIGILL, &sigill_save, NULL);
  94858. }
  94859. if(!sse)
  94860. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94861. #elif defined(_MSC_VER)
  94862. # ifdef USE_TRY_CATCH_FLAVOR
  94863. _try {
  94864. __asm {
  94865. # if _MSC_VER <= 1200
  94866. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  94867. _emit 0x0F
  94868. _emit 0x57
  94869. _emit 0xC0
  94870. # else
  94871. xorps xmm0,xmm0
  94872. # endif
  94873. }
  94874. }
  94875. _except(EXCEPTION_EXECUTE_HANDLER) {
  94876. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  94877. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94878. }
  94879. # else
  94880. int sse = 0;
  94881. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  94882. /* see GCC version above for explanation */
  94883. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  94884. /* http://www.codeproject.com/cpp/gccasm.asp */
  94885. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  94886. __asm {
  94887. # if _MSC_VER <= 1200
  94888. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  94889. _emit 0x0F
  94890. _emit 0x57
  94891. _emit 0xC0
  94892. # else
  94893. xorps xmm0,xmm0
  94894. # endif
  94895. inc sse
  94896. nop
  94897. nop
  94898. nop
  94899. nop
  94900. nop
  94901. nop
  94902. nop
  94903. nop
  94904. nop
  94905. }
  94906. SetUnhandledExceptionFilter(save);
  94907. if(!sse)
  94908. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94909. # endif
  94910. #else
  94911. /* no way to test, disable to be safe */
  94912. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94913. #endif
  94914. #ifdef DEBUG
  94915. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  94916. #endif
  94917. }
  94918. }
  94919. #else
  94920. info->use_asm = false;
  94921. #endif
  94922. /*
  94923. * PPC-specific
  94924. */
  94925. #elif defined FLAC__CPU_PPC
  94926. info->type = FLAC__CPUINFO_TYPE_PPC;
  94927. # if !defined FLAC__NO_ASM
  94928. info->use_asm = true;
  94929. # ifdef FLAC__USE_ALTIVEC
  94930. # if defined FLAC__SYS_DARWIN
  94931. {
  94932. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  94933. size_t len = sizeof(val);
  94934. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  94935. }
  94936. {
  94937. host_basic_info_data_t hostInfo;
  94938. mach_msg_type_number_t infoCount;
  94939. infoCount = HOST_BASIC_INFO_COUNT;
  94940. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  94941. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  94942. }
  94943. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  94944. {
  94945. /* no Darwin, do it the brute-force way */
  94946. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  94947. info->data.ppc.altivec = 0;
  94948. info->data.ppc.ppc64 = 0;
  94949. signal (SIGILL, sigill_handler);
  94950. canjump = 0;
  94951. if (!sigsetjmp (jmpbuf, 1)) {
  94952. canjump = 1;
  94953. asm volatile (
  94954. "mtspr 256, %0\n\t"
  94955. "vand %%v0, %%v0, %%v0"
  94956. :
  94957. : "r" (-1)
  94958. );
  94959. info->data.ppc.altivec = 1;
  94960. }
  94961. canjump = 0;
  94962. if (!sigsetjmp (jmpbuf, 1)) {
  94963. int x = 0;
  94964. canjump = 1;
  94965. /* PPC64 hardware implements the cntlzd instruction */
  94966. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  94967. info->data.ppc.ppc64 = 1;
  94968. }
  94969. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  94970. }
  94971. # endif
  94972. # else /* !FLAC__USE_ALTIVEC */
  94973. info->data.ppc.altivec = 0;
  94974. info->data.ppc.ppc64 = 0;
  94975. # endif
  94976. # else
  94977. info->use_asm = false;
  94978. # endif
  94979. /*
  94980. * unknown CPI
  94981. */
  94982. #else
  94983. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  94984. info->use_asm = false;
  94985. #endif
  94986. }
  94987. #endif
  94988. /*** End of inlined file: cpu.c ***/
  94989. /*** Start of inlined file: crc.c ***/
  94990. /*** Start of inlined file: juce_FlacHeader.h ***/
  94991. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94992. // tasks..
  94993. #define VERSION "1.2.1"
  94994. #define FLAC__NO_DLL 1
  94995. #if JUCE_MSVC
  94996. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94997. #endif
  94998. #if JUCE_MAC
  94999. #define FLAC__SYS_DARWIN 1
  95000. #endif
  95001. /*** End of inlined file: juce_FlacHeader.h ***/
  95002. #if JUCE_USE_FLAC
  95003. #if HAVE_CONFIG_H
  95004. # include <config.h>
  95005. #endif
  95006. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95007. FLAC__byte const FLAC__crc8_table[256] = {
  95008. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95009. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95010. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95011. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95012. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95013. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95014. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95015. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95016. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95017. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95018. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95019. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95020. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95021. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95022. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95023. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95024. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95025. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95026. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95027. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95028. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95029. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95030. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95031. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95032. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95033. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95034. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95035. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95036. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95037. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95038. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95039. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95040. };
  95041. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95042. unsigned FLAC__crc16_table[256] = {
  95043. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95044. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95045. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95046. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95047. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95048. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95049. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95050. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95051. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95052. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95053. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95054. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95055. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95056. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95057. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95058. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95059. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95060. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95061. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95062. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95063. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95064. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95065. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95066. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95067. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95068. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95069. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95070. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95071. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95072. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95073. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95074. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95075. };
  95076. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95077. {
  95078. *crc = FLAC__crc8_table[*crc ^ data];
  95079. }
  95080. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95081. {
  95082. while(len--)
  95083. *crc = FLAC__crc8_table[*crc ^ *data++];
  95084. }
  95085. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95086. {
  95087. FLAC__uint8 crc = 0;
  95088. while(len--)
  95089. crc = FLAC__crc8_table[crc ^ *data++];
  95090. return crc;
  95091. }
  95092. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95093. {
  95094. unsigned crc = 0;
  95095. while(len--)
  95096. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95097. return crc;
  95098. }
  95099. #endif
  95100. /*** End of inlined file: crc.c ***/
  95101. /*** Start of inlined file: fixed.c ***/
  95102. /*** Start of inlined file: juce_FlacHeader.h ***/
  95103. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95104. // tasks..
  95105. #define VERSION "1.2.1"
  95106. #define FLAC__NO_DLL 1
  95107. #if JUCE_MSVC
  95108. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95109. #endif
  95110. #if JUCE_MAC
  95111. #define FLAC__SYS_DARWIN 1
  95112. #endif
  95113. /*** End of inlined file: juce_FlacHeader.h ***/
  95114. #if JUCE_USE_FLAC
  95115. #if HAVE_CONFIG_H
  95116. # include <config.h>
  95117. #endif
  95118. #include <math.h>
  95119. #include <string.h>
  95120. /*** Start of inlined file: fixed.h ***/
  95121. #ifndef FLAC__PRIVATE__FIXED_H
  95122. #define FLAC__PRIVATE__FIXED_H
  95123. #ifdef HAVE_CONFIG_H
  95124. #include <config.h>
  95125. #endif
  95126. /*** Start of inlined file: float.h ***/
  95127. #ifndef FLAC__PRIVATE__FLOAT_H
  95128. #define FLAC__PRIVATE__FLOAT_H
  95129. #ifdef HAVE_CONFIG_H
  95130. #include <config.h>
  95131. #endif
  95132. /*
  95133. * These typedefs make it easier to ensure that integer versions of
  95134. * the library really only contain integer operations. All the code
  95135. * in libFLAC should use FLAC__float and FLAC__double in place of
  95136. * float and double, and be protected by checks of the macro
  95137. * FLAC__INTEGER_ONLY_LIBRARY.
  95138. *
  95139. * FLAC__real is the basic floating point type used in LPC analysis.
  95140. */
  95141. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95142. typedef double FLAC__double;
  95143. typedef float FLAC__float;
  95144. /*
  95145. * WATCHOUT: changing FLAC__real will change the signatures of many
  95146. * functions that have assembly language equivalents and break them.
  95147. */
  95148. typedef float FLAC__real;
  95149. #else
  95150. /*
  95151. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95152. * for the integer part and lower 16 bits for the fractional part.
  95153. */
  95154. typedef FLAC__int32 FLAC__fixedpoint;
  95155. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95156. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95157. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95158. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95159. extern const FLAC__fixedpoint FLAC__FP_E;
  95160. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95161. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95162. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95163. /*
  95164. * FLAC__fixedpoint_log2()
  95165. * --------------------------------------------------------------------
  95166. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95167. * algorithm by Knuth for x >= 1.0
  95168. *
  95169. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95170. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95171. *
  95172. * 'precision' roughly limits the number of iterations that are done;
  95173. * use (unsigned)(-1) for maximum precision.
  95174. *
  95175. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95176. * function will punt and return 0.
  95177. *
  95178. * The return value will also have 'fracbits' fractional bits.
  95179. */
  95180. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95181. #endif
  95182. #endif
  95183. /*** End of inlined file: float.h ***/
  95184. /*** Start of inlined file: format.h ***/
  95185. #ifndef FLAC__PRIVATE__FORMAT_H
  95186. #define FLAC__PRIVATE__FORMAT_H
  95187. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95188. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95189. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95190. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95191. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95192. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95193. #endif
  95194. /*** End of inlined file: format.h ***/
  95195. /*
  95196. * FLAC__fixed_compute_best_predictor()
  95197. * --------------------------------------------------------------------
  95198. * Compute the best fixed predictor and the expected bits-per-sample
  95199. * of the residual signal for each order. The _wide() version uses
  95200. * 64-bit integers which is statistically necessary when bits-per-
  95201. * sample + log2(blocksize) > 30
  95202. *
  95203. * IN data[0,data_len-1]
  95204. * IN data_len
  95205. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95206. */
  95207. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95208. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95209. # ifndef FLAC__NO_ASM
  95210. # ifdef FLAC__CPU_IA32
  95211. # ifdef FLAC__HAS_NASM
  95212. 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]);
  95213. # endif
  95214. # endif
  95215. # endif
  95216. 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]);
  95217. #else
  95218. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95219. 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]);
  95220. #endif
  95221. /*
  95222. * FLAC__fixed_compute_residual()
  95223. * --------------------------------------------------------------------
  95224. * Compute the residual signal obtained from sutracting the predicted
  95225. * signal from the original.
  95226. *
  95227. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95228. * IN data_len length of original signal
  95229. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95230. * OUT residual[0,data_len-1] residual signal
  95231. */
  95232. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95233. /*
  95234. * FLAC__fixed_restore_signal()
  95235. * --------------------------------------------------------------------
  95236. * Restore the original signal by summing the residual and the
  95237. * predictor.
  95238. *
  95239. * IN residual[0,data_len-1] residual signal
  95240. * IN data_len length of original signal
  95241. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95242. * *** IMPORTANT: the caller must pass in the historical samples:
  95243. * IN data[-order,-1] previously-reconstructed historical samples
  95244. * OUT data[0,data_len-1] original signal
  95245. */
  95246. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  95247. #endif
  95248. /*** End of inlined file: fixed.h ***/
  95249. #ifndef M_LN2
  95250. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95251. #define M_LN2 0.69314718055994530942
  95252. #endif
  95253. #ifdef min
  95254. #undef min
  95255. #endif
  95256. #define min(x,y) ((x) < (y)? (x) : (y))
  95257. #ifdef local_abs
  95258. #undef local_abs
  95259. #endif
  95260. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  95261. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95262. /* rbps stands for residual bits per sample
  95263. *
  95264. * (ln(2) * err)
  95265. * rbps = log (-----------)
  95266. * 2 ( n )
  95267. */
  95268. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  95269. {
  95270. FLAC__uint32 rbps;
  95271. unsigned bits; /* the number of bits required to represent a number */
  95272. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95273. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95274. FLAC__ASSERT(err > 0);
  95275. FLAC__ASSERT(n > 0);
  95276. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95277. if(err <= n)
  95278. return 0;
  95279. /*
  95280. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95281. * These allow us later to know we won't lose too much precision in the
  95282. * fixed-point division (err<<fracbits)/n.
  95283. */
  95284. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  95285. err <<= fracbits;
  95286. err /= n;
  95287. /* err now holds err/n with fracbits fractional bits */
  95288. /*
  95289. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95290. * our purposes.
  95291. */
  95292. FLAC__ASSERT(err > 0);
  95293. bits = FLAC__bitmath_ilog2(err)+1;
  95294. if(bits > 16) {
  95295. err >>= (bits-16);
  95296. fracbits -= (bits-16);
  95297. }
  95298. rbps = (FLAC__uint32)err;
  95299. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95300. rbps *= FLAC__FP_LN2;
  95301. fracbits += 16;
  95302. FLAC__ASSERT(fracbits >= 0);
  95303. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95304. {
  95305. const int f = fracbits & 3;
  95306. if(f) {
  95307. rbps >>= f;
  95308. fracbits -= f;
  95309. }
  95310. }
  95311. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95312. if(rbps == 0)
  95313. return 0;
  95314. /*
  95315. * The return value must have 16 fractional bits. Since the whole part
  95316. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95317. * must be >= -3, these assertion allows us to be able to shift rbps
  95318. * left if necessary to get 16 fracbits without losing any bits of the
  95319. * whole part of rbps.
  95320. *
  95321. * There is a slight chance due to accumulated error that the whole part
  95322. * will require 6 bits, so we use 6 in the assertion. Really though as
  95323. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95324. */
  95325. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95326. FLAC__ASSERT(fracbits >= -3);
  95327. /* now shift the decimal point into place */
  95328. if(fracbits < 16)
  95329. return rbps << (16-fracbits);
  95330. else if(fracbits > 16)
  95331. return rbps >> (fracbits-16);
  95332. else
  95333. return rbps;
  95334. }
  95335. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95336. {
  95337. FLAC__uint32 rbps;
  95338. unsigned bits; /* the number of bits required to represent a number */
  95339. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95340. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95341. FLAC__ASSERT(err > 0);
  95342. FLAC__ASSERT(n > 0);
  95343. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95344. if(err <= n)
  95345. return 0;
  95346. /*
  95347. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95348. * These allow us later to know we won't lose too much precision in the
  95349. * fixed-point division (err<<fracbits)/n.
  95350. */
  95351. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95352. err <<= fracbits;
  95353. err /= n;
  95354. /* err now holds err/n with fracbits fractional bits */
  95355. /*
  95356. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95357. * our purposes.
  95358. */
  95359. FLAC__ASSERT(err > 0);
  95360. bits = FLAC__bitmath_ilog2_wide(err)+1;
  95361. if(bits > 16) {
  95362. err >>= (bits-16);
  95363. fracbits -= (bits-16);
  95364. }
  95365. rbps = (FLAC__uint32)err;
  95366. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95367. rbps *= FLAC__FP_LN2;
  95368. fracbits += 16;
  95369. FLAC__ASSERT(fracbits >= 0);
  95370. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95371. {
  95372. const int f = fracbits & 3;
  95373. if(f) {
  95374. rbps >>= f;
  95375. fracbits -= f;
  95376. }
  95377. }
  95378. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95379. if(rbps == 0)
  95380. return 0;
  95381. /*
  95382. * The return value must have 16 fractional bits. Since the whole part
  95383. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95384. * must be >= -3, these assertion allows us to be able to shift rbps
  95385. * left if necessary to get 16 fracbits without losing any bits of the
  95386. * whole part of rbps.
  95387. *
  95388. * There is a slight chance due to accumulated error that the whole part
  95389. * will require 6 bits, so we use 6 in the assertion. Really though as
  95390. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95391. */
  95392. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95393. FLAC__ASSERT(fracbits >= -3);
  95394. /* now shift the decimal point into place */
  95395. if(fracbits < 16)
  95396. return rbps << (16-fracbits);
  95397. else if(fracbits > 16)
  95398. return rbps >> (fracbits-16);
  95399. else
  95400. return rbps;
  95401. }
  95402. #endif
  95403. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95404. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95405. #else
  95406. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95407. #endif
  95408. {
  95409. FLAC__int32 last_error_0 = data[-1];
  95410. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95411. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95412. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95413. FLAC__int32 error, save;
  95414. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95415. unsigned i, order;
  95416. for(i = 0; i < data_len; i++) {
  95417. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95418. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95419. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95420. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95421. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95422. }
  95423. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95424. order = 0;
  95425. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95426. order = 1;
  95427. else if(total_error_2 < min(total_error_3, total_error_4))
  95428. order = 2;
  95429. else if(total_error_3 < total_error_4)
  95430. order = 3;
  95431. else
  95432. order = 4;
  95433. /* Estimate the expected number of bits per residual signal sample. */
  95434. /* 'total_error*' is linearly related to the variance of the residual */
  95435. /* signal, so we use it directly to compute E(|x|) */
  95436. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95437. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95438. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95439. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95440. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95441. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95442. 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);
  95443. 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);
  95444. 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);
  95445. 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);
  95446. 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);
  95447. #else
  95448. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  95449. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  95450. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  95451. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  95452. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  95453. #endif
  95454. return order;
  95455. }
  95456. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95457. 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])
  95458. #else
  95459. 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])
  95460. #endif
  95461. {
  95462. FLAC__int32 last_error_0 = data[-1];
  95463. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95464. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95465. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95466. FLAC__int32 error, save;
  95467. /* total_error_* are 64-bits to avoid overflow when encoding
  95468. * erratic signals when the bits-per-sample and blocksize are
  95469. * large.
  95470. */
  95471. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95472. unsigned i, order;
  95473. for(i = 0; i < data_len; i++) {
  95474. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95475. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95476. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95477. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95478. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95479. }
  95480. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95481. order = 0;
  95482. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95483. order = 1;
  95484. else if(total_error_2 < min(total_error_3, total_error_4))
  95485. order = 2;
  95486. else if(total_error_3 < total_error_4)
  95487. order = 3;
  95488. else
  95489. order = 4;
  95490. /* Estimate the expected number of bits per residual signal sample. */
  95491. /* 'total_error*' is linearly related to the variance of the residual */
  95492. /* signal, so we use it directly to compute E(|x|) */
  95493. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95494. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95495. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95496. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95497. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95498. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95499. #if defined _MSC_VER || defined __MINGW32__
  95500. /* with MSVC you have to spoon feed it the casting */
  95501. 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);
  95502. 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);
  95503. 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);
  95504. 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);
  95505. 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);
  95506. #else
  95507. 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);
  95508. 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);
  95509. 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);
  95510. 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);
  95511. 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);
  95512. #endif
  95513. #else
  95514. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  95515. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  95516. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  95517. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  95518. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  95519. #endif
  95520. return order;
  95521. }
  95522. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  95523. {
  95524. const int idata_len = (int)data_len;
  95525. int i;
  95526. switch(order) {
  95527. case 0:
  95528. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95529. memcpy(residual, data, sizeof(residual[0])*data_len);
  95530. break;
  95531. case 1:
  95532. for(i = 0; i < idata_len; i++)
  95533. residual[i] = data[i] - data[i-1];
  95534. break;
  95535. case 2:
  95536. for(i = 0; i < idata_len; i++)
  95537. #if 1 /* OPT: may be faster with some compilers on some systems */
  95538. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  95539. #else
  95540. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  95541. #endif
  95542. break;
  95543. case 3:
  95544. for(i = 0; i < idata_len; i++)
  95545. #if 1 /* OPT: may be faster with some compilers on some systems */
  95546. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  95547. #else
  95548. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  95549. #endif
  95550. break;
  95551. case 4:
  95552. for(i = 0; i < idata_len; i++)
  95553. #if 1 /* OPT: may be faster with some compilers on some systems */
  95554. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  95555. #else
  95556. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  95557. #endif
  95558. break;
  95559. default:
  95560. FLAC__ASSERT(0);
  95561. }
  95562. }
  95563. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  95564. {
  95565. int i, idata_len = (int)data_len;
  95566. switch(order) {
  95567. case 0:
  95568. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95569. memcpy(data, residual, sizeof(residual[0])*data_len);
  95570. break;
  95571. case 1:
  95572. for(i = 0; i < idata_len; i++)
  95573. data[i] = residual[i] + data[i-1];
  95574. break;
  95575. case 2:
  95576. for(i = 0; i < idata_len; i++)
  95577. #if 1 /* OPT: may be faster with some compilers on some systems */
  95578. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  95579. #else
  95580. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  95581. #endif
  95582. break;
  95583. case 3:
  95584. for(i = 0; i < idata_len; i++)
  95585. #if 1 /* OPT: may be faster with some compilers on some systems */
  95586. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  95587. #else
  95588. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  95589. #endif
  95590. break;
  95591. case 4:
  95592. for(i = 0; i < idata_len; i++)
  95593. #if 1 /* OPT: may be faster with some compilers on some systems */
  95594. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  95595. #else
  95596. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  95597. #endif
  95598. break;
  95599. default:
  95600. FLAC__ASSERT(0);
  95601. }
  95602. }
  95603. #endif
  95604. /*** End of inlined file: fixed.c ***/
  95605. /*** Start of inlined file: float.c ***/
  95606. /*** Start of inlined file: juce_FlacHeader.h ***/
  95607. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95608. // tasks..
  95609. #define VERSION "1.2.1"
  95610. #define FLAC__NO_DLL 1
  95611. #if JUCE_MSVC
  95612. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95613. #endif
  95614. #if JUCE_MAC
  95615. #define FLAC__SYS_DARWIN 1
  95616. #endif
  95617. /*** End of inlined file: juce_FlacHeader.h ***/
  95618. #if JUCE_USE_FLAC
  95619. #if HAVE_CONFIG_H
  95620. # include <config.h>
  95621. #endif
  95622. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95623. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95624. #ifdef _MSC_VER
  95625. #define FLAC__U64L(x) x
  95626. #else
  95627. #define FLAC__U64L(x) x##LLU
  95628. #endif
  95629. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  95630. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  95631. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  95632. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  95633. const FLAC__fixedpoint FLAC__FP_E = 178145;
  95634. /* Lookup tables for Knuth's logarithm algorithm */
  95635. #define LOG2_LOOKUP_PRECISION 16
  95636. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  95637. {
  95638. /*
  95639. * 0 fraction bits
  95640. */
  95641. /* undefined */ 0x00000000,
  95642. /* lg(2/1) = */ 0x00000001,
  95643. /* lg(4/3) = */ 0x00000000,
  95644. /* lg(8/7) = */ 0x00000000,
  95645. /* lg(16/15) = */ 0x00000000,
  95646. /* lg(32/31) = */ 0x00000000,
  95647. /* lg(64/63) = */ 0x00000000,
  95648. /* lg(128/127) = */ 0x00000000,
  95649. /* lg(256/255) = */ 0x00000000,
  95650. /* lg(512/511) = */ 0x00000000,
  95651. /* lg(1024/1023) = */ 0x00000000,
  95652. /* lg(2048/2047) = */ 0x00000000,
  95653. /* lg(4096/4095) = */ 0x00000000,
  95654. /* lg(8192/8191) = */ 0x00000000,
  95655. /* lg(16384/16383) = */ 0x00000000,
  95656. /* lg(32768/32767) = */ 0x00000000
  95657. },
  95658. {
  95659. /*
  95660. * 4 fraction bits
  95661. */
  95662. /* undefined */ 0x00000000,
  95663. /* lg(2/1) = */ 0x00000010,
  95664. /* lg(4/3) = */ 0x00000007,
  95665. /* lg(8/7) = */ 0x00000003,
  95666. /* lg(16/15) = */ 0x00000001,
  95667. /* lg(32/31) = */ 0x00000001,
  95668. /* lg(64/63) = */ 0x00000000,
  95669. /* lg(128/127) = */ 0x00000000,
  95670. /* lg(256/255) = */ 0x00000000,
  95671. /* lg(512/511) = */ 0x00000000,
  95672. /* lg(1024/1023) = */ 0x00000000,
  95673. /* lg(2048/2047) = */ 0x00000000,
  95674. /* lg(4096/4095) = */ 0x00000000,
  95675. /* lg(8192/8191) = */ 0x00000000,
  95676. /* lg(16384/16383) = */ 0x00000000,
  95677. /* lg(32768/32767) = */ 0x00000000
  95678. },
  95679. {
  95680. /*
  95681. * 8 fraction bits
  95682. */
  95683. /* undefined */ 0x00000000,
  95684. /* lg(2/1) = */ 0x00000100,
  95685. /* lg(4/3) = */ 0x0000006a,
  95686. /* lg(8/7) = */ 0x00000031,
  95687. /* lg(16/15) = */ 0x00000018,
  95688. /* lg(32/31) = */ 0x0000000c,
  95689. /* lg(64/63) = */ 0x00000006,
  95690. /* lg(128/127) = */ 0x00000003,
  95691. /* lg(256/255) = */ 0x00000001,
  95692. /* lg(512/511) = */ 0x00000001,
  95693. /* lg(1024/1023) = */ 0x00000000,
  95694. /* lg(2048/2047) = */ 0x00000000,
  95695. /* lg(4096/4095) = */ 0x00000000,
  95696. /* lg(8192/8191) = */ 0x00000000,
  95697. /* lg(16384/16383) = */ 0x00000000,
  95698. /* lg(32768/32767) = */ 0x00000000
  95699. },
  95700. {
  95701. /*
  95702. * 12 fraction bits
  95703. */
  95704. /* undefined */ 0x00000000,
  95705. /* lg(2/1) = */ 0x00001000,
  95706. /* lg(4/3) = */ 0x000006a4,
  95707. /* lg(8/7) = */ 0x00000315,
  95708. /* lg(16/15) = */ 0x0000017d,
  95709. /* lg(32/31) = */ 0x000000bc,
  95710. /* lg(64/63) = */ 0x0000005d,
  95711. /* lg(128/127) = */ 0x0000002e,
  95712. /* lg(256/255) = */ 0x00000017,
  95713. /* lg(512/511) = */ 0x0000000c,
  95714. /* lg(1024/1023) = */ 0x00000006,
  95715. /* lg(2048/2047) = */ 0x00000003,
  95716. /* lg(4096/4095) = */ 0x00000001,
  95717. /* lg(8192/8191) = */ 0x00000001,
  95718. /* lg(16384/16383) = */ 0x00000000,
  95719. /* lg(32768/32767) = */ 0x00000000
  95720. },
  95721. {
  95722. /*
  95723. * 16 fraction bits
  95724. */
  95725. /* undefined */ 0x00000000,
  95726. /* lg(2/1) = */ 0x00010000,
  95727. /* lg(4/3) = */ 0x00006a40,
  95728. /* lg(8/7) = */ 0x00003151,
  95729. /* lg(16/15) = */ 0x000017d6,
  95730. /* lg(32/31) = */ 0x00000bba,
  95731. /* lg(64/63) = */ 0x000005d1,
  95732. /* lg(128/127) = */ 0x000002e6,
  95733. /* lg(256/255) = */ 0x00000172,
  95734. /* lg(512/511) = */ 0x000000b9,
  95735. /* lg(1024/1023) = */ 0x0000005c,
  95736. /* lg(2048/2047) = */ 0x0000002e,
  95737. /* lg(4096/4095) = */ 0x00000017,
  95738. /* lg(8192/8191) = */ 0x0000000c,
  95739. /* lg(16384/16383) = */ 0x00000006,
  95740. /* lg(32768/32767) = */ 0x00000003
  95741. },
  95742. {
  95743. /*
  95744. * 20 fraction bits
  95745. */
  95746. /* undefined */ 0x00000000,
  95747. /* lg(2/1) = */ 0x00100000,
  95748. /* lg(4/3) = */ 0x0006a3fe,
  95749. /* lg(8/7) = */ 0x00031513,
  95750. /* lg(16/15) = */ 0x00017d60,
  95751. /* lg(32/31) = */ 0x0000bb9d,
  95752. /* lg(64/63) = */ 0x00005d10,
  95753. /* lg(128/127) = */ 0x00002e59,
  95754. /* lg(256/255) = */ 0x00001721,
  95755. /* lg(512/511) = */ 0x00000b8e,
  95756. /* lg(1024/1023) = */ 0x000005c6,
  95757. /* lg(2048/2047) = */ 0x000002e3,
  95758. /* lg(4096/4095) = */ 0x00000171,
  95759. /* lg(8192/8191) = */ 0x000000b9,
  95760. /* lg(16384/16383) = */ 0x0000005c,
  95761. /* lg(32768/32767) = */ 0x0000002e
  95762. },
  95763. {
  95764. /*
  95765. * 24 fraction bits
  95766. */
  95767. /* undefined */ 0x00000000,
  95768. /* lg(2/1) = */ 0x01000000,
  95769. /* lg(4/3) = */ 0x006a3fe6,
  95770. /* lg(8/7) = */ 0x00315130,
  95771. /* lg(16/15) = */ 0x0017d605,
  95772. /* lg(32/31) = */ 0x000bb9ca,
  95773. /* lg(64/63) = */ 0x0005d0fc,
  95774. /* lg(128/127) = */ 0x0002e58f,
  95775. /* lg(256/255) = */ 0x0001720e,
  95776. /* lg(512/511) = */ 0x0000b8d8,
  95777. /* lg(1024/1023) = */ 0x00005c61,
  95778. /* lg(2048/2047) = */ 0x00002e2d,
  95779. /* lg(4096/4095) = */ 0x00001716,
  95780. /* lg(8192/8191) = */ 0x00000b8b,
  95781. /* lg(16384/16383) = */ 0x000005c5,
  95782. /* lg(32768/32767) = */ 0x000002e3
  95783. },
  95784. {
  95785. /*
  95786. * 28 fraction bits
  95787. */
  95788. /* undefined */ 0x00000000,
  95789. /* lg(2/1) = */ 0x10000000,
  95790. /* lg(4/3) = */ 0x06a3fe5c,
  95791. /* lg(8/7) = */ 0x03151301,
  95792. /* lg(16/15) = */ 0x017d6049,
  95793. /* lg(32/31) = */ 0x00bb9ca6,
  95794. /* lg(64/63) = */ 0x005d0fba,
  95795. /* lg(128/127) = */ 0x002e58f7,
  95796. /* lg(256/255) = */ 0x001720da,
  95797. /* lg(512/511) = */ 0x000b8d87,
  95798. /* lg(1024/1023) = */ 0x0005c60b,
  95799. /* lg(2048/2047) = */ 0x0002e2d7,
  95800. /* lg(4096/4095) = */ 0x00017160,
  95801. /* lg(8192/8191) = */ 0x0000b8ad,
  95802. /* lg(16384/16383) = */ 0x00005c56,
  95803. /* lg(32768/32767) = */ 0x00002e2b
  95804. }
  95805. };
  95806. #if 0
  95807. static const FLAC__uint64 log2_lookup_wide[] = {
  95808. {
  95809. /*
  95810. * 32 fraction bits
  95811. */
  95812. /* undefined */ 0x00000000,
  95813. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  95814. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  95815. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  95816. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  95817. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  95818. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  95819. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  95820. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  95821. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  95822. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  95823. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  95824. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  95825. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  95826. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  95827. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  95828. },
  95829. {
  95830. /*
  95831. * 48 fraction bits
  95832. */
  95833. /* undefined */ 0x00000000,
  95834. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  95835. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  95836. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  95837. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  95838. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  95839. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  95840. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  95841. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  95842. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  95843. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  95844. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  95845. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  95846. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  95847. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  95848. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  95849. }
  95850. };
  95851. #endif
  95852. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  95853. {
  95854. const FLAC__uint32 ONE = (1u << fracbits);
  95855. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  95856. FLAC__ASSERT(fracbits < 32);
  95857. FLAC__ASSERT((fracbits & 0x3) == 0);
  95858. if(x < ONE)
  95859. return 0;
  95860. if(precision > LOG2_LOOKUP_PRECISION)
  95861. precision = LOG2_LOOKUP_PRECISION;
  95862. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  95863. {
  95864. FLAC__uint32 y = 0;
  95865. FLAC__uint32 z = x >> 1, k = 1;
  95866. while (x > ONE && k < precision) {
  95867. if (x - z >= ONE) {
  95868. x -= z;
  95869. z = x >> k;
  95870. y += table[k];
  95871. }
  95872. else {
  95873. z >>= 1;
  95874. k++;
  95875. }
  95876. }
  95877. return y;
  95878. }
  95879. }
  95880. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  95881. #endif
  95882. /*** End of inlined file: float.c ***/
  95883. /*** Start of inlined file: format.c ***/
  95884. /*** Start of inlined file: juce_FlacHeader.h ***/
  95885. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95886. // tasks..
  95887. #define VERSION "1.2.1"
  95888. #define FLAC__NO_DLL 1
  95889. #if JUCE_MSVC
  95890. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95891. #endif
  95892. #if JUCE_MAC
  95893. #define FLAC__SYS_DARWIN 1
  95894. #endif
  95895. /*** End of inlined file: juce_FlacHeader.h ***/
  95896. #if JUCE_USE_FLAC
  95897. #if HAVE_CONFIG_H
  95898. # include <config.h>
  95899. #endif
  95900. #include <stdio.h>
  95901. #include <stdlib.h> /* for qsort() */
  95902. #include <string.h> /* for memset() */
  95903. #ifndef FLaC__INLINE
  95904. #define FLaC__INLINE
  95905. #endif
  95906. #ifdef min
  95907. #undef min
  95908. #endif
  95909. #define min(a,b) ((a)<(b)?(a):(b))
  95910. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95911. #ifdef _MSC_VER
  95912. #define FLAC__U64L(x) x
  95913. #else
  95914. #define FLAC__U64L(x) x##LLU
  95915. #endif
  95916. /* VERSION should come from configure */
  95917. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  95918. ;
  95919. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  95920. /* yet one more hack because of MSVC6: */
  95921. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  95922. #else
  95923. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  95924. #endif
  95925. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  95926. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  95927. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  95928. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  95929. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  95930. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  95931. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  95932. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  95933. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  95934. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  95935. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  95936. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  95937. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  95938. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  95939. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  95940. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  95941. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  95942. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  95943. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  95944. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  95945. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  95946. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  95947. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  95948. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  95949. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  95950. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  95951. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  95952. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  95953. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  95954. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  95955. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  95956. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  95957. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  95958. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  95959. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  95960. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  95961. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  95962. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  95963. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  95964. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  95965. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  95966. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  95967. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  95968. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  95969. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  95970. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  95971. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  95972. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  95973. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  95974. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  95975. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  95976. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  95977. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  95978. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  95979. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  95980. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  95981. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  95982. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  95983. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  95984. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  95985. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  95986. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  95987. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  95988. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  95989. "PARTITIONED_RICE",
  95990. "PARTITIONED_RICE2"
  95991. };
  95992. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  95993. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  95994. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  95995. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  95996. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  95997. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  95998. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  95999. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96000. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96001. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96002. "CONSTANT",
  96003. "VERBATIM",
  96004. "FIXED",
  96005. "LPC"
  96006. };
  96007. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96008. "INDEPENDENT",
  96009. "LEFT_SIDE",
  96010. "RIGHT_SIDE",
  96011. "MID_SIDE"
  96012. };
  96013. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96014. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96015. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96016. };
  96017. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96018. "STREAMINFO",
  96019. "PADDING",
  96020. "APPLICATION",
  96021. "SEEKTABLE",
  96022. "VORBIS_COMMENT",
  96023. "CUESHEET",
  96024. "PICTURE"
  96025. };
  96026. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96027. "Other",
  96028. "32x32 pixels 'file icon' (PNG only)",
  96029. "Other file icon",
  96030. "Cover (front)",
  96031. "Cover (back)",
  96032. "Leaflet page",
  96033. "Media (e.g. label side of CD)",
  96034. "Lead artist/lead performer/soloist",
  96035. "Artist/performer",
  96036. "Conductor",
  96037. "Band/Orchestra",
  96038. "Composer",
  96039. "Lyricist/text writer",
  96040. "Recording Location",
  96041. "During recording",
  96042. "During performance",
  96043. "Movie/video screen capture",
  96044. "A bright coloured fish",
  96045. "Illustration",
  96046. "Band/artist logotype",
  96047. "Publisher/Studio logotype"
  96048. };
  96049. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96050. {
  96051. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96052. return false;
  96053. }
  96054. else
  96055. return true;
  96056. }
  96057. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96058. {
  96059. if(
  96060. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96061. (
  96062. sample_rate >= (1u << 16) &&
  96063. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96064. )
  96065. ) {
  96066. return false;
  96067. }
  96068. else
  96069. return true;
  96070. }
  96071. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96072. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96073. {
  96074. unsigned i;
  96075. FLAC__uint64 prev_sample_number = 0;
  96076. FLAC__bool got_prev = false;
  96077. FLAC__ASSERT(0 != seek_table);
  96078. for(i = 0; i < seek_table->num_points; i++) {
  96079. if(got_prev) {
  96080. if(
  96081. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96082. seek_table->points[i].sample_number <= prev_sample_number
  96083. )
  96084. return false;
  96085. }
  96086. prev_sample_number = seek_table->points[i].sample_number;
  96087. got_prev = true;
  96088. }
  96089. return true;
  96090. }
  96091. /* used as the sort predicate for qsort() */
  96092. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96093. {
  96094. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96095. if(l->sample_number == r->sample_number)
  96096. return 0;
  96097. else if(l->sample_number < r->sample_number)
  96098. return -1;
  96099. else
  96100. return 1;
  96101. }
  96102. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96103. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96104. {
  96105. unsigned i, j;
  96106. FLAC__bool first;
  96107. FLAC__ASSERT(0 != seek_table);
  96108. /* sort the seekpoints */
  96109. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  96110. /* uniquify the seekpoints */
  96111. first = true;
  96112. for(i = j = 0; i < seek_table->num_points; i++) {
  96113. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96114. if(!first) {
  96115. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96116. continue;
  96117. }
  96118. }
  96119. first = false;
  96120. seek_table->points[j++] = seek_table->points[i];
  96121. }
  96122. for(i = j; i < seek_table->num_points; i++) {
  96123. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96124. seek_table->points[i].stream_offset = 0;
  96125. seek_table->points[i].frame_samples = 0;
  96126. }
  96127. return j;
  96128. }
  96129. /*
  96130. * also disallows non-shortest-form encodings, c.f.
  96131. * http://www.unicode.org/versions/corrigendum1.html
  96132. * and a more clear explanation at the end of this section:
  96133. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96134. */
  96135. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96136. {
  96137. FLAC__ASSERT(0 != utf8);
  96138. if ((utf8[0] & 0x80) == 0) {
  96139. return 1;
  96140. }
  96141. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96142. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96143. return 0;
  96144. return 2;
  96145. }
  96146. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96147. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96148. return 0;
  96149. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96150. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96151. return 0;
  96152. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96153. return 0;
  96154. return 3;
  96155. }
  96156. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96157. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96158. return 0;
  96159. return 4;
  96160. }
  96161. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96162. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96163. return 0;
  96164. return 5;
  96165. }
  96166. 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) {
  96167. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96168. return 0;
  96169. return 6;
  96170. }
  96171. else {
  96172. return 0;
  96173. }
  96174. }
  96175. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96176. {
  96177. char c;
  96178. for(c = *name; c; c = *(++name))
  96179. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96180. return false;
  96181. return true;
  96182. }
  96183. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96184. {
  96185. if(length == (unsigned)(-1)) {
  96186. while(*value) {
  96187. unsigned n = utf8len_(value);
  96188. if(n == 0)
  96189. return false;
  96190. value += n;
  96191. }
  96192. }
  96193. else {
  96194. const FLAC__byte *end = value + length;
  96195. while(value < end) {
  96196. unsigned n = utf8len_(value);
  96197. if(n == 0)
  96198. return false;
  96199. value += n;
  96200. }
  96201. if(value != end)
  96202. return false;
  96203. }
  96204. return true;
  96205. }
  96206. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96207. {
  96208. const FLAC__byte *s, *end;
  96209. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96210. if(*s < 0x20 || *s > 0x7D)
  96211. return false;
  96212. }
  96213. if(s == end)
  96214. return false;
  96215. s++; /* skip '=' */
  96216. while(s < end) {
  96217. unsigned n = utf8len_(s);
  96218. if(n == 0)
  96219. return false;
  96220. s += n;
  96221. }
  96222. if(s != end)
  96223. return false;
  96224. return true;
  96225. }
  96226. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96227. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96228. {
  96229. unsigned i, j;
  96230. if(check_cd_da_subset) {
  96231. if(cue_sheet->lead_in < 2 * 44100) {
  96232. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96233. return false;
  96234. }
  96235. if(cue_sheet->lead_in % 588 != 0) {
  96236. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96237. return false;
  96238. }
  96239. }
  96240. if(cue_sheet->num_tracks == 0) {
  96241. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  96242. return false;
  96243. }
  96244. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  96245. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  96246. return false;
  96247. }
  96248. for(i = 0; i < cue_sheet->num_tracks; i++) {
  96249. if(cue_sheet->tracks[i].number == 0) {
  96250. if(violation) *violation = "cue sheet may not have a track number 0";
  96251. return false;
  96252. }
  96253. if(check_cd_da_subset) {
  96254. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  96255. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  96256. return false;
  96257. }
  96258. }
  96259. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  96260. if(violation) {
  96261. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  96262. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  96263. else
  96264. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  96265. }
  96266. return false;
  96267. }
  96268. if(i < cue_sheet->num_tracks - 1) {
  96269. if(cue_sheet->tracks[i].num_indices == 0) {
  96270. if(violation) *violation = "cue sheet track must have at least one index point";
  96271. return false;
  96272. }
  96273. if(cue_sheet->tracks[i].indices[0].number > 1) {
  96274. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  96275. return false;
  96276. }
  96277. }
  96278. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  96279. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  96280. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  96281. return false;
  96282. }
  96283. if(j > 0) {
  96284. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  96285. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  96286. return false;
  96287. }
  96288. }
  96289. }
  96290. }
  96291. return true;
  96292. }
  96293. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96294. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  96295. {
  96296. char *p;
  96297. FLAC__byte *b;
  96298. for(p = picture->mime_type; *p; p++) {
  96299. if(*p < 0x20 || *p > 0x7e) {
  96300. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  96301. return false;
  96302. }
  96303. }
  96304. for(b = picture->description; *b; ) {
  96305. unsigned n = utf8len_(b);
  96306. if(n == 0) {
  96307. if(violation) *violation = "description string must be valid UTF-8";
  96308. return false;
  96309. }
  96310. b += n;
  96311. }
  96312. return true;
  96313. }
  96314. /*
  96315. * These routines are private to libFLAC
  96316. */
  96317. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96318. {
  96319. return
  96320. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96321. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96322. blocksize,
  96323. predictor_order
  96324. );
  96325. }
  96326. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96327. {
  96328. unsigned max_rice_partition_order = 0;
  96329. while(!(blocksize & 1)) {
  96330. max_rice_partition_order++;
  96331. blocksize >>= 1;
  96332. }
  96333. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96334. }
  96335. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96336. {
  96337. unsigned max_rice_partition_order = limit;
  96338. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96339. max_rice_partition_order--;
  96340. FLAC__ASSERT(
  96341. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96342. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96343. );
  96344. return max_rice_partition_order;
  96345. }
  96346. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96347. {
  96348. FLAC__ASSERT(0 != object);
  96349. object->parameters = 0;
  96350. object->raw_bits = 0;
  96351. object->capacity_by_order = 0;
  96352. }
  96353. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96354. {
  96355. FLAC__ASSERT(0 != object);
  96356. if(0 != object->parameters)
  96357. free(object->parameters);
  96358. if(0 != object->raw_bits)
  96359. free(object->raw_bits);
  96360. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  96361. }
  96362. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  96363. {
  96364. FLAC__ASSERT(0 != object);
  96365. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  96366. if(object->capacity_by_order < max_partition_order) {
  96367. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  96368. return false;
  96369. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  96370. return false;
  96371. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  96372. object->capacity_by_order = max_partition_order;
  96373. }
  96374. return true;
  96375. }
  96376. #endif
  96377. /*** End of inlined file: format.c ***/
  96378. /*** Start of inlined file: lpc_flac.c ***/
  96379. /*** Start of inlined file: juce_FlacHeader.h ***/
  96380. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96381. // tasks..
  96382. #define VERSION "1.2.1"
  96383. #define FLAC__NO_DLL 1
  96384. #if JUCE_MSVC
  96385. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96386. #endif
  96387. #if JUCE_MAC
  96388. #define FLAC__SYS_DARWIN 1
  96389. #endif
  96390. /*** End of inlined file: juce_FlacHeader.h ***/
  96391. #if JUCE_USE_FLAC
  96392. #if HAVE_CONFIG_H
  96393. # include <config.h>
  96394. #endif
  96395. #include <math.h>
  96396. /*** Start of inlined file: lpc.h ***/
  96397. #ifndef FLAC__PRIVATE__LPC_H
  96398. #define FLAC__PRIVATE__LPC_H
  96399. #ifdef HAVE_CONFIG_H
  96400. #include <config.h>
  96401. #endif
  96402. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96403. /*
  96404. * FLAC__lpc_window_data()
  96405. * --------------------------------------------------------------------
  96406. * Applies the given window to the data.
  96407. * OPT: asm implementation
  96408. *
  96409. * IN in[0,data_len-1]
  96410. * IN window[0,data_len-1]
  96411. * OUT out[0,lag-1]
  96412. * IN data_len
  96413. */
  96414. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  96415. /*
  96416. * FLAC__lpc_compute_autocorrelation()
  96417. * --------------------------------------------------------------------
  96418. * Compute the autocorrelation for lags between 0 and lag-1.
  96419. * Assumes data[] outside of [0,data_len-1] == 0.
  96420. * Asserts that lag > 0.
  96421. *
  96422. * IN data[0,data_len-1]
  96423. * IN data_len
  96424. * IN 0 < lag <= data_len
  96425. * OUT autoc[0,lag-1]
  96426. */
  96427. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96428. #ifndef FLAC__NO_ASM
  96429. # ifdef FLAC__CPU_IA32
  96430. # ifdef FLAC__HAS_NASM
  96431. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96432. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96433. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96434. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96435. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96436. # endif
  96437. # endif
  96438. #endif
  96439. /*
  96440. * FLAC__lpc_compute_lp_coefficients()
  96441. * --------------------------------------------------------------------
  96442. * Computes LP coefficients for orders 1..max_order.
  96443. * Do not call if autoc[0] == 0.0. This means the signal is zero
  96444. * and there is no point in calculating a predictor.
  96445. *
  96446. * IN autoc[0,max_order] autocorrelation values
  96447. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  96448. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  96449. * *** IMPORTANT:
  96450. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  96451. * OUT error[0,max_order-1] error for each order (more
  96452. * specifically, the variance of
  96453. * the error signal times # of
  96454. * samples in the signal)
  96455. *
  96456. * Example: if max_order is 9, the LP coefficients for order 9 will be
  96457. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  96458. * in lp_coeff[7][0,7], etc.
  96459. */
  96460. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  96461. /*
  96462. * FLAC__lpc_quantize_coefficients()
  96463. * --------------------------------------------------------------------
  96464. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  96465. * must be less than 32 (sizeof(FLAC__int32)*8).
  96466. *
  96467. * IN lp_coeff[0,order-1] LP coefficients
  96468. * IN order LP order
  96469. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  96470. * desired precision (in bits, including sign
  96471. * bit) of largest coefficient
  96472. * OUT qlp_coeff[0,order-1] quantized coefficients
  96473. * OUT shift # of bits to shift right to get approximated
  96474. * LP coefficients. NOTE: could be negative.
  96475. * RETURN 0 => quantization OK
  96476. * 1 => coefficients require too much shifting for *shift to
  96477. * fit in the LPC subframe header. 'shift' is unset.
  96478. * 2 => coefficients are all zero, which is bad. 'shift' is
  96479. * unset.
  96480. */
  96481. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  96482. /*
  96483. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  96484. * --------------------------------------------------------------------
  96485. * Compute the residual signal obtained from sutracting the predicted
  96486. * signal from the original.
  96487. *
  96488. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96489. * IN data_len length of original signal
  96490. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96491. * IN order > 0 LP order
  96492. * IN lp_quantization quantization of LP coefficients in bits
  96493. * OUT residual[0,data_len-1] residual signal
  96494. */
  96495. 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[]);
  96496. 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[]);
  96497. #ifndef FLAC__NO_ASM
  96498. # ifdef FLAC__CPU_IA32
  96499. # ifdef FLAC__HAS_NASM
  96500. 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[]);
  96501. 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[]);
  96502. # endif
  96503. # endif
  96504. #endif
  96505. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96506. /*
  96507. * FLAC__lpc_restore_signal()
  96508. * --------------------------------------------------------------------
  96509. * Restore the original signal by summing the residual and the
  96510. * predictor.
  96511. *
  96512. * IN residual[0,data_len-1] residual signal
  96513. * IN data_len length of original signal
  96514. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96515. * IN order > 0 LP order
  96516. * IN lp_quantization quantization of LP coefficients in bits
  96517. * *** IMPORTANT: the caller must pass in the historical samples:
  96518. * IN data[-order,-1] previously-reconstructed historical samples
  96519. * OUT data[0,data_len-1] original signal
  96520. */
  96521. 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[]);
  96522. 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[]);
  96523. #ifndef FLAC__NO_ASM
  96524. # ifdef FLAC__CPU_IA32
  96525. # ifdef FLAC__HAS_NASM
  96526. 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[]);
  96527. 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[]);
  96528. # endif /* FLAC__HAS_NASM */
  96529. # elif defined FLAC__CPU_PPC
  96530. 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[]);
  96531. 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[]);
  96532. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  96533. #endif /* FLAC__NO_ASM */
  96534. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96535. /*
  96536. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  96537. * --------------------------------------------------------------------
  96538. * Compute the expected number of bits per residual signal sample
  96539. * based on the LP error (which is related to the residual variance).
  96540. *
  96541. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  96542. * IN total_samples > 0 # of samples in residual signal
  96543. * RETURN expected bits per sample
  96544. */
  96545. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  96546. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  96547. /*
  96548. * FLAC__lpc_compute_best_order()
  96549. * --------------------------------------------------------------------
  96550. * Compute the best order from the array of signal errors returned
  96551. * during coefficient computation.
  96552. *
  96553. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  96554. * IN max_order > 0 max LP order
  96555. * IN total_samples > 0 # of samples in residual signal
  96556. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  96557. * (includes warmup sample size and quantized LP coefficient)
  96558. * RETURN [1,max_order] best order
  96559. */
  96560. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  96561. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96562. #endif
  96563. /*** End of inlined file: lpc.h ***/
  96564. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  96565. #include <stdio.h>
  96566. #endif
  96567. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96568. #ifndef M_LN2
  96569. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  96570. #define M_LN2 0.69314718055994530942
  96571. #endif
  96572. /* OPT: #undef'ing this may improve the speed on some architectures */
  96573. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  96574. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  96575. {
  96576. unsigned i;
  96577. for(i = 0; i < data_len; i++)
  96578. out[i] = in[i] * window[i];
  96579. }
  96580. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  96581. {
  96582. /* a readable, but slower, version */
  96583. #if 0
  96584. FLAC__real d;
  96585. unsigned i;
  96586. FLAC__ASSERT(lag > 0);
  96587. FLAC__ASSERT(lag <= data_len);
  96588. /*
  96589. * Technically we should subtract the mean first like so:
  96590. * for(i = 0; i < data_len; i++)
  96591. * data[i] -= mean;
  96592. * but it appears not to make enough of a difference to matter, and
  96593. * most signals are already closely centered around zero
  96594. */
  96595. while(lag--) {
  96596. for(i = lag, d = 0.0; i < data_len; i++)
  96597. d += data[i] * data[i - lag];
  96598. autoc[lag] = d;
  96599. }
  96600. #endif
  96601. /*
  96602. * this version tends to run faster because of better data locality
  96603. * ('data_len' is usually much larger than 'lag')
  96604. */
  96605. FLAC__real d;
  96606. unsigned sample, coeff;
  96607. const unsigned limit = data_len - lag;
  96608. FLAC__ASSERT(lag > 0);
  96609. FLAC__ASSERT(lag <= data_len);
  96610. for(coeff = 0; coeff < lag; coeff++)
  96611. autoc[coeff] = 0.0;
  96612. for(sample = 0; sample <= limit; sample++) {
  96613. d = data[sample];
  96614. for(coeff = 0; coeff < lag; coeff++)
  96615. autoc[coeff] += d * data[sample+coeff];
  96616. }
  96617. for(; sample < data_len; sample++) {
  96618. d = data[sample];
  96619. for(coeff = 0; coeff < data_len - sample; coeff++)
  96620. autoc[coeff] += d * data[sample+coeff];
  96621. }
  96622. }
  96623. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  96624. {
  96625. unsigned i, j;
  96626. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  96627. FLAC__ASSERT(0 != max_order);
  96628. FLAC__ASSERT(0 < *max_order);
  96629. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  96630. FLAC__ASSERT(autoc[0] != 0.0);
  96631. err = autoc[0];
  96632. for(i = 0; i < *max_order; i++) {
  96633. /* Sum up this iteration's reflection coefficient. */
  96634. r = -autoc[i+1];
  96635. for(j = 0; j < i; j++)
  96636. r -= lpc[j] * autoc[i-j];
  96637. ref[i] = (r/=err);
  96638. /* Update LPC coefficients and total error. */
  96639. lpc[i]=r;
  96640. for(j = 0; j < (i>>1); j++) {
  96641. FLAC__double tmp = lpc[j];
  96642. lpc[j] += r * lpc[i-1-j];
  96643. lpc[i-1-j] += r * tmp;
  96644. }
  96645. if(i & 1)
  96646. lpc[j] += lpc[j] * r;
  96647. err *= (1.0 - r * r);
  96648. /* save this order */
  96649. for(j = 0; j <= i; j++)
  96650. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  96651. error[i] = err;
  96652. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  96653. if(err == 0.0) {
  96654. *max_order = i+1;
  96655. return;
  96656. }
  96657. }
  96658. }
  96659. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  96660. {
  96661. unsigned i;
  96662. FLAC__double cmax;
  96663. FLAC__int32 qmax, qmin;
  96664. FLAC__ASSERT(precision > 0);
  96665. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  96666. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  96667. precision--;
  96668. qmax = 1 << precision;
  96669. qmin = -qmax;
  96670. qmax--;
  96671. /* calc cmax = max( |lp_coeff[i]| ) */
  96672. cmax = 0.0;
  96673. for(i = 0; i < order; i++) {
  96674. const FLAC__double d = fabs(lp_coeff[i]);
  96675. if(d > cmax)
  96676. cmax = d;
  96677. }
  96678. if(cmax <= 0.0) {
  96679. /* => coefficients are all 0, which means our constant-detect didn't work */
  96680. return 2;
  96681. }
  96682. else {
  96683. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  96684. const int min_shiftlimit = -max_shiftlimit - 1;
  96685. int log2cmax;
  96686. (void)frexp(cmax, &log2cmax);
  96687. log2cmax--;
  96688. *shift = (int)precision - log2cmax - 1;
  96689. if(*shift > max_shiftlimit)
  96690. *shift = max_shiftlimit;
  96691. else if(*shift < min_shiftlimit)
  96692. return 1;
  96693. }
  96694. if(*shift >= 0) {
  96695. FLAC__double error = 0.0;
  96696. FLAC__int32 q;
  96697. for(i = 0; i < order; i++) {
  96698. error += lp_coeff[i] * (1 << *shift);
  96699. #if 1 /* unfortunately lround() is C99 */
  96700. if(error >= 0.0)
  96701. q = (FLAC__int32)(error + 0.5);
  96702. else
  96703. q = (FLAC__int32)(error - 0.5);
  96704. #else
  96705. q = lround(error);
  96706. #endif
  96707. #ifdef FLAC__OVERFLOW_DETECT
  96708. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96709. 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]);
  96710. else if(q < qmin)
  96711. 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]);
  96712. #endif
  96713. if(q > qmax)
  96714. q = qmax;
  96715. else if(q < qmin)
  96716. q = qmin;
  96717. error -= q;
  96718. qlp_coeff[i] = q;
  96719. }
  96720. }
  96721. /* negative shift is very rare but due to design flaw, negative shift is
  96722. * a NOP in the decoder, so it must be handled specially by scaling down
  96723. * coeffs
  96724. */
  96725. else {
  96726. const int nshift = -(*shift);
  96727. FLAC__double error = 0.0;
  96728. FLAC__int32 q;
  96729. #ifdef DEBUG
  96730. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  96731. #endif
  96732. for(i = 0; i < order; i++) {
  96733. error += lp_coeff[i] / (1 << nshift);
  96734. #if 1 /* unfortunately lround() is C99 */
  96735. if(error >= 0.0)
  96736. q = (FLAC__int32)(error + 0.5);
  96737. else
  96738. q = (FLAC__int32)(error - 0.5);
  96739. #else
  96740. q = lround(error);
  96741. #endif
  96742. #ifdef FLAC__OVERFLOW_DETECT
  96743. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96744. 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]);
  96745. else if(q < qmin)
  96746. 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]);
  96747. #endif
  96748. if(q > qmax)
  96749. q = qmax;
  96750. else if(q < qmin)
  96751. q = qmin;
  96752. error -= q;
  96753. qlp_coeff[i] = q;
  96754. }
  96755. *shift = 0;
  96756. }
  96757. return 0;
  96758. }
  96759. 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[])
  96760. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  96761. {
  96762. FLAC__int64 sumo;
  96763. unsigned i, j;
  96764. FLAC__int32 sum;
  96765. const FLAC__int32 *history;
  96766. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  96767. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  96768. for(i=0;i<order;i++)
  96769. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  96770. fprintf(stderr,"\n");
  96771. #endif
  96772. FLAC__ASSERT(order > 0);
  96773. for(i = 0; i < data_len; i++) {
  96774. sumo = 0;
  96775. sum = 0;
  96776. history = data;
  96777. for(j = 0; j < order; j++) {
  96778. sum += qlp_coeff[j] * (*(--history));
  96779. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  96780. #if defined _MSC_VER
  96781. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  96782. 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);
  96783. #else
  96784. if(sumo > 2147483647ll || sumo < -2147483648ll)
  96785. 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);
  96786. #endif
  96787. }
  96788. *(residual++) = *(data++) - (sum >> lp_quantization);
  96789. }
  96790. /* Here's a slower but clearer version:
  96791. for(i = 0; i < data_len; i++) {
  96792. sum = 0;
  96793. for(j = 0; j < order; j++)
  96794. sum += qlp_coeff[j] * data[i-j-1];
  96795. residual[i] = data[i] - (sum >> lp_quantization);
  96796. }
  96797. */
  96798. }
  96799. #else /* fully unrolled version for normal use */
  96800. {
  96801. int i;
  96802. FLAC__int32 sum;
  96803. FLAC__ASSERT(order > 0);
  96804. FLAC__ASSERT(order <= 32);
  96805. /*
  96806. * We do unique versions up to 12th order since that's the subset limit.
  96807. * Also they are roughly ordered to match frequency of occurrence to
  96808. * minimize branching.
  96809. */
  96810. if(order <= 12) {
  96811. if(order > 8) {
  96812. if(order > 10) {
  96813. if(order == 12) {
  96814. for(i = 0; i < (int)data_len; i++) {
  96815. sum = 0;
  96816. sum += qlp_coeff[11] * data[i-12];
  96817. sum += qlp_coeff[10] * data[i-11];
  96818. sum += qlp_coeff[9] * data[i-10];
  96819. sum += qlp_coeff[8] * data[i-9];
  96820. sum += qlp_coeff[7] * data[i-8];
  96821. sum += qlp_coeff[6] * data[i-7];
  96822. sum += qlp_coeff[5] * data[i-6];
  96823. sum += qlp_coeff[4] * data[i-5];
  96824. sum += qlp_coeff[3] * data[i-4];
  96825. sum += qlp_coeff[2] * data[i-3];
  96826. sum += qlp_coeff[1] * data[i-2];
  96827. sum += qlp_coeff[0] * data[i-1];
  96828. residual[i] = data[i] - (sum >> lp_quantization);
  96829. }
  96830. }
  96831. else { /* order == 11 */
  96832. for(i = 0; i < (int)data_len; i++) {
  96833. sum = 0;
  96834. sum += qlp_coeff[10] * data[i-11];
  96835. sum += qlp_coeff[9] * data[i-10];
  96836. sum += qlp_coeff[8] * data[i-9];
  96837. sum += qlp_coeff[7] * data[i-8];
  96838. sum += qlp_coeff[6] * data[i-7];
  96839. sum += qlp_coeff[5] * data[i-6];
  96840. sum += qlp_coeff[4] * data[i-5];
  96841. sum += qlp_coeff[3] * data[i-4];
  96842. sum += qlp_coeff[2] * data[i-3];
  96843. sum += qlp_coeff[1] * data[i-2];
  96844. sum += qlp_coeff[0] * data[i-1];
  96845. residual[i] = data[i] - (sum >> lp_quantization);
  96846. }
  96847. }
  96848. }
  96849. else {
  96850. if(order == 10) {
  96851. for(i = 0; i < (int)data_len; i++) {
  96852. sum = 0;
  96853. sum += qlp_coeff[9] * data[i-10];
  96854. sum += qlp_coeff[8] * data[i-9];
  96855. sum += qlp_coeff[7] * data[i-8];
  96856. sum += qlp_coeff[6] * data[i-7];
  96857. sum += qlp_coeff[5] * data[i-6];
  96858. sum += qlp_coeff[4] * data[i-5];
  96859. sum += qlp_coeff[3] * data[i-4];
  96860. sum += qlp_coeff[2] * data[i-3];
  96861. sum += qlp_coeff[1] * data[i-2];
  96862. sum += qlp_coeff[0] * data[i-1];
  96863. residual[i] = data[i] - (sum >> lp_quantization);
  96864. }
  96865. }
  96866. else { /* order == 9 */
  96867. for(i = 0; i < (int)data_len; i++) {
  96868. sum = 0;
  96869. sum += qlp_coeff[8] * data[i-9];
  96870. sum += qlp_coeff[7] * data[i-8];
  96871. sum += qlp_coeff[6] * data[i-7];
  96872. sum += qlp_coeff[5] * data[i-6];
  96873. sum += qlp_coeff[4] * data[i-5];
  96874. sum += qlp_coeff[3] * data[i-4];
  96875. sum += qlp_coeff[2] * data[i-3];
  96876. sum += qlp_coeff[1] * data[i-2];
  96877. sum += qlp_coeff[0] * data[i-1];
  96878. residual[i] = data[i] - (sum >> lp_quantization);
  96879. }
  96880. }
  96881. }
  96882. }
  96883. else if(order > 4) {
  96884. if(order > 6) {
  96885. if(order == 8) {
  96886. for(i = 0; i < (int)data_len; i++) {
  96887. sum = 0;
  96888. sum += qlp_coeff[7] * data[i-8];
  96889. sum += qlp_coeff[6] * data[i-7];
  96890. sum += qlp_coeff[5] * data[i-6];
  96891. sum += qlp_coeff[4] * data[i-5];
  96892. sum += qlp_coeff[3] * data[i-4];
  96893. sum += qlp_coeff[2] * data[i-3];
  96894. sum += qlp_coeff[1] * data[i-2];
  96895. sum += qlp_coeff[0] * data[i-1];
  96896. residual[i] = data[i] - (sum >> lp_quantization);
  96897. }
  96898. }
  96899. else { /* order == 7 */
  96900. for(i = 0; i < (int)data_len; i++) {
  96901. sum = 0;
  96902. sum += qlp_coeff[6] * data[i-7];
  96903. sum += qlp_coeff[5] * data[i-6];
  96904. sum += qlp_coeff[4] * data[i-5];
  96905. sum += qlp_coeff[3] * data[i-4];
  96906. sum += qlp_coeff[2] * data[i-3];
  96907. sum += qlp_coeff[1] * data[i-2];
  96908. sum += qlp_coeff[0] * data[i-1];
  96909. residual[i] = data[i] - (sum >> lp_quantization);
  96910. }
  96911. }
  96912. }
  96913. else {
  96914. if(order == 6) {
  96915. for(i = 0; i < (int)data_len; i++) {
  96916. sum = 0;
  96917. sum += qlp_coeff[5] * data[i-6];
  96918. sum += qlp_coeff[4] * data[i-5];
  96919. sum += qlp_coeff[3] * data[i-4];
  96920. sum += qlp_coeff[2] * data[i-3];
  96921. sum += qlp_coeff[1] * data[i-2];
  96922. sum += qlp_coeff[0] * data[i-1];
  96923. residual[i] = data[i] - (sum >> lp_quantization);
  96924. }
  96925. }
  96926. else { /* order == 5 */
  96927. for(i = 0; i < (int)data_len; i++) {
  96928. sum = 0;
  96929. sum += qlp_coeff[4] * data[i-5];
  96930. sum += qlp_coeff[3] * data[i-4];
  96931. sum += qlp_coeff[2] * data[i-3];
  96932. sum += qlp_coeff[1] * data[i-2];
  96933. sum += qlp_coeff[0] * data[i-1];
  96934. residual[i] = data[i] - (sum >> lp_quantization);
  96935. }
  96936. }
  96937. }
  96938. }
  96939. else {
  96940. if(order > 2) {
  96941. if(order == 4) {
  96942. for(i = 0; i < (int)data_len; i++) {
  96943. sum = 0;
  96944. sum += qlp_coeff[3] * data[i-4];
  96945. sum += qlp_coeff[2] * data[i-3];
  96946. sum += qlp_coeff[1] * data[i-2];
  96947. sum += qlp_coeff[0] * data[i-1];
  96948. residual[i] = data[i] - (sum >> lp_quantization);
  96949. }
  96950. }
  96951. else { /* order == 3 */
  96952. for(i = 0; i < (int)data_len; i++) {
  96953. sum = 0;
  96954. sum += qlp_coeff[2] * data[i-3];
  96955. sum += qlp_coeff[1] * data[i-2];
  96956. sum += qlp_coeff[0] * data[i-1];
  96957. residual[i] = data[i] - (sum >> lp_quantization);
  96958. }
  96959. }
  96960. }
  96961. else {
  96962. if(order == 2) {
  96963. for(i = 0; i < (int)data_len; i++) {
  96964. sum = 0;
  96965. sum += qlp_coeff[1] * data[i-2];
  96966. sum += qlp_coeff[0] * data[i-1];
  96967. residual[i] = data[i] - (sum >> lp_quantization);
  96968. }
  96969. }
  96970. else { /* order == 1 */
  96971. for(i = 0; i < (int)data_len; i++)
  96972. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  96973. }
  96974. }
  96975. }
  96976. }
  96977. else { /* order > 12 */
  96978. for(i = 0; i < (int)data_len; i++) {
  96979. sum = 0;
  96980. switch(order) {
  96981. case 32: sum += qlp_coeff[31] * data[i-32];
  96982. case 31: sum += qlp_coeff[30] * data[i-31];
  96983. case 30: sum += qlp_coeff[29] * data[i-30];
  96984. case 29: sum += qlp_coeff[28] * data[i-29];
  96985. case 28: sum += qlp_coeff[27] * data[i-28];
  96986. case 27: sum += qlp_coeff[26] * data[i-27];
  96987. case 26: sum += qlp_coeff[25] * data[i-26];
  96988. case 25: sum += qlp_coeff[24] * data[i-25];
  96989. case 24: sum += qlp_coeff[23] * data[i-24];
  96990. case 23: sum += qlp_coeff[22] * data[i-23];
  96991. case 22: sum += qlp_coeff[21] * data[i-22];
  96992. case 21: sum += qlp_coeff[20] * data[i-21];
  96993. case 20: sum += qlp_coeff[19] * data[i-20];
  96994. case 19: sum += qlp_coeff[18] * data[i-19];
  96995. case 18: sum += qlp_coeff[17] * data[i-18];
  96996. case 17: sum += qlp_coeff[16] * data[i-17];
  96997. case 16: sum += qlp_coeff[15] * data[i-16];
  96998. case 15: sum += qlp_coeff[14] * data[i-15];
  96999. case 14: sum += qlp_coeff[13] * data[i-14];
  97000. case 13: sum += qlp_coeff[12] * data[i-13];
  97001. sum += qlp_coeff[11] * data[i-12];
  97002. sum += qlp_coeff[10] * data[i-11];
  97003. sum += qlp_coeff[ 9] * data[i-10];
  97004. sum += qlp_coeff[ 8] * data[i- 9];
  97005. sum += qlp_coeff[ 7] * data[i- 8];
  97006. sum += qlp_coeff[ 6] * data[i- 7];
  97007. sum += qlp_coeff[ 5] * data[i- 6];
  97008. sum += qlp_coeff[ 4] * data[i- 5];
  97009. sum += qlp_coeff[ 3] * data[i- 4];
  97010. sum += qlp_coeff[ 2] * data[i- 3];
  97011. sum += qlp_coeff[ 1] * data[i- 2];
  97012. sum += qlp_coeff[ 0] * data[i- 1];
  97013. }
  97014. residual[i] = data[i] - (sum >> lp_quantization);
  97015. }
  97016. }
  97017. }
  97018. #endif
  97019. 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[])
  97020. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97021. {
  97022. unsigned i, j;
  97023. FLAC__int64 sum;
  97024. const FLAC__int32 *history;
  97025. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97026. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97027. for(i=0;i<order;i++)
  97028. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97029. fprintf(stderr,"\n");
  97030. #endif
  97031. FLAC__ASSERT(order > 0);
  97032. for(i = 0; i < data_len; i++) {
  97033. sum = 0;
  97034. history = data;
  97035. for(j = 0; j < order; j++)
  97036. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97037. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97038. #if defined _MSC_VER
  97039. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97040. #else
  97041. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97042. #endif
  97043. break;
  97044. }
  97045. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97046. #if defined _MSC_VER
  97047. 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));
  97048. #else
  97049. 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)));
  97050. #endif
  97051. break;
  97052. }
  97053. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97054. }
  97055. }
  97056. #else /* fully unrolled version for normal use */
  97057. {
  97058. int i;
  97059. FLAC__int64 sum;
  97060. FLAC__ASSERT(order > 0);
  97061. FLAC__ASSERT(order <= 32);
  97062. /*
  97063. * We do unique versions up to 12th order since that's the subset limit.
  97064. * Also they are roughly ordered to match frequency of occurrence to
  97065. * minimize branching.
  97066. */
  97067. if(order <= 12) {
  97068. if(order > 8) {
  97069. if(order > 10) {
  97070. if(order == 12) {
  97071. for(i = 0; i < (int)data_len; i++) {
  97072. sum = 0;
  97073. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97074. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97075. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97076. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97077. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97078. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97079. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97080. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97081. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97082. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97083. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97084. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97085. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97086. }
  97087. }
  97088. else { /* order == 11 */
  97089. for(i = 0; i < (int)data_len; i++) {
  97090. sum = 0;
  97091. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97092. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97093. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97094. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97095. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97096. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97097. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97098. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97099. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97100. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97101. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97102. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97103. }
  97104. }
  97105. }
  97106. else {
  97107. if(order == 10) {
  97108. for(i = 0; i < (int)data_len; i++) {
  97109. sum = 0;
  97110. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97111. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97112. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97113. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97114. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97115. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97116. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97117. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97118. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97119. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97120. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97121. }
  97122. }
  97123. else { /* order == 9 */
  97124. for(i = 0; i < (int)data_len; i++) {
  97125. sum = 0;
  97126. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97127. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97128. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97129. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97130. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97131. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97132. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97133. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97134. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97135. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97136. }
  97137. }
  97138. }
  97139. }
  97140. else if(order > 4) {
  97141. if(order > 6) {
  97142. if(order == 8) {
  97143. for(i = 0; i < (int)data_len; i++) {
  97144. sum = 0;
  97145. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97146. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97147. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97148. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97149. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97150. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97151. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97152. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97153. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97154. }
  97155. }
  97156. else { /* order == 7 */
  97157. for(i = 0; i < (int)data_len; i++) {
  97158. sum = 0;
  97159. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97160. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97161. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97162. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97163. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97164. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97165. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97166. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97167. }
  97168. }
  97169. }
  97170. else {
  97171. if(order == 6) {
  97172. for(i = 0; i < (int)data_len; i++) {
  97173. sum = 0;
  97174. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97175. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97176. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97177. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97178. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97179. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97180. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97181. }
  97182. }
  97183. else { /* order == 5 */
  97184. for(i = 0; i < (int)data_len; i++) {
  97185. sum = 0;
  97186. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97187. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97188. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97189. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97190. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97191. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97192. }
  97193. }
  97194. }
  97195. }
  97196. else {
  97197. if(order > 2) {
  97198. if(order == 4) {
  97199. for(i = 0; i < (int)data_len; i++) {
  97200. sum = 0;
  97201. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97202. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97203. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97204. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97205. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97206. }
  97207. }
  97208. else { /* order == 3 */
  97209. for(i = 0; i < (int)data_len; i++) {
  97210. sum = 0;
  97211. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97212. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97213. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97214. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97215. }
  97216. }
  97217. }
  97218. else {
  97219. if(order == 2) {
  97220. for(i = 0; i < (int)data_len; i++) {
  97221. sum = 0;
  97222. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97223. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97224. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97225. }
  97226. }
  97227. else { /* order == 1 */
  97228. for(i = 0; i < (int)data_len; i++)
  97229. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97230. }
  97231. }
  97232. }
  97233. }
  97234. else { /* order > 12 */
  97235. for(i = 0; i < (int)data_len; i++) {
  97236. sum = 0;
  97237. switch(order) {
  97238. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97239. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97240. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97241. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97242. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97243. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97244. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97245. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97246. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97247. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97248. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97249. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97250. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97251. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97252. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97253. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97254. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97255. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97256. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97257. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97258. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97259. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97260. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97261. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97262. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97263. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97264. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97265. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97266. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97267. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97268. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97269. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97270. }
  97271. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97272. }
  97273. }
  97274. }
  97275. #endif
  97276. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97277. 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[])
  97278. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97279. {
  97280. FLAC__int64 sumo;
  97281. unsigned i, j;
  97282. FLAC__int32 sum;
  97283. const FLAC__int32 *r = residual, *history;
  97284. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97285. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97286. for(i=0;i<order;i++)
  97287. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97288. fprintf(stderr,"\n");
  97289. #endif
  97290. FLAC__ASSERT(order > 0);
  97291. for(i = 0; i < data_len; i++) {
  97292. sumo = 0;
  97293. sum = 0;
  97294. history = data;
  97295. for(j = 0; j < order; j++) {
  97296. sum += qlp_coeff[j] * (*(--history));
  97297. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97298. #if defined _MSC_VER
  97299. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97300. 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);
  97301. #else
  97302. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97303. 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);
  97304. #endif
  97305. }
  97306. *(data++) = *(r++) + (sum >> lp_quantization);
  97307. }
  97308. /* Here's a slower but clearer version:
  97309. for(i = 0; i < data_len; i++) {
  97310. sum = 0;
  97311. for(j = 0; j < order; j++)
  97312. sum += qlp_coeff[j] * data[i-j-1];
  97313. data[i] = residual[i] + (sum >> lp_quantization);
  97314. }
  97315. */
  97316. }
  97317. #else /* fully unrolled version for normal use */
  97318. {
  97319. int i;
  97320. FLAC__int32 sum;
  97321. FLAC__ASSERT(order > 0);
  97322. FLAC__ASSERT(order <= 32);
  97323. /*
  97324. * We do unique versions up to 12th order since that's the subset limit.
  97325. * Also they are roughly ordered to match frequency of occurrence to
  97326. * minimize branching.
  97327. */
  97328. if(order <= 12) {
  97329. if(order > 8) {
  97330. if(order > 10) {
  97331. if(order == 12) {
  97332. for(i = 0; i < (int)data_len; i++) {
  97333. sum = 0;
  97334. sum += qlp_coeff[11] * data[i-12];
  97335. sum += qlp_coeff[10] * data[i-11];
  97336. sum += qlp_coeff[9] * data[i-10];
  97337. sum += qlp_coeff[8] * data[i-9];
  97338. sum += qlp_coeff[7] * data[i-8];
  97339. sum += qlp_coeff[6] * data[i-7];
  97340. sum += qlp_coeff[5] * data[i-6];
  97341. sum += qlp_coeff[4] * data[i-5];
  97342. sum += qlp_coeff[3] * data[i-4];
  97343. sum += qlp_coeff[2] * data[i-3];
  97344. sum += qlp_coeff[1] * data[i-2];
  97345. sum += qlp_coeff[0] * data[i-1];
  97346. data[i] = residual[i] + (sum >> lp_quantization);
  97347. }
  97348. }
  97349. else { /* order == 11 */
  97350. for(i = 0; i < (int)data_len; i++) {
  97351. sum = 0;
  97352. sum += qlp_coeff[10] * data[i-11];
  97353. sum += qlp_coeff[9] * data[i-10];
  97354. sum += qlp_coeff[8] * data[i-9];
  97355. sum += qlp_coeff[7] * data[i-8];
  97356. sum += qlp_coeff[6] * data[i-7];
  97357. sum += qlp_coeff[5] * data[i-6];
  97358. sum += qlp_coeff[4] * data[i-5];
  97359. sum += qlp_coeff[3] * data[i-4];
  97360. sum += qlp_coeff[2] * data[i-3];
  97361. sum += qlp_coeff[1] * data[i-2];
  97362. sum += qlp_coeff[0] * data[i-1];
  97363. data[i] = residual[i] + (sum >> lp_quantization);
  97364. }
  97365. }
  97366. }
  97367. else {
  97368. if(order == 10) {
  97369. for(i = 0; i < (int)data_len; i++) {
  97370. sum = 0;
  97371. sum += qlp_coeff[9] * data[i-10];
  97372. sum += qlp_coeff[8] * data[i-9];
  97373. sum += qlp_coeff[7] * data[i-8];
  97374. sum += qlp_coeff[6] * data[i-7];
  97375. sum += qlp_coeff[5] * data[i-6];
  97376. sum += qlp_coeff[4] * data[i-5];
  97377. sum += qlp_coeff[3] * data[i-4];
  97378. sum += qlp_coeff[2] * data[i-3];
  97379. sum += qlp_coeff[1] * data[i-2];
  97380. sum += qlp_coeff[0] * data[i-1];
  97381. data[i] = residual[i] + (sum >> lp_quantization);
  97382. }
  97383. }
  97384. else { /* order == 9 */
  97385. for(i = 0; i < (int)data_len; i++) {
  97386. sum = 0;
  97387. sum += qlp_coeff[8] * data[i-9];
  97388. sum += qlp_coeff[7] * data[i-8];
  97389. sum += qlp_coeff[6] * data[i-7];
  97390. sum += qlp_coeff[5] * data[i-6];
  97391. sum += qlp_coeff[4] * data[i-5];
  97392. sum += qlp_coeff[3] * data[i-4];
  97393. sum += qlp_coeff[2] * data[i-3];
  97394. sum += qlp_coeff[1] * data[i-2];
  97395. sum += qlp_coeff[0] * data[i-1];
  97396. data[i] = residual[i] + (sum >> lp_quantization);
  97397. }
  97398. }
  97399. }
  97400. }
  97401. else if(order > 4) {
  97402. if(order > 6) {
  97403. if(order == 8) {
  97404. for(i = 0; i < (int)data_len; i++) {
  97405. sum = 0;
  97406. sum += qlp_coeff[7] * data[i-8];
  97407. sum += qlp_coeff[6] * data[i-7];
  97408. sum += qlp_coeff[5] * data[i-6];
  97409. sum += qlp_coeff[4] * data[i-5];
  97410. sum += qlp_coeff[3] * data[i-4];
  97411. sum += qlp_coeff[2] * data[i-3];
  97412. sum += qlp_coeff[1] * data[i-2];
  97413. sum += qlp_coeff[0] * data[i-1];
  97414. data[i] = residual[i] + (sum >> lp_quantization);
  97415. }
  97416. }
  97417. else { /* order == 7 */
  97418. for(i = 0; i < (int)data_len; i++) {
  97419. sum = 0;
  97420. sum += qlp_coeff[6] * data[i-7];
  97421. sum += qlp_coeff[5] * data[i-6];
  97422. sum += qlp_coeff[4] * data[i-5];
  97423. sum += qlp_coeff[3] * data[i-4];
  97424. sum += qlp_coeff[2] * data[i-3];
  97425. sum += qlp_coeff[1] * data[i-2];
  97426. sum += qlp_coeff[0] * data[i-1];
  97427. data[i] = residual[i] + (sum >> lp_quantization);
  97428. }
  97429. }
  97430. }
  97431. else {
  97432. if(order == 6) {
  97433. for(i = 0; i < (int)data_len; i++) {
  97434. sum = 0;
  97435. sum += qlp_coeff[5] * data[i-6];
  97436. sum += qlp_coeff[4] * data[i-5];
  97437. sum += qlp_coeff[3] * data[i-4];
  97438. sum += qlp_coeff[2] * data[i-3];
  97439. sum += qlp_coeff[1] * data[i-2];
  97440. sum += qlp_coeff[0] * data[i-1];
  97441. data[i] = residual[i] + (sum >> lp_quantization);
  97442. }
  97443. }
  97444. else { /* order == 5 */
  97445. for(i = 0; i < (int)data_len; i++) {
  97446. sum = 0;
  97447. sum += qlp_coeff[4] * data[i-5];
  97448. sum += qlp_coeff[3] * data[i-4];
  97449. sum += qlp_coeff[2] * data[i-3];
  97450. sum += qlp_coeff[1] * data[i-2];
  97451. sum += qlp_coeff[0] * data[i-1];
  97452. data[i] = residual[i] + (sum >> lp_quantization);
  97453. }
  97454. }
  97455. }
  97456. }
  97457. else {
  97458. if(order > 2) {
  97459. if(order == 4) {
  97460. for(i = 0; i < (int)data_len; i++) {
  97461. sum = 0;
  97462. sum += qlp_coeff[3] * data[i-4];
  97463. sum += qlp_coeff[2] * data[i-3];
  97464. sum += qlp_coeff[1] * data[i-2];
  97465. sum += qlp_coeff[0] * data[i-1];
  97466. data[i] = residual[i] + (sum >> lp_quantization);
  97467. }
  97468. }
  97469. else { /* order == 3 */
  97470. for(i = 0; i < (int)data_len; i++) {
  97471. sum = 0;
  97472. sum += qlp_coeff[2] * data[i-3];
  97473. sum += qlp_coeff[1] * data[i-2];
  97474. sum += qlp_coeff[0] * data[i-1];
  97475. data[i] = residual[i] + (sum >> lp_quantization);
  97476. }
  97477. }
  97478. }
  97479. else {
  97480. if(order == 2) {
  97481. for(i = 0; i < (int)data_len; i++) {
  97482. sum = 0;
  97483. sum += qlp_coeff[1] * data[i-2];
  97484. sum += qlp_coeff[0] * data[i-1];
  97485. data[i] = residual[i] + (sum >> lp_quantization);
  97486. }
  97487. }
  97488. else { /* order == 1 */
  97489. for(i = 0; i < (int)data_len; i++)
  97490. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97491. }
  97492. }
  97493. }
  97494. }
  97495. else { /* order > 12 */
  97496. for(i = 0; i < (int)data_len; i++) {
  97497. sum = 0;
  97498. switch(order) {
  97499. case 32: sum += qlp_coeff[31] * data[i-32];
  97500. case 31: sum += qlp_coeff[30] * data[i-31];
  97501. case 30: sum += qlp_coeff[29] * data[i-30];
  97502. case 29: sum += qlp_coeff[28] * data[i-29];
  97503. case 28: sum += qlp_coeff[27] * data[i-28];
  97504. case 27: sum += qlp_coeff[26] * data[i-27];
  97505. case 26: sum += qlp_coeff[25] * data[i-26];
  97506. case 25: sum += qlp_coeff[24] * data[i-25];
  97507. case 24: sum += qlp_coeff[23] * data[i-24];
  97508. case 23: sum += qlp_coeff[22] * data[i-23];
  97509. case 22: sum += qlp_coeff[21] * data[i-22];
  97510. case 21: sum += qlp_coeff[20] * data[i-21];
  97511. case 20: sum += qlp_coeff[19] * data[i-20];
  97512. case 19: sum += qlp_coeff[18] * data[i-19];
  97513. case 18: sum += qlp_coeff[17] * data[i-18];
  97514. case 17: sum += qlp_coeff[16] * data[i-17];
  97515. case 16: sum += qlp_coeff[15] * data[i-16];
  97516. case 15: sum += qlp_coeff[14] * data[i-15];
  97517. case 14: sum += qlp_coeff[13] * data[i-14];
  97518. case 13: sum += qlp_coeff[12] * data[i-13];
  97519. sum += qlp_coeff[11] * data[i-12];
  97520. sum += qlp_coeff[10] * data[i-11];
  97521. sum += qlp_coeff[ 9] * data[i-10];
  97522. sum += qlp_coeff[ 8] * data[i- 9];
  97523. sum += qlp_coeff[ 7] * data[i- 8];
  97524. sum += qlp_coeff[ 6] * data[i- 7];
  97525. sum += qlp_coeff[ 5] * data[i- 6];
  97526. sum += qlp_coeff[ 4] * data[i- 5];
  97527. sum += qlp_coeff[ 3] * data[i- 4];
  97528. sum += qlp_coeff[ 2] * data[i- 3];
  97529. sum += qlp_coeff[ 1] * data[i- 2];
  97530. sum += qlp_coeff[ 0] * data[i- 1];
  97531. }
  97532. data[i] = residual[i] + (sum >> lp_quantization);
  97533. }
  97534. }
  97535. }
  97536. #endif
  97537. 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[])
  97538. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97539. {
  97540. unsigned i, j;
  97541. FLAC__int64 sum;
  97542. const FLAC__int32 *r = residual, *history;
  97543. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97544. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97545. for(i=0;i<order;i++)
  97546. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97547. fprintf(stderr,"\n");
  97548. #endif
  97549. FLAC__ASSERT(order > 0);
  97550. for(i = 0; i < data_len; i++) {
  97551. sum = 0;
  97552. history = data;
  97553. for(j = 0; j < order; j++)
  97554. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97555. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97556. #ifdef _MSC_VER
  97557. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97558. #else
  97559. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97560. #endif
  97561. break;
  97562. }
  97563. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  97564. #ifdef _MSC_VER
  97565. 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));
  97566. #else
  97567. 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)));
  97568. #endif
  97569. break;
  97570. }
  97571. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  97572. }
  97573. }
  97574. #else /* fully unrolled version for normal use */
  97575. {
  97576. int i;
  97577. FLAC__int64 sum;
  97578. FLAC__ASSERT(order > 0);
  97579. FLAC__ASSERT(order <= 32);
  97580. /*
  97581. * We do unique versions up to 12th order since that's the subset limit.
  97582. * Also they are roughly ordered to match frequency of occurrence to
  97583. * minimize branching.
  97584. */
  97585. if(order <= 12) {
  97586. if(order > 8) {
  97587. if(order > 10) {
  97588. if(order == 12) {
  97589. for(i = 0; i < (int)data_len; i++) {
  97590. sum = 0;
  97591. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97592. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97593. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97594. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97595. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97596. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97597. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97598. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97599. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97600. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97601. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97602. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97603. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97604. }
  97605. }
  97606. else { /* order == 11 */
  97607. for(i = 0; i < (int)data_len; i++) {
  97608. sum = 0;
  97609. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97610. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97611. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97612. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97613. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97614. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97615. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97616. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97617. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97618. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97619. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97620. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97621. }
  97622. }
  97623. }
  97624. else {
  97625. if(order == 10) {
  97626. for(i = 0; i < (int)data_len; i++) {
  97627. sum = 0;
  97628. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97629. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97630. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97631. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97632. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97633. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97634. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97635. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97636. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97637. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97638. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97639. }
  97640. }
  97641. else { /* order == 9 */
  97642. for(i = 0; i < (int)data_len; i++) {
  97643. sum = 0;
  97644. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97645. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97646. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97647. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97648. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97649. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97650. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97651. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97652. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97653. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97654. }
  97655. }
  97656. }
  97657. }
  97658. else if(order > 4) {
  97659. if(order > 6) {
  97660. if(order == 8) {
  97661. for(i = 0; i < (int)data_len; i++) {
  97662. sum = 0;
  97663. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97664. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97665. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97666. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97667. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97668. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97669. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97670. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97671. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97672. }
  97673. }
  97674. else { /* order == 7 */
  97675. for(i = 0; i < (int)data_len; i++) {
  97676. sum = 0;
  97677. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97678. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97679. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97680. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97681. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97682. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97683. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97684. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97685. }
  97686. }
  97687. }
  97688. else {
  97689. if(order == 6) {
  97690. for(i = 0; i < (int)data_len; i++) {
  97691. sum = 0;
  97692. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97693. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97694. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97695. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97696. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97697. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97698. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97699. }
  97700. }
  97701. else { /* order == 5 */
  97702. for(i = 0; i < (int)data_len; i++) {
  97703. sum = 0;
  97704. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97705. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97706. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97707. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97708. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97709. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97710. }
  97711. }
  97712. }
  97713. }
  97714. else {
  97715. if(order > 2) {
  97716. if(order == 4) {
  97717. for(i = 0; i < (int)data_len; i++) {
  97718. sum = 0;
  97719. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97720. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97721. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97722. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97723. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97724. }
  97725. }
  97726. else { /* order == 3 */
  97727. for(i = 0; i < (int)data_len; i++) {
  97728. sum = 0;
  97729. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97730. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97731. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97732. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97733. }
  97734. }
  97735. }
  97736. else {
  97737. if(order == 2) {
  97738. for(i = 0; i < (int)data_len; i++) {
  97739. sum = 0;
  97740. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97741. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97742. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97743. }
  97744. }
  97745. else { /* order == 1 */
  97746. for(i = 0; i < (int)data_len; i++)
  97747. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97748. }
  97749. }
  97750. }
  97751. }
  97752. else { /* order > 12 */
  97753. for(i = 0; i < (int)data_len; i++) {
  97754. sum = 0;
  97755. switch(order) {
  97756. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97757. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97758. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97759. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97760. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97761. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97762. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97763. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97764. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97765. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97766. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97767. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97768. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97769. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97770. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97771. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97772. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97773. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97774. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97775. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97776. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97777. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97778. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97779. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97780. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97781. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97782. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97783. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97784. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97785. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97786. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97787. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97788. }
  97789. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97790. }
  97791. }
  97792. }
  97793. #endif
  97794. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97795. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  97796. {
  97797. FLAC__double error_scale;
  97798. FLAC__ASSERT(total_samples > 0);
  97799. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  97800. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  97801. }
  97802. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  97803. {
  97804. if(lpc_error > 0.0) {
  97805. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  97806. if(bps >= 0.0)
  97807. return bps;
  97808. else
  97809. return 0.0;
  97810. }
  97811. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  97812. return 1e32;
  97813. }
  97814. else {
  97815. return 0.0;
  97816. }
  97817. }
  97818. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  97819. {
  97820. 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 */
  97821. FLAC__double bits, best_bits, error_scale;
  97822. FLAC__ASSERT(max_order > 0);
  97823. FLAC__ASSERT(total_samples > 0);
  97824. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  97825. best_index = 0;
  97826. best_bits = (unsigned)(-1);
  97827. for(index = 0, order = 1; index < max_order; index++, order++) {
  97828. 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);
  97829. if(bits < best_bits) {
  97830. best_index = index;
  97831. best_bits = bits;
  97832. }
  97833. }
  97834. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  97835. }
  97836. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97837. #endif
  97838. /*** End of inlined file: lpc_flac.c ***/
  97839. /*** Start of inlined file: md5.c ***/
  97840. /*** Start of inlined file: juce_FlacHeader.h ***/
  97841. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97842. // tasks..
  97843. #define VERSION "1.2.1"
  97844. #define FLAC__NO_DLL 1
  97845. #if JUCE_MSVC
  97846. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97847. #endif
  97848. #if JUCE_MAC
  97849. #define FLAC__SYS_DARWIN 1
  97850. #endif
  97851. /*** End of inlined file: juce_FlacHeader.h ***/
  97852. #if JUCE_USE_FLAC
  97853. #if HAVE_CONFIG_H
  97854. # include <config.h>
  97855. #endif
  97856. #include <stdlib.h> /* for malloc() */
  97857. #include <string.h> /* for memcpy() */
  97858. /*** Start of inlined file: md5.h ***/
  97859. #ifndef FLAC__PRIVATE__MD5_H
  97860. #define FLAC__PRIVATE__MD5_H
  97861. /*
  97862. * This is the header file for the MD5 message-digest algorithm.
  97863. * The algorithm is due to Ron Rivest. This code was
  97864. * written by Colin Plumb in 1993, no copyright is claimed.
  97865. * This code is in the public domain; do with it what you wish.
  97866. *
  97867. * Equivalent code is available from RSA Data Security, Inc.
  97868. * This code has been tested against that, and is equivalent,
  97869. * except that you don't need to include two pages of legalese
  97870. * with every copy.
  97871. *
  97872. * To compute the message digest of a chunk of bytes, declare an
  97873. * MD5Context structure, pass it to MD5Init, call MD5Update as
  97874. * needed on buffers full of bytes, and then call MD5Final, which
  97875. * will fill a supplied 16-byte array with the digest.
  97876. *
  97877. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  97878. * header definitions; now uses stuff from dpkg's config.h
  97879. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  97880. * Still in the public domain.
  97881. *
  97882. * Josh Coalson: made some changes to integrate with libFLAC.
  97883. * Still in the public domain, with no warranty.
  97884. */
  97885. typedef struct {
  97886. FLAC__uint32 in[16];
  97887. FLAC__uint32 buf[4];
  97888. FLAC__uint32 bytes[2];
  97889. FLAC__byte *internal_buf;
  97890. size_t capacity;
  97891. } FLAC__MD5Context;
  97892. void FLAC__MD5Init(FLAC__MD5Context *context);
  97893. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  97894. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  97895. #endif
  97896. /*** End of inlined file: md5.h ***/
  97897. #ifndef FLaC__INLINE
  97898. #define FLaC__INLINE
  97899. #endif
  97900. /*
  97901. * This code implements the MD5 message-digest algorithm.
  97902. * The algorithm is due to Ron Rivest. This code was
  97903. * written by Colin Plumb in 1993, no copyright is claimed.
  97904. * This code is in the public domain; do with it what you wish.
  97905. *
  97906. * Equivalent code is available from RSA Data Security, Inc.
  97907. * This code has been tested against that, and is equivalent,
  97908. * except that you don't need to include two pages of legalese
  97909. * with every copy.
  97910. *
  97911. * To compute the message digest of a chunk of bytes, declare an
  97912. * MD5Context structure, pass it to MD5Init, call MD5Update as
  97913. * needed on buffers full of bytes, and then call MD5Final, which
  97914. * will fill a supplied 16-byte array with the digest.
  97915. *
  97916. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  97917. * definitions; now uses stuff from dpkg's config.h.
  97918. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  97919. * Still in the public domain.
  97920. *
  97921. * Josh Coalson: made some changes to integrate with libFLAC.
  97922. * Still in the public domain.
  97923. */
  97924. /* The four core functions - F1 is optimized somewhat */
  97925. /* #define F1(x, y, z) (x & y | ~x & z) */
  97926. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  97927. #define F2(x, y, z) F1(z, x, y)
  97928. #define F3(x, y, z) (x ^ y ^ z)
  97929. #define F4(x, y, z) (y ^ (x | ~z))
  97930. /* This is the central step in the MD5 algorithm. */
  97931. #define MD5STEP(f,w,x,y,z,in,s) \
  97932. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  97933. /*
  97934. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  97935. * reflect the addition of 16 longwords of new data. MD5Update blocks
  97936. * the data and converts bytes into longwords for this routine.
  97937. */
  97938. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  97939. {
  97940. register FLAC__uint32 a, b, c, d;
  97941. a = buf[0];
  97942. b = buf[1];
  97943. c = buf[2];
  97944. d = buf[3];
  97945. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  97946. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  97947. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  97948. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  97949. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  97950. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  97951. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  97952. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  97953. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  97954. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  97955. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  97956. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  97957. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  97958. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  97959. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  97960. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  97961. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  97962. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  97963. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  97964. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  97965. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  97966. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  97967. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  97968. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  97969. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  97970. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  97971. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  97972. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  97973. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  97974. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  97975. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  97976. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  97977. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  97978. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  97979. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  97980. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  97981. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  97982. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  97983. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  97984. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  97985. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  97986. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  97987. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  97988. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  97989. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  97990. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  97991. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  97992. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  97993. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  97994. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  97995. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  97996. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  97997. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  97998. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  97999. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98000. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98001. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98002. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98003. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98004. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98005. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98006. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98007. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98008. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98009. buf[0] += a;
  98010. buf[1] += b;
  98011. buf[2] += c;
  98012. buf[3] += d;
  98013. }
  98014. #if WORDS_BIGENDIAN
  98015. //@@@@@@ OPT: use bswap/intrinsics
  98016. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98017. {
  98018. register FLAC__uint32 x;
  98019. do {
  98020. x = *buf;
  98021. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98022. *buf++ = (x >> 16) | (x << 16);
  98023. } while (--words);
  98024. }
  98025. static void byteSwapX16(FLAC__uint32 *buf)
  98026. {
  98027. register FLAC__uint32 x;
  98028. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98029. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98030. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98031. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98032. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98033. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98034. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98035. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98036. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98037. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98038. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98039. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98040. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98041. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98042. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98043. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98044. }
  98045. #else
  98046. #define byteSwap(buf, words)
  98047. #define byteSwapX16(buf)
  98048. #endif
  98049. /*
  98050. * Update context to reflect the concatenation of another buffer full
  98051. * of bytes.
  98052. */
  98053. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98054. {
  98055. FLAC__uint32 t;
  98056. /* Update byte count */
  98057. t = ctx->bytes[0];
  98058. if ((ctx->bytes[0] = t + len) < t)
  98059. ctx->bytes[1]++; /* Carry from low to high */
  98060. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98061. if (t > len) {
  98062. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98063. return;
  98064. }
  98065. /* First chunk is an odd size */
  98066. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98067. byteSwapX16(ctx->in);
  98068. FLAC__MD5Transform(ctx->buf, ctx->in);
  98069. buf += t;
  98070. len -= t;
  98071. /* Process data in 64-byte chunks */
  98072. while (len >= 64) {
  98073. memcpy(ctx->in, buf, 64);
  98074. byteSwapX16(ctx->in);
  98075. FLAC__MD5Transform(ctx->buf, ctx->in);
  98076. buf += 64;
  98077. len -= 64;
  98078. }
  98079. /* Handle any remaining bytes of data. */
  98080. memcpy(ctx->in, buf, len);
  98081. }
  98082. /*
  98083. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98084. * initialization constants.
  98085. */
  98086. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98087. {
  98088. ctx->buf[0] = 0x67452301;
  98089. ctx->buf[1] = 0xefcdab89;
  98090. ctx->buf[2] = 0x98badcfe;
  98091. ctx->buf[3] = 0x10325476;
  98092. ctx->bytes[0] = 0;
  98093. ctx->bytes[1] = 0;
  98094. ctx->internal_buf = 0;
  98095. ctx->capacity = 0;
  98096. }
  98097. /*
  98098. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98099. * 1 0* (64-bit count of bits processed, MSB-first)
  98100. */
  98101. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98102. {
  98103. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98104. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98105. /* Set the first char of padding to 0x80. There is always room. */
  98106. *p++ = 0x80;
  98107. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98108. count = 56 - 1 - count;
  98109. if (count < 0) { /* Padding forces an extra block */
  98110. memset(p, 0, count + 8);
  98111. byteSwapX16(ctx->in);
  98112. FLAC__MD5Transform(ctx->buf, ctx->in);
  98113. p = (FLAC__byte *)ctx->in;
  98114. count = 56;
  98115. }
  98116. memset(p, 0, count);
  98117. byteSwap(ctx->in, 14);
  98118. /* Append length in bits and transform */
  98119. ctx->in[14] = ctx->bytes[0] << 3;
  98120. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98121. FLAC__MD5Transform(ctx->buf, ctx->in);
  98122. byteSwap(ctx->buf, 4);
  98123. memcpy(digest, ctx->buf, 16);
  98124. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98125. if(0 != ctx->internal_buf) {
  98126. free(ctx->internal_buf);
  98127. ctx->internal_buf = 0;
  98128. ctx->capacity = 0;
  98129. }
  98130. }
  98131. /*
  98132. * Convert the incoming audio signal to a byte stream
  98133. */
  98134. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98135. {
  98136. unsigned channel, sample;
  98137. register FLAC__int32 a_word;
  98138. register FLAC__byte *buf_ = buf;
  98139. #if WORDS_BIGENDIAN
  98140. #else
  98141. if(channels == 2 && bytes_per_sample == 2) {
  98142. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98143. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98144. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98145. *buf1_ = (FLAC__int16)signal[1][sample];
  98146. }
  98147. else if(channels == 1 && bytes_per_sample == 2) {
  98148. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98149. for(sample = 0; sample < samples; sample++)
  98150. *buf1_++ = (FLAC__int16)signal[0][sample];
  98151. }
  98152. else
  98153. #endif
  98154. if(bytes_per_sample == 2) {
  98155. if(channels == 2) {
  98156. for(sample = 0; sample < samples; sample++) {
  98157. a_word = signal[0][sample];
  98158. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98159. *buf_++ = (FLAC__byte)a_word;
  98160. a_word = signal[1][sample];
  98161. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98162. *buf_++ = (FLAC__byte)a_word;
  98163. }
  98164. }
  98165. else if(channels == 1) {
  98166. for(sample = 0; sample < samples; sample++) {
  98167. a_word = signal[0][sample];
  98168. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98169. *buf_++ = (FLAC__byte)a_word;
  98170. }
  98171. }
  98172. else {
  98173. for(sample = 0; sample < samples; sample++) {
  98174. for(channel = 0; channel < channels; channel++) {
  98175. a_word = signal[channel][sample];
  98176. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98177. *buf_++ = (FLAC__byte)a_word;
  98178. }
  98179. }
  98180. }
  98181. }
  98182. else if(bytes_per_sample == 3) {
  98183. if(channels == 2) {
  98184. for(sample = 0; sample < samples; sample++) {
  98185. a_word = signal[0][sample];
  98186. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98187. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98188. *buf_++ = (FLAC__byte)a_word;
  98189. a_word = signal[1][sample];
  98190. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98191. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98192. *buf_++ = (FLAC__byte)a_word;
  98193. }
  98194. }
  98195. else if(channels == 1) {
  98196. for(sample = 0; sample < samples; sample++) {
  98197. a_word = signal[0][sample];
  98198. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98199. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98200. *buf_++ = (FLAC__byte)a_word;
  98201. }
  98202. }
  98203. else {
  98204. for(sample = 0; sample < samples; sample++) {
  98205. for(channel = 0; channel < channels; channel++) {
  98206. a_word = signal[channel][sample];
  98207. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98208. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98209. *buf_++ = (FLAC__byte)a_word;
  98210. }
  98211. }
  98212. }
  98213. }
  98214. else if(bytes_per_sample == 1) {
  98215. if(channels == 2) {
  98216. for(sample = 0; sample < samples; sample++) {
  98217. a_word = signal[0][sample];
  98218. *buf_++ = (FLAC__byte)a_word;
  98219. a_word = signal[1][sample];
  98220. *buf_++ = (FLAC__byte)a_word;
  98221. }
  98222. }
  98223. else if(channels == 1) {
  98224. for(sample = 0; sample < samples; sample++) {
  98225. a_word = signal[0][sample];
  98226. *buf_++ = (FLAC__byte)a_word;
  98227. }
  98228. }
  98229. else {
  98230. for(sample = 0; sample < samples; sample++) {
  98231. for(channel = 0; channel < channels; channel++) {
  98232. a_word = signal[channel][sample];
  98233. *buf_++ = (FLAC__byte)a_word;
  98234. }
  98235. }
  98236. }
  98237. }
  98238. else { /* bytes_per_sample == 4, maybe optimize more later */
  98239. for(sample = 0; sample < samples; sample++) {
  98240. for(channel = 0; channel < channels; channel++) {
  98241. a_word = signal[channel][sample];
  98242. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98243. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98244. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98245. *buf_++ = (FLAC__byte)a_word;
  98246. }
  98247. }
  98248. }
  98249. }
  98250. /*
  98251. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  98252. */
  98253. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98254. {
  98255. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  98256. /* overflow check */
  98257. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  98258. return false;
  98259. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  98260. return false;
  98261. if(ctx->capacity < bytes_needed) {
  98262. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  98263. if(0 == tmp) {
  98264. free(ctx->internal_buf);
  98265. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  98266. return false;
  98267. }
  98268. ctx->internal_buf = tmp;
  98269. ctx->capacity = bytes_needed;
  98270. }
  98271. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  98272. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  98273. return true;
  98274. }
  98275. #endif
  98276. /*** End of inlined file: md5.c ***/
  98277. /*** Start of inlined file: memory.c ***/
  98278. /*** Start of inlined file: juce_FlacHeader.h ***/
  98279. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98280. // tasks..
  98281. #define VERSION "1.2.1"
  98282. #define FLAC__NO_DLL 1
  98283. #if JUCE_MSVC
  98284. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98285. #endif
  98286. #if JUCE_MAC
  98287. #define FLAC__SYS_DARWIN 1
  98288. #endif
  98289. /*** End of inlined file: juce_FlacHeader.h ***/
  98290. #if JUCE_USE_FLAC
  98291. #if HAVE_CONFIG_H
  98292. # include <config.h>
  98293. #endif
  98294. /*** Start of inlined file: memory.h ***/
  98295. #ifndef FLAC__PRIVATE__MEMORY_H
  98296. #define FLAC__PRIVATE__MEMORY_H
  98297. #ifdef HAVE_CONFIG_H
  98298. #include <config.h>
  98299. #endif
  98300. #include <stdlib.h> /* for size_t */
  98301. /* Returns the unaligned address returned by malloc.
  98302. * Use free() on this address to deallocate.
  98303. */
  98304. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98305. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98306. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98307. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98308. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98309. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98310. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98311. #endif
  98312. #endif
  98313. /*** End of inlined file: memory.h ***/
  98314. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98315. {
  98316. void *x;
  98317. FLAC__ASSERT(0 != aligned_address);
  98318. #ifdef FLAC__ALIGN_MALLOC_DATA
  98319. /* align on 32-byte (256-bit) boundary */
  98320. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98321. #ifdef SIZEOF_VOIDP
  98322. #if SIZEOF_VOIDP == 4
  98323. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98324. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98325. #elif SIZEOF_VOIDP == 8
  98326. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98327. #else
  98328. # error Unsupported sizeof(void*)
  98329. #endif
  98330. #else
  98331. /* there's got to be a better way to do this right for all archs */
  98332. if(sizeof(void*) == sizeof(unsigned))
  98333. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98334. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98335. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98336. else
  98337. return 0;
  98338. #endif
  98339. #else
  98340. x = safe_malloc_(bytes);
  98341. *aligned_address = x;
  98342. #endif
  98343. return x;
  98344. }
  98345. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98346. {
  98347. FLAC__int32 *pu; /* unaligned pointer */
  98348. union { /* union needed to comply with C99 pointer aliasing rules */
  98349. FLAC__int32 *pa; /* aligned pointer */
  98350. void *pv; /* aligned pointer alias */
  98351. } u;
  98352. FLAC__ASSERT(elements > 0);
  98353. FLAC__ASSERT(0 != unaligned_pointer);
  98354. FLAC__ASSERT(0 != aligned_pointer);
  98355. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98356. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98357. if(0 == pu) {
  98358. return false;
  98359. }
  98360. else {
  98361. if(*unaligned_pointer != 0)
  98362. free(*unaligned_pointer);
  98363. *unaligned_pointer = pu;
  98364. *aligned_pointer = u.pa;
  98365. return true;
  98366. }
  98367. }
  98368. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  98369. {
  98370. FLAC__uint32 *pu; /* unaligned pointer */
  98371. union { /* union needed to comply with C99 pointer aliasing rules */
  98372. FLAC__uint32 *pa; /* aligned pointer */
  98373. void *pv; /* aligned pointer alias */
  98374. } u;
  98375. FLAC__ASSERT(elements > 0);
  98376. FLAC__ASSERT(0 != unaligned_pointer);
  98377. FLAC__ASSERT(0 != aligned_pointer);
  98378. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98379. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98380. if(0 == pu) {
  98381. return false;
  98382. }
  98383. else {
  98384. if(*unaligned_pointer != 0)
  98385. free(*unaligned_pointer);
  98386. *unaligned_pointer = pu;
  98387. *aligned_pointer = u.pa;
  98388. return true;
  98389. }
  98390. }
  98391. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  98392. {
  98393. FLAC__uint64 *pu; /* unaligned pointer */
  98394. union { /* union needed to comply with C99 pointer aliasing rules */
  98395. FLAC__uint64 *pa; /* aligned pointer */
  98396. void *pv; /* aligned pointer alias */
  98397. } u;
  98398. FLAC__ASSERT(elements > 0);
  98399. FLAC__ASSERT(0 != unaligned_pointer);
  98400. FLAC__ASSERT(0 != aligned_pointer);
  98401. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98402. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98403. if(0 == pu) {
  98404. return false;
  98405. }
  98406. else {
  98407. if(*unaligned_pointer != 0)
  98408. free(*unaligned_pointer);
  98409. *unaligned_pointer = pu;
  98410. *aligned_pointer = u.pa;
  98411. return true;
  98412. }
  98413. }
  98414. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  98415. {
  98416. unsigned *pu; /* unaligned pointer */
  98417. union { /* union needed to comply with C99 pointer aliasing rules */
  98418. unsigned *pa; /* aligned pointer */
  98419. void *pv; /* aligned pointer alias */
  98420. } u;
  98421. FLAC__ASSERT(elements > 0);
  98422. FLAC__ASSERT(0 != unaligned_pointer);
  98423. FLAC__ASSERT(0 != aligned_pointer);
  98424. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98425. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98426. if(0 == pu) {
  98427. return false;
  98428. }
  98429. else {
  98430. if(*unaligned_pointer != 0)
  98431. free(*unaligned_pointer);
  98432. *unaligned_pointer = pu;
  98433. *aligned_pointer = u.pa;
  98434. return true;
  98435. }
  98436. }
  98437. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98438. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  98439. {
  98440. FLAC__real *pu; /* unaligned pointer */
  98441. union { /* union needed to comply with C99 pointer aliasing rules */
  98442. FLAC__real *pa; /* aligned pointer */
  98443. void *pv; /* aligned pointer alias */
  98444. } u;
  98445. FLAC__ASSERT(elements > 0);
  98446. FLAC__ASSERT(0 != unaligned_pointer);
  98447. FLAC__ASSERT(0 != aligned_pointer);
  98448. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98449. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98450. if(0 == pu) {
  98451. return false;
  98452. }
  98453. else {
  98454. if(*unaligned_pointer != 0)
  98455. free(*unaligned_pointer);
  98456. *unaligned_pointer = pu;
  98457. *aligned_pointer = u.pa;
  98458. return true;
  98459. }
  98460. }
  98461. #endif
  98462. #endif
  98463. /*** End of inlined file: memory.c ***/
  98464. /*** Start of inlined file: stream_decoder.c ***/
  98465. /*** Start of inlined file: juce_FlacHeader.h ***/
  98466. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98467. // tasks..
  98468. #define VERSION "1.2.1"
  98469. #define FLAC__NO_DLL 1
  98470. #if JUCE_MSVC
  98471. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98472. #endif
  98473. #if JUCE_MAC
  98474. #define FLAC__SYS_DARWIN 1
  98475. #endif
  98476. /*** End of inlined file: juce_FlacHeader.h ***/
  98477. #if JUCE_USE_FLAC
  98478. #if HAVE_CONFIG_H
  98479. # include <config.h>
  98480. #endif
  98481. #if defined _MSC_VER || defined __MINGW32__
  98482. #include <io.h> /* for _setmode() */
  98483. #include <fcntl.h> /* for _O_BINARY */
  98484. #endif
  98485. #if defined __CYGWIN__ || defined __EMX__
  98486. #include <io.h> /* for setmode(), O_BINARY */
  98487. #include <fcntl.h> /* for _O_BINARY */
  98488. #endif
  98489. #include <stdio.h>
  98490. #include <stdlib.h> /* for malloc() */
  98491. #include <string.h> /* for memset/memcpy() */
  98492. #include <sys/stat.h> /* for stat() */
  98493. #include <sys/types.h> /* for off_t */
  98494. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  98495. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  98496. #define fseeko fseek
  98497. #define ftello ftell
  98498. #endif
  98499. #endif
  98500. /*** Start of inlined file: stream_decoder.h ***/
  98501. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  98502. #define FLAC__PROTECTED__STREAM_DECODER_H
  98503. #if FLAC__HAS_OGG
  98504. #include "include/private/ogg_decoder_aspect.h"
  98505. #endif
  98506. typedef struct FLAC__StreamDecoderProtected {
  98507. FLAC__StreamDecoderState state;
  98508. unsigned channels;
  98509. FLAC__ChannelAssignment channel_assignment;
  98510. unsigned bits_per_sample;
  98511. unsigned sample_rate; /* in Hz */
  98512. unsigned blocksize; /* in samples (per channel) */
  98513. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  98514. #if FLAC__HAS_OGG
  98515. FLAC__OggDecoderAspect ogg_decoder_aspect;
  98516. #endif
  98517. } FLAC__StreamDecoderProtected;
  98518. /*
  98519. * return the number of input bytes consumed
  98520. */
  98521. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  98522. #endif
  98523. /*** End of inlined file: stream_decoder.h ***/
  98524. #ifdef max
  98525. #undef max
  98526. #endif
  98527. #define max(a,b) ((a)>(b)?(a):(b))
  98528. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  98529. #ifdef _MSC_VER
  98530. #define FLAC__U64L(x) x
  98531. #else
  98532. #define FLAC__U64L(x) x##LLU
  98533. #endif
  98534. /* technically this should be in an "export.c" but this is convenient enough */
  98535. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  98536. #if FLAC__HAS_OGG
  98537. 1
  98538. #else
  98539. 0
  98540. #endif
  98541. ;
  98542. /***********************************************************************
  98543. *
  98544. * Private static data
  98545. *
  98546. ***********************************************************************/
  98547. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  98548. /***********************************************************************
  98549. *
  98550. * Private class method prototypes
  98551. *
  98552. ***********************************************************************/
  98553. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  98554. static FILE *get_binary_stdin_(void);
  98555. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  98556. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  98557. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  98558. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  98559. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98560. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98561. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  98562. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  98563. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  98564. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  98565. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  98566. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  98567. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  98568. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98569. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98570. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98571. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98572. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98573. 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);
  98574. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  98575. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  98576. #if FLAC__HAS_OGG
  98577. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  98578. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98579. #endif
  98580. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  98581. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  98582. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98583. #if FLAC__HAS_OGG
  98584. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98585. #endif
  98586. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98587. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  98588. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  98589. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  98590. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  98591. /***********************************************************************
  98592. *
  98593. * Private class data
  98594. *
  98595. ***********************************************************************/
  98596. typedef struct FLAC__StreamDecoderPrivate {
  98597. #if FLAC__HAS_OGG
  98598. FLAC__bool is_ogg;
  98599. #endif
  98600. FLAC__StreamDecoderReadCallback read_callback;
  98601. FLAC__StreamDecoderSeekCallback seek_callback;
  98602. FLAC__StreamDecoderTellCallback tell_callback;
  98603. FLAC__StreamDecoderLengthCallback length_callback;
  98604. FLAC__StreamDecoderEofCallback eof_callback;
  98605. FLAC__StreamDecoderWriteCallback write_callback;
  98606. FLAC__StreamDecoderMetadataCallback metadata_callback;
  98607. FLAC__StreamDecoderErrorCallback error_callback;
  98608. /* generic 32-bit datapath: */
  98609. 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[]);
  98610. /* generic 64-bit datapath: */
  98611. 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[]);
  98612. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  98613. 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[]);
  98614. /* 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: */
  98615. 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[]);
  98616. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  98617. void *client_data;
  98618. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  98619. FLAC__BitReader *input;
  98620. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  98621. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  98622. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  98623. unsigned output_capacity, output_channels;
  98624. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  98625. FLAC__uint64 samples_decoded;
  98626. FLAC__bool has_stream_info, has_seek_table;
  98627. FLAC__StreamMetadata stream_info;
  98628. FLAC__StreamMetadata seek_table;
  98629. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  98630. FLAC__byte *metadata_filter_ids;
  98631. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  98632. FLAC__Frame frame;
  98633. FLAC__bool cached; /* true if there is a byte in lookahead */
  98634. FLAC__CPUInfo cpuinfo;
  98635. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  98636. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  98637. /* unaligned (original) pointers to allocated data */
  98638. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  98639. 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 */
  98640. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  98641. FLAC__bool is_seeking;
  98642. FLAC__MD5Context md5context;
  98643. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  98644. /* (the rest of these are only used for seeking) */
  98645. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  98646. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  98647. FLAC__uint64 target_sample;
  98648. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  98649. #if FLAC__HAS_OGG
  98650. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  98651. #endif
  98652. } FLAC__StreamDecoderPrivate;
  98653. /***********************************************************************
  98654. *
  98655. * Public static class data
  98656. *
  98657. ***********************************************************************/
  98658. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  98659. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  98660. "FLAC__STREAM_DECODER_READ_METADATA",
  98661. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  98662. "FLAC__STREAM_DECODER_READ_FRAME",
  98663. "FLAC__STREAM_DECODER_END_OF_STREAM",
  98664. "FLAC__STREAM_DECODER_OGG_ERROR",
  98665. "FLAC__STREAM_DECODER_SEEK_ERROR",
  98666. "FLAC__STREAM_DECODER_ABORTED",
  98667. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  98668. "FLAC__STREAM_DECODER_UNINITIALIZED"
  98669. };
  98670. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  98671. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  98672. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  98673. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  98674. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  98675. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  98676. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  98677. };
  98678. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  98679. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  98680. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  98681. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  98682. };
  98683. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  98684. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  98685. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  98686. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  98687. };
  98688. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  98689. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  98690. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  98691. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  98692. };
  98693. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  98694. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  98695. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  98696. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  98697. };
  98698. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  98699. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  98700. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  98701. };
  98702. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  98703. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  98704. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  98705. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  98706. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  98707. };
  98708. /***********************************************************************
  98709. *
  98710. * Class constructor/destructor
  98711. *
  98712. ***********************************************************************/
  98713. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  98714. {
  98715. FLAC__StreamDecoder *decoder;
  98716. unsigned i;
  98717. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  98718. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  98719. if(decoder == 0) {
  98720. return 0;
  98721. }
  98722. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  98723. if(decoder->protected_ == 0) {
  98724. free(decoder);
  98725. return 0;
  98726. }
  98727. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  98728. if(decoder->private_ == 0) {
  98729. free(decoder->protected_);
  98730. free(decoder);
  98731. return 0;
  98732. }
  98733. decoder->private_->input = FLAC__bitreader_new();
  98734. if(decoder->private_->input == 0) {
  98735. free(decoder->private_);
  98736. free(decoder->protected_);
  98737. free(decoder);
  98738. return 0;
  98739. }
  98740. decoder->private_->metadata_filter_ids_capacity = 16;
  98741. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  98742. FLAC__bitreader_delete(decoder->private_->input);
  98743. free(decoder->private_);
  98744. free(decoder->protected_);
  98745. free(decoder);
  98746. return 0;
  98747. }
  98748. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98749. decoder->private_->output[i] = 0;
  98750. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  98751. }
  98752. decoder->private_->output_capacity = 0;
  98753. decoder->private_->output_channels = 0;
  98754. decoder->private_->has_seek_table = false;
  98755. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  98756. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  98757. decoder->private_->file = 0;
  98758. set_defaults_dec(decoder);
  98759. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  98760. return decoder;
  98761. }
  98762. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  98763. {
  98764. unsigned i;
  98765. FLAC__ASSERT(0 != decoder);
  98766. FLAC__ASSERT(0 != decoder->protected_);
  98767. FLAC__ASSERT(0 != decoder->private_);
  98768. FLAC__ASSERT(0 != decoder->private_->input);
  98769. (void)FLAC__stream_decoder_finish(decoder);
  98770. if(0 != decoder->private_->metadata_filter_ids)
  98771. free(decoder->private_->metadata_filter_ids);
  98772. FLAC__bitreader_delete(decoder->private_->input);
  98773. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  98774. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  98775. free(decoder->private_);
  98776. free(decoder->protected_);
  98777. free(decoder);
  98778. }
  98779. /***********************************************************************
  98780. *
  98781. * Public class methods
  98782. *
  98783. ***********************************************************************/
  98784. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  98785. FLAC__StreamDecoder *decoder,
  98786. FLAC__StreamDecoderReadCallback read_callback,
  98787. FLAC__StreamDecoderSeekCallback seek_callback,
  98788. FLAC__StreamDecoderTellCallback tell_callback,
  98789. FLAC__StreamDecoderLengthCallback length_callback,
  98790. FLAC__StreamDecoderEofCallback eof_callback,
  98791. FLAC__StreamDecoderWriteCallback write_callback,
  98792. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98793. FLAC__StreamDecoderErrorCallback error_callback,
  98794. void *client_data,
  98795. FLAC__bool is_ogg
  98796. )
  98797. {
  98798. FLAC__ASSERT(0 != decoder);
  98799. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98800. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  98801. #if !FLAC__HAS_OGG
  98802. if(is_ogg)
  98803. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  98804. #endif
  98805. if(
  98806. 0 == read_callback ||
  98807. 0 == write_callback ||
  98808. 0 == error_callback ||
  98809. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  98810. )
  98811. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  98812. #if FLAC__HAS_OGG
  98813. decoder->private_->is_ogg = is_ogg;
  98814. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  98815. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  98816. #endif
  98817. /*
  98818. * get the CPU info and set the function pointers
  98819. */
  98820. FLAC__cpu_info(&decoder->private_->cpuinfo);
  98821. /* first default to the non-asm routines */
  98822. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  98823. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  98824. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  98825. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  98826. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  98827. /* now override with asm where appropriate */
  98828. #ifndef FLAC__NO_ASM
  98829. if(decoder->private_->cpuinfo.use_asm) {
  98830. #ifdef FLAC__CPU_IA32
  98831. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  98832. #ifdef FLAC__HAS_NASM
  98833. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  98834. if(decoder->private_->cpuinfo.data.ia32.bswap)
  98835. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  98836. #endif
  98837. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  98838. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  98839. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  98840. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  98841. }
  98842. else {
  98843. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  98844. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  98845. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  98846. }
  98847. #endif
  98848. #elif defined FLAC__CPU_PPC
  98849. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  98850. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  98851. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  98852. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  98853. }
  98854. #endif
  98855. }
  98856. #endif
  98857. /* from here on, errors are fatal */
  98858. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  98859. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98860. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  98861. }
  98862. decoder->private_->read_callback = read_callback;
  98863. decoder->private_->seek_callback = seek_callback;
  98864. decoder->private_->tell_callback = tell_callback;
  98865. decoder->private_->length_callback = length_callback;
  98866. decoder->private_->eof_callback = eof_callback;
  98867. decoder->private_->write_callback = write_callback;
  98868. decoder->private_->metadata_callback = metadata_callback;
  98869. decoder->private_->error_callback = error_callback;
  98870. decoder->private_->client_data = client_data;
  98871. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  98872. decoder->private_->samples_decoded = 0;
  98873. decoder->private_->has_stream_info = false;
  98874. decoder->private_->cached = false;
  98875. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  98876. decoder->private_->is_seeking = false;
  98877. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  98878. if(!FLAC__stream_decoder_reset(decoder)) {
  98879. /* above call sets the state for us */
  98880. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  98881. }
  98882. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  98883. }
  98884. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  98885. FLAC__StreamDecoder *decoder,
  98886. FLAC__StreamDecoderReadCallback read_callback,
  98887. FLAC__StreamDecoderSeekCallback seek_callback,
  98888. FLAC__StreamDecoderTellCallback tell_callback,
  98889. FLAC__StreamDecoderLengthCallback length_callback,
  98890. FLAC__StreamDecoderEofCallback eof_callback,
  98891. FLAC__StreamDecoderWriteCallback write_callback,
  98892. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98893. FLAC__StreamDecoderErrorCallback error_callback,
  98894. void *client_data
  98895. )
  98896. {
  98897. return init_stream_internal_dec(
  98898. decoder,
  98899. read_callback,
  98900. seek_callback,
  98901. tell_callback,
  98902. length_callback,
  98903. eof_callback,
  98904. write_callback,
  98905. metadata_callback,
  98906. error_callback,
  98907. client_data,
  98908. /*is_ogg=*/false
  98909. );
  98910. }
  98911. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  98912. FLAC__StreamDecoder *decoder,
  98913. FLAC__StreamDecoderReadCallback read_callback,
  98914. FLAC__StreamDecoderSeekCallback seek_callback,
  98915. FLAC__StreamDecoderTellCallback tell_callback,
  98916. FLAC__StreamDecoderLengthCallback length_callback,
  98917. FLAC__StreamDecoderEofCallback eof_callback,
  98918. FLAC__StreamDecoderWriteCallback write_callback,
  98919. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98920. FLAC__StreamDecoderErrorCallback error_callback,
  98921. void *client_data
  98922. )
  98923. {
  98924. return init_stream_internal_dec(
  98925. decoder,
  98926. read_callback,
  98927. seek_callback,
  98928. tell_callback,
  98929. length_callback,
  98930. eof_callback,
  98931. write_callback,
  98932. metadata_callback,
  98933. error_callback,
  98934. client_data,
  98935. /*is_ogg=*/true
  98936. );
  98937. }
  98938. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  98939. FLAC__StreamDecoder *decoder,
  98940. FILE *file,
  98941. FLAC__StreamDecoderWriteCallback write_callback,
  98942. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98943. FLAC__StreamDecoderErrorCallback error_callback,
  98944. void *client_data,
  98945. FLAC__bool is_ogg
  98946. )
  98947. {
  98948. FLAC__ASSERT(0 != decoder);
  98949. FLAC__ASSERT(0 != file);
  98950. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98951. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  98952. if(0 == write_callback || 0 == error_callback)
  98953. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  98954. /*
  98955. * To make sure that our file does not go unclosed after an error, we
  98956. * must assign the FILE pointer before any further error can occur in
  98957. * this routine.
  98958. */
  98959. if(file == stdin)
  98960. file = get_binary_stdin_(); /* just to be safe */
  98961. decoder->private_->file = file;
  98962. return init_stream_internal_dec(
  98963. decoder,
  98964. file_read_callback_dec,
  98965. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  98966. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  98967. decoder->private_->file == stdin? 0: file_length_callback_,
  98968. file_eof_callback_,
  98969. write_callback,
  98970. metadata_callback,
  98971. error_callback,
  98972. client_data,
  98973. is_ogg
  98974. );
  98975. }
  98976. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  98977. FLAC__StreamDecoder *decoder,
  98978. FILE *file,
  98979. FLAC__StreamDecoderWriteCallback write_callback,
  98980. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98981. FLAC__StreamDecoderErrorCallback error_callback,
  98982. void *client_data
  98983. )
  98984. {
  98985. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  98986. }
  98987. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  98988. FLAC__StreamDecoder *decoder,
  98989. FILE *file,
  98990. FLAC__StreamDecoderWriteCallback write_callback,
  98991. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98992. FLAC__StreamDecoderErrorCallback error_callback,
  98993. void *client_data
  98994. )
  98995. {
  98996. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  98997. }
  98998. static FLAC__StreamDecoderInitStatus init_file_internal_(
  98999. FLAC__StreamDecoder *decoder,
  99000. const char *filename,
  99001. FLAC__StreamDecoderWriteCallback write_callback,
  99002. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99003. FLAC__StreamDecoderErrorCallback error_callback,
  99004. void *client_data,
  99005. FLAC__bool is_ogg
  99006. )
  99007. {
  99008. FILE *file;
  99009. FLAC__ASSERT(0 != decoder);
  99010. /*
  99011. * To make sure that our file does not go unclosed after an error, we
  99012. * have to do the same entrance checks here that are later performed
  99013. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99014. */
  99015. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99016. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99017. if(0 == write_callback || 0 == error_callback)
  99018. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99019. file = filename? fopen(filename, "rb") : stdin;
  99020. if(0 == file)
  99021. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99022. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99023. }
  99024. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99025. FLAC__StreamDecoder *decoder,
  99026. const char *filename,
  99027. FLAC__StreamDecoderWriteCallback write_callback,
  99028. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99029. FLAC__StreamDecoderErrorCallback error_callback,
  99030. void *client_data
  99031. )
  99032. {
  99033. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99034. }
  99035. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99036. FLAC__StreamDecoder *decoder,
  99037. const char *filename,
  99038. FLAC__StreamDecoderWriteCallback write_callback,
  99039. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99040. FLAC__StreamDecoderErrorCallback error_callback,
  99041. void *client_data
  99042. )
  99043. {
  99044. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99045. }
  99046. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99047. {
  99048. FLAC__bool md5_failed = false;
  99049. unsigned i;
  99050. FLAC__ASSERT(0 != decoder);
  99051. FLAC__ASSERT(0 != decoder->private_);
  99052. FLAC__ASSERT(0 != decoder->protected_);
  99053. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99054. return true;
  99055. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99056. * always call FLAC__MD5Final()
  99057. */
  99058. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99059. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99060. free(decoder->private_->seek_table.data.seek_table.points);
  99061. decoder->private_->seek_table.data.seek_table.points = 0;
  99062. decoder->private_->has_seek_table = false;
  99063. }
  99064. FLAC__bitreader_free(decoder->private_->input);
  99065. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99066. /* WATCHOUT:
  99067. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99068. * output arrays have a buffer of up to 3 zeroes in front
  99069. * (at negative indices) for alignment purposes; we use 4
  99070. * to keep the data well-aligned.
  99071. */
  99072. if(0 != decoder->private_->output[i]) {
  99073. free(decoder->private_->output[i]-4);
  99074. decoder->private_->output[i] = 0;
  99075. }
  99076. if(0 != decoder->private_->residual_unaligned[i]) {
  99077. free(decoder->private_->residual_unaligned[i]);
  99078. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99079. }
  99080. }
  99081. decoder->private_->output_capacity = 0;
  99082. decoder->private_->output_channels = 0;
  99083. #if FLAC__HAS_OGG
  99084. if(decoder->private_->is_ogg)
  99085. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99086. #endif
  99087. if(0 != decoder->private_->file) {
  99088. if(decoder->private_->file != stdin)
  99089. fclose(decoder->private_->file);
  99090. decoder->private_->file = 0;
  99091. }
  99092. if(decoder->private_->do_md5_checking) {
  99093. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99094. md5_failed = true;
  99095. }
  99096. decoder->private_->is_seeking = false;
  99097. set_defaults_dec(decoder);
  99098. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99099. return !md5_failed;
  99100. }
  99101. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99102. {
  99103. FLAC__ASSERT(0 != decoder);
  99104. FLAC__ASSERT(0 != decoder->private_);
  99105. FLAC__ASSERT(0 != decoder->protected_);
  99106. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99107. return false;
  99108. #if FLAC__HAS_OGG
  99109. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99110. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99111. return true;
  99112. #else
  99113. (void)value;
  99114. return false;
  99115. #endif
  99116. }
  99117. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99118. {
  99119. FLAC__ASSERT(0 != decoder);
  99120. FLAC__ASSERT(0 != decoder->protected_);
  99121. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99122. return false;
  99123. decoder->protected_->md5_checking = value;
  99124. return true;
  99125. }
  99126. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99127. {
  99128. FLAC__ASSERT(0 != decoder);
  99129. FLAC__ASSERT(0 != decoder->private_);
  99130. FLAC__ASSERT(0 != decoder->protected_);
  99131. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99132. /* double protection */
  99133. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99134. return false;
  99135. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99136. return false;
  99137. decoder->private_->metadata_filter[type] = true;
  99138. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99139. decoder->private_->metadata_filter_ids_count = 0;
  99140. return true;
  99141. }
  99142. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99143. {
  99144. FLAC__ASSERT(0 != decoder);
  99145. FLAC__ASSERT(0 != decoder->private_);
  99146. FLAC__ASSERT(0 != decoder->protected_);
  99147. FLAC__ASSERT(0 != id);
  99148. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99149. return false;
  99150. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99151. return true;
  99152. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99153. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99154. 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))) {
  99155. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99156. return false;
  99157. }
  99158. decoder->private_->metadata_filter_ids_capacity *= 2;
  99159. }
  99160. 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));
  99161. decoder->private_->metadata_filter_ids_count++;
  99162. return true;
  99163. }
  99164. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99165. {
  99166. unsigned i;
  99167. FLAC__ASSERT(0 != decoder);
  99168. FLAC__ASSERT(0 != decoder->private_);
  99169. FLAC__ASSERT(0 != decoder->protected_);
  99170. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99171. return false;
  99172. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99173. decoder->private_->metadata_filter[i] = true;
  99174. decoder->private_->metadata_filter_ids_count = 0;
  99175. return true;
  99176. }
  99177. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99178. {
  99179. FLAC__ASSERT(0 != decoder);
  99180. FLAC__ASSERT(0 != decoder->private_);
  99181. FLAC__ASSERT(0 != decoder->protected_);
  99182. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99183. /* double protection */
  99184. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99185. return false;
  99186. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99187. return false;
  99188. decoder->private_->metadata_filter[type] = false;
  99189. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99190. decoder->private_->metadata_filter_ids_count = 0;
  99191. return true;
  99192. }
  99193. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99194. {
  99195. FLAC__ASSERT(0 != decoder);
  99196. FLAC__ASSERT(0 != decoder->private_);
  99197. FLAC__ASSERT(0 != decoder->protected_);
  99198. FLAC__ASSERT(0 != id);
  99199. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99200. return false;
  99201. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99202. return true;
  99203. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99204. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99205. 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))) {
  99206. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99207. return false;
  99208. }
  99209. decoder->private_->metadata_filter_ids_capacity *= 2;
  99210. }
  99211. 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));
  99212. decoder->private_->metadata_filter_ids_count++;
  99213. return true;
  99214. }
  99215. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99216. {
  99217. FLAC__ASSERT(0 != decoder);
  99218. FLAC__ASSERT(0 != decoder->private_);
  99219. FLAC__ASSERT(0 != decoder->protected_);
  99220. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99221. return false;
  99222. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99223. decoder->private_->metadata_filter_ids_count = 0;
  99224. return true;
  99225. }
  99226. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99227. {
  99228. FLAC__ASSERT(0 != decoder);
  99229. FLAC__ASSERT(0 != decoder->protected_);
  99230. return decoder->protected_->state;
  99231. }
  99232. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99233. {
  99234. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99235. }
  99236. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99237. {
  99238. FLAC__ASSERT(0 != decoder);
  99239. FLAC__ASSERT(0 != decoder->protected_);
  99240. return decoder->protected_->md5_checking;
  99241. }
  99242. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  99243. {
  99244. FLAC__ASSERT(0 != decoder);
  99245. FLAC__ASSERT(0 != decoder->protected_);
  99246. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  99247. }
  99248. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  99249. {
  99250. FLAC__ASSERT(0 != decoder);
  99251. FLAC__ASSERT(0 != decoder->protected_);
  99252. return decoder->protected_->channels;
  99253. }
  99254. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  99255. {
  99256. FLAC__ASSERT(0 != decoder);
  99257. FLAC__ASSERT(0 != decoder->protected_);
  99258. return decoder->protected_->channel_assignment;
  99259. }
  99260. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  99261. {
  99262. FLAC__ASSERT(0 != decoder);
  99263. FLAC__ASSERT(0 != decoder->protected_);
  99264. return decoder->protected_->bits_per_sample;
  99265. }
  99266. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  99267. {
  99268. FLAC__ASSERT(0 != decoder);
  99269. FLAC__ASSERT(0 != decoder->protected_);
  99270. return decoder->protected_->sample_rate;
  99271. }
  99272. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  99273. {
  99274. FLAC__ASSERT(0 != decoder);
  99275. FLAC__ASSERT(0 != decoder->protected_);
  99276. return decoder->protected_->blocksize;
  99277. }
  99278. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  99279. {
  99280. FLAC__ASSERT(0 != decoder);
  99281. FLAC__ASSERT(0 != decoder->private_);
  99282. FLAC__ASSERT(0 != position);
  99283. #if FLAC__HAS_OGG
  99284. if(decoder->private_->is_ogg)
  99285. return false;
  99286. #endif
  99287. if(0 == decoder->private_->tell_callback)
  99288. return false;
  99289. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  99290. return false;
  99291. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  99292. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  99293. return false;
  99294. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  99295. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  99296. return true;
  99297. }
  99298. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  99299. {
  99300. FLAC__ASSERT(0 != decoder);
  99301. FLAC__ASSERT(0 != decoder->private_);
  99302. FLAC__ASSERT(0 != decoder->protected_);
  99303. decoder->private_->samples_decoded = 0;
  99304. decoder->private_->do_md5_checking = false;
  99305. #if FLAC__HAS_OGG
  99306. if(decoder->private_->is_ogg)
  99307. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99308. #endif
  99309. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99310. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99311. return false;
  99312. }
  99313. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99314. return true;
  99315. }
  99316. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99317. {
  99318. FLAC__ASSERT(0 != decoder);
  99319. FLAC__ASSERT(0 != decoder->private_);
  99320. FLAC__ASSERT(0 != decoder->protected_);
  99321. if(!FLAC__stream_decoder_flush(decoder)) {
  99322. /* above call sets the state for us */
  99323. return false;
  99324. }
  99325. #if FLAC__HAS_OGG
  99326. /*@@@ could go in !internal_reset_hack block below */
  99327. if(decoder->private_->is_ogg)
  99328. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99329. #endif
  99330. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99331. * (internal_reset_hack) don't try to rewind since we are already at
  99332. * the beginning of the stream and don't want to fail if the input is
  99333. * not seekable.
  99334. */
  99335. if(!decoder->private_->internal_reset_hack) {
  99336. if(decoder->private_->file == stdin)
  99337. return false; /* can't rewind stdin, reset fails */
  99338. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99339. return false; /* seekable and seek fails, reset fails */
  99340. }
  99341. else
  99342. decoder->private_->internal_reset_hack = false;
  99343. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99344. decoder->private_->has_stream_info = false;
  99345. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99346. free(decoder->private_->seek_table.data.seek_table.points);
  99347. decoder->private_->seek_table.data.seek_table.points = 0;
  99348. decoder->private_->has_seek_table = false;
  99349. }
  99350. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99351. /*
  99352. * This goes in reset() and not flush() because according to the spec, a
  99353. * fixed-blocksize stream must stay that way through the whole stream.
  99354. */
  99355. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99356. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99357. * is because md5 checking may be turned on to start and then turned off if
  99358. * a seek occurs. So we init the context here and finalize it in
  99359. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  99360. * properly.
  99361. */
  99362. FLAC__MD5Init(&decoder->private_->md5context);
  99363. decoder->private_->first_frame_offset = 0;
  99364. decoder->private_->unparseable_frame_count = 0;
  99365. return true;
  99366. }
  99367. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  99368. {
  99369. FLAC__bool got_a_frame;
  99370. FLAC__ASSERT(0 != decoder);
  99371. FLAC__ASSERT(0 != decoder->protected_);
  99372. while(1) {
  99373. switch(decoder->protected_->state) {
  99374. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99375. if(!find_metadata_(decoder))
  99376. return false; /* above function sets the status for us */
  99377. break;
  99378. case FLAC__STREAM_DECODER_READ_METADATA:
  99379. if(!read_metadata_(decoder))
  99380. return false; /* above function sets the status for us */
  99381. else
  99382. return true;
  99383. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99384. if(!frame_sync_(decoder))
  99385. return true; /* above function sets the status for us */
  99386. break;
  99387. case FLAC__STREAM_DECODER_READ_FRAME:
  99388. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  99389. return false; /* above function sets the status for us */
  99390. if(got_a_frame)
  99391. return true; /* above function sets the status for us */
  99392. break;
  99393. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99394. case FLAC__STREAM_DECODER_ABORTED:
  99395. return true;
  99396. default:
  99397. FLAC__ASSERT(0);
  99398. return false;
  99399. }
  99400. }
  99401. }
  99402. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  99403. {
  99404. FLAC__ASSERT(0 != decoder);
  99405. FLAC__ASSERT(0 != decoder->protected_);
  99406. while(1) {
  99407. switch(decoder->protected_->state) {
  99408. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99409. if(!find_metadata_(decoder))
  99410. return false; /* above function sets the status for us */
  99411. break;
  99412. case FLAC__STREAM_DECODER_READ_METADATA:
  99413. if(!read_metadata_(decoder))
  99414. return false; /* above function sets the status for us */
  99415. break;
  99416. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99417. case FLAC__STREAM_DECODER_READ_FRAME:
  99418. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99419. case FLAC__STREAM_DECODER_ABORTED:
  99420. return true;
  99421. default:
  99422. FLAC__ASSERT(0);
  99423. return false;
  99424. }
  99425. }
  99426. }
  99427. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  99428. {
  99429. FLAC__bool dummy;
  99430. FLAC__ASSERT(0 != decoder);
  99431. FLAC__ASSERT(0 != decoder->protected_);
  99432. while(1) {
  99433. switch(decoder->protected_->state) {
  99434. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99435. if(!find_metadata_(decoder))
  99436. return false; /* above function sets the status for us */
  99437. break;
  99438. case FLAC__STREAM_DECODER_READ_METADATA:
  99439. if(!read_metadata_(decoder))
  99440. return false; /* above function sets the status for us */
  99441. break;
  99442. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99443. if(!frame_sync_(decoder))
  99444. return true; /* above function sets the status for us */
  99445. break;
  99446. case FLAC__STREAM_DECODER_READ_FRAME:
  99447. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  99448. return false; /* above function sets the status for us */
  99449. break;
  99450. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99451. case FLAC__STREAM_DECODER_ABORTED:
  99452. return true;
  99453. default:
  99454. FLAC__ASSERT(0);
  99455. return false;
  99456. }
  99457. }
  99458. }
  99459. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  99460. {
  99461. FLAC__bool got_a_frame;
  99462. FLAC__ASSERT(0 != decoder);
  99463. FLAC__ASSERT(0 != decoder->protected_);
  99464. while(1) {
  99465. switch(decoder->protected_->state) {
  99466. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99467. case FLAC__STREAM_DECODER_READ_METADATA:
  99468. return false; /* above function sets the status for us */
  99469. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99470. if(!frame_sync_(decoder))
  99471. return true; /* above function sets the status for us */
  99472. break;
  99473. case FLAC__STREAM_DECODER_READ_FRAME:
  99474. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  99475. return false; /* above function sets the status for us */
  99476. if(got_a_frame)
  99477. return true; /* above function sets the status for us */
  99478. break;
  99479. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99480. case FLAC__STREAM_DECODER_ABORTED:
  99481. return true;
  99482. default:
  99483. FLAC__ASSERT(0);
  99484. return false;
  99485. }
  99486. }
  99487. }
  99488. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  99489. {
  99490. FLAC__uint64 length;
  99491. FLAC__ASSERT(0 != decoder);
  99492. if(
  99493. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  99494. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  99495. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  99496. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  99497. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  99498. )
  99499. return false;
  99500. if(0 == decoder->private_->seek_callback)
  99501. return false;
  99502. FLAC__ASSERT(decoder->private_->seek_callback);
  99503. FLAC__ASSERT(decoder->private_->tell_callback);
  99504. FLAC__ASSERT(decoder->private_->length_callback);
  99505. FLAC__ASSERT(decoder->private_->eof_callback);
  99506. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  99507. return false;
  99508. decoder->private_->is_seeking = true;
  99509. /* turn off md5 checking if a seek is attempted */
  99510. decoder->private_->do_md5_checking = false;
  99511. /* 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) */
  99512. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  99513. decoder->private_->is_seeking = false;
  99514. return false;
  99515. }
  99516. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  99517. if(
  99518. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  99519. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  99520. ) {
  99521. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  99522. /* above call sets the state for us */
  99523. decoder->private_->is_seeking = false;
  99524. return false;
  99525. }
  99526. /* check this again in case we didn't know total_samples the first time */
  99527. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  99528. decoder->private_->is_seeking = false;
  99529. return false;
  99530. }
  99531. }
  99532. {
  99533. const FLAC__bool ok =
  99534. #if FLAC__HAS_OGG
  99535. decoder->private_->is_ogg?
  99536. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  99537. #endif
  99538. seek_to_absolute_sample_(decoder, length, sample)
  99539. ;
  99540. decoder->private_->is_seeking = false;
  99541. return ok;
  99542. }
  99543. }
  99544. /***********************************************************************
  99545. *
  99546. * Protected class methods
  99547. *
  99548. ***********************************************************************/
  99549. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  99550. {
  99551. FLAC__ASSERT(0 != decoder);
  99552. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99553. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  99554. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  99555. }
  99556. /***********************************************************************
  99557. *
  99558. * Private class methods
  99559. *
  99560. ***********************************************************************/
  99561. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  99562. {
  99563. #if FLAC__HAS_OGG
  99564. decoder->private_->is_ogg = false;
  99565. #endif
  99566. decoder->private_->read_callback = 0;
  99567. decoder->private_->seek_callback = 0;
  99568. decoder->private_->tell_callback = 0;
  99569. decoder->private_->length_callback = 0;
  99570. decoder->private_->eof_callback = 0;
  99571. decoder->private_->write_callback = 0;
  99572. decoder->private_->metadata_callback = 0;
  99573. decoder->private_->error_callback = 0;
  99574. decoder->private_->client_data = 0;
  99575. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99576. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  99577. decoder->private_->metadata_filter_ids_count = 0;
  99578. decoder->protected_->md5_checking = false;
  99579. #if FLAC__HAS_OGG
  99580. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  99581. #endif
  99582. }
  99583. /*
  99584. * This will forcibly set stdin to binary mode (for OSes that require it)
  99585. */
  99586. FILE *get_binary_stdin_(void)
  99587. {
  99588. /* if something breaks here it is probably due to the presence or
  99589. * absence of an underscore before the identifiers 'setmode',
  99590. * 'fileno', and/or 'O_BINARY'; check your system header files.
  99591. */
  99592. #if defined _MSC_VER || defined __MINGW32__
  99593. _setmode(_fileno(stdin), _O_BINARY);
  99594. #elif defined __CYGWIN__
  99595. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  99596. setmode(_fileno(stdin), _O_BINARY);
  99597. #elif defined __EMX__
  99598. setmode(fileno(stdin), O_BINARY);
  99599. #endif
  99600. return stdin;
  99601. }
  99602. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  99603. {
  99604. unsigned i;
  99605. FLAC__int32 *tmp;
  99606. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  99607. return true;
  99608. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  99609. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99610. if(0 != decoder->private_->output[i]) {
  99611. free(decoder->private_->output[i]-4);
  99612. decoder->private_->output[i] = 0;
  99613. }
  99614. if(0 != decoder->private_->residual_unaligned[i]) {
  99615. free(decoder->private_->residual_unaligned[i]);
  99616. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99617. }
  99618. }
  99619. for(i = 0; i < channels; i++) {
  99620. /* WATCHOUT:
  99621. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99622. * output arrays have a buffer of up to 3 zeroes in front
  99623. * (at negative indices) for alignment purposes; we use 4
  99624. * to keep the data well-aligned.
  99625. */
  99626. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  99627. if(tmp == 0) {
  99628. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99629. return false;
  99630. }
  99631. memset(tmp, 0, sizeof(FLAC__int32)*4);
  99632. decoder->private_->output[i] = tmp + 4;
  99633. /* WATCHOUT:
  99634. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  99635. */
  99636. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  99637. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99638. return false;
  99639. }
  99640. }
  99641. decoder->private_->output_capacity = size;
  99642. decoder->private_->output_channels = channels;
  99643. return true;
  99644. }
  99645. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  99646. {
  99647. size_t i;
  99648. FLAC__ASSERT(0 != decoder);
  99649. FLAC__ASSERT(0 != decoder->private_);
  99650. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  99651. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  99652. return true;
  99653. return false;
  99654. }
  99655. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  99656. {
  99657. FLAC__uint32 x;
  99658. unsigned i, id_;
  99659. FLAC__bool first = true;
  99660. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99661. for(i = id_ = 0; i < 4; ) {
  99662. if(decoder->private_->cached) {
  99663. x = (FLAC__uint32)decoder->private_->lookahead;
  99664. decoder->private_->cached = false;
  99665. }
  99666. else {
  99667. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99668. return false; /* read_callback_ sets the state for us */
  99669. }
  99670. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  99671. first = true;
  99672. i++;
  99673. id_ = 0;
  99674. continue;
  99675. }
  99676. if(x == ID3V2_TAG_[id_]) {
  99677. id_++;
  99678. i = 0;
  99679. if(id_ == 3) {
  99680. if(!skip_id3v2_tag_(decoder))
  99681. return false; /* skip_id3v2_tag_ sets the state for us */
  99682. }
  99683. continue;
  99684. }
  99685. id_ = 0;
  99686. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99687. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  99688. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99689. return false; /* read_callback_ sets the state for us */
  99690. /* 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 */
  99691. /* else we have to check if the second byte is the end of a sync code */
  99692. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99693. decoder->private_->lookahead = (FLAC__byte)x;
  99694. decoder->private_->cached = true;
  99695. }
  99696. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  99697. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  99698. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  99699. return true;
  99700. }
  99701. }
  99702. i = 0;
  99703. if(first) {
  99704. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  99705. first = false;
  99706. }
  99707. }
  99708. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  99709. return true;
  99710. }
  99711. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  99712. {
  99713. FLAC__bool is_last;
  99714. FLAC__uint32 i, x, type, length;
  99715. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99716. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  99717. return false; /* read_callback_ sets the state for us */
  99718. is_last = x? true : false;
  99719. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  99720. return false; /* read_callback_ sets the state for us */
  99721. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  99722. return false; /* read_callback_ sets the state for us */
  99723. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  99724. if(!read_metadata_streaminfo_(decoder, is_last, length))
  99725. return false;
  99726. decoder->private_->has_stream_info = true;
  99727. 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))
  99728. decoder->private_->do_md5_checking = false;
  99729. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  99730. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  99731. }
  99732. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  99733. if(!read_metadata_seektable_(decoder, is_last, length))
  99734. return false;
  99735. decoder->private_->has_seek_table = true;
  99736. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  99737. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  99738. }
  99739. else {
  99740. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  99741. unsigned real_length = length;
  99742. FLAC__StreamMetadata block;
  99743. block.is_last = is_last;
  99744. block.type = (FLAC__MetadataType)type;
  99745. block.length = length;
  99746. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  99747. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  99748. return false; /* read_callback_ sets the state for us */
  99749. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  99750. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  99751. return false;
  99752. }
  99753. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  99754. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  99755. skip_it = !skip_it;
  99756. }
  99757. if(skip_it) {
  99758. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  99759. return false; /* read_callback_ sets the state for us */
  99760. }
  99761. else {
  99762. switch(type) {
  99763. case FLAC__METADATA_TYPE_PADDING:
  99764. /* skip the padding bytes */
  99765. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  99766. return false; /* read_callback_ sets the state for us */
  99767. break;
  99768. case FLAC__METADATA_TYPE_APPLICATION:
  99769. /* remember, we read the ID already */
  99770. if(real_length > 0) {
  99771. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  99772. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99773. return false;
  99774. }
  99775. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  99776. return false; /* read_callback_ sets the state for us */
  99777. }
  99778. else
  99779. block.data.application.data = 0;
  99780. break;
  99781. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  99782. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  99783. return false;
  99784. break;
  99785. case FLAC__METADATA_TYPE_CUESHEET:
  99786. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  99787. return false;
  99788. break;
  99789. case FLAC__METADATA_TYPE_PICTURE:
  99790. if(!read_metadata_picture_(decoder, &block.data.picture))
  99791. return false;
  99792. break;
  99793. case FLAC__METADATA_TYPE_STREAMINFO:
  99794. case FLAC__METADATA_TYPE_SEEKTABLE:
  99795. FLAC__ASSERT(0);
  99796. break;
  99797. default:
  99798. if(real_length > 0) {
  99799. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  99800. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99801. return false;
  99802. }
  99803. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  99804. return false; /* read_callback_ sets the state for us */
  99805. }
  99806. else
  99807. block.data.unknown.data = 0;
  99808. break;
  99809. }
  99810. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  99811. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  99812. /* now we have to free any malloc()ed data in the block */
  99813. switch(type) {
  99814. case FLAC__METADATA_TYPE_PADDING:
  99815. break;
  99816. case FLAC__METADATA_TYPE_APPLICATION:
  99817. if(0 != block.data.application.data)
  99818. free(block.data.application.data);
  99819. break;
  99820. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  99821. if(0 != block.data.vorbis_comment.vendor_string.entry)
  99822. free(block.data.vorbis_comment.vendor_string.entry);
  99823. if(block.data.vorbis_comment.num_comments > 0)
  99824. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  99825. if(0 != block.data.vorbis_comment.comments[i].entry)
  99826. free(block.data.vorbis_comment.comments[i].entry);
  99827. if(0 != block.data.vorbis_comment.comments)
  99828. free(block.data.vorbis_comment.comments);
  99829. break;
  99830. case FLAC__METADATA_TYPE_CUESHEET:
  99831. if(block.data.cue_sheet.num_tracks > 0)
  99832. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  99833. if(0 != block.data.cue_sheet.tracks[i].indices)
  99834. free(block.data.cue_sheet.tracks[i].indices);
  99835. if(0 != block.data.cue_sheet.tracks)
  99836. free(block.data.cue_sheet.tracks);
  99837. break;
  99838. case FLAC__METADATA_TYPE_PICTURE:
  99839. if(0 != block.data.picture.mime_type)
  99840. free(block.data.picture.mime_type);
  99841. if(0 != block.data.picture.description)
  99842. free(block.data.picture.description);
  99843. if(0 != block.data.picture.data)
  99844. free(block.data.picture.data);
  99845. break;
  99846. case FLAC__METADATA_TYPE_STREAMINFO:
  99847. case FLAC__METADATA_TYPE_SEEKTABLE:
  99848. FLAC__ASSERT(0);
  99849. default:
  99850. if(0 != block.data.unknown.data)
  99851. free(block.data.unknown.data);
  99852. break;
  99853. }
  99854. }
  99855. }
  99856. if(is_last) {
  99857. /* if this fails, it's OK, it's just a hint for the seek routine */
  99858. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  99859. decoder->private_->first_frame_offset = 0;
  99860. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99861. }
  99862. return true;
  99863. }
  99864. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  99865. {
  99866. FLAC__uint32 x;
  99867. unsigned bits, used_bits = 0;
  99868. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99869. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  99870. decoder->private_->stream_info.is_last = is_last;
  99871. decoder->private_->stream_info.length = length;
  99872. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  99873. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  99874. return false; /* read_callback_ sets the state for us */
  99875. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  99876. used_bits += bits;
  99877. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  99878. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  99879. return false; /* read_callback_ sets the state for us */
  99880. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  99881. used_bits += bits;
  99882. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  99883. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  99884. return false; /* read_callback_ sets the state for us */
  99885. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  99886. used_bits += bits;
  99887. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  99888. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  99889. return false; /* read_callback_ sets the state for us */
  99890. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  99891. used_bits += bits;
  99892. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  99893. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  99894. return false; /* read_callback_ sets the state for us */
  99895. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  99896. used_bits += bits;
  99897. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  99898. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  99899. return false; /* read_callback_ sets the state for us */
  99900. decoder->private_->stream_info.data.stream_info.channels = x+1;
  99901. used_bits += bits;
  99902. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  99903. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  99904. return false; /* read_callback_ sets the state for us */
  99905. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  99906. used_bits += bits;
  99907. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  99908. 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))
  99909. return false; /* read_callback_ sets the state for us */
  99910. used_bits += bits;
  99911. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  99912. return false; /* read_callback_ sets the state for us */
  99913. used_bits += 16*8;
  99914. /* skip the rest of the block */
  99915. FLAC__ASSERT(used_bits % 8 == 0);
  99916. length -= (used_bits / 8);
  99917. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  99918. return false; /* read_callback_ sets the state for us */
  99919. return true;
  99920. }
  99921. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  99922. {
  99923. FLAC__uint32 i, x;
  99924. FLAC__uint64 xx;
  99925. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99926. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  99927. decoder->private_->seek_table.is_last = is_last;
  99928. decoder->private_->seek_table.length = length;
  99929. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  99930. /* use realloc since we may pass through here several times (e.g. after seeking) */
  99931. 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)))) {
  99932. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99933. return false;
  99934. }
  99935. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  99936. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  99937. return false; /* read_callback_ sets the state for us */
  99938. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  99939. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  99940. return false; /* read_callback_ sets the state for us */
  99941. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  99942. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  99943. return false; /* read_callback_ sets the state for us */
  99944. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  99945. }
  99946. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  99947. /* if there is a partial point left, skip over it */
  99948. if(length > 0) {
  99949. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  99950. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  99951. return false; /* read_callback_ sets the state for us */
  99952. }
  99953. return true;
  99954. }
  99955. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  99956. {
  99957. FLAC__uint32 i;
  99958. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99959. /* read vendor string */
  99960. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  99961. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  99962. return false; /* read_callback_ sets the state for us */
  99963. if(obj->vendor_string.length > 0) {
  99964. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  99965. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99966. return false;
  99967. }
  99968. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  99969. return false; /* read_callback_ sets the state for us */
  99970. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  99971. }
  99972. else
  99973. obj->vendor_string.entry = 0;
  99974. /* read num comments */
  99975. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  99976. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  99977. return false; /* read_callback_ sets the state for us */
  99978. /* read comments */
  99979. if(obj->num_comments > 0) {
  99980. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  99981. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99982. return false;
  99983. }
  99984. for(i = 0; i < obj->num_comments; i++) {
  99985. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  99986. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  99987. return false; /* read_callback_ sets the state for us */
  99988. if(obj->comments[i].length > 0) {
  99989. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  99990. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99991. return false;
  99992. }
  99993. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  99994. return false; /* read_callback_ sets the state for us */
  99995. obj->comments[i].entry[obj->comments[i].length] = '\0';
  99996. }
  99997. else
  99998. obj->comments[i].entry = 0;
  99999. }
  100000. }
  100001. else {
  100002. obj->comments = 0;
  100003. }
  100004. return true;
  100005. }
  100006. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100007. {
  100008. FLAC__uint32 i, j, x;
  100009. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100010. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100011. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100012. 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))
  100013. return false; /* read_callback_ sets the state for us */
  100014. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100015. return false; /* read_callback_ sets the state for us */
  100016. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100017. return false; /* read_callback_ sets the state for us */
  100018. obj->is_cd = x? true : false;
  100019. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100020. return false; /* read_callback_ sets the state for us */
  100021. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100022. return false; /* read_callback_ sets the state for us */
  100023. obj->num_tracks = x;
  100024. if(obj->num_tracks > 0) {
  100025. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100026. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100027. return false;
  100028. }
  100029. for(i = 0; i < obj->num_tracks; i++) {
  100030. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100031. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100032. return false; /* read_callback_ sets the state for us */
  100033. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100034. return false; /* read_callback_ sets the state for us */
  100035. track->number = (FLAC__byte)x;
  100036. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100037. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100038. return false; /* read_callback_ sets the state for us */
  100039. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100040. return false; /* read_callback_ sets the state for us */
  100041. track->type = x;
  100042. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100043. return false; /* read_callback_ sets the state for us */
  100044. track->pre_emphasis = x;
  100045. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100046. return false; /* read_callback_ sets the state for us */
  100047. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100048. return false; /* read_callback_ sets the state for us */
  100049. track->num_indices = (FLAC__byte)x;
  100050. if(track->num_indices > 0) {
  100051. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100052. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100053. return false;
  100054. }
  100055. for(j = 0; j < track->num_indices; j++) {
  100056. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100057. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100058. return false; /* read_callback_ sets the state for us */
  100059. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100060. return false; /* read_callback_ sets the state for us */
  100061. index->number = (FLAC__byte)x;
  100062. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100063. return false; /* read_callback_ sets the state for us */
  100064. }
  100065. }
  100066. }
  100067. }
  100068. return true;
  100069. }
  100070. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100071. {
  100072. FLAC__uint32 x;
  100073. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100074. /* read type */
  100075. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100076. return false; /* read_callback_ sets the state for us */
  100077. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100078. /* read MIME type */
  100079. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100080. return false; /* read_callback_ sets the state for us */
  100081. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100082. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100083. return false;
  100084. }
  100085. if(x > 0) {
  100086. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100087. return false; /* read_callback_ sets the state for us */
  100088. }
  100089. obj->mime_type[x] = '\0';
  100090. /* read description */
  100091. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100092. return false; /* read_callback_ sets the state for us */
  100093. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100094. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100095. return false;
  100096. }
  100097. if(x > 0) {
  100098. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100099. return false; /* read_callback_ sets the state for us */
  100100. }
  100101. obj->description[x] = '\0';
  100102. /* read width */
  100103. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100104. return false; /* read_callback_ sets the state for us */
  100105. /* read height */
  100106. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100107. return false; /* read_callback_ sets the state for us */
  100108. /* read depth */
  100109. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100110. return false; /* read_callback_ sets the state for us */
  100111. /* read colors */
  100112. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100113. return false; /* read_callback_ sets the state for us */
  100114. /* read data */
  100115. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100116. return false; /* read_callback_ sets the state for us */
  100117. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100118. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100119. return false;
  100120. }
  100121. if(obj->data_length > 0) {
  100122. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100123. return false; /* read_callback_ sets the state for us */
  100124. }
  100125. return true;
  100126. }
  100127. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100128. {
  100129. FLAC__uint32 x;
  100130. unsigned i, skip;
  100131. /* skip the version and flags bytes */
  100132. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100133. return false; /* read_callback_ sets the state for us */
  100134. /* get the size (in bytes) to skip */
  100135. skip = 0;
  100136. for(i = 0; i < 4; i++) {
  100137. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100138. return false; /* read_callback_ sets the state for us */
  100139. skip <<= 7;
  100140. skip |= (x & 0x7f);
  100141. }
  100142. /* skip the rest of the tag */
  100143. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100144. return false; /* read_callback_ sets the state for us */
  100145. return true;
  100146. }
  100147. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100148. {
  100149. FLAC__uint32 x;
  100150. FLAC__bool first = true;
  100151. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100152. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100153. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100154. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100155. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100156. return true;
  100157. }
  100158. }
  100159. /* make sure we're byte aligned */
  100160. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100161. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100162. return false; /* read_callback_ sets the state for us */
  100163. }
  100164. while(1) {
  100165. if(decoder->private_->cached) {
  100166. x = (FLAC__uint32)decoder->private_->lookahead;
  100167. decoder->private_->cached = false;
  100168. }
  100169. else {
  100170. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100171. return false; /* read_callback_ sets the state for us */
  100172. }
  100173. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100174. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100175. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100176. return false; /* read_callback_ sets the state for us */
  100177. /* 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 */
  100178. /* else we have to check if the second byte is the end of a sync code */
  100179. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100180. decoder->private_->lookahead = (FLAC__byte)x;
  100181. decoder->private_->cached = true;
  100182. }
  100183. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100184. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100185. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100186. return true;
  100187. }
  100188. }
  100189. if(first) {
  100190. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100191. first = false;
  100192. }
  100193. }
  100194. return true;
  100195. }
  100196. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100197. {
  100198. unsigned channel;
  100199. unsigned i;
  100200. FLAC__int32 mid, side;
  100201. unsigned frame_crc; /* the one we calculate from the input stream */
  100202. FLAC__uint32 x;
  100203. *got_a_frame = false;
  100204. /* init the CRC */
  100205. frame_crc = 0;
  100206. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100207. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100208. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100209. if(!read_frame_header_(decoder))
  100210. return false;
  100211. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100212. return true;
  100213. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100214. return false;
  100215. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100216. /*
  100217. * first figure the correct bits-per-sample of the subframe
  100218. */
  100219. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100220. switch(decoder->private_->frame.header.channel_assignment) {
  100221. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100222. /* no adjustment needed */
  100223. break;
  100224. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100225. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100226. if(channel == 1)
  100227. bps++;
  100228. break;
  100229. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100230. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100231. if(channel == 0)
  100232. bps++;
  100233. break;
  100234. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100235. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100236. if(channel == 1)
  100237. bps++;
  100238. break;
  100239. default:
  100240. FLAC__ASSERT(0);
  100241. }
  100242. /*
  100243. * now read it
  100244. */
  100245. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  100246. return false;
  100247. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100248. return true;
  100249. }
  100250. if(!read_zero_padding_(decoder))
  100251. return false;
  100252. 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) */
  100253. return true;
  100254. /*
  100255. * Read the frame CRC-16 from the footer and check
  100256. */
  100257. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  100258. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  100259. return false; /* read_callback_ sets the state for us */
  100260. if(frame_crc == x) {
  100261. if(do_full_decode) {
  100262. /* Undo any special channel coding */
  100263. switch(decoder->private_->frame.header.channel_assignment) {
  100264. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100265. /* do nothing */
  100266. break;
  100267. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100268. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100269. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100270. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  100271. break;
  100272. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100273. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100274. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100275. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  100276. break;
  100277. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100278. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100279. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100280. #if 1
  100281. mid = decoder->private_->output[0][i];
  100282. side = decoder->private_->output[1][i];
  100283. mid <<= 1;
  100284. mid |= (side & 1); /* i.e. if 'side' is odd... */
  100285. decoder->private_->output[0][i] = (mid + side) >> 1;
  100286. decoder->private_->output[1][i] = (mid - side) >> 1;
  100287. #else
  100288. /* OPT: without 'side' temp variable */
  100289. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  100290. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  100291. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  100292. #endif
  100293. }
  100294. break;
  100295. default:
  100296. FLAC__ASSERT(0);
  100297. break;
  100298. }
  100299. }
  100300. }
  100301. else {
  100302. /* Bad frame, emit error and zero the output signal */
  100303. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  100304. if(do_full_decode) {
  100305. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100306. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100307. }
  100308. }
  100309. }
  100310. *got_a_frame = true;
  100311. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100312. if(decoder->private_->next_fixed_block_size)
  100313. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100314. /* put the latest values into the public section of the decoder instance */
  100315. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100316. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100317. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100318. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100319. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100320. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100321. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100322. /* write it */
  100323. if(do_full_decode) {
  100324. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100325. return false;
  100326. }
  100327. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100328. return true;
  100329. }
  100330. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100331. {
  100332. FLAC__uint32 x;
  100333. FLAC__uint64 xx;
  100334. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100335. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100336. unsigned raw_header_len;
  100337. FLAC__bool is_unparseable = false;
  100338. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100339. /* init the raw header with the saved bits from synchronization */
  100340. raw_header[0] = decoder->private_->header_warmup[0];
  100341. raw_header[1] = decoder->private_->header_warmup[1];
  100342. raw_header_len = 2;
  100343. /* check to make sure that reserved bit is 0 */
  100344. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100345. is_unparseable = true;
  100346. /*
  100347. * Note that along the way as we read the header, we look for a sync
  100348. * code inside. If we find one it would indicate that our original
  100349. * sync was bad since there cannot be a sync code in a valid header.
  100350. *
  100351. * Three kinds of things can go wrong when reading the frame header:
  100352. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100353. * If we don't find a sync code, it can end up looking like we read
  100354. * a valid but unparseable header, until getting to the frame header
  100355. * CRC. Even then we could get a false positive on the CRC.
  100356. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100357. * future encoder).
  100358. * 3) We may be on a damaged frame which appears valid but unparseable.
  100359. *
  100360. * For all these reasons, we try and read a complete frame header as
  100361. * long as it seems valid, even if unparseable, up until the frame
  100362. * header CRC.
  100363. */
  100364. /*
  100365. * read in the raw header as bytes so we can CRC it, and parse it on the way
  100366. */
  100367. for(i = 0; i < 2; i++) {
  100368. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100369. return false; /* read_callback_ sets the state for us */
  100370. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100371. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  100372. decoder->private_->lookahead = (FLAC__byte)x;
  100373. decoder->private_->cached = true;
  100374. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100375. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100376. return true;
  100377. }
  100378. raw_header[raw_header_len++] = (FLAC__byte)x;
  100379. }
  100380. switch(x = raw_header[2] >> 4) {
  100381. case 0:
  100382. is_unparseable = true;
  100383. break;
  100384. case 1:
  100385. decoder->private_->frame.header.blocksize = 192;
  100386. break;
  100387. case 2:
  100388. case 3:
  100389. case 4:
  100390. case 5:
  100391. decoder->private_->frame.header.blocksize = 576 << (x-2);
  100392. break;
  100393. case 6:
  100394. case 7:
  100395. blocksize_hint = x;
  100396. break;
  100397. case 8:
  100398. case 9:
  100399. case 10:
  100400. case 11:
  100401. case 12:
  100402. case 13:
  100403. case 14:
  100404. case 15:
  100405. decoder->private_->frame.header.blocksize = 256 << (x-8);
  100406. break;
  100407. default:
  100408. FLAC__ASSERT(0);
  100409. break;
  100410. }
  100411. switch(x = raw_header[2] & 0x0f) {
  100412. case 0:
  100413. if(decoder->private_->has_stream_info)
  100414. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  100415. else
  100416. is_unparseable = true;
  100417. break;
  100418. case 1:
  100419. decoder->private_->frame.header.sample_rate = 88200;
  100420. break;
  100421. case 2:
  100422. decoder->private_->frame.header.sample_rate = 176400;
  100423. break;
  100424. case 3:
  100425. decoder->private_->frame.header.sample_rate = 192000;
  100426. break;
  100427. case 4:
  100428. decoder->private_->frame.header.sample_rate = 8000;
  100429. break;
  100430. case 5:
  100431. decoder->private_->frame.header.sample_rate = 16000;
  100432. break;
  100433. case 6:
  100434. decoder->private_->frame.header.sample_rate = 22050;
  100435. break;
  100436. case 7:
  100437. decoder->private_->frame.header.sample_rate = 24000;
  100438. break;
  100439. case 8:
  100440. decoder->private_->frame.header.sample_rate = 32000;
  100441. break;
  100442. case 9:
  100443. decoder->private_->frame.header.sample_rate = 44100;
  100444. break;
  100445. case 10:
  100446. decoder->private_->frame.header.sample_rate = 48000;
  100447. break;
  100448. case 11:
  100449. decoder->private_->frame.header.sample_rate = 96000;
  100450. break;
  100451. case 12:
  100452. case 13:
  100453. case 14:
  100454. sample_rate_hint = x;
  100455. break;
  100456. case 15:
  100457. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100458. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100459. return true;
  100460. default:
  100461. FLAC__ASSERT(0);
  100462. }
  100463. x = (unsigned)(raw_header[3] >> 4);
  100464. if(x & 8) {
  100465. decoder->private_->frame.header.channels = 2;
  100466. switch(x & 7) {
  100467. case 0:
  100468. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  100469. break;
  100470. case 1:
  100471. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  100472. break;
  100473. case 2:
  100474. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  100475. break;
  100476. default:
  100477. is_unparseable = true;
  100478. break;
  100479. }
  100480. }
  100481. else {
  100482. decoder->private_->frame.header.channels = (unsigned)x + 1;
  100483. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  100484. }
  100485. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  100486. case 0:
  100487. if(decoder->private_->has_stream_info)
  100488. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100489. else
  100490. is_unparseable = true;
  100491. break;
  100492. case 1:
  100493. decoder->private_->frame.header.bits_per_sample = 8;
  100494. break;
  100495. case 2:
  100496. decoder->private_->frame.header.bits_per_sample = 12;
  100497. break;
  100498. case 4:
  100499. decoder->private_->frame.header.bits_per_sample = 16;
  100500. break;
  100501. case 5:
  100502. decoder->private_->frame.header.bits_per_sample = 20;
  100503. break;
  100504. case 6:
  100505. decoder->private_->frame.header.bits_per_sample = 24;
  100506. break;
  100507. case 3:
  100508. case 7:
  100509. is_unparseable = true;
  100510. break;
  100511. default:
  100512. FLAC__ASSERT(0);
  100513. break;
  100514. }
  100515. /* check to make sure that reserved bit is 0 */
  100516. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  100517. is_unparseable = true;
  100518. /* read the frame's starting sample number (or frame number as the case may be) */
  100519. if(
  100520. raw_header[1] & 0x01 ||
  100521. /*@@@ 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 */
  100522. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  100523. ) { /* variable blocksize */
  100524. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  100525. return false; /* read_callback_ sets the state for us */
  100526. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  100527. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100528. decoder->private_->cached = true;
  100529. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100530. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100531. return true;
  100532. }
  100533. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100534. decoder->private_->frame.header.number.sample_number = xx;
  100535. }
  100536. else { /* fixed blocksize */
  100537. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  100538. return false; /* read_callback_ sets the state for us */
  100539. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  100540. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100541. decoder->private_->cached = true;
  100542. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100543. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100544. return true;
  100545. }
  100546. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  100547. decoder->private_->frame.header.number.frame_number = x;
  100548. }
  100549. if(blocksize_hint) {
  100550. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100551. return false; /* read_callback_ sets the state for us */
  100552. raw_header[raw_header_len++] = (FLAC__byte)x;
  100553. if(blocksize_hint == 7) {
  100554. FLAC__uint32 _x;
  100555. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100556. return false; /* read_callback_ sets the state for us */
  100557. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100558. x = (x << 8) | _x;
  100559. }
  100560. decoder->private_->frame.header.blocksize = x+1;
  100561. }
  100562. if(sample_rate_hint) {
  100563. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100564. return false; /* read_callback_ sets the state for us */
  100565. raw_header[raw_header_len++] = (FLAC__byte)x;
  100566. if(sample_rate_hint != 12) {
  100567. FLAC__uint32 _x;
  100568. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100569. return false; /* read_callback_ sets the state for us */
  100570. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100571. x = (x << 8) | _x;
  100572. }
  100573. if(sample_rate_hint == 12)
  100574. decoder->private_->frame.header.sample_rate = x*1000;
  100575. else if(sample_rate_hint == 13)
  100576. decoder->private_->frame.header.sample_rate = x;
  100577. else
  100578. decoder->private_->frame.header.sample_rate = x*10;
  100579. }
  100580. /* read the CRC-8 byte */
  100581. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100582. return false; /* read_callback_ sets the state for us */
  100583. crc8 = (FLAC__byte)x;
  100584. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  100585. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100586. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100587. return true;
  100588. }
  100589. /* calculate the sample number from the frame number if needed */
  100590. decoder->private_->next_fixed_block_size = 0;
  100591. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  100592. x = decoder->private_->frame.header.number.frame_number;
  100593. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100594. if(decoder->private_->fixed_block_size)
  100595. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  100596. else if(decoder->private_->has_stream_info) {
  100597. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  100598. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  100599. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  100600. }
  100601. else
  100602. is_unparseable = true;
  100603. }
  100604. else if(x == 0) {
  100605. decoder->private_->frame.header.number.sample_number = 0;
  100606. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  100607. }
  100608. else {
  100609. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  100610. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  100611. }
  100612. }
  100613. if(is_unparseable) {
  100614. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100615. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100616. return true;
  100617. }
  100618. return true;
  100619. }
  100620. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100621. {
  100622. FLAC__uint32 x;
  100623. FLAC__bool wasted_bits;
  100624. unsigned i;
  100625. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  100626. return false; /* read_callback_ sets the state for us */
  100627. wasted_bits = (x & 1);
  100628. x &= 0xfe;
  100629. if(wasted_bits) {
  100630. unsigned u;
  100631. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  100632. return false; /* read_callback_ sets the state for us */
  100633. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  100634. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  100635. }
  100636. else
  100637. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  100638. /*
  100639. * Lots of magic numbers here
  100640. */
  100641. if(x & 0x80) {
  100642. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100643. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100644. return true;
  100645. }
  100646. else if(x == 0) {
  100647. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  100648. return false;
  100649. }
  100650. else if(x == 2) {
  100651. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  100652. return false;
  100653. }
  100654. else if(x < 16) {
  100655. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100656. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100657. return true;
  100658. }
  100659. else if(x <= 24) {
  100660. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  100661. return false;
  100662. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100663. return true;
  100664. }
  100665. else if(x < 64) {
  100666. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100667. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100668. return true;
  100669. }
  100670. else {
  100671. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  100672. return false;
  100673. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100674. return true;
  100675. }
  100676. if(wasted_bits && do_full_decode) {
  100677. x = decoder->private_->frame.subframes[channel].wasted_bits;
  100678. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100679. decoder->private_->output[channel][i] <<= x;
  100680. }
  100681. return true;
  100682. }
  100683. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100684. {
  100685. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  100686. FLAC__int32 x;
  100687. unsigned i;
  100688. FLAC__int32 *output = decoder->private_->output[channel];
  100689. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  100690. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  100691. return false; /* read_callback_ sets the state for us */
  100692. subframe->value = x;
  100693. /* decode the subframe */
  100694. if(do_full_decode) {
  100695. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100696. output[i] = x;
  100697. }
  100698. return true;
  100699. }
  100700. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100701. {
  100702. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  100703. FLAC__int32 i32;
  100704. FLAC__uint32 u32;
  100705. unsigned u;
  100706. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  100707. subframe->residual = decoder->private_->residual[channel];
  100708. subframe->order = order;
  100709. /* read warm-up samples */
  100710. for(u = 0; u < order; u++) {
  100711. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100712. return false; /* read_callback_ sets the state for us */
  100713. subframe->warmup[u] = i32;
  100714. }
  100715. /* read entropy coding method info */
  100716. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100717. return false; /* read_callback_ sets the state for us */
  100718. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  100719. switch(subframe->entropy_coding_method.type) {
  100720. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100721. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100722. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100723. return false; /* read_callback_ sets the state for us */
  100724. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  100725. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  100726. break;
  100727. default:
  100728. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100729. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100730. return true;
  100731. }
  100732. /* read residual */
  100733. switch(subframe->entropy_coding_method.type) {
  100734. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100735. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100736. 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))
  100737. return false;
  100738. break;
  100739. default:
  100740. FLAC__ASSERT(0);
  100741. }
  100742. /* decode the subframe */
  100743. if(do_full_decode) {
  100744. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  100745. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  100746. }
  100747. return true;
  100748. }
  100749. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100750. {
  100751. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  100752. FLAC__int32 i32;
  100753. FLAC__uint32 u32;
  100754. unsigned u;
  100755. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  100756. subframe->residual = decoder->private_->residual[channel];
  100757. subframe->order = order;
  100758. /* read warm-up samples */
  100759. for(u = 0; u < order; u++) {
  100760. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100761. return false; /* read_callback_ sets the state for us */
  100762. subframe->warmup[u] = i32;
  100763. }
  100764. /* read qlp coeff precision */
  100765. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  100766. return false; /* read_callback_ sets the state for us */
  100767. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  100768. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100769. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100770. return true;
  100771. }
  100772. subframe->qlp_coeff_precision = u32+1;
  100773. /* read qlp shift */
  100774. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  100775. return false; /* read_callback_ sets the state for us */
  100776. subframe->quantization_level = i32;
  100777. /* read quantized lp coefficiencts */
  100778. for(u = 0; u < order; u++) {
  100779. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  100780. return false; /* read_callback_ sets the state for us */
  100781. subframe->qlp_coeff[u] = i32;
  100782. }
  100783. /* read entropy coding method info */
  100784. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100785. return false; /* read_callback_ sets the state for us */
  100786. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  100787. switch(subframe->entropy_coding_method.type) {
  100788. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100789. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100790. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100791. return false; /* read_callback_ sets the state for us */
  100792. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  100793. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  100794. break;
  100795. default:
  100796. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100797. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100798. return true;
  100799. }
  100800. /* read residual */
  100801. switch(subframe->entropy_coding_method.type) {
  100802. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100803. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100804. 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))
  100805. return false;
  100806. break;
  100807. default:
  100808. FLAC__ASSERT(0);
  100809. }
  100810. /* decode the subframe */
  100811. if(do_full_decode) {
  100812. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  100813. /*@@@@@@ technically not pessimistic enough, should be more like
  100814. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  100815. */
  100816. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  100817. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  100818. if(order <= 8)
  100819. 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);
  100820. else
  100821. 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);
  100822. }
  100823. else
  100824. 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);
  100825. else
  100826. 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);
  100827. }
  100828. return true;
  100829. }
  100830. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100831. {
  100832. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  100833. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  100834. unsigned i;
  100835. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  100836. subframe->data = residual;
  100837. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100838. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  100839. return false; /* read_callback_ sets the state for us */
  100840. residual[i] = x;
  100841. }
  100842. /* decode the subframe */
  100843. if(do_full_decode)
  100844. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100845. return true;
  100846. }
  100847. 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)
  100848. {
  100849. FLAC__uint32 rice_parameter;
  100850. int i;
  100851. unsigned partition, sample, u;
  100852. const unsigned partitions = 1u << partition_order;
  100853. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  100854. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  100855. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  100856. /* sanity checks */
  100857. if(partition_order == 0) {
  100858. if(decoder->private_->frame.header.blocksize < predictor_order) {
  100859. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100860. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100861. return true;
  100862. }
  100863. }
  100864. else {
  100865. if(partition_samples < predictor_order) {
  100866. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100867. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100868. return true;
  100869. }
  100870. }
  100871. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  100872. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100873. return false;
  100874. }
  100875. sample = 0;
  100876. for(partition = 0; partition < partitions; partition++) {
  100877. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  100878. return false; /* read_callback_ sets the state for us */
  100879. partitioned_rice_contents->parameters[partition] = rice_parameter;
  100880. if(rice_parameter < pesc) {
  100881. partitioned_rice_contents->raw_bits[partition] = 0;
  100882. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  100883. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  100884. return false; /* read_callback_ sets the state for us */
  100885. sample += u;
  100886. }
  100887. else {
  100888. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  100889. return false; /* read_callback_ sets the state for us */
  100890. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  100891. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  100892. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  100893. return false; /* read_callback_ sets the state for us */
  100894. residual[sample] = i;
  100895. }
  100896. }
  100897. }
  100898. return true;
  100899. }
  100900. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  100901. {
  100902. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100903. FLAC__uint32 zero = 0;
  100904. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100905. return false; /* read_callback_ sets the state for us */
  100906. if(zero != 0) {
  100907. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100908. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100909. }
  100910. }
  100911. return true;
  100912. }
  100913. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  100914. {
  100915. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  100916. if(
  100917. #if FLAC__HAS_OGG
  100918. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  100919. !decoder->private_->is_ogg &&
  100920. #endif
  100921. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  100922. ) {
  100923. *bytes = 0;
  100924. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100925. return false;
  100926. }
  100927. else if(*bytes > 0) {
  100928. /* While seeking, it is possible for our seek to land in the
  100929. * middle of audio data that looks exactly like a frame header
  100930. * from a future version of an encoder. When that happens, our
  100931. * error callback will get an
  100932. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  100933. * unparseable_frame_count. But there is a remote possibility
  100934. * that it is properly synced at such a "future-codec frame",
  100935. * so to make sure, we wait to see many "unparseable" errors in
  100936. * a row before bailing out.
  100937. */
  100938. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  100939. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100940. return false;
  100941. }
  100942. else {
  100943. const FLAC__StreamDecoderReadStatus status =
  100944. #if FLAC__HAS_OGG
  100945. decoder->private_->is_ogg?
  100946. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  100947. #endif
  100948. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  100949. ;
  100950. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  100951. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100952. return false;
  100953. }
  100954. else if(*bytes == 0) {
  100955. if(
  100956. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  100957. (
  100958. #if FLAC__HAS_OGG
  100959. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  100960. !decoder->private_->is_ogg &&
  100961. #endif
  100962. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  100963. )
  100964. ) {
  100965. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100966. return false;
  100967. }
  100968. else
  100969. return true;
  100970. }
  100971. else
  100972. return true;
  100973. }
  100974. }
  100975. else {
  100976. /* abort to avoid a deadlock */
  100977. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100978. return false;
  100979. }
  100980. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  100981. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  100982. * and at the same time hit the end of the stream (for example, seeking
  100983. * to a point that is after the beginning of the last Ogg page). There
  100984. * is no way to report an Ogg sync loss through the callbacks (see note
  100985. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  100986. * So to keep the decoder from stopping at this point we gate the call
  100987. * to the eof_callback and let the Ogg decoder aspect set the
  100988. * end-of-stream state when it is needed.
  100989. */
  100990. }
  100991. #if FLAC__HAS_OGG
  100992. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  100993. {
  100994. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  100995. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  100996. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  100997. /* we don't really have a way to handle lost sync via read
  100998. * callback so we'll let it pass and let the underlying
  100999. * FLAC decoder catch the error
  101000. */
  101001. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101002. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101003. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101004. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101005. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101006. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101007. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101008. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101009. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101010. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101011. default:
  101012. FLAC__ASSERT(0);
  101013. /* double protection */
  101014. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101015. }
  101016. }
  101017. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101018. {
  101019. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101020. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101021. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101022. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101023. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101024. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101025. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101026. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101027. default:
  101028. /* double protection: */
  101029. FLAC__ASSERT(0);
  101030. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101031. }
  101032. }
  101033. #endif
  101034. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101035. {
  101036. if(decoder->private_->is_seeking) {
  101037. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101038. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101039. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101040. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101041. #if FLAC__HAS_OGG
  101042. decoder->private_->got_a_frame = true;
  101043. #endif
  101044. decoder->private_->last_frame = *frame; /* save the frame */
  101045. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101046. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101047. /* kick out of seek mode */
  101048. decoder->private_->is_seeking = false;
  101049. /* shift out the samples before target_sample */
  101050. if(delta > 0) {
  101051. unsigned channel;
  101052. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101053. for(channel = 0; channel < frame->header.channels; channel++)
  101054. newbuffer[channel] = buffer[channel] + delta;
  101055. decoder->private_->last_frame.header.blocksize -= delta;
  101056. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101057. /* write the relevant samples */
  101058. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101059. }
  101060. else {
  101061. /* write the relevant samples */
  101062. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101063. }
  101064. }
  101065. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101066. }
  101067. /*
  101068. * If we never got STREAMINFO, turn off MD5 checking to save
  101069. * cycles since we don't have a sum to compare to anyway
  101070. */
  101071. if(!decoder->private_->has_stream_info)
  101072. decoder->private_->do_md5_checking = false;
  101073. if(decoder->private_->do_md5_checking) {
  101074. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101075. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101076. }
  101077. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101078. }
  101079. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101080. {
  101081. if(!decoder->private_->is_seeking)
  101082. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101083. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101084. decoder->private_->unparseable_frame_count++;
  101085. }
  101086. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101087. {
  101088. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101089. FLAC__int64 pos = -1;
  101090. int i;
  101091. unsigned approx_bytes_per_frame;
  101092. FLAC__bool first_seek = true;
  101093. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101094. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101095. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101096. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101097. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101098. /* take these from the current frame in case they've changed mid-stream */
  101099. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101100. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101101. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101102. /* use values from stream info if we didn't decode a frame */
  101103. if(channels == 0)
  101104. channels = decoder->private_->stream_info.data.stream_info.channels;
  101105. if(bps == 0)
  101106. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101107. /* we are just guessing here */
  101108. if(max_framesize > 0)
  101109. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101110. /*
  101111. * Check if it's a known fixed-blocksize stream. Note that though
  101112. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101113. * never get a STREAMINFO block when decoding so the value of
  101114. * min_blocksize might be zero.
  101115. */
  101116. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101117. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101118. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101119. }
  101120. else
  101121. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101122. /*
  101123. * First, we set an upper and lower bound on where in the
  101124. * stream we will search. For now we assume the worst case
  101125. * scenario, which is our best guess at the beginning of
  101126. * the first frame and end of the stream.
  101127. */
  101128. lower_bound = first_frame_offset;
  101129. lower_bound_sample = 0;
  101130. upper_bound = stream_length;
  101131. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101132. /*
  101133. * Now we refine the bounds if we have a seektable with
  101134. * suitable points. Note that according to the spec they
  101135. * must be ordered by ascending sample number.
  101136. *
  101137. * Note: to protect against invalid seek tables we will ignore points
  101138. * that have frame_samples==0 or sample_number>=total_samples
  101139. */
  101140. if(seek_table) {
  101141. FLAC__uint64 new_lower_bound = lower_bound;
  101142. FLAC__uint64 new_upper_bound = upper_bound;
  101143. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101144. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101145. /* find the closest seek point <= target_sample, if it exists */
  101146. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101147. if(
  101148. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101149. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101150. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101151. seek_table->points[i].sample_number <= target_sample
  101152. )
  101153. break;
  101154. }
  101155. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101156. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101157. new_lower_bound_sample = seek_table->points[i].sample_number;
  101158. }
  101159. /* find the closest seek point > target_sample, if it exists */
  101160. for(i = 0; i < (int)seek_table->num_points; i++) {
  101161. if(
  101162. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101163. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101164. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101165. seek_table->points[i].sample_number > target_sample
  101166. )
  101167. break;
  101168. }
  101169. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101170. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101171. new_upper_bound_sample = seek_table->points[i].sample_number;
  101172. }
  101173. /* final protection against unsorted seek tables; keep original values if bogus */
  101174. if(new_upper_bound >= new_lower_bound) {
  101175. lower_bound = new_lower_bound;
  101176. upper_bound = new_upper_bound;
  101177. lower_bound_sample = new_lower_bound_sample;
  101178. upper_bound_sample = new_upper_bound_sample;
  101179. }
  101180. }
  101181. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101182. /* there are 2 insidious ways that the following equality occurs, which
  101183. * we need to fix:
  101184. * 1) total_samples is 0 (unknown) and target_sample is 0
  101185. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101186. * exactly equal to the last seek point in the seek table; this
  101187. * means there is no seek point above it, and upper_bound_samples
  101188. * remains equal to the estimate (of target_samples) we made above
  101189. * in either case it does not hurt to move upper_bound_sample up by 1
  101190. */
  101191. if(upper_bound_sample == lower_bound_sample)
  101192. upper_bound_sample++;
  101193. decoder->private_->target_sample = target_sample;
  101194. while(1) {
  101195. /* check if the bounds are still ok */
  101196. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101197. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101198. return false;
  101199. }
  101200. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101201. #if defined _MSC_VER || defined __MINGW32__
  101202. /* with VC++ you have to spoon feed it the casting */
  101203. 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;
  101204. #else
  101205. 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;
  101206. #endif
  101207. #else
  101208. /* a little less accurate: */
  101209. if(upper_bound - lower_bound < 0xffffffff)
  101210. 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;
  101211. else /* @@@ WATCHOUT, ~2TB limit */
  101212. 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;
  101213. #endif
  101214. if(pos >= (FLAC__int64)upper_bound)
  101215. pos = (FLAC__int64)upper_bound - 1;
  101216. if(pos < (FLAC__int64)lower_bound)
  101217. pos = (FLAC__int64)lower_bound;
  101218. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101219. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101220. return false;
  101221. }
  101222. if(!FLAC__stream_decoder_flush(decoder)) {
  101223. /* above call sets the state for us */
  101224. return false;
  101225. }
  101226. /* Now we need to get a frame. First we need to reset our
  101227. * unparseable_frame_count; if we get too many unparseable
  101228. * frames in a row, the read callback will return
  101229. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101230. * FLAC__stream_decoder_process_single() to return false.
  101231. */
  101232. decoder->private_->unparseable_frame_count = 0;
  101233. if(!FLAC__stream_decoder_process_single(decoder)) {
  101234. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101235. return false;
  101236. }
  101237. /* our write callback will change the state when it gets to the target frame */
  101238. /* 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 */
  101239. #if 0
  101240. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101241. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  101242. break;
  101243. #endif
  101244. if(!decoder->private_->is_seeking)
  101245. break;
  101246. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101247. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101248. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  101249. if (pos == (FLAC__int64)lower_bound) {
  101250. /* can't move back any more than the first frame, something is fatally wrong */
  101251. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101252. return false;
  101253. }
  101254. /* our last move backwards wasn't big enough, try again */
  101255. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  101256. continue;
  101257. }
  101258. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  101259. first_seek = false;
  101260. /* make sure we are not seeking in corrupted stream */
  101261. if (this_frame_sample < lower_bound_sample) {
  101262. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101263. return false;
  101264. }
  101265. /* we need to narrow the search */
  101266. if(target_sample < this_frame_sample) {
  101267. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101268. /*@@@@@@ what will decode position be if at end of stream? */
  101269. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  101270. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101271. return false;
  101272. }
  101273. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  101274. }
  101275. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  101276. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101277. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  101278. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101279. return false;
  101280. }
  101281. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  101282. }
  101283. }
  101284. return true;
  101285. }
  101286. #if FLAC__HAS_OGG
  101287. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101288. {
  101289. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  101290. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  101291. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  101292. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  101293. FLAC__bool did_a_seek;
  101294. unsigned iteration = 0;
  101295. /* In the first iterations, we will calculate the target byte position
  101296. * by the distance from the target sample to left_sample and
  101297. * right_sample (let's call it "proportional search"). After that, we
  101298. * will switch to binary search.
  101299. */
  101300. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  101301. /* We will switch to a linear search once our current sample is less
  101302. * than this number of samples ahead of the target sample
  101303. */
  101304. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101305. /* If the total number of samples is unknown, use a large value, and
  101306. * force binary search immediately.
  101307. */
  101308. if(right_sample == 0) {
  101309. right_sample = (FLAC__uint64)(-1);
  101310. BINARY_SEARCH_AFTER_ITERATION = 0;
  101311. }
  101312. decoder->private_->target_sample = target_sample;
  101313. for( ; ; iteration++) {
  101314. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101315. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101316. pos = (right_pos + left_pos) / 2;
  101317. }
  101318. else {
  101319. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101320. #if defined _MSC_VER || defined __MINGW32__
  101321. /* with MSVC you have to spoon feed it the casting */
  101322. 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));
  101323. #else
  101324. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101325. #endif
  101326. #else
  101327. /* a little less accurate: */
  101328. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101329. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101330. else /* @@@ WATCHOUT, ~2TB limit */
  101331. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101332. #endif
  101333. /* @@@ TODO: might want to limit pos to some distance
  101334. * before EOF, to make sure we land before the last frame,
  101335. * thereby getting a this_frame_sample and so having a better
  101336. * estimate.
  101337. */
  101338. }
  101339. /* physical seek */
  101340. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101341. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101342. return false;
  101343. }
  101344. if(!FLAC__stream_decoder_flush(decoder)) {
  101345. /* above call sets the state for us */
  101346. return false;
  101347. }
  101348. did_a_seek = true;
  101349. }
  101350. else
  101351. did_a_seek = false;
  101352. decoder->private_->got_a_frame = false;
  101353. if(!FLAC__stream_decoder_process_single(decoder)) {
  101354. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101355. return false;
  101356. }
  101357. if(!decoder->private_->got_a_frame) {
  101358. if(did_a_seek) {
  101359. /* this can happen if we seek to a point after the last frame; we drop
  101360. * to binary search right away in this case to avoid any wasted
  101361. * iterations of proportional search.
  101362. */
  101363. right_pos = pos;
  101364. BINARY_SEARCH_AFTER_ITERATION = 0;
  101365. }
  101366. else {
  101367. /* this can probably only happen if total_samples is unknown and the
  101368. * target_sample is past the end of the stream
  101369. */
  101370. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101371. return false;
  101372. }
  101373. }
  101374. /* our write callback will change the state when it gets to the target frame */
  101375. else if(!decoder->private_->is_seeking) {
  101376. break;
  101377. }
  101378. else {
  101379. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101380. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101381. if (did_a_seek) {
  101382. if (this_frame_sample <= target_sample) {
  101383. /* The 'equal' case should not happen, since
  101384. * FLAC__stream_decoder_process_single()
  101385. * should recognize that it has hit the
  101386. * target sample and we would exit through
  101387. * the 'break' above.
  101388. */
  101389. FLAC__ASSERT(this_frame_sample != target_sample);
  101390. left_sample = this_frame_sample;
  101391. /* sanity check to avoid infinite loop */
  101392. if (left_pos == pos) {
  101393. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101394. return false;
  101395. }
  101396. left_pos = pos;
  101397. }
  101398. else if(this_frame_sample > target_sample) {
  101399. right_sample = this_frame_sample;
  101400. /* sanity check to avoid infinite loop */
  101401. if (right_pos == pos) {
  101402. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101403. return false;
  101404. }
  101405. right_pos = pos;
  101406. }
  101407. }
  101408. }
  101409. }
  101410. return true;
  101411. }
  101412. #endif
  101413. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101414. {
  101415. (void)client_data;
  101416. if(*bytes > 0) {
  101417. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  101418. if(ferror(decoder->private_->file))
  101419. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101420. else if(*bytes == 0)
  101421. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101422. else
  101423. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101424. }
  101425. else
  101426. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  101427. }
  101428. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101429. {
  101430. (void)client_data;
  101431. if(decoder->private_->file == stdin)
  101432. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  101433. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101434. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  101435. else
  101436. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  101437. }
  101438. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101439. {
  101440. off_t pos;
  101441. (void)client_data;
  101442. if(decoder->private_->file == stdin)
  101443. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  101444. else if((pos = ftello(decoder->private_->file)) < 0)
  101445. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  101446. else {
  101447. *absolute_byte_offset = (FLAC__uint64)pos;
  101448. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  101449. }
  101450. }
  101451. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  101452. {
  101453. struct stat filestats;
  101454. (void)client_data;
  101455. if(decoder->private_->file == stdin)
  101456. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  101457. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  101458. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  101459. else {
  101460. *stream_length = (FLAC__uint64)filestats.st_size;
  101461. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  101462. }
  101463. }
  101464. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  101465. {
  101466. (void)client_data;
  101467. return feof(decoder->private_->file)? true : false;
  101468. }
  101469. #endif
  101470. /*** End of inlined file: stream_decoder.c ***/
  101471. /*** Start of inlined file: stream_encoder.c ***/
  101472. /*** Start of inlined file: juce_FlacHeader.h ***/
  101473. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101474. // tasks..
  101475. #define VERSION "1.2.1"
  101476. #define FLAC__NO_DLL 1
  101477. #if JUCE_MSVC
  101478. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101479. #endif
  101480. #if JUCE_MAC
  101481. #define FLAC__SYS_DARWIN 1
  101482. #endif
  101483. /*** End of inlined file: juce_FlacHeader.h ***/
  101484. #if JUCE_USE_FLAC
  101485. #if HAVE_CONFIG_H
  101486. # include <config.h>
  101487. #endif
  101488. #if defined _MSC_VER || defined __MINGW32__
  101489. #include <io.h> /* for _setmode() */
  101490. #include <fcntl.h> /* for _O_BINARY */
  101491. #endif
  101492. #if defined __CYGWIN__ || defined __EMX__
  101493. #include <io.h> /* for setmode(), O_BINARY */
  101494. #include <fcntl.h> /* for _O_BINARY */
  101495. #endif
  101496. #include <limits.h>
  101497. #include <stdio.h>
  101498. #include <stdlib.h> /* for malloc() */
  101499. #include <string.h> /* for memcpy() */
  101500. #include <sys/types.h> /* for off_t */
  101501. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  101502. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  101503. #define fseeko fseek
  101504. #define ftello ftell
  101505. #endif
  101506. #endif
  101507. /*** Start of inlined file: stream_encoder.h ***/
  101508. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  101509. #define FLAC__PROTECTED__STREAM_ENCODER_H
  101510. #if FLAC__HAS_OGG
  101511. #include "private/ogg_encoder_aspect.h"
  101512. #endif
  101513. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101514. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  101515. typedef enum {
  101516. FLAC__APODIZATION_BARTLETT,
  101517. FLAC__APODIZATION_BARTLETT_HANN,
  101518. FLAC__APODIZATION_BLACKMAN,
  101519. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  101520. FLAC__APODIZATION_CONNES,
  101521. FLAC__APODIZATION_FLATTOP,
  101522. FLAC__APODIZATION_GAUSS,
  101523. FLAC__APODIZATION_HAMMING,
  101524. FLAC__APODIZATION_HANN,
  101525. FLAC__APODIZATION_KAISER_BESSEL,
  101526. FLAC__APODIZATION_NUTTALL,
  101527. FLAC__APODIZATION_RECTANGLE,
  101528. FLAC__APODIZATION_TRIANGLE,
  101529. FLAC__APODIZATION_TUKEY,
  101530. FLAC__APODIZATION_WELCH
  101531. } FLAC__ApodizationFunction;
  101532. typedef struct {
  101533. FLAC__ApodizationFunction type;
  101534. union {
  101535. struct {
  101536. FLAC__real stddev;
  101537. } gauss;
  101538. struct {
  101539. FLAC__real p;
  101540. } tukey;
  101541. } parameters;
  101542. } FLAC__ApodizationSpecification;
  101543. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101544. typedef struct FLAC__StreamEncoderProtected {
  101545. FLAC__StreamEncoderState state;
  101546. FLAC__bool verify;
  101547. FLAC__bool streamable_subset;
  101548. FLAC__bool do_md5;
  101549. FLAC__bool do_mid_side_stereo;
  101550. FLAC__bool loose_mid_side_stereo;
  101551. unsigned channels;
  101552. unsigned bits_per_sample;
  101553. unsigned sample_rate;
  101554. unsigned blocksize;
  101555. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101556. unsigned num_apodizations;
  101557. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  101558. #endif
  101559. unsigned max_lpc_order;
  101560. unsigned qlp_coeff_precision;
  101561. FLAC__bool do_qlp_coeff_prec_search;
  101562. FLAC__bool do_exhaustive_model_search;
  101563. FLAC__bool do_escape_coding;
  101564. unsigned min_residual_partition_order;
  101565. unsigned max_residual_partition_order;
  101566. unsigned rice_parameter_search_dist;
  101567. FLAC__uint64 total_samples_estimate;
  101568. FLAC__StreamMetadata **metadata;
  101569. unsigned num_metadata_blocks;
  101570. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  101571. #if FLAC__HAS_OGG
  101572. FLAC__OggEncoderAspect ogg_encoder_aspect;
  101573. #endif
  101574. } FLAC__StreamEncoderProtected;
  101575. #endif
  101576. /*** End of inlined file: stream_encoder.h ***/
  101577. #if FLAC__HAS_OGG
  101578. #include "include/private/ogg_helper.h"
  101579. #include "include/private/ogg_mapping.h"
  101580. #endif
  101581. /*** Start of inlined file: stream_encoder_framing.h ***/
  101582. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101583. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101584. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  101585. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  101586. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101587. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101588. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101589. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101590. #endif
  101591. /*** End of inlined file: stream_encoder_framing.h ***/
  101592. /*** Start of inlined file: window.h ***/
  101593. #ifndef FLAC__PRIVATE__WINDOW_H
  101594. #define FLAC__PRIVATE__WINDOW_H
  101595. #ifdef HAVE_CONFIG_H
  101596. #include <config.h>
  101597. #endif
  101598. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101599. /*
  101600. * FLAC__window_*()
  101601. * --------------------------------------------------------------------
  101602. * Calculates window coefficients according to different apodization
  101603. * functions.
  101604. *
  101605. * OUT window[0,L-1]
  101606. * IN L (number of points in window)
  101607. */
  101608. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  101609. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  101610. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  101611. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  101612. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  101613. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  101614. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  101615. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  101616. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  101617. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  101618. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  101619. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  101620. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  101621. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  101622. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  101623. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  101624. #endif
  101625. /*** End of inlined file: window.h ***/
  101626. #ifndef FLaC__INLINE
  101627. #define FLaC__INLINE
  101628. #endif
  101629. #ifdef min
  101630. #undef min
  101631. #endif
  101632. #define min(x,y) ((x)<(y)?(x):(y))
  101633. #ifdef max
  101634. #undef max
  101635. #endif
  101636. #define max(x,y) ((x)>(y)?(x):(y))
  101637. /* Exact Rice codeword length calculation is off by default. The simple
  101638. * (and fast) estimation (of how many bits a residual value will be
  101639. * encoded with) in this encoder is very good, almost always yielding
  101640. * compression within 0.1% of exact calculation.
  101641. */
  101642. #undef EXACT_RICE_BITS_CALCULATION
  101643. /* Rice parameter searching is off by default. The simple (and fast)
  101644. * parameter estimation in this encoder is very good, almost always
  101645. * yielding compression within 0.1% of the optimal parameters.
  101646. */
  101647. #undef ENABLE_RICE_PARAMETER_SEARCH
  101648. typedef struct {
  101649. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  101650. unsigned size; /* of each data[] in samples */
  101651. unsigned tail;
  101652. } verify_input_fifo;
  101653. typedef struct {
  101654. const FLAC__byte *data;
  101655. unsigned capacity;
  101656. unsigned bytes;
  101657. } verify_output;
  101658. typedef enum {
  101659. ENCODER_IN_MAGIC = 0,
  101660. ENCODER_IN_METADATA = 1,
  101661. ENCODER_IN_AUDIO = 2
  101662. } EncoderStateHint;
  101663. static struct CompressionLevels {
  101664. FLAC__bool do_mid_side_stereo;
  101665. FLAC__bool loose_mid_side_stereo;
  101666. unsigned max_lpc_order;
  101667. unsigned qlp_coeff_precision;
  101668. FLAC__bool do_qlp_coeff_prec_search;
  101669. FLAC__bool do_escape_coding;
  101670. FLAC__bool do_exhaustive_model_search;
  101671. unsigned min_residual_partition_order;
  101672. unsigned max_residual_partition_order;
  101673. unsigned rice_parameter_search_dist;
  101674. } compression_levels_[] = {
  101675. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  101676. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  101677. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  101678. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  101679. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  101680. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  101681. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  101682. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  101683. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  101684. };
  101685. /***********************************************************************
  101686. *
  101687. * Private class method prototypes
  101688. *
  101689. ***********************************************************************/
  101690. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  101691. static void free_(FLAC__StreamEncoder *encoder);
  101692. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  101693. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  101694. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  101695. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  101696. #if FLAC__HAS_OGG
  101697. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  101698. #endif
  101699. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  101700. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  101701. static FLAC__bool process_subframe_(
  101702. FLAC__StreamEncoder *encoder,
  101703. unsigned min_partition_order,
  101704. unsigned max_partition_order,
  101705. const FLAC__FrameHeader *frame_header,
  101706. unsigned subframe_bps,
  101707. const FLAC__int32 integer_signal[],
  101708. FLAC__Subframe *subframe[2],
  101709. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  101710. FLAC__int32 *residual[2],
  101711. unsigned *best_subframe,
  101712. unsigned *best_bits
  101713. );
  101714. static FLAC__bool add_subframe_(
  101715. FLAC__StreamEncoder *encoder,
  101716. unsigned blocksize,
  101717. unsigned subframe_bps,
  101718. const FLAC__Subframe *subframe,
  101719. FLAC__BitWriter *frame
  101720. );
  101721. static unsigned evaluate_constant_subframe_(
  101722. FLAC__StreamEncoder *encoder,
  101723. const FLAC__int32 signal,
  101724. unsigned blocksize,
  101725. unsigned subframe_bps,
  101726. FLAC__Subframe *subframe
  101727. );
  101728. static unsigned evaluate_fixed_subframe_(
  101729. FLAC__StreamEncoder *encoder,
  101730. const FLAC__int32 signal[],
  101731. FLAC__int32 residual[],
  101732. FLAC__uint64 abs_residual_partition_sums[],
  101733. unsigned raw_bits_per_partition[],
  101734. unsigned blocksize,
  101735. unsigned subframe_bps,
  101736. unsigned order,
  101737. unsigned rice_parameter,
  101738. unsigned rice_parameter_limit,
  101739. unsigned min_partition_order,
  101740. unsigned max_partition_order,
  101741. FLAC__bool do_escape_coding,
  101742. unsigned rice_parameter_search_dist,
  101743. FLAC__Subframe *subframe,
  101744. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101745. );
  101746. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101747. static unsigned evaluate_lpc_subframe_(
  101748. FLAC__StreamEncoder *encoder,
  101749. const FLAC__int32 signal[],
  101750. FLAC__int32 residual[],
  101751. FLAC__uint64 abs_residual_partition_sums[],
  101752. unsigned raw_bits_per_partition[],
  101753. const FLAC__real lp_coeff[],
  101754. unsigned blocksize,
  101755. unsigned subframe_bps,
  101756. unsigned order,
  101757. unsigned qlp_coeff_precision,
  101758. unsigned rice_parameter,
  101759. unsigned rice_parameter_limit,
  101760. unsigned min_partition_order,
  101761. unsigned max_partition_order,
  101762. FLAC__bool do_escape_coding,
  101763. unsigned rice_parameter_search_dist,
  101764. FLAC__Subframe *subframe,
  101765. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101766. );
  101767. #endif
  101768. static unsigned evaluate_verbatim_subframe_(
  101769. FLAC__StreamEncoder *encoder,
  101770. const FLAC__int32 signal[],
  101771. unsigned blocksize,
  101772. unsigned subframe_bps,
  101773. FLAC__Subframe *subframe
  101774. );
  101775. static unsigned find_best_partition_order_(
  101776. struct FLAC__StreamEncoderPrivate *private_,
  101777. const FLAC__int32 residual[],
  101778. FLAC__uint64 abs_residual_partition_sums[],
  101779. unsigned raw_bits_per_partition[],
  101780. unsigned residual_samples,
  101781. unsigned predictor_order,
  101782. unsigned rice_parameter,
  101783. unsigned rice_parameter_limit,
  101784. unsigned min_partition_order,
  101785. unsigned max_partition_order,
  101786. unsigned bps,
  101787. FLAC__bool do_escape_coding,
  101788. unsigned rice_parameter_search_dist,
  101789. FLAC__EntropyCodingMethod *best_ecm
  101790. );
  101791. static void precompute_partition_info_sums_(
  101792. const FLAC__int32 residual[],
  101793. FLAC__uint64 abs_residual_partition_sums[],
  101794. unsigned residual_samples,
  101795. unsigned predictor_order,
  101796. unsigned min_partition_order,
  101797. unsigned max_partition_order,
  101798. unsigned bps
  101799. );
  101800. static void precompute_partition_info_escapes_(
  101801. const FLAC__int32 residual[],
  101802. unsigned raw_bits_per_partition[],
  101803. unsigned residual_samples,
  101804. unsigned predictor_order,
  101805. unsigned min_partition_order,
  101806. unsigned max_partition_order
  101807. );
  101808. static FLAC__bool set_partitioned_rice_(
  101809. #ifdef EXACT_RICE_BITS_CALCULATION
  101810. const FLAC__int32 residual[],
  101811. #endif
  101812. const FLAC__uint64 abs_residual_partition_sums[],
  101813. const unsigned raw_bits_per_partition[],
  101814. const unsigned residual_samples,
  101815. const unsigned predictor_order,
  101816. const unsigned suggested_rice_parameter,
  101817. const unsigned rice_parameter_limit,
  101818. const unsigned rice_parameter_search_dist,
  101819. const unsigned partition_order,
  101820. const FLAC__bool search_for_escapes,
  101821. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  101822. unsigned *bits
  101823. );
  101824. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  101825. /* verify-related routines: */
  101826. static void append_to_verify_fifo_(
  101827. verify_input_fifo *fifo,
  101828. const FLAC__int32 * const input[],
  101829. unsigned input_offset,
  101830. unsigned channels,
  101831. unsigned wide_samples
  101832. );
  101833. static void append_to_verify_fifo_interleaved_(
  101834. verify_input_fifo *fifo,
  101835. const FLAC__int32 input[],
  101836. unsigned input_offset,
  101837. unsigned channels,
  101838. unsigned wide_samples
  101839. );
  101840. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  101841. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  101842. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  101843. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  101844. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  101845. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  101846. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  101847. 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);
  101848. static FILE *get_binary_stdout_(void);
  101849. /***********************************************************************
  101850. *
  101851. * Private class data
  101852. *
  101853. ***********************************************************************/
  101854. typedef struct FLAC__StreamEncoderPrivate {
  101855. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  101856. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  101857. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  101858. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101859. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  101860. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  101861. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  101862. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  101863. #endif
  101864. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  101865. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  101866. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  101867. FLAC__int32 *residual_workspace_mid_side[2][2];
  101868. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  101869. FLAC__Subframe subframe_workspace_mid_side[2][2];
  101870. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  101871. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  101872. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  101873. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  101874. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  101875. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  101876. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  101877. unsigned best_subframe_mid_side[2];
  101878. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  101879. unsigned best_subframe_bits_mid_side[2];
  101880. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  101881. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  101882. FLAC__BitWriter *frame; /* the current frame being worked on */
  101883. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  101884. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  101885. FLAC__ChannelAssignment last_channel_assignment;
  101886. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  101887. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  101888. unsigned current_sample_number;
  101889. unsigned current_frame_number;
  101890. FLAC__MD5Context md5context;
  101891. FLAC__CPUInfo cpuinfo;
  101892. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101893. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  101894. #else
  101895. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  101896. #endif
  101897. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101898. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  101899. 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[]);
  101900. 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[]);
  101901. 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[]);
  101902. #endif
  101903. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  101904. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  101905. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  101906. FLAC__bool disable_constant_subframes;
  101907. FLAC__bool disable_fixed_subframes;
  101908. FLAC__bool disable_verbatim_subframes;
  101909. #if FLAC__HAS_OGG
  101910. FLAC__bool is_ogg;
  101911. #endif
  101912. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  101913. FLAC__StreamEncoderSeekCallback seek_callback;
  101914. FLAC__StreamEncoderTellCallback tell_callback;
  101915. FLAC__StreamEncoderWriteCallback write_callback;
  101916. FLAC__StreamEncoderMetadataCallback metadata_callback;
  101917. FLAC__StreamEncoderProgressCallback progress_callback;
  101918. void *client_data;
  101919. unsigned first_seekpoint_to_check;
  101920. FILE *file; /* only used when encoding to a file */
  101921. FLAC__uint64 bytes_written;
  101922. FLAC__uint64 samples_written;
  101923. unsigned frames_written;
  101924. unsigned total_frames_estimate;
  101925. /* unaligned (original) pointers to allocated data */
  101926. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  101927. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  101928. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101929. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  101930. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  101931. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  101932. FLAC__real *windowed_signal_unaligned;
  101933. #endif
  101934. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  101935. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  101936. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  101937. unsigned *raw_bits_per_partition_unaligned;
  101938. /*
  101939. * These fields have been moved here from private function local
  101940. * declarations merely to save stack space during encoding.
  101941. */
  101942. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101943. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  101944. #endif
  101945. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  101946. /*
  101947. * The data for the verify section
  101948. */
  101949. struct {
  101950. FLAC__StreamDecoder *decoder;
  101951. EncoderStateHint state_hint;
  101952. FLAC__bool needs_magic_hack;
  101953. verify_input_fifo input_fifo;
  101954. verify_output output;
  101955. struct {
  101956. FLAC__uint64 absolute_sample;
  101957. unsigned frame_number;
  101958. unsigned channel;
  101959. unsigned sample;
  101960. FLAC__int32 expected;
  101961. FLAC__int32 got;
  101962. } error_stats;
  101963. } verify;
  101964. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  101965. } FLAC__StreamEncoderPrivate;
  101966. /***********************************************************************
  101967. *
  101968. * Public static class data
  101969. *
  101970. ***********************************************************************/
  101971. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  101972. "FLAC__STREAM_ENCODER_OK",
  101973. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  101974. "FLAC__STREAM_ENCODER_OGG_ERROR",
  101975. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  101976. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  101977. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  101978. "FLAC__STREAM_ENCODER_IO_ERROR",
  101979. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  101980. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  101981. };
  101982. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  101983. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  101984. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  101985. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  101986. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  101987. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  101988. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  101989. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  101990. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  101991. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  101992. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  101993. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  101994. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  101995. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  101996. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  101997. };
  101998. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  101999. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102000. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102001. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102002. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102003. };
  102004. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102005. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102006. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102007. };
  102008. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102009. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102010. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102011. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102012. };
  102013. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102014. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102015. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102016. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102017. };
  102018. /* Number of samples that will be overread to watch for end of stream. By
  102019. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102020. * always try to read blocksize+1 samples before encoding a block, so that
  102021. * even if the stream has a total sample count that is an integral multiple
  102022. * of the blocksize, we will still notice when we are encoding the last
  102023. * block. This is needed, for example, to correctly set the end-of-stream
  102024. * marker in Ogg FLAC.
  102025. *
  102026. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102027. * not really any reason to change it.
  102028. */
  102029. static const unsigned OVERREAD_ = 1;
  102030. /***********************************************************************
  102031. *
  102032. * Class constructor/destructor
  102033. *
  102034. */
  102035. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102036. {
  102037. FLAC__StreamEncoder *encoder;
  102038. unsigned i;
  102039. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102040. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102041. if(encoder == 0) {
  102042. return 0;
  102043. }
  102044. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102045. if(encoder->protected_ == 0) {
  102046. free(encoder);
  102047. return 0;
  102048. }
  102049. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102050. if(encoder->private_ == 0) {
  102051. free(encoder->protected_);
  102052. free(encoder);
  102053. return 0;
  102054. }
  102055. encoder->private_->frame = FLAC__bitwriter_new();
  102056. if(encoder->private_->frame == 0) {
  102057. free(encoder->private_);
  102058. free(encoder->protected_);
  102059. free(encoder);
  102060. return 0;
  102061. }
  102062. encoder->private_->file = 0;
  102063. set_defaults_enc(encoder);
  102064. encoder->private_->is_being_deleted = false;
  102065. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102066. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102067. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102068. }
  102069. for(i = 0; i < 2; i++) {
  102070. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102071. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102072. }
  102073. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102074. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102075. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102076. }
  102077. for(i = 0; i < 2; i++) {
  102078. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102079. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102080. }
  102081. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102082. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102083. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102084. }
  102085. for(i = 0; i < 2; i++) {
  102086. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102087. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102088. }
  102089. for(i = 0; i < 2; i++)
  102090. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102091. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102092. return encoder;
  102093. }
  102094. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102095. {
  102096. unsigned i;
  102097. FLAC__ASSERT(0 != encoder);
  102098. FLAC__ASSERT(0 != encoder->protected_);
  102099. FLAC__ASSERT(0 != encoder->private_);
  102100. FLAC__ASSERT(0 != encoder->private_->frame);
  102101. encoder->private_->is_being_deleted = true;
  102102. (void)FLAC__stream_encoder_finish(encoder);
  102103. if(0 != encoder->private_->verify.decoder)
  102104. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102105. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102106. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102107. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102108. }
  102109. for(i = 0; i < 2; i++) {
  102110. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102111. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102112. }
  102113. for(i = 0; i < 2; i++)
  102114. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102115. FLAC__bitwriter_delete(encoder->private_->frame);
  102116. free(encoder->private_);
  102117. free(encoder->protected_);
  102118. free(encoder);
  102119. }
  102120. /***********************************************************************
  102121. *
  102122. * Public class methods
  102123. *
  102124. ***********************************************************************/
  102125. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102126. FLAC__StreamEncoder *encoder,
  102127. FLAC__StreamEncoderReadCallback read_callback,
  102128. FLAC__StreamEncoderWriteCallback write_callback,
  102129. FLAC__StreamEncoderSeekCallback seek_callback,
  102130. FLAC__StreamEncoderTellCallback tell_callback,
  102131. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102132. void *client_data,
  102133. FLAC__bool is_ogg
  102134. )
  102135. {
  102136. unsigned i;
  102137. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102138. FLAC__ASSERT(0 != encoder);
  102139. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102140. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102141. #if !FLAC__HAS_OGG
  102142. if(is_ogg)
  102143. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102144. #endif
  102145. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102146. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102147. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102148. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102149. if(encoder->protected_->channels != 2) {
  102150. encoder->protected_->do_mid_side_stereo = false;
  102151. encoder->protected_->loose_mid_side_stereo = false;
  102152. }
  102153. else if(!encoder->protected_->do_mid_side_stereo)
  102154. encoder->protected_->loose_mid_side_stereo = false;
  102155. if(encoder->protected_->bits_per_sample >= 32)
  102156. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102157. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102158. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102159. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102160. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102161. if(encoder->protected_->blocksize == 0) {
  102162. if(encoder->protected_->max_lpc_order == 0)
  102163. encoder->protected_->blocksize = 1152;
  102164. else
  102165. encoder->protected_->blocksize = 4096;
  102166. }
  102167. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102168. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102169. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102170. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102171. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102172. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102173. if(encoder->protected_->qlp_coeff_precision == 0) {
  102174. if(encoder->protected_->bits_per_sample < 16) {
  102175. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102176. /* @@@ until then we'll make a guess */
  102177. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102178. }
  102179. else if(encoder->protected_->bits_per_sample == 16) {
  102180. if(encoder->protected_->blocksize <= 192)
  102181. encoder->protected_->qlp_coeff_precision = 7;
  102182. else if(encoder->protected_->blocksize <= 384)
  102183. encoder->protected_->qlp_coeff_precision = 8;
  102184. else if(encoder->protected_->blocksize <= 576)
  102185. encoder->protected_->qlp_coeff_precision = 9;
  102186. else if(encoder->protected_->blocksize <= 1152)
  102187. encoder->protected_->qlp_coeff_precision = 10;
  102188. else if(encoder->protected_->blocksize <= 2304)
  102189. encoder->protected_->qlp_coeff_precision = 11;
  102190. else if(encoder->protected_->blocksize <= 4608)
  102191. encoder->protected_->qlp_coeff_precision = 12;
  102192. else
  102193. encoder->protected_->qlp_coeff_precision = 13;
  102194. }
  102195. else {
  102196. if(encoder->protected_->blocksize <= 384)
  102197. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102198. else if(encoder->protected_->blocksize <= 1152)
  102199. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102200. else
  102201. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102202. }
  102203. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102204. }
  102205. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102206. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102207. if(encoder->protected_->streamable_subset) {
  102208. if(
  102209. encoder->protected_->blocksize != 192 &&
  102210. encoder->protected_->blocksize != 576 &&
  102211. encoder->protected_->blocksize != 1152 &&
  102212. encoder->protected_->blocksize != 2304 &&
  102213. encoder->protected_->blocksize != 4608 &&
  102214. encoder->protected_->blocksize != 256 &&
  102215. encoder->protected_->blocksize != 512 &&
  102216. encoder->protected_->blocksize != 1024 &&
  102217. encoder->protected_->blocksize != 2048 &&
  102218. encoder->protected_->blocksize != 4096 &&
  102219. encoder->protected_->blocksize != 8192 &&
  102220. encoder->protected_->blocksize != 16384
  102221. )
  102222. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102223. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102224. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102225. if(
  102226. encoder->protected_->bits_per_sample != 8 &&
  102227. encoder->protected_->bits_per_sample != 12 &&
  102228. encoder->protected_->bits_per_sample != 16 &&
  102229. encoder->protected_->bits_per_sample != 20 &&
  102230. encoder->protected_->bits_per_sample != 24
  102231. )
  102232. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102233. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102234. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102235. if(
  102236. encoder->protected_->sample_rate <= 48000 &&
  102237. (
  102238. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102239. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102240. )
  102241. ) {
  102242. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102243. }
  102244. }
  102245. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102246. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  102247. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  102248. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  102249. #if FLAC__HAS_OGG
  102250. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  102251. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  102252. unsigned i;
  102253. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  102254. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102255. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  102256. for( ; i > 0; i--)
  102257. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  102258. encoder->protected_->metadata[0] = vc;
  102259. break;
  102260. }
  102261. }
  102262. }
  102263. #endif
  102264. /* keep track of any SEEKTABLE block */
  102265. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  102266. unsigned i;
  102267. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102268. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102269. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  102270. break; /* take only the first one */
  102271. }
  102272. }
  102273. }
  102274. /* validate metadata */
  102275. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  102276. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102277. metadata_has_seektable = false;
  102278. metadata_has_vorbis_comment = false;
  102279. metadata_picture_has_type1 = false;
  102280. metadata_picture_has_type2 = false;
  102281. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102282. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  102283. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  102284. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102285. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102286. if(metadata_has_seektable) /* only one is allowed */
  102287. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102288. metadata_has_seektable = true;
  102289. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  102290. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102291. }
  102292. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102293. if(metadata_has_vorbis_comment) /* only one is allowed */
  102294. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102295. metadata_has_vorbis_comment = true;
  102296. }
  102297. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  102298. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  102299. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102300. }
  102301. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  102302. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  102303. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102304. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102305. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102306. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102307. metadata_picture_has_type1 = true;
  102308. /* standard icon must be 32x32 pixel PNG */
  102309. if(
  102310. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102311. (
  102312. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102313. m->data.picture.width != 32 ||
  102314. m->data.picture.height != 32
  102315. )
  102316. )
  102317. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102318. }
  102319. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102320. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102321. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102322. metadata_picture_has_type2 = true;
  102323. }
  102324. }
  102325. }
  102326. encoder->private_->input_capacity = 0;
  102327. for(i = 0; i < encoder->protected_->channels; i++) {
  102328. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102329. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102330. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102331. #endif
  102332. }
  102333. for(i = 0; i < 2; i++) {
  102334. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102335. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102336. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102337. #endif
  102338. }
  102339. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102340. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102341. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102342. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102343. #endif
  102344. for(i = 0; i < encoder->protected_->channels; i++) {
  102345. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102346. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102347. encoder->private_->best_subframe[i] = 0;
  102348. }
  102349. for(i = 0; i < 2; i++) {
  102350. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102351. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102352. encoder->private_->best_subframe_mid_side[i] = 0;
  102353. }
  102354. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102355. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102356. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102357. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102358. #else
  102359. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  102360. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  102361. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  102362. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  102363. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  102364. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  102365. 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);
  102366. #endif
  102367. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  102368. encoder->private_->loose_mid_side_stereo_frames = 1;
  102369. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  102370. encoder->private_->current_sample_number = 0;
  102371. encoder->private_->current_frame_number = 0;
  102372. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  102373. 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? */
  102374. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  102375. /*
  102376. * get the CPU info and set the function pointers
  102377. */
  102378. FLAC__cpu_info(&encoder->private_->cpuinfo);
  102379. /* first default to the non-asm routines */
  102380. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102381. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  102382. #endif
  102383. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  102384. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102385. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102386. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  102387. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102388. #endif
  102389. /* now override with asm where appropriate */
  102390. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102391. # ifndef FLAC__NO_ASM
  102392. if(encoder->private_->cpuinfo.use_asm) {
  102393. # ifdef FLAC__CPU_IA32
  102394. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  102395. # ifdef FLAC__HAS_NASM
  102396. if(encoder->private_->cpuinfo.data.ia32.sse) {
  102397. if(encoder->protected_->max_lpc_order < 4)
  102398. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  102399. else if(encoder->protected_->max_lpc_order < 8)
  102400. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  102401. else if(encoder->protected_->max_lpc_order < 12)
  102402. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  102403. else
  102404. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102405. }
  102406. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  102407. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  102408. else
  102409. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102410. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  102411. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102412. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  102413. }
  102414. else {
  102415. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102416. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102417. }
  102418. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  102419. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  102420. # endif /* FLAC__HAS_NASM */
  102421. # endif /* FLAC__CPU_IA32 */
  102422. }
  102423. # endif /* !FLAC__NO_ASM */
  102424. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  102425. /* finally override based on wide-ness if necessary */
  102426. if(encoder->private_->use_wide_by_block) {
  102427. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  102428. }
  102429. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  102430. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  102431. #if FLAC__HAS_OGG
  102432. encoder->private_->is_ogg = is_ogg;
  102433. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  102434. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  102435. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102436. }
  102437. #endif
  102438. encoder->private_->read_callback = read_callback;
  102439. encoder->private_->write_callback = write_callback;
  102440. encoder->private_->seek_callback = seek_callback;
  102441. encoder->private_->tell_callback = tell_callback;
  102442. encoder->private_->metadata_callback = metadata_callback;
  102443. encoder->private_->client_data = client_data;
  102444. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  102445. /* the above function sets the state for us in case of an error */
  102446. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102447. }
  102448. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  102449. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102450. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102451. }
  102452. /*
  102453. * Set up the verify stuff if necessary
  102454. */
  102455. if(encoder->protected_->verify) {
  102456. /*
  102457. * First, set up the fifo which will hold the
  102458. * original signal to compare against
  102459. */
  102460. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  102461. for(i = 0; i < encoder->protected_->channels; i++) {
  102462. 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))) {
  102463. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102464. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102465. }
  102466. }
  102467. encoder->private_->verify.input_fifo.tail = 0;
  102468. /*
  102469. * Now set up a stream decoder for verification
  102470. */
  102471. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  102472. if(0 == encoder->private_->verify.decoder) {
  102473. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102474. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102475. }
  102476. 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) {
  102477. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102478. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102479. }
  102480. }
  102481. encoder->private_->verify.error_stats.absolute_sample = 0;
  102482. encoder->private_->verify.error_stats.frame_number = 0;
  102483. encoder->private_->verify.error_stats.channel = 0;
  102484. encoder->private_->verify.error_stats.sample = 0;
  102485. encoder->private_->verify.error_stats.expected = 0;
  102486. encoder->private_->verify.error_stats.got = 0;
  102487. /*
  102488. * These must be done before we write any metadata, because that
  102489. * calls the write_callback, which uses these values.
  102490. */
  102491. encoder->private_->first_seekpoint_to_check = 0;
  102492. encoder->private_->samples_written = 0;
  102493. encoder->protected_->streaminfo_offset = 0;
  102494. encoder->protected_->seektable_offset = 0;
  102495. encoder->protected_->audio_offset = 0;
  102496. /*
  102497. * write the stream header
  102498. */
  102499. if(encoder->protected_->verify)
  102500. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  102501. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  102502. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102503. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102504. }
  102505. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102506. /* the above function sets the state for us in case of an error */
  102507. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102508. }
  102509. /*
  102510. * write the STREAMINFO metadata block
  102511. */
  102512. if(encoder->protected_->verify)
  102513. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  102514. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  102515. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  102516. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  102517. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  102518. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  102519. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  102520. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  102521. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  102522. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  102523. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  102524. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  102525. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  102526. if(encoder->protected_->do_md5)
  102527. FLAC__MD5Init(&encoder->private_->md5context);
  102528. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  102529. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102530. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102531. }
  102532. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102533. /* the above function sets the state for us in case of an error */
  102534. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102535. }
  102536. /*
  102537. * Now that the STREAMINFO block is written, we can init this to an
  102538. * absurdly-high value...
  102539. */
  102540. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  102541. /* ... and clear this to 0 */
  102542. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  102543. /*
  102544. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  102545. * if not, we will write an empty one (FLAC__add_metadata_block()
  102546. * automatically supplies the vendor string).
  102547. *
  102548. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  102549. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  102550. * true it will have already insured that the metadata list is properly
  102551. * ordered.)
  102552. */
  102553. if(!metadata_has_vorbis_comment) {
  102554. FLAC__StreamMetadata vorbis_comment;
  102555. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  102556. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  102557. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  102558. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  102559. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  102560. vorbis_comment.data.vorbis_comment.num_comments = 0;
  102561. vorbis_comment.data.vorbis_comment.comments = 0;
  102562. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  102563. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102564. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102565. }
  102566. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102567. /* the above function sets the state for us in case of an error */
  102568. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102569. }
  102570. }
  102571. /*
  102572. * write the user's metadata blocks
  102573. */
  102574. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102575. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  102576. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  102577. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102578. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102579. }
  102580. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102581. /* the above function sets the state for us in case of an error */
  102582. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102583. }
  102584. }
  102585. /* now that all the metadata is written, we save the stream offset */
  102586. 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 */
  102587. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  102588. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102589. }
  102590. if(encoder->protected_->verify)
  102591. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  102592. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  102593. }
  102594. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  102595. FLAC__StreamEncoder *encoder,
  102596. FLAC__StreamEncoderWriteCallback write_callback,
  102597. FLAC__StreamEncoderSeekCallback seek_callback,
  102598. FLAC__StreamEncoderTellCallback tell_callback,
  102599. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102600. void *client_data
  102601. )
  102602. {
  102603. return init_stream_internal_enc(
  102604. encoder,
  102605. /*read_callback=*/0,
  102606. write_callback,
  102607. seek_callback,
  102608. tell_callback,
  102609. metadata_callback,
  102610. client_data,
  102611. /*is_ogg=*/false
  102612. );
  102613. }
  102614. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  102615. FLAC__StreamEncoder *encoder,
  102616. FLAC__StreamEncoderReadCallback read_callback,
  102617. FLAC__StreamEncoderWriteCallback write_callback,
  102618. FLAC__StreamEncoderSeekCallback seek_callback,
  102619. FLAC__StreamEncoderTellCallback tell_callback,
  102620. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102621. void *client_data
  102622. )
  102623. {
  102624. return init_stream_internal_enc(
  102625. encoder,
  102626. read_callback,
  102627. write_callback,
  102628. seek_callback,
  102629. tell_callback,
  102630. metadata_callback,
  102631. client_data,
  102632. /*is_ogg=*/true
  102633. );
  102634. }
  102635. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  102636. FLAC__StreamEncoder *encoder,
  102637. FILE *file,
  102638. FLAC__StreamEncoderProgressCallback progress_callback,
  102639. void *client_data,
  102640. FLAC__bool is_ogg
  102641. )
  102642. {
  102643. FLAC__StreamEncoderInitStatus init_status;
  102644. FLAC__ASSERT(0 != encoder);
  102645. FLAC__ASSERT(0 != file);
  102646. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102647. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102648. /* double protection */
  102649. if(file == 0) {
  102650. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102651. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102652. }
  102653. /*
  102654. * To make sure that our file does not go unclosed after an error, we
  102655. * must assign the FILE pointer before any further error can occur in
  102656. * this routine.
  102657. */
  102658. if(file == stdout)
  102659. file = get_binary_stdout_(); /* just to be safe */
  102660. encoder->private_->file = file;
  102661. encoder->private_->progress_callback = progress_callback;
  102662. encoder->private_->bytes_written = 0;
  102663. encoder->private_->samples_written = 0;
  102664. encoder->private_->frames_written = 0;
  102665. init_status = init_stream_internal_enc(
  102666. encoder,
  102667. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  102668. file_write_callback_,
  102669. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  102670. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  102671. /*metadata_callback=*/0,
  102672. client_data,
  102673. is_ogg
  102674. );
  102675. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  102676. /* the above function sets the state for us in case of an error */
  102677. return init_status;
  102678. }
  102679. {
  102680. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  102681. FLAC__ASSERT(blocksize != 0);
  102682. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  102683. }
  102684. return init_status;
  102685. }
  102686. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  102687. FLAC__StreamEncoder *encoder,
  102688. FILE *file,
  102689. FLAC__StreamEncoderProgressCallback progress_callback,
  102690. void *client_data
  102691. )
  102692. {
  102693. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  102694. }
  102695. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  102696. FLAC__StreamEncoder *encoder,
  102697. FILE *file,
  102698. FLAC__StreamEncoderProgressCallback progress_callback,
  102699. void *client_data
  102700. )
  102701. {
  102702. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  102703. }
  102704. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  102705. FLAC__StreamEncoder *encoder,
  102706. const char *filename,
  102707. FLAC__StreamEncoderProgressCallback progress_callback,
  102708. void *client_data,
  102709. FLAC__bool is_ogg
  102710. )
  102711. {
  102712. FILE *file;
  102713. FLAC__ASSERT(0 != encoder);
  102714. /*
  102715. * To make sure that our file does not go unclosed after an error, we
  102716. * have to do the same entrance checks here that are later performed
  102717. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  102718. */
  102719. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102720. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102721. file = filename? fopen(filename, "w+b") : stdout;
  102722. if(file == 0) {
  102723. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102724. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102725. }
  102726. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  102727. }
  102728. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  102729. FLAC__StreamEncoder *encoder,
  102730. const char *filename,
  102731. FLAC__StreamEncoderProgressCallback progress_callback,
  102732. void *client_data
  102733. )
  102734. {
  102735. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  102736. }
  102737. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  102738. FLAC__StreamEncoder *encoder,
  102739. const char *filename,
  102740. FLAC__StreamEncoderProgressCallback progress_callback,
  102741. void *client_data
  102742. )
  102743. {
  102744. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  102745. }
  102746. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  102747. {
  102748. FLAC__bool error = false;
  102749. FLAC__ASSERT(0 != encoder);
  102750. FLAC__ASSERT(0 != encoder->private_);
  102751. FLAC__ASSERT(0 != encoder->protected_);
  102752. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  102753. return true;
  102754. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  102755. if(encoder->private_->current_sample_number != 0) {
  102756. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  102757. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  102758. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  102759. error = true;
  102760. }
  102761. }
  102762. if(encoder->protected_->do_md5)
  102763. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  102764. if(!encoder->private_->is_being_deleted) {
  102765. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  102766. if(encoder->private_->seek_callback) {
  102767. #if FLAC__HAS_OGG
  102768. if(encoder->private_->is_ogg)
  102769. update_ogg_metadata_(encoder);
  102770. else
  102771. #endif
  102772. update_metadata_(encoder);
  102773. /* check if an error occurred while updating metadata */
  102774. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  102775. error = true;
  102776. }
  102777. if(encoder->private_->metadata_callback)
  102778. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  102779. }
  102780. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  102781. if(!error)
  102782. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  102783. error = true;
  102784. }
  102785. }
  102786. if(0 != encoder->private_->file) {
  102787. if(encoder->private_->file != stdout)
  102788. fclose(encoder->private_->file);
  102789. encoder->private_->file = 0;
  102790. }
  102791. #if FLAC__HAS_OGG
  102792. if(encoder->private_->is_ogg)
  102793. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  102794. #endif
  102795. free_(encoder);
  102796. set_defaults_enc(encoder);
  102797. if(!error)
  102798. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102799. return !error;
  102800. }
  102801. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  102802. {
  102803. FLAC__ASSERT(0 != encoder);
  102804. FLAC__ASSERT(0 != encoder->private_);
  102805. FLAC__ASSERT(0 != encoder->protected_);
  102806. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102807. return false;
  102808. #if FLAC__HAS_OGG
  102809. /* can't check encoder->private_->is_ogg since that's not set until init time */
  102810. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  102811. return true;
  102812. #else
  102813. (void)value;
  102814. return false;
  102815. #endif
  102816. }
  102817. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102818. {
  102819. FLAC__ASSERT(0 != encoder);
  102820. FLAC__ASSERT(0 != encoder->private_);
  102821. FLAC__ASSERT(0 != encoder->protected_);
  102822. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102823. return false;
  102824. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  102825. encoder->protected_->verify = value;
  102826. #endif
  102827. return true;
  102828. }
  102829. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102830. {
  102831. FLAC__ASSERT(0 != encoder);
  102832. FLAC__ASSERT(0 != encoder->private_);
  102833. FLAC__ASSERT(0 != encoder->protected_);
  102834. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102835. return false;
  102836. encoder->protected_->streamable_subset = value;
  102837. return true;
  102838. }
  102839. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102840. {
  102841. FLAC__ASSERT(0 != encoder);
  102842. FLAC__ASSERT(0 != encoder->private_);
  102843. FLAC__ASSERT(0 != encoder->protected_);
  102844. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102845. return false;
  102846. encoder->protected_->do_md5 = value;
  102847. return true;
  102848. }
  102849. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  102850. {
  102851. FLAC__ASSERT(0 != encoder);
  102852. FLAC__ASSERT(0 != encoder->private_);
  102853. FLAC__ASSERT(0 != encoder->protected_);
  102854. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102855. return false;
  102856. encoder->protected_->channels = value;
  102857. return true;
  102858. }
  102859. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  102860. {
  102861. FLAC__ASSERT(0 != encoder);
  102862. FLAC__ASSERT(0 != encoder->private_);
  102863. FLAC__ASSERT(0 != encoder->protected_);
  102864. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102865. return false;
  102866. encoder->protected_->bits_per_sample = value;
  102867. return true;
  102868. }
  102869. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  102870. {
  102871. FLAC__ASSERT(0 != encoder);
  102872. FLAC__ASSERT(0 != encoder->private_);
  102873. FLAC__ASSERT(0 != encoder->protected_);
  102874. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102875. return false;
  102876. encoder->protected_->sample_rate = value;
  102877. return true;
  102878. }
  102879. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  102880. {
  102881. FLAC__bool ok = true;
  102882. FLAC__ASSERT(0 != encoder);
  102883. FLAC__ASSERT(0 != encoder->private_);
  102884. FLAC__ASSERT(0 != encoder->protected_);
  102885. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102886. return false;
  102887. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  102888. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  102889. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  102890. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  102891. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102892. #if 0
  102893. /* was: */
  102894. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  102895. /* but it's too hard to specify the string in a locale-specific way */
  102896. #else
  102897. encoder->protected_->num_apodizations = 1;
  102898. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  102899. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  102900. #endif
  102901. #endif
  102902. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  102903. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  102904. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  102905. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  102906. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  102907. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  102908. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  102909. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  102910. return ok;
  102911. }
  102912. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  102913. {
  102914. FLAC__ASSERT(0 != encoder);
  102915. FLAC__ASSERT(0 != encoder->private_);
  102916. FLAC__ASSERT(0 != encoder->protected_);
  102917. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102918. return false;
  102919. encoder->protected_->blocksize = value;
  102920. return true;
  102921. }
  102922. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102923. {
  102924. FLAC__ASSERT(0 != encoder);
  102925. FLAC__ASSERT(0 != encoder->private_);
  102926. FLAC__ASSERT(0 != encoder->protected_);
  102927. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102928. return false;
  102929. encoder->protected_->do_mid_side_stereo = value;
  102930. return true;
  102931. }
  102932. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102933. {
  102934. FLAC__ASSERT(0 != encoder);
  102935. FLAC__ASSERT(0 != encoder->private_);
  102936. FLAC__ASSERT(0 != encoder->protected_);
  102937. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102938. return false;
  102939. encoder->protected_->loose_mid_side_stereo = value;
  102940. return true;
  102941. }
  102942. /*@@@@add to tests*/
  102943. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  102944. {
  102945. FLAC__ASSERT(0 != encoder);
  102946. FLAC__ASSERT(0 != encoder->private_);
  102947. FLAC__ASSERT(0 != encoder->protected_);
  102948. FLAC__ASSERT(0 != specification);
  102949. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102950. return false;
  102951. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  102952. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  102953. #else
  102954. encoder->protected_->num_apodizations = 0;
  102955. while(1) {
  102956. const char *s = strchr(specification, ';');
  102957. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  102958. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  102959. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  102960. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  102961. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  102962. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  102963. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  102964. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  102965. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  102966. else if(n==6 && 0 == strncmp("connes" , specification, n))
  102967. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  102968. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  102969. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  102970. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  102971. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  102972. if (stddev > 0.0 && stddev <= 0.5) {
  102973. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  102974. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  102975. }
  102976. }
  102977. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  102978. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  102979. else if(n==4 && 0 == strncmp("hann" , specification, n))
  102980. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  102981. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  102982. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  102983. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  102984. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  102985. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  102986. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  102987. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  102988. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  102989. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  102990. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  102991. if (p >= 0.0 && p <= 1.0) {
  102992. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  102993. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  102994. }
  102995. }
  102996. else if(n==5 && 0 == strncmp("welch" , specification, n))
  102997. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  102998. if (encoder->protected_->num_apodizations == 32)
  102999. break;
  103000. if (s)
  103001. specification = s+1;
  103002. else
  103003. break;
  103004. }
  103005. if(encoder->protected_->num_apodizations == 0) {
  103006. encoder->protected_->num_apodizations = 1;
  103007. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103008. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103009. }
  103010. #endif
  103011. return true;
  103012. }
  103013. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103014. {
  103015. FLAC__ASSERT(0 != encoder);
  103016. FLAC__ASSERT(0 != encoder->private_);
  103017. FLAC__ASSERT(0 != encoder->protected_);
  103018. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103019. return false;
  103020. encoder->protected_->max_lpc_order = value;
  103021. return true;
  103022. }
  103023. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103024. {
  103025. FLAC__ASSERT(0 != encoder);
  103026. FLAC__ASSERT(0 != encoder->private_);
  103027. FLAC__ASSERT(0 != encoder->protected_);
  103028. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103029. return false;
  103030. encoder->protected_->qlp_coeff_precision = value;
  103031. return true;
  103032. }
  103033. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103034. {
  103035. FLAC__ASSERT(0 != encoder);
  103036. FLAC__ASSERT(0 != encoder->private_);
  103037. FLAC__ASSERT(0 != encoder->protected_);
  103038. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103039. return false;
  103040. encoder->protected_->do_qlp_coeff_prec_search = value;
  103041. return true;
  103042. }
  103043. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103044. {
  103045. FLAC__ASSERT(0 != encoder);
  103046. FLAC__ASSERT(0 != encoder->private_);
  103047. FLAC__ASSERT(0 != encoder->protected_);
  103048. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103049. return false;
  103050. #if 0
  103051. /*@@@ deprecated: */
  103052. encoder->protected_->do_escape_coding = value;
  103053. #else
  103054. (void)value;
  103055. #endif
  103056. return true;
  103057. }
  103058. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103059. {
  103060. FLAC__ASSERT(0 != encoder);
  103061. FLAC__ASSERT(0 != encoder->private_);
  103062. FLAC__ASSERT(0 != encoder->protected_);
  103063. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103064. return false;
  103065. encoder->protected_->do_exhaustive_model_search = value;
  103066. return true;
  103067. }
  103068. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103069. {
  103070. FLAC__ASSERT(0 != encoder);
  103071. FLAC__ASSERT(0 != encoder->private_);
  103072. FLAC__ASSERT(0 != encoder->protected_);
  103073. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103074. return false;
  103075. encoder->protected_->min_residual_partition_order = value;
  103076. return true;
  103077. }
  103078. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103079. {
  103080. FLAC__ASSERT(0 != encoder);
  103081. FLAC__ASSERT(0 != encoder->private_);
  103082. FLAC__ASSERT(0 != encoder->protected_);
  103083. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103084. return false;
  103085. encoder->protected_->max_residual_partition_order = value;
  103086. return true;
  103087. }
  103088. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103089. {
  103090. FLAC__ASSERT(0 != encoder);
  103091. FLAC__ASSERT(0 != encoder->private_);
  103092. FLAC__ASSERT(0 != encoder->protected_);
  103093. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103094. return false;
  103095. #if 0
  103096. /*@@@ deprecated: */
  103097. encoder->protected_->rice_parameter_search_dist = value;
  103098. #else
  103099. (void)value;
  103100. #endif
  103101. return true;
  103102. }
  103103. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103104. {
  103105. FLAC__ASSERT(0 != encoder);
  103106. FLAC__ASSERT(0 != encoder->private_);
  103107. FLAC__ASSERT(0 != encoder->protected_);
  103108. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103109. return false;
  103110. encoder->protected_->total_samples_estimate = value;
  103111. return true;
  103112. }
  103113. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103114. {
  103115. FLAC__ASSERT(0 != encoder);
  103116. FLAC__ASSERT(0 != encoder->private_);
  103117. FLAC__ASSERT(0 != encoder->protected_);
  103118. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103119. return false;
  103120. if(0 == metadata)
  103121. num_blocks = 0;
  103122. if(0 == num_blocks)
  103123. metadata = 0;
  103124. /* realloc() does not do exactly what we want so... */
  103125. if(encoder->protected_->metadata) {
  103126. free(encoder->protected_->metadata);
  103127. encoder->protected_->metadata = 0;
  103128. encoder->protected_->num_metadata_blocks = 0;
  103129. }
  103130. if(num_blocks) {
  103131. FLAC__StreamMetadata **m;
  103132. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103133. return false;
  103134. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103135. encoder->protected_->metadata = m;
  103136. encoder->protected_->num_metadata_blocks = num_blocks;
  103137. }
  103138. #if FLAC__HAS_OGG
  103139. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103140. return false;
  103141. #endif
  103142. return true;
  103143. }
  103144. /*
  103145. * These three functions are not static, but not publically exposed in
  103146. * include/FLAC/ either. They are used by the test suite.
  103147. */
  103148. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103149. {
  103150. FLAC__ASSERT(0 != encoder);
  103151. FLAC__ASSERT(0 != encoder->private_);
  103152. FLAC__ASSERT(0 != encoder->protected_);
  103153. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103154. return false;
  103155. encoder->private_->disable_constant_subframes = value;
  103156. return true;
  103157. }
  103158. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103159. {
  103160. FLAC__ASSERT(0 != encoder);
  103161. FLAC__ASSERT(0 != encoder->private_);
  103162. FLAC__ASSERT(0 != encoder->protected_);
  103163. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103164. return false;
  103165. encoder->private_->disable_fixed_subframes = value;
  103166. return true;
  103167. }
  103168. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103169. {
  103170. FLAC__ASSERT(0 != encoder);
  103171. FLAC__ASSERT(0 != encoder->private_);
  103172. FLAC__ASSERT(0 != encoder->protected_);
  103173. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103174. return false;
  103175. encoder->private_->disable_verbatim_subframes = value;
  103176. return true;
  103177. }
  103178. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103179. {
  103180. FLAC__ASSERT(0 != encoder);
  103181. FLAC__ASSERT(0 != encoder->private_);
  103182. FLAC__ASSERT(0 != encoder->protected_);
  103183. return encoder->protected_->state;
  103184. }
  103185. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103186. {
  103187. FLAC__ASSERT(0 != encoder);
  103188. FLAC__ASSERT(0 != encoder->private_);
  103189. FLAC__ASSERT(0 != encoder->protected_);
  103190. if(encoder->protected_->verify)
  103191. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103192. else
  103193. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103194. }
  103195. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103196. {
  103197. FLAC__ASSERT(0 != encoder);
  103198. FLAC__ASSERT(0 != encoder->private_);
  103199. FLAC__ASSERT(0 != encoder->protected_);
  103200. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103201. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103202. else
  103203. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103204. }
  103205. 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)
  103206. {
  103207. FLAC__ASSERT(0 != encoder);
  103208. FLAC__ASSERT(0 != encoder->private_);
  103209. FLAC__ASSERT(0 != encoder->protected_);
  103210. if(0 != absolute_sample)
  103211. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103212. if(0 != frame_number)
  103213. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103214. if(0 != channel)
  103215. *channel = encoder->private_->verify.error_stats.channel;
  103216. if(0 != sample)
  103217. *sample = encoder->private_->verify.error_stats.sample;
  103218. if(0 != expected)
  103219. *expected = encoder->private_->verify.error_stats.expected;
  103220. if(0 != got)
  103221. *got = encoder->private_->verify.error_stats.got;
  103222. }
  103223. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103224. {
  103225. FLAC__ASSERT(0 != encoder);
  103226. FLAC__ASSERT(0 != encoder->private_);
  103227. FLAC__ASSERT(0 != encoder->protected_);
  103228. return encoder->protected_->verify;
  103229. }
  103230. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  103231. {
  103232. FLAC__ASSERT(0 != encoder);
  103233. FLAC__ASSERT(0 != encoder->private_);
  103234. FLAC__ASSERT(0 != encoder->protected_);
  103235. return encoder->protected_->streamable_subset;
  103236. }
  103237. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  103238. {
  103239. FLAC__ASSERT(0 != encoder);
  103240. FLAC__ASSERT(0 != encoder->private_);
  103241. FLAC__ASSERT(0 != encoder->protected_);
  103242. return encoder->protected_->do_md5;
  103243. }
  103244. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  103245. {
  103246. FLAC__ASSERT(0 != encoder);
  103247. FLAC__ASSERT(0 != encoder->private_);
  103248. FLAC__ASSERT(0 != encoder->protected_);
  103249. return encoder->protected_->channels;
  103250. }
  103251. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  103252. {
  103253. FLAC__ASSERT(0 != encoder);
  103254. FLAC__ASSERT(0 != encoder->private_);
  103255. FLAC__ASSERT(0 != encoder->protected_);
  103256. return encoder->protected_->bits_per_sample;
  103257. }
  103258. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  103259. {
  103260. FLAC__ASSERT(0 != encoder);
  103261. FLAC__ASSERT(0 != encoder->private_);
  103262. FLAC__ASSERT(0 != encoder->protected_);
  103263. return encoder->protected_->sample_rate;
  103264. }
  103265. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  103266. {
  103267. FLAC__ASSERT(0 != encoder);
  103268. FLAC__ASSERT(0 != encoder->private_);
  103269. FLAC__ASSERT(0 != encoder->protected_);
  103270. return encoder->protected_->blocksize;
  103271. }
  103272. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103273. {
  103274. FLAC__ASSERT(0 != encoder);
  103275. FLAC__ASSERT(0 != encoder->private_);
  103276. FLAC__ASSERT(0 != encoder->protected_);
  103277. return encoder->protected_->do_mid_side_stereo;
  103278. }
  103279. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103280. {
  103281. FLAC__ASSERT(0 != encoder);
  103282. FLAC__ASSERT(0 != encoder->private_);
  103283. FLAC__ASSERT(0 != encoder->protected_);
  103284. return encoder->protected_->loose_mid_side_stereo;
  103285. }
  103286. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  103287. {
  103288. FLAC__ASSERT(0 != encoder);
  103289. FLAC__ASSERT(0 != encoder->private_);
  103290. FLAC__ASSERT(0 != encoder->protected_);
  103291. return encoder->protected_->max_lpc_order;
  103292. }
  103293. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  103294. {
  103295. FLAC__ASSERT(0 != encoder);
  103296. FLAC__ASSERT(0 != encoder->private_);
  103297. FLAC__ASSERT(0 != encoder->protected_);
  103298. return encoder->protected_->qlp_coeff_precision;
  103299. }
  103300. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  103301. {
  103302. FLAC__ASSERT(0 != encoder);
  103303. FLAC__ASSERT(0 != encoder->private_);
  103304. FLAC__ASSERT(0 != encoder->protected_);
  103305. return encoder->protected_->do_qlp_coeff_prec_search;
  103306. }
  103307. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103308. {
  103309. FLAC__ASSERT(0 != encoder);
  103310. FLAC__ASSERT(0 != encoder->private_);
  103311. FLAC__ASSERT(0 != encoder->protected_);
  103312. return encoder->protected_->do_escape_coding;
  103313. }
  103314. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103315. {
  103316. FLAC__ASSERT(0 != encoder);
  103317. FLAC__ASSERT(0 != encoder->private_);
  103318. FLAC__ASSERT(0 != encoder->protected_);
  103319. return encoder->protected_->do_exhaustive_model_search;
  103320. }
  103321. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103322. {
  103323. FLAC__ASSERT(0 != encoder);
  103324. FLAC__ASSERT(0 != encoder->private_);
  103325. FLAC__ASSERT(0 != encoder->protected_);
  103326. return encoder->protected_->min_residual_partition_order;
  103327. }
  103328. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103329. {
  103330. FLAC__ASSERT(0 != encoder);
  103331. FLAC__ASSERT(0 != encoder->private_);
  103332. FLAC__ASSERT(0 != encoder->protected_);
  103333. return encoder->protected_->max_residual_partition_order;
  103334. }
  103335. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103336. {
  103337. FLAC__ASSERT(0 != encoder);
  103338. FLAC__ASSERT(0 != encoder->private_);
  103339. FLAC__ASSERT(0 != encoder->protected_);
  103340. return encoder->protected_->rice_parameter_search_dist;
  103341. }
  103342. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103343. {
  103344. FLAC__ASSERT(0 != encoder);
  103345. FLAC__ASSERT(0 != encoder->private_);
  103346. FLAC__ASSERT(0 != encoder->protected_);
  103347. return encoder->protected_->total_samples_estimate;
  103348. }
  103349. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103350. {
  103351. unsigned i, j = 0, channel;
  103352. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103353. FLAC__ASSERT(0 != encoder);
  103354. FLAC__ASSERT(0 != encoder->private_);
  103355. FLAC__ASSERT(0 != encoder->protected_);
  103356. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103357. do {
  103358. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  103359. if(encoder->protected_->verify)
  103360. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  103361. for(channel = 0; channel < channels; channel++)
  103362. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  103363. if(encoder->protected_->do_mid_side_stereo) {
  103364. FLAC__ASSERT(channels == 2);
  103365. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103366. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103367. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  103368. 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' ! */
  103369. }
  103370. }
  103371. else
  103372. j += n;
  103373. encoder->private_->current_sample_number += n;
  103374. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103375. if(encoder->private_->current_sample_number > blocksize) {
  103376. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  103377. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103378. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103379. return false;
  103380. /* move unprocessed overread samples to beginnings of arrays */
  103381. for(channel = 0; channel < channels; channel++)
  103382. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103383. if(encoder->protected_->do_mid_side_stereo) {
  103384. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103385. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103386. }
  103387. encoder->private_->current_sample_number = 1;
  103388. }
  103389. } while(j < samples);
  103390. return true;
  103391. }
  103392. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  103393. {
  103394. unsigned i, j, k, channel;
  103395. FLAC__int32 x, mid, side;
  103396. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103397. FLAC__ASSERT(0 != encoder);
  103398. FLAC__ASSERT(0 != encoder->private_);
  103399. FLAC__ASSERT(0 != encoder->protected_);
  103400. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103401. j = k = 0;
  103402. /*
  103403. * we have several flavors of the same basic loop, optimized for
  103404. * different conditions:
  103405. */
  103406. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  103407. /*
  103408. * stereo coding: unroll channel loop
  103409. */
  103410. do {
  103411. if(encoder->protected_->verify)
  103412. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103413. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103414. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103415. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  103416. x = buffer[k++];
  103417. encoder->private_->integer_signal[1][i] = x;
  103418. mid += x;
  103419. side -= x;
  103420. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  103421. encoder->private_->integer_signal_mid_side[1][i] = side;
  103422. encoder->private_->integer_signal_mid_side[0][i] = mid;
  103423. }
  103424. encoder->private_->current_sample_number = i;
  103425. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103426. if(i > blocksize) {
  103427. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103428. return false;
  103429. /* move unprocessed overread samples to beginnings of arrays */
  103430. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103431. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103432. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  103433. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  103434. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103435. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103436. encoder->private_->current_sample_number = 1;
  103437. }
  103438. } while(j < samples);
  103439. }
  103440. else {
  103441. /*
  103442. * independent channel coding: buffer each channel in inner loop
  103443. */
  103444. do {
  103445. if(encoder->protected_->verify)
  103446. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103447. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103448. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103449. for(channel = 0; channel < channels; channel++)
  103450. encoder->private_->integer_signal[channel][i] = buffer[k++];
  103451. }
  103452. encoder->private_->current_sample_number = i;
  103453. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103454. if(i > blocksize) {
  103455. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103456. return false;
  103457. /* move unprocessed overread samples to beginnings of arrays */
  103458. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103459. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103460. for(channel = 0; channel < channels; channel++)
  103461. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103462. encoder->private_->current_sample_number = 1;
  103463. }
  103464. } while(j < samples);
  103465. }
  103466. return true;
  103467. }
  103468. /***********************************************************************
  103469. *
  103470. * Private class methods
  103471. *
  103472. ***********************************************************************/
  103473. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  103474. {
  103475. FLAC__ASSERT(0 != encoder);
  103476. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103477. encoder->protected_->verify = true;
  103478. #else
  103479. encoder->protected_->verify = false;
  103480. #endif
  103481. encoder->protected_->streamable_subset = true;
  103482. encoder->protected_->do_md5 = true;
  103483. encoder->protected_->do_mid_side_stereo = false;
  103484. encoder->protected_->loose_mid_side_stereo = false;
  103485. encoder->protected_->channels = 2;
  103486. encoder->protected_->bits_per_sample = 16;
  103487. encoder->protected_->sample_rate = 44100;
  103488. encoder->protected_->blocksize = 0;
  103489. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103490. encoder->protected_->num_apodizations = 1;
  103491. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103492. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103493. #endif
  103494. encoder->protected_->max_lpc_order = 0;
  103495. encoder->protected_->qlp_coeff_precision = 0;
  103496. encoder->protected_->do_qlp_coeff_prec_search = false;
  103497. encoder->protected_->do_exhaustive_model_search = false;
  103498. encoder->protected_->do_escape_coding = false;
  103499. encoder->protected_->min_residual_partition_order = 0;
  103500. encoder->protected_->max_residual_partition_order = 0;
  103501. encoder->protected_->rice_parameter_search_dist = 0;
  103502. encoder->protected_->total_samples_estimate = 0;
  103503. encoder->protected_->metadata = 0;
  103504. encoder->protected_->num_metadata_blocks = 0;
  103505. encoder->private_->seek_table = 0;
  103506. encoder->private_->disable_constant_subframes = false;
  103507. encoder->private_->disable_fixed_subframes = false;
  103508. encoder->private_->disable_verbatim_subframes = false;
  103509. #if FLAC__HAS_OGG
  103510. encoder->private_->is_ogg = false;
  103511. #endif
  103512. encoder->private_->read_callback = 0;
  103513. encoder->private_->write_callback = 0;
  103514. encoder->private_->seek_callback = 0;
  103515. encoder->private_->tell_callback = 0;
  103516. encoder->private_->metadata_callback = 0;
  103517. encoder->private_->progress_callback = 0;
  103518. encoder->private_->client_data = 0;
  103519. #if FLAC__HAS_OGG
  103520. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  103521. #endif
  103522. }
  103523. void free_(FLAC__StreamEncoder *encoder)
  103524. {
  103525. unsigned i, channel;
  103526. FLAC__ASSERT(0 != encoder);
  103527. if(encoder->protected_->metadata) {
  103528. free(encoder->protected_->metadata);
  103529. encoder->protected_->metadata = 0;
  103530. encoder->protected_->num_metadata_blocks = 0;
  103531. }
  103532. for(i = 0; i < encoder->protected_->channels; i++) {
  103533. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  103534. free(encoder->private_->integer_signal_unaligned[i]);
  103535. encoder->private_->integer_signal_unaligned[i] = 0;
  103536. }
  103537. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103538. if(0 != encoder->private_->real_signal_unaligned[i]) {
  103539. free(encoder->private_->real_signal_unaligned[i]);
  103540. encoder->private_->real_signal_unaligned[i] = 0;
  103541. }
  103542. #endif
  103543. }
  103544. for(i = 0; i < 2; i++) {
  103545. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  103546. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  103547. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  103548. }
  103549. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103550. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  103551. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  103552. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  103553. }
  103554. #endif
  103555. }
  103556. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103557. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  103558. if(0 != encoder->private_->window_unaligned[i]) {
  103559. free(encoder->private_->window_unaligned[i]);
  103560. encoder->private_->window_unaligned[i] = 0;
  103561. }
  103562. }
  103563. if(0 != encoder->private_->windowed_signal_unaligned) {
  103564. free(encoder->private_->windowed_signal_unaligned);
  103565. encoder->private_->windowed_signal_unaligned = 0;
  103566. }
  103567. #endif
  103568. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103569. for(i = 0; i < 2; i++) {
  103570. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  103571. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  103572. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  103573. }
  103574. }
  103575. }
  103576. for(channel = 0; channel < 2; channel++) {
  103577. for(i = 0; i < 2; i++) {
  103578. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  103579. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  103580. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  103581. }
  103582. }
  103583. }
  103584. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  103585. free(encoder->private_->abs_residual_partition_sums_unaligned);
  103586. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  103587. }
  103588. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  103589. free(encoder->private_->raw_bits_per_partition_unaligned);
  103590. encoder->private_->raw_bits_per_partition_unaligned = 0;
  103591. }
  103592. if(encoder->protected_->verify) {
  103593. for(i = 0; i < encoder->protected_->channels; i++) {
  103594. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  103595. free(encoder->private_->verify.input_fifo.data[i]);
  103596. encoder->private_->verify.input_fifo.data[i] = 0;
  103597. }
  103598. }
  103599. }
  103600. FLAC__bitwriter_free(encoder->private_->frame);
  103601. }
  103602. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  103603. {
  103604. FLAC__bool ok;
  103605. unsigned i, channel;
  103606. FLAC__ASSERT(new_blocksize > 0);
  103607. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103608. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  103609. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  103610. if(new_blocksize <= encoder->private_->input_capacity)
  103611. return true;
  103612. ok = true;
  103613. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  103614. * requires that the input arrays (in our case the integer signals)
  103615. * have a buffer of up to 3 zeroes in front (at negative indices) for
  103616. * alignment purposes; we use 4 in front to keep the data well-aligned.
  103617. */
  103618. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  103619. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  103620. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  103621. encoder->private_->integer_signal[i] += 4;
  103622. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103623. #if 0 /* @@@ currently unused */
  103624. if(encoder->protected_->max_lpc_order > 0)
  103625. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  103626. #endif
  103627. #endif
  103628. }
  103629. for(i = 0; ok && i < 2; i++) {
  103630. 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]);
  103631. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  103632. encoder->private_->integer_signal_mid_side[i] += 4;
  103633. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103634. #if 0 /* @@@ currently unused */
  103635. if(encoder->protected_->max_lpc_order > 0)
  103636. 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]);
  103637. #endif
  103638. #endif
  103639. }
  103640. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103641. if(ok && encoder->protected_->max_lpc_order > 0) {
  103642. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  103643. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  103644. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  103645. }
  103646. #endif
  103647. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  103648. for(i = 0; ok && i < 2; i++) {
  103649. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  103650. }
  103651. }
  103652. for(channel = 0; ok && channel < 2; channel++) {
  103653. for(i = 0; ok && i < 2; i++) {
  103654. 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]);
  103655. }
  103656. }
  103657. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  103658. /*@@@ 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) */
  103659. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  103660. if(encoder->protected_->do_escape_coding)
  103661. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  103662. /* now adjust the windows if the blocksize has changed */
  103663. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103664. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  103665. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  103666. switch(encoder->protected_->apodizations[i].type) {
  103667. case FLAC__APODIZATION_BARTLETT:
  103668. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  103669. break;
  103670. case FLAC__APODIZATION_BARTLETT_HANN:
  103671. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  103672. break;
  103673. case FLAC__APODIZATION_BLACKMAN:
  103674. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  103675. break;
  103676. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  103677. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  103678. break;
  103679. case FLAC__APODIZATION_CONNES:
  103680. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  103681. break;
  103682. case FLAC__APODIZATION_FLATTOP:
  103683. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  103684. break;
  103685. case FLAC__APODIZATION_GAUSS:
  103686. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  103687. break;
  103688. case FLAC__APODIZATION_HAMMING:
  103689. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  103690. break;
  103691. case FLAC__APODIZATION_HANN:
  103692. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103693. break;
  103694. case FLAC__APODIZATION_KAISER_BESSEL:
  103695. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  103696. break;
  103697. case FLAC__APODIZATION_NUTTALL:
  103698. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  103699. break;
  103700. case FLAC__APODIZATION_RECTANGLE:
  103701. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  103702. break;
  103703. case FLAC__APODIZATION_TRIANGLE:
  103704. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  103705. break;
  103706. case FLAC__APODIZATION_TUKEY:
  103707. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  103708. break;
  103709. case FLAC__APODIZATION_WELCH:
  103710. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  103711. break;
  103712. default:
  103713. FLAC__ASSERT(0);
  103714. /* double protection */
  103715. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103716. break;
  103717. }
  103718. }
  103719. }
  103720. #endif
  103721. if(ok)
  103722. encoder->private_->input_capacity = new_blocksize;
  103723. else
  103724. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103725. return ok;
  103726. }
  103727. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  103728. {
  103729. const FLAC__byte *buffer;
  103730. size_t bytes;
  103731. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  103732. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  103733. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103734. return false;
  103735. }
  103736. if(encoder->protected_->verify) {
  103737. encoder->private_->verify.output.data = buffer;
  103738. encoder->private_->verify.output.bytes = bytes;
  103739. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  103740. encoder->private_->verify.needs_magic_hack = true;
  103741. }
  103742. else {
  103743. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  103744. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103745. FLAC__bitwriter_clear(encoder->private_->frame);
  103746. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  103747. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103748. return false;
  103749. }
  103750. }
  103751. }
  103752. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103753. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103754. FLAC__bitwriter_clear(encoder->private_->frame);
  103755. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103756. return false;
  103757. }
  103758. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103759. FLAC__bitwriter_clear(encoder->private_->frame);
  103760. if(samples > 0) {
  103761. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  103762. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  103763. }
  103764. return true;
  103765. }
  103766. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  103767. {
  103768. FLAC__StreamEncoderWriteStatus status;
  103769. FLAC__uint64 output_position = 0;
  103770. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  103771. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  103772. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103773. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  103774. }
  103775. /*
  103776. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  103777. */
  103778. if(samples == 0) {
  103779. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  103780. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  103781. encoder->protected_->streaminfo_offset = output_position;
  103782. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  103783. encoder->protected_->seektable_offset = output_position;
  103784. }
  103785. /*
  103786. * Mark the current seek point if hit (if audio_offset == 0 that
  103787. * means we're still writing metadata and haven't hit the first
  103788. * frame yet)
  103789. */
  103790. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  103791. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103792. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  103793. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  103794. FLAC__uint64 test_sample;
  103795. unsigned i;
  103796. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  103797. test_sample = encoder->private_->seek_table->points[i].sample_number;
  103798. if(test_sample > frame_last_sample) {
  103799. break;
  103800. }
  103801. else if(test_sample >= frame_first_sample) {
  103802. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  103803. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  103804. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  103805. encoder->private_->first_seekpoint_to_check++;
  103806. /* DO NOT: "break;" and here's why:
  103807. * The seektable template may contain more than one target
  103808. * sample for any given frame; we will keep looping, generating
  103809. * duplicate seekpoints for them, and we'll clean it up later,
  103810. * just before writing the seektable back to the metadata.
  103811. */
  103812. }
  103813. else {
  103814. encoder->private_->first_seekpoint_to_check++;
  103815. }
  103816. }
  103817. }
  103818. #if FLAC__HAS_OGG
  103819. if(encoder->private_->is_ogg) {
  103820. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  103821. &encoder->protected_->ogg_encoder_aspect,
  103822. buffer,
  103823. bytes,
  103824. samples,
  103825. encoder->private_->current_frame_number,
  103826. is_last_block,
  103827. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  103828. encoder,
  103829. encoder->private_->client_data
  103830. );
  103831. }
  103832. else
  103833. #endif
  103834. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  103835. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103836. encoder->private_->bytes_written += bytes;
  103837. encoder->private_->samples_written += samples;
  103838. /* we keep a high watermark on the number of frames written because
  103839. * when the encoder goes back to write metadata, 'current_frame'
  103840. * will drop back to 0.
  103841. */
  103842. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  103843. }
  103844. else
  103845. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103846. return status;
  103847. }
  103848. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  103849. void update_metadata_(const FLAC__StreamEncoder *encoder)
  103850. {
  103851. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  103852. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  103853. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  103854. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  103855. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  103856. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  103857. FLAC__StreamEncoderSeekStatus seek_status;
  103858. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  103859. /* All this is based on intimate knowledge of the stream header
  103860. * layout, but a change to the header format that would break this
  103861. * would also break all streams encoded in the previous format.
  103862. */
  103863. /*
  103864. * Write MD5 signature
  103865. */
  103866. {
  103867. const unsigned md5_offset =
  103868. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103869. (
  103870. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103871. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103872. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103873. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103874. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103875. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103876. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  103877. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  103878. ) / 8;
  103879. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  103880. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103881. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103882. return;
  103883. }
  103884. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103885. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103886. return;
  103887. }
  103888. }
  103889. /*
  103890. * Write total samples
  103891. */
  103892. {
  103893. const unsigned total_samples_byte_offset =
  103894. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103895. (
  103896. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103897. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103898. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103899. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103900. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103901. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103902. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  103903. - 4
  103904. ) / 8;
  103905. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  103906. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  103907. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  103908. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  103909. b[4] = (FLAC__byte)(samples & 0xFF);
  103910. 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) {
  103911. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103912. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103913. return;
  103914. }
  103915. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103916. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103917. return;
  103918. }
  103919. }
  103920. /*
  103921. * Write min/max framesize
  103922. */
  103923. {
  103924. const unsigned min_framesize_offset =
  103925. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103926. (
  103927. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103928. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  103929. ) / 8;
  103930. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  103931. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  103932. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  103933. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  103934. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  103935. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  103936. 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) {
  103937. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103938. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103939. return;
  103940. }
  103941. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103942. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103943. return;
  103944. }
  103945. }
  103946. /*
  103947. * Write seektable
  103948. */
  103949. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  103950. unsigned i;
  103951. FLAC__format_seektable_sort(encoder->private_->seek_table);
  103952. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  103953. 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) {
  103954. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103955. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103956. return;
  103957. }
  103958. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  103959. FLAC__uint64 xx;
  103960. unsigned x;
  103961. xx = encoder->private_->seek_table->points[i].sample_number;
  103962. b[7] = (FLAC__byte)xx; xx >>= 8;
  103963. b[6] = (FLAC__byte)xx; xx >>= 8;
  103964. b[5] = (FLAC__byte)xx; xx >>= 8;
  103965. b[4] = (FLAC__byte)xx; xx >>= 8;
  103966. b[3] = (FLAC__byte)xx; xx >>= 8;
  103967. b[2] = (FLAC__byte)xx; xx >>= 8;
  103968. b[1] = (FLAC__byte)xx; xx >>= 8;
  103969. b[0] = (FLAC__byte)xx; xx >>= 8;
  103970. xx = encoder->private_->seek_table->points[i].stream_offset;
  103971. b[15] = (FLAC__byte)xx; xx >>= 8;
  103972. b[14] = (FLAC__byte)xx; xx >>= 8;
  103973. b[13] = (FLAC__byte)xx; xx >>= 8;
  103974. b[12] = (FLAC__byte)xx; xx >>= 8;
  103975. b[11] = (FLAC__byte)xx; xx >>= 8;
  103976. b[10] = (FLAC__byte)xx; xx >>= 8;
  103977. b[9] = (FLAC__byte)xx; xx >>= 8;
  103978. b[8] = (FLAC__byte)xx; xx >>= 8;
  103979. x = encoder->private_->seek_table->points[i].frame_samples;
  103980. b[17] = (FLAC__byte)x; x >>= 8;
  103981. b[16] = (FLAC__byte)x; x >>= 8;
  103982. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103983. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103984. return;
  103985. }
  103986. }
  103987. }
  103988. }
  103989. #if FLAC__HAS_OGG
  103990. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  103991. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  103992. {
  103993. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  103994. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  103995. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  103996. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  103997. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  103998. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  103999. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104000. FLAC__STREAM_SYNC_LENGTH
  104001. ;
  104002. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104003. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104004. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104005. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104006. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104007. ogg_page page;
  104008. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104009. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104010. /* Pre-check that client supports seeking, since we don't want the
  104011. * ogg_helper code to ever have to deal with this condition.
  104012. */
  104013. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104014. return;
  104015. /* All this is based on intimate knowledge of the stream header
  104016. * layout, but a change to the header format that would break this
  104017. * would also break all streams encoded in the previous format.
  104018. */
  104019. /**
  104020. ** Write STREAMINFO stats
  104021. **/
  104022. simple_ogg_page__init(&page);
  104023. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104024. simple_ogg_page__clear(&page);
  104025. return; /* state already set */
  104026. }
  104027. /*
  104028. * Write MD5 signature
  104029. */
  104030. {
  104031. const unsigned md5_offset =
  104032. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104033. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104034. (
  104035. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104036. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104037. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104038. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104039. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104040. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104041. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104042. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104043. ) / 8;
  104044. if(md5_offset + 16 > (unsigned)page.body_len) {
  104045. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104046. simple_ogg_page__clear(&page);
  104047. return;
  104048. }
  104049. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104050. }
  104051. /*
  104052. * Write total samples
  104053. */
  104054. {
  104055. const unsigned total_samples_byte_offset =
  104056. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104057. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104058. (
  104059. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104060. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104061. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104062. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104063. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104064. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104065. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104066. - 4
  104067. ) / 8;
  104068. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104069. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104070. simple_ogg_page__clear(&page);
  104071. return;
  104072. }
  104073. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104074. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104075. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104076. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104077. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104078. b[4] = (FLAC__byte)(samples & 0xFF);
  104079. memcpy(page.body + total_samples_byte_offset, b, 5);
  104080. }
  104081. /*
  104082. * Write min/max framesize
  104083. */
  104084. {
  104085. const unsigned min_framesize_offset =
  104086. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104087. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104088. (
  104089. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104090. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104091. ) / 8;
  104092. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104093. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104094. simple_ogg_page__clear(&page);
  104095. return;
  104096. }
  104097. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104098. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104099. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104100. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104101. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104102. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104103. memcpy(page.body + min_framesize_offset, b, 6);
  104104. }
  104105. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104106. simple_ogg_page__clear(&page);
  104107. return; /* state already set */
  104108. }
  104109. simple_ogg_page__clear(&page);
  104110. /*
  104111. * Write seektable
  104112. */
  104113. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104114. unsigned i;
  104115. FLAC__byte *p;
  104116. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104117. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104118. simple_ogg_page__init(&page);
  104119. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104120. simple_ogg_page__clear(&page);
  104121. return; /* state already set */
  104122. }
  104123. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104124. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104125. simple_ogg_page__clear(&page);
  104126. return;
  104127. }
  104128. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104129. FLAC__uint64 xx;
  104130. unsigned x;
  104131. xx = encoder->private_->seek_table->points[i].sample_number;
  104132. b[7] = (FLAC__byte)xx; xx >>= 8;
  104133. b[6] = (FLAC__byte)xx; xx >>= 8;
  104134. b[5] = (FLAC__byte)xx; xx >>= 8;
  104135. b[4] = (FLAC__byte)xx; xx >>= 8;
  104136. b[3] = (FLAC__byte)xx; xx >>= 8;
  104137. b[2] = (FLAC__byte)xx; xx >>= 8;
  104138. b[1] = (FLAC__byte)xx; xx >>= 8;
  104139. b[0] = (FLAC__byte)xx; xx >>= 8;
  104140. xx = encoder->private_->seek_table->points[i].stream_offset;
  104141. b[15] = (FLAC__byte)xx; xx >>= 8;
  104142. b[14] = (FLAC__byte)xx; xx >>= 8;
  104143. b[13] = (FLAC__byte)xx; xx >>= 8;
  104144. b[12] = (FLAC__byte)xx; xx >>= 8;
  104145. b[11] = (FLAC__byte)xx; xx >>= 8;
  104146. b[10] = (FLAC__byte)xx; xx >>= 8;
  104147. b[9] = (FLAC__byte)xx; xx >>= 8;
  104148. b[8] = (FLAC__byte)xx; xx >>= 8;
  104149. x = encoder->private_->seek_table->points[i].frame_samples;
  104150. b[17] = (FLAC__byte)x; x >>= 8;
  104151. b[16] = (FLAC__byte)x; x >>= 8;
  104152. memcpy(p, b, 18);
  104153. }
  104154. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104155. simple_ogg_page__clear(&page);
  104156. return; /* state already set */
  104157. }
  104158. simple_ogg_page__clear(&page);
  104159. }
  104160. }
  104161. #endif
  104162. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104163. {
  104164. FLAC__uint16 crc;
  104165. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104166. /*
  104167. * Accumulate raw signal to the MD5 signature
  104168. */
  104169. 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)) {
  104170. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104171. return false;
  104172. }
  104173. /*
  104174. * Process the frame header and subframes into the frame bitbuffer
  104175. */
  104176. if(!process_subframes_(encoder, is_fractional_block)) {
  104177. /* the above function sets the state for us in case of an error */
  104178. return false;
  104179. }
  104180. /*
  104181. * Zero-pad the frame to a byte_boundary
  104182. */
  104183. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104184. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104185. return false;
  104186. }
  104187. /*
  104188. * CRC-16 the whole thing
  104189. */
  104190. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104191. if(
  104192. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104193. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104194. ) {
  104195. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104196. return false;
  104197. }
  104198. /*
  104199. * Write it
  104200. */
  104201. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104202. /* the above function sets the state for us in case of an error */
  104203. return false;
  104204. }
  104205. /*
  104206. * Get ready for the next frame
  104207. */
  104208. encoder->private_->current_sample_number = 0;
  104209. encoder->private_->current_frame_number++;
  104210. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104211. return true;
  104212. }
  104213. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104214. {
  104215. FLAC__FrameHeader frame_header;
  104216. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104217. FLAC__bool do_independent, do_mid_side;
  104218. /*
  104219. * Calculate the min,max Rice partition orders
  104220. */
  104221. if(is_fractional_block) {
  104222. max_partition_order = 0;
  104223. }
  104224. else {
  104225. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104226. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104227. }
  104228. min_partition_order = min(min_partition_order, max_partition_order);
  104229. /*
  104230. * Setup the frame
  104231. */
  104232. frame_header.blocksize = encoder->protected_->blocksize;
  104233. frame_header.sample_rate = encoder->protected_->sample_rate;
  104234. frame_header.channels = encoder->protected_->channels;
  104235. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104236. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104237. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104238. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104239. /*
  104240. * Figure out what channel assignments to try
  104241. */
  104242. if(encoder->protected_->do_mid_side_stereo) {
  104243. if(encoder->protected_->loose_mid_side_stereo) {
  104244. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  104245. do_independent = true;
  104246. do_mid_side = true;
  104247. }
  104248. else {
  104249. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  104250. do_mid_side = !do_independent;
  104251. }
  104252. }
  104253. else {
  104254. do_independent = true;
  104255. do_mid_side = true;
  104256. }
  104257. }
  104258. else {
  104259. do_independent = true;
  104260. do_mid_side = false;
  104261. }
  104262. FLAC__ASSERT(do_independent || do_mid_side);
  104263. /*
  104264. * Check for wasted bits; set effective bps for each subframe
  104265. */
  104266. if(do_independent) {
  104267. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104268. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  104269. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  104270. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  104271. }
  104272. }
  104273. if(do_mid_side) {
  104274. FLAC__ASSERT(encoder->protected_->channels == 2);
  104275. for(channel = 0; channel < 2; channel++) {
  104276. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  104277. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  104278. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  104279. }
  104280. }
  104281. /*
  104282. * First do a normal encoding pass of each independent channel
  104283. */
  104284. if(do_independent) {
  104285. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104286. if(!
  104287. process_subframe_(
  104288. encoder,
  104289. min_partition_order,
  104290. max_partition_order,
  104291. &frame_header,
  104292. encoder->private_->subframe_bps[channel],
  104293. encoder->private_->integer_signal[channel],
  104294. encoder->private_->subframe_workspace_ptr[channel],
  104295. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  104296. encoder->private_->residual_workspace[channel],
  104297. encoder->private_->best_subframe+channel,
  104298. encoder->private_->best_subframe_bits+channel
  104299. )
  104300. )
  104301. return false;
  104302. }
  104303. }
  104304. /*
  104305. * Now do mid and side channels if requested
  104306. */
  104307. if(do_mid_side) {
  104308. FLAC__ASSERT(encoder->protected_->channels == 2);
  104309. for(channel = 0; channel < 2; channel++) {
  104310. if(!
  104311. process_subframe_(
  104312. encoder,
  104313. min_partition_order,
  104314. max_partition_order,
  104315. &frame_header,
  104316. encoder->private_->subframe_bps_mid_side[channel],
  104317. encoder->private_->integer_signal_mid_side[channel],
  104318. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104319. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104320. encoder->private_->residual_workspace_mid_side[channel],
  104321. encoder->private_->best_subframe_mid_side+channel,
  104322. encoder->private_->best_subframe_bits_mid_side+channel
  104323. )
  104324. )
  104325. return false;
  104326. }
  104327. }
  104328. /*
  104329. * Compose the frame bitbuffer
  104330. */
  104331. if(do_mid_side) {
  104332. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104333. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104334. FLAC__ChannelAssignment channel_assignment;
  104335. FLAC__ASSERT(encoder->protected_->channels == 2);
  104336. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104337. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104338. }
  104339. else {
  104340. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104341. unsigned min_bits;
  104342. int ca;
  104343. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104344. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104345. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104346. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104347. FLAC__ASSERT(do_independent && do_mid_side);
  104348. /* We have to figure out which channel assignent results in the smallest frame */
  104349. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104350. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104351. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104352. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104353. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104354. min_bits = bits[channel_assignment];
  104355. for(ca = 1; ca <= 3; ca++) {
  104356. if(bits[ca] < min_bits) {
  104357. min_bits = bits[ca];
  104358. channel_assignment = (FLAC__ChannelAssignment)ca;
  104359. }
  104360. }
  104361. }
  104362. frame_header.channel_assignment = channel_assignment;
  104363. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104364. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104365. return false;
  104366. }
  104367. switch(channel_assignment) {
  104368. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104369. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104370. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104371. break;
  104372. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104373. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104374. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104375. break;
  104376. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104377. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104378. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104379. break;
  104380. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104381. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  104382. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104383. break;
  104384. default:
  104385. FLAC__ASSERT(0);
  104386. }
  104387. switch(channel_assignment) {
  104388. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104389. left_bps = encoder->private_->subframe_bps [0];
  104390. right_bps = encoder->private_->subframe_bps [1];
  104391. break;
  104392. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104393. left_bps = encoder->private_->subframe_bps [0];
  104394. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104395. break;
  104396. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104397. left_bps = encoder->private_->subframe_bps_mid_side[1];
  104398. right_bps = encoder->private_->subframe_bps [1];
  104399. break;
  104400. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104401. left_bps = encoder->private_->subframe_bps_mid_side[0];
  104402. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104403. break;
  104404. default:
  104405. FLAC__ASSERT(0);
  104406. }
  104407. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  104408. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  104409. return false;
  104410. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  104411. return false;
  104412. }
  104413. else {
  104414. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104415. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104416. return false;
  104417. }
  104418. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104419. 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)) {
  104420. /* the above function sets the state for us in case of an error */
  104421. return false;
  104422. }
  104423. }
  104424. }
  104425. if(encoder->protected_->loose_mid_side_stereo) {
  104426. encoder->private_->loose_mid_side_stereo_frame_count++;
  104427. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  104428. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  104429. }
  104430. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  104431. return true;
  104432. }
  104433. FLAC__bool process_subframe_(
  104434. FLAC__StreamEncoder *encoder,
  104435. unsigned min_partition_order,
  104436. unsigned max_partition_order,
  104437. const FLAC__FrameHeader *frame_header,
  104438. unsigned subframe_bps,
  104439. const FLAC__int32 integer_signal[],
  104440. FLAC__Subframe *subframe[2],
  104441. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  104442. FLAC__int32 *residual[2],
  104443. unsigned *best_subframe,
  104444. unsigned *best_bits
  104445. )
  104446. {
  104447. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104448. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104449. #else
  104450. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104451. #endif
  104452. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104453. FLAC__double lpc_residual_bits_per_sample;
  104454. 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 */
  104455. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  104456. unsigned min_lpc_order, max_lpc_order, lpc_order;
  104457. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  104458. #endif
  104459. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  104460. unsigned rice_parameter;
  104461. unsigned _candidate_bits, _best_bits;
  104462. unsigned _best_subframe;
  104463. /* only use RICE2 partitions if stream bps > 16 */
  104464. 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;
  104465. FLAC__ASSERT(frame_header->blocksize > 0);
  104466. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  104467. _best_subframe = 0;
  104468. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  104469. _best_bits = UINT_MAX;
  104470. else
  104471. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104472. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  104473. unsigned signal_is_constant = false;
  104474. 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);
  104475. /* check for constant subframe */
  104476. if(
  104477. !encoder->private_->disable_constant_subframes &&
  104478. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104479. fixed_residual_bits_per_sample[1] == 0.0
  104480. #else
  104481. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  104482. #endif
  104483. ) {
  104484. /* the above means it's possible all samples are the same value; now double-check it: */
  104485. unsigned i;
  104486. signal_is_constant = true;
  104487. for(i = 1; i < frame_header->blocksize; i++) {
  104488. if(integer_signal[0] != integer_signal[i]) {
  104489. signal_is_constant = false;
  104490. break;
  104491. }
  104492. }
  104493. }
  104494. if(signal_is_constant) {
  104495. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  104496. if(_candidate_bits < _best_bits) {
  104497. _best_subframe = !_best_subframe;
  104498. _best_bits = _candidate_bits;
  104499. }
  104500. }
  104501. else {
  104502. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  104503. /* encode fixed */
  104504. if(encoder->protected_->do_exhaustive_model_search) {
  104505. min_fixed_order = 0;
  104506. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  104507. }
  104508. else {
  104509. min_fixed_order = max_fixed_order = guess_fixed_order;
  104510. }
  104511. if(max_fixed_order >= frame_header->blocksize)
  104512. max_fixed_order = frame_header->blocksize - 1;
  104513. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  104514. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104515. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  104516. continue; /* don't even try */
  104517. 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 */
  104518. #else
  104519. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  104520. continue; /* don't even try */
  104521. 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 */
  104522. #endif
  104523. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104524. if(rice_parameter >= rice_parameter_limit) {
  104525. #ifdef DEBUG_VERBOSE
  104526. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  104527. #endif
  104528. rice_parameter = rice_parameter_limit - 1;
  104529. }
  104530. _candidate_bits =
  104531. evaluate_fixed_subframe_(
  104532. encoder,
  104533. integer_signal,
  104534. residual[!_best_subframe],
  104535. encoder->private_->abs_residual_partition_sums,
  104536. encoder->private_->raw_bits_per_partition,
  104537. frame_header->blocksize,
  104538. subframe_bps,
  104539. fixed_order,
  104540. rice_parameter,
  104541. rice_parameter_limit,
  104542. min_partition_order,
  104543. max_partition_order,
  104544. encoder->protected_->do_escape_coding,
  104545. encoder->protected_->rice_parameter_search_dist,
  104546. subframe[!_best_subframe],
  104547. partitioned_rice_contents[!_best_subframe]
  104548. );
  104549. if(_candidate_bits < _best_bits) {
  104550. _best_subframe = !_best_subframe;
  104551. _best_bits = _candidate_bits;
  104552. }
  104553. }
  104554. }
  104555. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104556. /* encode lpc */
  104557. if(encoder->protected_->max_lpc_order > 0) {
  104558. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  104559. max_lpc_order = frame_header->blocksize-1;
  104560. else
  104561. max_lpc_order = encoder->protected_->max_lpc_order;
  104562. if(max_lpc_order > 0) {
  104563. unsigned a;
  104564. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  104565. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  104566. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  104567. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  104568. if(autoc[0] != 0.0) {
  104569. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  104570. if(encoder->protected_->do_exhaustive_model_search) {
  104571. min_lpc_order = 1;
  104572. }
  104573. else {
  104574. const unsigned guess_lpc_order =
  104575. FLAC__lpc_compute_best_order(
  104576. lpc_error,
  104577. max_lpc_order,
  104578. frame_header->blocksize,
  104579. subframe_bps + (
  104580. encoder->protected_->do_qlp_coeff_prec_search?
  104581. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  104582. encoder->protected_->qlp_coeff_precision
  104583. )
  104584. );
  104585. min_lpc_order = max_lpc_order = guess_lpc_order;
  104586. }
  104587. if(max_lpc_order >= frame_header->blocksize)
  104588. max_lpc_order = frame_header->blocksize - 1;
  104589. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  104590. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  104591. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  104592. continue; /* don't even try */
  104593. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  104594. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104595. if(rice_parameter >= rice_parameter_limit) {
  104596. #ifdef DEBUG_VERBOSE
  104597. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  104598. #endif
  104599. rice_parameter = rice_parameter_limit - 1;
  104600. }
  104601. if(encoder->protected_->do_qlp_coeff_prec_search) {
  104602. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  104603. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  104604. if(subframe_bps <= 17) {
  104605. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  104606. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  104607. }
  104608. else
  104609. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  104610. }
  104611. else {
  104612. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  104613. }
  104614. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  104615. _candidate_bits =
  104616. evaluate_lpc_subframe_(
  104617. encoder,
  104618. integer_signal,
  104619. residual[!_best_subframe],
  104620. encoder->private_->abs_residual_partition_sums,
  104621. encoder->private_->raw_bits_per_partition,
  104622. encoder->private_->lp_coeff[lpc_order-1],
  104623. frame_header->blocksize,
  104624. subframe_bps,
  104625. lpc_order,
  104626. qlp_coeff_precision,
  104627. rice_parameter,
  104628. rice_parameter_limit,
  104629. min_partition_order,
  104630. max_partition_order,
  104631. encoder->protected_->do_escape_coding,
  104632. encoder->protected_->rice_parameter_search_dist,
  104633. subframe[!_best_subframe],
  104634. partitioned_rice_contents[!_best_subframe]
  104635. );
  104636. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  104637. if(_candidate_bits < _best_bits) {
  104638. _best_subframe = !_best_subframe;
  104639. _best_bits = _candidate_bits;
  104640. }
  104641. }
  104642. }
  104643. }
  104644. }
  104645. }
  104646. }
  104647. }
  104648. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  104649. }
  104650. }
  104651. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  104652. if(_best_bits == UINT_MAX) {
  104653. FLAC__ASSERT(_best_subframe == 0);
  104654. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104655. }
  104656. *best_subframe = _best_subframe;
  104657. *best_bits = _best_bits;
  104658. return true;
  104659. }
  104660. FLAC__bool add_subframe_(
  104661. FLAC__StreamEncoder *encoder,
  104662. unsigned blocksize,
  104663. unsigned subframe_bps,
  104664. const FLAC__Subframe *subframe,
  104665. FLAC__BitWriter *frame
  104666. )
  104667. {
  104668. switch(subframe->type) {
  104669. case FLAC__SUBFRAME_TYPE_CONSTANT:
  104670. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  104671. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104672. return false;
  104673. }
  104674. break;
  104675. case FLAC__SUBFRAME_TYPE_FIXED:
  104676. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  104677. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104678. return false;
  104679. }
  104680. break;
  104681. case FLAC__SUBFRAME_TYPE_LPC:
  104682. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  104683. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104684. return false;
  104685. }
  104686. break;
  104687. case FLAC__SUBFRAME_TYPE_VERBATIM:
  104688. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  104689. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104690. return false;
  104691. }
  104692. break;
  104693. default:
  104694. FLAC__ASSERT(0);
  104695. }
  104696. return true;
  104697. }
  104698. #define SPOTCHECK_ESTIMATE 0
  104699. #if SPOTCHECK_ESTIMATE
  104700. static void spotcheck_subframe_estimate_(
  104701. FLAC__StreamEncoder *encoder,
  104702. unsigned blocksize,
  104703. unsigned subframe_bps,
  104704. const FLAC__Subframe *subframe,
  104705. unsigned estimate
  104706. )
  104707. {
  104708. FLAC__bool ret;
  104709. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  104710. if(frame == 0) {
  104711. fprintf(stderr, "EST: can't allocate frame\n");
  104712. return;
  104713. }
  104714. if(!FLAC__bitwriter_init(frame)) {
  104715. fprintf(stderr, "EST: can't init frame\n");
  104716. return;
  104717. }
  104718. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  104719. FLAC__ASSERT(ret);
  104720. {
  104721. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  104722. if(estimate != actual)
  104723. 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);
  104724. }
  104725. FLAC__bitwriter_delete(frame);
  104726. }
  104727. #endif
  104728. unsigned evaluate_constant_subframe_(
  104729. FLAC__StreamEncoder *encoder,
  104730. const FLAC__int32 signal,
  104731. unsigned blocksize,
  104732. unsigned subframe_bps,
  104733. FLAC__Subframe *subframe
  104734. )
  104735. {
  104736. unsigned estimate;
  104737. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  104738. subframe->data.constant.value = signal;
  104739. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  104740. #if SPOTCHECK_ESTIMATE
  104741. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104742. #else
  104743. (void)encoder, (void)blocksize;
  104744. #endif
  104745. return estimate;
  104746. }
  104747. unsigned evaluate_fixed_subframe_(
  104748. FLAC__StreamEncoder *encoder,
  104749. const FLAC__int32 signal[],
  104750. FLAC__int32 residual[],
  104751. FLAC__uint64 abs_residual_partition_sums[],
  104752. unsigned raw_bits_per_partition[],
  104753. unsigned blocksize,
  104754. unsigned subframe_bps,
  104755. unsigned order,
  104756. unsigned rice_parameter,
  104757. unsigned rice_parameter_limit,
  104758. unsigned min_partition_order,
  104759. unsigned max_partition_order,
  104760. FLAC__bool do_escape_coding,
  104761. unsigned rice_parameter_search_dist,
  104762. FLAC__Subframe *subframe,
  104763. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  104764. )
  104765. {
  104766. unsigned i, residual_bits, estimate;
  104767. const unsigned residual_samples = blocksize - order;
  104768. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  104769. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  104770. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  104771. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  104772. subframe->data.fixed.residual = residual;
  104773. residual_bits =
  104774. find_best_partition_order_(
  104775. encoder->private_,
  104776. residual,
  104777. abs_residual_partition_sums,
  104778. raw_bits_per_partition,
  104779. residual_samples,
  104780. order,
  104781. rice_parameter,
  104782. rice_parameter_limit,
  104783. min_partition_order,
  104784. max_partition_order,
  104785. subframe_bps,
  104786. do_escape_coding,
  104787. rice_parameter_search_dist,
  104788. &subframe->data.fixed.entropy_coding_method
  104789. );
  104790. subframe->data.fixed.order = order;
  104791. for(i = 0; i < order; i++)
  104792. subframe->data.fixed.warmup[i] = signal[i];
  104793. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  104794. #if SPOTCHECK_ESTIMATE
  104795. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104796. #endif
  104797. return estimate;
  104798. }
  104799. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104800. unsigned evaluate_lpc_subframe_(
  104801. FLAC__StreamEncoder *encoder,
  104802. const FLAC__int32 signal[],
  104803. FLAC__int32 residual[],
  104804. FLAC__uint64 abs_residual_partition_sums[],
  104805. unsigned raw_bits_per_partition[],
  104806. const FLAC__real lp_coeff[],
  104807. unsigned blocksize,
  104808. unsigned subframe_bps,
  104809. unsigned order,
  104810. unsigned qlp_coeff_precision,
  104811. unsigned rice_parameter,
  104812. unsigned rice_parameter_limit,
  104813. unsigned min_partition_order,
  104814. unsigned max_partition_order,
  104815. FLAC__bool do_escape_coding,
  104816. unsigned rice_parameter_search_dist,
  104817. FLAC__Subframe *subframe,
  104818. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  104819. )
  104820. {
  104821. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  104822. unsigned i, residual_bits, estimate;
  104823. int quantization, ret;
  104824. const unsigned residual_samples = blocksize - order;
  104825. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  104826. if(subframe_bps <= 16) {
  104827. FLAC__ASSERT(order > 0);
  104828. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  104829. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  104830. }
  104831. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  104832. if(ret != 0)
  104833. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  104834. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  104835. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  104836. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104837. else
  104838. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104839. else
  104840. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104841. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  104842. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  104843. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  104844. subframe->data.lpc.residual = residual;
  104845. residual_bits =
  104846. find_best_partition_order_(
  104847. encoder->private_,
  104848. residual,
  104849. abs_residual_partition_sums,
  104850. raw_bits_per_partition,
  104851. residual_samples,
  104852. order,
  104853. rice_parameter,
  104854. rice_parameter_limit,
  104855. min_partition_order,
  104856. max_partition_order,
  104857. subframe_bps,
  104858. do_escape_coding,
  104859. rice_parameter_search_dist,
  104860. &subframe->data.lpc.entropy_coding_method
  104861. );
  104862. subframe->data.lpc.order = order;
  104863. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  104864. subframe->data.lpc.quantization_level = quantization;
  104865. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  104866. for(i = 0; i < order; i++)
  104867. subframe->data.lpc.warmup[i] = signal[i];
  104868. 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;
  104869. #if SPOTCHECK_ESTIMATE
  104870. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104871. #endif
  104872. return estimate;
  104873. }
  104874. #endif
  104875. unsigned evaluate_verbatim_subframe_(
  104876. FLAC__StreamEncoder *encoder,
  104877. const FLAC__int32 signal[],
  104878. unsigned blocksize,
  104879. unsigned subframe_bps,
  104880. FLAC__Subframe *subframe
  104881. )
  104882. {
  104883. unsigned estimate;
  104884. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  104885. subframe->data.verbatim.data = signal;
  104886. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  104887. #if SPOTCHECK_ESTIMATE
  104888. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104889. #else
  104890. (void)encoder;
  104891. #endif
  104892. return estimate;
  104893. }
  104894. unsigned find_best_partition_order_(
  104895. FLAC__StreamEncoderPrivate *private_,
  104896. const FLAC__int32 residual[],
  104897. FLAC__uint64 abs_residual_partition_sums[],
  104898. unsigned raw_bits_per_partition[],
  104899. unsigned residual_samples,
  104900. unsigned predictor_order,
  104901. unsigned rice_parameter,
  104902. unsigned rice_parameter_limit,
  104903. unsigned min_partition_order,
  104904. unsigned max_partition_order,
  104905. unsigned bps,
  104906. FLAC__bool do_escape_coding,
  104907. unsigned rice_parameter_search_dist,
  104908. FLAC__EntropyCodingMethod *best_ecm
  104909. )
  104910. {
  104911. unsigned residual_bits, best_residual_bits = 0;
  104912. unsigned best_parameters_index = 0;
  104913. unsigned best_partition_order = 0;
  104914. const unsigned blocksize = residual_samples + predictor_order;
  104915. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  104916. min_partition_order = min(min_partition_order, max_partition_order);
  104917. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  104918. if(do_escape_coding)
  104919. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  104920. {
  104921. int partition_order;
  104922. unsigned sum;
  104923. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  104924. if(!
  104925. set_partitioned_rice_(
  104926. #ifdef EXACT_RICE_BITS_CALCULATION
  104927. residual,
  104928. #endif
  104929. abs_residual_partition_sums+sum,
  104930. raw_bits_per_partition+sum,
  104931. residual_samples,
  104932. predictor_order,
  104933. rice_parameter,
  104934. rice_parameter_limit,
  104935. rice_parameter_search_dist,
  104936. (unsigned)partition_order,
  104937. do_escape_coding,
  104938. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  104939. &residual_bits
  104940. )
  104941. )
  104942. {
  104943. FLAC__ASSERT(best_residual_bits != 0);
  104944. break;
  104945. }
  104946. sum += 1u << partition_order;
  104947. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  104948. best_residual_bits = residual_bits;
  104949. best_parameters_index = !best_parameters_index;
  104950. best_partition_order = partition_order;
  104951. }
  104952. }
  104953. }
  104954. best_ecm->data.partitioned_rice.order = best_partition_order;
  104955. {
  104956. /*
  104957. * We are allowed to de-const the pointer based on our special
  104958. * knowledge; it is const to the outside world.
  104959. */
  104960. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  104961. unsigned partition;
  104962. /* save best parameters and raw_bits */
  104963. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  104964. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  104965. if(do_escape_coding)
  104966. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  104967. /*
  104968. * Now need to check if the type should be changed to
  104969. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  104970. * size of the rice parameters.
  104971. */
  104972. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  104973. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  104974. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  104975. break;
  104976. }
  104977. }
  104978. }
  104979. return best_residual_bits;
  104980. }
  104981. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  104982. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  104983. const FLAC__int32 residual[],
  104984. FLAC__uint64 abs_residual_partition_sums[],
  104985. unsigned blocksize,
  104986. unsigned predictor_order,
  104987. unsigned min_partition_order,
  104988. unsigned max_partition_order
  104989. );
  104990. #endif
  104991. void precompute_partition_info_sums_(
  104992. const FLAC__int32 residual[],
  104993. FLAC__uint64 abs_residual_partition_sums[],
  104994. unsigned residual_samples,
  104995. unsigned predictor_order,
  104996. unsigned min_partition_order,
  104997. unsigned max_partition_order,
  104998. unsigned bps
  104999. )
  105000. {
  105001. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105002. unsigned partitions = 1u << max_partition_order;
  105003. FLAC__ASSERT(default_partition_samples > predictor_order);
  105004. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105005. /* slightly pessimistic but still catches all common cases */
  105006. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105007. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105008. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105009. return;
  105010. }
  105011. #endif
  105012. /* first do max_partition_order */
  105013. {
  105014. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105015. /* slightly pessimistic but still catches all common cases */
  105016. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105017. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105018. FLAC__uint32 abs_residual_partition_sum;
  105019. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105020. end += default_partition_samples;
  105021. abs_residual_partition_sum = 0;
  105022. for( ; residual_sample < end; residual_sample++)
  105023. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105024. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105025. }
  105026. }
  105027. else { /* have to pessimistically use 64 bits for accumulator */
  105028. FLAC__uint64 abs_residual_partition_sum;
  105029. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105030. end += default_partition_samples;
  105031. abs_residual_partition_sum = 0;
  105032. for( ; residual_sample < end; residual_sample++)
  105033. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105034. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105035. }
  105036. }
  105037. }
  105038. /* now merge partitions for lower orders */
  105039. {
  105040. unsigned from_partition = 0, to_partition = partitions;
  105041. int partition_order;
  105042. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105043. unsigned i;
  105044. partitions >>= 1;
  105045. for(i = 0; i < partitions; i++) {
  105046. abs_residual_partition_sums[to_partition++] =
  105047. abs_residual_partition_sums[from_partition ] +
  105048. abs_residual_partition_sums[from_partition+1];
  105049. from_partition += 2;
  105050. }
  105051. }
  105052. }
  105053. }
  105054. void precompute_partition_info_escapes_(
  105055. const FLAC__int32 residual[],
  105056. unsigned raw_bits_per_partition[],
  105057. unsigned residual_samples,
  105058. unsigned predictor_order,
  105059. unsigned min_partition_order,
  105060. unsigned max_partition_order
  105061. )
  105062. {
  105063. int partition_order;
  105064. unsigned from_partition, to_partition = 0;
  105065. const unsigned blocksize = residual_samples + predictor_order;
  105066. /* first do max_partition_order */
  105067. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105068. FLAC__int32 r;
  105069. FLAC__uint32 rmax;
  105070. unsigned partition, partition_sample, partition_samples, residual_sample;
  105071. const unsigned partitions = 1u << partition_order;
  105072. const unsigned default_partition_samples = blocksize >> partition_order;
  105073. FLAC__ASSERT(default_partition_samples > predictor_order);
  105074. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105075. partition_samples = default_partition_samples;
  105076. if(partition == 0)
  105077. partition_samples -= predictor_order;
  105078. rmax = 0;
  105079. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105080. r = residual[residual_sample++];
  105081. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105082. if(r < 0)
  105083. rmax |= ~r;
  105084. else
  105085. rmax |= r;
  105086. }
  105087. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105088. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105089. }
  105090. to_partition = partitions;
  105091. break; /*@@@ yuck, should remove the 'for' loop instead */
  105092. }
  105093. /* now merge partitions for lower orders */
  105094. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105095. unsigned m;
  105096. unsigned i;
  105097. const unsigned partitions = 1u << partition_order;
  105098. for(i = 0; i < partitions; i++) {
  105099. m = raw_bits_per_partition[from_partition];
  105100. from_partition++;
  105101. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105102. from_partition++;
  105103. to_partition++;
  105104. }
  105105. }
  105106. }
  105107. #ifdef EXACT_RICE_BITS_CALCULATION
  105108. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105109. const unsigned rice_parameter,
  105110. const unsigned partition_samples,
  105111. const FLAC__int32 *residual
  105112. )
  105113. {
  105114. unsigned i, partition_bits =
  105115. 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 */
  105116. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105117. ;
  105118. for(i = 0; i < partition_samples; i++)
  105119. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105120. return partition_bits;
  105121. }
  105122. #else
  105123. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105124. const unsigned rice_parameter,
  105125. const unsigned partition_samples,
  105126. const FLAC__uint64 abs_residual_partition_sum
  105127. )
  105128. {
  105129. return
  105130. 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 */
  105131. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105132. (
  105133. rice_parameter?
  105134. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105135. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105136. )
  105137. - (partition_samples >> 1)
  105138. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105139. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105140. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105141. * So the subtraction term tries to guess how many extra bits were contributed.
  105142. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105143. */
  105144. ;
  105145. }
  105146. #endif
  105147. FLAC__bool set_partitioned_rice_(
  105148. #ifdef EXACT_RICE_BITS_CALCULATION
  105149. const FLAC__int32 residual[],
  105150. #endif
  105151. const FLAC__uint64 abs_residual_partition_sums[],
  105152. const unsigned raw_bits_per_partition[],
  105153. const unsigned residual_samples,
  105154. const unsigned predictor_order,
  105155. const unsigned suggested_rice_parameter,
  105156. const unsigned rice_parameter_limit,
  105157. const unsigned rice_parameter_search_dist,
  105158. const unsigned partition_order,
  105159. const FLAC__bool search_for_escapes,
  105160. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105161. unsigned *bits
  105162. )
  105163. {
  105164. unsigned rice_parameter, partition_bits;
  105165. unsigned best_partition_bits, best_rice_parameter = 0;
  105166. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105167. unsigned *parameters, *raw_bits;
  105168. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105169. unsigned min_rice_parameter, max_rice_parameter;
  105170. #else
  105171. (void)rice_parameter_search_dist;
  105172. #endif
  105173. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105174. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105175. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105176. parameters = partitioned_rice_contents->parameters;
  105177. raw_bits = partitioned_rice_contents->raw_bits;
  105178. if(partition_order == 0) {
  105179. best_partition_bits = (unsigned)(-1);
  105180. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105181. if(rice_parameter_search_dist) {
  105182. if(suggested_rice_parameter < rice_parameter_search_dist)
  105183. min_rice_parameter = 0;
  105184. else
  105185. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105186. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105187. if(max_rice_parameter >= rice_parameter_limit) {
  105188. #ifdef DEBUG_VERBOSE
  105189. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105190. #endif
  105191. max_rice_parameter = rice_parameter_limit - 1;
  105192. }
  105193. }
  105194. else
  105195. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105196. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105197. #else
  105198. rice_parameter = suggested_rice_parameter;
  105199. #endif
  105200. #ifdef EXACT_RICE_BITS_CALCULATION
  105201. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105202. #else
  105203. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105204. #endif
  105205. if(partition_bits < best_partition_bits) {
  105206. best_rice_parameter = rice_parameter;
  105207. best_partition_bits = partition_bits;
  105208. }
  105209. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105210. }
  105211. #endif
  105212. if(search_for_escapes) {
  105213. 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;
  105214. if(partition_bits <= best_partition_bits) {
  105215. raw_bits[0] = raw_bits_per_partition[0];
  105216. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105217. best_partition_bits = partition_bits;
  105218. }
  105219. else
  105220. raw_bits[0] = 0;
  105221. }
  105222. parameters[0] = best_rice_parameter;
  105223. bits_ += best_partition_bits;
  105224. }
  105225. else {
  105226. unsigned partition, residual_sample;
  105227. unsigned partition_samples;
  105228. FLAC__uint64 mean, k;
  105229. const unsigned partitions = 1u << partition_order;
  105230. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105231. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105232. if(partition == 0) {
  105233. if(partition_samples <= predictor_order)
  105234. return false;
  105235. else
  105236. partition_samples -= predictor_order;
  105237. }
  105238. mean = abs_residual_partition_sums[partition];
  105239. /* we are basically calculating the size in bits of the
  105240. * average residual magnitude in the partition:
  105241. * rice_parameter = floor(log2(mean/partition_samples))
  105242. * 'mean' is not a good name for the variable, it is
  105243. * actually the sum of magnitudes of all residual values
  105244. * in the partition, so the actual mean is
  105245. * mean/partition_samples
  105246. */
  105247. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  105248. ;
  105249. if(rice_parameter >= rice_parameter_limit) {
  105250. #ifdef DEBUG_VERBOSE
  105251. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  105252. #endif
  105253. rice_parameter = rice_parameter_limit - 1;
  105254. }
  105255. best_partition_bits = (unsigned)(-1);
  105256. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105257. if(rice_parameter_search_dist) {
  105258. if(rice_parameter < rice_parameter_search_dist)
  105259. min_rice_parameter = 0;
  105260. else
  105261. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  105262. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  105263. if(max_rice_parameter >= rice_parameter_limit) {
  105264. #ifdef DEBUG_VERBOSE
  105265. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  105266. #endif
  105267. max_rice_parameter = rice_parameter_limit - 1;
  105268. }
  105269. }
  105270. else
  105271. min_rice_parameter = max_rice_parameter = rice_parameter;
  105272. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105273. #endif
  105274. #ifdef EXACT_RICE_BITS_CALCULATION
  105275. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  105276. #else
  105277. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  105278. #endif
  105279. if(partition_bits < best_partition_bits) {
  105280. best_rice_parameter = rice_parameter;
  105281. best_partition_bits = partition_bits;
  105282. }
  105283. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105284. }
  105285. #endif
  105286. if(search_for_escapes) {
  105287. 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;
  105288. if(partition_bits <= best_partition_bits) {
  105289. raw_bits[partition] = raw_bits_per_partition[partition];
  105290. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105291. best_partition_bits = partition_bits;
  105292. }
  105293. else
  105294. raw_bits[partition] = 0;
  105295. }
  105296. parameters[partition] = best_rice_parameter;
  105297. bits_ += best_partition_bits;
  105298. residual_sample += partition_samples;
  105299. }
  105300. }
  105301. *bits = bits_;
  105302. return true;
  105303. }
  105304. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105305. {
  105306. unsigned i, shift;
  105307. FLAC__int32 x = 0;
  105308. for(i = 0; i < samples && !(x&1); i++)
  105309. x |= signal[i];
  105310. if(x == 0) {
  105311. shift = 0;
  105312. }
  105313. else {
  105314. for(shift = 0; !(x&1); shift++)
  105315. x >>= 1;
  105316. }
  105317. if(shift > 0) {
  105318. for(i = 0; i < samples; i++)
  105319. signal[i] >>= shift;
  105320. }
  105321. return shift;
  105322. }
  105323. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105324. {
  105325. unsigned channel;
  105326. for(channel = 0; channel < channels; channel++)
  105327. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105328. fifo->tail += wide_samples;
  105329. FLAC__ASSERT(fifo->tail <= fifo->size);
  105330. }
  105331. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105332. {
  105333. unsigned channel;
  105334. unsigned sample, wide_sample;
  105335. unsigned tail = fifo->tail;
  105336. sample = input_offset * channels;
  105337. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105338. for(channel = 0; channel < channels; channel++)
  105339. fifo->data[channel][tail] = input[sample++];
  105340. tail++;
  105341. }
  105342. fifo->tail = tail;
  105343. FLAC__ASSERT(fifo->tail <= fifo->size);
  105344. }
  105345. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105346. {
  105347. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105348. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105349. (void)decoder;
  105350. if(encoder->private_->verify.needs_magic_hack) {
  105351. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105352. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105353. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105354. encoder->private_->verify.needs_magic_hack = false;
  105355. }
  105356. else {
  105357. if(encoded_bytes == 0) {
  105358. /*
  105359. * If we get here, a FIFO underflow has occurred,
  105360. * which means there is a bug somewhere.
  105361. */
  105362. FLAC__ASSERT(0);
  105363. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  105364. }
  105365. else if(encoded_bytes < *bytes)
  105366. *bytes = encoded_bytes;
  105367. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  105368. encoder->private_->verify.output.data += *bytes;
  105369. encoder->private_->verify.output.bytes -= *bytes;
  105370. }
  105371. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105372. }
  105373. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  105374. {
  105375. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  105376. unsigned channel;
  105377. const unsigned channels = frame->header.channels;
  105378. const unsigned blocksize = frame->header.blocksize;
  105379. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  105380. (void)decoder;
  105381. for(channel = 0; channel < channels; channel++) {
  105382. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  105383. unsigned i, sample = 0;
  105384. FLAC__int32 expect = 0, got = 0;
  105385. for(i = 0; i < blocksize; i++) {
  105386. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  105387. sample = i;
  105388. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  105389. got = (FLAC__int32)buffer[channel][i];
  105390. break;
  105391. }
  105392. }
  105393. FLAC__ASSERT(i < blocksize);
  105394. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  105395. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  105396. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  105397. encoder->private_->verify.error_stats.channel = channel;
  105398. encoder->private_->verify.error_stats.sample = sample;
  105399. encoder->private_->verify.error_stats.expected = expect;
  105400. encoder->private_->verify.error_stats.got = got;
  105401. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  105402. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  105403. }
  105404. }
  105405. /* dequeue the frame from the fifo */
  105406. encoder->private_->verify.input_fifo.tail -= blocksize;
  105407. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  105408. for(channel = 0; channel < channels; channel++)
  105409. 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]));
  105410. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  105411. }
  105412. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  105413. {
  105414. (void)decoder, (void)metadata, (void)client_data;
  105415. }
  105416. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  105417. {
  105418. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105419. (void)decoder, (void)status;
  105420. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  105421. }
  105422. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105423. {
  105424. (void)client_data;
  105425. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  105426. if (*bytes == 0) {
  105427. if (feof(encoder->private_->file))
  105428. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  105429. else if (ferror(encoder->private_->file))
  105430. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  105431. }
  105432. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  105433. }
  105434. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  105435. {
  105436. (void)client_data;
  105437. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  105438. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  105439. else
  105440. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  105441. }
  105442. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  105443. {
  105444. off_t offset;
  105445. (void)client_data;
  105446. offset = ftello(encoder->private_->file);
  105447. if(offset < 0) {
  105448. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  105449. }
  105450. else {
  105451. *absolute_byte_offset = (FLAC__uint64)offset;
  105452. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  105453. }
  105454. }
  105455. #ifdef FLAC__VALGRIND_TESTING
  105456. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  105457. {
  105458. size_t ret = fwrite(ptr, size, nmemb, stream);
  105459. if(!ferror(stream))
  105460. fflush(stream);
  105461. return ret;
  105462. }
  105463. #else
  105464. #define local__fwrite fwrite
  105465. #endif
  105466. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  105467. {
  105468. (void)client_data, (void)current_frame;
  105469. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  105470. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  105471. #if FLAC__HAS_OGG
  105472. /* We would like to be able to use 'samples > 0' in the
  105473. * clause here but currently because of the nature of our
  105474. * Ogg writing implementation, 'samples' is always 0 (see
  105475. * ogg_encoder_aspect.c). The downside is extra progress
  105476. * callbacks.
  105477. */
  105478. encoder->private_->is_ogg? true :
  105479. #endif
  105480. samples > 0
  105481. );
  105482. if(call_it) {
  105483. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  105484. * because at this point in the callback chain, the stats
  105485. * have not been updated. Only after we return and control
  105486. * gets back to write_frame_() are the stats updated
  105487. */
  105488. 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);
  105489. }
  105490. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  105491. }
  105492. else
  105493. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  105494. }
  105495. /*
  105496. * This will forcibly set stdout to binary mode (for OSes that require it)
  105497. */
  105498. FILE *get_binary_stdout_(void)
  105499. {
  105500. /* if something breaks here it is probably due to the presence or
  105501. * absence of an underscore before the identifiers 'setmode',
  105502. * 'fileno', and/or 'O_BINARY'; check your system header files.
  105503. */
  105504. #if defined _MSC_VER || defined __MINGW32__
  105505. _setmode(_fileno(stdout), _O_BINARY);
  105506. #elif defined __CYGWIN__
  105507. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  105508. setmode(_fileno(stdout), _O_BINARY);
  105509. #elif defined __EMX__
  105510. setmode(fileno(stdout), O_BINARY);
  105511. #endif
  105512. return stdout;
  105513. }
  105514. #endif
  105515. /*** End of inlined file: stream_encoder.c ***/
  105516. /*** Start of inlined file: stream_encoder_framing.c ***/
  105517. /*** Start of inlined file: juce_FlacHeader.h ***/
  105518. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  105519. // tasks..
  105520. #define VERSION "1.2.1"
  105521. #define FLAC__NO_DLL 1
  105522. #if JUCE_MSVC
  105523. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  105524. #endif
  105525. #if JUCE_MAC
  105526. #define FLAC__SYS_DARWIN 1
  105527. #endif
  105528. /*** End of inlined file: juce_FlacHeader.h ***/
  105529. #if JUCE_USE_FLAC
  105530. #if HAVE_CONFIG_H
  105531. # include <config.h>
  105532. #endif
  105533. #include <stdio.h>
  105534. #include <string.h> /* for strlen() */
  105535. #ifdef max
  105536. #undef max
  105537. #endif
  105538. #define max(x,y) ((x)>(y)?(x):(y))
  105539. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  105540. 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);
  105541. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  105542. {
  105543. unsigned i, j;
  105544. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  105545. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  105546. return false;
  105547. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  105548. return false;
  105549. /*
  105550. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  105551. */
  105552. i = metadata->length;
  105553. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  105554. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  105555. i -= metadata->data.vorbis_comment.vendor_string.length;
  105556. i += vendor_string_length;
  105557. }
  105558. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  105559. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  105560. return false;
  105561. switch(metadata->type) {
  105562. case FLAC__METADATA_TYPE_STREAMINFO:
  105563. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  105564. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  105565. return false;
  105566. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  105567. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  105568. return false;
  105569. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  105570. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  105571. return false;
  105572. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  105573. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  105574. return false;
  105575. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  105576. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  105577. return false;
  105578. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  105579. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  105580. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  105581. return false;
  105582. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  105583. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105584. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  105585. return false;
  105586. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  105587. return false;
  105588. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  105589. return false;
  105590. break;
  105591. case FLAC__METADATA_TYPE_PADDING:
  105592. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  105593. return false;
  105594. break;
  105595. case FLAC__METADATA_TYPE_APPLICATION:
  105596. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  105597. return false;
  105598. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  105599. return false;
  105600. break;
  105601. case FLAC__METADATA_TYPE_SEEKTABLE:
  105602. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  105603. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  105604. return false;
  105605. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  105606. return false;
  105607. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  105608. return false;
  105609. }
  105610. break;
  105611. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  105612. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  105613. return false;
  105614. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  105615. return false;
  105616. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  105617. return false;
  105618. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  105619. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  105620. return false;
  105621. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  105622. return false;
  105623. }
  105624. break;
  105625. case FLAC__METADATA_TYPE_CUESHEET:
  105626. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  105627. 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))
  105628. return false;
  105629. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  105630. return false;
  105631. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  105632. return false;
  105633. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  105634. return false;
  105635. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  105636. return false;
  105637. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  105638. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  105639. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  105640. return false;
  105641. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  105642. return false;
  105643. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  105644. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  105645. return false;
  105646. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  105647. return false;
  105648. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  105649. return false;
  105650. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  105651. return false;
  105652. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  105653. return false;
  105654. for(j = 0; j < track->num_indices; j++) {
  105655. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  105656. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  105657. return false;
  105658. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  105659. return false;
  105660. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  105661. return false;
  105662. }
  105663. }
  105664. break;
  105665. case FLAC__METADATA_TYPE_PICTURE:
  105666. {
  105667. size_t len;
  105668. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  105669. return false;
  105670. len = strlen(metadata->data.picture.mime_type);
  105671. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  105672. return false;
  105673. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  105674. return false;
  105675. len = strlen((const char *)metadata->data.picture.description);
  105676. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  105677. return false;
  105678. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  105679. return false;
  105680. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  105681. return false;
  105682. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  105683. return false;
  105684. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  105685. return false;
  105686. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  105687. return false;
  105688. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  105689. return false;
  105690. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  105691. return false;
  105692. }
  105693. break;
  105694. default:
  105695. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  105696. return false;
  105697. break;
  105698. }
  105699. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105700. return true;
  105701. }
  105702. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  105703. {
  105704. unsigned u, blocksize_hint, sample_rate_hint;
  105705. FLAC__byte crc;
  105706. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105707. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  105708. return false;
  105709. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  105710. return false;
  105711. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  105712. return false;
  105713. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  105714. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  105715. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  105716. blocksize_hint = 0;
  105717. switch(header->blocksize) {
  105718. case 192: u = 1; break;
  105719. case 576: u = 2; break;
  105720. case 1152: u = 3; break;
  105721. case 2304: u = 4; break;
  105722. case 4608: u = 5; break;
  105723. case 256: u = 8; break;
  105724. case 512: u = 9; break;
  105725. case 1024: u = 10; break;
  105726. case 2048: u = 11; break;
  105727. case 4096: u = 12; break;
  105728. case 8192: u = 13; break;
  105729. case 16384: u = 14; break;
  105730. case 32768: u = 15; break;
  105731. default:
  105732. if(header->blocksize <= 0x100)
  105733. blocksize_hint = u = 6;
  105734. else
  105735. blocksize_hint = u = 7;
  105736. break;
  105737. }
  105738. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  105739. return false;
  105740. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  105741. sample_rate_hint = 0;
  105742. switch(header->sample_rate) {
  105743. case 88200: u = 1; break;
  105744. case 176400: u = 2; break;
  105745. case 192000: u = 3; break;
  105746. case 8000: u = 4; break;
  105747. case 16000: u = 5; break;
  105748. case 22050: u = 6; break;
  105749. case 24000: u = 7; break;
  105750. case 32000: u = 8; break;
  105751. case 44100: u = 9; break;
  105752. case 48000: u = 10; break;
  105753. case 96000: u = 11; break;
  105754. default:
  105755. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  105756. sample_rate_hint = u = 12;
  105757. else if(header->sample_rate % 10 == 0)
  105758. sample_rate_hint = u = 14;
  105759. else if(header->sample_rate <= 0xffff)
  105760. sample_rate_hint = u = 13;
  105761. else
  105762. u = 0;
  105763. break;
  105764. }
  105765. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  105766. return false;
  105767. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  105768. switch(header->channel_assignment) {
  105769. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105770. u = header->channels - 1;
  105771. break;
  105772. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105773. FLAC__ASSERT(header->channels == 2);
  105774. u = 8;
  105775. break;
  105776. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105777. FLAC__ASSERT(header->channels == 2);
  105778. u = 9;
  105779. break;
  105780. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105781. FLAC__ASSERT(header->channels == 2);
  105782. u = 10;
  105783. break;
  105784. default:
  105785. FLAC__ASSERT(0);
  105786. }
  105787. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  105788. return false;
  105789. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105790. switch(header->bits_per_sample) {
  105791. case 8 : u = 1; break;
  105792. case 12: u = 2; break;
  105793. case 16: u = 4; break;
  105794. case 20: u = 5; break;
  105795. case 24: u = 6; break;
  105796. default: u = 0; break;
  105797. }
  105798. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  105799. return false;
  105800. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  105801. return false;
  105802. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  105803. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  105804. return false;
  105805. }
  105806. else {
  105807. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  105808. return false;
  105809. }
  105810. if(blocksize_hint)
  105811. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  105812. return false;
  105813. switch(sample_rate_hint) {
  105814. case 12:
  105815. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  105816. return false;
  105817. break;
  105818. case 13:
  105819. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  105820. return false;
  105821. break;
  105822. case 14:
  105823. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  105824. return false;
  105825. break;
  105826. }
  105827. /* write the CRC */
  105828. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  105829. return false;
  105830. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  105831. return false;
  105832. return true;
  105833. }
  105834. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105835. {
  105836. FLAC__bool ok;
  105837. ok =
  105838. 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) &&
  105839. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  105840. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  105841. ;
  105842. return ok;
  105843. }
  105844. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105845. {
  105846. unsigned i;
  105847. 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))
  105848. return false;
  105849. if(wasted_bits)
  105850. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105851. return false;
  105852. for(i = 0; i < subframe->order; i++)
  105853. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  105854. return false;
  105855. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  105856. return false;
  105857. switch(subframe->entropy_coding_method.type) {
  105858. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105859. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105860. if(!add_residual_partitioned_rice_(
  105861. bw,
  105862. subframe->residual,
  105863. residual_samples,
  105864. subframe->order,
  105865. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  105866. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  105867. subframe->entropy_coding_method.data.partitioned_rice.order,
  105868. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  105869. ))
  105870. return false;
  105871. break;
  105872. default:
  105873. FLAC__ASSERT(0);
  105874. }
  105875. return true;
  105876. }
  105877. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105878. {
  105879. unsigned i;
  105880. 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))
  105881. return false;
  105882. if(wasted_bits)
  105883. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105884. return false;
  105885. for(i = 0; i < subframe->order; i++)
  105886. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  105887. return false;
  105888. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  105889. return false;
  105890. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  105891. return false;
  105892. for(i = 0; i < subframe->order; i++)
  105893. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  105894. return false;
  105895. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  105896. return false;
  105897. switch(subframe->entropy_coding_method.type) {
  105898. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105899. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105900. if(!add_residual_partitioned_rice_(
  105901. bw,
  105902. subframe->residual,
  105903. residual_samples,
  105904. subframe->order,
  105905. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  105906. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  105907. subframe->entropy_coding_method.data.partitioned_rice.order,
  105908. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  105909. ))
  105910. return false;
  105911. break;
  105912. default:
  105913. FLAC__ASSERT(0);
  105914. }
  105915. return true;
  105916. }
  105917. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105918. {
  105919. unsigned i;
  105920. const FLAC__int32 *signal = subframe->data;
  105921. 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))
  105922. return false;
  105923. if(wasted_bits)
  105924. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105925. return false;
  105926. for(i = 0; i < samples; i++)
  105927. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  105928. return false;
  105929. return true;
  105930. }
  105931. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  105932. {
  105933. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  105934. return false;
  105935. switch(method->type) {
  105936. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105937. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105938. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  105939. return false;
  105940. break;
  105941. default:
  105942. FLAC__ASSERT(0);
  105943. }
  105944. return true;
  105945. }
  105946. 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)
  105947. {
  105948. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  105949. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  105950. if(partition_order == 0) {
  105951. unsigned i;
  105952. if(raw_bits[0] == 0) {
  105953. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  105954. return false;
  105955. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  105956. return false;
  105957. }
  105958. else {
  105959. FLAC__ASSERT(rice_parameters[0] == 0);
  105960. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  105961. return false;
  105962. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  105963. return false;
  105964. for(i = 0; i < residual_samples; i++) {
  105965. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  105966. return false;
  105967. }
  105968. }
  105969. return true;
  105970. }
  105971. else {
  105972. unsigned i, j, k = 0, k_last = 0;
  105973. unsigned partition_samples;
  105974. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  105975. for(i = 0; i < (1u<<partition_order); i++) {
  105976. partition_samples = default_partition_samples;
  105977. if(i == 0)
  105978. partition_samples -= predictor_order;
  105979. k += partition_samples;
  105980. if(raw_bits[i] == 0) {
  105981. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  105982. return false;
  105983. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  105984. return false;
  105985. }
  105986. else {
  105987. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  105988. return false;
  105989. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  105990. return false;
  105991. for(j = k_last; j < k; j++) {
  105992. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  105993. return false;
  105994. }
  105995. }
  105996. k_last = k;
  105997. }
  105998. return true;
  105999. }
  106000. }
  106001. #endif
  106002. /*** End of inlined file: stream_encoder_framing.c ***/
  106003. /*** Start of inlined file: window_flac.c ***/
  106004. /*** Start of inlined file: juce_FlacHeader.h ***/
  106005. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106006. // tasks..
  106007. #define VERSION "1.2.1"
  106008. #define FLAC__NO_DLL 1
  106009. #if JUCE_MSVC
  106010. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106011. #endif
  106012. #if JUCE_MAC
  106013. #define FLAC__SYS_DARWIN 1
  106014. #endif
  106015. /*** End of inlined file: juce_FlacHeader.h ***/
  106016. #if JUCE_USE_FLAC
  106017. #if HAVE_CONFIG_H
  106018. # include <config.h>
  106019. #endif
  106020. #include <math.h>
  106021. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106022. #ifndef M_PI
  106023. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106024. #define M_PI 3.14159265358979323846
  106025. #endif
  106026. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106027. {
  106028. const FLAC__int32 N = L - 1;
  106029. FLAC__int32 n;
  106030. if (L & 1) {
  106031. for (n = 0; n <= N/2; n++)
  106032. window[n] = 2.0f * n / (float)N;
  106033. for (; n <= N; n++)
  106034. window[n] = 2.0f - 2.0f * n / (float)N;
  106035. }
  106036. else {
  106037. for (n = 0; n <= L/2-1; n++)
  106038. window[n] = 2.0f * n / (float)N;
  106039. for (; n <= N; n++)
  106040. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106041. }
  106042. }
  106043. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106044. {
  106045. const FLAC__int32 N = L - 1;
  106046. FLAC__int32 n;
  106047. for (n = 0; n < L; n++)
  106048. 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)));
  106049. }
  106050. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106051. {
  106052. const FLAC__int32 N = L - 1;
  106053. FLAC__int32 n;
  106054. for (n = 0; n < L; n++)
  106055. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106056. }
  106057. /* 4-term -92dB side-lobe */
  106058. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106059. {
  106060. const FLAC__int32 N = L - 1;
  106061. FLAC__int32 n;
  106062. for (n = 0; n <= N; n++)
  106063. 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));
  106064. }
  106065. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106066. {
  106067. const FLAC__int32 N = L - 1;
  106068. const double N2 = (double)N / 2.;
  106069. FLAC__int32 n;
  106070. for (n = 0; n <= N; n++) {
  106071. double k = ((double)n - N2) / N2;
  106072. k = 1.0f - k * k;
  106073. window[n] = (FLAC__real)(k * k);
  106074. }
  106075. }
  106076. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106077. {
  106078. const FLAC__int32 N = L - 1;
  106079. FLAC__int32 n;
  106080. for (n = 0; n < L; n++)
  106081. 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));
  106082. }
  106083. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106084. {
  106085. const FLAC__int32 N = L - 1;
  106086. const double N2 = (double)N / 2.;
  106087. FLAC__int32 n;
  106088. for (n = 0; n <= N; n++) {
  106089. const double k = ((double)n - N2) / (stddev * N2);
  106090. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106091. }
  106092. }
  106093. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106094. {
  106095. const FLAC__int32 N = L - 1;
  106096. FLAC__int32 n;
  106097. for (n = 0; n < L; n++)
  106098. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106099. }
  106100. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106101. {
  106102. const FLAC__int32 N = L - 1;
  106103. FLAC__int32 n;
  106104. for (n = 0; n < L; n++)
  106105. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106106. }
  106107. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106108. {
  106109. const FLAC__int32 N = L - 1;
  106110. FLAC__int32 n;
  106111. for (n = 0; n < L; n++)
  106112. 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));
  106113. }
  106114. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106115. {
  106116. const FLAC__int32 N = L - 1;
  106117. FLAC__int32 n;
  106118. for (n = 0; n < L; n++)
  106119. 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));
  106120. }
  106121. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106122. {
  106123. FLAC__int32 n;
  106124. for (n = 0; n < L; n++)
  106125. window[n] = 1.0f;
  106126. }
  106127. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106128. {
  106129. FLAC__int32 n;
  106130. if (L & 1) {
  106131. for (n = 1; n <= L+1/2; n++)
  106132. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106133. for (; n <= L; n++)
  106134. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106135. }
  106136. else {
  106137. for (n = 1; n <= L/2; n++)
  106138. window[n-1] = 2.0f * n / (float)L;
  106139. for (; n <= L; n++)
  106140. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106141. }
  106142. }
  106143. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106144. {
  106145. if (p <= 0.0)
  106146. FLAC__window_rectangle(window, L);
  106147. else if (p >= 1.0)
  106148. FLAC__window_hann(window, L);
  106149. else {
  106150. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106151. FLAC__int32 n;
  106152. /* start with rectangle... */
  106153. FLAC__window_rectangle(window, L);
  106154. /* ...replace ends with hann */
  106155. if (Np > 0) {
  106156. for (n = 0; n <= Np; n++) {
  106157. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106158. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106159. }
  106160. }
  106161. }
  106162. }
  106163. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106164. {
  106165. const FLAC__int32 N = L - 1;
  106166. const double N2 = (double)N / 2.;
  106167. FLAC__int32 n;
  106168. for (n = 0; n <= N; n++) {
  106169. const double k = ((double)n - N2) / N2;
  106170. window[n] = (FLAC__real)(1.0f - k * k);
  106171. }
  106172. }
  106173. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106174. #endif
  106175. /*** End of inlined file: window_flac.c ***/
  106176. #else
  106177. #include <FLAC/all.h>
  106178. #endif
  106179. }
  106180. #undef max
  106181. #undef min
  106182. BEGIN_JUCE_NAMESPACE
  106183. static const char* const flacFormatName = "FLAC file";
  106184. static const char* const flacExtensions[] = { ".flac", 0 };
  106185. class FlacReader : public AudioFormatReader
  106186. {
  106187. public:
  106188. FlacReader (InputStream* const in)
  106189. : AudioFormatReader (in, TRANS (flacFormatName)),
  106190. reservoir (2, 0),
  106191. reservoirStart (0),
  106192. samplesInReservoir (0),
  106193. scanningForLength (false)
  106194. {
  106195. using namespace FlacNamespace;
  106196. lengthInSamples = 0;
  106197. decoder = FLAC__stream_decoder_new();
  106198. ok = FLAC__stream_decoder_init_stream (decoder,
  106199. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106200. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106201. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106202. if (ok)
  106203. {
  106204. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106205. if (lengthInSamples == 0 && sampleRate > 0)
  106206. {
  106207. // the length hasn't been stored in the metadata, so we'll need to
  106208. // work it out the length the hard way, by scanning the whole file..
  106209. scanningForLength = true;
  106210. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106211. scanningForLength = false;
  106212. const int64 tempLength = lengthInSamples;
  106213. FLAC__stream_decoder_reset (decoder);
  106214. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106215. lengthInSamples = tempLength;
  106216. }
  106217. }
  106218. }
  106219. ~FlacReader()
  106220. {
  106221. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106222. }
  106223. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106224. {
  106225. sampleRate = info.sample_rate;
  106226. bitsPerSample = info.bits_per_sample;
  106227. lengthInSamples = (unsigned int) info.total_samples;
  106228. numChannels = info.channels;
  106229. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106230. }
  106231. // returns the number of samples read
  106232. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106233. int64 startSampleInFile, int numSamples)
  106234. {
  106235. using namespace FlacNamespace;
  106236. if (! ok)
  106237. return false;
  106238. while (numSamples > 0)
  106239. {
  106240. if (startSampleInFile >= reservoirStart
  106241. && startSampleInFile < reservoirStart + samplesInReservoir)
  106242. {
  106243. const int num = (int) jmin ((int64) numSamples,
  106244. reservoirStart + samplesInReservoir - startSampleInFile);
  106245. jassert (num > 0);
  106246. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  106247. if (destSamples[i] != 0)
  106248. memcpy (destSamples[i] + startOffsetInDestBuffer,
  106249. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  106250. sizeof (int) * num);
  106251. startOffsetInDestBuffer += num;
  106252. startSampleInFile += num;
  106253. numSamples -= num;
  106254. }
  106255. else
  106256. {
  106257. if (startSampleInFile >= (int) lengthInSamples)
  106258. {
  106259. samplesInReservoir = 0;
  106260. }
  106261. else if (startSampleInFile < reservoirStart
  106262. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  106263. {
  106264. // had some problems with flac crashing if the read pos is aligned more
  106265. // accurately than this. Probably fixed in newer versions of the library, though.
  106266. reservoirStart = (int) (startSampleInFile & ~511);
  106267. samplesInReservoir = 0;
  106268. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  106269. }
  106270. else
  106271. {
  106272. reservoirStart += samplesInReservoir;
  106273. samplesInReservoir = 0;
  106274. FLAC__stream_decoder_process_single (decoder);
  106275. }
  106276. if (samplesInReservoir == 0)
  106277. break;
  106278. }
  106279. }
  106280. if (numSamples > 0)
  106281. {
  106282. for (int i = numDestChannels; --i >= 0;)
  106283. if (destSamples[i] != 0)
  106284. zeromem (destSamples[i] + startOffsetInDestBuffer,
  106285. sizeof (int) * numSamples);
  106286. }
  106287. return true;
  106288. }
  106289. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  106290. {
  106291. if (scanningForLength)
  106292. {
  106293. lengthInSamples += numSamples;
  106294. }
  106295. else
  106296. {
  106297. if (numSamples > reservoir.getNumSamples())
  106298. reservoir.setSize (numChannels, numSamples, false, false, true);
  106299. const int bitsToShift = 32 - bitsPerSample;
  106300. for (int i = 0; i < (int) numChannels; ++i)
  106301. {
  106302. const FlacNamespace::FLAC__int32* src = buffer[i];
  106303. int n = i;
  106304. while (src == 0 && n > 0)
  106305. src = buffer [--n];
  106306. if (src != 0)
  106307. {
  106308. int* dest = (int*) reservoir.getSampleData(i);
  106309. for (int j = 0; j < numSamples; ++j)
  106310. dest[j] = src[j] << bitsToShift;
  106311. }
  106312. }
  106313. samplesInReservoir = numSamples;
  106314. }
  106315. }
  106316. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106317. {
  106318. using namespace FlacNamespace;
  106319. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106320. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106321. }
  106322. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106323. {
  106324. using namespace FlacNamespace;
  106325. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106326. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106327. }
  106328. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106329. {
  106330. using namespace FlacNamespace;
  106331. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106332. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106333. }
  106334. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106335. {
  106336. using namespace FlacNamespace;
  106337. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106338. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106339. }
  106340. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106341. {
  106342. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106343. }
  106344. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106345. const FlacNamespace::FLAC__Frame* frame,
  106346. const FlacNamespace::FLAC__int32* const buffer[],
  106347. void* client_data)
  106348. {
  106349. using namespace FlacNamespace;
  106350. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106351. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106352. }
  106353. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106354. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106355. void* client_data)
  106356. {
  106357. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106358. }
  106359. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  106360. {
  106361. }
  106362. juce_UseDebuggingNewOperator
  106363. private:
  106364. FlacNamespace::FLAC__StreamDecoder* decoder;
  106365. AudioSampleBuffer reservoir;
  106366. int reservoirStart, samplesInReservoir;
  106367. bool ok, scanningForLength;
  106368. FlacReader (const FlacReader&);
  106369. FlacReader& operator= (const FlacReader&);
  106370. };
  106371. class FlacWriter : public AudioFormatWriter
  106372. {
  106373. public:
  106374. FlacWriter (OutputStream* const out,
  106375. const double sampleRate_,
  106376. const int numChannels_,
  106377. const int bitsPerSample_)
  106378. : AudioFormatWriter (out, TRANS (flacFormatName),
  106379. sampleRate_,
  106380. numChannels_,
  106381. bitsPerSample_)
  106382. {
  106383. using namespace FlacNamespace;
  106384. encoder = FLAC__stream_encoder_new();
  106385. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  106386. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  106387. FLAC__stream_encoder_set_channels (encoder, numChannels);
  106388. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  106389. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  106390. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  106391. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  106392. ok = FLAC__stream_encoder_init_stream (encoder,
  106393. encodeWriteCallback, encodeSeekCallback,
  106394. encodeTellCallback, encodeMetadataCallback,
  106395. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  106396. }
  106397. ~FlacWriter()
  106398. {
  106399. if (ok)
  106400. {
  106401. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  106402. output->flush();
  106403. }
  106404. else
  106405. {
  106406. output = 0; // to stop the base class deleting this, as it needs to be returned
  106407. // to the caller of createWriter()
  106408. }
  106409. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  106410. }
  106411. bool write (const int** samplesToWrite, int numSamples)
  106412. {
  106413. using namespace FlacNamespace;
  106414. if (! ok)
  106415. return false;
  106416. int* buf[3];
  106417. const int bitsToShift = 32 - bitsPerSample;
  106418. if (bitsToShift > 0)
  106419. {
  106420. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  106421. temp.setSize (sizeof (int) * numSamples * numChannelsToWrite);
  106422. buf[0] = (int*) temp.getData();
  106423. buf[1] = buf[0] + numSamples;
  106424. buf[2] = 0;
  106425. for (int i = numChannelsToWrite; --i >= 0;)
  106426. {
  106427. if (samplesToWrite[i] != 0)
  106428. {
  106429. for (int j = 0; j < numSamples; ++j)
  106430. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  106431. }
  106432. }
  106433. samplesToWrite = (const int**) buf;
  106434. }
  106435. return FLAC__stream_encoder_process (encoder,
  106436. (const FLAC__int32**) samplesToWrite,
  106437. numSamples) != 0;
  106438. }
  106439. bool writeData (const void* const data, const int size) const
  106440. {
  106441. return output->write (data, size);
  106442. }
  106443. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  106444. {
  106445. using namespace FlacNamespace;
  106446. b += bytes;
  106447. for (int i = 0; i < bytes; ++i)
  106448. {
  106449. *(--b) = (FLAC__byte) (val & 0xff);
  106450. val >>= 8;
  106451. }
  106452. }
  106453. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  106454. {
  106455. using namespace FlacNamespace;
  106456. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  106457. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  106458. const unsigned int channelsMinus1 = info.channels - 1;
  106459. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  106460. packUint32 (info.min_blocksize, buffer, 2);
  106461. packUint32 (info.max_blocksize, buffer + 2, 2);
  106462. packUint32 (info.min_framesize, buffer + 4, 3);
  106463. packUint32 (info.max_framesize, buffer + 7, 3);
  106464. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  106465. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  106466. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  106467. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  106468. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  106469. memcpy (buffer + 18, info.md5sum, 16);
  106470. const bool seekOk = output->setPosition (4);
  106471. (void) seekOk;
  106472. // if this fails, you've given it an output stream that can't seek! It needs
  106473. // to be able to seek back to write the header
  106474. jassert (seekOk);
  106475. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106476. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106477. }
  106478. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  106479. const FlacNamespace::FLAC__byte buffer[],
  106480. size_t bytes,
  106481. unsigned int /*samples*/,
  106482. unsigned int /*current_frame*/,
  106483. void* client_data)
  106484. {
  106485. using namespace FlacNamespace;
  106486. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  106487. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  106488. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106489. }
  106490. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  106491. {
  106492. using namespace FlacNamespace;
  106493. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  106494. }
  106495. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106496. {
  106497. using namespace FlacNamespace;
  106498. if (client_data == 0)
  106499. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  106500. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  106501. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106502. }
  106503. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  106504. {
  106505. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  106506. }
  106507. juce_UseDebuggingNewOperator
  106508. bool ok;
  106509. private:
  106510. FlacNamespace::FLAC__StreamEncoder* encoder;
  106511. MemoryBlock temp;
  106512. FlacWriter (const FlacWriter&);
  106513. FlacWriter& operator= (const FlacWriter&);
  106514. };
  106515. FlacAudioFormat::FlacAudioFormat()
  106516. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  106517. {
  106518. }
  106519. FlacAudioFormat::~FlacAudioFormat()
  106520. {
  106521. }
  106522. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  106523. {
  106524. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  106525. return Array <int> (rates);
  106526. }
  106527. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  106528. {
  106529. const int depths[] = { 16, 24, 0 };
  106530. return Array <int> (depths);
  106531. }
  106532. bool FlacAudioFormat::canDoStereo()
  106533. {
  106534. return true;
  106535. }
  106536. bool FlacAudioFormat::canDoMono()
  106537. {
  106538. return true;
  106539. }
  106540. bool FlacAudioFormat::isCompressed()
  106541. {
  106542. return true;
  106543. }
  106544. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  106545. const bool deleteStreamIfOpeningFails)
  106546. {
  106547. ScopedPointer<FlacReader> r (new FlacReader (in));
  106548. if (r->sampleRate != 0)
  106549. return r.release();
  106550. if (! deleteStreamIfOpeningFails)
  106551. r->input = 0;
  106552. return 0;
  106553. }
  106554. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  106555. double sampleRate,
  106556. unsigned int numberOfChannels,
  106557. int bitsPerSample,
  106558. const StringPairArray& /*metadataValues*/,
  106559. int /*qualityOptionIndex*/)
  106560. {
  106561. if (getPossibleBitDepths().contains (bitsPerSample))
  106562. {
  106563. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample));
  106564. if (w->ok)
  106565. return w.release();
  106566. }
  106567. return 0;
  106568. }
  106569. END_JUCE_NAMESPACE
  106570. #endif
  106571. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  106572. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  106573. #if JUCE_USE_OGGVORBIS
  106574. #if JUCE_MAC
  106575. #define __MACOSX__ 1
  106576. #endif
  106577. namespace OggVorbisNamespace
  106578. {
  106579. #if JUCE_INCLUDE_OGGVORBIS_CODE
  106580. /*** Start of inlined file: vorbisenc.h ***/
  106581. #ifndef _OV_ENC_H_
  106582. #define _OV_ENC_H_
  106583. #ifdef __cplusplus
  106584. extern "C"
  106585. {
  106586. #endif /* __cplusplus */
  106587. /*** Start of inlined file: codec.h ***/
  106588. #ifndef _vorbis_codec_h_
  106589. #define _vorbis_codec_h_
  106590. #ifdef __cplusplus
  106591. extern "C"
  106592. {
  106593. #endif /* __cplusplus */
  106594. /*** Start of inlined file: ogg.h ***/
  106595. #ifndef _OGG_H
  106596. #define _OGG_H
  106597. #ifdef __cplusplus
  106598. extern "C" {
  106599. #endif
  106600. /*** Start of inlined file: os_types.h ***/
  106601. #ifndef _OS_TYPES_H
  106602. #define _OS_TYPES_H
  106603. /* make it easy on the folks that want to compile the libs with a
  106604. different malloc than stdlib */
  106605. #define _ogg_malloc malloc
  106606. #define _ogg_calloc calloc
  106607. #define _ogg_realloc realloc
  106608. #define _ogg_free free
  106609. #if defined(_WIN32)
  106610. # if defined(__CYGWIN__)
  106611. # include <_G_config.h>
  106612. typedef _G_int64_t ogg_int64_t;
  106613. typedef _G_int32_t ogg_int32_t;
  106614. typedef _G_uint32_t ogg_uint32_t;
  106615. typedef _G_int16_t ogg_int16_t;
  106616. typedef _G_uint16_t ogg_uint16_t;
  106617. # elif defined(__MINGW32__)
  106618. typedef short ogg_int16_t;
  106619. typedef unsigned short ogg_uint16_t;
  106620. typedef int ogg_int32_t;
  106621. typedef unsigned int ogg_uint32_t;
  106622. typedef long long ogg_int64_t;
  106623. typedef unsigned long long ogg_uint64_t;
  106624. # elif defined(__MWERKS__)
  106625. typedef long long ogg_int64_t;
  106626. typedef int ogg_int32_t;
  106627. typedef unsigned int ogg_uint32_t;
  106628. typedef short ogg_int16_t;
  106629. typedef unsigned short ogg_uint16_t;
  106630. # else
  106631. /* MSVC/Borland */
  106632. typedef __int64 ogg_int64_t;
  106633. typedef __int32 ogg_int32_t;
  106634. typedef unsigned __int32 ogg_uint32_t;
  106635. typedef __int16 ogg_int16_t;
  106636. typedef unsigned __int16 ogg_uint16_t;
  106637. # endif
  106638. #elif defined(__MACOS__)
  106639. # include <sys/types.h>
  106640. typedef SInt16 ogg_int16_t;
  106641. typedef UInt16 ogg_uint16_t;
  106642. typedef SInt32 ogg_int32_t;
  106643. typedef UInt32 ogg_uint32_t;
  106644. typedef SInt64 ogg_int64_t;
  106645. #elif defined(__MACOSX__) /* MacOS X Framework build */
  106646. # include <sys/types.h>
  106647. typedef int16_t ogg_int16_t;
  106648. typedef u_int16_t ogg_uint16_t;
  106649. typedef int32_t ogg_int32_t;
  106650. typedef u_int32_t ogg_uint32_t;
  106651. typedef int64_t ogg_int64_t;
  106652. #elif defined(__BEOS__)
  106653. /* Be */
  106654. # include <inttypes.h>
  106655. typedef int16_t ogg_int16_t;
  106656. typedef u_int16_t ogg_uint16_t;
  106657. typedef int32_t ogg_int32_t;
  106658. typedef u_int32_t ogg_uint32_t;
  106659. typedef int64_t ogg_int64_t;
  106660. #elif defined (__EMX__)
  106661. /* OS/2 GCC */
  106662. typedef short ogg_int16_t;
  106663. typedef unsigned short ogg_uint16_t;
  106664. typedef int ogg_int32_t;
  106665. typedef unsigned int ogg_uint32_t;
  106666. typedef long long ogg_int64_t;
  106667. #elif defined (DJGPP)
  106668. /* DJGPP */
  106669. typedef short ogg_int16_t;
  106670. typedef int ogg_int32_t;
  106671. typedef unsigned int ogg_uint32_t;
  106672. typedef long long ogg_int64_t;
  106673. #elif defined(R5900)
  106674. /* PS2 EE */
  106675. typedef long ogg_int64_t;
  106676. typedef int ogg_int32_t;
  106677. typedef unsigned ogg_uint32_t;
  106678. typedef short ogg_int16_t;
  106679. #elif defined(__SYMBIAN32__)
  106680. /* Symbian GCC */
  106681. typedef signed short ogg_int16_t;
  106682. typedef unsigned short ogg_uint16_t;
  106683. typedef signed int ogg_int32_t;
  106684. typedef unsigned int ogg_uint32_t;
  106685. typedef long long int ogg_int64_t;
  106686. #else
  106687. # include <sys/types.h>
  106688. /*** Start of inlined file: config_types.h ***/
  106689. #ifndef __CONFIG_TYPES_H__
  106690. #define __CONFIG_TYPES_H__
  106691. typedef int16_t ogg_int16_t;
  106692. typedef unsigned short ogg_uint16_t;
  106693. typedef int32_t ogg_int32_t;
  106694. typedef unsigned int ogg_uint32_t;
  106695. typedef int64_t ogg_int64_t;
  106696. #endif
  106697. /*** End of inlined file: config_types.h ***/
  106698. #endif
  106699. #endif /* _OS_TYPES_H */
  106700. /*** End of inlined file: os_types.h ***/
  106701. typedef struct {
  106702. long endbyte;
  106703. int endbit;
  106704. unsigned char *buffer;
  106705. unsigned char *ptr;
  106706. long storage;
  106707. } oggpack_buffer;
  106708. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  106709. typedef struct {
  106710. unsigned char *header;
  106711. long header_len;
  106712. unsigned char *body;
  106713. long body_len;
  106714. } ogg_page;
  106715. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  106716. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  106717. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  106718. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  106719. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  106720. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  106721. }
  106722. /* ogg_stream_state contains the current encode/decode state of a logical
  106723. Ogg bitstream **********************************************************/
  106724. typedef struct {
  106725. unsigned char *body_data; /* bytes from packet bodies */
  106726. long body_storage; /* storage elements allocated */
  106727. long body_fill; /* elements stored; fill mark */
  106728. long body_returned; /* elements of fill returned */
  106729. int *lacing_vals; /* The values that will go to the segment table */
  106730. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  106731. this way, but it is simple coupled to the
  106732. lacing fifo */
  106733. long lacing_storage;
  106734. long lacing_fill;
  106735. long lacing_packet;
  106736. long lacing_returned;
  106737. unsigned char header[282]; /* working space for header encode */
  106738. int header_fill;
  106739. int e_o_s; /* set when we have buffered the last packet in the
  106740. logical bitstream */
  106741. int b_o_s; /* set after we've written the initial page
  106742. of a logical bitstream */
  106743. long serialno;
  106744. long pageno;
  106745. ogg_int64_t packetno; /* sequence number for decode; the framing
  106746. knows where there's a hole in the data,
  106747. but we need coupling so that the codec
  106748. (which is in a seperate abstraction
  106749. layer) also knows about the gap */
  106750. ogg_int64_t granulepos;
  106751. } ogg_stream_state;
  106752. /* ogg_packet is used to encapsulate the data and metadata belonging
  106753. to a single raw Ogg/Vorbis packet *************************************/
  106754. typedef struct {
  106755. unsigned char *packet;
  106756. long bytes;
  106757. long b_o_s;
  106758. long e_o_s;
  106759. ogg_int64_t granulepos;
  106760. ogg_int64_t packetno; /* sequence number for decode; the framing
  106761. knows where there's a hole in the data,
  106762. but we need coupling so that the codec
  106763. (which is in a seperate abstraction
  106764. layer) also knows about the gap */
  106765. } ogg_packet;
  106766. typedef struct {
  106767. unsigned char *data;
  106768. int storage;
  106769. int fill;
  106770. int returned;
  106771. int unsynced;
  106772. int headerbytes;
  106773. int bodybytes;
  106774. } ogg_sync_state;
  106775. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  106776. extern void oggpack_writeinit(oggpack_buffer *b);
  106777. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  106778. extern void oggpack_writealign(oggpack_buffer *b);
  106779. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  106780. extern void oggpack_reset(oggpack_buffer *b);
  106781. extern void oggpack_writeclear(oggpack_buffer *b);
  106782. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  106783. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  106784. extern long oggpack_look(oggpack_buffer *b,int bits);
  106785. extern long oggpack_look1(oggpack_buffer *b);
  106786. extern void oggpack_adv(oggpack_buffer *b,int bits);
  106787. extern void oggpack_adv1(oggpack_buffer *b);
  106788. extern long oggpack_read(oggpack_buffer *b,int bits);
  106789. extern long oggpack_read1(oggpack_buffer *b);
  106790. extern long oggpack_bytes(oggpack_buffer *b);
  106791. extern long oggpack_bits(oggpack_buffer *b);
  106792. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  106793. extern void oggpackB_writeinit(oggpack_buffer *b);
  106794. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  106795. extern void oggpackB_writealign(oggpack_buffer *b);
  106796. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  106797. extern void oggpackB_reset(oggpack_buffer *b);
  106798. extern void oggpackB_writeclear(oggpack_buffer *b);
  106799. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  106800. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  106801. extern long oggpackB_look(oggpack_buffer *b,int bits);
  106802. extern long oggpackB_look1(oggpack_buffer *b);
  106803. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  106804. extern void oggpackB_adv1(oggpack_buffer *b);
  106805. extern long oggpackB_read(oggpack_buffer *b,int bits);
  106806. extern long oggpackB_read1(oggpack_buffer *b);
  106807. extern long oggpackB_bytes(oggpack_buffer *b);
  106808. extern long oggpackB_bits(oggpack_buffer *b);
  106809. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  106810. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  106811. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  106812. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  106813. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  106814. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  106815. extern int ogg_sync_init(ogg_sync_state *oy);
  106816. extern int ogg_sync_clear(ogg_sync_state *oy);
  106817. extern int ogg_sync_reset(ogg_sync_state *oy);
  106818. extern int ogg_sync_destroy(ogg_sync_state *oy);
  106819. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  106820. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  106821. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  106822. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  106823. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  106824. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  106825. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  106826. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  106827. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  106828. extern int ogg_stream_clear(ogg_stream_state *os);
  106829. extern int ogg_stream_reset(ogg_stream_state *os);
  106830. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  106831. extern int ogg_stream_destroy(ogg_stream_state *os);
  106832. extern int ogg_stream_eos(ogg_stream_state *os);
  106833. extern void ogg_page_checksum_set(ogg_page *og);
  106834. extern int ogg_page_version(ogg_page *og);
  106835. extern int ogg_page_continued(ogg_page *og);
  106836. extern int ogg_page_bos(ogg_page *og);
  106837. extern int ogg_page_eos(ogg_page *og);
  106838. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  106839. extern int ogg_page_serialno(ogg_page *og);
  106840. extern long ogg_page_pageno(ogg_page *og);
  106841. extern int ogg_page_packets(ogg_page *og);
  106842. extern void ogg_packet_clear(ogg_packet *op);
  106843. #ifdef __cplusplus
  106844. }
  106845. #endif
  106846. #endif /* _OGG_H */
  106847. /*** End of inlined file: ogg.h ***/
  106848. typedef struct vorbis_info{
  106849. int version;
  106850. int channels;
  106851. long rate;
  106852. /* The below bitrate declarations are *hints*.
  106853. Combinations of the three values carry the following implications:
  106854. all three set to the same value:
  106855. implies a fixed rate bitstream
  106856. only nominal set:
  106857. implies a VBR stream that averages the nominal bitrate. No hard
  106858. upper/lower limit
  106859. upper and or lower set:
  106860. implies a VBR bitstream that obeys the bitrate limits. nominal
  106861. may also be set to give a nominal rate.
  106862. none set:
  106863. the coder does not care to speculate.
  106864. */
  106865. long bitrate_upper;
  106866. long bitrate_nominal;
  106867. long bitrate_lower;
  106868. long bitrate_window;
  106869. void *codec_setup;
  106870. } vorbis_info;
  106871. /* vorbis_dsp_state buffers the current vorbis audio
  106872. analysis/synthesis state. The DSP state belongs to a specific
  106873. logical bitstream ****************************************************/
  106874. typedef struct vorbis_dsp_state{
  106875. int analysisp;
  106876. vorbis_info *vi;
  106877. float **pcm;
  106878. float **pcmret;
  106879. int pcm_storage;
  106880. int pcm_current;
  106881. int pcm_returned;
  106882. int preextrapolate;
  106883. int eofflag;
  106884. long lW;
  106885. long W;
  106886. long nW;
  106887. long centerW;
  106888. ogg_int64_t granulepos;
  106889. ogg_int64_t sequence;
  106890. ogg_int64_t glue_bits;
  106891. ogg_int64_t time_bits;
  106892. ogg_int64_t floor_bits;
  106893. ogg_int64_t res_bits;
  106894. void *backend_state;
  106895. } vorbis_dsp_state;
  106896. typedef struct vorbis_block{
  106897. /* necessary stream state for linking to the framing abstraction */
  106898. float **pcm; /* this is a pointer into local storage */
  106899. oggpack_buffer opb;
  106900. long lW;
  106901. long W;
  106902. long nW;
  106903. int pcmend;
  106904. int mode;
  106905. int eofflag;
  106906. ogg_int64_t granulepos;
  106907. ogg_int64_t sequence;
  106908. vorbis_dsp_state *vd; /* For read-only access of configuration */
  106909. /* local storage to avoid remallocing; it's up to the mapping to
  106910. structure it */
  106911. void *localstore;
  106912. long localtop;
  106913. long localalloc;
  106914. long totaluse;
  106915. struct alloc_chain *reap;
  106916. /* bitmetrics for the frame */
  106917. long glue_bits;
  106918. long time_bits;
  106919. long floor_bits;
  106920. long res_bits;
  106921. void *internal;
  106922. } vorbis_block;
  106923. /* vorbis_block is a single block of data to be processed as part of
  106924. the analysis/synthesis stream; it belongs to a specific logical
  106925. bitstream, but is independant from other vorbis_blocks belonging to
  106926. that logical bitstream. *************************************************/
  106927. struct alloc_chain{
  106928. void *ptr;
  106929. struct alloc_chain *next;
  106930. };
  106931. /* vorbis_info contains all the setup information specific to the
  106932. specific compression/decompression mode in progress (eg,
  106933. psychoacoustic settings, channel setup, options, codebook
  106934. etc). vorbis_info and substructures are in backends.h.
  106935. *********************************************************************/
  106936. /* the comments are not part of vorbis_info so that vorbis_info can be
  106937. static storage */
  106938. typedef struct vorbis_comment{
  106939. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  106940. whatever vendor is set to in encode */
  106941. char **user_comments;
  106942. int *comment_lengths;
  106943. int comments;
  106944. char *vendor;
  106945. } vorbis_comment;
  106946. /* libvorbis encodes in two abstraction layers; first we perform DSP
  106947. and produce a packet (see docs/analysis.txt). The packet is then
  106948. coded into a framed OggSquish bitstream by the second layer (see
  106949. docs/framing.txt). Decode is the reverse process; we sync/frame
  106950. the bitstream and extract individual packets, then decode the
  106951. packet back into PCM audio.
  106952. The extra framing/packetizing is used in streaming formats, such as
  106953. files. Over the net (such as with UDP), the framing and
  106954. packetization aren't necessary as they're provided by the transport
  106955. and the streaming layer is not used */
  106956. /* Vorbis PRIMITIVES: general ***************************************/
  106957. extern void vorbis_info_init(vorbis_info *vi);
  106958. extern void vorbis_info_clear(vorbis_info *vi);
  106959. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  106960. extern void vorbis_comment_init(vorbis_comment *vc);
  106961. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  106962. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  106963. const char *tag, char *contents);
  106964. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  106965. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  106966. extern void vorbis_comment_clear(vorbis_comment *vc);
  106967. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  106968. extern int vorbis_block_clear(vorbis_block *vb);
  106969. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  106970. extern double vorbis_granule_time(vorbis_dsp_state *v,
  106971. ogg_int64_t granulepos);
  106972. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  106973. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  106974. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  106975. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  106976. vorbis_comment *vc,
  106977. ogg_packet *op,
  106978. ogg_packet *op_comm,
  106979. ogg_packet *op_code);
  106980. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  106981. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  106982. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  106983. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  106984. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  106985. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  106986. ogg_packet *op);
  106987. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  106988. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  106989. ogg_packet *op);
  106990. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  106991. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  106992. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  106993. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  106994. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  106995. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  106996. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  106997. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  106998. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  106999. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107000. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107001. /* Vorbis ERRORS and return codes ***********************************/
  107002. #define OV_FALSE -1
  107003. #define OV_EOF -2
  107004. #define OV_HOLE -3
  107005. #define OV_EREAD -128
  107006. #define OV_EFAULT -129
  107007. #define OV_EIMPL -130
  107008. #define OV_EINVAL -131
  107009. #define OV_ENOTVORBIS -132
  107010. #define OV_EBADHEADER -133
  107011. #define OV_EVERSION -134
  107012. #define OV_ENOTAUDIO -135
  107013. #define OV_EBADPACKET -136
  107014. #define OV_EBADLINK -137
  107015. #define OV_ENOSEEK -138
  107016. #ifdef __cplusplus
  107017. }
  107018. #endif /* __cplusplus */
  107019. #endif
  107020. /*** End of inlined file: codec.h ***/
  107021. extern int vorbis_encode_init(vorbis_info *vi,
  107022. long channels,
  107023. long rate,
  107024. long max_bitrate,
  107025. long nominal_bitrate,
  107026. long min_bitrate);
  107027. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107028. long channels,
  107029. long rate,
  107030. long max_bitrate,
  107031. long nominal_bitrate,
  107032. long min_bitrate);
  107033. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107034. long channels,
  107035. long rate,
  107036. float quality /* quality level from 0. (lo) to 1. (hi) */
  107037. );
  107038. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107039. long channels,
  107040. long rate,
  107041. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107042. );
  107043. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107044. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107045. /* deprecated rate management supported only for compatability */
  107046. #define OV_ECTL_RATEMANAGE_GET 0x10
  107047. #define OV_ECTL_RATEMANAGE_SET 0x11
  107048. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107049. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107050. struct ovectl_ratemanage_arg {
  107051. int management_active;
  107052. long bitrate_hard_min;
  107053. long bitrate_hard_max;
  107054. double bitrate_hard_window;
  107055. long bitrate_av_lo;
  107056. long bitrate_av_hi;
  107057. double bitrate_av_window;
  107058. double bitrate_av_window_center;
  107059. };
  107060. /* new rate setup */
  107061. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107062. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107063. struct ovectl_ratemanage2_arg {
  107064. int management_active;
  107065. long bitrate_limit_min_kbps;
  107066. long bitrate_limit_max_kbps;
  107067. long bitrate_limit_reservoir_bits;
  107068. double bitrate_limit_reservoir_bias;
  107069. long bitrate_average_kbps;
  107070. double bitrate_average_damping;
  107071. };
  107072. #define OV_ECTL_LOWPASS_GET 0x20
  107073. #define OV_ECTL_LOWPASS_SET 0x21
  107074. #define OV_ECTL_IBLOCK_GET 0x30
  107075. #define OV_ECTL_IBLOCK_SET 0x31
  107076. #ifdef __cplusplus
  107077. }
  107078. #endif /* __cplusplus */
  107079. #endif
  107080. /*** End of inlined file: vorbisenc.h ***/
  107081. /*** Start of inlined file: vorbisfile.h ***/
  107082. #ifndef _OV_FILE_H_
  107083. #define _OV_FILE_H_
  107084. #ifdef __cplusplus
  107085. extern "C"
  107086. {
  107087. #endif /* __cplusplus */
  107088. #include <stdio.h>
  107089. /* The function prototypes for the callbacks are basically the same as for
  107090. * the stdio functions fread, fseek, fclose, ftell.
  107091. * The one difference is that the FILE * arguments have been replaced with
  107092. * a void * - this is to be used as a pointer to whatever internal data these
  107093. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107094. *
  107095. * If you use other functions, check the docs for these functions and return
  107096. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107097. * unseekable
  107098. */
  107099. typedef struct {
  107100. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107101. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107102. int (*close_func) (void *datasource);
  107103. long (*tell_func) (void *datasource);
  107104. } ov_callbacks;
  107105. #define NOTOPEN 0
  107106. #define PARTOPEN 1
  107107. #define OPENED 2
  107108. #define STREAMSET 3
  107109. #define INITSET 4
  107110. typedef struct OggVorbis_File {
  107111. void *datasource; /* Pointer to a FILE *, etc. */
  107112. int seekable;
  107113. ogg_int64_t offset;
  107114. ogg_int64_t end;
  107115. ogg_sync_state oy;
  107116. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107117. stream appears */
  107118. int links;
  107119. ogg_int64_t *offsets;
  107120. ogg_int64_t *dataoffsets;
  107121. long *serialnos;
  107122. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107123. compatability; x2 size, stores both
  107124. beginning and end values */
  107125. vorbis_info *vi;
  107126. vorbis_comment *vc;
  107127. /* Decoding working state local storage */
  107128. ogg_int64_t pcm_offset;
  107129. int ready_state;
  107130. long current_serialno;
  107131. int current_link;
  107132. double bittrack;
  107133. double samptrack;
  107134. ogg_stream_state os; /* take physical pages, weld into a logical
  107135. stream of packets */
  107136. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107137. vorbis_block vb; /* local working space for packet->PCM decode */
  107138. ov_callbacks callbacks;
  107139. } OggVorbis_File;
  107140. extern int ov_clear(OggVorbis_File *vf);
  107141. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107142. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107143. char *initial, long ibytes, ov_callbacks callbacks);
  107144. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107145. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107146. char *initial, long ibytes, ov_callbacks callbacks);
  107147. extern int ov_test_open(OggVorbis_File *vf);
  107148. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107149. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107150. extern long ov_streams(OggVorbis_File *vf);
  107151. extern long ov_seekable(OggVorbis_File *vf);
  107152. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107153. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107154. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107155. extern double ov_time_total(OggVorbis_File *vf,int i);
  107156. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107157. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107158. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107159. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107160. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107161. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107162. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107163. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107164. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107165. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107166. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107167. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107168. extern double ov_time_tell(OggVorbis_File *vf);
  107169. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107170. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107171. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107172. int *bitstream);
  107173. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107174. int bigendianp,int word,int sgned,int *bitstream);
  107175. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107176. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107177. extern int ov_halfrate_p(OggVorbis_File *vf);
  107178. #ifdef __cplusplus
  107179. }
  107180. #endif /* __cplusplus */
  107181. #endif
  107182. /*** End of inlined file: vorbisfile.h ***/
  107183. /*** Start of inlined file: bitwise.c ***/
  107184. /* We're 'LSb' endian; if we write a word but read individual bits,
  107185. then we'll read the lsb first */
  107186. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107187. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107188. // tasks..
  107189. #if JUCE_MSVC
  107190. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107191. #endif
  107192. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107193. #if JUCE_USE_OGGVORBIS
  107194. #include <string.h>
  107195. #include <stdlib.h>
  107196. #define BUFFER_INCREMENT 256
  107197. static const unsigned long mask[]=
  107198. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107199. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107200. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107201. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107202. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107203. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107204. 0x3fffffff,0x7fffffff,0xffffffff };
  107205. static const unsigned int mask8B[]=
  107206. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107207. void oggpack_writeinit(oggpack_buffer *b){
  107208. memset(b,0,sizeof(*b));
  107209. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107210. b->buffer[0]='\0';
  107211. b->storage=BUFFER_INCREMENT;
  107212. }
  107213. void oggpackB_writeinit(oggpack_buffer *b){
  107214. oggpack_writeinit(b);
  107215. }
  107216. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107217. long bytes=bits>>3;
  107218. bits-=bytes*8;
  107219. b->ptr=b->buffer+bytes;
  107220. b->endbit=bits;
  107221. b->endbyte=bytes;
  107222. *b->ptr&=mask[bits];
  107223. }
  107224. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107225. long bytes=bits>>3;
  107226. bits-=bytes*8;
  107227. b->ptr=b->buffer+bytes;
  107228. b->endbit=bits;
  107229. b->endbyte=bytes;
  107230. *b->ptr&=mask8B[bits];
  107231. }
  107232. /* Takes only up to 32 bits. */
  107233. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107234. if(b->endbyte+4>=b->storage){
  107235. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107236. b->storage+=BUFFER_INCREMENT;
  107237. b->ptr=b->buffer+b->endbyte;
  107238. }
  107239. value&=mask[bits];
  107240. bits+=b->endbit;
  107241. b->ptr[0]|=value<<b->endbit;
  107242. if(bits>=8){
  107243. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107244. if(bits>=16){
  107245. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107246. if(bits>=24){
  107247. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107248. if(bits>=32){
  107249. if(b->endbit)
  107250. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107251. else
  107252. b->ptr[4]=0;
  107253. }
  107254. }
  107255. }
  107256. }
  107257. b->endbyte+=bits/8;
  107258. b->ptr+=bits/8;
  107259. b->endbit=bits&7;
  107260. }
  107261. /* Takes only up to 32 bits. */
  107262. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  107263. if(b->endbyte+4>=b->storage){
  107264. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107265. b->storage+=BUFFER_INCREMENT;
  107266. b->ptr=b->buffer+b->endbyte;
  107267. }
  107268. value=(value&mask[bits])<<(32-bits);
  107269. bits+=b->endbit;
  107270. b->ptr[0]|=value>>(24+b->endbit);
  107271. if(bits>=8){
  107272. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  107273. if(bits>=16){
  107274. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  107275. if(bits>=24){
  107276. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  107277. if(bits>=32){
  107278. if(b->endbit)
  107279. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  107280. else
  107281. b->ptr[4]=0;
  107282. }
  107283. }
  107284. }
  107285. }
  107286. b->endbyte+=bits/8;
  107287. b->ptr+=bits/8;
  107288. b->endbit=bits&7;
  107289. }
  107290. void oggpack_writealign(oggpack_buffer *b){
  107291. int bits=8-b->endbit;
  107292. if(bits<8)
  107293. oggpack_write(b,0,bits);
  107294. }
  107295. void oggpackB_writealign(oggpack_buffer *b){
  107296. int bits=8-b->endbit;
  107297. if(bits<8)
  107298. oggpackB_write(b,0,bits);
  107299. }
  107300. static void oggpack_writecopy_helper(oggpack_buffer *b,
  107301. void *source,
  107302. long bits,
  107303. void (*w)(oggpack_buffer *,
  107304. unsigned long,
  107305. int),
  107306. int msb){
  107307. unsigned char *ptr=(unsigned char *)source;
  107308. long bytes=bits/8;
  107309. bits-=bytes*8;
  107310. if(b->endbit){
  107311. int i;
  107312. /* unaligned copy. Do it the hard way. */
  107313. for(i=0;i<bytes;i++)
  107314. w(b,(unsigned long)(ptr[i]),8);
  107315. }else{
  107316. /* aligned block copy */
  107317. if(b->endbyte+bytes+1>=b->storage){
  107318. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107319. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107320. b->ptr=b->buffer+b->endbyte;
  107321. }
  107322. memmove(b->ptr,source,bytes);
  107323. b->ptr+=bytes;
  107324. b->endbyte+=bytes;
  107325. *b->ptr=0;
  107326. }
  107327. if(bits){
  107328. if(msb)
  107329. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107330. else
  107331. w(b,(unsigned long)(ptr[bytes]),bits);
  107332. }
  107333. }
  107334. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107335. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107336. }
  107337. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107338. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107339. }
  107340. void oggpack_reset(oggpack_buffer *b){
  107341. b->ptr=b->buffer;
  107342. b->buffer[0]=0;
  107343. b->endbit=b->endbyte=0;
  107344. }
  107345. void oggpackB_reset(oggpack_buffer *b){
  107346. oggpack_reset(b);
  107347. }
  107348. void oggpack_writeclear(oggpack_buffer *b){
  107349. _ogg_free(b->buffer);
  107350. memset(b,0,sizeof(*b));
  107351. }
  107352. void oggpackB_writeclear(oggpack_buffer *b){
  107353. oggpack_writeclear(b);
  107354. }
  107355. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107356. memset(b,0,sizeof(*b));
  107357. b->buffer=b->ptr=buf;
  107358. b->storage=bytes;
  107359. }
  107360. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107361. oggpack_readinit(b,buf,bytes);
  107362. }
  107363. /* Read in bits without advancing the bitptr; bits <= 32 */
  107364. long oggpack_look(oggpack_buffer *b,int bits){
  107365. unsigned long ret;
  107366. unsigned long m=mask[bits];
  107367. bits+=b->endbit;
  107368. if(b->endbyte+4>=b->storage){
  107369. /* not the main path */
  107370. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107371. }
  107372. ret=b->ptr[0]>>b->endbit;
  107373. if(bits>8){
  107374. ret|=b->ptr[1]<<(8-b->endbit);
  107375. if(bits>16){
  107376. ret|=b->ptr[2]<<(16-b->endbit);
  107377. if(bits>24){
  107378. ret|=b->ptr[3]<<(24-b->endbit);
  107379. if(bits>32 && b->endbit)
  107380. ret|=b->ptr[4]<<(32-b->endbit);
  107381. }
  107382. }
  107383. }
  107384. return(m&ret);
  107385. }
  107386. /* Read in bits without advancing the bitptr; bits <= 32 */
  107387. long oggpackB_look(oggpack_buffer *b,int bits){
  107388. unsigned long ret;
  107389. int m=32-bits;
  107390. bits+=b->endbit;
  107391. if(b->endbyte+4>=b->storage){
  107392. /* not the main path */
  107393. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107394. }
  107395. ret=b->ptr[0]<<(24+b->endbit);
  107396. if(bits>8){
  107397. ret|=b->ptr[1]<<(16+b->endbit);
  107398. if(bits>16){
  107399. ret|=b->ptr[2]<<(8+b->endbit);
  107400. if(bits>24){
  107401. ret|=b->ptr[3]<<(b->endbit);
  107402. if(bits>32 && b->endbit)
  107403. ret|=b->ptr[4]>>(8-b->endbit);
  107404. }
  107405. }
  107406. }
  107407. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  107408. }
  107409. long oggpack_look1(oggpack_buffer *b){
  107410. if(b->endbyte>=b->storage)return(-1);
  107411. return((b->ptr[0]>>b->endbit)&1);
  107412. }
  107413. long oggpackB_look1(oggpack_buffer *b){
  107414. if(b->endbyte>=b->storage)return(-1);
  107415. return((b->ptr[0]>>(7-b->endbit))&1);
  107416. }
  107417. void oggpack_adv(oggpack_buffer *b,int bits){
  107418. bits+=b->endbit;
  107419. b->ptr+=bits/8;
  107420. b->endbyte+=bits/8;
  107421. b->endbit=bits&7;
  107422. }
  107423. void oggpackB_adv(oggpack_buffer *b,int bits){
  107424. oggpack_adv(b,bits);
  107425. }
  107426. void oggpack_adv1(oggpack_buffer *b){
  107427. if(++(b->endbit)>7){
  107428. b->endbit=0;
  107429. b->ptr++;
  107430. b->endbyte++;
  107431. }
  107432. }
  107433. void oggpackB_adv1(oggpack_buffer *b){
  107434. oggpack_adv1(b);
  107435. }
  107436. /* bits <= 32 */
  107437. long oggpack_read(oggpack_buffer *b,int bits){
  107438. long ret;
  107439. unsigned long m=mask[bits];
  107440. bits+=b->endbit;
  107441. if(b->endbyte+4>=b->storage){
  107442. /* not the main path */
  107443. ret=-1L;
  107444. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107445. }
  107446. ret=b->ptr[0]>>b->endbit;
  107447. if(bits>8){
  107448. ret|=b->ptr[1]<<(8-b->endbit);
  107449. if(bits>16){
  107450. ret|=b->ptr[2]<<(16-b->endbit);
  107451. if(bits>24){
  107452. ret|=b->ptr[3]<<(24-b->endbit);
  107453. if(bits>32 && b->endbit){
  107454. ret|=b->ptr[4]<<(32-b->endbit);
  107455. }
  107456. }
  107457. }
  107458. }
  107459. ret&=m;
  107460. overflow:
  107461. b->ptr+=bits/8;
  107462. b->endbyte+=bits/8;
  107463. b->endbit=bits&7;
  107464. return(ret);
  107465. }
  107466. /* bits <= 32 */
  107467. long oggpackB_read(oggpack_buffer *b,int bits){
  107468. long ret;
  107469. long m=32-bits;
  107470. bits+=b->endbit;
  107471. if(b->endbyte+4>=b->storage){
  107472. /* not the main path */
  107473. ret=-1L;
  107474. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107475. }
  107476. ret=b->ptr[0]<<(24+b->endbit);
  107477. if(bits>8){
  107478. ret|=b->ptr[1]<<(16+b->endbit);
  107479. if(bits>16){
  107480. ret|=b->ptr[2]<<(8+b->endbit);
  107481. if(bits>24){
  107482. ret|=b->ptr[3]<<(b->endbit);
  107483. if(bits>32 && b->endbit)
  107484. ret|=b->ptr[4]>>(8-b->endbit);
  107485. }
  107486. }
  107487. }
  107488. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  107489. overflow:
  107490. b->ptr+=bits/8;
  107491. b->endbyte+=bits/8;
  107492. b->endbit=bits&7;
  107493. return(ret);
  107494. }
  107495. long oggpack_read1(oggpack_buffer *b){
  107496. long ret;
  107497. if(b->endbyte>=b->storage){
  107498. /* not the main path */
  107499. ret=-1L;
  107500. goto overflow;
  107501. }
  107502. ret=(b->ptr[0]>>b->endbit)&1;
  107503. overflow:
  107504. b->endbit++;
  107505. if(b->endbit>7){
  107506. b->endbit=0;
  107507. b->ptr++;
  107508. b->endbyte++;
  107509. }
  107510. return(ret);
  107511. }
  107512. long oggpackB_read1(oggpack_buffer *b){
  107513. long ret;
  107514. if(b->endbyte>=b->storage){
  107515. /* not the main path */
  107516. ret=-1L;
  107517. goto overflow;
  107518. }
  107519. ret=(b->ptr[0]>>(7-b->endbit))&1;
  107520. overflow:
  107521. b->endbit++;
  107522. if(b->endbit>7){
  107523. b->endbit=0;
  107524. b->ptr++;
  107525. b->endbyte++;
  107526. }
  107527. return(ret);
  107528. }
  107529. long oggpack_bytes(oggpack_buffer *b){
  107530. return(b->endbyte+(b->endbit+7)/8);
  107531. }
  107532. long oggpack_bits(oggpack_buffer *b){
  107533. return(b->endbyte*8+b->endbit);
  107534. }
  107535. long oggpackB_bytes(oggpack_buffer *b){
  107536. return oggpack_bytes(b);
  107537. }
  107538. long oggpackB_bits(oggpack_buffer *b){
  107539. return oggpack_bits(b);
  107540. }
  107541. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  107542. return(b->buffer);
  107543. }
  107544. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  107545. return oggpack_get_buffer(b);
  107546. }
  107547. /* Self test of the bitwise routines; everything else is based on
  107548. them, so they damned well better be solid. */
  107549. #ifdef _V_SELFTEST
  107550. #include <stdio.h>
  107551. static int ilog(unsigned int v){
  107552. int ret=0;
  107553. while(v){
  107554. ret++;
  107555. v>>=1;
  107556. }
  107557. return(ret);
  107558. }
  107559. oggpack_buffer o;
  107560. oggpack_buffer r;
  107561. void report(char *in){
  107562. fprintf(stderr,"%s",in);
  107563. exit(1);
  107564. }
  107565. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107566. long bytes,i;
  107567. unsigned char *buffer;
  107568. oggpack_reset(&o);
  107569. for(i=0;i<vals;i++)
  107570. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  107571. buffer=oggpack_get_buffer(&o);
  107572. bytes=oggpack_bytes(&o);
  107573. if(bytes!=compsize)report("wrong number of bytes!\n");
  107574. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107575. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107576. report("wrote incorrect value!\n");
  107577. }
  107578. oggpack_readinit(&r,buffer,bytes);
  107579. for(i=0;i<vals;i++){
  107580. int tbit=bits?bits:ilog(b[i]);
  107581. if(oggpack_look(&r,tbit)==-1)
  107582. report("out of data!\n");
  107583. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  107584. report("looked at incorrect value!\n");
  107585. if(tbit==1)
  107586. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  107587. report("looked at single bit incorrect value!\n");
  107588. if(tbit==1){
  107589. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  107590. report("read incorrect single bit value!\n");
  107591. }else{
  107592. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  107593. report("read incorrect value!\n");
  107594. }
  107595. }
  107596. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107597. }
  107598. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107599. long bytes,i;
  107600. unsigned char *buffer;
  107601. oggpackB_reset(&o);
  107602. for(i=0;i<vals;i++)
  107603. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  107604. buffer=oggpackB_get_buffer(&o);
  107605. bytes=oggpackB_bytes(&o);
  107606. if(bytes!=compsize)report("wrong number of bytes!\n");
  107607. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107608. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107609. report("wrote incorrect value!\n");
  107610. }
  107611. oggpackB_readinit(&r,buffer,bytes);
  107612. for(i=0;i<vals;i++){
  107613. int tbit=bits?bits:ilog(b[i]);
  107614. if(oggpackB_look(&r,tbit)==-1)
  107615. report("out of data!\n");
  107616. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  107617. report("looked at incorrect value!\n");
  107618. if(tbit==1)
  107619. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  107620. report("looked at single bit incorrect value!\n");
  107621. if(tbit==1){
  107622. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  107623. report("read incorrect single bit value!\n");
  107624. }else{
  107625. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  107626. report("read incorrect value!\n");
  107627. }
  107628. }
  107629. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107630. }
  107631. int main(void){
  107632. unsigned char *buffer;
  107633. long bytes,i;
  107634. static unsigned long testbuffer1[]=
  107635. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  107636. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  107637. int test1size=43;
  107638. static unsigned long testbuffer2[]=
  107639. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  107640. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  107641. 85525151,0,12321,1,349528352};
  107642. int test2size=21;
  107643. static unsigned long testbuffer3[]=
  107644. {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,
  107645. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  107646. int test3size=56;
  107647. static unsigned long large[]=
  107648. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  107649. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  107650. 85525151,0,12321,1,2146528352};
  107651. int onesize=33;
  107652. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  107653. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  107654. 223,4};
  107655. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  107656. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  107657. 245,251,128};
  107658. int twosize=6;
  107659. static int two[6]={61,255,255,251,231,29};
  107660. static int twoB[6]={247,63,255,253,249,120};
  107661. int threesize=54;
  107662. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  107663. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  107664. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  107665. 100,52,4,14,18,86,77,1};
  107666. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  107667. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  107668. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  107669. 200,20,254,4,58,106,176,144,0};
  107670. int foursize=38;
  107671. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  107672. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  107673. 28,2,133,0,1};
  107674. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  107675. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  107676. 129,10,4,32};
  107677. int fivesize=45;
  107678. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  107679. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  107680. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  107681. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  107682. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  107683. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  107684. int sixsize=7;
  107685. static int six[7]={17,177,170,242,169,19,148};
  107686. static int sixB[7]={136,141,85,79,149,200,41};
  107687. /* Test read/write together */
  107688. /* Later we test against pregenerated bitstreams */
  107689. oggpack_writeinit(&o);
  107690. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  107691. cliptest(testbuffer1,test1size,0,one,onesize);
  107692. fprintf(stderr,"ok.");
  107693. fprintf(stderr,"\nNull bit call (LSb): ");
  107694. cliptest(testbuffer3,test3size,0,two,twosize);
  107695. fprintf(stderr,"ok.");
  107696. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  107697. cliptest(testbuffer2,test2size,0,three,threesize);
  107698. fprintf(stderr,"ok.");
  107699. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  107700. oggpack_reset(&o);
  107701. for(i=0;i<test2size;i++)
  107702. oggpack_write(&o,large[i],32);
  107703. buffer=oggpack_get_buffer(&o);
  107704. bytes=oggpack_bytes(&o);
  107705. oggpack_readinit(&r,buffer,bytes);
  107706. for(i=0;i<test2size;i++){
  107707. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  107708. if(oggpack_look(&r,32)!=large[i]){
  107709. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  107710. oggpack_look(&r,32),large[i]);
  107711. report("read incorrect value!\n");
  107712. }
  107713. oggpack_adv(&r,32);
  107714. }
  107715. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107716. fprintf(stderr,"ok.");
  107717. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  107718. cliptest(testbuffer1,test1size,7,four,foursize);
  107719. fprintf(stderr,"ok.");
  107720. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  107721. cliptest(testbuffer2,test2size,17,five,fivesize);
  107722. fprintf(stderr,"ok.");
  107723. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  107724. cliptest(testbuffer3,test3size,1,six,sixsize);
  107725. fprintf(stderr,"ok.");
  107726. fprintf(stderr,"\nTesting read past end (LSb): ");
  107727. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107728. for(i=0;i<64;i++){
  107729. if(oggpack_read(&r,1)!=0){
  107730. fprintf(stderr,"failed; got -1 prematurely.\n");
  107731. exit(1);
  107732. }
  107733. }
  107734. if(oggpack_look(&r,1)!=-1 ||
  107735. oggpack_read(&r,1)!=-1){
  107736. fprintf(stderr,"failed; read past end without -1.\n");
  107737. exit(1);
  107738. }
  107739. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107740. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  107741. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  107742. exit(1);
  107743. }
  107744. if(oggpack_look(&r,18)!=0 ||
  107745. oggpack_look(&r,18)!=0){
  107746. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  107747. exit(1);
  107748. }
  107749. if(oggpack_look(&r,19)!=-1 ||
  107750. oggpack_look(&r,19)!=-1){
  107751. fprintf(stderr,"failed; read past end without -1.\n");
  107752. exit(1);
  107753. }
  107754. if(oggpack_look(&r,32)!=-1 ||
  107755. oggpack_look(&r,32)!=-1){
  107756. fprintf(stderr,"failed; read past end without -1.\n");
  107757. exit(1);
  107758. }
  107759. oggpack_writeclear(&o);
  107760. fprintf(stderr,"ok.\n");
  107761. /********** lazy, cut-n-paste retest with MSb packing ***********/
  107762. /* Test read/write together */
  107763. /* Later we test against pregenerated bitstreams */
  107764. oggpackB_writeinit(&o);
  107765. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  107766. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  107767. fprintf(stderr,"ok.");
  107768. fprintf(stderr,"\nNull bit call (MSb): ");
  107769. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  107770. fprintf(stderr,"ok.");
  107771. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  107772. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  107773. fprintf(stderr,"ok.");
  107774. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  107775. oggpackB_reset(&o);
  107776. for(i=0;i<test2size;i++)
  107777. oggpackB_write(&o,large[i],32);
  107778. buffer=oggpackB_get_buffer(&o);
  107779. bytes=oggpackB_bytes(&o);
  107780. oggpackB_readinit(&r,buffer,bytes);
  107781. for(i=0;i<test2size;i++){
  107782. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  107783. if(oggpackB_look(&r,32)!=large[i]){
  107784. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  107785. oggpackB_look(&r,32),large[i]);
  107786. report("read incorrect value!\n");
  107787. }
  107788. oggpackB_adv(&r,32);
  107789. }
  107790. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107791. fprintf(stderr,"ok.");
  107792. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  107793. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  107794. fprintf(stderr,"ok.");
  107795. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  107796. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  107797. fprintf(stderr,"ok.");
  107798. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  107799. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  107800. fprintf(stderr,"ok.");
  107801. fprintf(stderr,"\nTesting read past end (MSb): ");
  107802. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107803. for(i=0;i<64;i++){
  107804. if(oggpackB_read(&r,1)!=0){
  107805. fprintf(stderr,"failed; got -1 prematurely.\n");
  107806. exit(1);
  107807. }
  107808. }
  107809. if(oggpackB_look(&r,1)!=-1 ||
  107810. oggpackB_read(&r,1)!=-1){
  107811. fprintf(stderr,"failed; read past end without -1.\n");
  107812. exit(1);
  107813. }
  107814. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107815. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  107816. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  107817. exit(1);
  107818. }
  107819. if(oggpackB_look(&r,18)!=0 ||
  107820. oggpackB_look(&r,18)!=0){
  107821. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  107822. exit(1);
  107823. }
  107824. if(oggpackB_look(&r,19)!=-1 ||
  107825. oggpackB_look(&r,19)!=-1){
  107826. fprintf(stderr,"failed; read past end without -1.\n");
  107827. exit(1);
  107828. }
  107829. if(oggpackB_look(&r,32)!=-1 ||
  107830. oggpackB_look(&r,32)!=-1){
  107831. fprintf(stderr,"failed; read past end without -1.\n");
  107832. exit(1);
  107833. }
  107834. oggpackB_writeclear(&o);
  107835. fprintf(stderr,"ok.\n\n");
  107836. return(0);
  107837. }
  107838. #endif /* _V_SELFTEST */
  107839. #undef BUFFER_INCREMENT
  107840. #endif
  107841. /*** End of inlined file: bitwise.c ***/
  107842. /*** Start of inlined file: framing.c ***/
  107843. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107844. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107845. // tasks..
  107846. #if JUCE_MSVC
  107847. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107848. #endif
  107849. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107850. #if JUCE_USE_OGGVORBIS
  107851. #include <stdlib.h>
  107852. #include <string.h>
  107853. /* A complete description of Ogg framing exists in docs/framing.html */
  107854. int ogg_page_version(ogg_page *og){
  107855. return((int)(og->header[4]));
  107856. }
  107857. int ogg_page_continued(ogg_page *og){
  107858. return((int)(og->header[5]&0x01));
  107859. }
  107860. int ogg_page_bos(ogg_page *og){
  107861. return((int)(og->header[5]&0x02));
  107862. }
  107863. int ogg_page_eos(ogg_page *og){
  107864. return((int)(og->header[5]&0x04));
  107865. }
  107866. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  107867. unsigned char *page=og->header;
  107868. ogg_int64_t granulepos=page[13]&(0xff);
  107869. granulepos= (granulepos<<8)|(page[12]&0xff);
  107870. granulepos= (granulepos<<8)|(page[11]&0xff);
  107871. granulepos= (granulepos<<8)|(page[10]&0xff);
  107872. granulepos= (granulepos<<8)|(page[9]&0xff);
  107873. granulepos= (granulepos<<8)|(page[8]&0xff);
  107874. granulepos= (granulepos<<8)|(page[7]&0xff);
  107875. granulepos= (granulepos<<8)|(page[6]&0xff);
  107876. return(granulepos);
  107877. }
  107878. int ogg_page_serialno(ogg_page *og){
  107879. return(og->header[14] |
  107880. (og->header[15]<<8) |
  107881. (og->header[16]<<16) |
  107882. (og->header[17]<<24));
  107883. }
  107884. long ogg_page_pageno(ogg_page *og){
  107885. return(og->header[18] |
  107886. (og->header[19]<<8) |
  107887. (og->header[20]<<16) |
  107888. (og->header[21]<<24));
  107889. }
  107890. /* returns the number of packets that are completed on this page (if
  107891. the leading packet is begun on a previous page, but ends on this
  107892. page, it's counted */
  107893. /* NOTE:
  107894. If a page consists of a packet begun on a previous page, and a new
  107895. packet begun (but not completed) on this page, the return will be:
  107896. ogg_page_packets(page) ==1,
  107897. ogg_page_continued(page) !=0
  107898. If a page happens to be a single packet that was begun on a
  107899. previous page, and spans to the next page (in the case of a three or
  107900. more page packet), the return will be:
  107901. ogg_page_packets(page) ==0,
  107902. ogg_page_continued(page) !=0
  107903. */
  107904. int ogg_page_packets(ogg_page *og){
  107905. int i,n=og->header[26],count=0;
  107906. for(i=0;i<n;i++)
  107907. if(og->header[27+i]<255)count++;
  107908. return(count);
  107909. }
  107910. #if 0
  107911. /* helper to initialize lookup for direct-table CRC (illustrative; we
  107912. use the static init below) */
  107913. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  107914. int i;
  107915. unsigned long r;
  107916. r = index << 24;
  107917. for (i=0; i<8; i++)
  107918. if (r & 0x80000000UL)
  107919. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  107920. polynomial, although we use an
  107921. unreflected alg and an init/final
  107922. of 0, not 0xffffffff */
  107923. else
  107924. r<<=1;
  107925. return (r & 0xffffffffUL);
  107926. }
  107927. #endif
  107928. static const ogg_uint32_t crc_lookup[256]={
  107929. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  107930. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  107931. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  107932. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  107933. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  107934. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  107935. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  107936. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  107937. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  107938. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  107939. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  107940. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  107941. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  107942. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  107943. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  107944. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  107945. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  107946. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  107947. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  107948. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  107949. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  107950. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  107951. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  107952. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  107953. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  107954. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  107955. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  107956. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  107957. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  107958. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  107959. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  107960. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  107961. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  107962. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  107963. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  107964. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  107965. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  107966. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  107967. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  107968. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  107969. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  107970. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  107971. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  107972. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  107973. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  107974. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  107975. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  107976. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  107977. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  107978. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  107979. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  107980. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  107981. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  107982. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  107983. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  107984. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  107985. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  107986. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  107987. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  107988. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  107989. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  107990. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  107991. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  107992. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  107993. /* init the encode/decode logical stream state */
  107994. int ogg_stream_init(ogg_stream_state *os,int serialno){
  107995. if(os){
  107996. memset(os,0,sizeof(*os));
  107997. os->body_storage=16*1024;
  107998. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  107999. os->lacing_storage=1024;
  108000. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108001. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108002. os->serialno=serialno;
  108003. return(0);
  108004. }
  108005. return(-1);
  108006. }
  108007. /* _clear does not free os, only the non-flat storage within */
  108008. int ogg_stream_clear(ogg_stream_state *os){
  108009. if(os){
  108010. if(os->body_data)_ogg_free(os->body_data);
  108011. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108012. if(os->granule_vals)_ogg_free(os->granule_vals);
  108013. memset(os,0,sizeof(*os));
  108014. }
  108015. return(0);
  108016. }
  108017. int ogg_stream_destroy(ogg_stream_state *os){
  108018. if(os){
  108019. ogg_stream_clear(os);
  108020. _ogg_free(os);
  108021. }
  108022. return(0);
  108023. }
  108024. /* Helpers for ogg_stream_encode; this keeps the structure and
  108025. what's happening fairly clear */
  108026. static void _os_body_expand(ogg_stream_state *os,int needed){
  108027. if(os->body_storage<=os->body_fill+needed){
  108028. os->body_storage+=(needed+1024);
  108029. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108030. }
  108031. }
  108032. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108033. if(os->lacing_storage<=os->lacing_fill+needed){
  108034. os->lacing_storage+=(needed+32);
  108035. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108036. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108037. }
  108038. }
  108039. /* checksum the page */
  108040. /* Direct table CRC; note that this will be faster in the future if we
  108041. perform the checksum silmultaneously with other copies */
  108042. void ogg_page_checksum_set(ogg_page *og){
  108043. if(og){
  108044. ogg_uint32_t crc_reg=0;
  108045. int i;
  108046. /* safety; needed for API behavior, but not framing code */
  108047. og->header[22]=0;
  108048. og->header[23]=0;
  108049. og->header[24]=0;
  108050. og->header[25]=0;
  108051. for(i=0;i<og->header_len;i++)
  108052. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108053. for(i=0;i<og->body_len;i++)
  108054. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108055. og->header[22]=(unsigned char)(crc_reg&0xff);
  108056. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108057. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108058. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108059. }
  108060. }
  108061. /* submit data to the internal buffer of the framing engine */
  108062. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108063. int lacing_vals=op->bytes/255+1,i;
  108064. if(os->body_returned){
  108065. /* advance packet data according to the body_returned pointer. We
  108066. had to keep it around to return a pointer into the buffer last
  108067. call */
  108068. os->body_fill-=os->body_returned;
  108069. if(os->body_fill)
  108070. memmove(os->body_data,os->body_data+os->body_returned,
  108071. os->body_fill);
  108072. os->body_returned=0;
  108073. }
  108074. /* make sure we have the buffer storage */
  108075. _os_body_expand(os,op->bytes);
  108076. _os_lacing_expand(os,lacing_vals);
  108077. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108078. the liability of overly clean abstraction for the time being. It
  108079. will actually be fairly easy to eliminate the extra copy in the
  108080. future */
  108081. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108082. os->body_fill+=op->bytes;
  108083. /* Store lacing vals for this packet */
  108084. for(i=0;i<lacing_vals-1;i++){
  108085. os->lacing_vals[os->lacing_fill+i]=255;
  108086. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108087. }
  108088. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108089. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108090. /* flag the first segment as the beginning of the packet */
  108091. os->lacing_vals[os->lacing_fill]|= 0x100;
  108092. os->lacing_fill+=lacing_vals;
  108093. /* for the sake of completeness */
  108094. os->packetno++;
  108095. if(op->e_o_s)os->e_o_s=1;
  108096. return(0);
  108097. }
  108098. /* This will flush remaining packets into a page (returning nonzero),
  108099. even if there is not enough data to trigger a flush normally
  108100. (undersized page). If there are no packets or partial packets to
  108101. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108102. try to flush a normal sized page like ogg_stream_pageout; a call to
  108103. ogg_stream_flush does not guarantee that all packets have flushed.
  108104. Only a return value of 0 from ogg_stream_flush indicates all packet
  108105. data is flushed into pages.
  108106. since ogg_stream_flush will flush the last page in a stream even if
  108107. it's undersized, you almost certainly want to use ogg_stream_pageout
  108108. (and *not* ogg_stream_flush) unless you specifically need to flush
  108109. an page regardless of size in the middle of a stream. */
  108110. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108111. int i;
  108112. int vals=0;
  108113. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108114. int bytes=0;
  108115. long acc=0;
  108116. ogg_int64_t granule_pos=-1;
  108117. if(maxvals==0)return(0);
  108118. /* construct a page */
  108119. /* decide how many segments to include */
  108120. /* If this is the initial header case, the first page must only include
  108121. the initial header packet */
  108122. if(os->b_o_s==0){ /* 'initial header page' case */
  108123. granule_pos=0;
  108124. for(vals=0;vals<maxvals;vals++){
  108125. if((os->lacing_vals[vals]&0x0ff)<255){
  108126. vals++;
  108127. break;
  108128. }
  108129. }
  108130. }else{
  108131. for(vals=0;vals<maxvals;vals++){
  108132. if(acc>4096)break;
  108133. acc+=os->lacing_vals[vals]&0x0ff;
  108134. if((os->lacing_vals[vals]&0xff)<255)
  108135. granule_pos=os->granule_vals[vals];
  108136. }
  108137. }
  108138. /* construct the header in temp storage */
  108139. memcpy(os->header,"OggS",4);
  108140. /* stream structure version */
  108141. os->header[4]=0x00;
  108142. /* continued packet flag? */
  108143. os->header[5]=0x00;
  108144. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108145. /* first page flag? */
  108146. if(os->b_o_s==0)os->header[5]|=0x02;
  108147. /* last page flag? */
  108148. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108149. os->b_o_s=1;
  108150. /* 64 bits of PCM position */
  108151. for(i=6;i<14;i++){
  108152. os->header[i]=(unsigned char)(granule_pos&0xff);
  108153. granule_pos>>=8;
  108154. }
  108155. /* 32 bits of stream serial number */
  108156. {
  108157. long serialno=os->serialno;
  108158. for(i=14;i<18;i++){
  108159. os->header[i]=(unsigned char)(serialno&0xff);
  108160. serialno>>=8;
  108161. }
  108162. }
  108163. /* 32 bits of page counter (we have both counter and page header
  108164. because this val can roll over) */
  108165. if(os->pageno==-1)os->pageno=0; /* because someone called
  108166. stream_reset; this would be a
  108167. strange thing to do in an
  108168. encode stream, but it has
  108169. plausible uses */
  108170. {
  108171. long pageno=os->pageno++;
  108172. for(i=18;i<22;i++){
  108173. os->header[i]=(unsigned char)(pageno&0xff);
  108174. pageno>>=8;
  108175. }
  108176. }
  108177. /* zero for computation; filled in later */
  108178. os->header[22]=0;
  108179. os->header[23]=0;
  108180. os->header[24]=0;
  108181. os->header[25]=0;
  108182. /* segment table */
  108183. os->header[26]=(unsigned char)(vals&0xff);
  108184. for(i=0;i<vals;i++)
  108185. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108186. /* set pointers in the ogg_page struct */
  108187. og->header=os->header;
  108188. og->header_len=os->header_fill=vals+27;
  108189. og->body=os->body_data+os->body_returned;
  108190. og->body_len=bytes;
  108191. /* advance the lacing data and set the body_returned pointer */
  108192. os->lacing_fill-=vals;
  108193. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108194. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108195. os->body_returned+=bytes;
  108196. /* calculate the checksum */
  108197. ogg_page_checksum_set(og);
  108198. /* done */
  108199. return(1);
  108200. }
  108201. /* This constructs pages from buffered packet segments. The pointers
  108202. returned are to static buffers; do not free. The returned buffers are
  108203. good only until the next call (using the same ogg_stream_state) */
  108204. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108205. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108206. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108207. os->lacing_fill>=255 || /* 'segment table full' case */
  108208. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108209. return(ogg_stream_flush(os,og));
  108210. }
  108211. /* not enough data to construct a page and not end of stream */
  108212. return(0);
  108213. }
  108214. int ogg_stream_eos(ogg_stream_state *os){
  108215. return os->e_o_s;
  108216. }
  108217. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108218. /* This has two layers to place more of the multi-serialno and paging
  108219. control in the application's hands. First, we expose a data buffer
  108220. using ogg_sync_buffer(). The app either copies into the
  108221. buffer, or passes it directly to read(), etc. We then call
  108222. ogg_sync_wrote() to tell how many bytes we just added.
  108223. Pages are returned (pointers into the buffer in ogg_sync_state)
  108224. by ogg_sync_pageout(). The page is then submitted to
  108225. ogg_stream_pagein() along with the appropriate
  108226. ogg_stream_state* (ie, matching serialno). We then get raw
  108227. packets out calling ogg_stream_packetout() with a
  108228. ogg_stream_state. */
  108229. /* initialize the struct to a known state */
  108230. int ogg_sync_init(ogg_sync_state *oy){
  108231. if(oy){
  108232. memset(oy,0,sizeof(*oy));
  108233. }
  108234. return(0);
  108235. }
  108236. /* clear non-flat storage within */
  108237. int ogg_sync_clear(ogg_sync_state *oy){
  108238. if(oy){
  108239. if(oy->data)_ogg_free(oy->data);
  108240. ogg_sync_init(oy);
  108241. }
  108242. return(0);
  108243. }
  108244. int ogg_sync_destroy(ogg_sync_state *oy){
  108245. if(oy){
  108246. ogg_sync_clear(oy);
  108247. _ogg_free(oy);
  108248. }
  108249. return(0);
  108250. }
  108251. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108252. /* first, clear out any space that has been previously returned */
  108253. if(oy->returned){
  108254. oy->fill-=oy->returned;
  108255. if(oy->fill>0)
  108256. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108257. oy->returned=0;
  108258. }
  108259. if(size>oy->storage-oy->fill){
  108260. /* We need to extend the internal buffer */
  108261. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108262. if(oy->data)
  108263. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  108264. else
  108265. oy->data=(unsigned char*) _ogg_malloc(newsize);
  108266. oy->storage=newsize;
  108267. }
  108268. /* expose a segment at least as large as requested at the fill mark */
  108269. return((char *)oy->data+oy->fill);
  108270. }
  108271. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  108272. if(oy->fill+bytes>oy->storage)return(-1);
  108273. oy->fill+=bytes;
  108274. return(0);
  108275. }
  108276. /* sync the stream. This is meant to be useful for finding page
  108277. boundaries.
  108278. return values for this:
  108279. -n) skipped n bytes
  108280. 0) page not ready; more data (no bytes skipped)
  108281. n) page synced at current location; page length n bytes
  108282. */
  108283. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  108284. unsigned char *page=oy->data+oy->returned;
  108285. unsigned char *next;
  108286. long bytes=oy->fill-oy->returned;
  108287. if(oy->headerbytes==0){
  108288. int headerbytes,i;
  108289. if(bytes<27)return(0); /* not enough for a header */
  108290. /* verify capture pattern */
  108291. if(memcmp(page,"OggS",4))goto sync_fail;
  108292. headerbytes=page[26]+27;
  108293. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  108294. /* count up body length in the segment table */
  108295. for(i=0;i<page[26];i++)
  108296. oy->bodybytes+=page[27+i];
  108297. oy->headerbytes=headerbytes;
  108298. }
  108299. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  108300. /* The whole test page is buffered. Verify the checksum */
  108301. {
  108302. /* Grab the checksum bytes, set the header field to zero */
  108303. char chksum[4];
  108304. ogg_page log;
  108305. memcpy(chksum,page+22,4);
  108306. memset(page+22,0,4);
  108307. /* set up a temp page struct and recompute the checksum */
  108308. log.header=page;
  108309. log.header_len=oy->headerbytes;
  108310. log.body=page+oy->headerbytes;
  108311. log.body_len=oy->bodybytes;
  108312. ogg_page_checksum_set(&log);
  108313. /* Compare */
  108314. if(memcmp(chksum,page+22,4)){
  108315. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108316. at all) */
  108317. /* replace the computed checksum with the one actually read in */
  108318. memcpy(page+22,chksum,4);
  108319. /* Bad checksum. Lose sync */
  108320. goto sync_fail;
  108321. }
  108322. }
  108323. /* yes, have a whole page all ready to go */
  108324. {
  108325. unsigned char *page=oy->data+oy->returned;
  108326. long bytes;
  108327. if(og){
  108328. og->header=page;
  108329. og->header_len=oy->headerbytes;
  108330. og->body=page+oy->headerbytes;
  108331. og->body_len=oy->bodybytes;
  108332. }
  108333. oy->unsynced=0;
  108334. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108335. oy->headerbytes=0;
  108336. oy->bodybytes=0;
  108337. return(bytes);
  108338. }
  108339. sync_fail:
  108340. oy->headerbytes=0;
  108341. oy->bodybytes=0;
  108342. /* search for possible capture */
  108343. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108344. if(!next)
  108345. next=oy->data+oy->fill;
  108346. oy->returned=next-oy->data;
  108347. return(-(next-page));
  108348. }
  108349. /* sync the stream and get a page. Keep trying until we find a page.
  108350. Supress 'sync errors' after reporting the first.
  108351. return values:
  108352. -1) recapture (hole in data)
  108353. 0) need more data
  108354. 1) page returned
  108355. Returns pointers into buffered data; invalidated by next call to
  108356. _stream, _clear, _init, or _buffer */
  108357. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108358. /* all we need to do is verify a page at the head of the stream
  108359. buffer. If it doesn't verify, we look for the next potential
  108360. frame */
  108361. for(;;){
  108362. long ret=ogg_sync_pageseek(oy,og);
  108363. if(ret>0){
  108364. /* have a page */
  108365. return(1);
  108366. }
  108367. if(ret==0){
  108368. /* need more data */
  108369. return(0);
  108370. }
  108371. /* head did not start a synced page... skipped some bytes */
  108372. if(!oy->unsynced){
  108373. oy->unsynced=1;
  108374. return(-1);
  108375. }
  108376. /* loop. keep looking */
  108377. }
  108378. }
  108379. /* add the incoming page to the stream state; we decompose the page
  108380. into packet segments here as well. */
  108381. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  108382. unsigned char *header=og->header;
  108383. unsigned char *body=og->body;
  108384. long bodysize=og->body_len;
  108385. int segptr=0;
  108386. int version=ogg_page_version(og);
  108387. int continued=ogg_page_continued(og);
  108388. int bos=ogg_page_bos(og);
  108389. int eos=ogg_page_eos(og);
  108390. ogg_int64_t granulepos=ogg_page_granulepos(og);
  108391. int serialno=ogg_page_serialno(og);
  108392. long pageno=ogg_page_pageno(og);
  108393. int segments=header[26];
  108394. /* clean up 'returned data' */
  108395. {
  108396. long lr=os->lacing_returned;
  108397. long br=os->body_returned;
  108398. /* body data */
  108399. if(br){
  108400. os->body_fill-=br;
  108401. if(os->body_fill)
  108402. memmove(os->body_data,os->body_data+br,os->body_fill);
  108403. os->body_returned=0;
  108404. }
  108405. if(lr){
  108406. /* segment table */
  108407. if(os->lacing_fill-lr){
  108408. memmove(os->lacing_vals,os->lacing_vals+lr,
  108409. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  108410. memmove(os->granule_vals,os->granule_vals+lr,
  108411. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  108412. }
  108413. os->lacing_fill-=lr;
  108414. os->lacing_packet-=lr;
  108415. os->lacing_returned=0;
  108416. }
  108417. }
  108418. /* check the serial number */
  108419. if(serialno!=os->serialno)return(-1);
  108420. if(version>0)return(-1);
  108421. _os_lacing_expand(os,segments+1);
  108422. /* are we in sequence? */
  108423. if(pageno!=os->pageno){
  108424. int i;
  108425. /* unroll previous partial packet (if any) */
  108426. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  108427. os->body_fill-=os->lacing_vals[i]&0xff;
  108428. os->lacing_fill=os->lacing_packet;
  108429. /* make a note of dropped data in segment table */
  108430. if(os->pageno!=-1){
  108431. os->lacing_vals[os->lacing_fill++]=0x400;
  108432. os->lacing_packet++;
  108433. }
  108434. }
  108435. /* are we a 'continued packet' page? If so, we may need to skip
  108436. some segments */
  108437. if(continued){
  108438. if(os->lacing_fill<1 ||
  108439. os->lacing_vals[os->lacing_fill-1]==0x400){
  108440. bos=0;
  108441. for(;segptr<segments;segptr++){
  108442. int val=header[27+segptr];
  108443. body+=val;
  108444. bodysize-=val;
  108445. if(val<255){
  108446. segptr++;
  108447. break;
  108448. }
  108449. }
  108450. }
  108451. }
  108452. if(bodysize){
  108453. _os_body_expand(os,bodysize);
  108454. memcpy(os->body_data+os->body_fill,body,bodysize);
  108455. os->body_fill+=bodysize;
  108456. }
  108457. {
  108458. int saved=-1;
  108459. while(segptr<segments){
  108460. int val=header[27+segptr];
  108461. os->lacing_vals[os->lacing_fill]=val;
  108462. os->granule_vals[os->lacing_fill]=-1;
  108463. if(bos){
  108464. os->lacing_vals[os->lacing_fill]|=0x100;
  108465. bos=0;
  108466. }
  108467. if(val<255)saved=os->lacing_fill;
  108468. os->lacing_fill++;
  108469. segptr++;
  108470. if(val<255)os->lacing_packet=os->lacing_fill;
  108471. }
  108472. /* set the granulepos on the last granuleval of the last full packet */
  108473. if(saved!=-1){
  108474. os->granule_vals[saved]=granulepos;
  108475. }
  108476. }
  108477. if(eos){
  108478. os->e_o_s=1;
  108479. if(os->lacing_fill>0)
  108480. os->lacing_vals[os->lacing_fill-1]|=0x200;
  108481. }
  108482. os->pageno=pageno+1;
  108483. return(0);
  108484. }
  108485. /* clear things to an initial state. Good to call, eg, before seeking */
  108486. int ogg_sync_reset(ogg_sync_state *oy){
  108487. oy->fill=0;
  108488. oy->returned=0;
  108489. oy->unsynced=0;
  108490. oy->headerbytes=0;
  108491. oy->bodybytes=0;
  108492. return(0);
  108493. }
  108494. int ogg_stream_reset(ogg_stream_state *os){
  108495. os->body_fill=0;
  108496. os->body_returned=0;
  108497. os->lacing_fill=0;
  108498. os->lacing_packet=0;
  108499. os->lacing_returned=0;
  108500. os->header_fill=0;
  108501. os->e_o_s=0;
  108502. os->b_o_s=0;
  108503. os->pageno=-1;
  108504. os->packetno=0;
  108505. os->granulepos=0;
  108506. return(0);
  108507. }
  108508. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  108509. ogg_stream_reset(os);
  108510. os->serialno=serialno;
  108511. return(0);
  108512. }
  108513. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  108514. /* The last part of decode. We have the stream broken into packet
  108515. segments. Now we need to group them into packets (or return the
  108516. out of sync markers) */
  108517. int ptr=os->lacing_returned;
  108518. if(os->lacing_packet<=ptr)return(0);
  108519. if(os->lacing_vals[ptr]&0x400){
  108520. /* we need to tell the codec there's a gap; it might need to
  108521. handle previous packet dependencies. */
  108522. os->lacing_returned++;
  108523. os->packetno++;
  108524. return(-1);
  108525. }
  108526. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  108527. to ask if there's a whole packet
  108528. waiting */
  108529. /* Gather the whole packet. We'll have no holes or a partial packet */
  108530. {
  108531. int size=os->lacing_vals[ptr]&0xff;
  108532. int bytes=size;
  108533. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  108534. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  108535. while(size==255){
  108536. int val=os->lacing_vals[++ptr];
  108537. size=val&0xff;
  108538. if(val&0x200)eos=0x200;
  108539. bytes+=size;
  108540. }
  108541. if(op){
  108542. op->e_o_s=eos;
  108543. op->b_o_s=bos;
  108544. op->packet=os->body_data+os->body_returned;
  108545. op->packetno=os->packetno;
  108546. op->granulepos=os->granule_vals[ptr];
  108547. op->bytes=bytes;
  108548. }
  108549. if(adv){
  108550. os->body_returned+=bytes;
  108551. os->lacing_returned=ptr+1;
  108552. os->packetno++;
  108553. }
  108554. }
  108555. return(1);
  108556. }
  108557. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  108558. return _packetout(os,op,1);
  108559. }
  108560. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  108561. return _packetout(os,op,0);
  108562. }
  108563. void ogg_packet_clear(ogg_packet *op) {
  108564. _ogg_free(op->packet);
  108565. memset(op, 0, sizeof(*op));
  108566. }
  108567. #ifdef _V_SELFTEST
  108568. #include <stdio.h>
  108569. ogg_stream_state os_en, os_de;
  108570. ogg_sync_state oy;
  108571. void checkpacket(ogg_packet *op,int len, int no, int pos){
  108572. long j;
  108573. static int sequence=0;
  108574. static int lastno=0;
  108575. if(op->bytes!=len){
  108576. fprintf(stderr,"incorrect packet length!\n");
  108577. exit(1);
  108578. }
  108579. if(op->granulepos!=pos){
  108580. fprintf(stderr,"incorrect packet position!\n");
  108581. exit(1);
  108582. }
  108583. /* packet number just follows sequence/gap; adjust the input number
  108584. for that */
  108585. if(no==0){
  108586. sequence=0;
  108587. }else{
  108588. sequence++;
  108589. if(no>lastno+1)
  108590. sequence++;
  108591. }
  108592. lastno=no;
  108593. if(op->packetno!=sequence){
  108594. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  108595. (long)(op->packetno),sequence);
  108596. exit(1);
  108597. }
  108598. /* Test data */
  108599. for(j=0;j<op->bytes;j++)
  108600. if(op->packet[j]!=((j+no)&0xff)){
  108601. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  108602. j,op->packet[j],(j+no)&0xff);
  108603. exit(1);
  108604. }
  108605. }
  108606. void check_page(unsigned char *data,const int *header,ogg_page *og){
  108607. long j;
  108608. /* Test data */
  108609. for(j=0;j<og->body_len;j++)
  108610. if(og->body[j]!=data[j]){
  108611. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  108612. j,data[j],og->body[j]);
  108613. exit(1);
  108614. }
  108615. /* Test header */
  108616. for(j=0;j<og->header_len;j++){
  108617. if(og->header[j]!=header[j]){
  108618. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  108619. for(j=0;j<header[26]+27;j++)
  108620. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  108621. fprintf(stderr,"\n");
  108622. exit(1);
  108623. }
  108624. }
  108625. if(og->header_len!=header[26]+27){
  108626. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  108627. og->header_len,header[26]+27);
  108628. exit(1);
  108629. }
  108630. }
  108631. void print_header(ogg_page *og){
  108632. int j;
  108633. fprintf(stderr,"\nHEADER:\n");
  108634. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  108635. og->header[0],og->header[1],og->header[2],og->header[3],
  108636. (int)og->header[4],(int)og->header[5]);
  108637. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  108638. (og->header[9]<<24)|(og->header[8]<<16)|
  108639. (og->header[7]<<8)|og->header[6],
  108640. (og->header[17]<<24)|(og->header[16]<<16)|
  108641. (og->header[15]<<8)|og->header[14],
  108642. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  108643. (og->header[19]<<8)|og->header[18]);
  108644. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  108645. (int)og->header[22],(int)og->header[23],
  108646. (int)og->header[24],(int)og->header[25],
  108647. (int)og->header[26]);
  108648. for(j=27;j<og->header_len;j++)
  108649. fprintf(stderr,"%d ",(int)og->header[j]);
  108650. fprintf(stderr,")\n\n");
  108651. }
  108652. void copy_page(ogg_page *og){
  108653. unsigned char *temp=_ogg_malloc(og->header_len);
  108654. memcpy(temp,og->header,og->header_len);
  108655. og->header=temp;
  108656. temp=_ogg_malloc(og->body_len);
  108657. memcpy(temp,og->body,og->body_len);
  108658. og->body=temp;
  108659. }
  108660. void free_page(ogg_page *og){
  108661. _ogg_free (og->header);
  108662. _ogg_free (og->body);
  108663. }
  108664. void error(void){
  108665. fprintf(stderr,"error!\n");
  108666. exit(1);
  108667. }
  108668. /* 17 only */
  108669. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  108670. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108671. 0x01,0x02,0x03,0x04,0,0,0,0,
  108672. 0x15,0xed,0xec,0x91,
  108673. 1,
  108674. 17};
  108675. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  108676. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108677. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108678. 0x01,0x02,0x03,0x04,0,0,0,0,
  108679. 0x59,0x10,0x6c,0x2c,
  108680. 1,
  108681. 17};
  108682. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108683. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  108684. 0x01,0x02,0x03,0x04,1,0,0,0,
  108685. 0x89,0x33,0x85,0xce,
  108686. 13,
  108687. 254,255,0,255,1,255,245,255,255,0,
  108688. 255,255,90};
  108689. /* nil packets; beginning,middle,end */
  108690. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108691. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108692. 0x01,0x02,0x03,0x04,0,0,0,0,
  108693. 0xff,0x7b,0x23,0x17,
  108694. 1,
  108695. 0};
  108696. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108697. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  108698. 0x01,0x02,0x03,0x04,1,0,0,0,
  108699. 0x5c,0x3f,0x66,0xcb,
  108700. 17,
  108701. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  108702. 255,255,90,0};
  108703. /* large initial packet */
  108704. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108705. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108706. 0x01,0x02,0x03,0x04,0,0,0,0,
  108707. 0x01,0x27,0x31,0xaa,
  108708. 18,
  108709. 255,255,255,255,255,255,255,255,
  108710. 255,255,255,255,255,255,255,255,255,10};
  108711. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108712. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  108713. 0x01,0x02,0x03,0x04,1,0,0,0,
  108714. 0x7f,0x4e,0x8a,0xd2,
  108715. 4,
  108716. 255,4,255,0};
  108717. /* continuing packet test */
  108718. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108719. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108720. 0x01,0x02,0x03,0x04,0,0,0,0,
  108721. 0xff,0x7b,0x23,0x17,
  108722. 1,
  108723. 0};
  108724. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108725. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108726. 0x01,0x02,0x03,0x04,1,0,0,0,
  108727. 0x54,0x05,0x51,0xc8,
  108728. 17,
  108729. 255,255,255,255,255,255,255,255,
  108730. 255,255,255,255,255,255,255,255,255};
  108731. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108732. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  108733. 0x01,0x02,0x03,0x04,2,0,0,0,
  108734. 0xc8,0xc3,0xcb,0xed,
  108735. 5,
  108736. 10,255,4,255,0};
  108737. /* page with the 255 segment limit */
  108738. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108739. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108740. 0x01,0x02,0x03,0x04,0,0,0,0,
  108741. 0xff,0x7b,0x23,0x17,
  108742. 1,
  108743. 0};
  108744. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108745. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  108746. 0x01,0x02,0x03,0x04,1,0,0,0,
  108747. 0xed,0x2a,0x2e,0xa7,
  108748. 255,
  108749. 10,10,10,10,10,10,10,10,
  108750. 10,10,10,10,10,10,10,10,
  108751. 10,10,10,10,10,10,10,10,
  108752. 10,10,10,10,10,10,10,10,
  108753. 10,10,10,10,10,10,10,10,
  108754. 10,10,10,10,10,10,10,10,
  108755. 10,10,10,10,10,10,10,10,
  108756. 10,10,10,10,10,10,10,10,
  108757. 10,10,10,10,10,10,10,10,
  108758. 10,10,10,10,10,10,10,10,
  108759. 10,10,10,10,10,10,10,10,
  108760. 10,10,10,10,10,10,10,10,
  108761. 10,10,10,10,10,10,10,10,
  108762. 10,10,10,10,10,10,10,10,
  108763. 10,10,10,10,10,10,10,10,
  108764. 10,10,10,10,10,10,10,10,
  108765. 10,10,10,10,10,10,10,10,
  108766. 10,10,10,10,10,10,10,10,
  108767. 10,10,10,10,10,10,10,10,
  108768. 10,10,10,10,10,10,10,10,
  108769. 10,10,10,10,10,10,10,10,
  108770. 10,10,10,10,10,10,10,10,
  108771. 10,10,10,10,10,10,10,10,
  108772. 10,10,10,10,10,10,10,10,
  108773. 10,10,10,10,10,10,10,10,
  108774. 10,10,10,10,10,10,10,10,
  108775. 10,10,10,10,10,10,10,10,
  108776. 10,10,10,10,10,10,10,10,
  108777. 10,10,10,10,10,10,10,10,
  108778. 10,10,10,10,10,10,10,10,
  108779. 10,10,10,10,10,10,10,10,
  108780. 10,10,10,10,10,10,10};
  108781. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108782. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  108783. 0x01,0x02,0x03,0x04,2,0,0,0,
  108784. 0x6c,0x3b,0x82,0x3d,
  108785. 1,
  108786. 50};
  108787. /* packet that overspans over an entire page */
  108788. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108789. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108790. 0x01,0x02,0x03,0x04,0,0,0,0,
  108791. 0xff,0x7b,0x23,0x17,
  108792. 1,
  108793. 0};
  108794. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108795. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  108796. 0x01,0x02,0x03,0x04,1,0,0,0,
  108797. 0x3c,0xd9,0x4d,0x3f,
  108798. 17,
  108799. 100,255,255,255,255,255,255,255,255,
  108800. 255,255,255,255,255,255,255,255};
  108801. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  108802. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108803. 0x01,0x02,0x03,0x04,2,0,0,0,
  108804. 0x01,0xd2,0xe5,0xe5,
  108805. 17,
  108806. 255,255,255,255,255,255,255,255,
  108807. 255,255,255,255,255,255,255,255,255};
  108808. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108809. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  108810. 0x01,0x02,0x03,0x04,3,0,0,0,
  108811. 0xef,0xdd,0x88,0xde,
  108812. 7,
  108813. 255,255,75,255,4,255,0};
  108814. /* packet that overspans over an entire page */
  108815. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108816. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108817. 0x01,0x02,0x03,0x04,0,0,0,0,
  108818. 0xff,0x7b,0x23,0x17,
  108819. 1,
  108820. 0};
  108821. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108822. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  108823. 0x01,0x02,0x03,0x04,1,0,0,0,
  108824. 0x3c,0xd9,0x4d,0x3f,
  108825. 17,
  108826. 100,255,255,255,255,255,255,255,255,
  108827. 255,255,255,255,255,255,255,255};
  108828. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108829. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  108830. 0x01,0x02,0x03,0x04,2,0,0,0,
  108831. 0xd4,0xe0,0x60,0xe5,
  108832. 1,0};
  108833. void test_pack(const int *pl, const int **headers, int byteskip,
  108834. int pageskip, int packetskip){
  108835. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  108836. long inptr=0;
  108837. long outptr=0;
  108838. long deptr=0;
  108839. long depacket=0;
  108840. long granule_pos=7,pageno=0;
  108841. int i,j,packets,pageout=pageskip;
  108842. int eosflag=0;
  108843. int bosflag=0;
  108844. int byteskipcount=0;
  108845. ogg_stream_reset(&os_en);
  108846. ogg_stream_reset(&os_de);
  108847. ogg_sync_reset(&oy);
  108848. for(packets=0;packets<packetskip;packets++)
  108849. depacket+=pl[packets];
  108850. for(packets=0;;packets++)if(pl[packets]==-1)break;
  108851. for(i=0;i<packets;i++){
  108852. /* construct a test packet */
  108853. ogg_packet op;
  108854. int len=pl[i];
  108855. op.packet=data+inptr;
  108856. op.bytes=len;
  108857. op.e_o_s=(pl[i+1]<0?1:0);
  108858. op.granulepos=granule_pos;
  108859. granule_pos+=1024;
  108860. for(j=0;j<len;j++)data[inptr++]=i+j;
  108861. /* submit the test packet */
  108862. ogg_stream_packetin(&os_en,&op);
  108863. /* retrieve any finished pages */
  108864. {
  108865. ogg_page og;
  108866. while(ogg_stream_pageout(&os_en,&og)){
  108867. /* We have a page. Check it carefully */
  108868. fprintf(stderr,"%ld, ",pageno);
  108869. if(headers[pageno]==NULL){
  108870. fprintf(stderr,"coded too many pages!\n");
  108871. exit(1);
  108872. }
  108873. check_page(data+outptr,headers[pageno],&og);
  108874. outptr+=og.body_len;
  108875. pageno++;
  108876. if(pageskip){
  108877. bosflag=1;
  108878. pageskip--;
  108879. deptr+=og.body_len;
  108880. }
  108881. /* have a complete page; submit it to sync/decode */
  108882. {
  108883. ogg_page og_de;
  108884. ogg_packet op_de,op_de2;
  108885. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  108886. char *next=buf;
  108887. byteskipcount+=og.header_len;
  108888. if(byteskipcount>byteskip){
  108889. memcpy(next,og.header,byteskipcount-byteskip);
  108890. next+=byteskipcount-byteskip;
  108891. byteskipcount=byteskip;
  108892. }
  108893. byteskipcount+=og.body_len;
  108894. if(byteskipcount>byteskip){
  108895. memcpy(next,og.body,byteskipcount-byteskip);
  108896. next+=byteskipcount-byteskip;
  108897. byteskipcount=byteskip;
  108898. }
  108899. ogg_sync_wrote(&oy,next-buf);
  108900. while(1){
  108901. int ret=ogg_sync_pageout(&oy,&og_de);
  108902. if(ret==0)break;
  108903. if(ret<0)continue;
  108904. /* got a page. Happy happy. Verify that it's good. */
  108905. fprintf(stderr,"(%ld), ",pageout);
  108906. check_page(data+deptr,headers[pageout],&og_de);
  108907. deptr+=og_de.body_len;
  108908. pageout++;
  108909. /* submit it to deconstitution */
  108910. ogg_stream_pagein(&os_de,&og_de);
  108911. /* packets out? */
  108912. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  108913. ogg_stream_packetpeek(&os_de,NULL);
  108914. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  108915. /* verify peek and out match */
  108916. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  108917. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  108918. depacket);
  108919. exit(1);
  108920. }
  108921. /* verify the packet! */
  108922. /* check data */
  108923. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  108924. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  108925. depacket);
  108926. exit(1);
  108927. }
  108928. /* check bos flag */
  108929. if(bosflag==0 && op_de.b_o_s==0){
  108930. fprintf(stderr,"b_o_s flag not set on packet!\n");
  108931. exit(1);
  108932. }
  108933. if(bosflag && op_de.b_o_s){
  108934. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  108935. exit(1);
  108936. }
  108937. bosflag=1;
  108938. depacket+=op_de.bytes;
  108939. /* check eos flag */
  108940. if(eosflag){
  108941. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  108942. exit(1);
  108943. }
  108944. if(op_de.e_o_s)eosflag=1;
  108945. /* check granulepos flag */
  108946. if(op_de.granulepos!=-1){
  108947. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  108948. }
  108949. }
  108950. }
  108951. }
  108952. }
  108953. }
  108954. }
  108955. _ogg_free(data);
  108956. if(headers[pageno]!=NULL){
  108957. fprintf(stderr,"did not write last page!\n");
  108958. exit(1);
  108959. }
  108960. if(headers[pageout]!=NULL){
  108961. fprintf(stderr,"did not decode last page!\n");
  108962. exit(1);
  108963. }
  108964. if(inptr!=outptr){
  108965. fprintf(stderr,"encoded page data incomplete!\n");
  108966. exit(1);
  108967. }
  108968. if(inptr!=deptr){
  108969. fprintf(stderr,"decoded page data incomplete!\n");
  108970. exit(1);
  108971. }
  108972. if(inptr!=depacket){
  108973. fprintf(stderr,"decoded packet data incomplete!\n");
  108974. exit(1);
  108975. }
  108976. if(!eosflag){
  108977. fprintf(stderr,"Never got a packet with EOS set!\n");
  108978. exit(1);
  108979. }
  108980. fprintf(stderr,"ok.\n");
  108981. }
  108982. int main(void){
  108983. ogg_stream_init(&os_en,0x04030201);
  108984. ogg_stream_init(&os_de,0x04030201);
  108985. ogg_sync_init(&oy);
  108986. /* Exercise each code path in the framing code. Also verify that
  108987. the checksums are working. */
  108988. {
  108989. /* 17 only */
  108990. const int packets[]={17, -1};
  108991. const int *headret[]={head1_0,NULL};
  108992. fprintf(stderr,"testing single page encoding... ");
  108993. test_pack(packets,headret,0,0,0);
  108994. }
  108995. {
  108996. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  108997. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  108998. const int *headret[]={head1_1,head2_1,NULL};
  108999. fprintf(stderr,"testing basic page encoding... ");
  109000. test_pack(packets,headret,0,0,0);
  109001. }
  109002. {
  109003. /* nil packets; beginning,middle,end */
  109004. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109005. const int *headret[]={head1_2,head2_2,NULL};
  109006. fprintf(stderr,"testing basic nil packets... ");
  109007. test_pack(packets,headret,0,0,0);
  109008. }
  109009. {
  109010. /* large initial packet */
  109011. const int packets[]={4345,259,255,-1};
  109012. const int *headret[]={head1_3,head2_3,NULL};
  109013. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109014. test_pack(packets,headret,0,0,0);
  109015. }
  109016. {
  109017. /* continuing packet test */
  109018. const int packets[]={0,4345,259,255,-1};
  109019. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109020. fprintf(stderr,"testing single packet page span... ");
  109021. test_pack(packets,headret,0,0,0);
  109022. }
  109023. /* page with the 255 segment limit */
  109024. {
  109025. const int packets[]={0,10,10,10,10,10,10,10,10,
  109026. 10,10,10,10,10,10,10,10,
  109027. 10,10,10,10,10,10,10,10,
  109028. 10,10,10,10,10,10,10,10,
  109029. 10,10,10,10,10,10,10,10,
  109030. 10,10,10,10,10,10,10,10,
  109031. 10,10,10,10,10,10,10,10,
  109032. 10,10,10,10,10,10,10,10,
  109033. 10,10,10,10,10,10,10,10,
  109034. 10,10,10,10,10,10,10,10,
  109035. 10,10,10,10,10,10,10,10,
  109036. 10,10,10,10,10,10,10,10,
  109037. 10,10,10,10,10,10,10,10,
  109038. 10,10,10,10,10,10,10,10,
  109039. 10,10,10,10,10,10,10,10,
  109040. 10,10,10,10,10,10,10,10,
  109041. 10,10,10,10,10,10,10,10,
  109042. 10,10,10,10,10,10,10,10,
  109043. 10,10,10,10,10,10,10,10,
  109044. 10,10,10,10,10,10,10,10,
  109045. 10,10,10,10,10,10,10,10,
  109046. 10,10,10,10,10,10,10,10,
  109047. 10,10,10,10,10,10,10,10,
  109048. 10,10,10,10,10,10,10,10,
  109049. 10,10,10,10,10,10,10,10,
  109050. 10,10,10,10,10,10,10,10,
  109051. 10,10,10,10,10,10,10,10,
  109052. 10,10,10,10,10,10,10,10,
  109053. 10,10,10,10,10,10,10,10,
  109054. 10,10,10,10,10,10,10,10,
  109055. 10,10,10,10,10,10,10,10,
  109056. 10,10,10,10,10,10,10,50,-1};
  109057. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109058. fprintf(stderr,"testing max packet segments... ");
  109059. test_pack(packets,headret,0,0,0);
  109060. }
  109061. {
  109062. /* packet that overspans over an entire page */
  109063. const int packets[]={0,100,9000,259,255,-1};
  109064. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109065. fprintf(stderr,"testing very large packets... ");
  109066. test_pack(packets,headret,0,0,0);
  109067. }
  109068. {
  109069. /* test for the libogg 1.1.1 resync in large continuation bug
  109070. found by Josh Coalson) */
  109071. const int packets[]={0,100,9000,259,255,-1};
  109072. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109073. fprintf(stderr,"testing continuation resync in very large packets... ");
  109074. test_pack(packets,headret,100,2,3);
  109075. }
  109076. {
  109077. /* term only page. why not? */
  109078. const int packets[]={0,100,4080,-1};
  109079. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109080. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109081. test_pack(packets,headret,0,0,0);
  109082. }
  109083. {
  109084. /* build a bunch of pages for testing */
  109085. unsigned char *data=_ogg_malloc(1024*1024);
  109086. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109087. int inptr=0,i,j;
  109088. ogg_page og[5];
  109089. ogg_stream_reset(&os_en);
  109090. for(i=0;pl[i]!=-1;i++){
  109091. ogg_packet op;
  109092. int len=pl[i];
  109093. op.packet=data+inptr;
  109094. op.bytes=len;
  109095. op.e_o_s=(pl[i+1]<0?1:0);
  109096. op.granulepos=(i+1)*1000;
  109097. for(j=0;j<len;j++)data[inptr++]=i+j;
  109098. ogg_stream_packetin(&os_en,&op);
  109099. }
  109100. _ogg_free(data);
  109101. /* retrieve finished pages */
  109102. for(i=0;i<5;i++){
  109103. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109104. fprintf(stderr,"Too few pages output building sync tests!\n");
  109105. exit(1);
  109106. }
  109107. copy_page(&og[i]);
  109108. }
  109109. /* Test lost pages on pagein/packetout: no rollback */
  109110. {
  109111. ogg_page temp;
  109112. ogg_packet test;
  109113. fprintf(stderr,"Testing loss of pages... ");
  109114. ogg_sync_reset(&oy);
  109115. ogg_stream_reset(&os_de);
  109116. for(i=0;i<5;i++){
  109117. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109118. og[i].header_len);
  109119. ogg_sync_wrote(&oy,og[i].header_len);
  109120. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109121. ogg_sync_wrote(&oy,og[i].body_len);
  109122. }
  109123. ogg_sync_pageout(&oy,&temp);
  109124. ogg_stream_pagein(&os_de,&temp);
  109125. ogg_sync_pageout(&oy,&temp);
  109126. ogg_stream_pagein(&os_de,&temp);
  109127. ogg_sync_pageout(&oy,&temp);
  109128. /* skip */
  109129. ogg_sync_pageout(&oy,&temp);
  109130. ogg_stream_pagein(&os_de,&temp);
  109131. /* do we get the expected results/packets? */
  109132. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109133. checkpacket(&test,0,0,0);
  109134. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109135. checkpacket(&test,100,1,-1);
  109136. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109137. checkpacket(&test,4079,2,3000);
  109138. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109139. fprintf(stderr,"Error: loss of page did not return error\n");
  109140. exit(1);
  109141. }
  109142. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109143. checkpacket(&test,76,5,-1);
  109144. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109145. checkpacket(&test,34,6,-1);
  109146. fprintf(stderr,"ok.\n");
  109147. }
  109148. /* Test lost pages on pagein/packetout: rollback with continuation */
  109149. {
  109150. ogg_page temp;
  109151. ogg_packet test;
  109152. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109153. ogg_sync_reset(&oy);
  109154. ogg_stream_reset(&os_de);
  109155. for(i=0;i<5;i++){
  109156. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109157. og[i].header_len);
  109158. ogg_sync_wrote(&oy,og[i].header_len);
  109159. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109160. ogg_sync_wrote(&oy,og[i].body_len);
  109161. }
  109162. ogg_sync_pageout(&oy,&temp);
  109163. ogg_stream_pagein(&os_de,&temp);
  109164. ogg_sync_pageout(&oy,&temp);
  109165. ogg_stream_pagein(&os_de,&temp);
  109166. ogg_sync_pageout(&oy,&temp);
  109167. ogg_stream_pagein(&os_de,&temp);
  109168. ogg_sync_pageout(&oy,&temp);
  109169. /* skip */
  109170. ogg_sync_pageout(&oy,&temp);
  109171. ogg_stream_pagein(&os_de,&temp);
  109172. /* do we get the expected results/packets? */
  109173. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109174. checkpacket(&test,0,0,0);
  109175. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109176. checkpacket(&test,100,1,-1);
  109177. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109178. checkpacket(&test,4079,2,3000);
  109179. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109180. checkpacket(&test,2956,3,4000);
  109181. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109182. fprintf(stderr,"Error: loss of page did not return error\n");
  109183. exit(1);
  109184. }
  109185. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109186. checkpacket(&test,300,13,14000);
  109187. fprintf(stderr,"ok.\n");
  109188. }
  109189. /* the rest only test sync */
  109190. {
  109191. ogg_page og_de;
  109192. /* Test fractional page inputs: incomplete capture */
  109193. fprintf(stderr,"Testing sync on partial inputs... ");
  109194. ogg_sync_reset(&oy);
  109195. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109196. 3);
  109197. ogg_sync_wrote(&oy,3);
  109198. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109199. /* Test fractional page inputs: incomplete fixed header */
  109200. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109201. 20);
  109202. ogg_sync_wrote(&oy,20);
  109203. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109204. /* Test fractional page inputs: incomplete header */
  109205. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109206. 5);
  109207. ogg_sync_wrote(&oy,5);
  109208. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109209. /* Test fractional page inputs: incomplete body */
  109210. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109211. og[1].header_len-28);
  109212. ogg_sync_wrote(&oy,og[1].header_len-28);
  109213. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109214. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109215. ogg_sync_wrote(&oy,1000);
  109216. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109217. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109218. og[1].body_len-1000);
  109219. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109220. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109221. fprintf(stderr,"ok.\n");
  109222. }
  109223. /* Test fractional page inputs: page + incomplete capture */
  109224. {
  109225. ogg_page og_de;
  109226. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109227. ogg_sync_reset(&oy);
  109228. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109229. og[1].header_len);
  109230. ogg_sync_wrote(&oy,og[1].header_len);
  109231. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109232. og[1].body_len);
  109233. ogg_sync_wrote(&oy,og[1].body_len);
  109234. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109235. 20);
  109236. ogg_sync_wrote(&oy,20);
  109237. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109238. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109239. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109240. og[1].header_len-20);
  109241. ogg_sync_wrote(&oy,og[1].header_len-20);
  109242. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109243. og[1].body_len);
  109244. ogg_sync_wrote(&oy,og[1].body_len);
  109245. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109246. fprintf(stderr,"ok.\n");
  109247. }
  109248. /* Test recapture: garbage + page */
  109249. {
  109250. ogg_page og_de;
  109251. fprintf(stderr,"Testing search for capture... ");
  109252. ogg_sync_reset(&oy);
  109253. /* 'garbage' */
  109254. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109255. og[1].body_len);
  109256. ogg_sync_wrote(&oy,og[1].body_len);
  109257. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109258. og[1].header_len);
  109259. ogg_sync_wrote(&oy,og[1].header_len);
  109260. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109261. og[1].body_len);
  109262. ogg_sync_wrote(&oy,og[1].body_len);
  109263. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109264. 20);
  109265. ogg_sync_wrote(&oy,20);
  109266. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109267. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109268. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109269. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  109270. og[2].header_len-20);
  109271. ogg_sync_wrote(&oy,og[2].header_len-20);
  109272. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109273. og[2].body_len);
  109274. ogg_sync_wrote(&oy,og[2].body_len);
  109275. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109276. fprintf(stderr,"ok.\n");
  109277. }
  109278. /* Test recapture: page + garbage + page */
  109279. {
  109280. ogg_page og_de;
  109281. fprintf(stderr,"Testing recapture... ");
  109282. ogg_sync_reset(&oy);
  109283. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109284. og[1].header_len);
  109285. ogg_sync_wrote(&oy,og[1].header_len);
  109286. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109287. og[1].body_len);
  109288. ogg_sync_wrote(&oy,og[1].body_len);
  109289. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109290. og[2].header_len);
  109291. ogg_sync_wrote(&oy,og[2].header_len);
  109292. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109293. og[2].header_len);
  109294. ogg_sync_wrote(&oy,og[2].header_len);
  109295. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109296. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109297. og[2].body_len-5);
  109298. ogg_sync_wrote(&oy,og[2].body_len-5);
  109299. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  109300. og[3].header_len);
  109301. ogg_sync_wrote(&oy,og[3].header_len);
  109302. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  109303. og[3].body_len);
  109304. ogg_sync_wrote(&oy,og[3].body_len);
  109305. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109306. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109307. fprintf(stderr,"ok.\n");
  109308. }
  109309. /* Free page data that was previously copied */
  109310. {
  109311. for(i=0;i<5;i++){
  109312. free_page(&og[i]);
  109313. }
  109314. }
  109315. }
  109316. return(0);
  109317. }
  109318. #endif
  109319. #endif
  109320. /*** End of inlined file: framing.c ***/
  109321. /*** Start of inlined file: analysis.c ***/
  109322. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109323. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109324. // tasks..
  109325. #if JUCE_MSVC
  109326. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109327. #endif
  109328. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109329. #if JUCE_USE_OGGVORBIS
  109330. #include <stdio.h>
  109331. #include <string.h>
  109332. #include <math.h>
  109333. /*** Start of inlined file: codec_internal.h ***/
  109334. #ifndef _V_CODECI_H_
  109335. #define _V_CODECI_H_
  109336. /*** Start of inlined file: envelope.h ***/
  109337. #ifndef _V_ENVELOPE_
  109338. #define _V_ENVELOPE_
  109339. /*** Start of inlined file: mdct.h ***/
  109340. #ifndef _OGG_mdct_H_
  109341. #define _OGG_mdct_H_
  109342. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109343. #ifdef MDCT_INTEGERIZED
  109344. #define DATA_TYPE int
  109345. #define REG_TYPE register int
  109346. #define TRIGBITS 14
  109347. #define cPI3_8 6270
  109348. #define cPI2_8 11585
  109349. #define cPI1_8 15137
  109350. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109351. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109352. #define HALVE(x) ((x)>>1)
  109353. #else
  109354. #define DATA_TYPE float
  109355. #define REG_TYPE float
  109356. #define cPI3_8 .38268343236508977175F
  109357. #define cPI2_8 .70710678118654752441F
  109358. #define cPI1_8 .92387953251128675613F
  109359. #define FLOAT_CONV(x) (x)
  109360. #define MULT_NORM(x) (x)
  109361. #define HALVE(x) ((x)*.5f)
  109362. #endif
  109363. typedef struct {
  109364. int n;
  109365. int log2n;
  109366. DATA_TYPE *trig;
  109367. int *bitrev;
  109368. DATA_TYPE scale;
  109369. } mdct_lookup;
  109370. extern void mdct_init(mdct_lookup *lookup,int n);
  109371. extern void mdct_clear(mdct_lookup *l);
  109372. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109373. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109374. #endif
  109375. /*** End of inlined file: mdct.h ***/
  109376. #define VE_PRE 16
  109377. #define VE_WIN 4
  109378. #define VE_POST 2
  109379. #define VE_AMP (VE_PRE+VE_POST-1)
  109380. #define VE_BANDS 7
  109381. #define VE_NEARDC 15
  109382. #define VE_MINSTRETCH 2 /* a bit less than short block */
  109383. #define VE_MAXSTRETCH 12 /* one-third full block */
  109384. typedef struct {
  109385. float ampbuf[VE_AMP];
  109386. int ampptr;
  109387. float nearDC[VE_NEARDC];
  109388. float nearDC_acc;
  109389. float nearDC_partialacc;
  109390. int nearptr;
  109391. } envelope_filter_state;
  109392. typedef struct {
  109393. int begin;
  109394. int end;
  109395. float *window;
  109396. float total;
  109397. } envelope_band;
  109398. typedef struct {
  109399. int ch;
  109400. int winlength;
  109401. int searchstep;
  109402. float minenergy;
  109403. mdct_lookup mdct;
  109404. float *mdct_win;
  109405. envelope_band band[VE_BANDS];
  109406. envelope_filter_state *filter;
  109407. int stretch;
  109408. int *mark;
  109409. long storage;
  109410. long current;
  109411. long curmark;
  109412. long cursor;
  109413. } envelope_lookup;
  109414. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  109415. extern void _ve_envelope_clear(envelope_lookup *e);
  109416. extern long _ve_envelope_search(vorbis_dsp_state *v);
  109417. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  109418. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  109419. #endif
  109420. /*** End of inlined file: envelope.h ***/
  109421. /*** Start of inlined file: codebook.h ***/
  109422. #ifndef _V_CODEBOOK_H_
  109423. #define _V_CODEBOOK_H_
  109424. /* This structure encapsulates huffman and VQ style encoding books; it
  109425. doesn't do anything specific to either.
  109426. valuelist/quantlist are nonNULL (and q_* significant) only if
  109427. there's entry->value mapping to be done.
  109428. If encode-side mapping must be done (and thus the entry needs to be
  109429. hunted), the auxiliary encode pointer will point to a decision
  109430. tree. This is true of both VQ and huffman, but is mostly useful
  109431. with VQ.
  109432. */
  109433. typedef struct static_codebook{
  109434. long dim; /* codebook dimensions (elements per vector) */
  109435. long entries; /* codebook entries */
  109436. long *lengthlist; /* codeword lengths in bits */
  109437. /* mapping ***************************************************************/
  109438. int maptype; /* 0=none
  109439. 1=implicitly populated values from map column
  109440. 2=listed arbitrary values */
  109441. /* The below does a linear, single monotonic sequence mapping. */
  109442. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  109443. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  109444. int q_quant; /* bits: 0 < quant <= 16 */
  109445. int q_sequencep; /* bitflag */
  109446. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  109447. map == 2: list of dim*entries quantized entry vals
  109448. */
  109449. /* encode helpers ********************************************************/
  109450. struct encode_aux_nearestmatch *nearest_tree;
  109451. struct encode_aux_threshmatch *thresh_tree;
  109452. struct encode_aux_pigeonhole *pigeon_tree;
  109453. int allocedp;
  109454. } static_codebook;
  109455. /* this structures an arbitrary trained book to quickly find the
  109456. nearest cell match */
  109457. typedef struct encode_aux_nearestmatch{
  109458. /* pre-calculated partitioning tree */
  109459. long *ptr0;
  109460. long *ptr1;
  109461. long *p; /* decision points (each is an entry) */
  109462. long *q; /* decision points (each is an entry) */
  109463. long aux; /* number of tree entries */
  109464. long alloc;
  109465. } encode_aux_nearestmatch;
  109466. /* assumes a maptype of 1; encode side only, so that's OK */
  109467. typedef struct encode_aux_threshmatch{
  109468. float *quantthresh;
  109469. long *quantmap;
  109470. int quantvals;
  109471. int threshvals;
  109472. } encode_aux_threshmatch;
  109473. typedef struct encode_aux_pigeonhole{
  109474. float min;
  109475. float del;
  109476. int mapentries;
  109477. int quantvals;
  109478. long *pigeonmap;
  109479. long fittotal;
  109480. long *fitlist;
  109481. long *fitmap;
  109482. long *fitlength;
  109483. } encode_aux_pigeonhole;
  109484. typedef struct codebook{
  109485. long dim; /* codebook dimensions (elements per vector) */
  109486. long entries; /* codebook entries */
  109487. long used_entries; /* populated codebook entries */
  109488. const static_codebook *c;
  109489. /* for encode, the below are entry-ordered, fully populated */
  109490. /* for decode, the below are ordered by bitreversed codeword and only
  109491. used entries are populated */
  109492. float *valuelist; /* list of dim*entries actual entry values */
  109493. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  109494. int *dec_index; /* only used if sparseness collapsed */
  109495. char *dec_codelengths;
  109496. ogg_uint32_t *dec_firsttable;
  109497. int dec_firsttablen;
  109498. int dec_maxlength;
  109499. } codebook;
  109500. extern void vorbis_staticbook_clear(static_codebook *b);
  109501. extern void vorbis_staticbook_destroy(static_codebook *b);
  109502. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  109503. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  109504. extern void vorbis_book_clear(codebook *b);
  109505. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  109506. extern float *_book_logdist(const static_codebook *b,float *vals);
  109507. extern float _float32_unpack(long val);
  109508. extern long _float32_pack(float val);
  109509. extern int _best(codebook *book, float *a, int step);
  109510. extern int _ilog(unsigned int v);
  109511. extern long _book_maptype1_quantvals(const static_codebook *b);
  109512. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  109513. extern long vorbis_book_codeword(codebook *book,int entry);
  109514. extern long vorbis_book_codelen(codebook *book,int entry);
  109515. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  109516. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  109517. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  109518. extern int vorbis_book_errorv(codebook *book, float *a);
  109519. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  109520. oggpack_buffer *b);
  109521. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  109522. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  109523. oggpack_buffer *b,int n);
  109524. extern long vorbis_book_decodev_set(codebook *book, float *a,
  109525. oggpack_buffer *b,int n);
  109526. extern long vorbis_book_decodev_add(codebook *book, float *a,
  109527. oggpack_buffer *b,int n);
  109528. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  109529. long off,int ch,
  109530. oggpack_buffer *b,int n);
  109531. #endif
  109532. /*** End of inlined file: codebook.h ***/
  109533. #define BLOCKTYPE_IMPULSE 0
  109534. #define BLOCKTYPE_PADDING 1
  109535. #define BLOCKTYPE_TRANSITION 0
  109536. #define BLOCKTYPE_LONG 1
  109537. #define PACKETBLOBS 15
  109538. typedef struct vorbis_block_internal{
  109539. float **pcmdelay; /* this is a pointer into local storage */
  109540. float ampmax;
  109541. int blocktype;
  109542. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  109543. blob [PACKETBLOBS/2] points to
  109544. the oggpack_buffer in the
  109545. main vorbis_block */
  109546. } vorbis_block_internal;
  109547. typedef void vorbis_look_floor;
  109548. typedef void vorbis_look_residue;
  109549. typedef void vorbis_look_transform;
  109550. /* mode ************************************************************/
  109551. typedef struct {
  109552. int blockflag;
  109553. int windowtype;
  109554. int transformtype;
  109555. int mapping;
  109556. } vorbis_info_mode;
  109557. typedef void vorbis_info_floor;
  109558. typedef void vorbis_info_residue;
  109559. typedef void vorbis_info_mapping;
  109560. /*** Start of inlined file: psy.h ***/
  109561. #ifndef _V_PSY_H_
  109562. #define _V_PSY_H_
  109563. /*** Start of inlined file: smallft.h ***/
  109564. #ifndef _V_SMFT_H_
  109565. #define _V_SMFT_H_
  109566. typedef struct {
  109567. int n;
  109568. float *trigcache;
  109569. int *splitcache;
  109570. } drft_lookup;
  109571. extern void drft_forward(drft_lookup *l,float *data);
  109572. extern void drft_backward(drft_lookup *l,float *data);
  109573. extern void drft_init(drft_lookup *l,int n);
  109574. extern void drft_clear(drft_lookup *l);
  109575. #endif
  109576. /*** End of inlined file: smallft.h ***/
  109577. /*** Start of inlined file: backends.h ***/
  109578. /* this is exposed up here because we need it for static modes.
  109579. Lookups for each backend aren't exposed because there's no reason
  109580. to do so */
  109581. #ifndef _vorbis_backend_h_
  109582. #define _vorbis_backend_h_
  109583. /* this would all be simpler/shorter with templates, but.... */
  109584. /* Floor backend generic *****************************************/
  109585. typedef struct{
  109586. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  109587. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  109588. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  109589. void (*free_info) (vorbis_info_floor *);
  109590. void (*free_look) (vorbis_look_floor *);
  109591. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  109592. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  109593. void *buffer,float *);
  109594. } vorbis_func_floor;
  109595. typedef struct{
  109596. int order;
  109597. long rate;
  109598. long barkmap;
  109599. int ampbits;
  109600. int ampdB;
  109601. int numbooks; /* <= 16 */
  109602. int books[16];
  109603. float lessthan; /* encode-only config setting hacks for libvorbis */
  109604. float greaterthan; /* encode-only config setting hacks for libvorbis */
  109605. } vorbis_info_floor0;
  109606. #define VIF_POSIT 63
  109607. #define VIF_CLASS 16
  109608. #define VIF_PARTS 31
  109609. typedef struct{
  109610. int partitions; /* 0 to 31 */
  109611. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  109612. int class_dim[VIF_CLASS]; /* 1 to 8 */
  109613. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  109614. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  109615. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  109616. int mult; /* 1 2 3 or 4 */
  109617. int postlist[VIF_POSIT+2]; /* first two implicit */
  109618. /* encode side analysis parameters */
  109619. float maxover;
  109620. float maxunder;
  109621. float maxerr;
  109622. float twofitweight;
  109623. float twofitatten;
  109624. int n;
  109625. } vorbis_info_floor1;
  109626. /* Residue backend generic *****************************************/
  109627. typedef struct{
  109628. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  109629. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  109630. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  109631. vorbis_info_residue *);
  109632. void (*free_info) (vorbis_info_residue *);
  109633. void (*free_look) (vorbis_look_residue *);
  109634. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  109635. float **,int *,int);
  109636. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  109637. vorbis_look_residue *,
  109638. float **,float **,int *,int,long **);
  109639. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  109640. float **,int *,int);
  109641. } vorbis_func_residue;
  109642. typedef struct vorbis_info_residue0{
  109643. /* block-partitioned VQ coded straight residue */
  109644. long begin;
  109645. long end;
  109646. /* first stage (lossless partitioning) */
  109647. int grouping; /* group n vectors per partition */
  109648. int partitions; /* possible codebooks for a partition */
  109649. int groupbook; /* huffbook for partitioning */
  109650. int secondstages[64]; /* expanded out to pointers in lookup */
  109651. int booklist[256]; /* list of second stage books */
  109652. float classmetric1[64];
  109653. float classmetric2[64];
  109654. } vorbis_info_residue0;
  109655. /* Mapping backend generic *****************************************/
  109656. typedef struct{
  109657. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  109658. oggpack_buffer *);
  109659. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  109660. void (*free_info) (vorbis_info_mapping *);
  109661. int (*forward) (struct vorbis_block *vb);
  109662. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  109663. } vorbis_func_mapping;
  109664. typedef struct vorbis_info_mapping0{
  109665. int submaps; /* <= 16 */
  109666. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  109667. int floorsubmap[16]; /* [mux] submap to floors */
  109668. int residuesubmap[16]; /* [mux] submap to residue */
  109669. int coupling_steps;
  109670. int coupling_mag[256];
  109671. int coupling_ang[256];
  109672. } vorbis_info_mapping0;
  109673. #endif
  109674. /*** End of inlined file: backends.h ***/
  109675. #ifndef EHMER_MAX
  109676. #define EHMER_MAX 56
  109677. #endif
  109678. /* psychoacoustic setup ********************************************/
  109679. #define P_BANDS 17 /* 62Hz to 16kHz */
  109680. #define P_LEVELS 8 /* 30dB to 100dB */
  109681. #define P_LEVEL_0 30. /* 30 dB */
  109682. #define P_NOISECURVES 3
  109683. #define NOISE_COMPAND_LEVELS 40
  109684. typedef struct vorbis_info_psy{
  109685. int blockflag;
  109686. float ath_adjatt;
  109687. float ath_maxatt;
  109688. float tone_masteratt[P_NOISECURVES];
  109689. float tone_centerboost;
  109690. float tone_decay;
  109691. float tone_abs_limit;
  109692. float toneatt[P_BANDS];
  109693. int noisemaskp;
  109694. float noisemaxsupp;
  109695. float noisewindowlo;
  109696. float noisewindowhi;
  109697. int noisewindowlomin;
  109698. int noisewindowhimin;
  109699. int noisewindowfixed;
  109700. float noiseoff[P_NOISECURVES][P_BANDS];
  109701. float noisecompand[NOISE_COMPAND_LEVELS];
  109702. float max_curve_dB;
  109703. int normal_channel_p;
  109704. int normal_point_p;
  109705. int normal_start;
  109706. int normal_partition;
  109707. double normal_thresh;
  109708. } vorbis_info_psy;
  109709. typedef struct{
  109710. int eighth_octave_lines;
  109711. /* for block long/short tuning; encode only */
  109712. float preecho_thresh[VE_BANDS];
  109713. float postecho_thresh[VE_BANDS];
  109714. float stretch_penalty;
  109715. float preecho_minenergy;
  109716. float ampmax_att_per_sec;
  109717. /* channel coupling config */
  109718. int coupling_pkHz[PACKETBLOBS];
  109719. int coupling_pointlimit[2][PACKETBLOBS];
  109720. int coupling_prepointamp[PACKETBLOBS];
  109721. int coupling_postpointamp[PACKETBLOBS];
  109722. int sliding_lowpass[2][PACKETBLOBS];
  109723. } vorbis_info_psy_global;
  109724. typedef struct {
  109725. float ampmax;
  109726. int channels;
  109727. vorbis_info_psy_global *gi;
  109728. int coupling_pointlimit[2][P_NOISECURVES];
  109729. } vorbis_look_psy_global;
  109730. typedef struct {
  109731. int n;
  109732. struct vorbis_info_psy *vi;
  109733. float ***tonecurves;
  109734. float **noiseoffset;
  109735. float *ath;
  109736. long *octave; /* in n.ocshift format */
  109737. long *bark;
  109738. long firstoc;
  109739. long shiftoc;
  109740. int eighth_octave_lines; /* power of two, please */
  109741. int total_octave_lines;
  109742. long rate; /* cache it */
  109743. float m_val; /* Masking compensation value */
  109744. } vorbis_look_psy;
  109745. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  109746. vorbis_info_psy_global *gi,int n,long rate);
  109747. extern void _vp_psy_clear(vorbis_look_psy *p);
  109748. extern void *_vi_psy_dup(void *source);
  109749. extern void _vi_psy_free(vorbis_info_psy *i);
  109750. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  109751. extern void _vp_remove_floor(vorbis_look_psy *p,
  109752. float *mdct,
  109753. int *icodedflr,
  109754. float *residue,
  109755. int sliding_lowpass);
  109756. extern void _vp_noisemask(vorbis_look_psy *p,
  109757. float *logmdct,
  109758. float *logmask);
  109759. extern void _vp_tonemask(vorbis_look_psy *p,
  109760. float *logfft,
  109761. float *logmask,
  109762. float global_specmax,
  109763. float local_specmax);
  109764. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  109765. float *noise,
  109766. float *tone,
  109767. int offset_select,
  109768. float *logmask,
  109769. float *mdct,
  109770. float *logmdct);
  109771. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  109772. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  109773. vorbis_info_psy_global *g,
  109774. vorbis_look_psy *p,
  109775. vorbis_info_mapping0 *vi,
  109776. float **mdct);
  109777. extern void _vp_couple(int blobno,
  109778. vorbis_info_psy_global *g,
  109779. vorbis_look_psy *p,
  109780. vorbis_info_mapping0 *vi,
  109781. float **res,
  109782. float **mag_memo,
  109783. int **mag_sort,
  109784. int **ifloor,
  109785. int *nonzero,
  109786. int sliding_lowpass);
  109787. extern void _vp_noise_normalize(vorbis_look_psy *p,
  109788. float *in,float *out,int *sortedindex);
  109789. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  109790. float *magnitudes,int *sortedindex);
  109791. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  109792. vorbis_look_psy *p,
  109793. vorbis_info_mapping0 *vi,
  109794. float **mags);
  109795. extern void hf_reduction(vorbis_info_psy_global *g,
  109796. vorbis_look_psy *p,
  109797. vorbis_info_mapping0 *vi,
  109798. float **mdct);
  109799. #endif
  109800. /*** End of inlined file: psy.h ***/
  109801. /*** Start of inlined file: bitrate.h ***/
  109802. #ifndef _V_BITRATE_H_
  109803. #define _V_BITRATE_H_
  109804. /*** Start of inlined file: os.h ***/
  109805. #ifndef _OS_H
  109806. #define _OS_H
  109807. /********************************************************************
  109808. * *
  109809. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  109810. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  109811. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  109812. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  109813. * *
  109814. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  109815. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  109816. * *
  109817. ********************************************************************
  109818. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  109819. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  109820. ********************************************************************/
  109821. #ifdef HAVE_CONFIG_H
  109822. #include "config.h"
  109823. #endif
  109824. #include <math.h>
  109825. /*** Start of inlined file: misc.h ***/
  109826. #ifndef _V_RANDOM_H_
  109827. #define _V_RANDOM_H_
  109828. extern int analysis_noisy;
  109829. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  109830. extern void _vorbis_block_ripcord(vorbis_block *vb);
  109831. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  109832. ogg_int64_t off);
  109833. #ifdef DEBUG_MALLOC
  109834. #define _VDBG_GRAPHFILE "malloc.m"
  109835. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  109836. extern void _VDBG_free(void *ptr,char *file,long line);
  109837. #ifndef MISC_C
  109838. #undef _ogg_malloc
  109839. #undef _ogg_calloc
  109840. #undef _ogg_realloc
  109841. #undef _ogg_free
  109842. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  109843. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  109844. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  109845. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  109846. #endif
  109847. #endif
  109848. #endif
  109849. /*** End of inlined file: misc.h ***/
  109850. #ifndef _V_IFDEFJAIL_H_
  109851. # define _V_IFDEFJAIL_H_
  109852. # ifdef __GNUC__
  109853. # define STIN static __inline__
  109854. # elif _WIN32
  109855. # define STIN static __inline
  109856. # else
  109857. # define STIN static
  109858. # endif
  109859. #ifdef DJGPP
  109860. # define rint(x) (floor((x)+0.5f))
  109861. #endif
  109862. #ifndef M_PI
  109863. # define M_PI (3.1415926536f)
  109864. #endif
  109865. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  109866. # include <malloc.h>
  109867. # define rint(x) (floor((x)+0.5f))
  109868. # define NO_FLOAT_MATH_LIB
  109869. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  109870. #endif
  109871. #if defined(__SYMBIAN32__) && defined(__WINS__)
  109872. void *_alloca(size_t size);
  109873. # define alloca _alloca
  109874. #endif
  109875. #ifndef FAST_HYPOT
  109876. # define FAST_HYPOT hypot
  109877. #endif
  109878. #endif
  109879. #ifdef HAVE_ALLOCA_H
  109880. # include <alloca.h>
  109881. #endif
  109882. #ifdef USE_MEMORY_H
  109883. # include <memory.h>
  109884. #endif
  109885. #ifndef min
  109886. # define min(x,y) ((x)>(y)?(y):(x))
  109887. #endif
  109888. #ifndef max
  109889. # define max(x,y) ((x)<(y)?(y):(x))
  109890. #endif
  109891. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  109892. # define VORBIS_FPU_CONTROL
  109893. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  109894. Because of encapsulation constraints (GCC can't see inside the asm
  109895. block and so we end up doing stupid things like a store/load that
  109896. is collectively a noop), we do it this way */
  109897. /* we must set up the fpu before this works!! */
  109898. typedef ogg_int16_t vorbis_fpu_control;
  109899. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  109900. ogg_int16_t ret;
  109901. ogg_int16_t temp;
  109902. __asm__ __volatile__("fnstcw %0\n\t"
  109903. "movw %0,%%dx\n\t"
  109904. "orw $62463,%%dx\n\t"
  109905. "movw %%dx,%1\n\t"
  109906. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  109907. *fpu=ret;
  109908. }
  109909. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  109910. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  109911. }
  109912. /* assumes the FPU is in round mode! */
  109913. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  109914. we get extra fst/fld to
  109915. truncate precision */
  109916. int i;
  109917. __asm__("fistl %0": "=m"(i) : "t"(f));
  109918. return(i);
  109919. }
  109920. #endif
  109921. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  109922. # define VORBIS_FPU_CONTROL
  109923. typedef ogg_int16_t vorbis_fpu_control;
  109924. static __inline int vorbis_ftoi(double f){
  109925. int i;
  109926. __asm{
  109927. fld f
  109928. fistp i
  109929. }
  109930. return i;
  109931. }
  109932. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  109933. }
  109934. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  109935. }
  109936. #endif
  109937. #ifndef VORBIS_FPU_CONTROL
  109938. typedef int vorbis_fpu_control;
  109939. static int vorbis_ftoi(double f){
  109940. return (int)(f+.5);
  109941. }
  109942. /* We don't have special code for this compiler/arch, so do it the slow way */
  109943. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  109944. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  109945. #endif
  109946. #endif /* _OS_H */
  109947. /*** End of inlined file: os.h ***/
  109948. /* encode side bitrate tracking */
  109949. typedef struct bitrate_manager_state {
  109950. int managed;
  109951. long avg_reservoir;
  109952. long minmax_reservoir;
  109953. long avg_bitsper;
  109954. long min_bitsper;
  109955. long max_bitsper;
  109956. long short_per_long;
  109957. double avgfloat;
  109958. vorbis_block *vb;
  109959. int choice;
  109960. } bitrate_manager_state;
  109961. typedef struct bitrate_manager_info{
  109962. long avg_rate;
  109963. long min_rate;
  109964. long max_rate;
  109965. long reservoir_bits;
  109966. double reservoir_bias;
  109967. double slew_damp;
  109968. } bitrate_manager_info;
  109969. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  109970. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  109971. extern int vorbis_bitrate_managed(vorbis_block *vb);
  109972. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  109973. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  109974. #endif
  109975. /*** End of inlined file: bitrate.h ***/
  109976. static int ilog(unsigned int v){
  109977. int ret=0;
  109978. while(v){
  109979. ret++;
  109980. v>>=1;
  109981. }
  109982. return(ret);
  109983. }
  109984. static int ilog2(unsigned int v){
  109985. int ret=0;
  109986. if(v)--v;
  109987. while(v){
  109988. ret++;
  109989. v>>=1;
  109990. }
  109991. return(ret);
  109992. }
  109993. typedef struct private_state {
  109994. /* local lookup storage */
  109995. envelope_lookup *ve; /* envelope lookup */
  109996. int window[2];
  109997. vorbis_look_transform **transform[2]; /* block, type */
  109998. drft_lookup fft_look[2];
  109999. int modebits;
  110000. vorbis_look_floor **flr;
  110001. vorbis_look_residue **residue;
  110002. vorbis_look_psy *psy;
  110003. vorbis_look_psy_global *psy_g_look;
  110004. /* local storage, only used on the encoding side. This way the
  110005. application does not need to worry about freeing some packets'
  110006. memory and not others'; packet storage is always tracked.
  110007. Cleared next call to a _dsp_ function */
  110008. unsigned char *header;
  110009. unsigned char *header1;
  110010. unsigned char *header2;
  110011. bitrate_manager_state bms;
  110012. ogg_int64_t sample_count;
  110013. } private_state;
  110014. /* codec_setup_info contains all the setup information specific to the
  110015. specific compression/decompression mode in progress (eg,
  110016. psychoacoustic settings, channel setup, options, codebook
  110017. etc).
  110018. *********************************************************************/
  110019. /*** Start of inlined file: highlevel.h ***/
  110020. typedef struct highlevel_byblocktype {
  110021. double tone_mask_setting;
  110022. double tone_peaklimit_setting;
  110023. double noise_bias_setting;
  110024. double noise_compand_setting;
  110025. } highlevel_byblocktype;
  110026. typedef struct highlevel_encode_setup {
  110027. void *setup;
  110028. int set_in_stone;
  110029. double base_setting;
  110030. double long_setting;
  110031. double short_setting;
  110032. double impulse_noisetune;
  110033. int managed;
  110034. long bitrate_min;
  110035. long bitrate_av;
  110036. double bitrate_av_damp;
  110037. long bitrate_max;
  110038. long bitrate_reservoir;
  110039. double bitrate_reservoir_bias;
  110040. int impulse_block_p;
  110041. int noise_normalize_p;
  110042. double stereo_point_setting;
  110043. double lowpass_kHz;
  110044. double ath_floating_dB;
  110045. double ath_absolute_dB;
  110046. double amplitude_track_dBpersec;
  110047. double trigger_setting;
  110048. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110049. } highlevel_encode_setup;
  110050. /*** End of inlined file: highlevel.h ***/
  110051. typedef struct codec_setup_info {
  110052. /* Vorbis supports only short and long blocks, but allows the
  110053. encoder to choose the sizes */
  110054. long blocksizes[2];
  110055. /* modes are the primary means of supporting on-the-fly different
  110056. blocksizes, different channel mappings (LR or M/A),
  110057. different residue backends, etc. Each mode consists of a
  110058. blocksize flag and a mapping (along with the mapping setup */
  110059. int modes;
  110060. int maps;
  110061. int floors;
  110062. int residues;
  110063. int books;
  110064. int psys; /* encode only */
  110065. vorbis_info_mode *mode_param[64];
  110066. int map_type[64];
  110067. vorbis_info_mapping *map_param[64];
  110068. int floor_type[64];
  110069. vorbis_info_floor *floor_param[64];
  110070. int residue_type[64];
  110071. vorbis_info_residue *residue_param[64];
  110072. static_codebook *book_param[256];
  110073. codebook *fullbooks;
  110074. vorbis_info_psy *psy_param[4]; /* encode only */
  110075. vorbis_info_psy_global psy_g_param;
  110076. bitrate_manager_info bi;
  110077. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110078. highly redundant structure, but
  110079. improves clarity of program flow. */
  110080. int halfrate_flag; /* painless downsample for decode */
  110081. } codec_setup_info;
  110082. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110083. extern void _vp_global_free(vorbis_look_psy_global *look);
  110084. #endif
  110085. /*** End of inlined file: codec_internal.h ***/
  110086. /*** Start of inlined file: registry.h ***/
  110087. #ifndef _V_REG_H_
  110088. #define _V_REG_H_
  110089. #define VI_TRANSFORMB 1
  110090. #define VI_WINDOWB 1
  110091. #define VI_TIMEB 1
  110092. #define VI_FLOORB 2
  110093. #define VI_RESB 3
  110094. #define VI_MAPB 1
  110095. extern vorbis_func_floor *_floor_P[];
  110096. extern vorbis_func_residue *_residue_P[];
  110097. extern vorbis_func_mapping *_mapping_P[];
  110098. #endif
  110099. /*** End of inlined file: registry.h ***/
  110100. /*** Start of inlined file: scales.h ***/
  110101. #ifndef _V_SCALES_H_
  110102. #define _V_SCALES_H_
  110103. #include <math.h>
  110104. /* 20log10(x) */
  110105. #define VORBIS_IEEE_FLOAT32 1
  110106. #ifdef VORBIS_IEEE_FLOAT32
  110107. static float unitnorm(float x){
  110108. union {
  110109. ogg_uint32_t i;
  110110. float f;
  110111. } ix;
  110112. ix.f = x;
  110113. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110114. return ix.f;
  110115. }
  110116. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110117. static float todB(const float *x){
  110118. union {
  110119. ogg_uint32_t i;
  110120. float f;
  110121. } ix;
  110122. ix.f = *x;
  110123. ix.i = ix.i&0x7fffffff;
  110124. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110125. }
  110126. #define todB_nn(x) todB(x)
  110127. #else
  110128. static float unitnorm(float x){
  110129. if(x<0)return(-1.f);
  110130. return(1.f);
  110131. }
  110132. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110133. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110134. #endif
  110135. #define fromdB(x) (exp((x)*.11512925f))
  110136. /* The bark scale equations are approximations, since the original
  110137. table was somewhat hand rolled. The below are chosen to have the
  110138. best possible fit to the rolled tables, thus their somewhat odd
  110139. appearance (these are more accurate and over a longer range than
  110140. the oft-quoted bark equations found in the texts I have). The
  110141. approximations are valid from 0 - 30kHz (nyquist) or so.
  110142. all f in Hz, z in Bark */
  110143. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110144. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110145. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110146. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110147. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110148. 0.0 */
  110149. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110150. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110151. #endif
  110152. /*** End of inlined file: scales.h ***/
  110153. int analysis_noisy=1;
  110154. /* decides between modes, dispatches to the appropriate mapping. */
  110155. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110156. int ret,i;
  110157. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110158. vb->glue_bits=0;
  110159. vb->time_bits=0;
  110160. vb->floor_bits=0;
  110161. vb->res_bits=0;
  110162. /* first things first. Make sure encode is ready */
  110163. for(i=0;i<PACKETBLOBS;i++)
  110164. oggpack_reset(vbi->packetblob[i]);
  110165. /* we only have one mapping type (0), and we let the mapping code
  110166. itself figure out what soft mode to use. This allows easier
  110167. bitrate management */
  110168. if((ret=_mapping_P[0]->forward(vb)))
  110169. return(ret);
  110170. if(op){
  110171. if(vorbis_bitrate_managed(vb))
  110172. /* The app is using a bitmanaged mode... but not using the
  110173. bitrate management interface. */
  110174. return(OV_EINVAL);
  110175. op->packet=oggpack_get_buffer(&vb->opb);
  110176. op->bytes=oggpack_bytes(&vb->opb);
  110177. op->b_o_s=0;
  110178. op->e_o_s=vb->eofflag;
  110179. op->granulepos=vb->granulepos;
  110180. op->packetno=vb->sequence; /* for sake of completeness */
  110181. }
  110182. return(0);
  110183. }
  110184. /* there was no great place to put this.... */
  110185. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110186. int j;
  110187. FILE *of;
  110188. char buffer[80];
  110189. /* if(i==5870){*/
  110190. sprintf(buffer,"%s_%d.m",base,i);
  110191. of=fopen(buffer,"w");
  110192. if(!of)perror("failed to open data dump file");
  110193. for(j=0;j<n;j++){
  110194. if(bark){
  110195. float b=toBARK((4000.f*j/n)+.25);
  110196. fprintf(of,"%f ",b);
  110197. }else
  110198. if(off!=0)
  110199. fprintf(of,"%f ",(double)(j+off)/8000.);
  110200. else
  110201. fprintf(of,"%f ",(double)j);
  110202. if(dB){
  110203. float val;
  110204. if(v[j]==0.)
  110205. val=-140.;
  110206. else
  110207. val=todB(v+j);
  110208. fprintf(of,"%f\n",val);
  110209. }else{
  110210. fprintf(of,"%f\n",v[j]);
  110211. }
  110212. }
  110213. fclose(of);
  110214. /* } */
  110215. }
  110216. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110217. ogg_int64_t off){
  110218. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110219. }
  110220. #endif
  110221. /*** End of inlined file: analysis.c ***/
  110222. /*** Start of inlined file: bitrate.c ***/
  110223. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110224. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110225. // tasks..
  110226. #if JUCE_MSVC
  110227. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110228. #endif
  110229. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110230. #if JUCE_USE_OGGVORBIS
  110231. #include <stdlib.h>
  110232. #include <string.h>
  110233. #include <math.h>
  110234. /* compute bitrate tracking setup */
  110235. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110236. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110237. bitrate_manager_info *bi=&ci->bi;
  110238. memset(bm,0,sizeof(*bm));
  110239. if(bi && (bi->reservoir_bits>0)){
  110240. long ratesamples=vi->rate;
  110241. int halfsamples=ci->blocksizes[0]>>1;
  110242. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110243. bm->managed=1;
  110244. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110245. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110246. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110247. bm->avgfloat=PACKETBLOBS/2;
  110248. /* not a necessary fix, but one that leads to a more balanced
  110249. typical initialization */
  110250. {
  110251. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110252. bm->minmax_reservoir=desired_fill;
  110253. bm->avg_reservoir=desired_fill;
  110254. }
  110255. }
  110256. }
  110257. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110258. memset(bm,0,sizeof(*bm));
  110259. return;
  110260. }
  110261. int vorbis_bitrate_managed(vorbis_block *vb){
  110262. vorbis_dsp_state *vd=vb->vd;
  110263. private_state *b=(private_state*)vd->backend_state;
  110264. bitrate_manager_state *bm=&b->bms;
  110265. if(bm && bm->managed)return(1);
  110266. return(0);
  110267. }
  110268. /* finish taking in the block we just processed */
  110269. int vorbis_bitrate_addblock(vorbis_block *vb){
  110270. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110271. vorbis_dsp_state *vd=vb->vd;
  110272. private_state *b=(private_state*)vd->backend_state;
  110273. bitrate_manager_state *bm=&b->bms;
  110274. vorbis_info *vi=vd->vi;
  110275. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110276. bitrate_manager_info *bi=&ci->bi;
  110277. int choice=rint(bm->avgfloat);
  110278. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110279. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  110280. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  110281. int samples=ci->blocksizes[vb->W]>>1;
  110282. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110283. if(!bm->managed){
  110284. /* not a bitrate managed stream, but for API simplicity, we'll
  110285. buffer the packet to keep the code path clean */
  110286. if(bm->vb)return(-1); /* one has been submitted without
  110287. being claimed */
  110288. bm->vb=vb;
  110289. return(0);
  110290. }
  110291. bm->vb=vb;
  110292. /* look ahead for avg floater */
  110293. if(bm->avg_bitsper>0){
  110294. double slew=0.;
  110295. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110296. double slewlimit= 15./bi->slew_damp;
  110297. /* choosing a new floater:
  110298. if we're over target, we slew down
  110299. if we're under target, we slew up
  110300. choose slew as follows: look through packetblobs of this frame
  110301. and set slew as the first in the appropriate direction that
  110302. gives us the slew we want. This may mean no slew if delta is
  110303. already favorable.
  110304. Then limit slew to slew max */
  110305. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110306. while(choice>0 && this_bits>avg_target_bits &&
  110307. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110308. choice--;
  110309. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110310. }
  110311. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110312. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110313. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110314. choice++;
  110315. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110316. }
  110317. }
  110318. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110319. if(slew<-slewlimit)slew=-slewlimit;
  110320. if(slew>slewlimit)slew=slewlimit;
  110321. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110322. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110323. }
  110324. /* enforce min(if used) on the current floater (if used) */
  110325. if(bm->min_bitsper>0){
  110326. /* do we need to force the bitrate up? */
  110327. if(this_bits<min_target_bits){
  110328. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110329. choice++;
  110330. if(choice>=PACKETBLOBS)break;
  110331. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110332. }
  110333. }
  110334. }
  110335. /* enforce max (if used) on the current floater (if used) */
  110336. if(bm->max_bitsper>0){
  110337. /* do we need to force the bitrate down? */
  110338. if(this_bits>max_target_bits){
  110339. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110340. choice--;
  110341. if(choice<0)break;
  110342. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110343. }
  110344. }
  110345. }
  110346. /* Choice of packetblobs now made based on floater, and min/max
  110347. requirements. Now boundary check extreme choices */
  110348. if(choice<0){
  110349. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110350. frame will need to be truncated */
  110351. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110352. bm->choice=choice=0;
  110353. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110354. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110355. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110356. }
  110357. }else{
  110358. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110359. if(choice>=PACKETBLOBS)
  110360. choice=PACKETBLOBS-1;
  110361. bm->choice=choice;
  110362. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110363. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110364. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110365. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110366. }
  110367. /* now we have the final packet and the final packet size. Update statistics */
  110368. /* min and max reservoir */
  110369. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110370. if(max_target_bits>0 && this_bits>max_target_bits){
  110371. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110372. }else if(min_target_bits>0 && this_bits<min_target_bits){
  110373. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110374. }else{
  110375. /* inbetween; we want to take reservoir toward but not past desired_fill */
  110376. if(bm->minmax_reservoir>desired_fill){
  110377. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  110378. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110379. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  110380. }else{
  110381. bm->minmax_reservoir=desired_fill;
  110382. }
  110383. }else{
  110384. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  110385. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110386. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  110387. }else{
  110388. bm->minmax_reservoir=desired_fill;
  110389. }
  110390. }
  110391. }
  110392. }
  110393. /* avg reservoir */
  110394. if(bm->avg_bitsper>0){
  110395. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110396. bm->avg_reservoir+=this_bits-avg_target_bits;
  110397. }
  110398. return(0);
  110399. }
  110400. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  110401. private_state *b=(private_state*)vd->backend_state;
  110402. bitrate_manager_state *bm=&b->bms;
  110403. vorbis_block *vb=bm->vb;
  110404. int choice=PACKETBLOBS/2;
  110405. if(!vb)return 0;
  110406. if(op){
  110407. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110408. if(vorbis_bitrate_managed(vb))
  110409. choice=bm->choice;
  110410. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  110411. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  110412. op->b_o_s=0;
  110413. op->e_o_s=vb->eofflag;
  110414. op->granulepos=vb->granulepos;
  110415. op->packetno=vb->sequence; /* for sake of completeness */
  110416. }
  110417. bm->vb=0;
  110418. return(1);
  110419. }
  110420. #endif
  110421. /*** End of inlined file: bitrate.c ***/
  110422. /*** Start of inlined file: block.c ***/
  110423. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110424. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110425. // tasks..
  110426. #if JUCE_MSVC
  110427. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110428. #endif
  110429. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110430. #if JUCE_USE_OGGVORBIS
  110431. #include <stdio.h>
  110432. #include <stdlib.h>
  110433. #include <string.h>
  110434. /*** Start of inlined file: window.h ***/
  110435. #ifndef _V_WINDOW_
  110436. #define _V_WINDOW_
  110437. extern float *_vorbis_window_get(int n);
  110438. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  110439. int lW,int W,int nW);
  110440. #endif
  110441. /*** End of inlined file: window.h ***/
  110442. /*** Start of inlined file: lpc.h ***/
  110443. #ifndef _V_LPC_H_
  110444. #define _V_LPC_H_
  110445. /* simple linear scale LPC code */
  110446. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  110447. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  110448. float *data,long n);
  110449. #endif
  110450. /*** End of inlined file: lpc.h ***/
  110451. /* pcm accumulator examples (not exhaustive):
  110452. <-------------- lW ---------------->
  110453. <--------------- W ---------------->
  110454. : .....|..... _______________ |
  110455. : .''' | '''_--- | |\ |
  110456. :.....''' |_____--- '''......| | \_______|
  110457. :.................|__________________|_______|__|______|
  110458. |<------ Sl ------>| > Sr < |endW
  110459. |beginSl |endSl | |endSr
  110460. |beginW |endlW |beginSr
  110461. |< lW >|
  110462. <--------------- W ---------------->
  110463. | | .. ______________ |
  110464. | | ' `/ | ---_ |
  110465. |___.'___/`. | ---_____|
  110466. |_______|__|_______|_________________|
  110467. | >|Sl|< |<------ Sr ----->|endW
  110468. | | |endSl |beginSr |endSr
  110469. |beginW | |endlW
  110470. mult[0] |beginSl mult[n]
  110471. <-------------- lW ----------------->
  110472. |<--W-->|
  110473. : .............. ___ | |
  110474. : .''' |`/ \ | |
  110475. :.....''' |/`....\|...|
  110476. :.........................|___|___|___|
  110477. |Sl |Sr |endW
  110478. | | |endSr
  110479. | |beginSr
  110480. | |endSl
  110481. |beginSl
  110482. |beginW
  110483. */
  110484. /* block abstraction setup *********************************************/
  110485. #ifndef WORD_ALIGN
  110486. #define WORD_ALIGN 8
  110487. #endif
  110488. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  110489. int i;
  110490. memset(vb,0,sizeof(*vb));
  110491. vb->vd=v;
  110492. vb->localalloc=0;
  110493. vb->localstore=NULL;
  110494. if(v->analysisp){
  110495. vorbis_block_internal *vbi=(vorbis_block_internal*)
  110496. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  110497. vbi->ampmax=-9999;
  110498. for(i=0;i<PACKETBLOBS;i++){
  110499. if(i==PACKETBLOBS/2){
  110500. vbi->packetblob[i]=&vb->opb;
  110501. }else{
  110502. vbi->packetblob[i]=
  110503. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  110504. }
  110505. oggpack_writeinit(vbi->packetblob[i]);
  110506. }
  110507. }
  110508. return(0);
  110509. }
  110510. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  110511. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  110512. if(bytes+vb->localtop>vb->localalloc){
  110513. /* can't just _ogg_realloc... there are outstanding pointers */
  110514. if(vb->localstore){
  110515. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  110516. vb->totaluse+=vb->localtop;
  110517. link->next=vb->reap;
  110518. link->ptr=vb->localstore;
  110519. vb->reap=link;
  110520. }
  110521. /* highly conservative */
  110522. vb->localalloc=bytes;
  110523. vb->localstore=_ogg_malloc(vb->localalloc);
  110524. vb->localtop=0;
  110525. }
  110526. {
  110527. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  110528. vb->localtop+=bytes;
  110529. return ret;
  110530. }
  110531. }
  110532. /* reap the chain, pull the ripcord */
  110533. void _vorbis_block_ripcord(vorbis_block *vb){
  110534. /* reap the chain */
  110535. struct alloc_chain *reap=vb->reap;
  110536. while(reap){
  110537. struct alloc_chain *next=reap->next;
  110538. _ogg_free(reap->ptr);
  110539. memset(reap,0,sizeof(*reap));
  110540. _ogg_free(reap);
  110541. reap=next;
  110542. }
  110543. /* consolidate storage */
  110544. if(vb->totaluse){
  110545. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  110546. vb->localalloc+=vb->totaluse;
  110547. vb->totaluse=0;
  110548. }
  110549. /* pull the ripcord */
  110550. vb->localtop=0;
  110551. vb->reap=NULL;
  110552. }
  110553. int vorbis_block_clear(vorbis_block *vb){
  110554. int i;
  110555. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110556. _vorbis_block_ripcord(vb);
  110557. if(vb->localstore)_ogg_free(vb->localstore);
  110558. if(vbi){
  110559. for(i=0;i<PACKETBLOBS;i++){
  110560. oggpack_writeclear(vbi->packetblob[i]);
  110561. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  110562. }
  110563. _ogg_free(vbi);
  110564. }
  110565. memset(vb,0,sizeof(*vb));
  110566. return(0);
  110567. }
  110568. /* Analysis side code, but directly related to blocking. Thus it's
  110569. here and not in analysis.c (which is for analysis transforms only).
  110570. The init is here because some of it is shared */
  110571. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  110572. int i;
  110573. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110574. private_state *b=NULL;
  110575. int hs;
  110576. if(ci==NULL) return 1;
  110577. hs=ci->halfrate_flag;
  110578. memset(v,0,sizeof(*v));
  110579. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  110580. v->vi=vi;
  110581. b->modebits=ilog2(ci->modes);
  110582. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  110583. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  110584. /* MDCT is tranform 0 */
  110585. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110586. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110587. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  110588. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  110589. /* Vorbis I uses only window type 0 */
  110590. b->window[0]=ilog2(ci->blocksizes[0])-6;
  110591. b->window[1]=ilog2(ci->blocksizes[1])-6;
  110592. if(encp){ /* encode/decode differ here */
  110593. /* analysis always needs an fft */
  110594. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  110595. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  110596. /* finish the codebooks */
  110597. if(!ci->fullbooks){
  110598. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110599. for(i=0;i<ci->books;i++)
  110600. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  110601. }
  110602. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  110603. for(i=0;i<ci->psys;i++){
  110604. _vp_psy_init(b->psy+i,
  110605. ci->psy_param[i],
  110606. &ci->psy_g_param,
  110607. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  110608. vi->rate);
  110609. }
  110610. v->analysisp=1;
  110611. }else{
  110612. /* finish the codebooks */
  110613. if(!ci->fullbooks){
  110614. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110615. for(i=0;i<ci->books;i++){
  110616. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  110617. /* decode codebooks are now standalone after init */
  110618. vorbis_staticbook_destroy(ci->book_param[i]);
  110619. ci->book_param[i]=NULL;
  110620. }
  110621. }
  110622. }
  110623. /* initialize the storage vectors. blocksize[1] is small for encode,
  110624. but the correct size for decode */
  110625. v->pcm_storage=ci->blocksizes[1];
  110626. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  110627. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  110628. {
  110629. int i;
  110630. for(i=0;i<vi->channels;i++)
  110631. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  110632. }
  110633. /* all 1 (large block) or 0 (small block) */
  110634. /* explicitly set for the sake of clarity */
  110635. v->lW=0; /* previous window size */
  110636. v->W=0; /* current window size */
  110637. /* all vector indexes */
  110638. v->centerW=ci->blocksizes[1]/2;
  110639. v->pcm_current=v->centerW;
  110640. /* initialize all the backend lookups */
  110641. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  110642. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  110643. for(i=0;i<ci->floors;i++)
  110644. b->flr[i]=_floor_P[ci->floor_type[i]]->
  110645. look(v,ci->floor_param[i]);
  110646. for(i=0;i<ci->residues;i++)
  110647. b->residue[i]=_residue_P[ci->residue_type[i]]->
  110648. look(v,ci->residue_param[i]);
  110649. return 0;
  110650. }
  110651. /* arbitrary settings and spec-mandated numbers get filled in here */
  110652. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  110653. private_state *b=NULL;
  110654. if(_vds_shared_init(v,vi,1))return 1;
  110655. b=(private_state*)v->backend_state;
  110656. b->psy_g_look=_vp_global_look(vi);
  110657. /* Initialize the envelope state storage */
  110658. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  110659. _ve_envelope_init(b->ve,vi);
  110660. vorbis_bitrate_init(vi,&b->bms);
  110661. /* compressed audio packets start after the headers
  110662. with sequence number 3 */
  110663. v->sequence=3;
  110664. return(0);
  110665. }
  110666. void vorbis_dsp_clear(vorbis_dsp_state *v){
  110667. int i;
  110668. if(v){
  110669. vorbis_info *vi=v->vi;
  110670. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  110671. private_state *b=(private_state*)v->backend_state;
  110672. if(b){
  110673. if(b->ve){
  110674. _ve_envelope_clear(b->ve);
  110675. _ogg_free(b->ve);
  110676. }
  110677. if(b->transform[0]){
  110678. mdct_clear((mdct_lookup*) b->transform[0][0]);
  110679. _ogg_free(b->transform[0][0]);
  110680. _ogg_free(b->transform[0]);
  110681. }
  110682. if(b->transform[1]){
  110683. mdct_clear((mdct_lookup*) b->transform[1][0]);
  110684. _ogg_free(b->transform[1][0]);
  110685. _ogg_free(b->transform[1]);
  110686. }
  110687. if(b->flr){
  110688. for(i=0;i<ci->floors;i++)
  110689. _floor_P[ci->floor_type[i]]->
  110690. free_look(b->flr[i]);
  110691. _ogg_free(b->flr);
  110692. }
  110693. if(b->residue){
  110694. for(i=0;i<ci->residues;i++)
  110695. _residue_P[ci->residue_type[i]]->
  110696. free_look(b->residue[i]);
  110697. _ogg_free(b->residue);
  110698. }
  110699. if(b->psy){
  110700. for(i=0;i<ci->psys;i++)
  110701. _vp_psy_clear(b->psy+i);
  110702. _ogg_free(b->psy);
  110703. }
  110704. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  110705. vorbis_bitrate_clear(&b->bms);
  110706. drft_clear(&b->fft_look[0]);
  110707. drft_clear(&b->fft_look[1]);
  110708. }
  110709. if(v->pcm){
  110710. for(i=0;i<vi->channels;i++)
  110711. if(v->pcm[i])_ogg_free(v->pcm[i]);
  110712. _ogg_free(v->pcm);
  110713. if(v->pcmret)_ogg_free(v->pcmret);
  110714. }
  110715. if(b){
  110716. /* free header, header1, header2 */
  110717. if(b->header)_ogg_free(b->header);
  110718. if(b->header1)_ogg_free(b->header1);
  110719. if(b->header2)_ogg_free(b->header2);
  110720. _ogg_free(b);
  110721. }
  110722. memset(v,0,sizeof(*v));
  110723. }
  110724. }
  110725. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  110726. int i;
  110727. vorbis_info *vi=v->vi;
  110728. private_state *b=(private_state*)v->backend_state;
  110729. /* free header, header1, header2 */
  110730. if(b->header)_ogg_free(b->header);b->header=NULL;
  110731. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  110732. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  110733. /* Do we have enough storage space for the requested buffer? If not,
  110734. expand the PCM (and envelope) storage */
  110735. if(v->pcm_current+vals>=v->pcm_storage){
  110736. v->pcm_storage=v->pcm_current+vals*2;
  110737. for(i=0;i<vi->channels;i++){
  110738. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  110739. }
  110740. }
  110741. for(i=0;i<vi->channels;i++)
  110742. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  110743. return(v->pcmret);
  110744. }
  110745. static void _preextrapolate_helper(vorbis_dsp_state *v){
  110746. int i;
  110747. int order=32;
  110748. float *lpc=(float*)alloca(order*sizeof(*lpc));
  110749. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  110750. long j;
  110751. v->preextrapolate=1;
  110752. if(v->pcm_current-v->centerW>order*2){ /* safety */
  110753. for(i=0;i<v->vi->channels;i++){
  110754. /* need to run the extrapolation in reverse! */
  110755. for(j=0;j<v->pcm_current;j++)
  110756. work[j]=v->pcm[i][v->pcm_current-j-1];
  110757. /* prime as above */
  110758. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  110759. /* run the predictor filter */
  110760. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  110761. order,
  110762. work+v->pcm_current-v->centerW,
  110763. v->centerW);
  110764. for(j=0;j<v->pcm_current;j++)
  110765. v->pcm[i][v->pcm_current-j-1]=work[j];
  110766. }
  110767. }
  110768. }
  110769. /* call with val<=0 to set eof */
  110770. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  110771. vorbis_info *vi=v->vi;
  110772. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110773. if(vals<=0){
  110774. int order=32;
  110775. int i;
  110776. float *lpc=(float*) alloca(order*sizeof(*lpc));
  110777. /* if it wasn't done earlier (very short sample) */
  110778. if(!v->preextrapolate)
  110779. _preextrapolate_helper(v);
  110780. /* We're encoding the end of the stream. Just make sure we have
  110781. [at least] a few full blocks of zeroes at the end. */
  110782. /* actually, we don't want zeroes; that could drop a large
  110783. amplitude off a cliff, creating spread spectrum noise that will
  110784. suck to encode. Extrapolate for the sake of cleanliness. */
  110785. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  110786. v->eofflag=v->pcm_current;
  110787. v->pcm_current+=ci->blocksizes[1]*3;
  110788. for(i=0;i<vi->channels;i++){
  110789. if(v->eofflag>order*2){
  110790. /* extrapolate with LPC to fill in */
  110791. long n;
  110792. /* make a predictor filter */
  110793. n=v->eofflag;
  110794. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  110795. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  110796. /* run the predictor filter */
  110797. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  110798. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  110799. }else{
  110800. /* not enough data to extrapolate (unlikely to happen due to
  110801. guarding the overlap, but bulletproof in case that
  110802. assumtion goes away). zeroes will do. */
  110803. memset(v->pcm[i]+v->eofflag,0,
  110804. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  110805. }
  110806. }
  110807. }else{
  110808. if(v->pcm_current+vals>v->pcm_storage)
  110809. return(OV_EINVAL);
  110810. v->pcm_current+=vals;
  110811. /* we may want to reverse extrapolate the beginning of a stream
  110812. too... in case we're beginning on a cliff! */
  110813. /* clumsy, but simple. It only runs once, so simple is good. */
  110814. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  110815. _preextrapolate_helper(v);
  110816. }
  110817. return(0);
  110818. }
  110819. /* do the deltas, envelope shaping, pre-echo and determine the size of
  110820. the next block on which to continue analysis */
  110821. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  110822. int i;
  110823. vorbis_info *vi=v->vi;
  110824. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110825. private_state *b=(private_state*)v->backend_state;
  110826. vorbis_look_psy_global *g=b->psy_g_look;
  110827. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  110828. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110829. /* check to see if we're started... */
  110830. if(!v->preextrapolate)return(0);
  110831. /* check to see if we're done... */
  110832. if(v->eofflag==-1)return(0);
  110833. /* By our invariant, we have lW, W and centerW set. Search for
  110834. the next boundary so we can determine nW (the next window size)
  110835. which lets us compute the shape of the current block's window */
  110836. /* we do an envelope search even on a single blocksize; we may still
  110837. be throwing more bits at impulses, and envelope search handles
  110838. marking impulses too. */
  110839. {
  110840. long bp=_ve_envelope_search(v);
  110841. if(bp==-1){
  110842. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  110843. full long block */
  110844. v->nW=0;
  110845. }else{
  110846. if(ci->blocksizes[0]==ci->blocksizes[1])
  110847. v->nW=0;
  110848. else
  110849. v->nW=bp;
  110850. }
  110851. }
  110852. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  110853. {
  110854. /* center of next block + next block maximum right side. */
  110855. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  110856. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  110857. although this check is
  110858. less strict that the
  110859. _ve_envelope_search,
  110860. the search is not run
  110861. if we only use one
  110862. block size */
  110863. }
  110864. /* fill in the block. Note that for a short window, lW and nW are *short*
  110865. regardless of actual settings in the stream */
  110866. _vorbis_block_ripcord(vb);
  110867. vb->lW=v->lW;
  110868. vb->W=v->W;
  110869. vb->nW=v->nW;
  110870. if(v->W){
  110871. if(!v->lW || !v->nW){
  110872. vbi->blocktype=BLOCKTYPE_TRANSITION;
  110873. /*fprintf(stderr,"-");*/
  110874. }else{
  110875. vbi->blocktype=BLOCKTYPE_LONG;
  110876. /*fprintf(stderr,"_");*/
  110877. }
  110878. }else{
  110879. if(_ve_envelope_mark(v)){
  110880. vbi->blocktype=BLOCKTYPE_IMPULSE;
  110881. /*fprintf(stderr,"|");*/
  110882. }else{
  110883. vbi->blocktype=BLOCKTYPE_PADDING;
  110884. /*fprintf(stderr,".");*/
  110885. }
  110886. }
  110887. vb->vd=v;
  110888. vb->sequence=v->sequence++;
  110889. vb->granulepos=v->granulepos;
  110890. vb->pcmend=ci->blocksizes[v->W];
  110891. /* copy the vectors; this uses the local storage in vb */
  110892. /* this tracks 'strongest peak' for later psychoacoustics */
  110893. /* moved to the global psy state; clean this mess up */
  110894. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  110895. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  110896. vbi->ampmax=g->ampmax;
  110897. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  110898. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  110899. for(i=0;i<vi->channels;i++){
  110900. vbi->pcmdelay[i]=
  110901. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  110902. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  110903. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  110904. /* before we added the delay
  110905. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  110906. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  110907. */
  110908. }
  110909. /* handle eof detection: eof==0 means that we've not yet received EOF
  110910. eof>0 marks the last 'real' sample in pcm[]
  110911. eof<0 'no more to do'; doesn't get here */
  110912. if(v->eofflag){
  110913. if(v->centerW>=v->eofflag){
  110914. v->eofflag=-1;
  110915. vb->eofflag=1;
  110916. return(1);
  110917. }
  110918. }
  110919. /* advance storage vectors and clean up */
  110920. {
  110921. int new_centerNext=ci->blocksizes[1]/2;
  110922. int movementW=centerNext-new_centerNext;
  110923. if(movementW>0){
  110924. _ve_envelope_shift(b->ve,movementW);
  110925. v->pcm_current-=movementW;
  110926. for(i=0;i<vi->channels;i++)
  110927. memmove(v->pcm[i],v->pcm[i]+movementW,
  110928. v->pcm_current*sizeof(*v->pcm[i]));
  110929. v->lW=v->W;
  110930. v->W=v->nW;
  110931. v->centerW=new_centerNext;
  110932. if(v->eofflag){
  110933. v->eofflag-=movementW;
  110934. if(v->eofflag<=0)v->eofflag=-1;
  110935. /* do not add padding to end of stream! */
  110936. if(v->centerW>=v->eofflag){
  110937. v->granulepos+=movementW-(v->centerW-v->eofflag);
  110938. }else{
  110939. v->granulepos+=movementW;
  110940. }
  110941. }else{
  110942. v->granulepos+=movementW;
  110943. }
  110944. }
  110945. }
  110946. /* done */
  110947. return(1);
  110948. }
  110949. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  110950. vorbis_info *vi=v->vi;
  110951. codec_setup_info *ci;
  110952. int hs;
  110953. if(!v->backend_state)return -1;
  110954. if(!vi)return -1;
  110955. ci=(codec_setup_info*) vi->codec_setup;
  110956. if(!ci)return -1;
  110957. hs=ci->halfrate_flag;
  110958. v->centerW=ci->blocksizes[1]>>(hs+1);
  110959. v->pcm_current=v->centerW>>hs;
  110960. v->pcm_returned=-1;
  110961. v->granulepos=-1;
  110962. v->sequence=-1;
  110963. v->eofflag=0;
  110964. ((private_state *)(v->backend_state))->sample_count=-1;
  110965. return(0);
  110966. }
  110967. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  110968. if(_vds_shared_init(v,vi,0)) return 1;
  110969. vorbis_synthesis_restart(v);
  110970. return 0;
  110971. }
  110972. /* Unlike in analysis, the window is only partially applied for each
  110973. block. The time domain envelope is not yet handled at the point of
  110974. calling (as it relies on the previous block). */
  110975. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  110976. vorbis_info *vi=v->vi;
  110977. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110978. private_state *b=(private_state*)v->backend_state;
  110979. int hs=ci->halfrate_flag;
  110980. int i,j;
  110981. if(!vb)return(OV_EINVAL);
  110982. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  110983. v->lW=v->W;
  110984. v->W=vb->W;
  110985. v->nW=-1;
  110986. if((v->sequence==-1)||
  110987. (v->sequence+1 != vb->sequence)){
  110988. v->granulepos=-1; /* out of sequence; lose count */
  110989. b->sample_count=-1;
  110990. }
  110991. v->sequence=vb->sequence;
  110992. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  110993. was called on block */
  110994. int n=ci->blocksizes[v->W]>>(hs+1);
  110995. int n0=ci->blocksizes[0]>>(hs+1);
  110996. int n1=ci->blocksizes[1]>>(hs+1);
  110997. int thisCenter;
  110998. int prevCenter;
  110999. v->glue_bits+=vb->glue_bits;
  111000. v->time_bits+=vb->time_bits;
  111001. v->floor_bits+=vb->floor_bits;
  111002. v->res_bits+=vb->res_bits;
  111003. if(v->centerW){
  111004. thisCenter=n1;
  111005. prevCenter=0;
  111006. }else{
  111007. thisCenter=0;
  111008. prevCenter=n1;
  111009. }
  111010. /* v->pcm is now used like a two-stage double buffer. We don't want
  111011. to have to constantly shift *or* adjust memory usage. Don't
  111012. accept a new block until the old is shifted out */
  111013. for(j=0;j<vi->channels;j++){
  111014. /* the overlap/add section */
  111015. if(v->lW){
  111016. if(v->W){
  111017. /* large/large */
  111018. float *w=_vorbis_window_get(b->window[1]-hs);
  111019. float *pcm=v->pcm[j]+prevCenter;
  111020. float *p=vb->pcm[j];
  111021. for(i=0;i<n1;i++)
  111022. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111023. }else{
  111024. /* large/small */
  111025. float *w=_vorbis_window_get(b->window[0]-hs);
  111026. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111027. float *p=vb->pcm[j];
  111028. for(i=0;i<n0;i++)
  111029. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111030. }
  111031. }else{
  111032. if(v->W){
  111033. /* small/large */
  111034. float *w=_vorbis_window_get(b->window[0]-hs);
  111035. float *pcm=v->pcm[j]+prevCenter;
  111036. float *p=vb->pcm[j]+n1/2-n0/2;
  111037. for(i=0;i<n0;i++)
  111038. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111039. for(;i<n1/2+n0/2;i++)
  111040. pcm[i]=p[i];
  111041. }else{
  111042. /* small/small */
  111043. float *w=_vorbis_window_get(b->window[0]-hs);
  111044. float *pcm=v->pcm[j]+prevCenter;
  111045. float *p=vb->pcm[j];
  111046. for(i=0;i<n0;i++)
  111047. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111048. }
  111049. }
  111050. /* the copy section */
  111051. {
  111052. float *pcm=v->pcm[j]+thisCenter;
  111053. float *p=vb->pcm[j]+n;
  111054. for(i=0;i<n;i++)
  111055. pcm[i]=p[i];
  111056. }
  111057. }
  111058. if(v->centerW)
  111059. v->centerW=0;
  111060. else
  111061. v->centerW=n1;
  111062. /* deal with initial packet state; we do this using the explicit
  111063. pcm_returned==-1 flag otherwise we're sensitive to first block
  111064. being short or long */
  111065. if(v->pcm_returned==-1){
  111066. v->pcm_returned=thisCenter;
  111067. v->pcm_current=thisCenter;
  111068. }else{
  111069. v->pcm_returned=prevCenter;
  111070. v->pcm_current=prevCenter+
  111071. ((ci->blocksizes[v->lW]/4+
  111072. ci->blocksizes[v->W]/4)>>hs);
  111073. }
  111074. }
  111075. /* track the frame number... This is for convenience, but also
  111076. making sure our last packet doesn't end with added padding. If
  111077. the last packet is partial, the number of samples we'll have to
  111078. return will be past the vb->granulepos.
  111079. This is not foolproof! It will be confused if we begin
  111080. decoding at the last page after a seek or hole. In that case,
  111081. we don't have a starting point to judge where the last frame
  111082. is. For this reason, vorbisfile will always try to make sure
  111083. it reads the last two marked pages in proper sequence */
  111084. if(b->sample_count==-1){
  111085. b->sample_count=0;
  111086. }else{
  111087. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111088. }
  111089. if(v->granulepos==-1){
  111090. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111091. v->granulepos=vb->granulepos;
  111092. /* is this a short page? */
  111093. if(b->sample_count>v->granulepos){
  111094. /* corner case; if this is both the first and last audio page,
  111095. then spec says the end is cut, not beginning */
  111096. if(vb->eofflag){
  111097. /* trim the end */
  111098. /* no preceeding granulepos; assume we started at zero (we'd
  111099. have to in a short single-page stream) */
  111100. /* granulepos could be -1 due to a seek, but that would result
  111101. in a long count, not short count */
  111102. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111103. }else{
  111104. /* trim the beginning */
  111105. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111106. if(v->pcm_returned>v->pcm_current)
  111107. v->pcm_returned=v->pcm_current;
  111108. }
  111109. }
  111110. }
  111111. }else{
  111112. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111113. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111114. if(v->granulepos>vb->granulepos){
  111115. long extra=v->granulepos-vb->granulepos;
  111116. if(extra)
  111117. if(vb->eofflag){
  111118. /* partial last frame. Strip the extra samples off */
  111119. v->pcm_current-=extra>>hs;
  111120. } /* else {Shouldn't happen *unless* the bitstream is out of
  111121. spec. Either way, believe the bitstream } */
  111122. } /* else {Shouldn't happen *unless* the bitstream is out of
  111123. spec. Either way, believe the bitstream } */
  111124. v->granulepos=vb->granulepos;
  111125. }
  111126. }
  111127. /* Update, cleanup */
  111128. if(vb->eofflag)v->eofflag=1;
  111129. return(0);
  111130. }
  111131. /* pcm==NULL indicates we just want the pending samples, no more */
  111132. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111133. vorbis_info *vi=v->vi;
  111134. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111135. if(pcm){
  111136. int i;
  111137. for(i=0;i<vi->channels;i++)
  111138. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111139. *pcm=v->pcmret;
  111140. }
  111141. return(v->pcm_current-v->pcm_returned);
  111142. }
  111143. return(0);
  111144. }
  111145. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111146. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111147. v->pcm_returned+=n;
  111148. return(0);
  111149. }
  111150. /* intended for use with a specific vorbisfile feature; we want access
  111151. to the [usually synthetic/postextrapolated] buffer and lapping at
  111152. the end of a decode cycle, specifically, a half-short-block worth.
  111153. This funtion works like pcmout above, except it will also expose
  111154. this implicit buffer data not normally decoded. */
  111155. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111156. vorbis_info *vi=v->vi;
  111157. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111158. int hs=ci->halfrate_flag;
  111159. int n=ci->blocksizes[v->W]>>(hs+1);
  111160. int n0=ci->blocksizes[0]>>(hs+1);
  111161. int n1=ci->blocksizes[1]>>(hs+1);
  111162. int i,j;
  111163. if(v->pcm_returned<0)return 0;
  111164. /* our returned data ends at pcm_returned; because the synthesis pcm
  111165. buffer is a two-fragment ring, that means our data block may be
  111166. fragmented by buffering, wrapping or a short block not filling
  111167. out a buffer. To simplify things, we unfragment if it's at all
  111168. possibly needed. Otherwise, we'd need to call lapout more than
  111169. once as well as hold additional dsp state. Opt for
  111170. simplicity. */
  111171. /* centerW was advanced by blockin; it would be the center of the
  111172. *next* block */
  111173. if(v->centerW==n1){
  111174. /* the data buffer wraps; swap the halves */
  111175. /* slow, sure, small */
  111176. for(j=0;j<vi->channels;j++){
  111177. float *p=v->pcm[j];
  111178. for(i=0;i<n1;i++){
  111179. float temp=p[i];
  111180. p[i]=p[i+n1];
  111181. p[i+n1]=temp;
  111182. }
  111183. }
  111184. v->pcm_current-=n1;
  111185. v->pcm_returned-=n1;
  111186. v->centerW=0;
  111187. }
  111188. /* solidify buffer into contiguous space */
  111189. if((v->lW^v->W)==1){
  111190. /* long/short or short/long */
  111191. for(j=0;j<vi->channels;j++){
  111192. float *s=v->pcm[j];
  111193. float *d=v->pcm[j]+(n1-n0)/2;
  111194. for(i=(n1+n0)/2-1;i>=0;--i)
  111195. d[i]=s[i];
  111196. }
  111197. v->pcm_returned+=(n1-n0)/2;
  111198. v->pcm_current+=(n1-n0)/2;
  111199. }else{
  111200. if(v->lW==0){
  111201. /* short/short */
  111202. for(j=0;j<vi->channels;j++){
  111203. float *s=v->pcm[j];
  111204. float *d=v->pcm[j]+n1-n0;
  111205. for(i=n0-1;i>=0;--i)
  111206. d[i]=s[i];
  111207. }
  111208. v->pcm_returned+=n1-n0;
  111209. v->pcm_current+=n1-n0;
  111210. }
  111211. }
  111212. if(pcm){
  111213. int i;
  111214. for(i=0;i<vi->channels;i++)
  111215. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111216. *pcm=v->pcmret;
  111217. }
  111218. return(n1+n-v->pcm_returned);
  111219. }
  111220. float *vorbis_window(vorbis_dsp_state *v,int W){
  111221. vorbis_info *vi=v->vi;
  111222. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111223. int hs=ci->halfrate_flag;
  111224. private_state *b=(private_state*)v->backend_state;
  111225. if(b->window[W]-1<0)return NULL;
  111226. return _vorbis_window_get(b->window[W]-hs);
  111227. }
  111228. #endif
  111229. /*** End of inlined file: block.c ***/
  111230. /*** Start of inlined file: codebook.c ***/
  111231. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111232. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111233. // tasks..
  111234. #if JUCE_MSVC
  111235. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111236. #endif
  111237. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111238. #if JUCE_USE_OGGVORBIS
  111239. #include <stdlib.h>
  111240. #include <string.h>
  111241. #include <math.h>
  111242. /* packs the given codebook into the bitstream **************************/
  111243. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111244. long i,j;
  111245. int ordered=0;
  111246. /* first the basic parameters */
  111247. oggpack_write(opb,0x564342,24);
  111248. oggpack_write(opb,c->dim,16);
  111249. oggpack_write(opb,c->entries,24);
  111250. /* pack the codewords. There are two packings; length ordered and
  111251. length random. Decide between the two now. */
  111252. for(i=1;i<c->entries;i++)
  111253. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111254. if(i==c->entries)ordered=1;
  111255. if(ordered){
  111256. /* length ordered. We only need to say how many codewords of
  111257. each length. The actual codewords are generated
  111258. deterministically */
  111259. long count=0;
  111260. oggpack_write(opb,1,1); /* ordered */
  111261. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111262. for(i=1;i<c->entries;i++){
  111263. long thisx=c->lengthlist[i];
  111264. long last=c->lengthlist[i-1];
  111265. if(thisx>last){
  111266. for(j=last;j<thisx;j++){
  111267. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111268. count=i;
  111269. }
  111270. }
  111271. }
  111272. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111273. }else{
  111274. /* length random. Again, we don't code the codeword itself, just
  111275. the length. This time, though, we have to encode each length */
  111276. oggpack_write(opb,0,1); /* unordered */
  111277. /* algortihmic mapping has use for 'unused entries', which we tag
  111278. here. The algorithmic mapping happens as usual, but the unused
  111279. entry has no codeword. */
  111280. for(i=0;i<c->entries;i++)
  111281. if(c->lengthlist[i]==0)break;
  111282. if(i==c->entries){
  111283. oggpack_write(opb,0,1); /* no unused entries */
  111284. for(i=0;i<c->entries;i++)
  111285. oggpack_write(opb,c->lengthlist[i]-1,5);
  111286. }else{
  111287. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  111288. for(i=0;i<c->entries;i++){
  111289. if(c->lengthlist[i]==0){
  111290. oggpack_write(opb,0,1);
  111291. }else{
  111292. oggpack_write(opb,1,1);
  111293. oggpack_write(opb,c->lengthlist[i]-1,5);
  111294. }
  111295. }
  111296. }
  111297. }
  111298. /* is the entry number the desired return value, or do we have a
  111299. mapping? If we have a mapping, what type? */
  111300. oggpack_write(opb,c->maptype,4);
  111301. switch(c->maptype){
  111302. case 0:
  111303. /* no mapping */
  111304. break;
  111305. case 1:case 2:
  111306. /* implicitly populated value mapping */
  111307. /* explicitly populated value mapping */
  111308. if(!c->quantlist){
  111309. /* no quantlist? error */
  111310. return(-1);
  111311. }
  111312. /* values that define the dequantization */
  111313. oggpack_write(opb,c->q_min,32);
  111314. oggpack_write(opb,c->q_delta,32);
  111315. oggpack_write(opb,c->q_quant-1,4);
  111316. oggpack_write(opb,c->q_sequencep,1);
  111317. {
  111318. int quantvals;
  111319. switch(c->maptype){
  111320. case 1:
  111321. /* a single column of (c->entries/c->dim) quantized values for
  111322. building a full value list algorithmically (square lattice) */
  111323. quantvals=_book_maptype1_quantvals(c);
  111324. break;
  111325. case 2:
  111326. /* every value (c->entries*c->dim total) specified explicitly */
  111327. quantvals=c->entries*c->dim;
  111328. break;
  111329. default: /* NOT_REACHABLE */
  111330. quantvals=-1;
  111331. }
  111332. /* quantized values */
  111333. for(i=0;i<quantvals;i++)
  111334. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111335. }
  111336. break;
  111337. default:
  111338. /* error case; we don't have any other map types now */
  111339. return(-1);
  111340. }
  111341. return(0);
  111342. }
  111343. /* unpacks a codebook from the packet buffer into the codebook struct,
  111344. readies the codebook auxiliary structures for decode *************/
  111345. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111346. long i,j;
  111347. memset(s,0,sizeof(*s));
  111348. s->allocedp=1;
  111349. /* make sure alignment is correct */
  111350. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111351. /* first the basic parameters */
  111352. s->dim=oggpack_read(opb,16);
  111353. s->entries=oggpack_read(opb,24);
  111354. if(s->entries==-1)goto _eofout;
  111355. /* codeword ordering.... length ordered or unordered? */
  111356. switch((int)oggpack_read(opb,1)){
  111357. case 0:
  111358. /* unordered */
  111359. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111360. /* allocated but unused entries? */
  111361. if(oggpack_read(opb,1)){
  111362. /* yes, unused entries */
  111363. for(i=0;i<s->entries;i++){
  111364. if(oggpack_read(opb,1)){
  111365. long num=oggpack_read(opb,5);
  111366. if(num==-1)goto _eofout;
  111367. s->lengthlist[i]=num+1;
  111368. }else
  111369. s->lengthlist[i]=0;
  111370. }
  111371. }else{
  111372. /* all entries used; no tagging */
  111373. for(i=0;i<s->entries;i++){
  111374. long num=oggpack_read(opb,5);
  111375. if(num==-1)goto _eofout;
  111376. s->lengthlist[i]=num+1;
  111377. }
  111378. }
  111379. break;
  111380. case 1:
  111381. /* ordered */
  111382. {
  111383. long length=oggpack_read(opb,5)+1;
  111384. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111385. for(i=0;i<s->entries;){
  111386. long num=oggpack_read(opb,_ilog(s->entries-i));
  111387. if(num==-1)goto _eofout;
  111388. for(j=0;j<num && i<s->entries;j++,i++)
  111389. s->lengthlist[i]=length;
  111390. length++;
  111391. }
  111392. }
  111393. break;
  111394. default:
  111395. /* EOF */
  111396. return(-1);
  111397. }
  111398. /* Do we have a mapping to unpack? */
  111399. switch((s->maptype=oggpack_read(opb,4))){
  111400. case 0:
  111401. /* no mapping */
  111402. break;
  111403. case 1: case 2:
  111404. /* implicitly populated value mapping */
  111405. /* explicitly populated value mapping */
  111406. s->q_min=oggpack_read(opb,32);
  111407. s->q_delta=oggpack_read(opb,32);
  111408. s->q_quant=oggpack_read(opb,4)+1;
  111409. s->q_sequencep=oggpack_read(opb,1);
  111410. {
  111411. int quantvals=0;
  111412. switch(s->maptype){
  111413. case 1:
  111414. quantvals=_book_maptype1_quantvals(s);
  111415. break;
  111416. case 2:
  111417. quantvals=s->entries*s->dim;
  111418. break;
  111419. }
  111420. /* quantized values */
  111421. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  111422. for(i=0;i<quantvals;i++)
  111423. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  111424. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  111425. }
  111426. break;
  111427. default:
  111428. goto _errout;
  111429. }
  111430. /* all set */
  111431. return(0);
  111432. _errout:
  111433. _eofout:
  111434. vorbis_staticbook_clear(s);
  111435. return(-1);
  111436. }
  111437. /* returns the number of bits ************************************************/
  111438. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  111439. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  111440. return(book->c->lengthlist[a]);
  111441. }
  111442. /* One the encode side, our vector writers are each designed for a
  111443. specific purpose, and the encoder is not flexible without modification:
  111444. The LSP vector coder uses a single stage nearest-match with no
  111445. interleave, so no step and no error return. This is specced by floor0
  111446. and doesn't change.
  111447. Residue0 encoding interleaves, uses multiple stages, and each stage
  111448. peels of a specific amount of resolution from a lattice (thus we want
  111449. to match by threshold, not nearest match). Residue doesn't *have* to
  111450. be encoded that way, but to change it, one will need to add more
  111451. infrastructure on the encode side (decode side is specced and simpler) */
  111452. /* floor0 LSP (single stage, non interleaved, nearest match) */
  111453. /* returns entry number and *modifies a* to the quantization value *****/
  111454. int vorbis_book_errorv(codebook *book,float *a){
  111455. int dim=book->dim,k;
  111456. int best=_best(book,a,1);
  111457. for(k=0;k<dim;k++)
  111458. a[k]=(book->valuelist+best*dim)[k];
  111459. return(best);
  111460. }
  111461. /* returns the number of bits and *modifies a* to the quantization value *****/
  111462. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  111463. int k,dim=book->dim;
  111464. for(k=0;k<dim;k++)
  111465. a[k]=(book->valuelist+best*dim)[k];
  111466. return(vorbis_book_encode(book,best,b));
  111467. }
  111468. /* the 'eliminate the decode tree' optimization actually requires the
  111469. codewords to be MSb first, not LSb. This is an annoying inelegancy
  111470. (and one of the first places where carefully thought out design
  111471. turned out to be wrong; Vorbis II and future Ogg codecs should go
  111472. to an MSb bitpacker), but not actually the huge hit it appears to
  111473. be. The first-stage decode table catches most words so that
  111474. bitreverse is not in the main execution path. */
  111475. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  111476. int read=book->dec_maxlength;
  111477. long lo,hi;
  111478. long lok = oggpack_look(b,book->dec_firsttablen);
  111479. if (lok >= 0) {
  111480. long entry = book->dec_firsttable[lok];
  111481. if(entry&0x80000000UL){
  111482. lo=(entry>>15)&0x7fff;
  111483. hi=book->used_entries-(entry&0x7fff);
  111484. }else{
  111485. oggpack_adv(b, book->dec_codelengths[entry-1]);
  111486. return(entry-1);
  111487. }
  111488. }else{
  111489. lo=0;
  111490. hi=book->used_entries;
  111491. }
  111492. lok = oggpack_look(b, read);
  111493. while(lok<0 && read>1)
  111494. lok = oggpack_look(b, --read);
  111495. if(lok<0)return -1;
  111496. /* bisect search for the codeword in the ordered list */
  111497. {
  111498. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  111499. while(hi-lo>1){
  111500. long p=(hi-lo)>>1;
  111501. long test=book->codelist[lo+p]>testword;
  111502. lo+=p&(test-1);
  111503. hi-=p&(-test);
  111504. }
  111505. if(book->dec_codelengths[lo]<=read){
  111506. oggpack_adv(b, book->dec_codelengths[lo]);
  111507. return(lo);
  111508. }
  111509. }
  111510. oggpack_adv(b, read);
  111511. return(-1);
  111512. }
  111513. /* Decode side is specced and easier, because we don't need to find
  111514. matches using different criteria; we simply read and map. There are
  111515. two things we need to do 'depending':
  111516. We may need to support interleave. We don't really, but it's
  111517. convenient to do it here rather than rebuild the vector later.
  111518. Cascades may be additive or multiplicitive; this is not inherent in
  111519. the codebook, but set in the code using the codebook. Like
  111520. interleaving, it's easiest to do it here.
  111521. addmul==0 -> declarative (set the value)
  111522. addmul==1 -> additive
  111523. addmul==2 -> multiplicitive */
  111524. /* returns the [original, not compacted] entry number or -1 on eof *********/
  111525. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  111526. long packed_entry=decode_packed_entry_number(book,b);
  111527. if(packed_entry>=0)
  111528. return(book->dec_index[packed_entry]);
  111529. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  111530. return(packed_entry);
  111531. }
  111532. /* returns 0 on OK or -1 on eof *************************************/
  111533. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111534. int step=n/book->dim;
  111535. long *entry = (long*)alloca(sizeof(*entry)*step);
  111536. float **t = (float**)alloca(sizeof(*t)*step);
  111537. int i,j,o;
  111538. for (i = 0; i < step; i++) {
  111539. entry[i]=decode_packed_entry_number(book,b);
  111540. if(entry[i]==-1)return(-1);
  111541. t[i] = book->valuelist+entry[i]*book->dim;
  111542. }
  111543. for(i=0,o=0;i<book->dim;i++,o+=step)
  111544. for (j=0;j<step;j++)
  111545. a[o+j]+=t[j][i];
  111546. return(0);
  111547. }
  111548. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111549. int i,j,entry;
  111550. float *t;
  111551. if(book->dim>8){
  111552. for(i=0;i<n;){
  111553. entry = decode_packed_entry_number(book,b);
  111554. if(entry==-1)return(-1);
  111555. t = book->valuelist+entry*book->dim;
  111556. for (j=0;j<book->dim;)
  111557. a[i++]+=t[j++];
  111558. }
  111559. }else{
  111560. for(i=0;i<n;){
  111561. entry = decode_packed_entry_number(book,b);
  111562. if(entry==-1)return(-1);
  111563. t = book->valuelist+entry*book->dim;
  111564. j=0;
  111565. switch((int)book->dim){
  111566. case 8:
  111567. a[i++]+=t[j++];
  111568. case 7:
  111569. a[i++]+=t[j++];
  111570. case 6:
  111571. a[i++]+=t[j++];
  111572. case 5:
  111573. a[i++]+=t[j++];
  111574. case 4:
  111575. a[i++]+=t[j++];
  111576. case 3:
  111577. a[i++]+=t[j++];
  111578. case 2:
  111579. a[i++]+=t[j++];
  111580. case 1:
  111581. a[i++]+=t[j++];
  111582. case 0:
  111583. break;
  111584. }
  111585. }
  111586. }
  111587. return(0);
  111588. }
  111589. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  111590. int i,j,entry;
  111591. float *t;
  111592. for(i=0;i<n;){
  111593. entry = decode_packed_entry_number(book,b);
  111594. if(entry==-1)return(-1);
  111595. t = book->valuelist+entry*book->dim;
  111596. for (j=0;j<book->dim;)
  111597. a[i++]=t[j++];
  111598. }
  111599. return(0);
  111600. }
  111601. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  111602. oggpack_buffer *b,int n){
  111603. long i,j,entry;
  111604. int chptr=0;
  111605. for(i=offset/ch;i<(offset+n)/ch;){
  111606. entry = decode_packed_entry_number(book,b);
  111607. if(entry==-1)return(-1);
  111608. {
  111609. const float *t = book->valuelist+entry*book->dim;
  111610. for (j=0;j<book->dim;j++){
  111611. a[chptr++][i]+=t[j];
  111612. if(chptr==ch){
  111613. chptr=0;
  111614. i++;
  111615. }
  111616. }
  111617. }
  111618. }
  111619. return(0);
  111620. }
  111621. #ifdef _V_SELFTEST
  111622. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  111623. number of vectors through (keeping track of the quantized values),
  111624. and decode using the unpacked book. quantized version of in should
  111625. exactly equal out */
  111626. #include <stdio.h>
  111627. #include "vorbis/book/lsp20_0.vqh"
  111628. #include "vorbis/book/res0a_13.vqh"
  111629. #define TESTSIZE 40
  111630. float test1[TESTSIZE]={
  111631. 0.105939f,
  111632. 0.215373f,
  111633. 0.429117f,
  111634. 0.587974f,
  111635. 0.181173f,
  111636. 0.296583f,
  111637. 0.515707f,
  111638. 0.715261f,
  111639. 0.162327f,
  111640. 0.263834f,
  111641. 0.342876f,
  111642. 0.406025f,
  111643. 0.103571f,
  111644. 0.223561f,
  111645. 0.368513f,
  111646. 0.540313f,
  111647. 0.136672f,
  111648. 0.395882f,
  111649. 0.587183f,
  111650. 0.652476f,
  111651. 0.114338f,
  111652. 0.417300f,
  111653. 0.525486f,
  111654. 0.698679f,
  111655. 0.147492f,
  111656. 0.324481f,
  111657. 0.643089f,
  111658. 0.757582f,
  111659. 0.139556f,
  111660. 0.215795f,
  111661. 0.324559f,
  111662. 0.399387f,
  111663. 0.120236f,
  111664. 0.267420f,
  111665. 0.446940f,
  111666. 0.608760f,
  111667. 0.115587f,
  111668. 0.287234f,
  111669. 0.571081f,
  111670. 0.708603f,
  111671. };
  111672. float test3[TESTSIZE]={
  111673. 0,1,-2,3,4,-5,6,7,8,9,
  111674. 8,-2,7,-1,4,6,8,3,1,-9,
  111675. 10,11,12,13,14,15,26,17,18,19,
  111676. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  111677. static_codebook *testlist[]={&_vq_book_lsp20_0,
  111678. &_vq_book_res0a_13,NULL};
  111679. float *testvec[]={test1,test3};
  111680. int main(){
  111681. oggpack_buffer write;
  111682. oggpack_buffer read;
  111683. long ptr=0,i;
  111684. oggpack_writeinit(&write);
  111685. fprintf(stderr,"Testing codebook abstraction...:\n");
  111686. while(testlist[ptr]){
  111687. codebook c;
  111688. static_codebook s;
  111689. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  111690. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  111691. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  111692. memset(iv,0,sizeof(*iv)*TESTSIZE);
  111693. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  111694. /* pack the codebook, write the testvector */
  111695. oggpack_reset(&write);
  111696. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  111697. we can write */
  111698. vorbis_staticbook_pack(testlist[ptr],&write);
  111699. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  111700. for(i=0;i<TESTSIZE;i+=c.dim){
  111701. int best=_best(&c,qv+i,1);
  111702. vorbis_book_encodev(&c,best,qv+i,&write);
  111703. }
  111704. vorbis_book_clear(&c);
  111705. fprintf(stderr,"OK.\n");
  111706. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  111707. /* transfer the write data to a read buffer and unpack/read */
  111708. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  111709. if(vorbis_staticbook_unpack(&read,&s)){
  111710. fprintf(stderr,"Error unpacking codebook.\n");
  111711. exit(1);
  111712. }
  111713. if(vorbis_book_init_decode(&c,&s)){
  111714. fprintf(stderr,"Error initializing codebook.\n");
  111715. exit(1);
  111716. }
  111717. for(i=0;i<TESTSIZE;i+=c.dim)
  111718. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  111719. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  111720. exit(1);
  111721. }
  111722. for(i=0;i<TESTSIZE;i++)
  111723. if(fabs(qv[i]-iv[i])>.000001){
  111724. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  111725. iv[i],qv[i],i);
  111726. exit(1);
  111727. }
  111728. fprintf(stderr,"OK\n");
  111729. ptr++;
  111730. }
  111731. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  111732. exit(0);
  111733. }
  111734. #endif
  111735. #endif
  111736. /*** End of inlined file: codebook.c ***/
  111737. /*** Start of inlined file: envelope.c ***/
  111738. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111739. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111740. // tasks..
  111741. #if JUCE_MSVC
  111742. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111743. #endif
  111744. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111745. #if JUCE_USE_OGGVORBIS
  111746. #include <stdlib.h>
  111747. #include <string.h>
  111748. #include <stdio.h>
  111749. #include <math.h>
  111750. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  111751. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111752. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111753. int ch=vi->channels;
  111754. int i,j;
  111755. int n=e->winlength=128;
  111756. e->searchstep=64; /* not random */
  111757. e->minenergy=gi->preecho_minenergy;
  111758. e->ch=ch;
  111759. e->storage=128;
  111760. e->cursor=ci->blocksizes[1]/2;
  111761. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  111762. mdct_init(&e->mdct,n);
  111763. for(i=0;i<n;i++){
  111764. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  111765. e->mdct_win[i]*=e->mdct_win[i];
  111766. }
  111767. /* magic follows */
  111768. e->band[0].begin=2; e->band[0].end=4;
  111769. e->band[1].begin=4; e->band[1].end=5;
  111770. e->band[2].begin=6; e->band[2].end=6;
  111771. e->band[3].begin=9; e->band[3].end=8;
  111772. e->band[4].begin=13; e->band[4].end=8;
  111773. e->band[5].begin=17; e->band[5].end=8;
  111774. e->band[6].begin=22; e->band[6].end=8;
  111775. for(j=0;j<VE_BANDS;j++){
  111776. n=e->band[j].end;
  111777. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  111778. for(i=0;i<n;i++){
  111779. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  111780. e->band[j].total+=e->band[j].window[i];
  111781. }
  111782. e->band[j].total=1./e->band[j].total;
  111783. }
  111784. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  111785. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  111786. }
  111787. void _ve_envelope_clear(envelope_lookup *e){
  111788. int i;
  111789. mdct_clear(&e->mdct);
  111790. for(i=0;i<VE_BANDS;i++)
  111791. _ogg_free(e->band[i].window);
  111792. _ogg_free(e->mdct_win);
  111793. _ogg_free(e->filter);
  111794. _ogg_free(e->mark);
  111795. memset(e,0,sizeof(*e));
  111796. }
  111797. /* fairly straight threshhold-by-band based until we find something
  111798. that works better and isn't patented. */
  111799. static int _ve_amp(envelope_lookup *ve,
  111800. vorbis_info_psy_global *gi,
  111801. float *data,
  111802. envelope_band *bands,
  111803. envelope_filter_state *filters,
  111804. long pos){
  111805. long n=ve->winlength;
  111806. int ret=0;
  111807. long i,j;
  111808. float decay;
  111809. /* we want to have a 'minimum bar' for energy, else we're just
  111810. basing blocks on quantization noise that outweighs the signal
  111811. itself (for low power signals) */
  111812. float minV=ve->minenergy;
  111813. float *vec=(float*) alloca(n*sizeof(*vec));
  111814. /* stretch is used to gradually lengthen the number of windows
  111815. considered prevoius-to-potential-trigger */
  111816. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  111817. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  111818. if(penalty<0.f)penalty=0.f;
  111819. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  111820. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  111821. totalshift+pos*ve->searchstep);*/
  111822. /* window and transform */
  111823. for(i=0;i<n;i++)
  111824. vec[i]=data[i]*ve->mdct_win[i];
  111825. mdct_forward(&ve->mdct,vec,vec);
  111826. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  111827. /* near-DC spreading function; this has nothing to do with
  111828. psychoacoustics, just sidelobe leakage and window size */
  111829. {
  111830. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  111831. int ptr=filters->nearptr;
  111832. /* the accumulation is regularly refreshed from scratch to avoid
  111833. floating point creep */
  111834. if(ptr==0){
  111835. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  111836. filters->nearDC_partialacc=temp;
  111837. }else{
  111838. decay=filters->nearDC_acc+=temp;
  111839. filters->nearDC_partialacc+=temp;
  111840. }
  111841. filters->nearDC_acc-=filters->nearDC[ptr];
  111842. filters->nearDC[ptr]=temp;
  111843. decay*=(1./(VE_NEARDC+1));
  111844. filters->nearptr++;
  111845. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  111846. decay=todB(&decay)*.5-15.f;
  111847. }
  111848. /* perform spreading and limiting, also smooth the spectrum. yes,
  111849. the MDCT results in all real coefficients, but it still *behaves*
  111850. like real/imaginary pairs */
  111851. for(i=0;i<n/2;i+=2){
  111852. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  111853. val=todB(&val)*.5f;
  111854. if(val<decay)val=decay;
  111855. if(val<minV)val=minV;
  111856. vec[i>>1]=val;
  111857. decay-=8.;
  111858. }
  111859. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  111860. /* perform preecho/postecho triggering by band */
  111861. for(j=0;j<VE_BANDS;j++){
  111862. float acc=0.;
  111863. float valmax,valmin;
  111864. /* accumulate amplitude */
  111865. for(i=0;i<bands[j].end;i++)
  111866. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  111867. acc*=bands[j].total;
  111868. /* convert amplitude to delta */
  111869. {
  111870. int p,thisx=filters[j].ampptr;
  111871. float postmax,postmin,premax=-99999.f,premin=99999.f;
  111872. p=thisx;
  111873. p--;
  111874. if(p<0)p+=VE_AMP;
  111875. postmax=max(acc,filters[j].ampbuf[p]);
  111876. postmin=min(acc,filters[j].ampbuf[p]);
  111877. for(i=0;i<stretch;i++){
  111878. p--;
  111879. if(p<0)p+=VE_AMP;
  111880. premax=max(premax,filters[j].ampbuf[p]);
  111881. premin=min(premin,filters[j].ampbuf[p]);
  111882. }
  111883. valmin=postmin-premin;
  111884. valmax=postmax-premax;
  111885. /*filters[j].markers[pos]=valmax;*/
  111886. filters[j].ampbuf[thisx]=acc;
  111887. filters[j].ampptr++;
  111888. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  111889. }
  111890. /* look at min/max, decide trigger */
  111891. if(valmax>gi->preecho_thresh[j]+penalty){
  111892. ret|=1;
  111893. ret|=4;
  111894. }
  111895. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  111896. }
  111897. return(ret);
  111898. }
  111899. #if 0
  111900. static int seq=0;
  111901. static ogg_int64_t totalshift=-1024;
  111902. #endif
  111903. long _ve_envelope_search(vorbis_dsp_state *v){
  111904. vorbis_info *vi=v->vi;
  111905. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111906. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111907. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  111908. long i,j;
  111909. int first=ve->current/ve->searchstep;
  111910. int last=v->pcm_current/ve->searchstep-VE_WIN;
  111911. if(first<0)first=0;
  111912. /* make sure we have enough storage to match the PCM */
  111913. if(last+VE_WIN+VE_POST>ve->storage){
  111914. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  111915. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  111916. }
  111917. for(j=first;j<last;j++){
  111918. int ret=0;
  111919. ve->stretch++;
  111920. if(ve->stretch>VE_MAXSTRETCH*2)
  111921. ve->stretch=VE_MAXSTRETCH*2;
  111922. for(i=0;i<ve->ch;i++){
  111923. float *pcm=v->pcm[i]+ve->searchstep*(j);
  111924. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  111925. }
  111926. ve->mark[j+VE_POST]=0;
  111927. if(ret&1){
  111928. ve->mark[j]=1;
  111929. ve->mark[j+1]=1;
  111930. }
  111931. if(ret&2){
  111932. ve->mark[j]=1;
  111933. if(j>0)ve->mark[j-1]=1;
  111934. }
  111935. if(ret&4)ve->stretch=-1;
  111936. }
  111937. ve->current=last*ve->searchstep;
  111938. {
  111939. long centerW=v->centerW;
  111940. long testW=
  111941. centerW+
  111942. ci->blocksizes[v->W]/4+
  111943. ci->blocksizes[1]/2+
  111944. ci->blocksizes[0]/4;
  111945. j=ve->cursor;
  111946. while(j<ve->current-(ve->searchstep)){/* account for postecho
  111947. working back one window */
  111948. if(j>=testW)return(1);
  111949. ve->cursor=j;
  111950. if(ve->mark[j/ve->searchstep]){
  111951. if(j>centerW){
  111952. #if 0
  111953. if(j>ve->curmark){
  111954. float *marker=alloca(v->pcm_current*sizeof(*marker));
  111955. int l,m;
  111956. memset(marker,0,sizeof(*marker)*v->pcm_current);
  111957. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  111958. seq,
  111959. (totalshift+ve->cursor)/44100.,
  111960. (totalshift+j)/44100.);
  111961. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  111962. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  111963. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  111964. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  111965. for(m=0;m<VE_BANDS;m++){
  111966. char buf[80];
  111967. sprintf(buf,"delL%d",m);
  111968. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  111969. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  111970. }
  111971. for(m=0;m<VE_BANDS;m++){
  111972. char buf[80];
  111973. sprintf(buf,"delR%d",m);
  111974. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  111975. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  111976. }
  111977. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  111978. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  111979. seq++;
  111980. }
  111981. #endif
  111982. ve->curmark=j;
  111983. if(j>=testW)return(1);
  111984. return(0);
  111985. }
  111986. }
  111987. j+=ve->searchstep;
  111988. }
  111989. }
  111990. return(-1);
  111991. }
  111992. int _ve_envelope_mark(vorbis_dsp_state *v){
  111993. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  111994. vorbis_info *vi=v->vi;
  111995. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111996. long centerW=v->centerW;
  111997. long beginW=centerW-ci->blocksizes[v->W]/4;
  111998. long endW=centerW+ci->blocksizes[v->W]/4;
  111999. if(v->W){
  112000. beginW-=ci->blocksizes[v->lW]/4;
  112001. endW+=ci->blocksizes[v->nW]/4;
  112002. }else{
  112003. beginW-=ci->blocksizes[0]/4;
  112004. endW+=ci->blocksizes[0]/4;
  112005. }
  112006. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112007. {
  112008. long first=beginW/ve->searchstep;
  112009. long last=endW/ve->searchstep;
  112010. long i;
  112011. for(i=first;i<last;i++)
  112012. if(ve->mark[i])return(1);
  112013. }
  112014. return(0);
  112015. }
  112016. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112017. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112018. ahead of ve->current */
  112019. int smallshift=shift/e->searchstep;
  112020. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112021. #if 0
  112022. for(i=0;i<VE_BANDS*e->ch;i++)
  112023. memmove(e->filter[i].markers,
  112024. e->filter[i].markers+smallshift,
  112025. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112026. totalshift+=shift;
  112027. #endif
  112028. e->current-=shift;
  112029. if(e->curmark>=0)
  112030. e->curmark-=shift;
  112031. e->cursor-=shift;
  112032. }
  112033. #endif
  112034. /*** End of inlined file: envelope.c ***/
  112035. /*** Start of inlined file: floor0.c ***/
  112036. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112037. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112038. // tasks..
  112039. #if JUCE_MSVC
  112040. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112041. #endif
  112042. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112043. #if JUCE_USE_OGGVORBIS
  112044. #include <stdlib.h>
  112045. #include <string.h>
  112046. #include <math.h>
  112047. /*** Start of inlined file: lsp.h ***/
  112048. #ifndef _V_LSP_H_
  112049. #define _V_LSP_H_
  112050. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112051. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112052. float *lsp,int m,
  112053. float amp,float ampoffset);
  112054. #endif
  112055. /*** End of inlined file: lsp.h ***/
  112056. #include <stdio.h>
  112057. typedef struct {
  112058. int ln;
  112059. int m;
  112060. int **linearmap;
  112061. int n[2];
  112062. vorbis_info_floor0 *vi;
  112063. long bits;
  112064. long frames;
  112065. } vorbis_look_floor0;
  112066. /***********************************************/
  112067. static void floor0_free_info(vorbis_info_floor *i){
  112068. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112069. if(info){
  112070. memset(info,0,sizeof(*info));
  112071. _ogg_free(info);
  112072. }
  112073. }
  112074. static void floor0_free_look(vorbis_look_floor *i){
  112075. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112076. if(look){
  112077. if(look->linearmap){
  112078. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112079. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112080. _ogg_free(look->linearmap);
  112081. }
  112082. memset(look,0,sizeof(*look));
  112083. _ogg_free(look);
  112084. }
  112085. }
  112086. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112087. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112088. int j;
  112089. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112090. info->order=oggpack_read(opb,8);
  112091. info->rate=oggpack_read(opb,16);
  112092. info->barkmap=oggpack_read(opb,16);
  112093. info->ampbits=oggpack_read(opb,6);
  112094. info->ampdB=oggpack_read(opb,8);
  112095. info->numbooks=oggpack_read(opb,4)+1;
  112096. if(info->order<1)goto err_out;
  112097. if(info->rate<1)goto err_out;
  112098. if(info->barkmap<1)goto err_out;
  112099. if(info->numbooks<1)goto err_out;
  112100. for(j=0;j<info->numbooks;j++){
  112101. info->books[j]=oggpack_read(opb,8);
  112102. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112103. }
  112104. return(info);
  112105. err_out:
  112106. floor0_free_info(info);
  112107. return(NULL);
  112108. }
  112109. /* initialize Bark scale and normalization lookups. We could do this
  112110. with static tables, but Vorbis allows a number of possible
  112111. combinations, so it's best to do it computationally.
  112112. The below is authoritative in terms of defining scale mapping.
  112113. Note that the scale depends on the sampling rate as well as the
  112114. linear block and mapping sizes */
  112115. static void floor0_map_lazy_init(vorbis_block *vb,
  112116. vorbis_info_floor *infoX,
  112117. vorbis_look_floor0 *look){
  112118. if(!look->linearmap[vb->W]){
  112119. vorbis_dsp_state *vd=vb->vd;
  112120. vorbis_info *vi=vd->vi;
  112121. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112122. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112123. int W=vb->W;
  112124. int n=ci->blocksizes[W]/2,j;
  112125. /* we choose a scaling constant so that:
  112126. floor(bark(rate/2-1)*C)=mapped-1
  112127. floor(bark(rate/2)*C)=mapped */
  112128. float scale=look->ln/toBARK(info->rate/2.f);
  112129. /* the mapping from a linear scale to a smaller bark scale is
  112130. straightforward. We do *not* make sure that the linear mapping
  112131. does not skip bark-scale bins; the decoder simply skips them and
  112132. the encoder may do what it wishes in filling them. They're
  112133. necessary in some mapping combinations to keep the scale spacing
  112134. accurate */
  112135. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112136. for(j=0;j<n;j++){
  112137. int val=floor( toBARK((info->rate/2.f)/n*j)
  112138. *scale); /* bark numbers represent band edges */
  112139. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112140. look->linearmap[W][j]=val;
  112141. }
  112142. look->linearmap[W][j]=-1;
  112143. look->n[W]=n;
  112144. }
  112145. }
  112146. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112147. vorbis_info_floor *i){
  112148. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112149. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112150. look->m=info->order;
  112151. look->ln=info->barkmap;
  112152. look->vi=info;
  112153. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112154. return look;
  112155. }
  112156. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112157. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112158. vorbis_info_floor0 *info=look->vi;
  112159. int j,k;
  112160. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112161. if(ampraw>0){ /* also handles the -1 out of data case */
  112162. long maxval=(1<<info->ampbits)-1;
  112163. float amp=(float)ampraw/maxval*info->ampdB;
  112164. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112165. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112166. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112167. codebook *b=ci->fullbooks+info->books[booknum];
  112168. float last=0.f;
  112169. /* the additional b->dim is a guard against any possible stack
  112170. smash; b->dim is provably more than we can overflow the
  112171. vector */
  112172. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112173. for(j=0;j<look->m;j+=b->dim)
  112174. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112175. for(j=0;j<look->m;){
  112176. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112177. last=lsp[j-1];
  112178. }
  112179. lsp[look->m]=amp;
  112180. return(lsp);
  112181. }
  112182. }
  112183. eop:
  112184. return(NULL);
  112185. }
  112186. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112187. void *memo,float *out){
  112188. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112189. vorbis_info_floor0 *info=look->vi;
  112190. floor0_map_lazy_init(vb,info,look);
  112191. if(memo){
  112192. float *lsp=(float *)memo;
  112193. float amp=lsp[look->m];
  112194. /* take the coefficients back to a spectral envelope curve */
  112195. vorbis_lsp_to_curve(out,
  112196. look->linearmap[vb->W],
  112197. look->n[vb->W],
  112198. look->ln,
  112199. lsp,look->m,amp,(float)info->ampdB);
  112200. return(1);
  112201. }
  112202. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112203. return(0);
  112204. }
  112205. /* export hooks */
  112206. vorbis_func_floor floor0_exportbundle={
  112207. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112208. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112209. };
  112210. #endif
  112211. /*** End of inlined file: floor0.c ***/
  112212. /*** Start of inlined file: floor1.c ***/
  112213. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112214. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112215. // tasks..
  112216. #if JUCE_MSVC
  112217. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112218. #endif
  112219. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112220. #if JUCE_USE_OGGVORBIS
  112221. #include <stdlib.h>
  112222. #include <string.h>
  112223. #include <math.h>
  112224. #include <stdio.h>
  112225. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112226. typedef struct {
  112227. int sorted_index[VIF_POSIT+2];
  112228. int forward_index[VIF_POSIT+2];
  112229. int reverse_index[VIF_POSIT+2];
  112230. int hineighbor[VIF_POSIT];
  112231. int loneighbor[VIF_POSIT];
  112232. int posts;
  112233. int n;
  112234. int quant_q;
  112235. vorbis_info_floor1 *vi;
  112236. long phrasebits;
  112237. long postbits;
  112238. long frames;
  112239. } vorbis_look_floor1;
  112240. typedef struct lsfit_acc{
  112241. long x0;
  112242. long x1;
  112243. long xa;
  112244. long ya;
  112245. long x2a;
  112246. long y2a;
  112247. long xya;
  112248. long an;
  112249. } lsfit_acc;
  112250. /***********************************************/
  112251. static void floor1_free_info(vorbis_info_floor *i){
  112252. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112253. if(info){
  112254. memset(info,0,sizeof(*info));
  112255. _ogg_free(info);
  112256. }
  112257. }
  112258. static void floor1_free_look(vorbis_look_floor *i){
  112259. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112260. if(look){
  112261. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112262. (float)look->phrasebits/look->frames,
  112263. (float)look->postbits/look->frames,
  112264. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112265. memset(look,0,sizeof(*look));
  112266. _ogg_free(look);
  112267. }
  112268. }
  112269. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  112270. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112271. int j,k;
  112272. int count=0;
  112273. int rangebits;
  112274. int maxposit=info->postlist[1];
  112275. int maxclass=-1;
  112276. /* save out partitions */
  112277. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  112278. for(j=0;j<info->partitions;j++){
  112279. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  112280. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112281. }
  112282. /* save out partition classes */
  112283. for(j=0;j<maxclass+1;j++){
  112284. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  112285. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  112286. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  112287. for(k=0;k<(1<<info->class_subs[j]);k++)
  112288. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  112289. }
  112290. /* save out the post list */
  112291. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  112292. oggpack_write(opb,ilog2(maxposit),4);
  112293. rangebits=ilog2(maxposit);
  112294. for(j=0,k=0;j<info->partitions;j++){
  112295. count+=info->class_dim[info->partitionclass[j]];
  112296. for(;k<count;k++)
  112297. oggpack_write(opb,info->postlist[k+2],rangebits);
  112298. }
  112299. }
  112300. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112301. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112302. int j,k,count=0,maxclass=-1,rangebits;
  112303. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  112304. /* read partitions */
  112305. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112306. for(j=0;j<info->partitions;j++){
  112307. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112308. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112309. }
  112310. /* read partition classes */
  112311. for(j=0;j<maxclass+1;j++){
  112312. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112313. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112314. if(info->class_subs[j]<0)
  112315. goto err_out;
  112316. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112317. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112318. goto err_out;
  112319. for(k=0;k<(1<<info->class_subs[j]);k++){
  112320. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112321. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112322. goto err_out;
  112323. }
  112324. }
  112325. /* read the post list */
  112326. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112327. rangebits=oggpack_read(opb,4);
  112328. for(j=0,k=0;j<info->partitions;j++){
  112329. count+=info->class_dim[info->partitionclass[j]];
  112330. for(;k<count;k++){
  112331. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112332. if(t<0 || t>=(1<<rangebits))
  112333. goto err_out;
  112334. }
  112335. }
  112336. info->postlist[0]=0;
  112337. info->postlist[1]=1<<rangebits;
  112338. return(info);
  112339. err_out:
  112340. floor1_free_info(info);
  112341. return(NULL);
  112342. }
  112343. static int icomp(const void *a,const void *b){
  112344. return(**(int **)a-**(int **)b);
  112345. }
  112346. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112347. vorbis_info_floor *in){
  112348. int *sortpointer[VIF_POSIT+2];
  112349. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112350. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112351. int i,j,n=0;
  112352. look->vi=info;
  112353. look->n=info->postlist[1];
  112354. /* we drop each position value in-between already decoded values,
  112355. and use linear interpolation to predict each new value past the
  112356. edges. The positions are read in the order of the position
  112357. list... we precompute the bounding positions in the lookup. Of
  112358. course, the neighbors can change (if a position is declined), but
  112359. this is an initial mapping */
  112360. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112361. n+=2;
  112362. look->posts=n;
  112363. /* also store a sorted position index */
  112364. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112365. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112366. /* points from sort order back to range number */
  112367. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112368. /* points from range order to sorted position */
  112369. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112370. /* we actually need the post values too */
  112371. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  112372. /* quantize values to multiplier spec */
  112373. switch(info->mult){
  112374. case 1: /* 1024 -> 256 */
  112375. look->quant_q=256;
  112376. break;
  112377. case 2: /* 1024 -> 128 */
  112378. look->quant_q=128;
  112379. break;
  112380. case 3: /* 1024 -> 86 */
  112381. look->quant_q=86;
  112382. break;
  112383. case 4: /* 1024 -> 64 */
  112384. look->quant_q=64;
  112385. break;
  112386. }
  112387. /* discover our neighbors for decode where we don't use fit flags
  112388. (that would push the neighbors outward) */
  112389. for(i=0;i<n-2;i++){
  112390. int lo=0;
  112391. int hi=1;
  112392. int lx=0;
  112393. int hx=look->n;
  112394. int currentx=info->postlist[i+2];
  112395. for(j=0;j<i+2;j++){
  112396. int x=info->postlist[j];
  112397. if(x>lx && x<currentx){
  112398. lo=j;
  112399. lx=x;
  112400. }
  112401. if(x<hx && x>currentx){
  112402. hi=j;
  112403. hx=x;
  112404. }
  112405. }
  112406. look->loneighbor[i]=lo;
  112407. look->hineighbor[i]=hi;
  112408. }
  112409. return(look);
  112410. }
  112411. static int render_point(int x0,int x1,int y0,int y1,int x){
  112412. y0&=0x7fff; /* mask off flag */
  112413. y1&=0x7fff;
  112414. {
  112415. int dy=y1-y0;
  112416. int adx=x1-x0;
  112417. int ady=abs(dy);
  112418. int err=ady*(x-x0);
  112419. int off=err/adx;
  112420. if(dy<0)return(y0-off);
  112421. return(y0+off);
  112422. }
  112423. }
  112424. static int vorbis_dBquant(const float *x){
  112425. int i= *x*7.3142857f+1023.5f;
  112426. if(i>1023)return(1023);
  112427. if(i<0)return(0);
  112428. return i;
  112429. }
  112430. static float FLOOR1_fromdB_LOOKUP[256]={
  112431. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  112432. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  112433. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  112434. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  112435. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  112436. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  112437. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  112438. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  112439. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  112440. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  112441. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  112442. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  112443. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  112444. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  112445. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  112446. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  112447. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  112448. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  112449. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  112450. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  112451. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  112452. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  112453. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  112454. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  112455. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  112456. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  112457. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  112458. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  112459. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  112460. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  112461. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  112462. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  112463. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  112464. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  112465. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  112466. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  112467. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  112468. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  112469. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  112470. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  112471. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  112472. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  112473. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  112474. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  112475. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  112476. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  112477. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  112478. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  112479. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  112480. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  112481. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  112482. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  112483. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  112484. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  112485. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  112486. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  112487. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  112488. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  112489. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  112490. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  112491. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  112492. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  112493. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  112494. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  112495. };
  112496. static void render_line(int x0,int x1,int y0,int y1,float *d){
  112497. int dy=y1-y0;
  112498. int adx=x1-x0;
  112499. int ady=abs(dy);
  112500. int base=dy/adx;
  112501. int sy=(dy<0?base-1:base+1);
  112502. int x=x0;
  112503. int y=y0;
  112504. int err=0;
  112505. ady-=abs(base*adx);
  112506. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112507. while(++x<x1){
  112508. err=err+ady;
  112509. if(err>=adx){
  112510. err-=adx;
  112511. y+=sy;
  112512. }else{
  112513. y+=base;
  112514. }
  112515. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112516. }
  112517. }
  112518. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  112519. int dy=y1-y0;
  112520. int adx=x1-x0;
  112521. int ady=abs(dy);
  112522. int base=dy/adx;
  112523. int sy=(dy<0?base-1:base+1);
  112524. int x=x0;
  112525. int y=y0;
  112526. int err=0;
  112527. ady-=abs(base*adx);
  112528. d[x]=y;
  112529. while(++x<x1){
  112530. err=err+ady;
  112531. if(err>=adx){
  112532. err-=adx;
  112533. y+=sy;
  112534. }else{
  112535. y+=base;
  112536. }
  112537. d[x]=y;
  112538. }
  112539. }
  112540. /* the floor has already been filtered to only include relevant sections */
  112541. static int accumulate_fit(const float *flr,const float *mdct,
  112542. int x0, int x1,lsfit_acc *a,
  112543. int n,vorbis_info_floor1 *info){
  112544. long i;
  112545. 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;
  112546. memset(a,0,sizeof(*a));
  112547. a->x0=x0;
  112548. a->x1=x1;
  112549. if(x1>=n)x1=n-1;
  112550. for(i=x0;i<=x1;i++){
  112551. int quantized=vorbis_dBquant(flr+i);
  112552. if(quantized){
  112553. if(mdct[i]+info->twofitatten>=flr[i]){
  112554. xa += i;
  112555. ya += quantized;
  112556. x2a += i*i;
  112557. y2a += quantized*quantized;
  112558. xya += i*quantized;
  112559. na++;
  112560. }else{
  112561. xb += i;
  112562. yb += quantized;
  112563. x2b += i*i;
  112564. y2b += quantized*quantized;
  112565. xyb += i*quantized;
  112566. nb++;
  112567. }
  112568. }
  112569. }
  112570. xb+=xa;
  112571. yb+=ya;
  112572. x2b+=x2a;
  112573. y2b+=y2a;
  112574. xyb+=xya;
  112575. nb+=na;
  112576. /* weight toward the actually used frequencies if we meet the threshhold */
  112577. {
  112578. int weight=nb*info->twofitweight/(na+1);
  112579. a->xa=xa*weight+xb;
  112580. a->ya=ya*weight+yb;
  112581. a->x2a=x2a*weight+x2b;
  112582. a->y2a=y2a*weight+y2b;
  112583. a->xya=xya*weight+xyb;
  112584. a->an=na*weight+nb;
  112585. }
  112586. return(na);
  112587. }
  112588. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  112589. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  112590. long x0=a[0].x0;
  112591. long x1=a[fits-1].x1;
  112592. for(i=0;i<fits;i++){
  112593. x+=a[i].xa;
  112594. y+=a[i].ya;
  112595. x2+=a[i].x2a;
  112596. y2+=a[i].y2a;
  112597. xy+=a[i].xya;
  112598. an+=a[i].an;
  112599. }
  112600. if(*y0>=0){
  112601. x+= x0;
  112602. y+= *y0;
  112603. x2+= x0 * x0;
  112604. y2+= *y0 * *y0;
  112605. xy+= *y0 * x0;
  112606. an++;
  112607. }
  112608. if(*y1>=0){
  112609. x+= x1;
  112610. y+= *y1;
  112611. x2+= x1 * x1;
  112612. y2+= *y1 * *y1;
  112613. xy+= *y1 * x1;
  112614. an++;
  112615. }
  112616. if(an){
  112617. /* need 64 bit multiplies, which C doesn't give portably as int */
  112618. double fx=x;
  112619. double fy=y;
  112620. double fx2=x2;
  112621. double fxy=xy;
  112622. double denom=1./(an*fx2-fx*fx);
  112623. double a=(fy*fx2-fxy*fx)*denom;
  112624. double b=(an*fxy-fx*fy)*denom;
  112625. *y0=rint(a+b*x0);
  112626. *y1=rint(a+b*x1);
  112627. /* limit to our range! */
  112628. if(*y0>1023)*y0=1023;
  112629. if(*y1>1023)*y1=1023;
  112630. if(*y0<0)*y0=0;
  112631. if(*y1<0)*y1=0;
  112632. }else{
  112633. *y0=0;
  112634. *y1=0;
  112635. }
  112636. }
  112637. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  112638. long y=0;
  112639. int i;
  112640. for(i=0;i<fits && y==0;i++)
  112641. y+=a[i].ya;
  112642. *y0=*y1=y;
  112643. }*/
  112644. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  112645. const float *mdct,
  112646. vorbis_info_floor1 *info){
  112647. int dy=y1-y0;
  112648. int adx=x1-x0;
  112649. int ady=abs(dy);
  112650. int base=dy/adx;
  112651. int sy=(dy<0?base-1:base+1);
  112652. int x=x0;
  112653. int y=y0;
  112654. int err=0;
  112655. int val=vorbis_dBquant(mask+x);
  112656. int mse=0;
  112657. int n=0;
  112658. ady-=abs(base*adx);
  112659. mse=(y-val);
  112660. mse*=mse;
  112661. n++;
  112662. if(mdct[x]+info->twofitatten>=mask[x]){
  112663. if(y+info->maxover<val)return(1);
  112664. if(y-info->maxunder>val)return(1);
  112665. }
  112666. while(++x<x1){
  112667. err=err+ady;
  112668. if(err>=adx){
  112669. err-=adx;
  112670. y+=sy;
  112671. }else{
  112672. y+=base;
  112673. }
  112674. val=vorbis_dBquant(mask+x);
  112675. mse+=((y-val)*(y-val));
  112676. n++;
  112677. if(mdct[x]+info->twofitatten>=mask[x]){
  112678. if(val){
  112679. if(y+info->maxover<val)return(1);
  112680. if(y-info->maxunder>val)return(1);
  112681. }
  112682. }
  112683. }
  112684. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  112685. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  112686. if(mse/n>info->maxerr)return(1);
  112687. return(0);
  112688. }
  112689. static int post_Y(int *A,int *B,int pos){
  112690. if(A[pos]<0)
  112691. return B[pos];
  112692. if(B[pos]<0)
  112693. return A[pos];
  112694. return (A[pos]+B[pos])>>1;
  112695. }
  112696. int *floor1_fit(vorbis_block *vb,void *look_,
  112697. const float *logmdct, /* in */
  112698. const float *logmask){
  112699. long i,j;
  112700. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  112701. vorbis_info_floor1 *info=look->vi;
  112702. long n=look->n;
  112703. long posts=look->posts;
  112704. long nonzero=0;
  112705. lsfit_acc fits[VIF_POSIT+1];
  112706. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  112707. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  112708. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  112709. int hineighbor[VIF_POSIT+2];
  112710. int *output=NULL;
  112711. int memo[VIF_POSIT+2];
  112712. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  112713. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  112714. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  112715. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  112716. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  112717. /* quantize the relevant floor points and collect them into line fit
  112718. structures (one per minimal division) at the same time */
  112719. if(posts==0){
  112720. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  112721. }else{
  112722. for(i=0;i<posts-1;i++)
  112723. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  112724. look->sorted_index[i+1],fits+i,
  112725. n,info);
  112726. }
  112727. if(nonzero){
  112728. /* start by fitting the implicit base case.... */
  112729. int y0=-200;
  112730. int y1=-200;
  112731. fit_line(fits,posts-1,&y0,&y1);
  112732. fit_valueA[0]=y0;
  112733. fit_valueB[0]=y0;
  112734. fit_valueB[1]=y1;
  112735. fit_valueA[1]=y1;
  112736. /* Non degenerate case */
  112737. /* start progressive splitting. This is a greedy, non-optimal
  112738. algorithm, but simple and close enough to the best
  112739. answer. */
  112740. for(i=2;i<posts;i++){
  112741. int sortpos=look->reverse_index[i];
  112742. int ln=loneighbor[sortpos];
  112743. int hn=hineighbor[sortpos];
  112744. /* eliminate repeat searches of a particular range with a memo */
  112745. if(memo[ln]!=hn){
  112746. /* haven't performed this error search yet */
  112747. int lsortpos=look->reverse_index[ln];
  112748. int hsortpos=look->reverse_index[hn];
  112749. memo[ln]=hn;
  112750. {
  112751. /* A note: we want to bound/minimize *local*, not global, error */
  112752. int lx=info->postlist[ln];
  112753. int hx=info->postlist[hn];
  112754. int ly=post_Y(fit_valueA,fit_valueB,ln);
  112755. int hy=post_Y(fit_valueA,fit_valueB,hn);
  112756. if(ly==-1 || hy==-1){
  112757. exit(1);
  112758. }
  112759. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  112760. /* outside error bounds/begin search area. Split it. */
  112761. int ly0=-200;
  112762. int ly1=-200;
  112763. int hy0=-200;
  112764. int hy1=-200;
  112765. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  112766. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  112767. /* store new edge values */
  112768. fit_valueB[ln]=ly0;
  112769. if(ln==0)fit_valueA[ln]=ly0;
  112770. fit_valueA[i]=ly1;
  112771. fit_valueB[i]=hy0;
  112772. fit_valueA[hn]=hy1;
  112773. if(hn==1)fit_valueB[hn]=hy1;
  112774. if(ly1>=0 || hy0>=0){
  112775. /* store new neighbor values */
  112776. for(j=sortpos-1;j>=0;j--)
  112777. if(hineighbor[j]==hn)
  112778. hineighbor[j]=i;
  112779. else
  112780. break;
  112781. for(j=sortpos+1;j<posts;j++)
  112782. if(loneighbor[j]==ln)
  112783. loneighbor[j]=i;
  112784. else
  112785. break;
  112786. }
  112787. }else{
  112788. fit_valueA[i]=-200;
  112789. fit_valueB[i]=-200;
  112790. }
  112791. }
  112792. }
  112793. }
  112794. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  112795. output[0]=post_Y(fit_valueA,fit_valueB,0);
  112796. output[1]=post_Y(fit_valueA,fit_valueB,1);
  112797. /* fill in posts marked as not using a fit; we will zero
  112798. back out to 'unused' when encoding them so long as curve
  112799. interpolation doesn't force them into use */
  112800. for(i=2;i<posts;i++){
  112801. int ln=look->loneighbor[i-2];
  112802. int hn=look->hineighbor[i-2];
  112803. int x0=info->postlist[ln];
  112804. int x1=info->postlist[hn];
  112805. int y0=output[ln];
  112806. int y1=output[hn];
  112807. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  112808. int vx=post_Y(fit_valueA,fit_valueB,i);
  112809. if(vx>=0 && predicted!=vx){
  112810. output[i]=vx;
  112811. }else{
  112812. output[i]= predicted|0x8000;
  112813. }
  112814. }
  112815. }
  112816. return(output);
  112817. }
  112818. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  112819. int *A,int *B,
  112820. int del){
  112821. long i;
  112822. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  112823. long posts=look->posts;
  112824. int *output=NULL;
  112825. if(A && B){
  112826. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  112827. for(i=0;i<posts;i++){
  112828. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  112829. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  112830. }
  112831. }
  112832. return(output);
  112833. }
  112834. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  112835. void*look_,
  112836. int *post,int *ilogmask){
  112837. long i,j;
  112838. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  112839. vorbis_info_floor1 *info=look->vi;
  112840. long posts=look->posts;
  112841. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  112842. int out[VIF_POSIT+2];
  112843. static_codebook **sbooks=ci->book_param;
  112844. codebook *books=ci->fullbooks;
  112845. static long seq=0;
  112846. /* quantize values to multiplier spec */
  112847. if(post){
  112848. for(i=0;i<posts;i++){
  112849. int val=post[i]&0x7fff;
  112850. switch(info->mult){
  112851. case 1: /* 1024 -> 256 */
  112852. val>>=2;
  112853. break;
  112854. case 2: /* 1024 -> 128 */
  112855. val>>=3;
  112856. break;
  112857. case 3: /* 1024 -> 86 */
  112858. val/=12;
  112859. break;
  112860. case 4: /* 1024 -> 64 */
  112861. val>>=4;
  112862. break;
  112863. }
  112864. post[i]=val | (post[i]&0x8000);
  112865. }
  112866. out[0]=post[0];
  112867. out[1]=post[1];
  112868. /* find prediction values for each post and subtract them */
  112869. for(i=2;i<posts;i++){
  112870. int ln=look->loneighbor[i-2];
  112871. int hn=look->hineighbor[i-2];
  112872. int x0=info->postlist[ln];
  112873. int x1=info->postlist[hn];
  112874. int y0=post[ln];
  112875. int y1=post[hn];
  112876. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  112877. if((post[i]&0x8000) || (predicted==post[i])){
  112878. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  112879. in interpolation */
  112880. out[i]=0;
  112881. }else{
  112882. int headroom=(look->quant_q-predicted<predicted?
  112883. look->quant_q-predicted:predicted);
  112884. int val=post[i]-predicted;
  112885. /* at this point the 'deviation' value is in the range +/- max
  112886. range, but the real, unique range can always be mapped to
  112887. only [0-maxrange). So we want to wrap the deviation into
  112888. this limited range, but do it in the way that least screws
  112889. an essentially gaussian probability distribution. */
  112890. if(val<0)
  112891. if(val<-headroom)
  112892. val=headroom-val-1;
  112893. else
  112894. val=-1-(val<<1);
  112895. else
  112896. if(val>=headroom)
  112897. val= val+headroom;
  112898. else
  112899. val<<=1;
  112900. out[i]=val;
  112901. post[ln]&=0x7fff;
  112902. post[hn]&=0x7fff;
  112903. }
  112904. }
  112905. /* we have everything we need. pack it out */
  112906. /* mark nontrivial floor */
  112907. oggpack_write(opb,1,1);
  112908. /* beginning/end post */
  112909. look->frames++;
  112910. look->postbits+=ilog(look->quant_q-1)*2;
  112911. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  112912. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  112913. /* partition by partition */
  112914. for(i=0,j=2;i<info->partitions;i++){
  112915. int classx=info->partitionclass[i];
  112916. int cdim=info->class_dim[classx];
  112917. int csubbits=info->class_subs[classx];
  112918. int csub=1<<csubbits;
  112919. int bookas[8]={0,0,0,0,0,0,0,0};
  112920. int cval=0;
  112921. int cshift=0;
  112922. int k,l;
  112923. /* generate the partition's first stage cascade value */
  112924. if(csubbits){
  112925. int maxval[8];
  112926. for(k=0;k<csub;k++){
  112927. int booknum=info->class_subbook[classx][k];
  112928. if(booknum<0){
  112929. maxval[k]=1;
  112930. }else{
  112931. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  112932. }
  112933. }
  112934. for(k=0;k<cdim;k++){
  112935. for(l=0;l<csub;l++){
  112936. int val=out[j+k];
  112937. if(val<maxval[l]){
  112938. bookas[k]=l;
  112939. break;
  112940. }
  112941. }
  112942. cval|= bookas[k]<<cshift;
  112943. cshift+=csubbits;
  112944. }
  112945. /* write it */
  112946. look->phrasebits+=
  112947. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  112948. #ifdef TRAIN_FLOOR1
  112949. {
  112950. FILE *of;
  112951. char buffer[80];
  112952. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  112953. vb->pcmend/2,posts-2,class);
  112954. of=fopen(buffer,"a");
  112955. fprintf(of,"%d\n",cval);
  112956. fclose(of);
  112957. }
  112958. #endif
  112959. }
  112960. /* write post values */
  112961. for(k=0;k<cdim;k++){
  112962. int book=info->class_subbook[classx][bookas[k]];
  112963. if(book>=0){
  112964. /* hack to allow training with 'bad' books */
  112965. if(out[j+k]<(books+book)->entries)
  112966. look->postbits+=vorbis_book_encode(books+book,
  112967. out[j+k],opb);
  112968. /*else
  112969. fprintf(stderr,"+!");*/
  112970. #ifdef TRAIN_FLOOR1
  112971. {
  112972. FILE *of;
  112973. char buffer[80];
  112974. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  112975. vb->pcmend/2,posts-2,class,bookas[k]);
  112976. of=fopen(buffer,"a");
  112977. fprintf(of,"%d\n",out[j+k]);
  112978. fclose(of);
  112979. }
  112980. #endif
  112981. }
  112982. }
  112983. j+=cdim;
  112984. }
  112985. {
  112986. /* generate quantized floor equivalent to what we'd unpack in decode */
  112987. /* render the lines */
  112988. int hx=0;
  112989. int lx=0;
  112990. int ly=post[0]*info->mult;
  112991. for(j=1;j<look->posts;j++){
  112992. int current=look->forward_index[j];
  112993. int hy=post[current]&0x7fff;
  112994. if(hy==post[current]){
  112995. hy*=info->mult;
  112996. hx=info->postlist[current];
  112997. render_line0(lx,hx,ly,hy,ilogmask);
  112998. lx=hx;
  112999. ly=hy;
  113000. }
  113001. }
  113002. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113003. seq++;
  113004. return(1);
  113005. }
  113006. }else{
  113007. oggpack_write(opb,0,1);
  113008. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113009. seq++;
  113010. return(0);
  113011. }
  113012. }
  113013. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113014. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113015. vorbis_info_floor1 *info=look->vi;
  113016. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113017. int i,j,k;
  113018. codebook *books=ci->fullbooks;
  113019. /* unpack wrapped/predicted values from stream */
  113020. if(oggpack_read(&vb->opb,1)==1){
  113021. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113022. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113023. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113024. /* partition by partition */
  113025. for(i=0,j=2;i<info->partitions;i++){
  113026. int classx=info->partitionclass[i];
  113027. int cdim=info->class_dim[classx];
  113028. int csubbits=info->class_subs[classx];
  113029. int csub=1<<csubbits;
  113030. int cval=0;
  113031. /* decode the partition's first stage cascade value */
  113032. if(csubbits){
  113033. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113034. if(cval==-1)goto eop;
  113035. }
  113036. for(k=0;k<cdim;k++){
  113037. int book=info->class_subbook[classx][cval&(csub-1)];
  113038. cval>>=csubbits;
  113039. if(book>=0){
  113040. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113041. goto eop;
  113042. }else{
  113043. fit_value[j+k]=0;
  113044. }
  113045. }
  113046. j+=cdim;
  113047. }
  113048. /* unwrap positive values and reconsitute via linear interpolation */
  113049. for(i=2;i<look->posts;i++){
  113050. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113051. info->postlist[look->hineighbor[i-2]],
  113052. fit_value[look->loneighbor[i-2]],
  113053. fit_value[look->hineighbor[i-2]],
  113054. info->postlist[i]);
  113055. int hiroom=look->quant_q-predicted;
  113056. int loroom=predicted;
  113057. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113058. int val=fit_value[i];
  113059. if(val){
  113060. if(val>=room){
  113061. if(hiroom>loroom){
  113062. val = val-loroom;
  113063. }else{
  113064. val = -1-(val-hiroom);
  113065. }
  113066. }else{
  113067. if(val&1){
  113068. val= -((val+1)>>1);
  113069. }else{
  113070. val>>=1;
  113071. }
  113072. }
  113073. fit_value[i]=val+predicted;
  113074. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113075. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113076. }else{
  113077. fit_value[i]=predicted|0x8000;
  113078. }
  113079. }
  113080. return(fit_value);
  113081. }
  113082. eop:
  113083. return(NULL);
  113084. }
  113085. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113086. float *out){
  113087. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113088. vorbis_info_floor1 *info=look->vi;
  113089. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113090. int n=ci->blocksizes[vb->W]/2;
  113091. int j;
  113092. if(memo){
  113093. /* render the lines */
  113094. int *fit_value=(int *)memo;
  113095. int hx=0;
  113096. int lx=0;
  113097. int ly=fit_value[0]*info->mult;
  113098. for(j=1;j<look->posts;j++){
  113099. int current=look->forward_index[j];
  113100. int hy=fit_value[current]&0x7fff;
  113101. if(hy==fit_value[current]){
  113102. hy*=info->mult;
  113103. hx=info->postlist[current];
  113104. render_line(lx,hx,ly,hy,out);
  113105. lx=hx;
  113106. ly=hy;
  113107. }
  113108. }
  113109. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113110. return(1);
  113111. }
  113112. memset(out,0,sizeof(*out)*n);
  113113. return(0);
  113114. }
  113115. /* export hooks */
  113116. vorbis_func_floor floor1_exportbundle={
  113117. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113118. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113119. };
  113120. #endif
  113121. /*** End of inlined file: floor1.c ***/
  113122. /*** Start of inlined file: info.c ***/
  113123. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113124. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113125. // tasks..
  113126. #if JUCE_MSVC
  113127. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113128. #endif
  113129. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113130. #if JUCE_USE_OGGVORBIS
  113131. /* general handling of the header and the vorbis_info structure (and
  113132. substructures) */
  113133. #include <stdlib.h>
  113134. #include <string.h>
  113135. #include <ctype.h>
  113136. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113137. while(bytes--){
  113138. oggpack_write(o,*s++,8);
  113139. }
  113140. }
  113141. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113142. while(bytes--){
  113143. *buf++=oggpack_read(o,8);
  113144. }
  113145. }
  113146. void vorbis_comment_init(vorbis_comment *vc){
  113147. memset(vc,0,sizeof(*vc));
  113148. }
  113149. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113150. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113151. (vc->comments+2)*sizeof(*vc->user_comments));
  113152. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113153. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113154. vc->comment_lengths[vc->comments]=strlen(comment);
  113155. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113156. strcpy(vc->user_comments[vc->comments], comment);
  113157. vc->comments++;
  113158. vc->user_comments[vc->comments]=NULL;
  113159. }
  113160. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113161. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113162. strcpy(comment, tag);
  113163. strcat(comment, "=");
  113164. strcat(comment, contents);
  113165. vorbis_comment_add(vc, comment);
  113166. }
  113167. /* This is more or less the same as strncasecmp - but that doesn't exist
  113168. * everywhere, and this is a fairly trivial function, so we include it */
  113169. static int tagcompare(const char *s1, const char *s2, int n){
  113170. int c=0;
  113171. while(c < n){
  113172. if(toupper(s1[c]) != toupper(s2[c]))
  113173. return !0;
  113174. c++;
  113175. }
  113176. return 0;
  113177. }
  113178. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113179. long i;
  113180. int found = 0;
  113181. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113182. char *fulltag = (char*)alloca(taglen+ 1);
  113183. strcpy(fulltag, tag);
  113184. strcat(fulltag, "=");
  113185. for(i=0;i<vc->comments;i++){
  113186. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113187. if(count == found)
  113188. /* We return a pointer to the data, not a copy */
  113189. return vc->user_comments[i] + taglen;
  113190. else
  113191. found++;
  113192. }
  113193. }
  113194. return NULL; /* didn't find anything */
  113195. }
  113196. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113197. int i,count=0;
  113198. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113199. char *fulltag = (char*)alloca(taglen+1);
  113200. strcpy(fulltag,tag);
  113201. strcat(fulltag, "=");
  113202. for(i=0;i<vc->comments;i++){
  113203. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113204. count++;
  113205. }
  113206. return count;
  113207. }
  113208. void vorbis_comment_clear(vorbis_comment *vc){
  113209. if(vc){
  113210. long i;
  113211. for(i=0;i<vc->comments;i++)
  113212. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113213. if(vc->user_comments)_ogg_free(vc->user_comments);
  113214. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113215. if(vc->vendor)_ogg_free(vc->vendor);
  113216. }
  113217. memset(vc,0,sizeof(*vc));
  113218. }
  113219. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113220. They may be equal, but short will never ge greater than long */
  113221. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113222. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113223. return ci ? ci->blocksizes[zo] : -1;
  113224. }
  113225. /* used by synthesis, which has a full, alloced vi */
  113226. void vorbis_info_init(vorbis_info *vi){
  113227. memset(vi,0,sizeof(*vi));
  113228. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113229. }
  113230. void vorbis_info_clear(vorbis_info *vi){
  113231. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113232. int i;
  113233. if(ci){
  113234. for(i=0;i<ci->modes;i++)
  113235. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113236. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113237. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113238. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113239. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113240. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113241. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113242. for(i=0;i<ci->books;i++){
  113243. if(ci->book_param[i]){
  113244. /* knows if the book was not alloced */
  113245. vorbis_staticbook_destroy(ci->book_param[i]);
  113246. }
  113247. if(ci->fullbooks)
  113248. vorbis_book_clear(ci->fullbooks+i);
  113249. }
  113250. if(ci->fullbooks)
  113251. _ogg_free(ci->fullbooks);
  113252. for(i=0;i<ci->psys;i++)
  113253. _vi_psy_free(ci->psy_param[i]);
  113254. _ogg_free(ci);
  113255. }
  113256. memset(vi,0,sizeof(*vi));
  113257. }
  113258. /* Header packing/unpacking ********************************************/
  113259. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113260. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113261. if(!ci)return(OV_EFAULT);
  113262. vi->version=oggpack_read(opb,32);
  113263. if(vi->version!=0)return(OV_EVERSION);
  113264. vi->channels=oggpack_read(opb,8);
  113265. vi->rate=oggpack_read(opb,32);
  113266. vi->bitrate_upper=oggpack_read(opb,32);
  113267. vi->bitrate_nominal=oggpack_read(opb,32);
  113268. vi->bitrate_lower=oggpack_read(opb,32);
  113269. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  113270. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  113271. if(vi->rate<1)goto err_out;
  113272. if(vi->channels<1)goto err_out;
  113273. if(ci->blocksizes[0]<8)goto err_out;
  113274. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  113275. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113276. return(0);
  113277. err_out:
  113278. vorbis_info_clear(vi);
  113279. return(OV_EBADHEADER);
  113280. }
  113281. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  113282. int i;
  113283. int vendorlen=oggpack_read(opb,32);
  113284. if(vendorlen<0)goto err_out;
  113285. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  113286. _v_readstring(opb,vc->vendor,vendorlen);
  113287. vc->comments=oggpack_read(opb,32);
  113288. if(vc->comments<0)goto err_out;
  113289. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  113290. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  113291. for(i=0;i<vc->comments;i++){
  113292. int len=oggpack_read(opb,32);
  113293. if(len<0)goto err_out;
  113294. vc->comment_lengths[i]=len;
  113295. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  113296. _v_readstring(opb,vc->user_comments[i],len);
  113297. }
  113298. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113299. return(0);
  113300. err_out:
  113301. vorbis_comment_clear(vc);
  113302. return(OV_EBADHEADER);
  113303. }
  113304. /* all of the real encoding details are here. The modes, books,
  113305. everything */
  113306. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113307. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113308. int i;
  113309. if(!ci)return(OV_EFAULT);
  113310. /* codebooks */
  113311. ci->books=oggpack_read(opb,8)+1;
  113312. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113313. for(i=0;i<ci->books;i++){
  113314. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113315. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113316. }
  113317. /* time backend settings; hooks are unused */
  113318. {
  113319. int times=oggpack_read(opb,6)+1;
  113320. for(i=0;i<times;i++){
  113321. int test=oggpack_read(opb,16);
  113322. if(test<0 || test>=VI_TIMEB)goto err_out;
  113323. }
  113324. }
  113325. /* floor backend settings */
  113326. ci->floors=oggpack_read(opb,6)+1;
  113327. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113328. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113329. for(i=0;i<ci->floors;i++){
  113330. ci->floor_type[i]=oggpack_read(opb,16);
  113331. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113332. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113333. if(!ci->floor_param[i])goto err_out;
  113334. }
  113335. /* residue backend settings */
  113336. ci->residues=oggpack_read(opb,6)+1;
  113337. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113338. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113339. for(i=0;i<ci->residues;i++){
  113340. ci->residue_type[i]=oggpack_read(opb,16);
  113341. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113342. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113343. if(!ci->residue_param[i])goto err_out;
  113344. }
  113345. /* map backend settings */
  113346. ci->maps=oggpack_read(opb,6)+1;
  113347. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113348. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113349. for(i=0;i<ci->maps;i++){
  113350. ci->map_type[i]=oggpack_read(opb,16);
  113351. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113352. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113353. if(!ci->map_param[i])goto err_out;
  113354. }
  113355. /* mode settings */
  113356. ci->modes=oggpack_read(opb,6)+1;
  113357. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113358. for(i=0;i<ci->modes;i++){
  113359. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113360. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113361. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113362. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113363. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113364. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113365. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113366. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113367. }
  113368. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113369. return(0);
  113370. err_out:
  113371. vorbis_info_clear(vi);
  113372. return(OV_EBADHEADER);
  113373. }
  113374. /* The Vorbis header is in three packets; the initial small packet in
  113375. the first page that identifies basic parameters, a second packet
  113376. with bitstream comments and a third packet that holds the
  113377. codebook. */
  113378. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  113379. oggpack_buffer opb;
  113380. if(op){
  113381. oggpack_readinit(&opb,op->packet,op->bytes);
  113382. /* Which of the three types of header is this? */
  113383. /* Also verify header-ness, vorbis */
  113384. {
  113385. char buffer[6];
  113386. int packtype=oggpack_read(&opb,8);
  113387. memset(buffer,0,6);
  113388. _v_readstring(&opb,buffer,6);
  113389. if(memcmp(buffer,"vorbis",6)){
  113390. /* not a vorbis header */
  113391. return(OV_ENOTVORBIS);
  113392. }
  113393. switch(packtype){
  113394. case 0x01: /* least significant *bit* is read first */
  113395. if(!op->b_o_s){
  113396. /* Not the initial packet */
  113397. return(OV_EBADHEADER);
  113398. }
  113399. if(vi->rate!=0){
  113400. /* previously initialized info header */
  113401. return(OV_EBADHEADER);
  113402. }
  113403. return(_vorbis_unpack_info(vi,&opb));
  113404. case 0x03: /* least significant *bit* is read first */
  113405. if(vi->rate==0){
  113406. /* um... we didn't get the initial header */
  113407. return(OV_EBADHEADER);
  113408. }
  113409. return(_vorbis_unpack_comment(vc,&opb));
  113410. case 0x05: /* least significant *bit* is read first */
  113411. if(vi->rate==0 || vc->vendor==NULL){
  113412. /* um... we didn;t get the initial header or comments yet */
  113413. return(OV_EBADHEADER);
  113414. }
  113415. return(_vorbis_unpack_books(vi,&opb));
  113416. default:
  113417. /* Not a valid vorbis header type */
  113418. return(OV_EBADHEADER);
  113419. break;
  113420. }
  113421. }
  113422. }
  113423. return(OV_EBADHEADER);
  113424. }
  113425. /* pack side **********************************************************/
  113426. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  113427. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113428. if(!ci)return(OV_EFAULT);
  113429. /* preamble */
  113430. oggpack_write(opb,0x01,8);
  113431. _v_writestring(opb,"vorbis", 6);
  113432. /* basic information about the stream */
  113433. oggpack_write(opb,0x00,32);
  113434. oggpack_write(opb,vi->channels,8);
  113435. oggpack_write(opb,vi->rate,32);
  113436. oggpack_write(opb,vi->bitrate_upper,32);
  113437. oggpack_write(opb,vi->bitrate_nominal,32);
  113438. oggpack_write(opb,vi->bitrate_lower,32);
  113439. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  113440. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  113441. oggpack_write(opb,1,1);
  113442. return(0);
  113443. }
  113444. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  113445. char temp[]="Xiph.Org libVorbis I 20050304";
  113446. int bytes = strlen(temp);
  113447. /* preamble */
  113448. oggpack_write(opb,0x03,8);
  113449. _v_writestring(opb,"vorbis", 6);
  113450. /* vendor */
  113451. oggpack_write(opb,bytes,32);
  113452. _v_writestring(opb,temp, bytes);
  113453. /* comments */
  113454. oggpack_write(opb,vc->comments,32);
  113455. if(vc->comments){
  113456. int i;
  113457. for(i=0;i<vc->comments;i++){
  113458. if(vc->user_comments[i]){
  113459. oggpack_write(opb,vc->comment_lengths[i],32);
  113460. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  113461. }else{
  113462. oggpack_write(opb,0,32);
  113463. }
  113464. }
  113465. }
  113466. oggpack_write(opb,1,1);
  113467. return(0);
  113468. }
  113469. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  113470. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113471. int i;
  113472. if(!ci)return(OV_EFAULT);
  113473. oggpack_write(opb,0x05,8);
  113474. _v_writestring(opb,"vorbis", 6);
  113475. /* books */
  113476. oggpack_write(opb,ci->books-1,8);
  113477. for(i=0;i<ci->books;i++)
  113478. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  113479. /* times; hook placeholders */
  113480. oggpack_write(opb,0,6);
  113481. oggpack_write(opb,0,16);
  113482. /* floors */
  113483. oggpack_write(opb,ci->floors-1,6);
  113484. for(i=0;i<ci->floors;i++){
  113485. oggpack_write(opb,ci->floor_type[i],16);
  113486. if(_floor_P[ci->floor_type[i]]->pack)
  113487. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  113488. else
  113489. goto err_out;
  113490. }
  113491. /* residues */
  113492. oggpack_write(opb,ci->residues-1,6);
  113493. for(i=0;i<ci->residues;i++){
  113494. oggpack_write(opb,ci->residue_type[i],16);
  113495. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  113496. }
  113497. /* maps */
  113498. oggpack_write(opb,ci->maps-1,6);
  113499. for(i=0;i<ci->maps;i++){
  113500. oggpack_write(opb,ci->map_type[i],16);
  113501. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  113502. }
  113503. /* modes */
  113504. oggpack_write(opb,ci->modes-1,6);
  113505. for(i=0;i<ci->modes;i++){
  113506. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  113507. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  113508. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  113509. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  113510. }
  113511. oggpack_write(opb,1,1);
  113512. return(0);
  113513. err_out:
  113514. return(-1);
  113515. }
  113516. int vorbis_commentheader_out(vorbis_comment *vc,
  113517. ogg_packet *op){
  113518. oggpack_buffer opb;
  113519. oggpack_writeinit(&opb);
  113520. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  113521. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113522. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  113523. op->bytes=oggpack_bytes(&opb);
  113524. op->b_o_s=0;
  113525. op->e_o_s=0;
  113526. op->granulepos=0;
  113527. op->packetno=1;
  113528. return 0;
  113529. }
  113530. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  113531. vorbis_comment *vc,
  113532. ogg_packet *op,
  113533. ogg_packet *op_comm,
  113534. ogg_packet *op_code){
  113535. int ret=OV_EIMPL;
  113536. vorbis_info *vi=v->vi;
  113537. oggpack_buffer opb;
  113538. private_state *b=(private_state*)v->backend_state;
  113539. if(!b){
  113540. ret=OV_EFAULT;
  113541. goto err_out;
  113542. }
  113543. /* first header packet **********************************************/
  113544. oggpack_writeinit(&opb);
  113545. if(_vorbis_pack_info(&opb,vi))goto err_out;
  113546. /* build the packet */
  113547. if(b->header)_ogg_free(b->header);
  113548. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113549. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  113550. op->packet=b->header;
  113551. op->bytes=oggpack_bytes(&opb);
  113552. op->b_o_s=1;
  113553. op->e_o_s=0;
  113554. op->granulepos=0;
  113555. op->packetno=0;
  113556. /* second header packet (comments) **********************************/
  113557. oggpack_reset(&opb);
  113558. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  113559. if(b->header1)_ogg_free(b->header1);
  113560. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113561. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  113562. op_comm->packet=b->header1;
  113563. op_comm->bytes=oggpack_bytes(&opb);
  113564. op_comm->b_o_s=0;
  113565. op_comm->e_o_s=0;
  113566. op_comm->granulepos=0;
  113567. op_comm->packetno=1;
  113568. /* third header packet (modes/codebooks) ****************************/
  113569. oggpack_reset(&opb);
  113570. if(_vorbis_pack_books(&opb,vi))goto err_out;
  113571. if(b->header2)_ogg_free(b->header2);
  113572. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113573. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  113574. op_code->packet=b->header2;
  113575. op_code->bytes=oggpack_bytes(&opb);
  113576. op_code->b_o_s=0;
  113577. op_code->e_o_s=0;
  113578. op_code->granulepos=0;
  113579. op_code->packetno=2;
  113580. oggpack_writeclear(&opb);
  113581. return(0);
  113582. err_out:
  113583. oggpack_writeclear(&opb);
  113584. memset(op,0,sizeof(*op));
  113585. memset(op_comm,0,sizeof(*op_comm));
  113586. memset(op_code,0,sizeof(*op_code));
  113587. if(b->header)_ogg_free(b->header);
  113588. if(b->header1)_ogg_free(b->header1);
  113589. if(b->header2)_ogg_free(b->header2);
  113590. b->header=NULL;
  113591. b->header1=NULL;
  113592. b->header2=NULL;
  113593. return(ret);
  113594. }
  113595. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  113596. if(granulepos>=0)
  113597. return((double)granulepos/v->vi->rate);
  113598. return(-1);
  113599. }
  113600. #endif
  113601. /*** End of inlined file: info.c ***/
  113602. /*** Start of inlined file: lpc.c ***/
  113603. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  113604. are derived from code written by Jutta Degener and Carsten Bormann;
  113605. thus we include their copyright below. The entirety of this file
  113606. is freely redistributable on the condition that both of these
  113607. copyright notices are preserved without modification. */
  113608. /* Preserved Copyright: *********************************************/
  113609. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  113610. Technische Universita"t Berlin
  113611. Any use of this software is permitted provided that this notice is not
  113612. removed and that neither the authors nor the Technische Universita"t
  113613. Berlin are deemed to have made any representations as to the
  113614. suitability of this software for any purpose nor are held responsible
  113615. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  113616. THIS SOFTWARE.
  113617. As a matter of courtesy, the authors request to be informed about uses
  113618. this software has found, about bugs in this software, and about any
  113619. improvements that may be of general interest.
  113620. Berlin, 28.11.1994
  113621. Jutta Degener
  113622. Carsten Bormann
  113623. *********************************************************************/
  113624. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113625. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113626. // tasks..
  113627. #if JUCE_MSVC
  113628. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113629. #endif
  113630. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113631. #if JUCE_USE_OGGVORBIS
  113632. #include <stdlib.h>
  113633. #include <string.h>
  113634. #include <math.h>
  113635. /* Autocorrelation LPC coeff generation algorithm invented by
  113636. N. Levinson in 1947, modified by J. Durbin in 1959. */
  113637. /* Input : n elements of time doamin data
  113638. Output: m lpc coefficients, excitation energy */
  113639. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  113640. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  113641. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  113642. double error;
  113643. int i,j;
  113644. /* autocorrelation, p+1 lag coefficients */
  113645. j=m+1;
  113646. while(j--){
  113647. double d=0; /* double needed for accumulator depth */
  113648. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  113649. aut[j]=d;
  113650. }
  113651. /* Generate lpc coefficients from autocorr values */
  113652. error=aut[0];
  113653. for(i=0;i<m;i++){
  113654. double r= -aut[i+1];
  113655. if(error==0){
  113656. memset(lpci,0,m*sizeof(*lpci));
  113657. return 0;
  113658. }
  113659. /* Sum up this iteration's reflection coefficient; note that in
  113660. Vorbis we don't save it. If anyone wants to recycle this code
  113661. and needs reflection coefficients, save the results of 'r' from
  113662. each iteration. */
  113663. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  113664. r/=error;
  113665. /* Update LPC coefficients and total error */
  113666. lpc[i]=r;
  113667. for(j=0;j<i/2;j++){
  113668. double tmp=lpc[j];
  113669. lpc[j]+=r*lpc[i-1-j];
  113670. lpc[i-1-j]+=r*tmp;
  113671. }
  113672. if(i%2)lpc[j]+=lpc[j]*r;
  113673. error*=1.f-r*r;
  113674. }
  113675. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  113676. /* we need the error value to know how big an impulse to hit the
  113677. filter with later */
  113678. return error;
  113679. }
  113680. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  113681. float *data,long n){
  113682. /* in: coeff[0...m-1] LPC coefficients
  113683. prime[0...m-1] initial values (allocated size of n+m-1)
  113684. out: data[0...n-1] data samples */
  113685. long i,j,o,p;
  113686. float y;
  113687. float *work=(float*)alloca(sizeof(*work)*(m+n));
  113688. if(!prime)
  113689. for(i=0;i<m;i++)
  113690. work[i]=0.f;
  113691. else
  113692. for(i=0;i<m;i++)
  113693. work[i]=prime[i];
  113694. for(i=0;i<n;i++){
  113695. y=0;
  113696. o=i;
  113697. p=m;
  113698. for(j=0;j<m;j++)
  113699. y-=work[o++]*coeff[--p];
  113700. data[i]=work[o]=y;
  113701. }
  113702. }
  113703. #endif
  113704. /*** End of inlined file: lpc.c ***/
  113705. /*** Start of inlined file: lsp.c ***/
  113706. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  113707. an iterative root polisher (CACM algorithm 283). It *is* possible
  113708. to confuse this algorithm into not converging; that should only
  113709. happen with absurdly closely spaced roots (very sharp peaks in the
  113710. LPC f response) which in turn should be impossible in our use of
  113711. the code. If this *does* happen anyway, it's a bug in the floor
  113712. finder; find the cause of the confusion (probably a single bin
  113713. spike or accidental near-float-limit resolution problems) and
  113714. correct it. */
  113715. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113716. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113717. // tasks..
  113718. #if JUCE_MSVC
  113719. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113720. #endif
  113721. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113722. #if JUCE_USE_OGGVORBIS
  113723. #include <math.h>
  113724. #include <string.h>
  113725. #include <stdlib.h>
  113726. /*** Start of inlined file: lookup.h ***/
  113727. #ifndef _V_LOOKUP_H_
  113728. #ifdef FLOAT_LOOKUP
  113729. extern float vorbis_coslook(float a);
  113730. extern float vorbis_invsqlook(float a);
  113731. extern float vorbis_invsq2explook(int a);
  113732. extern float vorbis_fromdBlook(float a);
  113733. #endif
  113734. #ifdef INT_LOOKUP
  113735. extern long vorbis_invsqlook_i(long a,long e);
  113736. extern long vorbis_coslook_i(long a);
  113737. extern float vorbis_fromdBlook_i(long a);
  113738. #endif
  113739. #endif
  113740. /*** End of inlined file: lookup.h ***/
  113741. /* three possible LSP to f curve functions; the exact computation
  113742. (float), a lookup based float implementation, and an integer
  113743. implementation. The float lookup is likely the optimal choice on
  113744. any machine with an FPU. The integer implementation is *not* fixed
  113745. point (due to the need for a large dynamic range and thus a
  113746. seperately tracked exponent) and thus much more complex than the
  113747. relatively simple float implementations. It's mostly for future
  113748. work on a fully fixed point implementation for processors like the
  113749. ARM family. */
  113750. /* undefine both for the 'old' but more precise implementation */
  113751. #define FLOAT_LOOKUP
  113752. #undef INT_LOOKUP
  113753. #ifdef FLOAT_LOOKUP
  113754. /*** Start of inlined file: lookup.c ***/
  113755. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113756. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113757. // tasks..
  113758. #if JUCE_MSVC
  113759. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113760. #endif
  113761. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113762. #if JUCE_USE_OGGVORBIS
  113763. #include <math.h>
  113764. /*** Start of inlined file: lookup.h ***/
  113765. #ifndef _V_LOOKUP_H_
  113766. #ifdef FLOAT_LOOKUP
  113767. extern float vorbis_coslook(float a);
  113768. extern float vorbis_invsqlook(float a);
  113769. extern float vorbis_invsq2explook(int a);
  113770. extern float vorbis_fromdBlook(float a);
  113771. #endif
  113772. #ifdef INT_LOOKUP
  113773. extern long vorbis_invsqlook_i(long a,long e);
  113774. extern long vorbis_coslook_i(long a);
  113775. extern float vorbis_fromdBlook_i(long a);
  113776. #endif
  113777. #endif
  113778. /*** End of inlined file: lookup.h ***/
  113779. /*** Start of inlined file: lookup_data.h ***/
  113780. #ifndef _V_LOOKUP_DATA_H_
  113781. #ifdef FLOAT_LOOKUP
  113782. #define COS_LOOKUP_SZ 128
  113783. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  113784. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  113785. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  113786. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  113787. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  113788. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  113789. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  113790. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  113791. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  113792. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  113793. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  113794. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  113795. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  113796. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  113797. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  113798. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  113799. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  113800. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  113801. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  113802. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  113803. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  113804. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  113805. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  113806. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  113807. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  113808. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  113809. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  113810. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  113811. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  113812. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  113813. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  113814. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  113815. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  113816. -1.0000000000000f,
  113817. };
  113818. #define INVSQ_LOOKUP_SZ 32
  113819. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  113820. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  113821. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  113822. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  113823. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  113824. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  113825. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  113826. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  113827. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  113828. 1.000000000000f,
  113829. };
  113830. #define INVSQ2EXP_LOOKUP_MIN (-32)
  113831. #define INVSQ2EXP_LOOKUP_MAX 32
  113832. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  113833. INVSQ2EXP_LOOKUP_MIN+1]={
  113834. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  113835. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  113836. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  113837. 1024.f, 724.0773439f, 512.f, 362.038672f,
  113838. 256.f, 181.019336f, 128.f, 90.50966799f,
  113839. 64.f, 45.254834f, 32.f, 22.627417f,
  113840. 16.f, 11.3137085f, 8.f, 5.656854249f,
  113841. 4.f, 2.828427125f, 2.f, 1.414213562f,
  113842. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  113843. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  113844. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  113845. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  113846. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  113847. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  113848. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  113849. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  113850. 1.525878906e-05f,
  113851. };
  113852. #endif
  113853. #define FROMdB_LOOKUP_SZ 35
  113854. #define FROMdB2_LOOKUP_SZ 32
  113855. #define FROMdB_SHIFT 5
  113856. #define FROMdB2_SHIFT 3
  113857. #define FROMdB2_MASK 31
  113858. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  113859. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  113860. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  113861. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  113862. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  113863. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  113864. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  113865. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  113866. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  113867. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  113868. };
  113869. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  113870. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  113871. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  113872. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  113873. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  113874. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  113875. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  113876. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  113877. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  113878. };
  113879. #ifdef INT_LOOKUP
  113880. #define INVSQ_LOOKUP_I_SHIFT 10
  113881. #define INVSQ_LOOKUP_I_MASK 1023
  113882. static long INVSQ_LOOKUP_I[64+1]={
  113883. 92682l, 91966l, 91267l, 90583l,
  113884. 89915l, 89261l, 88621l, 87995l,
  113885. 87381l, 86781l, 86192l, 85616l,
  113886. 85051l, 84497l, 83953l, 83420l,
  113887. 82897l, 82384l, 81880l, 81385l,
  113888. 80899l, 80422l, 79953l, 79492l,
  113889. 79039l, 78594l, 78156l, 77726l,
  113890. 77302l, 76885l, 76475l, 76072l,
  113891. 75674l, 75283l, 74898l, 74519l,
  113892. 74146l, 73778l, 73415l, 73058l,
  113893. 72706l, 72359l, 72016l, 71679l,
  113894. 71347l, 71019l, 70695l, 70376l,
  113895. 70061l, 69750l, 69444l, 69141l,
  113896. 68842l, 68548l, 68256l, 67969l,
  113897. 67685l, 67405l, 67128l, 66855l,
  113898. 66585l, 66318l, 66054l, 65794l,
  113899. 65536l,
  113900. };
  113901. #define COS_LOOKUP_I_SHIFT 9
  113902. #define COS_LOOKUP_I_MASK 511
  113903. #define COS_LOOKUP_I_SZ 128
  113904. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  113905. 16384l, 16379l, 16364l, 16340l,
  113906. 16305l, 16261l, 16207l, 16143l,
  113907. 16069l, 15986l, 15893l, 15791l,
  113908. 15679l, 15557l, 15426l, 15286l,
  113909. 15137l, 14978l, 14811l, 14635l,
  113910. 14449l, 14256l, 14053l, 13842l,
  113911. 13623l, 13395l, 13160l, 12916l,
  113912. 12665l, 12406l, 12140l, 11866l,
  113913. 11585l, 11297l, 11003l, 10702l,
  113914. 10394l, 10080l, 9760l, 9434l,
  113915. 9102l, 8765l, 8423l, 8076l,
  113916. 7723l, 7366l, 7005l, 6639l,
  113917. 6270l, 5897l, 5520l, 5139l,
  113918. 4756l, 4370l, 3981l, 3590l,
  113919. 3196l, 2801l, 2404l, 2006l,
  113920. 1606l, 1205l, 804l, 402l,
  113921. 0l, -401l, -803l, -1204l,
  113922. -1605l, -2005l, -2403l, -2800l,
  113923. -3195l, -3589l, -3980l, -4369l,
  113924. -4755l, -5138l, -5519l, -5896l,
  113925. -6269l, -6638l, -7004l, -7365l,
  113926. -7722l, -8075l, -8422l, -8764l,
  113927. -9101l, -9433l, -9759l, -10079l,
  113928. -10393l, -10701l, -11002l, -11296l,
  113929. -11584l, -11865l, -12139l, -12405l,
  113930. -12664l, -12915l, -13159l, -13394l,
  113931. -13622l, -13841l, -14052l, -14255l,
  113932. -14448l, -14634l, -14810l, -14977l,
  113933. -15136l, -15285l, -15425l, -15556l,
  113934. -15678l, -15790l, -15892l, -15985l,
  113935. -16068l, -16142l, -16206l, -16260l,
  113936. -16304l, -16339l, -16363l, -16378l,
  113937. -16383l,
  113938. };
  113939. #endif
  113940. #endif
  113941. /*** End of inlined file: lookup_data.h ***/
  113942. #ifdef FLOAT_LOOKUP
  113943. /* interpolated lookup based cos function, domain 0 to PI only */
  113944. float vorbis_coslook(float a){
  113945. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  113946. int i=vorbis_ftoi(d-.5);
  113947. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  113948. }
  113949. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113950. float vorbis_invsqlook(float a){
  113951. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  113952. int i=vorbis_ftoi(d-.5f);
  113953. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  113954. }
  113955. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113956. float vorbis_invsq2explook(int a){
  113957. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  113958. }
  113959. #include <stdio.h>
  113960. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113961. float vorbis_fromdBlook(float a){
  113962. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  113963. return (i<0)?1.f:
  113964. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113965. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113966. }
  113967. #endif
  113968. #ifdef INT_LOOKUP
  113969. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  113970. 16.16 format
  113971. returns in m.8 format */
  113972. long vorbis_invsqlook_i(long a,long e){
  113973. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  113974. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  113975. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  113976. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  113977. d)>>16); /* result 1.16 */
  113978. e+=32;
  113979. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  113980. e=(e>>1)-8;
  113981. return(val>>e);
  113982. }
  113983. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113984. /* a is in n.12 format */
  113985. float vorbis_fromdBlook_i(long a){
  113986. int i=(-a)>>(12-FROMdB2_SHIFT);
  113987. return (i<0)?1.f:
  113988. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113989. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113990. }
  113991. /* interpolated lookup based cos function, domain 0 to PI only */
  113992. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  113993. long vorbis_coslook_i(long a){
  113994. int i=a>>COS_LOOKUP_I_SHIFT;
  113995. int d=a&COS_LOOKUP_I_MASK;
  113996. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  113997. COS_LOOKUP_I_SHIFT);
  113998. }
  113999. #endif
  114000. #endif
  114001. /*** End of inlined file: lookup.c ***/
  114002. /* catch this in the build system; we #include for
  114003. compilers (like gcc) that can't inline across
  114004. modules */
  114005. /* side effect: changes *lsp to cosines of lsp */
  114006. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114007. float amp,float ampoffset){
  114008. int i;
  114009. float wdel=M_PI/ln;
  114010. vorbis_fpu_control fpu;
  114011. (void) fpu; // to avoid an unused variable warning
  114012. vorbis_fpu_setround(&fpu);
  114013. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114014. i=0;
  114015. while(i<n){
  114016. int k=map[i];
  114017. int qexp;
  114018. float p=.7071067812f;
  114019. float q=.7071067812f;
  114020. float w=vorbis_coslook(wdel*k);
  114021. float *ftmp=lsp;
  114022. int c=m>>1;
  114023. do{
  114024. q*=ftmp[0]-w;
  114025. p*=ftmp[1]-w;
  114026. ftmp+=2;
  114027. }while(--c);
  114028. if(m&1){
  114029. /* odd order filter; slightly assymetric */
  114030. /* the last coefficient */
  114031. q*=ftmp[0]-w;
  114032. q*=q;
  114033. p*=p*(1.f-w*w);
  114034. }else{
  114035. /* even order filter; still symmetric */
  114036. q*=q*(1.f+w);
  114037. p*=p*(1.f-w);
  114038. }
  114039. q=frexp(p+q,&qexp);
  114040. q=vorbis_fromdBlook(amp*
  114041. vorbis_invsqlook(q)*
  114042. vorbis_invsq2explook(qexp+m)-
  114043. ampoffset);
  114044. do{
  114045. curve[i++]*=q;
  114046. }while(map[i]==k);
  114047. }
  114048. vorbis_fpu_restore(fpu);
  114049. }
  114050. #else
  114051. #ifdef INT_LOOKUP
  114052. /*** Start of inlined file: lookup.c ***/
  114053. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114054. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114055. // tasks..
  114056. #if JUCE_MSVC
  114057. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114058. #endif
  114059. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114060. #if JUCE_USE_OGGVORBIS
  114061. #include <math.h>
  114062. /*** Start of inlined file: lookup.h ***/
  114063. #ifndef _V_LOOKUP_H_
  114064. #ifdef FLOAT_LOOKUP
  114065. extern float vorbis_coslook(float a);
  114066. extern float vorbis_invsqlook(float a);
  114067. extern float vorbis_invsq2explook(int a);
  114068. extern float vorbis_fromdBlook(float a);
  114069. #endif
  114070. #ifdef INT_LOOKUP
  114071. extern long vorbis_invsqlook_i(long a,long e);
  114072. extern long vorbis_coslook_i(long a);
  114073. extern float vorbis_fromdBlook_i(long a);
  114074. #endif
  114075. #endif
  114076. /*** End of inlined file: lookup.h ***/
  114077. /*** Start of inlined file: lookup_data.h ***/
  114078. #ifndef _V_LOOKUP_DATA_H_
  114079. #ifdef FLOAT_LOOKUP
  114080. #define COS_LOOKUP_SZ 128
  114081. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114082. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114083. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114084. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114085. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114086. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114087. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114088. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114089. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114090. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114091. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114092. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114093. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114094. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114095. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114096. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114097. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114098. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114099. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114100. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114101. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114102. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114103. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114104. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114105. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114106. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114107. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114108. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114109. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114110. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114111. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114112. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114113. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114114. -1.0000000000000f,
  114115. };
  114116. #define INVSQ_LOOKUP_SZ 32
  114117. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114118. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114119. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114120. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114121. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114122. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114123. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114124. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114125. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114126. 1.000000000000f,
  114127. };
  114128. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114129. #define INVSQ2EXP_LOOKUP_MAX 32
  114130. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114131. INVSQ2EXP_LOOKUP_MIN+1]={
  114132. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114133. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114134. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114135. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114136. 256.f, 181.019336f, 128.f, 90.50966799f,
  114137. 64.f, 45.254834f, 32.f, 22.627417f,
  114138. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114139. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114140. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114141. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114142. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114143. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114144. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114145. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114146. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114147. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114148. 1.525878906e-05f,
  114149. };
  114150. #endif
  114151. #define FROMdB_LOOKUP_SZ 35
  114152. #define FROMdB2_LOOKUP_SZ 32
  114153. #define FROMdB_SHIFT 5
  114154. #define FROMdB2_SHIFT 3
  114155. #define FROMdB2_MASK 31
  114156. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114157. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114158. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114159. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114160. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114161. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114162. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114163. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114164. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114165. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114166. };
  114167. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114168. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114169. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114170. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114171. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114172. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114173. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114174. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114175. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114176. };
  114177. #ifdef INT_LOOKUP
  114178. #define INVSQ_LOOKUP_I_SHIFT 10
  114179. #define INVSQ_LOOKUP_I_MASK 1023
  114180. static long INVSQ_LOOKUP_I[64+1]={
  114181. 92682l, 91966l, 91267l, 90583l,
  114182. 89915l, 89261l, 88621l, 87995l,
  114183. 87381l, 86781l, 86192l, 85616l,
  114184. 85051l, 84497l, 83953l, 83420l,
  114185. 82897l, 82384l, 81880l, 81385l,
  114186. 80899l, 80422l, 79953l, 79492l,
  114187. 79039l, 78594l, 78156l, 77726l,
  114188. 77302l, 76885l, 76475l, 76072l,
  114189. 75674l, 75283l, 74898l, 74519l,
  114190. 74146l, 73778l, 73415l, 73058l,
  114191. 72706l, 72359l, 72016l, 71679l,
  114192. 71347l, 71019l, 70695l, 70376l,
  114193. 70061l, 69750l, 69444l, 69141l,
  114194. 68842l, 68548l, 68256l, 67969l,
  114195. 67685l, 67405l, 67128l, 66855l,
  114196. 66585l, 66318l, 66054l, 65794l,
  114197. 65536l,
  114198. };
  114199. #define COS_LOOKUP_I_SHIFT 9
  114200. #define COS_LOOKUP_I_MASK 511
  114201. #define COS_LOOKUP_I_SZ 128
  114202. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114203. 16384l, 16379l, 16364l, 16340l,
  114204. 16305l, 16261l, 16207l, 16143l,
  114205. 16069l, 15986l, 15893l, 15791l,
  114206. 15679l, 15557l, 15426l, 15286l,
  114207. 15137l, 14978l, 14811l, 14635l,
  114208. 14449l, 14256l, 14053l, 13842l,
  114209. 13623l, 13395l, 13160l, 12916l,
  114210. 12665l, 12406l, 12140l, 11866l,
  114211. 11585l, 11297l, 11003l, 10702l,
  114212. 10394l, 10080l, 9760l, 9434l,
  114213. 9102l, 8765l, 8423l, 8076l,
  114214. 7723l, 7366l, 7005l, 6639l,
  114215. 6270l, 5897l, 5520l, 5139l,
  114216. 4756l, 4370l, 3981l, 3590l,
  114217. 3196l, 2801l, 2404l, 2006l,
  114218. 1606l, 1205l, 804l, 402l,
  114219. 0l, -401l, -803l, -1204l,
  114220. -1605l, -2005l, -2403l, -2800l,
  114221. -3195l, -3589l, -3980l, -4369l,
  114222. -4755l, -5138l, -5519l, -5896l,
  114223. -6269l, -6638l, -7004l, -7365l,
  114224. -7722l, -8075l, -8422l, -8764l,
  114225. -9101l, -9433l, -9759l, -10079l,
  114226. -10393l, -10701l, -11002l, -11296l,
  114227. -11584l, -11865l, -12139l, -12405l,
  114228. -12664l, -12915l, -13159l, -13394l,
  114229. -13622l, -13841l, -14052l, -14255l,
  114230. -14448l, -14634l, -14810l, -14977l,
  114231. -15136l, -15285l, -15425l, -15556l,
  114232. -15678l, -15790l, -15892l, -15985l,
  114233. -16068l, -16142l, -16206l, -16260l,
  114234. -16304l, -16339l, -16363l, -16378l,
  114235. -16383l,
  114236. };
  114237. #endif
  114238. #endif
  114239. /*** End of inlined file: lookup_data.h ***/
  114240. #ifdef FLOAT_LOOKUP
  114241. /* interpolated lookup based cos function, domain 0 to PI only */
  114242. float vorbis_coslook(float a){
  114243. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114244. int i=vorbis_ftoi(d-.5);
  114245. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114246. }
  114247. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114248. float vorbis_invsqlook(float a){
  114249. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114250. int i=vorbis_ftoi(d-.5f);
  114251. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114252. }
  114253. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114254. float vorbis_invsq2explook(int a){
  114255. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114256. }
  114257. #include <stdio.h>
  114258. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114259. float vorbis_fromdBlook(float a){
  114260. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114261. return (i<0)?1.f:
  114262. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114263. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114264. }
  114265. #endif
  114266. #ifdef INT_LOOKUP
  114267. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114268. 16.16 format
  114269. returns in m.8 format */
  114270. long vorbis_invsqlook_i(long a,long e){
  114271. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114272. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114273. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114274. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114275. d)>>16); /* result 1.16 */
  114276. e+=32;
  114277. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114278. e=(e>>1)-8;
  114279. return(val>>e);
  114280. }
  114281. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114282. /* a is in n.12 format */
  114283. float vorbis_fromdBlook_i(long a){
  114284. int i=(-a)>>(12-FROMdB2_SHIFT);
  114285. return (i<0)?1.f:
  114286. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114287. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114288. }
  114289. /* interpolated lookup based cos function, domain 0 to PI only */
  114290. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114291. long vorbis_coslook_i(long a){
  114292. int i=a>>COS_LOOKUP_I_SHIFT;
  114293. int d=a&COS_LOOKUP_I_MASK;
  114294. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114295. COS_LOOKUP_I_SHIFT);
  114296. }
  114297. #endif
  114298. #endif
  114299. /*** End of inlined file: lookup.c ***/
  114300. /* catch this in the build system; we #include for
  114301. compilers (like gcc) that can't inline across
  114302. modules */
  114303. static int MLOOP_1[64]={
  114304. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114305. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114306. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114307. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114308. };
  114309. static int MLOOP_2[64]={
  114310. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114311. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114312. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114313. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114314. };
  114315. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114316. /* side effect: changes *lsp to cosines of lsp */
  114317. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114318. float amp,float ampoffset){
  114319. /* 0 <= m < 256 */
  114320. /* set up for using all int later */
  114321. int i;
  114322. int ampoffseti=rint(ampoffset*4096.f);
  114323. int ampi=rint(amp*16.f);
  114324. long *ilsp=alloca(m*sizeof(*ilsp));
  114325. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114326. i=0;
  114327. while(i<n){
  114328. int j,k=map[i];
  114329. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114330. unsigned long qi=46341;
  114331. int qexp=0,shift;
  114332. long wi=vorbis_coslook_i(k*65536/ln);
  114333. qi*=labs(ilsp[0]-wi);
  114334. pi*=labs(ilsp[1]-wi);
  114335. for(j=3;j<m;j+=2){
  114336. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114337. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114338. shift=MLOOP_3[(pi|qi)>>16];
  114339. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114340. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114341. qexp+=shift;
  114342. }
  114343. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114344. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114345. shift=MLOOP_3[(pi|qi)>>16];
  114346. /* pi,qi normalized collectively, both tracked using qexp */
  114347. if(m&1){
  114348. /* odd order filter; slightly assymetric */
  114349. /* the last coefficient */
  114350. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114351. pi=(pi>>shift)<<14;
  114352. qexp+=shift;
  114353. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114354. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114355. shift=MLOOP_3[(pi|qi)>>16];
  114356. pi>>=shift;
  114357. qi>>=shift;
  114358. qexp+=shift-14*((m+1)>>1);
  114359. pi=((pi*pi)>>16);
  114360. qi=((qi*qi)>>16);
  114361. qexp=qexp*2+m;
  114362. pi*=(1<<14)-((wi*wi)>>14);
  114363. qi+=pi>>14;
  114364. }else{
  114365. /* even order filter; still symmetric */
  114366. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114367. worth tracking step by step */
  114368. pi>>=shift;
  114369. qi>>=shift;
  114370. qexp+=shift-7*m;
  114371. pi=((pi*pi)>>16);
  114372. qi=((qi*qi)>>16);
  114373. qexp=qexp*2+m;
  114374. pi*=(1<<14)-wi;
  114375. qi*=(1<<14)+wi;
  114376. qi=(qi+pi)>>14;
  114377. }
  114378. /* we've let the normalization drift because it wasn't important;
  114379. however, for the lookup, things must be normalized again. We
  114380. need at most one right shift or a number of left shifts */
  114381. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114382. qi>>=1; qexp++;
  114383. }else
  114384. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114385. qi<<=1; qexp--;
  114386. }
  114387. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  114388. vorbis_invsqlook_i(qi,qexp)-
  114389. /* m.8, m+n<=8 */
  114390. ampoffseti); /* 8.12[0] */
  114391. curve[i]*=amp;
  114392. while(map[++i]==k)curve[i]*=amp;
  114393. }
  114394. }
  114395. #else
  114396. /* old, nonoptimized but simple version for any poor sap who needs to
  114397. figure out what the hell this code does, or wants the other
  114398. fraction of a dB precision */
  114399. /* side effect: changes *lsp to cosines of lsp */
  114400. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114401. float amp,float ampoffset){
  114402. int i;
  114403. float wdel=M_PI/ln;
  114404. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  114405. i=0;
  114406. while(i<n){
  114407. int j,k=map[i];
  114408. float p=.5f;
  114409. float q=.5f;
  114410. float w=2.f*cos(wdel*k);
  114411. for(j=1;j<m;j+=2){
  114412. q *= w-lsp[j-1];
  114413. p *= w-lsp[j];
  114414. }
  114415. if(j==m){
  114416. /* odd order filter; slightly assymetric */
  114417. /* the last coefficient */
  114418. q*=w-lsp[j-1];
  114419. p*=p*(4.f-w*w);
  114420. q*=q;
  114421. }else{
  114422. /* even order filter; still symmetric */
  114423. p*=p*(2.f-w);
  114424. q*=q*(2.f+w);
  114425. }
  114426. q=fromdB(amp/sqrt(p+q)-ampoffset);
  114427. curve[i]*=q;
  114428. while(map[++i]==k)curve[i]*=q;
  114429. }
  114430. }
  114431. #endif
  114432. #endif
  114433. static void cheby(float *g, int ord) {
  114434. int i, j;
  114435. g[0] *= .5f;
  114436. for(i=2; i<= ord; i++) {
  114437. for(j=ord; j >= i; j--) {
  114438. g[j-2] -= g[j];
  114439. g[j] += g[j];
  114440. }
  114441. }
  114442. }
  114443. static int comp(const void *a,const void *b){
  114444. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  114445. }
  114446. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  114447. but there are root sets for which it gets into limit cycles
  114448. (exacerbated by zero suppression) and fails. We can't afford to
  114449. fail, even if the failure is 1 in 100,000,000, so we now use
  114450. Laguerre and later polish with Newton-Raphson (which can then
  114451. afford to fail) */
  114452. #define EPSILON 10e-7
  114453. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  114454. int i,m;
  114455. double lastdelta=0.f;
  114456. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  114457. for(i=0;i<=ord;i++)defl[i]=a[i];
  114458. for(m=ord;m>0;m--){
  114459. double newx=0.f,delta;
  114460. /* iterate a root */
  114461. while(1){
  114462. double p=defl[m],pp=0.f,ppp=0.f,denom;
  114463. /* eval the polynomial and its first two derivatives */
  114464. for(i=m;i>0;i--){
  114465. ppp = newx*ppp + pp;
  114466. pp = newx*pp + p;
  114467. p = newx*p + defl[i-1];
  114468. }
  114469. /* Laguerre's method */
  114470. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  114471. if(denom<0)
  114472. return(-1); /* complex root! The LPC generator handed us a bad filter */
  114473. if(pp>0){
  114474. denom = pp + sqrt(denom);
  114475. if(denom<EPSILON)denom=EPSILON;
  114476. }else{
  114477. denom = pp - sqrt(denom);
  114478. if(denom>-(EPSILON))denom=-(EPSILON);
  114479. }
  114480. delta = m*p/denom;
  114481. newx -= delta;
  114482. if(delta<0.f)delta*=-1;
  114483. if(fabs(delta/newx)<10e-12)break;
  114484. lastdelta=delta;
  114485. }
  114486. r[m-1]=newx;
  114487. /* forward deflation */
  114488. for(i=m;i>0;i--)
  114489. defl[i-1]+=newx*defl[i];
  114490. defl++;
  114491. }
  114492. return(0);
  114493. }
  114494. /* for spit-and-polish only */
  114495. static int Newton_Raphson(float *a,int ord,float *r){
  114496. int i, k, count=0;
  114497. double error=1.f;
  114498. double *root=(double*)alloca(ord*sizeof(*root));
  114499. for(i=0; i<ord;i++) root[i] = r[i];
  114500. while(error>1e-20){
  114501. error=0;
  114502. for(i=0; i<ord; i++) { /* Update each point. */
  114503. double pp=0.,delta;
  114504. double rooti=root[i];
  114505. double p=a[ord];
  114506. for(k=ord-1; k>= 0; k--) {
  114507. pp= pp* rooti + p;
  114508. p = p * rooti + a[k];
  114509. }
  114510. delta = p/pp;
  114511. root[i] -= delta;
  114512. error+= delta*delta;
  114513. }
  114514. if(count>40)return(-1);
  114515. count++;
  114516. }
  114517. /* Replaced the original bubble sort with a real sort. With your
  114518. help, we can eliminate the bubble sort in our lifetime. --Monty */
  114519. for(i=0; i<ord;i++) r[i] = root[i];
  114520. return(0);
  114521. }
  114522. /* Convert lpc coefficients to lsp coefficients */
  114523. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  114524. int order2=(m+1)>>1;
  114525. int g1_order,g2_order;
  114526. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  114527. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  114528. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  114529. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  114530. int i;
  114531. /* even and odd are slightly different base cases */
  114532. g1_order=(m+1)>>1;
  114533. g2_order=(m) >>1;
  114534. /* Compute the lengths of the x polynomials. */
  114535. /* Compute the first half of K & R F1 & F2 polynomials. */
  114536. /* Compute half of the symmetric and antisymmetric polynomials. */
  114537. /* Remove the roots at +1 and -1. */
  114538. g1[g1_order] = 1.f;
  114539. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  114540. g2[g2_order] = 1.f;
  114541. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  114542. if(g1_order>g2_order){
  114543. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  114544. }else{
  114545. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  114546. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  114547. }
  114548. /* Convert into polynomials in cos(alpha) */
  114549. cheby(g1,g1_order);
  114550. cheby(g2,g2_order);
  114551. /* Find the roots of the 2 even polynomials.*/
  114552. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  114553. Laguerre_With_Deflation(g2,g2_order,g2r))
  114554. return(-1);
  114555. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  114556. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  114557. qsort(g1r,g1_order,sizeof(*g1r),comp);
  114558. qsort(g2r,g2_order,sizeof(*g2r),comp);
  114559. for(i=0;i<g1_order;i++)
  114560. lsp[i*2] = acos(g1r[i]);
  114561. for(i=0;i<g2_order;i++)
  114562. lsp[i*2+1] = acos(g2r[i]);
  114563. return(0);
  114564. }
  114565. #endif
  114566. /*** End of inlined file: lsp.c ***/
  114567. /*** Start of inlined file: mapping0.c ***/
  114568. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114569. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114570. // tasks..
  114571. #if JUCE_MSVC
  114572. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114573. #endif
  114574. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114575. #if JUCE_USE_OGGVORBIS
  114576. #include <stdlib.h>
  114577. #include <stdio.h>
  114578. #include <string.h>
  114579. #include <math.h>
  114580. /* simplistic, wasteful way of doing this (unique lookup for each
  114581. mode/submapping); there should be a central repository for
  114582. identical lookups. That will require minor work, so I'm putting it
  114583. off as low priority.
  114584. Why a lookup for each backend in a given mode? Because the
  114585. blocksize is set by the mode, and low backend lookups may require
  114586. parameters from other areas of the mode/mapping */
  114587. static void mapping0_free_info(vorbis_info_mapping *i){
  114588. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  114589. if(info){
  114590. memset(info,0,sizeof(*info));
  114591. _ogg_free(info);
  114592. }
  114593. }
  114594. static int ilog3(unsigned int v){
  114595. int ret=0;
  114596. if(v)--v;
  114597. while(v){
  114598. ret++;
  114599. v>>=1;
  114600. }
  114601. return(ret);
  114602. }
  114603. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  114604. oggpack_buffer *opb){
  114605. int i;
  114606. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  114607. /* another 'we meant to do it this way' hack... up to beta 4, we
  114608. packed 4 binary zeros here to signify one submapping in use. We
  114609. now redefine that to mean four bitflags that indicate use of
  114610. deeper features; bit0:submappings, bit1:coupling,
  114611. bit2,3:reserved. This is backward compatable with all actual uses
  114612. of the beta code. */
  114613. if(info->submaps>1){
  114614. oggpack_write(opb,1,1);
  114615. oggpack_write(opb,info->submaps-1,4);
  114616. }else
  114617. oggpack_write(opb,0,1);
  114618. if(info->coupling_steps>0){
  114619. oggpack_write(opb,1,1);
  114620. oggpack_write(opb,info->coupling_steps-1,8);
  114621. for(i=0;i<info->coupling_steps;i++){
  114622. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  114623. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  114624. }
  114625. }else
  114626. oggpack_write(opb,0,1);
  114627. oggpack_write(opb,0,2); /* 2,3:reserved */
  114628. /* we don't write the channel submappings if we only have one... */
  114629. if(info->submaps>1){
  114630. for(i=0;i<vi->channels;i++)
  114631. oggpack_write(opb,info->chmuxlist[i],4);
  114632. }
  114633. for(i=0;i<info->submaps;i++){
  114634. oggpack_write(opb,0,8); /* time submap unused */
  114635. oggpack_write(opb,info->floorsubmap[i],8);
  114636. oggpack_write(opb,info->residuesubmap[i],8);
  114637. }
  114638. }
  114639. /* also responsible for range checking */
  114640. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  114641. int i;
  114642. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  114643. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114644. memset(info,0,sizeof(*info));
  114645. if(oggpack_read(opb,1))
  114646. info->submaps=oggpack_read(opb,4)+1;
  114647. else
  114648. info->submaps=1;
  114649. if(oggpack_read(opb,1)){
  114650. info->coupling_steps=oggpack_read(opb,8)+1;
  114651. for(i=0;i<info->coupling_steps;i++){
  114652. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  114653. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  114654. if(testM<0 ||
  114655. testA<0 ||
  114656. testM==testA ||
  114657. testM>=vi->channels ||
  114658. testA>=vi->channels) goto err_out;
  114659. }
  114660. }
  114661. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  114662. if(info->submaps>1){
  114663. for(i=0;i<vi->channels;i++){
  114664. info->chmuxlist[i]=oggpack_read(opb,4);
  114665. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  114666. }
  114667. }
  114668. for(i=0;i<info->submaps;i++){
  114669. oggpack_read(opb,8); /* time submap unused */
  114670. info->floorsubmap[i]=oggpack_read(opb,8);
  114671. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  114672. info->residuesubmap[i]=oggpack_read(opb,8);
  114673. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  114674. }
  114675. return info;
  114676. err_out:
  114677. mapping0_free_info(info);
  114678. return(NULL);
  114679. }
  114680. #if 0
  114681. static long seq=0;
  114682. static ogg_int64_t total=0;
  114683. static float FLOOR1_fromdB_LOOKUP[256]={
  114684. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  114685. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  114686. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  114687. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  114688. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  114689. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  114690. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  114691. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  114692. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  114693. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  114694. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  114695. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  114696. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  114697. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  114698. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  114699. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  114700. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  114701. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  114702. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  114703. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  114704. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  114705. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  114706. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  114707. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  114708. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  114709. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  114710. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  114711. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  114712. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  114713. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  114714. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  114715. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  114716. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  114717. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  114718. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  114719. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  114720. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  114721. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  114722. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  114723. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  114724. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  114725. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  114726. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  114727. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  114728. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  114729. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  114730. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  114731. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  114732. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  114733. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  114734. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  114735. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  114736. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  114737. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  114738. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  114739. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  114740. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  114741. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  114742. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  114743. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  114744. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  114745. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  114746. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  114747. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  114748. };
  114749. #endif
  114750. extern int *floor1_fit(vorbis_block *vb,void *look,
  114751. const float *logmdct, /* in */
  114752. const float *logmask);
  114753. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  114754. int *A,int *B,
  114755. int del);
  114756. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  114757. void*look,
  114758. int *post,int *ilogmask);
  114759. static int mapping0_forward(vorbis_block *vb){
  114760. vorbis_dsp_state *vd=vb->vd;
  114761. vorbis_info *vi=vd->vi;
  114762. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114763. private_state *b=(private_state*)vb->vd->backend_state;
  114764. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  114765. int n=vb->pcmend;
  114766. int i,j,k;
  114767. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  114768. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  114769. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  114770. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  114771. float global_ampmax=vbi->ampmax;
  114772. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  114773. int blocktype=vbi->blocktype;
  114774. int modenumber=vb->W;
  114775. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  114776. vorbis_look_psy *psy_look=
  114777. b->psy+blocktype+(vb->W?2:0);
  114778. vb->mode=modenumber;
  114779. for(i=0;i<vi->channels;i++){
  114780. float scale=4.f/n;
  114781. float scale_dB;
  114782. float *pcm =vb->pcm[i];
  114783. float *logfft =pcm;
  114784. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  114785. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  114786. todB estimation used on IEEE 754
  114787. compliant machines had a bug that
  114788. returned dB values about a third
  114789. of a decibel too high. The bug
  114790. was harmless because tunings
  114791. implicitly took that into
  114792. account. However, fixing the bug
  114793. in the estimator requires
  114794. changing all the tunings as well.
  114795. For now, it's easier to sync
  114796. things back up here, and
  114797. recalibrate the tunings in the
  114798. next major model upgrade. */
  114799. #if 0
  114800. if(vi->channels==2)
  114801. if(i==0)
  114802. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  114803. else
  114804. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  114805. #endif
  114806. /* window the PCM data */
  114807. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  114808. #if 0
  114809. if(vi->channels==2)
  114810. if(i==0)
  114811. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  114812. else
  114813. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  114814. #endif
  114815. /* transform the PCM data */
  114816. /* only MDCT right now.... */
  114817. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  114818. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  114819. drft_forward(&b->fft_look[vb->W],pcm);
  114820. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  114821. original todB estimation used on
  114822. IEEE 754 compliant machines had a
  114823. bug that returned dB values about
  114824. a third of a decibel too high.
  114825. The bug was harmless because
  114826. tunings implicitly took that into
  114827. account. However, fixing the bug
  114828. in the estimator requires
  114829. changing all the tunings as well.
  114830. For now, it's easier to sync
  114831. things back up here, and
  114832. recalibrate the tunings in the
  114833. next major model upgrade. */
  114834. local_ampmax[i]=logfft[0];
  114835. for(j=1;j<n-1;j+=2){
  114836. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  114837. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  114838. .345 is a hack; the original todB
  114839. estimation used on IEEE 754
  114840. compliant machines had a bug that
  114841. returned dB values about a third
  114842. of a decibel too high. The bug
  114843. was harmless because tunings
  114844. implicitly took that into
  114845. account. However, fixing the bug
  114846. in the estimator requires
  114847. changing all the tunings as well.
  114848. For now, it's easier to sync
  114849. things back up here, and
  114850. recalibrate the tunings in the
  114851. next major model upgrade. */
  114852. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  114853. }
  114854. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  114855. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  114856. #if 0
  114857. if(vi->channels==2){
  114858. if(i==0){
  114859. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  114860. }else{
  114861. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  114862. }
  114863. }
  114864. #endif
  114865. }
  114866. {
  114867. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  114868. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  114869. for(i=0;i<vi->channels;i++){
  114870. /* the encoder setup assumes that all the modes used by any
  114871. specific bitrate tweaking use the same floor */
  114872. int submap=info->chmuxlist[i];
  114873. /* the following makes things clearer to *me* anyway */
  114874. float *mdct =gmdct[i];
  114875. float *logfft =vb->pcm[i];
  114876. float *logmdct =logfft+n/2;
  114877. float *logmask =logfft;
  114878. vb->mode=modenumber;
  114879. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  114880. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  114881. for(j=0;j<n/2;j++)
  114882. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  114883. todB estimation used on IEEE 754
  114884. compliant machines had a bug that
  114885. returned dB values about a third
  114886. of a decibel too high. The bug
  114887. was harmless because tunings
  114888. implicitly took that into
  114889. account. However, fixing the bug
  114890. in the estimator requires
  114891. changing all the tunings as well.
  114892. For now, it's easier to sync
  114893. things back up here, and
  114894. recalibrate the tunings in the
  114895. next major model upgrade. */
  114896. #if 0
  114897. if(vi->channels==2){
  114898. if(i==0)
  114899. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  114900. else
  114901. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  114902. }else{
  114903. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  114904. }
  114905. #endif
  114906. /* first step; noise masking. Not only does 'noise masking'
  114907. give us curves from which we can decide how much resolution
  114908. to give noise parts of the spectrum, it also implicitly hands
  114909. us a tonality estimate (the larger the value in the
  114910. 'noise_depth' vector, the more tonal that area is) */
  114911. _vp_noisemask(psy_look,
  114912. logmdct,
  114913. noise); /* noise does not have by-frequency offset
  114914. bias applied yet */
  114915. #if 0
  114916. if(vi->channels==2){
  114917. if(i==0)
  114918. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  114919. else
  114920. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  114921. }
  114922. #endif
  114923. /* second step: 'all the other crap'; all the stuff that isn't
  114924. computed/fit for bitrate management goes in the second psy
  114925. vector. This includes tone masking, peak limiting and ATH */
  114926. _vp_tonemask(psy_look,
  114927. logfft,
  114928. tone,
  114929. global_ampmax,
  114930. local_ampmax[i]);
  114931. #if 0
  114932. if(vi->channels==2){
  114933. if(i==0)
  114934. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  114935. else
  114936. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  114937. }
  114938. #endif
  114939. /* third step; we offset the noise vectors, overlay tone
  114940. masking. We then do a floor1-specific line fit. If we're
  114941. performing bitrate management, the line fit is performed
  114942. multiple times for up/down tweakage on demand. */
  114943. #if 0
  114944. {
  114945. float aotuv[psy_look->n];
  114946. #endif
  114947. _vp_offset_and_mix(psy_look,
  114948. noise,
  114949. tone,
  114950. 1,
  114951. logmask,
  114952. mdct,
  114953. logmdct);
  114954. #if 0
  114955. if(vi->channels==2){
  114956. if(i==0)
  114957. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  114958. else
  114959. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  114960. }
  114961. }
  114962. #endif
  114963. #if 0
  114964. if(vi->channels==2){
  114965. if(i==0)
  114966. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  114967. else
  114968. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  114969. }
  114970. #endif
  114971. /* this algorithm is hardwired to floor 1 for now; abort out if
  114972. we're *not* floor1. This won't happen unless someone has
  114973. broken the encode setup lib. Guard it anyway. */
  114974. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  114975. floor_posts[i][PACKETBLOBS/2]=
  114976. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  114977. logmdct,
  114978. logmask);
  114979. /* are we managing bitrate? If so, perform two more fits for
  114980. later rate tweaking (fits represent hi/lo) */
  114981. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  114982. /* higher rate by way of lower noise curve */
  114983. _vp_offset_and_mix(psy_look,
  114984. noise,
  114985. tone,
  114986. 2,
  114987. logmask,
  114988. mdct,
  114989. logmdct);
  114990. #if 0
  114991. if(vi->channels==2){
  114992. if(i==0)
  114993. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  114994. else
  114995. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  114996. }
  114997. #endif
  114998. floor_posts[i][PACKETBLOBS-1]=
  114999. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115000. logmdct,
  115001. logmask);
  115002. /* lower rate by way of higher noise curve */
  115003. _vp_offset_and_mix(psy_look,
  115004. noise,
  115005. tone,
  115006. 0,
  115007. logmask,
  115008. mdct,
  115009. logmdct);
  115010. #if 0
  115011. if(vi->channels==2)
  115012. if(i==0)
  115013. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115014. else
  115015. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115016. #endif
  115017. floor_posts[i][0]=
  115018. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115019. logmdct,
  115020. logmask);
  115021. /* we also interpolate a range of intermediate curves for
  115022. intermediate rates */
  115023. for(k=1;k<PACKETBLOBS/2;k++)
  115024. floor_posts[i][k]=
  115025. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115026. floor_posts[i][0],
  115027. floor_posts[i][PACKETBLOBS/2],
  115028. k*65536/(PACKETBLOBS/2));
  115029. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115030. floor_posts[i][k]=
  115031. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115032. floor_posts[i][PACKETBLOBS/2],
  115033. floor_posts[i][PACKETBLOBS-1],
  115034. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115035. }
  115036. }
  115037. }
  115038. vbi->ampmax=global_ampmax;
  115039. /*
  115040. the next phases are performed once for vbr-only and PACKETBLOB
  115041. times for bitrate managed modes.
  115042. 1) encode actual mode being used
  115043. 2) encode the floor for each channel, compute coded mask curve/res
  115044. 3) normalize and couple.
  115045. 4) encode residue
  115046. 5) save packet bytes to the packetblob vector
  115047. */
  115048. /* iterate over the many masking curve fits we've created */
  115049. {
  115050. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115051. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115052. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115053. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115054. float **mag_memo;
  115055. int **mag_sort;
  115056. if(info->coupling_steps){
  115057. mag_memo=_vp_quantize_couple_memo(vb,
  115058. &ci->psy_g_param,
  115059. psy_look,
  115060. info,
  115061. gmdct);
  115062. mag_sort=_vp_quantize_couple_sort(vb,
  115063. psy_look,
  115064. info,
  115065. mag_memo);
  115066. hf_reduction(&ci->psy_g_param,
  115067. psy_look,
  115068. info,
  115069. mag_memo);
  115070. }
  115071. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115072. if(psy_look->vi->normal_channel_p){
  115073. for(i=0;i<vi->channels;i++){
  115074. float *mdct =gmdct[i];
  115075. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115076. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115077. }
  115078. }
  115079. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115080. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115081. k++){
  115082. oggpack_buffer *opb=vbi->packetblob[k];
  115083. /* start out our new packet blob with packet type and mode */
  115084. /* Encode the packet type */
  115085. oggpack_write(opb,0,1);
  115086. /* Encode the modenumber */
  115087. /* Encode frame mode, pre,post windowsize, then dispatch */
  115088. oggpack_write(opb,modenumber,b->modebits);
  115089. if(vb->W){
  115090. oggpack_write(opb,vb->lW,1);
  115091. oggpack_write(opb,vb->nW,1);
  115092. }
  115093. /* encode floor, compute masking curve, sep out residue */
  115094. for(i=0;i<vi->channels;i++){
  115095. int submap=info->chmuxlist[i];
  115096. float *mdct =gmdct[i];
  115097. float *res =vb->pcm[i];
  115098. int *ilogmask=ilogmaskch[i]=
  115099. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115100. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115101. floor_posts[i][k],
  115102. ilogmask);
  115103. #if 0
  115104. {
  115105. char buf[80];
  115106. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115107. float work[n/2];
  115108. for(j=0;j<n/2;j++)
  115109. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115110. _analysis_output(buf,seq,work,n/2,1,1,0);
  115111. }
  115112. #endif
  115113. _vp_remove_floor(psy_look,
  115114. mdct,
  115115. ilogmask,
  115116. res,
  115117. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115118. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115119. #if 0
  115120. {
  115121. char buf[80];
  115122. float work[n/2];
  115123. for(j=0;j<n/2;j++)
  115124. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115125. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115126. _analysis_output(buf,seq,work,n/2,1,1,0);
  115127. }
  115128. #endif
  115129. }
  115130. /* our iteration is now based on masking curve, not prequant and
  115131. coupling. Only one prequant/coupling step */
  115132. /* quantize/couple */
  115133. /* incomplete implementation that assumes the tree is all depth
  115134. one, or no tree at all */
  115135. if(info->coupling_steps){
  115136. _vp_couple(k,
  115137. &ci->psy_g_param,
  115138. psy_look,
  115139. info,
  115140. vb->pcm,
  115141. mag_memo,
  115142. mag_sort,
  115143. ilogmaskch,
  115144. nonzero,
  115145. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115146. }
  115147. /* classify and encode by submap */
  115148. for(i=0;i<info->submaps;i++){
  115149. int ch_in_bundle=0;
  115150. long **classifications;
  115151. int resnum=info->residuesubmap[i];
  115152. for(j=0;j<vi->channels;j++){
  115153. if(info->chmuxlist[j]==i){
  115154. zerobundle[ch_in_bundle]=0;
  115155. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115156. res_bundle[ch_in_bundle]=vb->pcm[j];
  115157. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115158. }
  115159. }
  115160. classifications=_residue_P[ci->residue_type[resnum]]->
  115161. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115162. _residue_P[ci->residue_type[resnum]]->
  115163. forward(opb,vb,b->residue[resnum],
  115164. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115165. }
  115166. /* ok, done encoding. Next protopacket. */
  115167. }
  115168. }
  115169. #if 0
  115170. seq++;
  115171. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115172. #endif
  115173. return(0);
  115174. }
  115175. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115176. vorbis_dsp_state *vd=vb->vd;
  115177. vorbis_info *vi=vd->vi;
  115178. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115179. private_state *b=(private_state*)vd->backend_state;
  115180. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115181. int i,j;
  115182. long n=vb->pcmend=ci->blocksizes[vb->W];
  115183. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115184. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115185. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115186. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115187. /* recover the spectral envelope; store it in the PCM vector for now */
  115188. for(i=0;i<vi->channels;i++){
  115189. int submap=info->chmuxlist[i];
  115190. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115191. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115192. if(floormemo[i])
  115193. nonzero[i]=1;
  115194. else
  115195. nonzero[i]=0;
  115196. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115197. }
  115198. /* channel coupling can 'dirty' the nonzero listing */
  115199. for(i=0;i<info->coupling_steps;i++){
  115200. if(nonzero[info->coupling_mag[i]] ||
  115201. nonzero[info->coupling_ang[i]]){
  115202. nonzero[info->coupling_mag[i]]=1;
  115203. nonzero[info->coupling_ang[i]]=1;
  115204. }
  115205. }
  115206. /* recover the residue into our working vectors */
  115207. for(i=0;i<info->submaps;i++){
  115208. int ch_in_bundle=0;
  115209. for(j=0;j<vi->channels;j++){
  115210. if(info->chmuxlist[j]==i){
  115211. if(nonzero[j])
  115212. zerobundle[ch_in_bundle]=1;
  115213. else
  115214. zerobundle[ch_in_bundle]=0;
  115215. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115216. }
  115217. }
  115218. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115219. inverse(vb,b->residue[info->residuesubmap[i]],
  115220. pcmbundle,zerobundle,ch_in_bundle);
  115221. }
  115222. /* channel coupling */
  115223. for(i=info->coupling_steps-1;i>=0;i--){
  115224. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115225. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115226. for(j=0;j<n/2;j++){
  115227. float mag=pcmM[j];
  115228. float ang=pcmA[j];
  115229. if(mag>0)
  115230. if(ang>0){
  115231. pcmM[j]=mag;
  115232. pcmA[j]=mag-ang;
  115233. }else{
  115234. pcmA[j]=mag;
  115235. pcmM[j]=mag+ang;
  115236. }
  115237. else
  115238. if(ang>0){
  115239. pcmM[j]=mag;
  115240. pcmA[j]=mag+ang;
  115241. }else{
  115242. pcmA[j]=mag;
  115243. pcmM[j]=mag-ang;
  115244. }
  115245. }
  115246. }
  115247. /* compute and apply spectral envelope */
  115248. for(i=0;i<vi->channels;i++){
  115249. float *pcm=vb->pcm[i];
  115250. int submap=info->chmuxlist[i];
  115251. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115252. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115253. floormemo[i],pcm);
  115254. }
  115255. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115256. /* only MDCT right now.... */
  115257. for(i=0;i<vi->channels;i++){
  115258. float *pcm=vb->pcm[i];
  115259. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115260. }
  115261. /* all done! */
  115262. return(0);
  115263. }
  115264. /* export hooks */
  115265. vorbis_func_mapping mapping0_exportbundle={
  115266. &mapping0_pack,
  115267. &mapping0_unpack,
  115268. &mapping0_free_info,
  115269. &mapping0_forward,
  115270. &mapping0_inverse
  115271. };
  115272. #endif
  115273. /*** End of inlined file: mapping0.c ***/
  115274. /*** Start of inlined file: mdct.c ***/
  115275. /* this can also be run as an integer transform by uncommenting a
  115276. define in mdct.h; the integerization is a first pass and although
  115277. it's likely stable for Vorbis, the dynamic range is constrained and
  115278. roundoff isn't done (so it's noisy). Consider it functional, but
  115279. only a starting point. There's no point on a machine with an FPU */
  115280. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115281. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115282. // tasks..
  115283. #if JUCE_MSVC
  115284. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115285. #endif
  115286. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115287. #if JUCE_USE_OGGVORBIS
  115288. #include <stdio.h>
  115289. #include <stdlib.h>
  115290. #include <string.h>
  115291. #include <math.h>
  115292. /* build lookups for trig functions; also pre-figure scaling and
  115293. some window function algebra. */
  115294. void mdct_init(mdct_lookup *lookup,int n){
  115295. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115296. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115297. int i;
  115298. int n2=n>>1;
  115299. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115300. lookup->n=n;
  115301. lookup->trig=T;
  115302. lookup->bitrev=bitrev;
  115303. /* trig lookups... */
  115304. for(i=0;i<n/4;i++){
  115305. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115306. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115307. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115308. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115309. }
  115310. for(i=0;i<n/8;i++){
  115311. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115312. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115313. }
  115314. /* bitreverse lookup... */
  115315. {
  115316. int mask=(1<<(log2n-1))-1,i,j;
  115317. int msb=1<<(log2n-2);
  115318. for(i=0;i<n/8;i++){
  115319. int acc=0;
  115320. for(j=0;msb>>j;j++)
  115321. if((msb>>j)&i)acc|=1<<j;
  115322. bitrev[i*2]=((~acc)&mask)-1;
  115323. bitrev[i*2+1]=acc;
  115324. }
  115325. }
  115326. lookup->scale=FLOAT_CONV(4.f/n);
  115327. }
  115328. /* 8 point butterfly (in place, 4 register) */
  115329. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115330. REG_TYPE r0 = x[6] + x[2];
  115331. REG_TYPE r1 = x[6] - x[2];
  115332. REG_TYPE r2 = x[4] + x[0];
  115333. REG_TYPE r3 = x[4] - x[0];
  115334. x[6] = r0 + r2;
  115335. x[4] = r0 - r2;
  115336. r0 = x[5] - x[1];
  115337. r2 = x[7] - x[3];
  115338. x[0] = r1 + r0;
  115339. x[2] = r1 - r0;
  115340. r0 = x[5] + x[1];
  115341. r1 = x[7] + x[3];
  115342. x[3] = r2 + r3;
  115343. x[1] = r2 - r3;
  115344. x[7] = r1 + r0;
  115345. x[5] = r1 - r0;
  115346. }
  115347. /* 16 point butterfly (in place, 4 register) */
  115348. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115349. REG_TYPE r0 = x[1] - x[9];
  115350. REG_TYPE r1 = x[0] - x[8];
  115351. x[8] += x[0];
  115352. x[9] += x[1];
  115353. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115354. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115355. r0 = x[3] - x[11];
  115356. r1 = x[10] - x[2];
  115357. x[10] += x[2];
  115358. x[11] += x[3];
  115359. x[2] = r0;
  115360. x[3] = r1;
  115361. r0 = x[12] - x[4];
  115362. r1 = x[13] - x[5];
  115363. x[12] += x[4];
  115364. x[13] += x[5];
  115365. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115366. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115367. r0 = x[14] - x[6];
  115368. r1 = x[15] - x[7];
  115369. x[14] += x[6];
  115370. x[15] += x[7];
  115371. x[6] = r0;
  115372. x[7] = r1;
  115373. mdct_butterfly_8(x);
  115374. mdct_butterfly_8(x+8);
  115375. }
  115376. /* 32 point butterfly (in place, 4 register) */
  115377. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115378. REG_TYPE r0 = x[30] - x[14];
  115379. REG_TYPE r1 = x[31] - x[15];
  115380. x[30] += x[14];
  115381. x[31] += x[15];
  115382. x[14] = r0;
  115383. x[15] = r1;
  115384. r0 = x[28] - x[12];
  115385. r1 = x[29] - x[13];
  115386. x[28] += x[12];
  115387. x[29] += x[13];
  115388. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  115389. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  115390. r0 = x[26] - x[10];
  115391. r1 = x[27] - x[11];
  115392. x[26] += x[10];
  115393. x[27] += x[11];
  115394. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  115395. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  115396. r0 = x[24] - x[8];
  115397. r1 = x[25] - x[9];
  115398. x[24] += x[8];
  115399. x[25] += x[9];
  115400. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  115401. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115402. r0 = x[22] - x[6];
  115403. r1 = x[7] - x[23];
  115404. x[22] += x[6];
  115405. x[23] += x[7];
  115406. x[6] = r1;
  115407. x[7] = r0;
  115408. r0 = x[4] - x[20];
  115409. r1 = x[5] - x[21];
  115410. x[20] += x[4];
  115411. x[21] += x[5];
  115412. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  115413. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  115414. r0 = x[2] - x[18];
  115415. r1 = x[3] - x[19];
  115416. x[18] += x[2];
  115417. x[19] += x[3];
  115418. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  115419. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  115420. r0 = x[0] - x[16];
  115421. r1 = x[1] - x[17];
  115422. x[16] += x[0];
  115423. x[17] += x[1];
  115424. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115425. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  115426. mdct_butterfly_16(x);
  115427. mdct_butterfly_16(x+16);
  115428. }
  115429. /* N point first stage butterfly (in place, 2 register) */
  115430. STIN void mdct_butterfly_first(DATA_TYPE *T,
  115431. DATA_TYPE *x,
  115432. int points){
  115433. DATA_TYPE *x1 = x + points - 8;
  115434. DATA_TYPE *x2 = x + (points>>1) - 8;
  115435. REG_TYPE r0;
  115436. REG_TYPE r1;
  115437. do{
  115438. r0 = x1[6] - x2[6];
  115439. r1 = x1[7] - x2[7];
  115440. x1[6] += x2[6];
  115441. x1[7] += x2[7];
  115442. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115443. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115444. r0 = x1[4] - x2[4];
  115445. r1 = x1[5] - x2[5];
  115446. x1[4] += x2[4];
  115447. x1[5] += x2[5];
  115448. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  115449. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  115450. r0 = x1[2] - x2[2];
  115451. r1 = x1[3] - x2[3];
  115452. x1[2] += x2[2];
  115453. x1[3] += x2[3];
  115454. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  115455. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  115456. r0 = x1[0] - x2[0];
  115457. r1 = x1[1] - x2[1];
  115458. x1[0] += x2[0];
  115459. x1[1] += x2[1];
  115460. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  115461. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  115462. x1-=8;
  115463. x2-=8;
  115464. T+=16;
  115465. }while(x2>=x);
  115466. }
  115467. /* N/stage point generic N stage butterfly (in place, 2 register) */
  115468. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  115469. DATA_TYPE *x,
  115470. int points,
  115471. int trigint){
  115472. DATA_TYPE *x1 = x + points - 8;
  115473. DATA_TYPE *x2 = x + (points>>1) - 8;
  115474. REG_TYPE r0;
  115475. REG_TYPE r1;
  115476. do{
  115477. r0 = x1[6] - x2[6];
  115478. r1 = x1[7] - x2[7];
  115479. x1[6] += x2[6];
  115480. x1[7] += x2[7];
  115481. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115482. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115483. T+=trigint;
  115484. r0 = x1[4] - x2[4];
  115485. r1 = x1[5] - x2[5];
  115486. x1[4] += x2[4];
  115487. x1[5] += x2[5];
  115488. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115489. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115490. T+=trigint;
  115491. r0 = x1[2] - x2[2];
  115492. r1 = x1[3] - x2[3];
  115493. x1[2] += x2[2];
  115494. x1[3] += x2[3];
  115495. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115496. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115497. T+=trigint;
  115498. r0 = x1[0] - x2[0];
  115499. r1 = x1[1] - x2[1];
  115500. x1[0] += x2[0];
  115501. x1[1] += x2[1];
  115502. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115503. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115504. T+=trigint;
  115505. x1-=8;
  115506. x2-=8;
  115507. }while(x2>=x);
  115508. }
  115509. STIN void mdct_butterflies(mdct_lookup *init,
  115510. DATA_TYPE *x,
  115511. int points){
  115512. DATA_TYPE *T=init->trig;
  115513. int stages=init->log2n-5;
  115514. int i,j;
  115515. if(--stages>0){
  115516. mdct_butterfly_first(T,x,points);
  115517. }
  115518. for(i=1;--stages>0;i++){
  115519. for(j=0;j<(1<<i);j++)
  115520. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  115521. }
  115522. for(j=0;j<points;j+=32)
  115523. mdct_butterfly_32(x+j);
  115524. }
  115525. void mdct_clear(mdct_lookup *l){
  115526. if(l){
  115527. if(l->trig)_ogg_free(l->trig);
  115528. if(l->bitrev)_ogg_free(l->bitrev);
  115529. memset(l,0,sizeof(*l));
  115530. }
  115531. }
  115532. STIN void mdct_bitreverse(mdct_lookup *init,
  115533. DATA_TYPE *x){
  115534. int n = init->n;
  115535. int *bit = init->bitrev;
  115536. DATA_TYPE *w0 = x;
  115537. DATA_TYPE *w1 = x = w0+(n>>1);
  115538. DATA_TYPE *T = init->trig+n;
  115539. do{
  115540. DATA_TYPE *x0 = x+bit[0];
  115541. DATA_TYPE *x1 = x+bit[1];
  115542. REG_TYPE r0 = x0[1] - x1[1];
  115543. REG_TYPE r1 = x0[0] + x1[0];
  115544. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  115545. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  115546. w1 -= 4;
  115547. r0 = HALVE(x0[1] + x1[1]);
  115548. r1 = HALVE(x0[0] - x1[0]);
  115549. w0[0] = r0 + r2;
  115550. w1[2] = r0 - r2;
  115551. w0[1] = r1 + r3;
  115552. w1[3] = r3 - r1;
  115553. x0 = x+bit[2];
  115554. x1 = x+bit[3];
  115555. r0 = x0[1] - x1[1];
  115556. r1 = x0[0] + x1[0];
  115557. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  115558. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  115559. r0 = HALVE(x0[1] + x1[1]);
  115560. r1 = HALVE(x0[0] - x1[0]);
  115561. w0[2] = r0 + r2;
  115562. w1[0] = r0 - r2;
  115563. w0[3] = r1 + r3;
  115564. w1[1] = r3 - r1;
  115565. T += 4;
  115566. bit += 4;
  115567. w0 += 4;
  115568. }while(w0<w1);
  115569. }
  115570. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115571. int n=init->n;
  115572. int n2=n>>1;
  115573. int n4=n>>2;
  115574. /* rotate */
  115575. DATA_TYPE *iX = in+n2-7;
  115576. DATA_TYPE *oX = out+n2+n4;
  115577. DATA_TYPE *T = init->trig+n4;
  115578. do{
  115579. oX -= 4;
  115580. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  115581. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  115582. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  115583. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  115584. iX -= 8;
  115585. T += 4;
  115586. }while(iX>=in);
  115587. iX = in+n2-8;
  115588. oX = out+n2+n4;
  115589. T = init->trig+n4;
  115590. do{
  115591. T -= 4;
  115592. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  115593. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  115594. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  115595. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  115596. iX -= 8;
  115597. oX += 4;
  115598. }while(iX>=in);
  115599. mdct_butterflies(init,out+n2,n2);
  115600. mdct_bitreverse(init,out);
  115601. /* roatate + window */
  115602. {
  115603. DATA_TYPE *oX1=out+n2+n4;
  115604. DATA_TYPE *oX2=out+n2+n4;
  115605. DATA_TYPE *iX =out;
  115606. T =init->trig+n2;
  115607. do{
  115608. oX1-=4;
  115609. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  115610. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  115611. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  115612. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  115613. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  115614. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  115615. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  115616. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  115617. oX2+=4;
  115618. iX += 8;
  115619. T += 8;
  115620. }while(iX<oX1);
  115621. iX=out+n2+n4;
  115622. oX1=out+n4;
  115623. oX2=oX1;
  115624. do{
  115625. oX1-=4;
  115626. iX-=4;
  115627. oX2[0] = -(oX1[3] = iX[3]);
  115628. oX2[1] = -(oX1[2] = iX[2]);
  115629. oX2[2] = -(oX1[1] = iX[1]);
  115630. oX2[3] = -(oX1[0] = iX[0]);
  115631. oX2+=4;
  115632. }while(oX2<iX);
  115633. iX=out+n2+n4;
  115634. oX1=out+n2+n4;
  115635. oX2=out+n2;
  115636. do{
  115637. oX1-=4;
  115638. oX1[0]= iX[3];
  115639. oX1[1]= iX[2];
  115640. oX1[2]= iX[1];
  115641. oX1[3]= iX[0];
  115642. iX+=4;
  115643. }while(oX1>oX2);
  115644. }
  115645. }
  115646. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115647. int n=init->n;
  115648. int n2=n>>1;
  115649. int n4=n>>2;
  115650. int n8=n>>3;
  115651. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  115652. DATA_TYPE *w2=w+n2;
  115653. /* rotate */
  115654. /* window + rotate + step 1 */
  115655. REG_TYPE r0;
  115656. REG_TYPE r1;
  115657. DATA_TYPE *x0=in+n2+n4;
  115658. DATA_TYPE *x1=x0+1;
  115659. DATA_TYPE *T=init->trig+n2;
  115660. int i=0;
  115661. for(i=0;i<n8;i+=2){
  115662. x0 -=4;
  115663. T-=2;
  115664. r0= x0[2] + x1[0];
  115665. r1= x0[0] + x1[2];
  115666. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115667. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115668. x1 +=4;
  115669. }
  115670. x1=in+1;
  115671. for(;i<n2-n8;i+=2){
  115672. T-=2;
  115673. x0 -=4;
  115674. r0= x0[2] - x1[0];
  115675. r1= x0[0] - x1[2];
  115676. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115677. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115678. x1 +=4;
  115679. }
  115680. x0=in+n;
  115681. for(;i<n2;i+=2){
  115682. T-=2;
  115683. x0 -=4;
  115684. r0= -x0[2] - x1[0];
  115685. r1= -x0[0] - x1[2];
  115686. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115687. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115688. x1 +=4;
  115689. }
  115690. mdct_butterflies(init,w+n2,n2);
  115691. mdct_bitreverse(init,w);
  115692. /* roatate + window */
  115693. T=init->trig+n2;
  115694. x0=out+n2;
  115695. for(i=0;i<n4;i++){
  115696. x0--;
  115697. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  115698. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  115699. w+=2;
  115700. T+=2;
  115701. }
  115702. }
  115703. #endif
  115704. /*** End of inlined file: mdct.c ***/
  115705. /*** Start of inlined file: psy.c ***/
  115706. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115707. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115708. // tasks..
  115709. #if JUCE_MSVC
  115710. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115711. #endif
  115712. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115713. #if JUCE_USE_OGGVORBIS
  115714. #include <stdlib.h>
  115715. #include <math.h>
  115716. #include <string.h>
  115717. /*** Start of inlined file: masking.h ***/
  115718. #ifndef _V_MASKING_H_
  115719. #define _V_MASKING_H_
  115720. /* more detailed ATH; the bass if flat to save stressing the floor
  115721. overly for only a bin or two of savings. */
  115722. #define MAX_ATH 88
  115723. static float ATH[]={
  115724. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  115725. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  115726. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  115727. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  115728. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  115729. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  115730. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  115731. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  115732. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  115733. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  115734. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  115735. };
  115736. /* The tone masking curves from Ehmer's and Fielder's papers have been
  115737. replaced by an empirically collected data set. The previously
  115738. published values were, far too often, simply on crack. */
  115739. #define EHMER_OFFSET 16
  115740. #define EHMER_MAX 56
  115741. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  115742. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  115743. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  115744. for collection of these curves) */
  115745. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  115746. /* 62.5 Hz */
  115747. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  115748. -60, -60, -60, -60, -62, -62, -65, -73,
  115749. -69, -68, -68, -67, -70, -70, -72, -74,
  115750. -75, -79, -79, -80, -83, -88, -93, -100,
  115751. -110, -999, -999, -999, -999, -999, -999, -999,
  115752. -999, -999, -999, -999, -999, -999, -999, -999,
  115753. -999, -999, -999, -999, -999, -999, -999, -999},
  115754. { -48, -48, -48, -48, -48, -48, -48, -48,
  115755. -48, -48, -48, -48, -48, -53, -61, -66,
  115756. -66, -68, -67, -70, -76, -76, -72, -73,
  115757. -75, -76, -78, -79, -83, -88, -93, -100,
  115758. -110, -999, -999, -999, -999, -999, -999, -999,
  115759. -999, -999, -999, -999, -999, -999, -999, -999,
  115760. -999, -999, -999, -999, -999, -999, -999, -999},
  115761. { -37, -37, -37, -37, -37, -37, -37, -37,
  115762. -38, -40, -42, -46, -48, -53, -55, -62,
  115763. -65, -58, -56, -56, -61, -60, -65, -67,
  115764. -69, -71, -77, -77, -78, -80, -82, -84,
  115765. -88, -93, -98, -106, -112, -999, -999, -999,
  115766. -999, -999, -999, -999, -999, -999, -999, -999,
  115767. -999, -999, -999, -999, -999, -999, -999, -999},
  115768. { -25, -25, -25, -25, -25, -25, -25, -25,
  115769. -25, -26, -27, -29, -32, -38, -48, -52,
  115770. -52, -50, -48, -48, -51, -52, -54, -60,
  115771. -67, -67, -66, -68, -69, -73, -73, -76,
  115772. -80, -81, -81, -85, -85, -86, -88, -93,
  115773. -100, -110, -999, -999, -999, -999, -999, -999,
  115774. -999, -999, -999, -999, -999, -999, -999, -999},
  115775. { -16, -16, -16, -16, -16, -16, -16, -16,
  115776. -17, -19, -20, -22, -26, -28, -31, -40,
  115777. -47, -39, -39, -40, -42, -43, -47, -51,
  115778. -57, -52, -55, -55, -60, -58, -62, -63,
  115779. -70, -67, -69, -72, -73, -77, -80, -82,
  115780. -83, -87, -90, -94, -98, -104, -115, -999,
  115781. -999, -999, -999, -999, -999, -999, -999, -999},
  115782. { -8, -8, -8, -8, -8, -8, -8, -8,
  115783. -8, -8, -10, -11, -15, -19, -25, -30,
  115784. -34, -31, -30, -31, -29, -32, -35, -42,
  115785. -48, -42, -44, -46, -50, -50, -51, -52,
  115786. -59, -54, -55, -55, -58, -62, -63, -66,
  115787. -72, -73, -76, -75, -78, -80, -80, -81,
  115788. -84, -88, -90, -94, -98, -101, -106, -110}},
  115789. /* 88Hz */
  115790. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  115791. -66, -66, -66, -66, -66, -67, -67, -67,
  115792. -76, -72, -71, -74, -76, -76, -75, -78,
  115793. -79, -79, -81, -83, -86, -89, -93, -97,
  115794. -100, -105, -110, -999, -999, -999, -999, -999,
  115795. -999, -999, -999, -999, -999, -999, -999, -999,
  115796. -999, -999, -999, -999, -999, -999, -999, -999},
  115797. { -47, -47, -47, -47, -47, -47, -47, -47,
  115798. -47, -47, -47, -48, -51, -55, -59, -66,
  115799. -66, -66, -67, -66, -68, -69, -70, -74,
  115800. -79, -77, -77, -78, -80, -81, -82, -84,
  115801. -86, -88, -91, -95, -100, -108, -116, -999,
  115802. -999, -999, -999, -999, -999, -999, -999, -999,
  115803. -999, -999, -999, -999, -999, -999, -999, -999},
  115804. { -36, -36, -36, -36, -36, -36, -36, -36,
  115805. -36, -37, -37, -41, -44, -48, -51, -58,
  115806. -62, -60, -57, -59, -59, -60, -63, -65,
  115807. -72, -71, -70, -72, -74, -77, -76, -78,
  115808. -81, -81, -80, -83, -86, -91, -96, -100,
  115809. -105, -110, -999, -999, -999, -999, -999, -999,
  115810. -999, -999, -999, -999, -999, -999, -999, -999},
  115811. { -28, -28, -28, -28, -28, -28, -28, -28,
  115812. -28, -30, -32, -32, -33, -35, -41, -49,
  115813. -50, -49, -47, -48, -48, -52, -51, -57,
  115814. -65, -61, -59, -61, -64, -69, -70, -74,
  115815. -77, -77, -78, -81, -84, -85, -87, -90,
  115816. -92, -96, -100, -107, -112, -999, -999, -999,
  115817. -999, -999, -999, -999, -999, -999, -999, -999},
  115818. { -19, -19, -19, -19, -19, -19, -19, -19,
  115819. -20, -21, -23, -27, -30, -35, -36, -41,
  115820. -46, -44, -42, -40, -41, -41, -43, -48,
  115821. -55, -53, -52, -53, -56, -59, -58, -60,
  115822. -67, -66, -69, -71, -72, -75, -79, -81,
  115823. -84, -87, -90, -93, -97, -101, -107, -114,
  115824. -999, -999, -999, -999, -999, -999, -999, -999},
  115825. { -9, -9, -9, -9, -9, -9, -9, -9,
  115826. -11, -12, -12, -15, -16, -20, -23, -30,
  115827. -37, -34, -33, -34, -31, -32, -32, -38,
  115828. -47, -44, -41, -40, -47, -49, -46, -46,
  115829. -58, -50, -50, -54, -58, -62, -64, -67,
  115830. -67, -70, -72, -76, -79, -83, -87, -91,
  115831. -96, -100, -104, -110, -999, -999, -999, -999}},
  115832. /* 125 Hz */
  115833. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  115834. -62, -62, -63, -64, -66, -67, -66, -68,
  115835. -75, -72, -76, -75, -76, -78, -79, -82,
  115836. -84, -85, -90, -94, -101, -110, -999, -999,
  115837. -999, -999, -999, -999, -999, -999, -999, -999,
  115838. -999, -999, -999, -999, -999, -999, -999, -999,
  115839. -999, -999, -999, -999, -999, -999, -999, -999},
  115840. { -59, -59, -59, -59, -59, -59, -59, -59,
  115841. -59, -59, -59, -60, -60, -61, -63, -66,
  115842. -71, -68, -70, -70, -71, -72, -72, -75,
  115843. -81, -78, -79, -82, -83, -86, -90, -97,
  115844. -103, -113, -999, -999, -999, -999, -999, -999,
  115845. -999, -999, -999, -999, -999, -999, -999, -999,
  115846. -999, -999, -999, -999, -999, -999, -999, -999},
  115847. { -53, -53, -53, -53, -53, -53, -53, -53,
  115848. -53, -54, -55, -57, -56, -57, -55, -61,
  115849. -65, -60, -60, -62, -63, -63, -66, -68,
  115850. -74, -73, -75, -75, -78, -80, -80, -82,
  115851. -85, -90, -96, -101, -108, -999, -999, -999,
  115852. -999, -999, -999, -999, -999, -999, -999, -999,
  115853. -999, -999, -999, -999, -999, -999, -999, -999},
  115854. { -46, -46, -46, -46, -46, -46, -46, -46,
  115855. -46, -46, -47, -47, -47, -47, -48, -51,
  115856. -57, -51, -49, -50, -51, -53, -54, -59,
  115857. -66, -60, -62, -67, -67, -70, -72, -75,
  115858. -76, -78, -81, -85, -88, -94, -97, -104,
  115859. -112, -999, -999, -999, -999, -999, -999, -999,
  115860. -999, -999, -999, -999, -999, -999, -999, -999},
  115861. { -36, -36, -36, -36, -36, -36, -36, -36,
  115862. -39, -41, -42, -42, -39, -38, -41, -43,
  115863. -52, -44, -40, -39, -37, -37, -40, -47,
  115864. -54, -50, -48, -50, -55, -61, -59, -62,
  115865. -66, -66, -66, -69, -69, -73, -74, -74,
  115866. -75, -77, -79, -82, -87, -91, -95, -100,
  115867. -108, -115, -999, -999, -999, -999, -999, -999},
  115868. { -28, -26, -24, -22, -20, -20, -23, -29,
  115869. -30, -31, -28, -27, -28, -28, -28, -35,
  115870. -40, -33, -32, -29, -30, -30, -30, -37,
  115871. -45, -41, -37, -38, -45, -47, -47, -48,
  115872. -53, -49, -48, -50, -49, -49, -51, -52,
  115873. -58, -56, -57, -56, -60, -61, -62, -70,
  115874. -72, -74, -78, -83, -88, -93, -100, -106}},
  115875. /* 177 Hz */
  115876. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115877. -999, -110, -105, -100, -95, -91, -87, -83,
  115878. -80, -78, -76, -78, -78, -81, -83, -85,
  115879. -86, -85, -86, -87, -90, -97, -107, -999,
  115880. -999, -999, -999, -999, -999, -999, -999, -999,
  115881. -999, -999, -999, -999, -999, -999, -999, -999,
  115882. -999, -999, -999, -999, -999, -999, -999, -999},
  115883. {-999, -999, -999, -110, -105, -100, -95, -90,
  115884. -85, -81, -77, -73, -70, -67, -67, -68,
  115885. -75, -73, -70, -69, -70, -72, -75, -79,
  115886. -84, -83, -84, -86, -88, -89, -89, -93,
  115887. -98, -105, -112, -999, -999, -999, -999, -999,
  115888. -999, -999, -999, -999, -999, -999, -999, -999,
  115889. -999, -999, -999, -999, -999, -999, -999, -999},
  115890. {-105, -100, -95, -90, -85, -80, -76, -71,
  115891. -68, -68, -65, -63, -63, -62, -62, -64,
  115892. -65, -64, -61, -62, -63, -64, -66, -68,
  115893. -73, -73, -74, -75, -76, -81, -83, -85,
  115894. -88, -89, -92, -95, -100, -108, -999, -999,
  115895. -999, -999, -999, -999, -999, -999, -999, -999,
  115896. -999, -999, -999, -999, -999, -999, -999, -999},
  115897. { -80, -75, -71, -68, -65, -63, -62, -61,
  115898. -61, -61, -61, -59, -56, -57, -53, -50,
  115899. -58, -52, -50, -50, -52, -53, -54, -58,
  115900. -67, -63, -67, -68, -72, -75, -78, -80,
  115901. -81, -81, -82, -85, -89, -90, -93, -97,
  115902. -101, -107, -114, -999, -999, -999, -999, -999,
  115903. -999, -999, -999, -999, -999, -999, -999, -999},
  115904. { -65, -61, -59, -57, -56, -55, -55, -56,
  115905. -56, -57, -55, -53, -52, -47, -44, -44,
  115906. -50, -44, -41, -39, -39, -42, -40, -46,
  115907. -51, -49, -50, -53, -54, -63, -60, -61,
  115908. -62, -66, -66, -66, -70, -73, -74, -75,
  115909. -76, -75, -79, -85, -89, -91, -96, -102,
  115910. -110, -999, -999, -999, -999, -999, -999, -999},
  115911. { -52, -50, -49, -49, -48, -48, -48, -49,
  115912. -50, -50, -49, -46, -43, -39, -35, -33,
  115913. -38, -36, -32, -29, -32, -32, -32, -35,
  115914. -44, -39, -38, -38, -46, -50, -45, -46,
  115915. -53, -50, -50, -50, -54, -54, -53, -53,
  115916. -56, -57, -59, -66, -70, -72, -74, -79,
  115917. -83, -85, -90, -97, -114, -999, -999, -999}},
  115918. /* 250 Hz */
  115919. {{-999, -999, -999, -999, -999, -999, -110, -105,
  115920. -100, -95, -90, -86, -80, -75, -75, -79,
  115921. -80, -79, -80, -81, -82, -88, -95, -103,
  115922. -110, -999, -999, -999, -999, -999, -999, -999,
  115923. -999, -999, -999, -999, -999, -999, -999, -999,
  115924. -999, -999, -999, -999, -999, -999, -999, -999,
  115925. -999, -999, -999, -999, -999, -999, -999, -999},
  115926. {-999, -999, -999, -999, -108, -103, -98, -93,
  115927. -88, -83, -79, -78, -75, -71, -67, -68,
  115928. -73, -73, -72, -73, -75, -77, -80, -82,
  115929. -88, -93, -100, -107, -114, -999, -999, -999,
  115930. -999, -999, -999, -999, -999, -999, -999, -999,
  115931. -999, -999, -999, -999, -999, -999, -999, -999,
  115932. -999, -999, -999, -999, -999, -999, -999, -999},
  115933. {-999, -999, -999, -110, -105, -101, -96, -90,
  115934. -86, -81, -77, -73, -69, -66, -61, -62,
  115935. -66, -64, -62, -65, -66, -70, -72, -76,
  115936. -81, -80, -84, -90, -95, -102, -110, -999,
  115937. -999, -999, -999, -999, -999, -999, -999, -999,
  115938. -999, -999, -999, -999, -999, -999, -999, -999,
  115939. -999, -999, -999, -999, -999, -999, -999, -999},
  115940. {-999, -999, -999, -107, -103, -97, -92, -88,
  115941. -83, -79, -74, -70, -66, -59, -53, -58,
  115942. -62, -55, -54, -54, -54, -58, -61, -62,
  115943. -72, -70, -72, -75, -78, -80, -81, -80,
  115944. -83, -83, -88, -93, -100, -107, -115, -999,
  115945. -999, -999, -999, -999, -999, -999, -999, -999,
  115946. -999, -999, -999, -999, -999, -999, -999, -999},
  115947. {-999, -999, -999, -105, -100, -95, -90, -85,
  115948. -80, -75, -70, -66, -62, -56, -48, -44,
  115949. -48, -46, -46, -43, -46, -48, -48, -51,
  115950. -58, -58, -59, -60, -62, -62, -61, -61,
  115951. -65, -64, -65, -68, -70, -74, -75, -78,
  115952. -81, -86, -95, -110, -999, -999, -999, -999,
  115953. -999, -999, -999, -999, -999, -999, -999, -999},
  115954. {-999, -999, -105, -100, -95, -90, -85, -80,
  115955. -75, -70, -65, -61, -55, -49, -39, -33,
  115956. -40, -35, -32, -38, -40, -33, -35, -37,
  115957. -46, -41, -45, -44, -46, -42, -45, -46,
  115958. -52, -50, -50, -50, -54, -54, -55, -57,
  115959. -62, -64, -66, -68, -70, -76, -81, -90,
  115960. -100, -110, -999, -999, -999, -999, -999, -999}},
  115961. /* 354 hz */
  115962. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115963. -105, -98, -90, -85, -82, -83, -80, -78,
  115964. -84, -79, -80, -83, -87, -89, -91, -93,
  115965. -99, -106, -117, -999, -999, -999, -999, -999,
  115966. -999, -999, -999, -999, -999, -999, -999, -999,
  115967. -999, -999, -999, -999, -999, -999, -999, -999,
  115968. -999, -999, -999, -999, -999, -999, -999, -999},
  115969. {-999, -999, -999, -999, -999, -999, -999, -999,
  115970. -105, -98, -90, -85, -80, -75, -70, -68,
  115971. -74, -72, -74, -77, -80, -82, -85, -87,
  115972. -92, -89, -91, -95, -100, -106, -112, -999,
  115973. -999, -999, -999, -999, -999, -999, -999, -999,
  115974. -999, -999, -999, -999, -999, -999, -999, -999,
  115975. -999, -999, -999, -999, -999, -999, -999, -999},
  115976. {-999, -999, -999, -999, -999, -999, -999, -999,
  115977. -105, -98, -90, -83, -75, -71, -63, -64,
  115978. -67, -62, -64, -67, -70, -73, -77, -81,
  115979. -84, -83, -85, -89, -90, -93, -98, -104,
  115980. -109, -114, -999, -999, -999, -999, -999, -999,
  115981. -999, -999, -999, -999, -999, -999, -999, -999,
  115982. -999, -999, -999, -999, -999, -999, -999, -999},
  115983. {-999, -999, -999, -999, -999, -999, -999, -999,
  115984. -103, -96, -88, -81, -75, -68, -58, -54,
  115985. -56, -54, -56, -56, -58, -60, -63, -66,
  115986. -74, -69, -72, -72, -75, -74, -77, -81,
  115987. -81, -82, -84, -87, -93, -96, -99, -104,
  115988. -110, -999, -999, -999, -999, -999, -999, -999,
  115989. -999, -999, -999, -999, -999, -999, -999, -999},
  115990. {-999, -999, -999, -999, -999, -108, -102, -96,
  115991. -91, -85, -80, -74, -68, -60, -51, -46,
  115992. -48, -46, -43, -45, -47, -47, -49, -48,
  115993. -56, -53, -55, -58, -57, -63, -58, -60,
  115994. -66, -64, -67, -70, -70, -74, -77, -84,
  115995. -86, -89, -91, -93, -94, -101, -109, -118,
  115996. -999, -999, -999, -999, -999, -999, -999, -999},
  115997. {-999, -999, -999, -108, -103, -98, -93, -88,
  115998. -83, -78, -73, -68, -60, -53, -44, -35,
  115999. -38, -38, -34, -34, -36, -40, -41, -44,
  116000. -51, -45, -46, -47, -46, -54, -50, -49,
  116001. -50, -50, -50, -51, -54, -57, -58, -60,
  116002. -66, -66, -66, -64, -65, -68, -77, -82,
  116003. -87, -95, -110, -999, -999, -999, -999, -999}},
  116004. /* 500 Hz */
  116005. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116006. -107, -102, -97, -92, -87, -83, -78, -75,
  116007. -82, -79, -83, -85, -89, -92, -95, -98,
  116008. -101, -105, -109, -113, -999, -999, -999, -999,
  116009. -999, -999, -999, -999, -999, -999, -999, -999,
  116010. -999, -999, -999, -999, -999, -999, -999, -999,
  116011. -999, -999, -999, -999, -999, -999, -999, -999},
  116012. {-999, -999, -999, -999, -999, -999, -999, -106,
  116013. -100, -95, -90, -86, -81, -78, -74, -69,
  116014. -74, -74, -76, -79, -83, -84, -86, -89,
  116015. -92, -97, -93, -100, -103, -107, -110, -999,
  116016. -999, -999, -999, -999, -999, -999, -999, -999,
  116017. -999, -999, -999, -999, -999, -999, -999, -999,
  116018. -999, -999, -999, -999, -999, -999, -999, -999},
  116019. {-999, -999, -999, -999, -999, -999, -106, -100,
  116020. -95, -90, -87, -83, -80, -75, -69, -60,
  116021. -66, -66, -68, -70, -74, -78, -79, -81,
  116022. -81, -83, -84, -87, -93, -96, -99, -103,
  116023. -107, -110, -999, -999, -999, -999, -999, -999,
  116024. -999, -999, -999, -999, -999, -999, -999, -999,
  116025. -999, -999, -999, -999, -999, -999, -999, -999},
  116026. {-999, -999, -999, -999, -999, -108, -103, -98,
  116027. -93, -89, -85, -82, -78, -71, -62, -55,
  116028. -58, -58, -54, -54, -55, -59, -61, -62,
  116029. -70, -66, -66, -67, -70, -72, -75, -78,
  116030. -84, -84, -84, -88, -91, -90, -95, -98,
  116031. -102, -103, -106, -110, -999, -999, -999, -999,
  116032. -999, -999, -999, -999, -999, -999, -999, -999},
  116033. {-999, -999, -999, -999, -108, -103, -98, -94,
  116034. -90, -87, -82, -79, -73, -67, -58, -47,
  116035. -50, -45, -41, -45, -48, -44, -44, -49,
  116036. -54, -51, -48, -47, -49, -50, -51, -57,
  116037. -58, -60, -63, -69, -70, -69, -71, -74,
  116038. -78, -82, -90, -95, -101, -105, -110, -999,
  116039. -999, -999, -999, -999, -999, -999, -999, -999},
  116040. {-999, -999, -999, -105, -101, -97, -93, -90,
  116041. -85, -80, -77, -72, -65, -56, -48, -37,
  116042. -40, -36, -34, -40, -50, -47, -38, -41,
  116043. -47, -38, -35, -39, -38, -43, -40, -45,
  116044. -50, -45, -44, -47, -50, -55, -48, -48,
  116045. -52, -66, -70, -76, -82, -90, -97, -105,
  116046. -110, -999, -999, -999, -999, -999, -999, -999}},
  116047. /* 707 Hz */
  116048. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116049. -999, -108, -103, -98, -93, -86, -79, -76,
  116050. -83, -81, -85, -87, -89, -93, -98, -102,
  116051. -107, -112, -999, -999, -999, -999, -999, -999,
  116052. -999, -999, -999, -999, -999, -999, -999, -999,
  116053. -999, -999, -999, -999, -999, -999, -999, -999,
  116054. -999, -999, -999, -999, -999, -999, -999, -999},
  116055. {-999, -999, -999, -999, -999, -999, -999, -999,
  116056. -999, -108, -103, -98, -93, -86, -79, -71,
  116057. -77, -74, -77, -79, -81, -84, -85, -90,
  116058. -92, -93, -92, -98, -101, -108, -112, -999,
  116059. -999, -999, -999, -999, -999, -999, -999, -999,
  116060. -999, -999, -999, -999, -999, -999, -999, -999,
  116061. -999, -999, -999, -999, -999, -999, -999, -999},
  116062. {-999, -999, -999, -999, -999, -999, -999, -999,
  116063. -108, -103, -98, -93, -87, -78, -68, -65,
  116064. -66, -62, -65, -67, -70, -73, -75, -78,
  116065. -82, -82, -83, -84, -91, -93, -98, -102,
  116066. -106, -110, -999, -999, -999, -999, -999, -999,
  116067. -999, -999, -999, -999, -999, -999, -999, -999,
  116068. -999, -999, -999, -999, -999, -999, -999, -999},
  116069. {-999, -999, -999, -999, -999, -999, -999, -999,
  116070. -105, -100, -95, -90, -82, -74, -62, -57,
  116071. -58, -56, -51, -52, -52, -54, -54, -58,
  116072. -66, -59, -60, -63, -66, -69, -73, -79,
  116073. -83, -84, -80, -81, -81, -82, -88, -92,
  116074. -98, -105, -113, -999, -999, -999, -999, -999,
  116075. -999, -999, -999, -999, -999, -999, -999, -999},
  116076. {-999, -999, -999, -999, -999, -999, -999, -107,
  116077. -102, -97, -92, -84, -79, -69, -57, -47,
  116078. -52, -47, -44, -45, -50, -52, -42, -42,
  116079. -53, -43, -43, -48, -51, -56, -55, -52,
  116080. -57, -59, -61, -62, -67, -71, -78, -83,
  116081. -86, -94, -98, -103, -110, -999, -999, -999,
  116082. -999, -999, -999, -999, -999, -999, -999, -999},
  116083. {-999, -999, -999, -999, -999, -999, -105, -100,
  116084. -95, -90, -84, -78, -70, -61, -51, -41,
  116085. -40, -38, -40, -46, -52, -51, -41, -40,
  116086. -46, -40, -38, -38, -41, -46, -41, -46,
  116087. -47, -43, -43, -45, -41, -45, -56, -67,
  116088. -68, -83, -87, -90, -95, -102, -107, -113,
  116089. -999, -999, -999, -999, -999, -999, -999, -999}},
  116090. /* 1000 Hz */
  116091. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116092. -999, -109, -105, -101, -96, -91, -84, -77,
  116093. -82, -82, -85, -89, -94, -100, -106, -110,
  116094. -999, -999, -999, -999, -999, -999, -999, -999,
  116095. -999, -999, -999, -999, -999, -999, -999, -999,
  116096. -999, -999, -999, -999, -999, -999, -999, -999,
  116097. -999, -999, -999, -999, -999, -999, -999, -999},
  116098. {-999, -999, -999, -999, -999, -999, -999, -999,
  116099. -999, -106, -103, -98, -92, -85, -80, -71,
  116100. -75, -72, -76, -80, -84, -86, -89, -93,
  116101. -100, -107, -113, -999, -999, -999, -999, -999,
  116102. -999, -999, -999, -999, -999, -999, -999, -999,
  116103. -999, -999, -999, -999, -999, -999, -999, -999,
  116104. -999, -999, -999, -999, -999, -999, -999, -999},
  116105. {-999, -999, -999, -999, -999, -999, -999, -107,
  116106. -104, -101, -97, -92, -88, -84, -80, -64,
  116107. -66, -63, -64, -66, -69, -73, -77, -83,
  116108. -83, -86, -91, -98, -104, -111, -999, -999,
  116109. -999, -999, -999, -999, -999, -999, -999, -999,
  116110. -999, -999, -999, -999, -999, -999, -999, -999,
  116111. -999, -999, -999, -999, -999, -999, -999, -999},
  116112. {-999, -999, -999, -999, -999, -999, -999, -107,
  116113. -104, -101, -97, -92, -90, -84, -74, -57,
  116114. -58, -52, -55, -54, -50, -52, -50, -52,
  116115. -63, -62, -69, -76, -77, -78, -78, -79,
  116116. -82, -88, -94, -100, -106, -111, -999, -999,
  116117. -999, -999, -999, -999, -999, -999, -999, -999,
  116118. -999, -999, -999, -999, -999, -999, -999, -999},
  116119. {-999, -999, -999, -999, -999, -999, -106, -102,
  116120. -98, -95, -90, -85, -83, -78, -70, -50,
  116121. -50, -41, -44, -49, -47, -50, -50, -44,
  116122. -55, -46, -47, -48, -48, -54, -49, -49,
  116123. -58, -62, -71, -81, -87, -92, -97, -102,
  116124. -108, -114, -999, -999, -999, -999, -999, -999,
  116125. -999, -999, -999, -999, -999, -999, -999, -999},
  116126. {-999, -999, -999, -999, -999, -999, -106, -102,
  116127. -98, -95, -90, -85, -83, -78, -70, -45,
  116128. -43, -41, -47, -50, -51, -50, -49, -45,
  116129. -47, -41, -44, -41, -39, -43, -38, -37,
  116130. -40, -41, -44, -50, -58, -65, -73, -79,
  116131. -85, -92, -97, -101, -105, -109, -113, -999,
  116132. -999, -999, -999, -999, -999, -999, -999, -999}},
  116133. /* 1414 Hz */
  116134. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116135. -999, -999, -999, -107, -100, -95, -87, -81,
  116136. -85, -83, -88, -93, -100, -107, -114, -999,
  116137. -999, -999, -999, -999, -999, -999, -999, -999,
  116138. -999, -999, -999, -999, -999, -999, -999, -999,
  116139. -999, -999, -999, -999, -999, -999, -999, -999,
  116140. -999, -999, -999, -999, -999, -999, -999, -999},
  116141. {-999, -999, -999, -999, -999, -999, -999, -999,
  116142. -999, -999, -107, -101, -95, -88, -83, -76,
  116143. -73, -72, -79, -84, -90, -95, -100, -105,
  116144. -110, -115, -999, -999, -999, -999, -999, -999,
  116145. -999, -999, -999, -999, -999, -999, -999, -999,
  116146. -999, -999, -999, -999, -999, -999, -999, -999,
  116147. -999, -999, -999, -999, -999, -999, -999, -999},
  116148. {-999, -999, -999, -999, -999, -999, -999, -999,
  116149. -999, -999, -104, -98, -92, -87, -81, -70,
  116150. -65, -62, -67, -71, -74, -80, -85, -91,
  116151. -95, -99, -103, -108, -111, -114, -999, -999,
  116152. -999, -999, -999, -999, -999, -999, -999, -999,
  116153. -999, -999, -999, -999, -999, -999, -999, -999,
  116154. -999, -999, -999, -999, -999, -999, -999, -999},
  116155. {-999, -999, -999, -999, -999, -999, -999, -999,
  116156. -999, -999, -103, -97, -90, -85, -76, -60,
  116157. -56, -54, -60, -62, -61, -56, -63, -65,
  116158. -73, -74, -77, -75, -78, -81, -86, -87,
  116159. -88, -91, -94, -98, -103, -110, -999, -999,
  116160. -999, -999, -999, -999, -999, -999, -999, -999,
  116161. -999, -999, -999, -999, -999, -999, -999, -999},
  116162. {-999, -999, -999, -999, -999, -999, -999, -105,
  116163. -100, -97, -92, -86, -81, -79, -70, -57,
  116164. -51, -47, -51, -58, -60, -56, -53, -50,
  116165. -58, -52, -50, -50, -53, -55, -64, -69,
  116166. -71, -85, -82, -78, -81, -85, -95, -102,
  116167. -112, -999, -999, -999, -999, -999, -999, -999,
  116168. -999, -999, -999, -999, -999, -999, -999, -999},
  116169. {-999, -999, -999, -999, -999, -999, -999, -105,
  116170. -100, -97, -92, -85, -83, -79, -72, -49,
  116171. -40, -43, -43, -54, -56, -51, -50, -40,
  116172. -43, -38, -36, -35, -37, -38, -37, -44,
  116173. -54, -60, -57, -60, -70, -75, -84, -92,
  116174. -103, -112, -999, -999, -999, -999, -999, -999,
  116175. -999, -999, -999, -999, -999, -999, -999, -999}},
  116176. /* 2000 Hz */
  116177. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116178. -999, -999, -999, -110, -102, -95, -89, -82,
  116179. -83, -84, -90, -92, -99, -107, -113, -999,
  116180. -999, -999, -999, -999, -999, -999, -999, -999,
  116181. -999, -999, -999, -999, -999, -999, -999, -999,
  116182. -999, -999, -999, -999, -999, -999, -999, -999,
  116183. -999, -999, -999, -999, -999, -999, -999, -999},
  116184. {-999, -999, -999, -999, -999, -999, -999, -999,
  116185. -999, -999, -107, -101, -95, -89, -83, -72,
  116186. -74, -78, -85, -88, -88, -90, -92, -98,
  116187. -105, -111, -999, -999, -999, -999, -999, -999,
  116188. -999, -999, -999, -999, -999, -999, -999, -999,
  116189. -999, -999, -999, -999, -999, -999, -999, -999,
  116190. -999, -999, -999, -999, -999, -999, -999, -999},
  116191. {-999, -999, -999, -999, -999, -999, -999, -999,
  116192. -999, -109, -103, -97, -93, -87, -81, -70,
  116193. -70, -67, -75, -73, -76, -79, -81, -83,
  116194. -88, -89, -97, -103, -110, -999, -999, -999,
  116195. -999, -999, -999, -999, -999, -999, -999, -999,
  116196. -999, -999, -999, -999, -999, -999, -999, -999,
  116197. -999, -999, -999, -999, -999, -999, -999, -999},
  116198. {-999, -999, -999, -999, -999, -999, -999, -999,
  116199. -999, -107, -100, -94, -88, -83, -75, -63,
  116200. -59, -59, -63, -66, -60, -62, -67, -67,
  116201. -77, -76, -81, -88, -86, -92, -96, -102,
  116202. -109, -116, -999, -999, -999, -999, -999, -999,
  116203. -999, -999, -999, -999, -999, -999, -999, -999,
  116204. -999, -999, -999, -999, -999, -999, -999, -999},
  116205. {-999, -999, -999, -999, -999, -999, -999, -999,
  116206. -999, -105, -98, -92, -86, -81, -73, -56,
  116207. -52, -47, -55, -60, -58, -52, -51, -45,
  116208. -49, -50, -53, -54, -61, -71, -70, -69,
  116209. -78, -79, -87, -90, -96, -104, -112, -999,
  116210. -999, -999, -999, -999, -999, -999, -999, -999,
  116211. -999, -999, -999, -999, -999, -999, -999, -999},
  116212. {-999, -999, -999, -999, -999, -999, -999, -999,
  116213. -999, -103, -96, -90, -86, -78, -70, -51,
  116214. -42, -47, -48, -55, -54, -54, -53, -42,
  116215. -35, -28, -33, -38, -37, -44, -47, -49,
  116216. -54, -63, -68, -78, -82, -89, -94, -99,
  116217. -104, -109, -114, -999, -999, -999, -999, -999,
  116218. -999, -999, -999, -999, -999, -999, -999, -999}},
  116219. /* 2828 Hz */
  116220. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116221. -999, -999, -999, -999, -110, -100, -90, -79,
  116222. -85, -81, -82, -82, -89, -94, -99, -103,
  116223. -109, -115, -999, -999, -999, -999, -999, -999,
  116224. -999, -999, -999, -999, -999, -999, -999, -999,
  116225. -999, -999, -999, -999, -999, -999, -999, -999,
  116226. -999, -999, -999, -999, -999, -999, -999, -999},
  116227. {-999, -999, -999, -999, -999, -999, -999, -999,
  116228. -999, -999, -999, -999, -105, -97, -85, -72,
  116229. -74, -70, -70, -70, -76, -85, -91, -93,
  116230. -97, -103, -109, -115, -999, -999, -999, -999,
  116231. -999, -999, -999, -999, -999, -999, -999, -999,
  116232. -999, -999, -999, -999, -999, -999, -999, -999,
  116233. -999, -999, -999, -999, -999, -999, -999, -999},
  116234. {-999, -999, -999, -999, -999, -999, -999, -999,
  116235. -999, -999, -999, -999, -112, -93, -81, -68,
  116236. -62, -60, -60, -57, -63, -70, -77, -82,
  116237. -90, -93, -98, -104, -109, -113, -999, -999,
  116238. -999, -999, -999, -999, -999, -999, -999, -999,
  116239. -999, -999, -999, -999, -999, -999, -999, -999,
  116240. -999, -999, -999, -999, -999, -999, -999, -999},
  116241. {-999, -999, -999, -999, -999, -999, -999, -999,
  116242. -999, -999, -999, -113, -100, -93, -84, -63,
  116243. -58, -48, -53, -54, -52, -52, -57, -64,
  116244. -66, -76, -83, -81, -85, -85, -90, -95,
  116245. -98, -101, -103, -106, -108, -111, -999, -999,
  116246. -999, -999, -999, -999, -999, -999, -999, -999,
  116247. -999, -999, -999, -999, -999, -999, -999, -999},
  116248. {-999, -999, -999, -999, -999, -999, -999, -999,
  116249. -999, -999, -999, -105, -95, -86, -74, -53,
  116250. -50, -38, -43, -49, -43, -42, -39, -39,
  116251. -46, -52, -57, -56, -72, -69, -74, -81,
  116252. -87, -92, -94, -97, -99, -102, -105, -108,
  116253. -999, -999, -999, -999, -999, -999, -999, -999,
  116254. -999, -999, -999, -999, -999, -999, -999, -999},
  116255. {-999, -999, -999, -999, -999, -999, -999, -999,
  116256. -999, -999, -108, -99, -90, -76, -66, -45,
  116257. -43, -41, -44, -47, -43, -47, -40, -30,
  116258. -31, -31, -39, -33, -40, -41, -43, -53,
  116259. -59, -70, -73, -77, -79, -82, -84, -87,
  116260. -999, -999, -999, -999, -999, -999, -999, -999,
  116261. -999, -999, -999, -999, -999, -999, -999, -999}},
  116262. /* 4000 Hz */
  116263. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116264. -999, -999, -999, -999, -999, -110, -91, -76,
  116265. -75, -85, -93, -98, -104, -110, -999, -999,
  116266. -999, -999, -999, -999, -999, -999, -999, -999,
  116267. -999, -999, -999, -999, -999, -999, -999, -999,
  116268. -999, -999, -999, -999, -999, -999, -999, -999,
  116269. -999, -999, -999, -999, -999, -999, -999, -999},
  116270. {-999, -999, -999, -999, -999, -999, -999, -999,
  116271. -999, -999, -999, -999, -999, -110, -91, -70,
  116272. -70, -75, -86, -89, -94, -98, -101, -106,
  116273. -110, -999, -999, -999, -999, -999, -999, -999,
  116274. -999, -999, -999, -999, -999, -999, -999, -999,
  116275. -999, -999, -999, -999, -999, -999, -999, -999,
  116276. -999, -999, -999, -999, -999, -999, -999, -999},
  116277. {-999, -999, -999, -999, -999, -999, -999, -999,
  116278. -999, -999, -999, -999, -110, -95, -80, -60,
  116279. -65, -64, -74, -83, -88, -91, -95, -99,
  116280. -103, -107, -110, -999, -999, -999, -999, -999,
  116281. -999, -999, -999, -999, -999, -999, -999, -999,
  116282. -999, -999, -999, -999, -999, -999, -999, -999,
  116283. -999, -999, -999, -999, -999, -999, -999, -999},
  116284. {-999, -999, -999, -999, -999, -999, -999, -999,
  116285. -999, -999, -999, -999, -110, -95, -80, -58,
  116286. -55, -49, -66, -68, -71, -78, -78, -80,
  116287. -88, -85, -89, -97, -100, -105, -110, -999,
  116288. -999, -999, -999, -999, -999, -999, -999, -999,
  116289. -999, -999, -999, -999, -999, -999, -999, -999,
  116290. -999, -999, -999, -999, -999, -999, -999, -999},
  116291. {-999, -999, -999, -999, -999, -999, -999, -999,
  116292. -999, -999, -999, -999, -110, -95, -80, -53,
  116293. -52, -41, -59, -59, -49, -58, -56, -63,
  116294. -86, -79, -90, -93, -98, -103, -107, -112,
  116295. -999, -999, -999, -999, -999, -999, -999, -999,
  116296. -999, -999, -999, -999, -999, -999, -999, -999,
  116297. -999, -999, -999, -999, -999, -999, -999, -999},
  116298. {-999, -999, -999, -999, -999, -999, -999, -999,
  116299. -999, -999, -999, -110, -97, -91, -73, -45,
  116300. -40, -33, -53, -61, -49, -54, -50, -50,
  116301. -60, -52, -67, -74, -81, -92, -96, -100,
  116302. -105, -110, -999, -999, -999, -999, -999, -999,
  116303. -999, -999, -999, -999, -999, -999, -999, -999,
  116304. -999, -999, -999, -999, -999, -999, -999, -999}},
  116305. /* 5657 Hz */
  116306. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116307. -999, -999, -999, -113, -106, -99, -92, -77,
  116308. -80, -88, -97, -106, -115, -999, -999, -999,
  116309. -999, -999, -999, -999, -999, -999, -999, -999,
  116310. -999, -999, -999, -999, -999, -999, -999, -999,
  116311. -999, -999, -999, -999, -999, -999, -999, -999,
  116312. -999, -999, -999, -999, -999, -999, -999, -999},
  116313. {-999, -999, -999, -999, -999, -999, -999, -999,
  116314. -999, -999, -116, -109, -102, -95, -89, -74,
  116315. -72, -88, -87, -95, -102, -109, -116, -999,
  116316. -999, -999, -999, -999, -999, -999, -999, -999,
  116317. -999, -999, -999, -999, -999, -999, -999, -999,
  116318. -999, -999, -999, -999, -999, -999, -999, -999,
  116319. -999, -999, -999, -999, -999, -999, -999, -999},
  116320. {-999, -999, -999, -999, -999, -999, -999, -999,
  116321. -999, -999, -116, -109, -102, -95, -89, -75,
  116322. -66, -74, -77, -78, -86, -87, -90, -96,
  116323. -105, -115, -999, -999, -999, -999, -999, -999,
  116324. -999, -999, -999, -999, -999, -999, -999, -999,
  116325. -999, -999, -999, -999, -999, -999, -999, -999,
  116326. -999, -999, -999, -999, -999, -999, -999, -999},
  116327. {-999, -999, -999, -999, -999, -999, -999, -999,
  116328. -999, -999, -115, -108, -101, -94, -88, -66,
  116329. -56, -61, -70, -65, -78, -72, -83, -84,
  116330. -93, -98, -105, -110, -999, -999, -999, -999,
  116331. -999, -999, -999, -999, -999, -999, -999, -999,
  116332. -999, -999, -999, -999, -999, -999, -999, -999,
  116333. -999, -999, -999, -999, -999, -999, -999, -999},
  116334. {-999, -999, -999, -999, -999, -999, -999, -999,
  116335. -999, -999, -110, -105, -95, -89, -82, -57,
  116336. -52, -52, -59, -56, -59, -58, -69, -67,
  116337. -88, -82, -82, -89, -94, -100, -108, -999,
  116338. -999, -999, -999, -999, -999, -999, -999, -999,
  116339. -999, -999, -999, -999, -999, -999, -999, -999,
  116340. -999, -999, -999, -999, -999, -999, -999, -999},
  116341. {-999, -999, -999, -999, -999, -999, -999, -999,
  116342. -999, -110, -101, -96, -90, -83, -77, -54,
  116343. -43, -38, -50, -48, -52, -48, -42, -42,
  116344. -51, -52, -53, -59, -65, -71, -78, -85,
  116345. -95, -999, -999, -999, -999, -999, -999, -999,
  116346. -999, -999, -999, -999, -999, -999, -999, -999,
  116347. -999, -999, -999, -999, -999, -999, -999, -999}},
  116348. /* 8000 Hz */
  116349. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116350. -999, -999, -999, -999, -120, -105, -86, -68,
  116351. -78, -79, -90, -100, -110, -999, -999, -999,
  116352. -999, -999, -999, -999, -999, -999, -999, -999,
  116353. -999, -999, -999, -999, -999, -999, -999, -999,
  116354. -999, -999, -999, -999, -999, -999, -999, -999,
  116355. -999, -999, -999, -999, -999, -999, -999, -999},
  116356. {-999, -999, -999, -999, -999, -999, -999, -999,
  116357. -999, -999, -999, -999, -120, -105, -86, -66,
  116358. -73, -77, -88, -96, -105, -115, -999, -999,
  116359. -999, -999, -999, -999, -999, -999, -999, -999,
  116360. -999, -999, -999, -999, -999, -999, -999, -999,
  116361. -999, -999, -999, -999, -999, -999, -999, -999,
  116362. -999, -999, -999, -999, -999, -999, -999, -999},
  116363. {-999, -999, -999, -999, -999, -999, -999, -999,
  116364. -999, -999, -999, -120, -105, -92, -80, -61,
  116365. -64, -68, -80, -87, -92, -100, -110, -999,
  116366. -999, -999, -999, -999, -999, -999, -999, -999,
  116367. -999, -999, -999, -999, -999, -999, -999, -999,
  116368. -999, -999, -999, -999, -999, -999, -999, -999,
  116369. -999, -999, -999, -999, -999, -999, -999, -999},
  116370. {-999, -999, -999, -999, -999, -999, -999, -999,
  116371. -999, -999, -999, -120, -104, -91, -79, -52,
  116372. -60, -54, -64, -69, -77, -80, -82, -84,
  116373. -85, -87, -88, -90, -999, -999, -999, -999,
  116374. -999, -999, -999, -999, -999, -999, -999, -999,
  116375. -999, -999, -999, -999, -999, -999, -999, -999,
  116376. -999, -999, -999, -999, -999, -999, -999, -999},
  116377. {-999, -999, -999, -999, -999, -999, -999, -999,
  116378. -999, -999, -999, -118, -100, -87, -77, -49,
  116379. -50, -44, -58, -61, -61, -67, -65, -62,
  116380. -62, -62, -65, -68, -999, -999, -999, -999,
  116381. -999, -999, -999, -999, -999, -999, -999, -999,
  116382. -999, -999, -999, -999, -999, -999, -999, -999,
  116383. -999, -999, -999, -999, -999, -999, -999, -999},
  116384. {-999, -999, -999, -999, -999, -999, -999, -999,
  116385. -999, -999, -999, -115, -98, -84, -62, -49,
  116386. -44, -38, -46, -49, -49, -46, -39, -37,
  116387. -39, -40, -42, -43, -999, -999, -999, -999,
  116388. -999, -999, -999, -999, -999, -999, -999, -999,
  116389. -999, -999, -999, -999, -999, -999, -999, -999,
  116390. -999, -999, -999, -999, -999, -999, -999, -999}},
  116391. /* 11314 Hz */
  116392. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116393. -999, -999, -999, -999, -999, -110, -88, -74,
  116394. -77, -82, -82, -85, -90, -94, -99, -104,
  116395. -999, -999, -999, -999, -999, -999, -999, -999,
  116396. -999, -999, -999, -999, -999, -999, -999, -999,
  116397. -999, -999, -999, -999, -999, -999, -999, -999,
  116398. -999, -999, -999, -999, -999, -999, -999, -999},
  116399. {-999, -999, -999, -999, -999, -999, -999, -999,
  116400. -999, -999, -999, -999, -999, -110, -88, -66,
  116401. -70, -81, -80, -81, -84, -88, -91, -93,
  116402. -999, -999, -999, -999, -999, -999, -999, -999,
  116403. -999, -999, -999, -999, -999, -999, -999, -999,
  116404. -999, -999, -999, -999, -999, -999, -999, -999,
  116405. -999, -999, -999, -999, -999, -999, -999, -999},
  116406. {-999, -999, -999, -999, -999, -999, -999, -999,
  116407. -999, -999, -999, -999, -999, -110, -88, -61,
  116408. -63, -70, -71, -74, -77, -80, -83, -85,
  116409. -999, -999, -999, -999, -999, -999, -999, -999,
  116410. -999, -999, -999, -999, -999, -999, -999, -999,
  116411. -999, -999, -999, -999, -999, -999, -999, -999,
  116412. -999, -999, -999, -999, -999, -999, -999, -999},
  116413. {-999, -999, -999, -999, -999, -999, -999, -999,
  116414. -999, -999, -999, -999, -999, -110, -86, -62,
  116415. -63, -62, -62, -58, -52, -50, -50, -52,
  116416. -54, -999, -999, -999, -999, -999, -999, -999,
  116417. -999, -999, -999, -999, -999, -999, -999, -999,
  116418. -999, -999, -999, -999, -999, -999, -999, -999,
  116419. -999, -999, -999, -999, -999, -999, -999, -999},
  116420. {-999, -999, -999, -999, -999, -999, -999, -999,
  116421. -999, -999, -999, -999, -118, -108, -84, -53,
  116422. -50, -50, -50, -55, -47, -45, -40, -40,
  116423. -40, -999, -999, -999, -999, -999, -999, -999,
  116424. -999, -999, -999, -999, -999, -999, -999, -999,
  116425. -999, -999, -999, -999, -999, -999, -999, -999,
  116426. -999, -999, -999, -999, -999, -999, -999, -999},
  116427. {-999, -999, -999, -999, -999, -999, -999, -999,
  116428. -999, -999, -999, -999, -118, -100, -73, -43,
  116429. -37, -42, -43, -53, -38, -37, -35, -35,
  116430. -38, -999, -999, -999, -999, -999, -999, -999,
  116431. -999, -999, -999, -999, -999, -999, -999, -999,
  116432. -999, -999, -999, -999, -999, -999, -999, -999,
  116433. -999, -999, -999, -999, -999, -999, -999, -999}},
  116434. /* 16000 Hz */
  116435. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116436. -999, -999, -999, -110, -100, -91, -84, -74,
  116437. -80, -80, -80, -80, -80, -999, -999, -999,
  116438. -999, -999, -999, -999, -999, -999, -999, -999,
  116439. -999, -999, -999, -999, -999, -999, -999, -999,
  116440. -999, -999, -999, -999, -999, -999, -999, -999,
  116441. -999, -999, -999, -999, -999, -999, -999, -999},
  116442. {-999, -999, -999, -999, -999, -999, -999, -999,
  116443. -999, -999, -999, -110, -100, -91, -84, -74,
  116444. -68, -68, -68, -68, -68, -999, -999, -999,
  116445. -999, -999, -999, -999, -999, -999, -999, -999,
  116446. -999, -999, -999, -999, -999, -999, -999, -999,
  116447. -999, -999, -999, -999, -999, -999, -999, -999,
  116448. -999, -999, -999, -999, -999, -999, -999, -999},
  116449. {-999, -999, -999, -999, -999, -999, -999, -999,
  116450. -999, -999, -999, -110, -100, -86, -78, -70,
  116451. -60, -45, -30, -21, -999, -999, -999, -999,
  116452. -999, -999, -999, -999, -999, -999, -999, -999,
  116453. -999, -999, -999, -999, -999, -999, -999, -999,
  116454. -999, -999, -999, -999, -999, -999, -999, -999,
  116455. -999, -999, -999, -999, -999, -999, -999, -999},
  116456. {-999, -999, -999, -999, -999, -999, -999, -999,
  116457. -999, -999, -999, -110, -100, -87, -78, -67,
  116458. -48, -38, -29, -21, -999, -999, -999, -999,
  116459. -999, -999, -999, -999, -999, -999, -999, -999,
  116460. -999, -999, -999, -999, -999, -999, -999, -999,
  116461. -999, -999, -999, -999, -999, -999, -999, -999,
  116462. -999, -999, -999, -999, -999, -999, -999, -999},
  116463. {-999, -999, -999, -999, -999, -999, -999, -999,
  116464. -999, -999, -999, -110, -100, -86, -69, -56,
  116465. -45, -35, -33, -29, -999, -999, -999, -999,
  116466. -999, -999, -999, -999, -999, -999, -999, -999,
  116467. -999, -999, -999, -999, -999, -999, -999, -999,
  116468. -999, -999, -999, -999, -999, -999, -999, -999,
  116469. -999, -999, -999, -999, -999, -999, -999, -999},
  116470. {-999, -999, -999, -999, -999, -999, -999, -999,
  116471. -999, -999, -999, -110, -100, -83, -71, -48,
  116472. -27, -38, -37, -34, -999, -999, -999, -999,
  116473. -999, -999, -999, -999, -999, -999, -999, -999,
  116474. -999, -999, -999, -999, -999, -999, -999, -999,
  116475. -999, -999, -999, -999, -999, -999, -999, -999,
  116476. -999, -999, -999, -999, -999, -999, -999, -999}}
  116477. };
  116478. #endif
  116479. /*** End of inlined file: masking.h ***/
  116480. #define NEGINF -9999.f
  116481. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  116482. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  116483. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  116484. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116485. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116486. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  116487. look->channels=vi->channels;
  116488. look->ampmax=-9999.;
  116489. look->gi=gi;
  116490. return(look);
  116491. }
  116492. void _vp_global_free(vorbis_look_psy_global *look){
  116493. if(look){
  116494. memset(look,0,sizeof(*look));
  116495. _ogg_free(look);
  116496. }
  116497. }
  116498. void _vi_gpsy_free(vorbis_info_psy_global *i){
  116499. if(i){
  116500. memset(i,0,sizeof(*i));
  116501. _ogg_free(i);
  116502. }
  116503. }
  116504. void _vi_psy_free(vorbis_info_psy *i){
  116505. if(i){
  116506. memset(i,0,sizeof(*i));
  116507. _ogg_free(i);
  116508. }
  116509. }
  116510. static void min_curve(float *c,
  116511. float *c2){
  116512. int i;
  116513. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  116514. }
  116515. static void max_curve(float *c,
  116516. float *c2){
  116517. int i;
  116518. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  116519. }
  116520. static void attenuate_curve(float *c,float att){
  116521. int i;
  116522. for(i=0;i<EHMER_MAX;i++)
  116523. c[i]+=att;
  116524. }
  116525. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  116526. float center_boost, float center_decay_rate){
  116527. int i,j,k,m;
  116528. float ath[EHMER_MAX];
  116529. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  116530. float athc[P_LEVELS][EHMER_MAX];
  116531. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  116532. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  116533. memset(workc,0,sizeof(workc));
  116534. for(i=0;i<P_BANDS;i++){
  116535. /* we add back in the ATH to avoid low level curves falling off to
  116536. -infinity and unnecessarily cutting off high level curves in the
  116537. curve limiting (last step). */
  116538. /* A half-band's settings must be valid over the whole band, and
  116539. it's better to mask too little than too much */
  116540. int ath_offset=i*4;
  116541. for(j=0;j<EHMER_MAX;j++){
  116542. float min=999.;
  116543. for(k=0;k<4;k++)
  116544. if(j+k+ath_offset<MAX_ATH){
  116545. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  116546. }else{
  116547. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  116548. }
  116549. ath[j]=min;
  116550. }
  116551. /* copy curves into working space, replicate the 50dB curve to 30
  116552. and 40, replicate the 100dB curve to 110 */
  116553. for(j=0;j<6;j++)
  116554. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  116555. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116556. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116557. /* apply centered curve boost/decay */
  116558. for(j=0;j<P_LEVELS;j++){
  116559. for(k=0;k<EHMER_MAX;k++){
  116560. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  116561. if(adj<0. && center_boost>0)adj=0.;
  116562. if(adj>0. && center_boost<0)adj=0.;
  116563. workc[i][j][k]+=adj;
  116564. }
  116565. }
  116566. /* normalize curves so the driving amplitude is 0dB */
  116567. /* make temp curves with the ATH overlayed */
  116568. for(j=0;j<P_LEVELS;j++){
  116569. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  116570. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  116571. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  116572. max_curve(athc[j],workc[i][j]);
  116573. }
  116574. /* Now limit the louder curves.
  116575. the idea is this: We don't know what the playback attenuation
  116576. will be; 0dB SL moves every time the user twiddles the volume
  116577. knob. So that means we have to use a single 'most pessimal' curve
  116578. for all masking amplitudes, right? Wrong. The *loudest* sound
  116579. can be in (we assume) a range of ...+100dB] SL. However, sounds
  116580. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  116581. etc... */
  116582. for(j=1;j<P_LEVELS;j++){
  116583. min_curve(athc[j],athc[j-1]);
  116584. min_curve(workc[i][j],athc[j]);
  116585. }
  116586. }
  116587. for(i=0;i<P_BANDS;i++){
  116588. int hi_curve,lo_curve,bin;
  116589. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  116590. /* low frequency curves are measured with greater resolution than
  116591. the MDCT/FFT will actually give us; we want the curve applied
  116592. to the tone data to be pessimistic and thus apply the minimum
  116593. masking possible for a given bin. That means that a single bin
  116594. could span more than one octave and that the curve will be a
  116595. composite of multiple octaves. It also may mean that a single
  116596. bin may span > an eighth of an octave and that the eighth
  116597. octave values may also be composited. */
  116598. /* which octave curves will we be compositing? */
  116599. bin=floor(fromOC(i*.5)/binHz);
  116600. lo_curve= ceil(toOC(bin*binHz+1)*2);
  116601. hi_curve= floor(toOC((bin+1)*binHz)*2);
  116602. if(lo_curve>i)lo_curve=i;
  116603. if(lo_curve<0)lo_curve=0;
  116604. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  116605. for(m=0;m<P_LEVELS;m++){
  116606. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  116607. for(j=0;j<n;j++)brute_buffer[j]=999.;
  116608. /* render the curve into bins, then pull values back into curve.
  116609. The point is that any inherent subsampling aliasing results in
  116610. a safe minimum */
  116611. for(k=lo_curve;k<=hi_curve;k++){
  116612. int l=0;
  116613. for(j=0;j<EHMER_MAX;j++){
  116614. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  116615. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  116616. if(lo_bin<0)lo_bin=0;
  116617. if(lo_bin>n)lo_bin=n;
  116618. if(lo_bin<l)l=lo_bin;
  116619. if(hi_bin<0)hi_bin=0;
  116620. if(hi_bin>n)hi_bin=n;
  116621. for(;l<hi_bin && l<n;l++)
  116622. if(brute_buffer[l]>workc[k][m][j])
  116623. brute_buffer[l]=workc[k][m][j];
  116624. }
  116625. for(;l<n;l++)
  116626. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116627. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116628. }
  116629. /* be equally paranoid about being valid up to next half ocatve */
  116630. if(i+1<P_BANDS){
  116631. int l=0;
  116632. k=i+1;
  116633. for(j=0;j<EHMER_MAX;j++){
  116634. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  116635. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  116636. if(lo_bin<0)lo_bin=0;
  116637. if(lo_bin>n)lo_bin=n;
  116638. if(lo_bin<l)l=lo_bin;
  116639. if(hi_bin<0)hi_bin=0;
  116640. if(hi_bin>n)hi_bin=n;
  116641. for(;l<hi_bin && l<n;l++)
  116642. if(brute_buffer[l]>workc[k][m][j])
  116643. brute_buffer[l]=workc[k][m][j];
  116644. }
  116645. for(;l<n;l++)
  116646. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116647. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116648. }
  116649. for(j=0;j<EHMER_MAX;j++){
  116650. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  116651. if(bin<0){
  116652. ret[i][m][j+2]=-999.;
  116653. }else{
  116654. if(bin>=n){
  116655. ret[i][m][j+2]=-999.;
  116656. }else{
  116657. ret[i][m][j+2]=brute_buffer[bin];
  116658. }
  116659. }
  116660. }
  116661. /* add fenceposts */
  116662. for(j=0;j<EHMER_OFFSET;j++)
  116663. if(ret[i][m][j+2]>-200.f)break;
  116664. ret[i][m][0]=j;
  116665. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  116666. if(ret[i][m][j+2]>-200.f)
  116667. break;
  116668. ret[i][m][1]=j;
  116669. }
  116670. }
  116671. return(ret);
  116672. }
  116673. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  116674. vorbis_info_psy_global *gi,int n,long rate){
  116675. long i,j,lo=-99,hi=1;
  116676. long maxoc;
  116677. memset(p,0,sizeof(*p));
  116678. p->eighth_octave_lines=gi->eighth_octave_lines;
  116679. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  116680. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  116681. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  116682. p->total_octave_lines=maxoc-p->firstoc+1;
  116683. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  116684. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  116685. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  116686. p->vi=vi;
  116687. p->n=n;
  116688. p->rate=rate;
  116689. /* AoTuV HF weighting */
  116690. p->m_val = 1.;
  116691. if(rate < 26000) p->m_val = 0;
  116692. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  116693. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  116694. /* set up the lookups for a given blocksize and sample rate */
  116695. for(i=0,j=0;i<MAX_ATH-1;i++){
  116696. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  116697. float base=ATH[i];
  116698. if(j<endpos){
  116699. float delta=(ATH[i+1]-base)/(endpos-j);
  116700. for(;j<endpos && j<n;j++){
  116701. p->ath[j]=base+100.;
  116702. base+=delta;
  116703. }
  116704. }
  116705. }
  116706. for(i=0;i<n;i++){
  116707. float bark=toBARK(rate/(2*n)*i);
  116708. for(;lo+vi->noisewindowlomin<i &&
  116709. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  116710. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  116711. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  116712. p->bark[i]=((lo-1)<<16)+(hi-1);
  116713. }
  116714. for(i=0;i<n;i++)
  116715. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  116716. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  116717. vi->tone_centerboost,vi->tone_decay);
  116718. /* set up rolling noise median */
  116719. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  116720. for(i=0;i<P_NOISECURVES;i++)
  116721. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  116722. for(i=0;i<n;i++){
  116723. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  116724. int inthalfoc;
  116725. float del;
  116726. if(halfoc<0)halfoc=0;
  116727. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  116728. inthalfoc=(int)halfoc;
  116729. del=halfoc-inthalfoc;
  116730. for(j=0;j<P_NOISECURVES;j++)
  116731. p->noiseoffset[j][i]=
  116732. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  116733. p->vi->noiseoff[j][inthalfoc+1]*del;
  116734. }
  116735. #if 0
  116736. {
  116737. static int ls=0;
  116738. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  116739. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  116740. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  116741. }
  116742. #endif
  116743. }
  116744. void _vp_psy_clear(vorbis_look_psy *p){
  116745. int i,j;
  116746. if(p){
  116747. if(p->ath)_ogg_free(p->ath);
  116748. if(p->octave)_ogg_free(p->octave);
  116749. if(p->bark)_ogg_free(p->bark);
  116750. if(p->tonecurves){
  116751. for(i=0;i<P_BANDS;i++){
  116752. for(j=0;j<P_LEVELS;j++){
  116753. _ogg_free(p->tonecurves[i][j]);
  116754. }
  116755. _ogg_free(p->tonecurves[i]);
  116756. }
  116757. _ogg_free(p->tonecurves);
  116758. }
  116759. if(p->noiseoffset){
  116760. for(i=0;i<P_NOISECURVES;i++){
  116761. _ogg_free(p->noiseoffset[i]);
  116762. }
  116763. _ogg_free(p->noiseoffset);
  116764. }
  116765. memset(p,0,sizeof(*p));
  116766. }
  116767. }
  116768. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  116769. static void seed_curve(float *seed,
  116770. const float **curves,
  116771. float amp,
  116772. int oc, int n,
  116773. int linesper,float dBoffset){
  116774. int i,post1;
  116775. int seedptr;
  116776. const float *posts,*curve;
  116777. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  116778. choice=max(choice,0);
  116779. choice=min(choice,P_LEVELS-1);
  116780. posts=curves[choice];
  116781. curve=posts+2;
  116782. post1=(int)posts[1];
  116783. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  116784. for(i=posts[0];i<post1;i++){
  116785. if(seedptr>0){
  116786. float lin=amp+curve[i];
  116787. if(seed[seedptr]<lin)seed[seedptr]=lin;
  116788. }
  116789. seedptr+=linesper;
  116790. if(seedptr>=n)break;
  116791. }
  116792. }
  116793. static void seed_loop(vorbis_look_psy *p,
  116794. const float ***curves,
  116795. const float *f,
  116796. const float *flr,
  116797. float *seed,
  116798. float specmax){
  116799. vorbis_info_psy *vi=p->vi;
  116800. long n=p->n,i;
  116801. float dBoffset=vi->max_curve_dB-specmax;
  116802. /* prime the working vector with peak values */
  116803. for(i=0;i<n;i++){
  116804. float max=f[i];
  116805. long oc=p->octave[i];
  116806. while(i+1<n && p->octave[i+1]==oc){
  116807. i++;
  116808. if(f[i]>max)max=f[i];
  116809. }
  116810. if(max+6.f>flr[i]){
  116811. oc=oc>>p->shiftoc;
  116812. if(oc>=P_BANDS)oc=P_BANDS-1;
  116813. if(oc<0)oc=0;
  116814. seed_curve(seed,
  116815. curves[oc],
  116816. max,
  116817. p->octave[i]-p->firstoc,
  116818. p->total_octave_lines,
  116819. p->eighth_octave_lines,
  116820. dBoffset);
  116821. }
  116822. }
  116823. }
  116824. static void seed_chase(float *seeds, int linesper, long n){
  116825. long *posstack=(long*)alloca(n*sizeof(*posstack));
  116826. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  116827. long stack=0;
  116828. long pos=0;
  116829. long i;
  116830. for(i=0;i<n;i++){
  116831. if(stack<2){
  116832. posstack[stack]=i;
  116833. ampstack[stack++]=seeds[i];
  116834. }else{
  116835. while(1){
  116836. if(seeds[i]<ampstack[stack-1]){
  116837. posstack[stack]=i;
  116838. ampstack[stack++]=seeds[i];
  116839. break;
  116840. }else{
  116841. if(i<posstack[stack-1]+linesper){
  116842. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  116843. i<posstack[stack-2]+linesper){
  116844. /* we completely overlap, making stack-1 irrelevant. pop it */
  116845. stack--;
  116846. continue;
  116847. }
  116848. }
  116849. posstack[stack]=i;
  116850. ampstack[stack++]=seeds[i];
  116851. break;
  116852. }
  116853. }
  116854. }
  116855. }
  116856. /* the stack now contains only the positions that are relevant. Scan
  116857. 'em straight through */
  116858. for(i=0;i<stack;i++){
  116859. long endpos;
  116860. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  116861. endpos=posstack[i+1];
  116862. }else{
  116863. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  116864. discarded in short frames */
  116865. }
  116866. if(endpos>n)endpos=n;
  116867. for(;pos<endpos;pos++)
  116868. seeds[pos]=ampstack[i];
  116869. }
  116870. /* there. Linear time. I now remember this was on a problem set I
  116871. had in Grad Skool... I didn't solve it at the time ;-) */
  116872. }
  116873. /* bleaugh, this is more complicated than it needs to be */
  116874. #include<stdio.h>
  116875. static void max_seeds(vorbis_look_psy *p,
  116876. float *seed,
  116877. float *flr){
  116878. long n=p->total_octave_lines;
  116879. int linesper=p->eighth_octave_lines;
  116880. long linpos=0;
  116881. long pos;
  116882. seed_chase(seed,linesper,n); /* for masking */
  116883. pos=p->octave[0]-p->firstoc-(linesper>>1);
  116884. while(linpos+1<p->n){
  116885. float minV=seed[pos];
  116886. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  116887. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  116888. while(pos+1<=end){
  116889. pos++;
  116890. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  116891. minV=seed[pos];
  116892. }
  116893. end=pos+p->firstoc;
  116894. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  116895. if(flr[linpos]<minV)flr[linpos]=minV;
  116896. }
  116897. {
  116898. float minV=seed[p->total_octave_lines-1];
  116899. for(;linpos<p->n;linpos++)
  116900. if(flr[linpos]<minV)flr[linpos]=minV;
  116901. }
  116902. }
  116903. static void bark_noise_hybridmp(int n,const long *b,
  116904. const float *f,
  116905. float *noise,
  116906. const float offset,
  116907. const int fixed){
  116908. float *N=(float*) alloca(n*sizeof(*N));
  116909. float *X=(float*) alloca(n*sizeof(*N));
  116910. float *XX=(float*) alloca(n*sizeof(*N));
  116911. float *Y=(float*) alloca(n*sizeof(*N));
  116912. float *XY=(float*) alloca(n*sizeof(*N));
  116913. float tN, tX, tXX, tY, tXY;
  116914. int i;
  116915. int lo, hi;
  116916. float R, A, B, D;
  116917. float w, x, y;
  116918. tN = tX = tXX = tY = tXY = 0.f;
  116919. y = f[0] + offset;
  116920. if (y < 1.f) y = 1.f;
  116921. w = y * y * .5;
  116922. tN += w;
  116923. tX += w;
  116924. tY += w * y;
  116925. N[0] = tN;
  116926. X[0] = tX;
  116927. XX[0] = tXX;
  116928. Y[0] = tY;
  116929. XY[0] = tXY;
  116930. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  116931. y = f[i] + offset;
  116932. if (y < 1.f) y = 1.f;
  116933. w = y * y;
  116934. tN += w;
  116935. tX += w * x;
  116936. tXX += w * x * x;
  116937. tY += w * y;
  116938. tXY += w * x * y;
  116939. N[i] = tN;
  116940. X[i] = tX;
  116941. XX[i] = tXX;
  116942. Y[i] = tY;
  116943. XY[i] = tXY;
  116944. }
  116945. for (i = 0, x = 0.f;; i++, x += 1.f) {
  116946. lo = b[i] >> 16;
  116947. if( lo>=0 ) break;
  116948. hi = b[i] & 0xffff;
  116949. tN = N[hi] + N[-lo];
  116950. tX = X[hi] - X[-lo];
  116951. tXX = XX[hi] + XX[-lo];
  116952. tY = Y[hi] + Y[-lo];
  116953. tXY = XY[hi] - XY[-lo];
  116954. A = tY * tXX - tX * tXY;
  116955. B = tN * tXY - tX * tY;
  116956. D = tN * tXX - tX * tX;
  116957. R = (A + x * B) / D;
  116958. if (R < 0.f)
  116959. R = 0.f;
  116960. noise[i] = R - offset;
  116961. }
  116962. for ( ;; i++, x += 1.f) {
  116963. lo = b[i] >> 16;
  116964. hi = b[i] & 0xffff;
  116965. if(hi>=n)break;
  116966. tN = N[hi] - N[lo];
  116967. tX = X[hi] - X[lo];
  116968. tXX = XX[hi] - XX[lo];
  116969. tY = Y[hi] - Y[lo];
  116970. tXY = XY[hi] - XY[lo];
  116971. A = tY * tXX - tX * tXY;
  116972. B = tN * tXY - tX * tY;
  116973. D = tN * tXX - tX * tX;
  116974. R = (A + x * B) / D;
  116975. if (R < 0.f) R = 0.f;
  116976. noise[i] = R - offset;
  116977. }
  116978. for ( ; i < n; i++, x += 1.f) {
  116979. R = (A + x * B) / D;
  116980. if (R < 0.f) R = 0.f;
  116981. noise[i] = R - offset;
  116982. }
  116983. if (fixed <= 0) return;
  116984. for (i = 0, x = 0.f;; i++, x += 1.f) {
  116985. hi = i + fixed / 2;
  116986. lo = hi - fixed;
  116987. if(lo>=0)break;
  116988. tN = N[hi] + N[-lo];
  116989. tX = X[hi] - X[-lo];
  116990. tXX = XX[hi] + XX[-lo];
  116991. tY = Y[hi] + Y[-lo];
  116992. tXY = XY[hi] - XY[-lo];
  116993. A = tY * tXX - tX * tXY;
  116994. B = tN * tXY - tX * tY;
  116995. D = tN * tXX - tX * tX;
  116996. R = (A + x * B) / D;
  116997. if (R - offset < noise[i]) noise[i] = R - offset;
  116998. }
  116999. for ( ;; i++, x += 1.f) {
  117000. hi = i + fixed / 2;
  117001. lo = hi - fixed;
  117002. if(hi>=n)break;
  117003. tN = N[hi] - N[lo];
  117004. tX = X[hi] - X[lo];
  117005. tXX = XX[hi] - XX[lo];
  117006. tY = Y[hi] - Y[lo];
  117007. tXY = XY[hi] - XY[lo];
  117008. A = tY * tXX - tX * tXY;
  117009. B = tN * tXY - tX * tY;
  117010. D = tN * tXX - tX * tX;
  117011. R = (A + x * B) / D;
  117012. if (R - offset < noise[i]) noise[i] = R - offset;
  117013. }
  117014. for ( ; i < n; i++, x += 1.f) {
  117015. R = (A + x * B) / D;
  117016. if (R - offset < noise[i]) noise[i] = R - offset;
  117017. }
  117018. }
  117019. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117020. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117021. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117022. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117023. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117024. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117025. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117026. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117027. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117028. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117029. 973377.F, 913981.F, 858210.F, 805842.F,
  117030. 756669.F, 710497.F, 667142.F, 626433.F,
  117031. 588208.F, 552316.F, 518613.F, 486967.F,
  117032. 457252.F, 429351.F, 403152.F, 378551.F,
  117033. 355452.F, 333762.F, 313396.F, 294273.F,
  117034. 276316.F, 259455.F, 243623.F, 228757.F,
  117035. 214798.F, 201691.F, 189384.F, 177828.F,
  117036. 166977.F, 156788.F, 147221.F, 138237.F,
  117037. 129802.F, 121881.F, 114444.F, 107461.F,
  117038. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117039. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117040. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117041. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117042. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117043. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117044. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117045. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117046. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117047. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117048. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117049. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117050. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117051. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117052. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117053. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117054. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117055. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117056. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117057. 842.910F, 791.475F, 743.179F, 697.830F,
  117058. 655.249F, 615.265F, 577.722F, 542.469F,
  117059. 509.367F, 478.286F, 449.101F, 421.696F,
  117060. 395.964F, 371.803F, 349.115F, 327.812F,
  117061. 307.809F, 289.026F, 271.390F, 254.830F,
  117062. 239.280F, 224.679F, 210.969F, 198.096F,
  117063. 186.008F, 174.658F, 164.000F, 153.993F,
  117064. 144.596F, 135.773F, 127.488F, 119.708F,
  117065. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117066. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117067. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117068. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117069. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117070. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117071. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117072. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117073. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117074. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117075. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117076. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117077. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117078. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117079. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117080. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117081. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117082. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117083. 1.20790F, 1.13419F, 1.06499F, 1.F
  117084. };
  117085. void _vp_remove_floor(vorbis_look_psy *p,
  117086. float *mdct,
  117087. int *codedflr,
  117088. float *residue,
  117089. int sliding_lowpass){
  117090. int i,n=p->n;
  117091. if(sliding_lowpass>n)sliding_lowpass=n;
  117092. for(i=0;i<sliding_lowpass;i++){
  117093. residue[i]=
  117094. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117095. }
  117096. for(;i<n;i++)
  117097. residue[i]=0.;
  117098. }
  117099. void _vp_noisemask(vorbis_look_psy *p,
  117100. float *logmdct,
  117101. float *logmask){
  117102. int i,n=p->n;
  117103. float *work=(float*) alloca(n*sizeof(*work));
  117104. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117105. 140.,-1);
  117106. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117107. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117108. p->vi->noisewindowfixed);
  117109. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117110. #if 0
  117111. {
  117112. static int seq=0;
  117113. float work2[n];
  117114. for(i=0;i<n;i++){
  117115. work2[i]=logmask[i]+work[i];
  117116. }
  117117. if(seq&1)
  117118. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117119. else
  117120. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117121. if(seq&1)
  117122. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117123. else
  117124. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117125. seq++;
  117126. }
  117127. #endif
  117128. for(i=0;i<n;i++){
  117129. int dB=logmask[i]+.5;
  117130. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117131. if(dB<0)dB=0;
  117132. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117133. }
  117134. }
  117135. void _vp_tonemask(vorbis_look_psy *p,
  117136. float *logfft,
  117137. float *logmask,
  117138. float global_specmax,
  117139. float local_specmax){
  117140. int i,n=p->n;
  117141. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117142. float att=local_specmax+p->vi->ath_adjatt;
  117143. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117144. /* set the ATH (floating below localmax, not global max by a
  117145. specified att) */
  117146. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117147. for(i=0;i<n;i++)
  117148. logmask[i]=p->ath[i]+att;
  117149. /* tone masking */
  117150. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117151. max_seeds(p,seed,logmask);
  117152. }
  117153. void _vp_offset_and_mix(vorbis_look_psy *p,
  117154. float *noise,
  117155. float *tone,
  117156. int offset_select,
  117157. float *logmask,
  117158. float *mdct,
  117159. float *logmdct){
  117160. int i,n=p->n;
  117161. float de, coeffi, cx;/* AoTuV */
  117162. float toneatt=p->vi->tone_masteratt[offset_select];
  117163. cx = p->m_val;
  117164. for(i=0;i<n;i++){
  117165. float val= noise[i]+p->noiseoffset[offset_select][i];
  117166. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117167. logmask[i]=max(val,tone[i]+toneatt);
  117168. /* AoTuV */
  117169. /** @ M1 **
  117170. The following codes improve a noise problem.
  117171. A fundamental idea uses the value of masking and carries out
  117172. the relative compensation of the MDCT.
  117173. However, this code is not perfect and all noise problems cannot be solved.
  117174. by Aoyumi @ 2004/04/18
  117175. */
  117176. if(offset_select == 1) {
  117177. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117178. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117179. if(val > coeffi){
  117180. /* mdct value is > -17.2 dB below floor */
  117181. de = 1.0-((val-coeffi)*0.005*cx);
  117182. /* pro-rated attenuation:
  117183. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117184. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117185. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117186. etc... */
  117187. if(de < 0) de = 0.0001;
  117188. }else
  117189. /* mdct value is <= -17.2 dB below floor */
  117190. de = 1.0-((val-coeffi)*0.0003*cx);
  117191. /* pro-rated attenuation:
  117192. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117193. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117194. etc... */
  117195. mdct[i] *= de;
  117196. }
  117197. }
  117198. }
  117199. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117200. vorbis_info *vi=vd->vi;
  117201. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117202. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117203. int n=ci->blocksizes[vd->W]/2;
  117204. float secs=(float)n/vi->rate;
  117205. amp+=secs*gi->ampmax_att_per_sec;
  117206. if(amp<-9999)amp=-9999;
  117207. return(amp);
  117208. }
  117209. static void couple_lossless(float A, float B,
  117210. float *qA, float *qB){
  117211. int test1=fabs(*qA)>fabs(*qB);
  117212. test1-= fabs(*qA)<fabs(*qB);
  117213. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117214. if(test1==1){
  117215. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117216. }else{
  117217. float temp=*qB;
  117218. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117219. *qA=temp;
  117220. }
  117221. if(*qB>fabs(*qA)*1.9999f){
  117222. *qB= -fabs(*qA)*2.f;
  117223. *qA= -*qA;
  117224. }
  117225. }
  117226. static float hypot_lookup[32]={
  117227. -0.009935, -0.011245, -0.012726, -0.014397,
  117228. -0.016282, -0.018407, -0.020800, -0.023494,
  117229. -0.026522, -0.029923, -0.033737, -0.038010,
  117230. -0.042787, -0.048121, -0.054064, -0.060671,
  117231. -0.068000, -0.076109, -0.085054, -0.094892,
  117232. -0.105675, -0.117451, -0.130260, -0.144134,
  117233. -0.159093, -0.175146, -0.192286, -0.210490,
  117234. -0.229718, -0.249913, -0.271001, -0.292893};
  117235. static void precomputed_couple_point(float premag,
  117236. int floorA,int floorB,
  117237. float *mag, float *ang){
  117238. int test=(floorA>floorB)-1;
  117239. int offset=31-abs(floorA-floorB);
  117240. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117241. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117242. *mag=premag*floormag;
  117243. *ang=0.f;
  117244. }
  117245. /* just like below, this is currently set up to only do
  117246. single-step-depth coupling. Otherwise, we'd have to do more
  117247. copying (which will be inevitable later) */
  117248. /* doing the real circular magnitude calculation is audibly superior
  117249. to (A+B)/sqrt(2) */
  117250. static float dipole_hypot(float a, float b){
  117251. if(a>0.){
  117252. if(b>0.)return sqrt(a*a+b*b);
  117253. if(a>-b)return sqrt(a*a-b*b);
  117254. return -sqrt(b*b-a*a);
  117255. }
  117256. if(b<0.)return -sqrt(a*a+b*b);
  117257. if(-a>b)return -sqrt(a*a-b*b);
  117258. return sqrt(b*b-a*a);
  117259. }
  117260. static float round_hypot(float a, float b){
  117261. if(a>0.){
  117262. if(b>0.)return sqrt(a*a+b*b);
  117263. if(a>-b)return sqrt(a*a+b*b);
  117264. return -sqrt(b*b+a*a);
  117265. }
  117266. if(b<0.)return -sqrt(a*a+b*b);
  117267. if(-a>b)return -sqrt(a*a+b*b);
  117268. return sqrt(b*b+a*a);
  117269. }
  117270. /* revert to round hypot for now */
  117271. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117272. vorbis_info_psy_global *g,
  117273. vorbis_look_psy *p,
  117274. vorbis_info_mapping0 *vi,
  117275. float **mdct){
  117276. int i,j,n=p->n;
  117277. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117278. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117279. for(i=0;i<vi->coupling_steps;i++){
  117280. float *mdctM=mdct[vi->coupling_mag[i]];
  117281. float *mdctA=mdct[vi->coupling_ang[i]];
  117282. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117283. for(j=0;j<limit;j++)
  117284. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117285. for(;j<n;j++)
  117286. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117287. }
  117288. return(ret);
  117289. }
  117290. /* this is for per-channel noise normalization */
  117291. static int apsort(const void *a, const void *b){
  117292. float f1=fabs(**(float**)a);
  117293. float f2=fabs(**(float**)b);
  117294. return (f1<f2)-(f1>f2);
  117295. }
  117296. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117297. vorbis_look_psy *p,
  117298. vorbis_info_mapping0 *vi,
  117299. float **mags){
  117300. if(p->vi->normal_point_p){
  117301. int i,j,k,n=p->n;
  117302. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117303. int partition=p->vi->normal_partition;
  117304. float **work=(float**) alloca(sizeof(*work)*partition);
  117305. for(i=0;i<vi->coupling_steps;i++){
  117306. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117307. for(j=0;j<n;j+=partition){
  117308. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117309. qsort(work,partition,sizeof(*work),apsort);
  117310. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117311. }
  117312. }
  117313. return(ret);
  117314. }
  117315. return(NULL);
  117316. }
  117317. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117318. float *magnitudes,int *sortedindex){
  117319. int i,j,n=p->n;
  117320. vorbis_info_psy *vi=p->vi;
  117321. int partition=vi->normal_partition;
  117322. float **work=(float**) alloca(sizeof(*work)*partition);
  117323. int start=vi->normal_start;
  117324. for(j=start;j<n;j+=partition){
  117325. if(j+partition>n)partition=n-j;
  117326. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117327. qsort(work,partition,sizeof(*work),apsort);
  117328. for(i=0;i<partition;i++){
  117329. sortedindex[i+j-start]=work[i]-magnitudes;
  117330. }
  117331. }
  117332. }
  117333. void _vp_noise_normalize(vorbis_look_psy *p,
  117334. float *in,float *out,int *sortedindex){
  117335. int flag=0,i,j=0,n=p->n;
  117336. vorbis_info_psy *vi=p->vi;
  117337. int partition=vi->normal_partition;
  117338. int start=vi->normal_start;
  117339. if(start>n)start=n;
  117340. if(vi->normal_channel_p){
  117341. for(;j<start;j++)
  117342. out[j]=rint(in[j]);
  117343. for(;j+partition<=n;j+=partition){
  117344. float acc=0.;
  117345. int k;
  117346. for(i=j;i<j+partition;i++)
  117347. acc+=in[i]*in[i];
  117348. for(i=0;i<partition;i++){
  117349. k=sortedindex[i+j-start];
  117350. if(in[k]*in[k]>=.25f){
  117351. out[k]=rint(in[k]);
  117352. acc-=in[k]*in[k];
  117353. flag=1;
  117354. }else{
  117355. if(acc<vi->normal_thresh)break;
  117356. out[k]=unitnorm(in[k]);
  117357. acc-=1.;
  117358. }
  117359. }
  117360. for(;i<partition;i++){
  117361. k=sortedindex[i+j-start];
  117362. out[k]=0.;
  117363. }
  117364. }
  117365. }
  117366. for(;j<n;j++)
  117367. out[j]=rint(in[j]);
  117368. }
  117369. void _vp_couple(int blobno,
  117370. vorbis_info_psy_global *g,
  117371. vorbis_look_psy *p,
  117372. vorbis_info_mapping0 *vi,
  117373. float **res,
  117374. float **mag_memo,
  117375. int **mag_sort,
  117376. int **ifloor,
  117377. int *nonzero,
  117378. int sliding_lowpass){
  117379. int i,j,k,n=p->n;
  117380. /* perform any requested channel coupling */
  117381. /* point stereo can only be used in a first stage (in this encoder)
  117382. because of the dependency on floor lookups */
  117383. for(i=0;i<vi->coupling_steps;i++){
  117384. /* once we're doing multistage coupling in which a channel goes
  117385. through more than one coupling step, the floor vector
  117386. magnitudes will also have to be recalculated an propogated
  117387. along with PCM. Right now, we're not (that will wait until 5.1
  117388. most likely), so the code isn't here yet. The memory management
  117389. here is all assuming single depth couplings anyway. */
  117390. /* make sure coupling a zero and a nonzero channel results in two
  117391. nonzero channels. */
  117392. if(nonzero[vi->coupling_mag[i]] ||
  117393. nonzero[vi->coupling_ang[i]]){
  117394. float *rM=res[vi->coupling_mag[i]];
  117395. float *rA=res[vi->coupling_ang[i]];
  117396. float *qM=rM+n;
  117397. float *qA=rA+n;
  117398. int *floorM=ifloor[vi->coupling_mag[i]];
  117399. int *floorA=ifloor[vi->coupling_ang[i]];
  117400. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  117401. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  117402. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  117403. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  117404. int pointlimit=limit;
  117405. nonzero[vi->coupling_mag[i]]=1;
  117406. nonzero[vi->coupling_ang[i]]=1;
  117407. /* The threshold of a stereo is changed with the size of n */
  117408. if(n > 1000)
  117409. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  117410. for(j=0;j<p->n;j+=partition){
  117411. float acc=0.f;
  117412. for(k=0;k<partition;k++){
  117413. int l=k+j;
  117414. if(l<sliding_lowpass){
  117415. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  117416. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  117417. precomputed_couple_point(mag_memo[i][l],
  117418. floorM[l],floorA[l],
  117419. qM+l,qA+l);
  117420. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  117421. }else{
  117422. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  117423. }
  117424. }else{
  117425. qM[l]=0.;
  117426. qA[l]=0.;
  117427. }
  117428. }
  117429. if(p->vi->normal_point_p){
  117430. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  117431. int l=mag_sort[i][j+k];
  117432. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  117433. qM[l]=unitnorm(qM[l]);
  117434. acc-=1.f;
  117435. }
  117436. }
  117437. }
  117438. }
  117439. }
  117440. }
  117441. }
  117442. /* AoTuV */
  117443. /** @ M2 **
  117444. The boost problem by the combination of noise normalization and point stereo is eased.
  117445. However, this is a temporary patch.
  117446. by Aoyumi @ 2004/04/18
  117447. */
  117448. void hf_reduction(vorbis_info_psy_global *g,
  117449. vorbis_look_psy *p,
  117450. vorbis_info_mapping0 *vi,
  117451. float **mdct){
  117452. int i,j,n=p->n, de=0.3*p->m_val;
  117453. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117454. for(i=0; i<vi->coupling_steps; i++){
  117455. /* for(j=start; j<limit; j++){} // ???*/
  117456. for(j=limit; j<n; j++)
  117457. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  117458. }
  117459. }
  117460. #endif
  117461. /*** End of inlined file: psy.c ***/
  117462. /*** Start of inlined file: registry.c ***/
  117463. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117464. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117465. // tasks..
  117466. #if JUCE_MSVC
  117467. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117468. #endif
  117469. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117470. #if JUCE_USE_OGGVORBIS
  117471. /* seems like major overkill now; the backend numbers will grow into
  117472. the infrastructure soon enough */
  117473. extern vorbis_func_floor floor0_exportbundle;
  117474. extern vorbis_func_floor floor1_exportbundle;
  117475. extern vorbis_func_residue residue0_exportbundle;
  117476. extern vorbis_func_residue residue1_exportbundle;
  117477. extern vorbis_func_residue residue2_exportbundle;
  117478. extern vorbis_func_mapping mapping0_exportbundle;
  117479. vorbis_func_floor *_floor_P[]={
  117480. &floor0_exportbundle,
  117481. &floor1_exportbundle,
  117482. };
  117483. vorbis_func_residue *_residue_P[]={
  117484. &residue0_exportbundle,
  117485. &residue1_exportbundle,
  117486. &residue2_exportbundle,
  117487. };
  117488. vorbis_func_mapping *_mapping_P[]={
  117489. &mapping0_exportbundle,
  117490. };
  117491. #endif
  117492. /*** End of inlined file: registry.c ***/
  117493. /*** Start of inlined file: res0.c ***/
  117494. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  117495. encode/decode loops are coded for clarity and performance is not
  117496. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  117497. it's slow. */
  117498. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117499. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117500. // tasks..
  117501. #if JUCE_MSVC
  117502. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117503. #endif
  117504. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117505. #if JUCE_USE_OGGVORBIS
  117506. #include <stdlib.h>
  117507. #include <string.h>
  117508. #include <math.h>
  117509. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117510. #include <stdio.h>
  117511. #endif
  117512. typedef struct {
  117513. vorbis_info_residue0 *info;
  117514. int parts;
  117515. int stages;
  117516. codebook *fullbooks;
  117517. codebook *phrasebook;
  117518. codebook ***partbooks;
  117519. int partvals;
  117520. int **decodemap;
  117521. long postbits;
  117522. long phrasebits;
  117523. long frames;
  117524. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  117525. int train_seq;
  117526. long *training_data[8][64];
  117527. float training_max[8][64];
  117528. float training_min[8][64];
  117529. float tmin;
  117530. float tmax;
  117531. #endif
  117532. } vorbis_look_residue0;
  117533. void res0_free_info(vorbis_info_residue *i){
  117534. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  117535. if(info){
  117536. memset(info,0,sizeof(*info));
  117537. _ogg_free(info);
  117538. }
  117539. }
  117540. void res0_free_look(vorbis_look_residue *i){
  117541. int j;
  117542. if(i){
  117543. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  117544. #ifdef TRAIN_RES
  117545. {
  117546. int j,k,l;
  117547. for(j=0;j<look->parts;j++){
  117548. /*fprintf(stderr,"partition %d: ",j);*/
  117549. for(k=0;k<8;k++)
  117550. if(look->training_data[k][j]){
  117551. char buffer[80];
  117552. FILE *of;
  117553. codebook *statebook=look->partbooks[j][k];
  117554. /* long and short into the same bucket by current convention */
  117555. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  117556. of=fopen(buffer,"a");
  117557. for(l=0;l<statebook->entries;l++)
  117558. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  117559. fclose(of);
  117560. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  117561. look->training_min[k][j],look->training_max[k][j]);*/
  117562. _ogg_free(look->training_data[k][j]);
  117563. look->training_data[k][j]=NULL;
  117564. }
  117565. /*fprintf(stderr,"\n");*/
  117566. }
  117567. }
  117568. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  117569. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  117570. (float)look->phrasebits/look->frames,
  117571. (float)look->postbits/look->frames,
  117572. (float)(look->postbits+look->phrasebits)/look->frames);*/
  117573. #endif
  117574. /*vorbis_info_residue0 *info=look->info;
  117575. fprintf(stderr,
  117576. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  117577. "(%g/frame) \n",look->frames,look->phrasebits,
  117578. look->resbitsflat,
  117579. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  117580. for(j=0;j<look->parts;j++){
  117581. long acc=0;
  117582. fprintf(stderr,"\t[%d] == ",j);
  117583. for(k=0;k<look->stages;k++)
  117584. if((info->secondstages[j]>>k)&1){
  117585. fprintf(stderr,"%ld,",look->resbits[j][k]);
  117586. acc+=look->resbits[j][k];
  117587. }
  117588. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  117589. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  117590. }
  117591. fprintf(stderr,"\n");*/
  117592. for(j=0;j<look->parts;j++)
  117593. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  117594. _ogg_free(look->partbooks);
  117595. for(j=0;j<look->partvals;j++)
  117596. _ogg_free(look->decodemap[j]);
  117597. _ogg_free(look->decodemap);
  117598. memset(look,0,sizeof(*look));
  117599. _ogg_free(look);
  117600. }
  117601. }
  117602. static int icount(unsigned int v){
  117603. int ret=0;
  117604. while(v){
  117605. ret+=v&1;
  117606. v>>=1;
  117607. }
  117608. return(ret);
  117609. }
  117610. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  117611. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117612. int j,acc=0;
  117613. oggpack_write(opb,info->begin,24);
  117614. oggpack_write(opb,info->end,24);
  117615. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  117616. code with a partitioned book */
  117617. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  117618. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  117619. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  117620. bitmask of one indicates this partition class has bits to write
  117621. this pass */
  117622. for(j=0;j<info->partitions;j++){
  117623. if(ilog(info->secondstages[j])>3){
  117624. /* yes, this is a minor hack due to not thinking ahead */
  117625. oggpack_write(opb,info->secondstages[j],3);
  117626. oggpack_write(opb,1,1);
  117627. oggpack_write(opb,info->secondstages[j]>>3,5);
  117628. }else
  117629. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  117630. acc+=icount(info->secondstages[j]);
  117631. }
  117632. for(j=0;j<acc;j++)
  117633. oggpack_write(opb,info->booklist[j],8);
  117634. }
  117635. /* vorbis_info is for range checking */
  117636. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  117637. int j,acc=0;
  117638. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  117639. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  117640. info->begin=oggpack_read(opb,24);
  117641. info->end=oggpack_read(opb,24);
  117642. info->grouping=oggpack_read(opb,24)+1;
  117643. info->partitions=oggpack_read(opb,6)+1;
  117644. info->groupbook=oggpack_read(opb,8);
  117645. for(j=0;j<info->partitions;j++){
  117646. int cascade=oggpack_read(opb,3);
  117647. if(oggpack_read(opb,1))
  117648. cascade|=(oggpack_read(opb,5)<<3);
  117649. info->secondstages[j]=cascade;
  117650. acc+=icount(cascade);
  117651. }
  117652. for(j=0;j<acc;j++)
  117653. info->booklist[j]=oggpack_read(opb,8);
  117654. if(info->groupbook>=ci->books)goto errout;
  117655. for(j=0;j<acc;j++)
  117656. if(info->booklist[j]>=ci->books)goto errout;
  117657. return(info);
  117658. errout:
  117659. res0_free_info(info);
  117660. return(NULL);
  117661. }
  117662. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  117663. vorbis_info_residue *vr){
  117664. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117665. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  117666. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  117667. int j,k,acc=0;
  117668. int dim;
  117669. int maxstage=0;
  117670. look->info=info;
  117671. look->parts=info->partitions;
  117672. look->fullbooks=ci->fullbooks;
  117673. look->phrasebook=ci->fullbooks+info->groupbook;
  117674. dim=look->phrasebook->dim;
  117675. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  117676. for(j=0;j<look->parts;j++){
  117677. int stages=ilog(info->secondstages[j]);
  117678. if(stages){
  117679. if(stages>maxstage)maxstage=stages;
  117680. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  117681. for(k=0;k<stages;k++)
  117682. if(info->secondstages[j]&(1<<k)){
  117683. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  117684. #ifdef TRAIN_RES
  117685. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  117686. sizeof(***look->training_data));
  117687. #endif
  117688. }
  117689. }
  117690. }
  117691. look->partvals=rint(pow((float)look->parts,(float)dim));
  117692. look->stages=maxstage;
  117693. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  117694. for(j=0;j<look->partvals;j++){
  117695. long val=j;
  117696. long mult=look->partvals/look->parts;
  117697. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  117698. for(k=0;k<dim;k++){
  117699. long deco=val/mult;
  117700. val-=deco*mult;
  117701. mult/=look->parts;
  117702. look->decodemap[j][k]=deco;
  117703. }
  117704. }
  117705. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117706. {
  117707. static int train_seq=0;
  117708. look->train_seq=train_seq++;
  117709. }
  117710. #endif
  117711. return(look);
  117712. }
  117713. /* break an abstraction and copy some code for performance purposes */
  117714. static int local_book_besterror(codebook *book,float *a){
  117715. int dim=book->dim,i,k,o;
  117716. int best=0;
  117717. encode_aux_threshmatch *tt=book->c->thresh_tree;
  117718. /* find the quant val of each scalar */
  117719. for(k=0,o=dim;k<dim;++k){
  117720. float val=a[--o];
  117721. i=tt->threshvals>>1;
  117722. if(val<tt->quantthresh[i]){
  117723. if(val<tt->quantthresh[i-1]){
  117724. for(--i;i>0;--i)
  117725. if(val>=tt->quantthresh[i-1])
  117726. break;
  117727. }
  117728. }else{
  117729. for(++i;i<tt->threshvals-1;++i)
  117730. if(val<tt->quantthresh[i])break;
  117731. }
  117732. best=(best*tt->quantvals)+tt->quantmap[i];
  117733. }
  117734. /* regular lattices are easy :-) */
  117735. if(book->c->lengthlist[best]<=0){
  117736. const static_codebook *c=book->c;
  117737. int i,j;
  117738. float bestf=0.f;
  117739. float *e=book->valuelist;
  117740. best=-1;
  117741. for(i=0;i<book->entries;i++){
  117742. if(c->lengthlist[i]>0){
  117743. float thisx=0.f;
  117744. for(j=0;j<dim;j++){
  117745. float val=(e[j]-a[j]);
  117746. thisx+=val*val;
  117747. }
  117748. if(best==-1 || thisx<bestf){
  117749. bestf=thisx;
  117750. best=i;
  117751. }
  117752. }
  117753. e+=dim;
  117754. }
  117755. }
  117756. {
  117757. float *ptr=book->valuelist+best*dim;
  117758. for(i=0;i<dim;i++)
  117759. *a++ -= *ptr++;
  117760. }
  117761. return(best);
  117762. }
  117763. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  117764. codebook *book,long *acc){
  117765. int i,bits=0;
  117766. int dim=book->dim;
  117767. int step=n/dim;
  117768. for(i=0;i<step;i++){
  117769. int entry=local_book_besterror(book,vec+i*dim);
  117770. #ifdef TRAIN_RES
  117771. acc[entry]++;
  117772. #endif
  117773. bits+=vorbis_book_encode(book,entry,opb);
  117774. }
  117775. return(bits);
  117776. }
  117777. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  117778. float **in,int ch){
  117779. long i,j,k;
  117780. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117781. vorbis_info_residue0 *info=look->info;
  117782. /* move all this setup out later */
  117783. int samples_per_partition=info->grouping;
  117784. int possible_partitions=info->partitions;
  117785. int n=info->end-info->begin;
  117786. int partvals=n/samples_per_partition;
  117787. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  117788. float scale=100./samples_per_partition;
  117789. /* we find the partition type for each partition of each
  117790. channel. We'll go back and do the interleaved encoding in a
  117791. bit. For now, clarity */
  117792. for(i=0;i<ch;i++){
  117793. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  117794. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  117795. }
  117796. for(i=0;i<partvals;i++){
  117797. int offset=i*samples_per_partition+info->begin;
  117798. for(j=0;j<ch;j++){
  117799. float max=0.;
  117800. float ent=0.;
  117801. for(k=0;k<samples_per_partition;k++){
  117802. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  117803. ent+=fabs(rint(in[j][offset+k]));
  117804. }
  117805. ent*=scale;
  117806. for(k=0;k<possible_partitions-1;k++)
  117807. if(max<=info->classmetric1[k] &&
  117808. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  117809. break;
  117810. partword[j][i]=k;
  117811. }
  117812. }
  117813. #ifdef TRAIN_RESAUX
  117814. {
  117815. FILE *of;
  117816. char buffer[80];
  117817. for(i=0;i<ch;i++){
  117818. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  117819. of=fopen(buffer,"a");
  117820. for(j=0;j<partvals;j++)
  117821. fprintf(of,"%ld, ",partword[i][j]);
  117822. fprintf(of,"\n");
  117823. fclose(of);
  117824. }
  117825. }
  117826. #endif
  117827. look->frames++;
  117828. return(partword);
  117829. }
  117830. /* designed for stereo or other modes where the partition size is an
  117831. integer multiple of the number of channels encoded in the current
  117832. submap */
  117833. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  117834. int ch){
  117835. long i,j,k,l;
  117836. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117837. vorbis_info_residue0 *info=look->info;
  117838. /* move all this setup out later */
  117839. int samples_per_partition=info->grouping;
  117840. int possible_partitions=info->partitions;
  117841. int n=info->end-info->begin;
  117842. int partvals=n/samples_per_partition;
  117843. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  117844. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117845. FILE *of;
  117846. char buffer[80];
  117847. #endif
  117848. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  117849. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  117850. for(i=0,l=info->begin/ch;i<partvals;i++){
  117851. float magmax=0.f;
  117852. float angmax=0.f;
  117853. for(j=0;j<samples_per_partition;j+=ch){
  117854. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  117855. for(k=1;k<ch;k++)
  117856. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  117857. l++;
  117858. }
  117859. for(j=0;j<possible_partitions-1;j++)
  117860. if(magmax<=info->classmetric1[j] &&
  117861. angmax<=info->classmetric2[j])
  117862. break;
  117863. partword[0][i]=j;
  117864. }
  117865. #ifdef TRAIN_RESAUX
  117866. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  117867. of=fopen(buffer,"a");
  117868. for(i=0;i<partvals;i++)
  117869. fprintf(of,"%ld, ",partword[0][i]);
  117870. fprintf(of,"\n");
  117871. fclose(of);
  117872. #endif
  117873. look->frames++;
  117874. return(partword);
  117875. }
  117876. static int _01forward(oggpack_buffer *opb,
  117877. vorbis_block *vb,vorbis_look_residue *vl,
  117878. float **in,int ch,
  117879. long **partword,
  117880. int (*encode)(oggpack_buffer *,float *,int,
  117881. codebook *,long *)){
  117882. long i,j,k,s;
  117883. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117884. vorbis_info_residue0 *info=look->info;
  117885. /* move all this setup out later */
  117886. int samples_per_partition=info->grouping;
  117887. int possible_partitions=info->partitions;
  117888. int partitions_per_word=look->phrasebook->dim;
  117889. int n=info->end-info->begin;
  117890. int partvals=n/samples_per_partition;
  117891. long resbits[128];
  117892. long resvals[128];
  117893. #ifdef TRAIN_RES
  117894. for(i=0;i<ch;i++)
  117895. for(j=info->begin;j<info->end;j++){
  117896. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  117897. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  117898. }
  117899. #endif
  117900. memset(resbits,0,sizeof(resbits));
  117901. memset(resvals,0,sizeof(resvals));
  117902. /* we code the partition words for each channel, then the residual
  117903. words for a partition per channel until we've written all the
  117904. residual words for that partition word. Then write the next
  117905. partition channel words... */
  117906. for(s=0;s<look->stages;s++){
  117907. for(i=0;i<partvals;){
  117908. /* first we encode a partition codeword for each channel */
  117909. if(s==0){
  117910. for(j=0;j<ch;j++){
  117911. long val=partword[j][i];
  117912. for(k=1;k<partitions_per_word;k++){
  117913. val*=possible_partitions;
  117914. if(i+k<partvals)
  117915. val+=partword[j][i+k];
  117916. }
  117917. /* training hack */
  117918. if(val<look->phrasebook->entries)
  117919. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  117920. #if 0 /*def TRAIN_RES*/
  117921. else
  117922. fprintf(stderr,"!");
  117923. #endif
  117924. }
  117925. }
  117926. /* now we encode interleaved residual values for the partitions */
  117927. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  117928. long offset=i*samples_per_partition+info->begin;
  117929. for(j=0;j<ch;j++){
  117930. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  117931. if(info->secondstages[partword[j][i]]&(1<<s)){
  117932. codebook *statebook=look->partbooks[partword[j][i]][s];
  117933. if(statebook){
  117934. int ret;
  117935. long *accumulator=NULL;
  117936. #ifdef TRAIN_RES
  117937. accumulator=look->training_data[s][partword[j][i]];
  117938. {
  117939. int l;
  117940. float *samples=in[j]+offset;
  117941. for(l=0;l<samples_per_partition;l++){
  117942. if(samples[l]<look->training_min[s][partword[j][i]])
  117943. look->training_min[s][partword[j][i]]=samples[l];
  117944. if(samples[l]>look->training_max[s][partword[j][i]])
  117945. look->training_max[s][partword[j][i]]=samples[l];
  117946. }
  117947. }
  117948. #endif
  117949. ret=encode(opb,in[j]+offset,samples_per_partition,
  117950. statebook,accumulator);
  117951. look->postbits+=ret;
  117952. resbits[partword[j][i]]+=ret;
  117953. }
  117954. }
  117955. }
  117956. }
  117957. }
  117958. }
  117959. /*{
  117960. long total=0;
  117961. long totalbits=0;
  117962. fprintf(stderr,"%d :: ",vb->mode);
  117963. for(k=0;k<possible_partitions;k++){
  117964. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  117965. total+=resvals[k];
  117966. totalbits+=resbits[k];
  117967. }
  117968. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  117969. }*/
  117970. return(0);
  117971. }
  117972. /* a truncated packet here just means 'stop working'; it's not an error */
  117973. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117974. float **in,int ch,
  117975. long (*decodepart)(codebook *, float *,
  117976. oggpack_buffer *,int)){
  117977. long i,j,k,l,s;
  117978. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117979. vorbis_info_residue0 *info=look->info;
  117980. /* move all this setup out later */
  117981. int samples_per_partition=info->grouping;
  117982. int partitions_per_word=look->phrasebook->dim;
  117983. int n=info->end-info->begin;
  117984. int partvals=n/samples_per_partition;
  117985. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  117986. int ***partword=(int***)alloca(ch*sizeof(*partword));
  117987. for(j=0;j<ch;j++)
  117988. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  117989. for(s=0;s<look->stages;s++){
  117990. /* each loop decodes on partition codeword containing
  117991. partitions_pre_word partitions */
  117992. for(i=0,l=0;i<partvals;l++){
  117993. if(s==0){
  117994. /* fetch the partition word for each channel */
  117995. for(j=0;j<ch;j++){
  117996. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  117997. if(temp==-1)goto eopbreak;
  117998. partword[j][l]=look->decodemap[temp];
  117999. if(partword[j][l]==NULL)goto errout;
  118000. }
  118001. }
  118002. /* now we decode residual values for the partitions */
  118003. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118004. for(j=0;j<ch;j++){
  118005. long offset=info->begin+i*samples_per_partition;
  118006. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118007. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118008. if(stagebook){
  118009. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118010. samples_per_partition)==-1)goto eopbreak;
  118011. }
  118012. }
  118013. }
  118014. }
  118015. }
  118016. errout:
  118017. eopbreak:
  118018. return(0);
  118019. }
  118020. #if 0
  118021. /* residue 0 and 1 are just slight variants of one another. 0 is
  118022. interleaved, 1 is not */
  118023. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118024. float **in,int *nonzero,int ch){
  118025. /* we encode only the nonzero parts of a bundle */
  118026. int i,used=0;
  118027. for(i=0;i<ch;i++)
  118028. if(nonzero[i])
  118029. in[used++]=in[i];
  118030. if(used)
  118031. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118032. return(_01class(vb,vl,in,used));
  118033. else
  118034. return(0);
  118035. }
  118036. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118037. float **in,float **out,int *nonzero,int ch,
  118038. long **partword){
  118039. /* we encode only the nonzero parts of a bundle */
  118040. int i,j,used=0,n=vb->pcmend/2;
  118041. for(i=0;i<ch;i++)
  118042. if(nonzero[i]){
  118043. if(out)
  118044. for(j=0;j<n;j++)
  118045. out[i][j]+=in[i][j];
  118046. in[used++]=in[i];
  118047. }
  118048. if(used){
  118049. int ret=_01forward(vb,vl,in,used,partword,
  118050. _interleaved_encodepart);
  118051. if(out){
  118052. used=0;
  118053. for(i=0;i<ch;i++)
  118054. if(nonzero[i]){
  118055. for(j=0;j<n;j++)
  118056. out[i][j]-=in[used][j];
  118057. used++;
  118058. }
  118059. }
  118060. return(ret);
  118061. }else{
  118062. return(0);
  118063. }
  118064. }
  118065. #endif
  118066. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118067. float **in,int *nonzero,int ch){
  118068. int i,used=0;
  118069. for(i=0;i<ch;i++)
  118070. if(nonzero[i])
  118071. in[used++]=in[i];
  118072. if(used)
  118073. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118074. else
  118075. return(0);
  118076. }
  118077. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118078. float **in,float **out,int *nonzero,int ch,
  118079. long **partword){
  118080. int i,j,used=0,n=vb->pcmend/2;
  118081. for(i=0;i<ch;i++)
  118082. if(nonzero[i]){
  118083. if(out)
  118084. for(j=0;j<n;j++)
  118085. out[i][j]+=in[i][j];
  118086. in[used++]=in[i];
  118087. }
  118088. if(used){
  118089. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118090. if(out){
  118091. used=0;
  118092. for(i=0;i<ch;i++)
  118093. if(nonzero[i]){
  118094. for(j=0;j<n;j++)
  118095. out[i][j]-=in[used][j];
  118096. used++;
  118097. }
  118098. }
  118099. return(ret);
  118100. }else{
  118101. return(0);
  118102. }
  118103. }
  118104. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118105. float **in,int *nonzero,int ch){
  118106. int i,used=0;
  118107. for(i=0;i<ch;i++)
  118108. if(nonzero[i])
  118109. in[used++]=in[i];
  118110. if(used)
  118111. return(_01class(vb,vl,in,used));
  118112. else
  118113. return(0);
  118114. }
  118115. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118116. float **in,int *nonzero,int ch){
  118117. int i,used=0;
  118118. for(i=0;i<ch;i++)
  118119. if(nonzero[i])
  118120. in[used++]=in[i];
  118121. if(used)
  118122. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118123. else
  118124. return(0);
  118125. }
  118126. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118127. float **in,int *nonzero,int ch){
  118128. int i,used=0;
  118129. for(i=0;i<ch;i++)
  118130. if(nonzero[i])used++;
  118131. if(used)
  118132. return(_2class(vb,vl,in,ch));
  118133. else
  118134. return(0);
  118135. }
  118136. /* res2 is slightly more different; all the channels are interleaved
  118137. into a single vector and encoded. */
  118138. int res2_forward(oggpack_buffer *opb,
  118139. vorbis_block *vb,vorbis_look_residue *vl,
  118140. float **in,float **out,int *nonzero,int ch,
  118141. long **partword){
  118142. long i,j,k,n=vb->pcmend/2,used=0;
  118143. /* don't duplicate the code; use a working vector hack for now and
  118144. reshape ourselves into a single channel res1 */
  118145. /* ugly; reallocs for each coupling pass :-( */
  118146. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118147. for(i=0;i<ch;i++){
  118148. float *pcm=in[i];
  118149. if(nonzero[i])used++;
  118150. for(j=0,k=i;j<n;j++,k+=ch)
  118151. work[k]=pcm[j];
  118152. }
  118153. if(used){
  118154. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118155. /* update the sofar vector */
  118156. if(out){
  118157. for(i=0;i<ch;i++){
  118158. float *pcm=in[i];
  118159. float *sofar=out[i];
  118160. for(j=0,k=i;j<n;j++,k+=ch)
  118161. sofar[j]+=pcm[j]-work[k];
  118162. }
  118163. }
  118164. return(ret);
  118165. }else{
  118166. return(0);
  118167. }
  118168. }
  118169. /* duplicate code here as speed is somewhat more important */
  118170. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118171. float **in,int *nonzero,int ch){
  118172. long i,k,l,s;
  118173. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118174. vorbis_info_residue0 *info=look->info;
  118175. /* move all this setup out later */
  118176. int samples_per_partition=info->grouping;
  118177. int partitions_per_word=look->phrasebook->dim;
  118178. int n=info->end-info->begin;
  118179. int partvals=n/samples_per_partition;
  118180. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118181. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118182. for(i=0;i<ch;i++)if(nonzero[i])break;
  118183. if(i==ch)return(0); /* no nonzero vectors */
  118184. for(s=0;s<look->stages;s++){
  118185. for(i=0,l=0;i<partvals;l++){
  118186. if(s==0){
  118187. /* fetch the partition word */
  118188. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118189. if(temp==-1)goto eopbreak;
  118190. partword[l]=look->decodemap[temp];
  118191. if(partword[l]==NULL)goto errout;
  118192. }
  118193. /* now we decode residual values for the partitions */
  118194. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118195. if(info->secondstages[partword[l][k]]&(1<<s)){
  118196. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118197. if(stagebook){
  118198. if(vorbis_book_decodevv_add(stagebook,in,
  118199. i*samples_per_partition+info->begin,ch,
  118200. &vb->opb,samples_per_partition)==-1)
  118201. goto eopbreak;
  118202. }
  118203. }
  118204. }
  118205. }
  118206. errout:
  118207. eopbreak:
  118208. return(0);
  118209. }
  118210. vorbis_func_residue residue0_exportbundle={
  118211. NULL,
  118212. &res0_unpack,
  118213. &res0_look,
  118214. &res0_free_info,
  118215. &res0_free_look,
  118216. NULL,
  118217. NULL,
  118218. &res0_inverse
  118219. };
  118220. vorbis_func_residue residue1_exportbundle={
  118221. &res0_pack,
  118222. &res0_unpack,
  118223. &res0_look,
  118224. &res0_free_info,
  118225. &res0_free_look,
  118226. &res1_class,
  118227. &res1_forward,
  118228. &res1_inverse
  118229. };
  118230. vorbis_func_residue residue2_exportbundle={
  118231. &res0_pack,
  118232. &res0_unpack,
  118233. &res0_look,
  118234. &res0_free_info,
  118235. &res0_free_look,
  118236. &res2_class,
  118237. &res2_forward,
  118238. &res2_inverse
  118239. };
  118240. #endif
  118241. /*** End of inlined file: res0.c ***/
  118242. /*** Start of inlined file: sharedbook.c ***/
  118243. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118244. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118245. // tasks..
  118246. #if JUCE_MSVC
  118247. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118248. #endif
  118249. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118250. #if JUCE_USE_OGGVORBIS
  118251. #include <stdlib.h>
  118252. #include <math.h>
  118253. #include <string.h>
  118254. /**** pack/unpack helpers ******************************************/
  118255. int _ilog(unsigned int v){
  118256. int ret=0;
  118257. while(v){
  118258. ret++;
  118259. v>>=1;
  118260. }
  118261. return(ret);
  118262. }
  118263. /* 32 bit float (not IEEE; nonnormalized mantissa +
  118264. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  118265. Why not IEEE? It's just not that important here. */
  118266. #define VQ_FEXP 10
  118267. #define VQ_FMAN 21
  118268. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  118269. /* doesn't currently guard under/overflow */
  118270. long _float32_pack(float val){
  118271. int sign=0;
  118272. long exp;
  118273. long mant;
  118274. if(val<0){
  118275. sign=0x80000000;
  118276. val= -val;
  118277. }
  118278. exp= floor(log(val)/log(2.f));
  118279. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  118280. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  118281. return(sign|exp|mant);
  118282. }
  118283. float _float32_unpack(long val){
  118284. double mant=val&0x1fffff;
  118285. int sign=val&0x80000000;
  118286. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  118287. if(sign)mant= -mant;
  118288. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  118289. }
  118290. /* given a list of word lengths, generate a list of codewords. Works
  118291. for length ordered or unordered, always assigns the lowest valued
  118292. codewords first. Extended to handle unused entries (length 0) */
  118293. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  118294. long i,j,count=0;
  118295. ogg_uint32_t marker[33];
  118296. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  118297. memset(marker,0,sizeof(marker));
  118298. for(i=0;i<n;i++){
  118299. long length=l[i];
  118300. if(length>0){
  118301. ogg_uint32_t entry=marker[length];
  118302. /* when we claim a node for an entry, we also claim the nodes
  118303. below it (pruning off the imagined tree that may have dangled
  118304. from it) as well as blocking the use of any nodes directly
  118305. above for leaves */
  118306. /* update ourself */
  118307. if(length<32 && (entry>>length)){
  118308. /* error condition; the lengths must specify an overpopulated tree */
  118309. _ogg_free(r);
  118310. return(NULL);
  118311. }
  118312. r[count++]=entry;
  118313. /* Look to see if the next shorter marker points to the node
  118314. above. if so, update it and repeat. */
  118315. {
  118316. for(j=length;j>0;j--){
  118317. if(marker[j]&1){
  118318. /* have to jump branches */
  118319. if(j==1)
  118320. marker[1]++;
  118321. else
  118322. marker[j]=marker[j-1]<<1;
  118323. break; /* invariant says next upper marker would already
  118324. have been moved if it was on the same path */
  118325. }
  118326. marker[j]++;
  118327. }
  118328. }
  118329. /* prune the tree; the implicit invariant says all the longer
  118330. markers were dangling from our just-taken node. Dangle them
  118331. from our *new* node. */
  118332. for(j=length+1;j<33;j++)
  118333. if((marker[j]>>1) == entry){
  118334. entry=marker[j];
  118335. marker[j]=marker[j-1]<<1;
  118336. }else
  118337. break;
  118338. }else
  118339. if(sparsecount==0)count++;
  118340. }
  118341. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118342. endian */
  118343. for(i=0,count=0;i<n;i++){
  118344. ogg_uint32_t temp=0;
  118345. for(j=0;j<l[i];j++){
  118346. temp<<=1;
  118347. temp|=(r[count]>>j)&1;
  118348. }
  118349. if(sparsecount){
  118350. if(l[i])
  118351. r[count++]=temp;
  118352. }else
  118353. r[count++]=temp;
  118354. }
  118355. return(r);
  118356. }
  118357. /* there might be a straightforward one-line way to do the below
  118358. that's portable and totally safe against roundoff, but I haven't
  118359. thought of it. Therefore, we opt on the side of caution */
  118360. long _book_maptype1_quantvals(const static_codebook *b){
  118361. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118362. /* the above *should* be reliable, but we'll not assume that FP is
  118363. ever reliable when bitstream sync is at stake; verify via integer
  118364. means that vals really is the greatest value of dim for which
  118365. vals^b->bim <= b->entries */
  118366. /* treat the above as an initial guess */
  118367. while(1){
  118368. long acc=1;
  118369. long acc1=1;
  118370. int i;
  118371. for(i=0;i<b->dim;i++){
  118372. acc*=vals;
  118373. acc1*=vals+1;
  118374. }
  118375. if(acc<=b->entries && acc1>b->entries){
  118376. return(vals);
  118377. }else{
  118378. if(acc>b->entries){
  118379. vals--;
  118380. }else{
  118381. vals++;
  118382. }
  118383. }
  118384. }
  118385. }
  118386. /* unpack the quantized list of values for encode/decode ***********/
  118387. /* we need to deal with two map types: in map type 1, the values are
  118388. generated algorithmically (each column of the vector counts through
  118389. the values in the quant vector). in map type 2, all the values came
  118390. in in an explicit list. Both value lists must be unpacked */
  118391. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  118392. long j,k,count=0;
  118393. if(b->maptype==1 || b->maptype==2){
  118394. int quantvals;
  118395. float mindel=_float32_unpack(b->q_min);
  118396. float delta=_float32_unpack(b->q_delta);
  118397. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  118398. /* maptype 1 and 2 both use a quantized value vector, but
  118399. different sizes */
  118400. switch(b->maptype){
  118401. case 1:
  118402. /* most of the time, entries%dimensions == 0, but we need to be
  118403. well defined. We define that the possible vales at each
  118404. scalar is values == entries/dim. If entries%dim != 0, we'll
  118405. have 'too few' values (values*dim<entries), which means that
  118406. we'll have 'left over' entries; left over entries use zeroed
  118407. values (and are wasted). So don't generate codebooks like
  118408. that */
  118409. quantvals=_book_maptype1_quantvals(b);
  118410. for(j=0;j<b->entries;j++){
  118411. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118412. float last=0.f;
  118413. int indexdiv=1;
  118414. for(k=0;k<b->dim;k++){
  118415. int index= (j/indexdiv)%quantvals;
  118416. float val=b->quantlist[index];
  118417. val=fabs(val)*delta+mindel+last;
  118418. if(b->q_sequencep)last=val;
  118419. if(sparsemap)
  118420. r[sparsemap[count]*b->dim+k]=val;
  118421. else
  118422. r[count*b->dim+k]=val;
  118423. indexdiv*=quantvals;
  118424. }
  118425. count++;
  118426. }
  118427. }
  118428. break;
  118429. case 2:
  118430. for(j=0;j<b->entries;j++){
  118431. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118432. float last=0.f;
  118433. for(k=0;k<b->dim;k++){
  118434. float val=b->quantlist[j*b->dim+k];
  118435. val=fabs(val)*delta+mindel+last;
  118436. if(b->q_sequencep)last=val;
  118437. if(sparsemap)
  118438. r[sparsemap[count]*b->dim+k]=val;
  118439. else
  118440. r[count*b->dim+k]=val;
  118441. }
  118442. count++;
  118443. }
  118444. }
  118445. break;
  118446. }
  118447. return(r);
  118448. }
  118449. return(NULL);
  118450. }
  118451. void vorbis_staticbook_clear(static_codebook *b){
  118452. if(b->allocedp){
  118453. if(b->quantlist)_ogg_free(b->quantlist);
  118454. if(b->lengthlist)_ogg_free(b->lengthlist);
  118455. if(b->nearest_tree){
  118456. _ogg_free(b->nearest_tree->ptr0);
  118457. _ogg_free(b->nearest_tree->ptr1);
  118458. _ogg_free(b->nearest_tree->p);
  118459. _ogg_free(b->nearest_tree->q);
  118460. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  118461. _ogg_free(b->nearest_tree);
  118462. }
  118463. if(b->thresh_tree){
  118464. _ogg_free(b->thresh_tree->quantthresh);
  118465. _ogg_free(b->thresh_tree->quantmap);
  118466. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  118467. _ogg_free(b->thresh_tree);
  118468. }
  118469. memset(b,0,sizeof(*b));
  118470. }
  118471. }
  118472. void vorbis_staticbook_destroy(static_codebook *b){
  118473. if(b->allocedp){
  118474. vorbis_staticbook_clear(b);
  118475. _ogg_free(b);
  118476. }
  118477. }
  118478. void vorbis_book_clear(codebook *b){
  118479. /* static book is not cleared; we're likely called on the lookup and
  118480. the static codebook belongs to the info struct */
  118481. if(b->valuelist)_ogg_free(b->valuelist);
  118482. if(b->codelist)_ogg_free(b->codelist);
  118483. if(b->dec_index)_ogg_free(b->dec_index);
  118484. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  118485. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  118486. memset(b,0,sizeof(*b));
  118487. }
  118488. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  118489. memset(c,0,sizeof(*c));
  118490. c->c=s;
  118491. c->entries=s->entries;
  118492. c->used_entries=s->entries;
  118493. c->dim=s->dim;
  118494. c->codelist=_make_words(s->lengthlist,s->entries,0);
  118495. c->valuelist=_book_unquantize(s,s->entries,NULL);
  118496. return(0);
  118497. }
  118498. static int sort32a(const void *a,const void *b){
  118499. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  118500. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  118501. }
  118502. /* decode codebook arrangement is more heavily optimized than encode */
  118503. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  118504. int i,j,n=0,tabn;
  118505. int *sortindex;
  118506. memset(c,0,sizeof(*c));
  118507. /* count actually used entries */
  118508. for(i=0;i<s->entries;i++)
  118509. if(s->lengthlist[i]>0)
  118510. n++;
  118511. c->entries=s->entries;
  118512. c->used_entries=n;
  118513. c->dim=s->dim;
  118514. /* two different remappings go on here.
  118515. First, we collapse the likely sparse codebook down only to
  118516. actually represented values/words. This collapsing needs to be
  118517. indexed as map-valueless books are used to encode original entry
  118518. positions as integers.
  118519. Second, we reorder all vectors, including the entry index above,
  118520. by sorted bitreversed codeword to allow treeless decode. */
  118521. {
  118522. /* perform sort */
  118523. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  118524. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  118525. if(codes==NULL)goto err_out;
  118526. for(i=0;i<n;i++){
  118527. codes[i]=ogg_bitreverse(codes[i]);
  118528. codep[i]=codes+i;
  118529. }
  118530. qsort(codep,n,sizeof(*codep),sort32a);
  118531. sortindex=(int*)alloca(n*sizeof(*sortindex));
  118532. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  118533. /* the index is a reverse index */
  118534. for(i=0;i<n;i++){
  118535. int position=codep[i]-codes;
  118536. sortindex[position]=i;
  118537. }
  118538. for(i=0;i<n;i++)
  118539. c->codelist[sortindex[i]]=codes[i];
  118540. _ogg_free(codes);
  118541. }
  118542. c->valuelist=_book_unquantize(s,n,sortindex);
  118543. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  118544. for(n=0,i=0;i<s->entries;i++)
  118545. if(s->lengthlist[i]>0)
  118546. c->dec_index[sortindex[n++]]=i;
  118547. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  118548. for(n=0,i=0;i<s->entries;i++)
  118549. if(s->lengthlist[i]>0)
  118550. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  118551. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  118552. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  118553. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  118554. tabn=1<<c->dec_firsttablen;
  118555. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  118556. c->dec_maxlength=0;
  118557. for(i=0;i<n;i++){
  118558. if(c->dec_maxlength<c->dec_codelengths[i])
  118559. c->dec_maxlength=c->dec_codelengths[i];
  118560. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  118561. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  118562. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  118563. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  118564. }
  118565. }
  118566. /* now fill in 'unused' entries in the firsttable with hi/lo search
  118567. hints for the non-direct-hits */
  118568. {
  118569. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  118570. long lo=0,hi=0;
  118571. for(i=0;i<tabn;i++){
  118572. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  118573. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  118574. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  118575. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  118576. /* we only actually have 15 bits per hint to play with here.
  118577. In order to overflow gracefully (nothing breaks, efficiency
  118578. just drops), encode as the difference from the extremes. */
  118579. {
  118580. unsigned long loval=lo;
  118581. unsigned long hival=n-hi;
  118582. if(loval>0x7fff)loval=0x7fff;
  118583. if(hival>0x7fff)hival=0x7fff;
  118584. c->dec_firsttable[ogg_bitreverse(word)]=
  118585. 0x80000000UL | (loval<<15) | hival;
  118586. }
  118587. }
  118588. }
  118589. }
  118590. return(0);
  118591. err_out:
  118592. vorbis_book_clear(c);
  118593. return(-1);
  118594. }
  118595. static float _dist(int el,float *ref, float *b,int step){
  118596. int i;
  118597. float acc=0.f;
  118598. for(i=0;i<el;i++){
  118599. float val=(ref[i]-b[i*step]);
  118600. acc+=val*val;
  118601. }
  118602. return(acc);
  118603. }
  118604. int _best(codebook *book, float *a, int step){
  118605. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118606. #if 0
  118607. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  118608. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  118609. #endif
  118610. int dim=book->dim;
  118611. int k,o;
  118612. /*int savebest=-1;
  118613. float saverr;*/
  118614. /* do we have a threshhold encode hint? */
  118615. if(tt){
  118616. int index=0,i;
  118617. /* find the quant val of each scalar */
  118618. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118619. i=tt->threshvals>>1;
  118620. if(a[o]<tt->quantthresh[i]){
  118621. for(;i>0;i--)
  118622. if(a[o]>=tt->quantthresh[i-1])
  118623. break;
  118624. }else{
  118625. for(i++;i<tt->threshvals-1;i++)
  118626. if(a[o]<tt->quantthresh[i])break;
  118627. }
  118628. index=(index*tt->quantvals)+tt->quantmap[i];
  118629. }
  118630. /* regular lattices are easy :-) */
  118631. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  118632. use a decision tree after all
  118633. and fall through*/
  118634. return(index);
  118635. }
  118636. #if 0
  118637. /* do we have a pigeonhole encode hint? */
  118638. if(pt){
  118639. const static_codebook *c=book->c;
  118640. int i,besti=-1;
  118641. float best=0.f;
  118642. int entry=0;
  118643. /* dealing with sequentialness is a pain in the ass */
  118644. if(c->q_sequencep){
  118645. int pv;
  118646. long mul=1;
  118647. float qlast=0;
  118648. for(k=0,o=0;k<dim;k++,o+=step){
  118649. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  118650. if(pv<0 || pv>=pt->mapentries)break;
  118651. entry+=pt->pigeonmap[pv]*mul;
  118652. mul*=pt->quantvals;
  118653. qlast+=pv*pt->del+pt->min;
  118654. }
  118655. }else{
  118656. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118657. int pv=(int)((a[o]-pt->min)/pt->del);
  118658. if(pv<0 || pv>=pt->mapentries)break;
  118659. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  118660. }
  118661. }
  118662. /* must be within the pigeonholable range; if we quant outside (or
  118663. in an entry that we define no list for), brute force it */
  118664. if(k==dim && pt->fitlength[entry]){
  118665. /* search the abbreviated list */
  118666. long *list=pt->fitlist+pt->fitmap[entry];
  118667. for(i=0;i<pt->fitlength[entry];i++){
  118668. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  118669. if(besti==-1 || this<best){
  118670. best=this;
  118671. besti=list[i];
  118672. }
  118673. }
  118674. return(besti);
  118675. }
  118676. }
  118677. if(nt){
  118678. /* optimized using the decision tree */
  118679. while(1){
  118680. float c=0.f;
  118681. float *p=book->valuelist+nt->p[ptr];
  118682. float *q=book->valuelist+nt->q[ptr];
  118683. for(k=0,o=0;k<dim;k++,o+=step)
  118684. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  118685. if(c>0.f) /* in A */
  118686. ptr= -nt->ptr0[ptr];
  118687. else /* in B */
  118688. ptr= -nt->ptr1[ptr];
  118689. if(ptr<=0)break;
  118690. }
  118691. return(-ptr);
  118692. }
  118693. #endif
  118694. /* brute force it! */
  118695. {
  118696. const static_codebook *c=book->c;
  118697. int i,besti=-1;
  118698. float best=0.f;
  118699. float *e=book->valuelist;
  118700. for(i=0;i<book->entries;i++){
  118701. if(c->lengthlist[i]>0){
  118702. float thisx=_dist(dim,e,a,step);
  118703. if(besti==-1 || thisx<best){
  118704. best=thisx;
  118705. besti=i;
  118706. }
  118707. }
  118708. e+=dim;
  118709. }
  118710. /*if(savebest!=-1 && savebest!=besti){
  118711. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  118712. "original:");
  118713. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  118714. fprintf(stderr,"\n"
  118715. "pigeonhole (entry %d, err %g):",savebest,saverr);
  118716. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118717. (book->valuelist+savebest*dim)[i]);
  118718. fprintf(stderr,"\n"
  118719. "bruteforce (entry %d, err %g):",besti,best);
  118720. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118721. (book->valuelist+besti*dim)[i]);
  118722. fprintf(stderr,"\n");
  118723. }*/
  118724. return(besti);
  118725. }
  118726. }
  118727. long vorbis_book_codeword(codebook *book,int entry){
  118728. if(book->c) /* only use with encode; decode optimizations are
  118729. allowed to break this */
  118730. return book->codelist[entry];
  118731. return -1;
  118732. }
  118733. long vorbis_book_codelen(codebook *book,int entry){
  118734. if(book->c) /* only use with encode; decode optimizations are
  118735. allowed to break this */
  118736. return book->c->lengthlist[entry];
  118737. return -1;
  118738. }
  118739. #ifdef _V_SELFTEST
  118740. /* Unit tests of the dequantizer; this stuff will be OK
  118741. cross-platform, I simply want to be sure that special mapping cases
  118742. actually work properly; a bug could go unnoticed for a while */
  118743. #include <stdio.h>
  118744. /* cases:
  118745. no mapping
  118746. full, explicit mapping
  118747. algorithmic mapping
  118748. nonsequential
  118749. sequential
  118750. */
  118751. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  118752. static long partial_quantlist1[]={0,7,2};
  118753. /* no mapping */
  118754. static_codebook test1={
  118755. 4,16,
  118756. NULL,
  118757. 0,
  118758. 0,0,0,0,
  118759. NULL,
  118760. NULL,NULL
  118761. };
  118762. static float *test1_result=NULL;
  118763. /* linear, full mapping, nonsequential */
  118764. static_codebook test2={
  118765. 4,3,
  118766. NULL,
  118767. 2,
  118768. -533200896,1611661312,4,0,
  118769. full_quantlist1,
  118770. NULL,NULL
  118771. };
  118772. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  118773. /* linear, full mapping, sequential */
  118774. static_codebook test3={
  118775. 4,3,
  118776. NULL,
  118777. 2,
  118778. -533200896,1611661312,4,1,
  118779. full_quantlist1,
  118780. NULL,NULL
  118781. };
  118782. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  118783. /* linear, algorithmic mapping, nonsequential */
  118784. static_codebook test4={
  118785. 3,27,
  118786. NULL,
  118787. 1,
  118788. -533200896,1611661312,4,0,
  118789. partial_quantlist1,
  118790. NULL,NULL
  118791. };
  118792. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  118793. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  118794. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  118795. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  118796. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  118797. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  118798. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  118799. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  118800. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  118801. /* linear, algorithmic mapping, sequential */
  118802. static_codebook test5={
  118803. 3,27,
  118804. NULL,
  118805. 1,
  118806. -533200896,1611661312,4,1,
  118807. partial_quantlist1,
  118808. NULL,NULL
  118809. };
  118810. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  118811. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  118812. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  118813. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  118814. -3, 1, 5, 4, 8,12, -1, 3, 7,
  118815. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  118816. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  118817. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  118818. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  118819. void run_test(static_codebook *b,float *comp){
  118820. float *out=_book_unquantize(b,b->entries,NULL);
  118821. int i;
  118822. if(comp){
  118823. if(!out){
  118824. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  118825. exit(1);
  118826. }
  118827. for(i=0;i<b->entries*b->dim;i++)
  118828. if(fabs(out[i]-comp[i])>.0001){
  118829. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  118830. "position %d, %g != %g\n",i,out[i],comp[i]);
  118831. exit(1);
  118832. }
  118833. }else{
  118834. if(out){
  118835. fprintf(stderr,"_book_unquantize returned a value array: \n"
  118836. " correct result should have been NULL\n");
  118837. exit(1);
  118838. }
  118839. }
  118840. }
  118841. int main(){
  118842. /* run the nine dequant tests, and compare to the hand-rolled results */
  118843. fprintf(stderr,"Dequant test 1... ");
  118844. run_test(&test1,test1_result);
  118845. fprintf(stderr,"OK\nDequant test 2... ");
  118846. run_test(&test2,test2_result);
  118847. fprintf(stderr,"OK\nDequant test 3... ");
  118848. run_test(&test3,test3_result);
  118849. fprintf(stderr,"OK\nDequant test 4... ");
  118850. run_test(&test4,test4_result);
  118851. fprintf(stderr,"OK\nDequant test 5... ");
  118852. run_test(&test5,test5_result);
  118853. fprintf(stderr,"OK\n\n");
  118854. return(0);
  118855. }
  118856. #endif
  118857. #endif
  118858. /*** End of inlined file: sharedbook.c ***/
  118859. /*** Start of inlined file: smallft.c ***/
  118860. /* FFT implementation from OggSquish, minus cosine transforms,
  118861. * minus all but radix 2/4 case. In Vorbis we only need this
  118862. * cut-down version.
  118863. *
  118864. * To do more than just power-of-two sized vectors, see the full
  118865. * version I wrote for NetLib.
  118866. *
  118867. * Note that the packing is a little strange; rather than the FFT r/i
  118868. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  118869. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  118870. * FORTRAN version
  118871. */
  118872. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118873. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118874. // tasks..
  118875. #if JUCE_MSVC
  118876. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118877. #endif
  118878. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118879. #if JUCE_USE_OGGVORBIS
  118880. #include <stdlib.h>
  118881. #include <string.h>
  118882. #include <math.h>
  118883. static void drfti1(int n, float *wa, int *ifac){
  118884. static int ntryh[4] = { 4,2,3,5 };
  118885. static float tpi = 6.28318530717958648f;
  118886. float arg,argh,argld,fi;
  118887. int ntry=0,i,j=-1;
  118888. int k1, l1, l2, ib;
  118889. int ld, ii, ip, is, nq, nr;
  118890. int ido, ipm, nfm1;
  118891. int nl=n;
  118892. int nf=0;
  118893. L101:
  118894. j++;
  118895. if (j < 4)
  118896. ntry=ntryh[j];
  118897. else
  118898. ntry+=2;
  118899. L104:
  118900. nq=nl/ntry;
  118901. nr=nl-ntry*nq;
  118902. if (nr!=0) goto L101;
  118903. nf++;
  118904. ifac[nf+1]=ntry;
  118905. nl=nq;
  118906. if(ntry!=2)goto L107;
  118907. if(nf==1)goto L107;
  118908. for (i=1;i<nf;i++){
  118909. ib=nf-i+1;
  118910. ifac[ib+1]=ifac[ib];
  118911. }
  118912. ifac[2] = 2;
  118913. L107:
  118914. if(nl!=1)goto L104;
  118915. ifac[0]=n;
  118916. ifac[1]=nf;
  118917. argh=tpi/n;
  118918. is=0;
  118919. nfm1=nf-1;
  118920. l1=1;
  118921. if(nfm1==0)return;
  118922. for (k1=0;k1<nfm1;k1++){
  118923. ip=ifac[k1+2];
  118924. ld=0;
  118925. l2=l1*ip;
  118926. ido=n/l2;
  118927. ipm=ip-1;
  118928. for (j=0;j<ipm;j++){
  118929. ld+=l1;
  118930. i=is;
  118931. argld=(float)ld*argh;
  118932. fi=0.f;
  118933. for (ii=2;ii<ido;ii+=2){
  118934. fi+=1.f;
  118935. arg=fi*argld;
  118936. wa[i++]=cos(arg);
  118937. wa[i++]=sin(arg);
  118938. }
  118939. is+=ido;
  118940. }
  118941. l1=l2;
  118942. }
  118943. }
  118944. static void fdrffti(int n, float *wsave, int *ifac){
  118945. if (n == 1) return;
  118946. drfti1(n, wsave+n, ifac);
  118947. }
  118948. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  118949. int i,k;
  118950. float ti2,tr2;
  118951. int t0,t1,t2,t3,t4,t5,t6;
  118952. t1=0;
  118953. t0=(t2=l1*ido);
  118954. t3=ido<<1;
  118955. for(k=0;k<l1;k++){
  118956. ch[t1<<1]=cc[t1]+cc[t2];
  118957. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  118958. t1+=ido;
  118959. t2+=ido;
  118960. }
  118961. if(ido<2)return;
  118962. if(ido==2)goto L105;
  118963. t1=0;
  118964. t2=t0;
  118965. for(k=0;k<l1;k++){
  118966. t3=t2;
  118967. t4=(t1<<1)+(ido<<1);
  118968. t5=t1;
  118969. t6=t1+t1;
  118970. for(i=2;i<ido;i+=2){
  118971. t3+=2;
  118972. t4-=2;
  118973. t5+=2;
  118974. t6+=2;
  118975. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  118976. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  118977. ch[t6]=cc[t5]+ti2;
  118978. ch[t4]=ti2-cc[t5];
  118979. ch[t6-1]=cc[t5-1]+tr2;
  118980. ch[t4-1]=cc[t5-1]-tr2;
  118981. }
  118982. t1+=ido;
  118983. t2+=ido;
  118984. }
  118985. if(ido%2==1)return;
  118986. L105:
  118987. t3=(t2=(t1=ido)-1);
  118988. t2+=t0;
  118989. for(k=0;k<l1;k++){
  118990. ch[t1]=-cc[t2];
  118991. ch[t1-1]=cc[t3];
  118992. t1+=ido<<1;
  118993. t2+=ido;
  118994. t3+=ido;
  118995. }
  118996. }
  118997. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  118998. float *wa2,float *wa3){
  118999. static float hsqt2 = .70710678118654752f;
  119000. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119001. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119002. t0=l1*ido;
  119003. t1=t0;
  119004. t4=t1<<1;
  119005. t2=t1+(t1<<1);
  119006. t3=0;
  119007. for(k=0;k<l1;k++){
  119008. tr1=cc[t1]+cc[t2];
  119009. tr2=cc[t3]+cc[t4];
  119010. ch[t5=t3<<2]=tr1+tr2;
  119011. ch[(ido<<2)+t5-1]=tr2-tr1;
  119012. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119013. ch[t5]=cc[t2]-cc[t1];
  119014. t1+=ido;
  119015. t2+=ido;
  119016. t3+=ido;
  119017. t4+=ido;
  119018. }
  119019. if(ido<2)return;
  119020. if(ido==2)goto L105;
  119021. t1=0;
  119022. for(k=0;k<l1;k++){
  119023. t2=t1;
  119024. t4=t1<<2;
  119025. t5=(t6=ido<<1)+t4;
  119026. for(i=2;i<ido;i+=2){
  119027. t3=(t2+=2);
  119028. t4+=2;
  119029. t5-=2;
  119030. t3+=t0;
  119031. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119032. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119033. t3+=t0;
  119034. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119035. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119036. t3+=t0;
  119037. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119038. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119039. tr1=cr2+cr4;
  119040. tr4=cr4-cr2;
  119041. ti1=ci2+ci4;
  119042. ti4=ci2-ci4;
  119043. ti2=cc[t2]+ci3;
  119044. ti3=cc[t2]-ci3;
  119045. tr2=cc[t2-1]+cr3;
  119046. tr3=cc[t2-1]-cr3;
  119047. ch[t4-1]=tr1+tr2;
  119048. ch[t4]=ti1+ti2;
  119049. ch[t5-1]=tr3-ti4;
  119050. ch[t5]=tr4-ti3;
  119051. ch[t4+t6-1]=ti4+tr3;
  119052. ch[t4+t6]=tr4+ti3;
  119053. ch[t5+t6-1]=tr2-tr1;
  119054. ch[t5+t6]=ti1-ti2;
  119055. }
  119056. t1+=ido;
  119057. }
  119058. if(ido&1)return;
  119059. L105:
  119060. t2=(t1=t0+ido-1)+(t0<<1);
  119061. t3=ido<<2;
  119062. t4=ido;
  119063. t5=ido<<1;
  119064. t6=ido;
  119065. for(k=0;k<l1;k++){
  119066. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119067. tr1=hsqt2*(cc[t1]-cc[t2]);
  119068. ch[t4-1]=tr1+cc[t6-1];
  119069. ch[t4+t5-1]=cc[t6-1]-tr1;
  119070. ch[t4]=ti1-cc[t1+t0];
  119071. ch[t4+t5]=ti1+cc[t1+t0];
  119072. t1+=ido;
  119073. t2+=ido;
  119074. t4+=t3;
  119075. t6+=ido;
  119076. }
  119077. }
  119078. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119079. float *c2,float *ch,float *ch2,float *wa){
  119080. static float tpi=6.283185307179586f;
  119081. int idij,ipph,i,j,k,l,ic,ik,is;
  119082. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119083. float dc2,ai1,ai2,ar1,ar2,ds2;
  119084. int nbd;
  119085. float dcp,arg,dsp,ar1h,ar2h;
  119086. int idp2,ipp2;
  119087. arg=tpi/(float)ip;
  119088. dcp=cos(arg);
  119089. dsp=sin(arg);
  119090. ipph=(ip+1)>>1;
  119091. ipp2=ip;
  119092. idp2=ido;
  119093. nbd=(ido-1)>>1;
  119094. t0=l1*ido;
  119095. t10=ip*ido;
  119096. if(ido==1)goto L119;
  119097. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119098. t1=0;
  119099. for(j=1;j<ip;j++){
  119100. t1+=t0;
  119101. t2=t1;
  119102. for(k=0;k<l1;k++){
  119103. ch[t2]=c1[t2];
  119104. t2+=ido;
  119105. }
  119106. }
  119107. is=-ido;
  119108. t1=0;
  119109. if(nbd>l1){
  119110. for(j=1;j<ip;j++){
  119111. t1+=t0;
  119112. is+=ido;
  119113. t2= -ido+t1;
  119114. for(k=0;k<l1;k++){
  119115. idij=is-1;
  119116. t2+=ido;
  119117. t3=t2;
  119118. for(i=2;i<ido;i+=2){
  119119. idij+=2;
  119120. t3+=2;
  119121. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119122. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119123. }
  119124. }
  119125. }
  119126. }else{
  119127. for(j=1;j<ip;j++){
  119128. is+=ido;
  119129. idij=is-1;
  119130. t1+=t0;
  119131. t2=t1;
  119132. for(i=2;i<ido;i+=2){
  119133. idij+=2;
  119134. t2+=2;
  119135. t3=t2;
  119136. for(k=0;k<l1;k++){
  119137. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119138. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119139. t3+=ido;
  119140. }
  119141. }
  119142. }
  119143. }
  119144. t1=0;
  119145. t2=ipp2*t0;
  119146. if(nbd<l1){
  119147. for(j=1;j<ipph;j++){
  119148. t1+=t0;
  119149. t2-=t0;
  119150. t3=t1;
  119151. t4=t2;
  119152. for(i=2;i<ido;i+=2){
  119153. t3+=2;
  119154. t4+=2;
  119155. t5=t3-ido;
  119156. t6=t4-ido;
  119157. for(k=0;k<l1;k++){
  119158. t5+=ido;
  119159. t6+=ido;
  119160. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119161. c1[t6-1]=ch[t5]-ch[t6];
  119162. c1[t5]=ch[t5]+ch[t6];
  119163. c1[t6]=ch[t6-1]-ch[t5-1];
  119164. }
  119165. }
  119166. }
  119167. }else{
  119168. for(j=1;j<ipph;j++){
  119169. t1+=t0;
  119170. t2-=t0;
  119171. t3=t1;
  119172. t4=t2;
  119173. for(k=0;k<l1;k++){
  119174. t5=t3;
  119175. t6=t4;
  119176. for(i=2;i<ido;i+=2){
  119177. t5+=2;
  119178. t6+=2;
  119179. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119180. c1[t6-1]=ch[t5]-ch[t6];
  119181. c1[t5]=ch[t5]+ch[t6];
  119182. c1[t6]=ch[t6-1]-ch[t5-1];
  119183. }
  119184. t3+=ido;
  119185. t4+=ido;
  119186. }
  119187. }
  119188. }
  119189. L119:
  119190. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119191. t1=0;
  119192. t2=ipp2*idl1;
  119193. for(j=1;j<ipph;j++){
  119194. t1+=t0;
  119195. t2-=t0;
  119196. t3=t1-ido;
  119197. t4=t2-ido;
  119198. for(k=0;k<l1;k++){
  119199. t3+=ido;
  119200. t4+=ido;
  119201. c1[t3]=ch[t3]+ch[t4];
  119202. c1[t4]=ch[t4]-ch[t3];
  119203. }
  119204. }
  119205. ar1=1.f;
  119206. ai1=0.f;
  119207. t1=0;
  119208. t2=ipp2*idl1;
  119209. t3=(ip-1)*idl1;
  119210. for(l=1;l<ipph;l++){
  119211. t1+=idl1;
  119212. t2-=idl1;
  119213. ar1h=dcp*ar1-dsp*ai1;
  119214. ai1=dcp*ai1+dsp*ar1;
  119215. ar1=ar1h;
  119216. t4=t1;
  119217. t5=t2;
  119218. t6=t3;
  119219. t7=idl1;
  119220. for(ik=0;ik<idl1;ik++){
  119221. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119222. ch2[t5++]=ai1*c2[t6++];
  119223. }
  119224. dc2=ar1;
  119225. ds2=ai1;
  119226. ar2=ar1;
  119227. ai2=ai1;
  119228. t4=idl1;
  119229. t5=(ipp2-1)*idl1;
  119230. for(j=2;j<ipph;j++){
  119231. t4+=idl1;
  119232. t5-=idl1;
  119233. ar2h=dc2*ar2-ds2*ai2;
  119234. ai2=dc2*ai2+ds2*ar2;
  119235. ar2=ar2h;
  119236. t6=t1;
  119237. t7=t2;
  119238. t8=t4;
  119239. t9=t5;
  119240. for(ik=0;ik<idl1;ik++){
  119241. ch2[t6++]+=ar2*c2[t8++];
  119242. ch2[t7++]+=ai2*c2[t9++];
  119243. }
  119244. }
  119245. }
  119246. t1=0;
  119247. for(j=1;j<ipph;j++){
  119248. t1+=idl1;
  119249. t2=t1;
  119250. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119251. }
  119252. if(ido<l1)goto L132;
  119253. t1=0;
  119254. t2=0;
  119255. for(k=0;k<l1;k++){
  119256. t3=t1;
  119257. t4=t2;
  119258. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119259. t1+=ido;
  119260. t2+=t10;
  119261. }
  119262. goto L135;
  119263. L132:
  119264. for(i=0;i<ido;i++){
  119265. t1=i;
  119266. t2=i;
  119267. for(k=0;k<l1;k++){
  119268. cc[t2]=ch[t1];
  119269. t1+=ido;
  119270. t2+=t10;
  119271. }
  119272. }
  119273. L135:
  119274. t1=0;
  119275. t2=ido<<1;
  119276. t3=0;
  119277. t4=ipp2*t0;
  119278. for(j=1;j<ipph;j++){
  119279. t1+=t2;
  119280. t3+=t0;
  119281. t4-=t0;
  119282. t5=t1;
  119283. t6=t3;
  119284. t7=t4;
  119285. for(k=0;k<l1;k++){
  119286. cc[t5-1]=ch[t6];
  119287. cc[t5]=ch[t7];
  119288. t5+=t10;
  119289. t6+=ido;
  119290. t7+=ido;
  119291. }
  119292. }
  119293. if(ido==1)return;
  119294. if(nbd<l1)goto L141;
  119295. t1=-ido;
  119296. t3=0;
  119297. t4=0;
  119298. t5=ipp2*t0;
  119299. for(j=1;j<ipph;j++){
  119300. t1+=t2;
  119301. t3+=t2;
  119302. t4+=t0;
  119303. t5-=t0;
  119304. t6=t1;
  119305. t7=t3;
  119306. t8=t4;
  119307. t9=t5;
  119308. for(k=0;k<l1;k++){
  119309. for(i=2;i<ido;i+=2){
  119310. ic=idp2-i;
  119311. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119312. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119313. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119314. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119315. }
  119316. t6+=t10;
  119317. t7+=t10;
  119318. t8+=ido;
  119319. t9+=ido;
  119320. }
  119321. }
  119322. return;
  119323. L141:
  119324. t1=-ido;
  119325. t3=0;
  119326. t4=0;
  119327. t5=ipp2*t0;
  119328. for(j=1;j<ipph;j++){
  119329. t1+=t2;
  119330. t3+=t2;
  119331. t4+=t0;
  119332. t5-=t0;
  119333. for(i=2;i<ido;i+=2){
  119334. t6=idp2+t1-i;
  119335. t7=i+t3;
  119336. t8=i+t4;
  119337. t9=i+t5;
  119338. for(k=0;k<l1;k++){
  119339. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119340. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119341. cc[t7]=ch[t8]+ch[t9];
  119342. cc[t6]=ch[t9]-ch[t8];
  119343. t6+=t10;
  119344. t7+=t10;
  119345. t8+=ido;
  119346. t9+=ido;
  119347. }
  119348. }
  119349. }
  119350. }
  119351. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119352. int i,k1,l1,l2;
  119353. int na,kh,nf;
  119354. int ip,iw,ido,idl1,ix2,ix3;
  119355. nf=ifac[1];
  119356. na=1;
  119357. l2=n;
  119358. iw=n;
  119359. for(k1=0;k1<nf;k1++){
  119360. kh=nf-k1;
  119361. ip=ifac[kh+1];
  119362. l1=l2/ip;
  119363. ido=n/l2;
  119364. idl1=ido*l1;
  119365. iw-=(ip-1)*ido;
  119366. na=1-na;
  119367. if(ip!=4)goto L102;
  119368. ix2=iw+ido;
  119369. ix3=ix2+ido;
  119370. if(na!=0)
  119371. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119372. else
  119373. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119374. goto L110;
  119375. L102:
  119376. if(ip!=2)goto L104;
  119377. if(na!=0)goto L103;
  119378. dradf2(ido,l1,c,ch,wa+iw-1);
  119379. goto L110;
  119380. L103:
  119381. dradf2(ido,l1,ch,c,wa+iw-1);
  119382. goto L110;
  119383. L104:
  119384. if(ido==1)na=1-na;
  119385. if(na!=0)goto L109;
  119386. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119387. na=1;
  119388. goto L110;
  119389. L109:
  119390. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119391. na=0;
  119392. L110:
  119393. l2=l1;
  119394. }
  119395. if(na==1)return;
  119396. for(i=0;i<n;i++)c[i]=ch[i];
  119397. }
  119398. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  119399. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119400. float ti2,tr2;
  119401. t0=l1*ido;
  119402. t1=0;
  119403. t2=0;
  119404. t3=(ido<<1)-1;
  119405. for(k=0;k<l1;k++){
  119406. ch[t1]=cc[t2]+cc[t3+t2];
  119407. ch[t1+t0]=cc[t2]-cc[t3+t2];
  119408. t2=(t1+=ido)<<1;
  119409. }
  119410. if(ido<2)return;
  119411. if(ido==2)goto L105;
  119412. t1=0;
  119413. t2=0;
  119414. for(k=0;k<l1;k++){
  119415. t3=t1;
  119416. t5=(t4=t2)+(ido<<1);
  119417. t6=t0+t1;
  119418. for(i=2;i<ido;i+=2){
  119419. t3+=2;
  119420. t4+=2;
  119421. t5-=2;
  119422. t6+=2;
  119423. ch[t3-1]=cc[t4-1]+cc[t5-1];
  119424. tr2=cc[t4-1]-cc[t5-1];
  119425. ch[t3]=cc[t4]-cc[t5];
  119426. ti2=cc[t4]+cc[t5];
  119427. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  119428. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  119429. }
  119430. t2=(t1+=ido)<<1;
  119431. }
  119432. if(ido%2==1)return;
  119433. L105:
  119434. t1=ido-1;
  119435. t2=ido-1;
  119436. for(k=0;k<l1;k++){
  119437. ch[t1]=cc[t2]+cc[t2];
  119438. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  119439. t1+=ido;
  119440. t2+=ido<<1;
  119441. }
  119442. }
  119443. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  119444. float *wa2){
  119445. static float taur = -.5f;
  119446. static float taui = .8660254037844386f;
  119447. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119448. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  119449. t0=l1*ido;
  119450. t1=0;
  119451. t2=t0<<1;
  119452. t3=ido<<1;
  119453. t4=ido+(ido<<1);
  119454. t5=0;
  119455. for(k=0;k<l1;k++){
  119456. tr2=cc[t3-1]+cc[t3-1];
  119457. cr2=cc[t5]+(taur*tr2);
  119458. ch[t1]=cc[t5]+tr2;
  119459. ci3=taui*(cc[t3]+cc[t3]);
  119460. ch[t1+t0]=cr2-ci3;
  119461. ch[t1+t2]=cr2+ci3;
  119462. t1+=ido;
  119463. t3+=t4;
  119464. t5+=t4;
  119465. }
  119466. if(ido==1)return;
  119467. t1=0;
  119468. t3=ido<<1;
  119469. for(k=0;k<l1;k++){
  119470. t7=t1+(t1<<1);
  119471. t6=(t5=t7+t3);
  119472. t8=t1;
  119473. t10=(t9=t1+t0)+t0;
  119474. for(i=2;i<ido;i+=2){
  119475. t5+=2;
  119476. t6-=2;
  119477. t7+=2;
  119478. t8+=2;
  119479. t9+=2;
  119480. t10+=2;
  119481. tr2=cc[t5-1]+cc[t6-1];
  119482. cr2=cc[t7-1]+(taur*tr2);
  119483. ch[t8-1]=cc[t7-1]+tr2;
  119484. ti2=cc[t5]-cc[t6];
  119485. ci2=cc[t7]+(taur*ti2);
  119486. ch[t8]=cc[t7]+ti2;
  119487. cr3=taui*(cc[t5-1]-cc[t6-1]);
  119488. ci3=taui*(cc[t5]+cc[t6]);
  119489. dr2=cr2-ci3;
  119490. dr3=cr2+ci3;
  119491. di2=ci2+cr3;
  119492. di3=ci2-cr3;
  119493. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  119494. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  119495. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  119496. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  119497. }
  119498. t1+=ido;
  119499. }
  119500. }
  119501. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  119502. float *wa2,float *wa3){
  119503. static float sqrt2=1.414213562373095f;
  119504. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  119505. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119506. t0=l1*ido;
  119507. t1=0;
  119508. t2=ido<<2;
  119509. t3=0;
  119510. t6=ido<<1;
  119511. for(k=0;k<l1;k++){
  119512. t4=t3+t6;
  119513. t5=t1;
  119514. tr3=cc[t4-1]+cc[t4-1];
  119515. tr4=cc[t4]+cc[t4];
  119516. tr1=cc[t3]-cc[(t4+=t6)-1];
  119517. tr2=cc[t3]+cc[t4-1];
  119518. ch[t5]=tr2+tr3;
  119519. ch[t5+=t0]=tr1-tr4;
  119520. ch[t5+=t0]=tr2-tr3;
  119521. ch[t5+=t0]=tr1+tr4;
  119522. t1+=ido;
  119523. t3+=t2;
  119524. }
  119525. if(ido<2)return;
  119526. if(ido==2)goto L105;
  119527. t1=0;
  119528. for(k=0;k<l1;k++){
  119529. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  119530. t7=t1;
  119531. for(i=2;i<ido;i+=2){
  119532. t2+=2;
  119533. t3+=2;
  119534. t4-=2;
  119535. t5-=2;
  119536. t7+=2;
  119537. ti1=cc[t2]+cc[t5];
  119538. ti2=cc[t2]-cc[t5];
  119539. ti3=cc[t3]-cc[t4];
  119540. tr4=cc[t3]+cc[t4];
  119541. tr1=cc[t2-1]-cc[t5-1];
  119542. tr2=cc[t2-1]+cc[t5-1];
  119543. ti4=cc[t3-1]-cc[t4-1];
  119544. tr3=cc[t3-1]+cc[t4-1];
  119545. ch[t7-1]=tr2+tr3;
  119546. cr3=tr2-tr3;
  119547. ch[t7]=ti2+ti3;
  119548. ci3=ti2-ti3;
  119549. cr2=tr1-tr4;
  119550. cr4=tr1+tr4;
  119551. ci2=ti1+ti4;
  119552. ci4=ti1-ti4;
  119553. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  119554. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  119555. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  119556. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  119557. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  119558. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  119559. }
  119560. t1+=ido;
  119561. }
  119562. if(ido%2 == 1)return;
  119563. L105:
  119564. t1=ido;
  119565. t2=ido<<2;
  119566. t3=ido-1;
  119567. t4=ido+(ido<<1);
  119568. for(k=0;k<l1;k++){
  119569. t5=t3;
  119570. ti1=cc[t1]+cc[t4];
  119571. ti2=cc[t4]-cc[t1];
  119572. tr1=cc[t1-1]-cc[t4-1];
  119573. tr2=cc[t1-1]+cc[t4-1];
  119574. ch[t5]=tr2+tr2;
  119575. ch[t5+=t0]=sqrt2*(tr1-ti1);
  119576. ch[t5+=t0]=ti2+ti2;
  119577. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  119578. t3+=ido;
  119579. t1+=t2;
  119580. t4+=t2;
  119581. }
  119582. }
  119583. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119584. float *c2,float *ch,float *ch2,float *wa){
  119585. static float tpi=6.283185307179586f;
  119586. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  119587. t11,t12;
  119588. float dc2,ai1,ai2,ar1,ar2,ds2;
  119589. int nbd;
  119590. float dcp,arg,dsp,ar1h,ar2h;
  119591. int ipp2;
  119592. t10=ip*ido;
  119593. t0=l1*ido;
  119594. arg=tpi/(float)ip;
  119595. dcp=cos(arg);
  119596. dsp=sin(arg);
  119597. nbd=(ido-1)>>1;
  119598. ipp2=ip;
  119599. ipph=(ip+1)>>1;
  119600. if(ido<l1)goto L103;
  119601. t1=0;
  119602. t2=0;
  119603. for(k=0;k<l1;k++){
  119604. t3=t1;
  119605. t4=t2;
  119606. for(i=0;i<ido;i++){
  119607. ch[t3]=cc[t4];
  119608. t3++;
  119609. t4++;
  119610. }
  119611. t1+=ido;
  119612. t2+=t10;
  119613. }
  119614. goto L106;
  119615. L103:
  119616. t1=0;
  119617. for(i=0;i<ido;i++){
  119618. t2=t1;
  119619. t3=t1;
  119620. for(k=0;k<l1;k++){
  119621. ch[t2]=cc[t3];
  119622. t2+=ido;
  119623. t3+=t10;
  119624. }
  119625. t1++;
  119626. }
  119627. L106:
  119628. t1=0;
  119629. t2=ipp2*t0;
  119630. t7=(t5=ido<<1);
  119631. for(j=1;j<ipph;j++){
  119632. t1+=t0;
  119633. t2-=t0;
  119634. t3=t1;
  119635. t4=t2;
  119636. t6=t5;
  119637. for(k=0;k<l1;k++){
  119638. ch[t3]=cc[t6-1]+cc[t6-1];
  119639. ch[t4]=cc[t6]+cc[t6];
  119640. t3+=ido;
  119641. t4+=ido;
  119642. t6+=t10;
  119643. }
  119644. t5+=t7;
  119645. }
  119646. if (ido == 1)goto L116;
  119647. if(nbd<l1)goto L112;
  119648. t1=0;
  119649. t2=ipp2*t0;
  119650. t7=0;
  119651. for(j=1;j<ipph;j++){
  119652. t1+=t0;
  119653. t2-=t0;
  119654. t3=t1;
  119655. t4=t2;
  119656. t7+=(ido<<1);
  119657. t8=t7;
  119658. for(k=0;k<l1;k++){
  119659. t5=t3;
  119660. t6=t4;
  119661. t9=t8;
  119662. t11=t8;
  119663. for(i=2;i<ido;i+=2){
  119664. t5+=2;
  119665. t6+=2;
  119666. t9+=2;
  119667. t11-=2;
  119668. ch[t5-1]=cc[t9-1]+cc[t11-1];
  119669. ch[t6-1]=cc[t9-1]-cc[t11-1];
  119670. ch[t5]=cc[t9]-cc[t11];
  119671. ch[t6]=cc[t9]+cc[t11];
  119672. }
  119673. t3+=ido;
  119674. t4+=ido;
  119675. t8+=t10;
  119676. }
  119677. }
  119678. goto L116;
  119679. L112:
  119680. t1=0;
  119681. t2=ipp2*t0;
  119682. t7=0;
  119683. for(j=1;j<ipph;j++){
  119684. t1+=t0;
  119685. t2-=t0;
  119686. t3=t1;
  119687. t4=t2;
  119688. t7+=(ido<<1);
  119689. t8=t7;
  119690. t9=t7;
  119691. for(i=2;i<ido;i+=2){
  119692. t3+=2;
  119693. t4+=2;
  119694. t8+=2;
  119695. t9-=2;
  119696. t5=t3;
  119697. t6=t4;
  119698. t11=t8;
  119699. t12=t9;
  119700. for(k=0;k<l1;k++){
  119701. ch[t5-1]=cc[t11-1]+cc[t12-1];
  119702. ch[t6-1]=cc[t11-1]-cc[t12-1];
  119703. ch[t5]=cc[t11]-cc[t12];
  119704. ch[t6]=cc[t11]+cc[t12];
  119705. t5+=ido;
  119706. t6+=ido;
  119707. t11+=t10;
  119708. t12+=t10;
  119709. }
  119710. }
  119711. }
  119712. L116:
  119713. ar1=1.f;
  119714. ai1=0.f;
  119715. t1=0;
  119716. t9=(t2=ipp2*idl1);
  119717. t3=(ip-1)*idl1;
  119718. for(l=1;l<ipph;l++){
  119719. t1+=idl1;
  119720. t2-=idl1;
  119721. ar1h=dcp*ar1-dsp*ai1;
  119722. ai1=dcp*ai1+dsp*ar1;
  119723. ar1=ar1h;
  119724. t4=t1;
  119725. t5=t2;
  119726. t6=0;
  119727. t7=idl1;
  119728. t8=t3;
  119729. for(ik=0;ik<idl1;ik++){
  119730. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  119731. c2[t5++]=ai1*ch2[t8++];
  119732. }
  119733. dc2=ar1;
  119734. ds2=ai1;
  119735. ar2=ar1;
  119736. ai2=ai1;
  119737. t6=idl1;
  119738. t7=t9-idl1;
  119739. for(j=2;j<ipph;j++){
  119740. t6+=idl1;
  119741. t7-=idl1;
  119742. ar2h=dc2*ar2-ds2*ai2;
  119743. ai2=dc2*ai2+ds2*ar2;
  119744. ar2=ar2h;
  119745. t4=t1;
  119746. t5=t2;
  119747. t11=t6;
  119748. t12=t7;
  119749. for(ik=0;ik<idl1;ik++){
  119750. c2[t4++]+=ar2*ch2[t11++];
  119751. c2[t5++]+=ai2*ch2[t12++];
  119752. }
  119753. }
  119754. }
  119755. t1=0;
  119756. for(j=1;j<ipph;j++){
  119757. t1+=idl1;
  119758. t2=t1;
  119759. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  119760. }
  119761. t1=0;
  119762. t2=ipp2*t0;
  119763. for(j=1;j<ipph;j++){
  119764. t1+=t0;
  119765. t2-=t0;
  119766. t3=t1;
  119767. t4=t2;
  119768. for(k=0;k<l1;k++){
  119769. ch[t3]=c1[t3]-c1[t4];
  119770. ch[t4]=c1[t3]+c1[t4];
  119771. t3+=ido;
  119772. t4+=ido;
  119773. }
  119774. }
  119775. if(ido==1)goto L132;
  119776. if(nbd<l1)goto L128;
  119777. t1=0;
  119778. t2=ipp2*t0;
  119779. for(j=1;j<ipph;j++){
  119780. t1+=t0;
  119781. t2-=t0;
  119782. t3=t1;
  119783. t4=t2;
  119784. for(k=0;k<l1;k++){
  119785. t5=t3;
  119786. t6=t4;
  119787. for(i=2;i<ido;i+=2){
  119788. t5+=2;
  119789. t6+=2;
  119790. ch[t5-1]=c1[t5-1]-c1[t6];
  119791. ch[t6-1]=c1[t5-1]+c1[t6];
  119792. ch[t5]=c1[t5]+c1[t6-1];
  119793. ch[t6]=c1[t5]-c1[t6-1];
  119794. }
  119795. t3+=ido;
  119796. t4+=ido;
  119797. }
  119798. }
  119799. goto L132;
  119800. L128:
  119801. t1=0;
  119802. t2=ipp2*t0;
  119803. for(j=1;j<ipph;j++){
  119804. t1+=t0;
  119805. t2-=t0;
  119806. t3=t1;
  119807. t4=t2;
  119808. for(i=2;i<ido;i+=2){
  119809. t3+=2;
  119810. t4+=2;
  119811. t5=t3;
  119812. t6=t4;
  119813. for(k=0;k<l1;k++){
  119814. ch[t5-1]=c1[t5-1]-c1[t6];
  119815. ch[t6-1]=c1[t5-1]+c1[t6];
  119816. ch[t5]=c1[t5]+c1[t6-1];
  119817. ch[t6]=c1[t5]-c1[t6-1];
  119818. t5+=ido;
  119819. t6+=ido;
  119820. }
  119821. }
  119822. }
  119823. L132:
  119824. if(ido==1)return;
  119825. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119826. t1=0;
  119827. for(j=1;j<ip;j++){
  119828. t2=(t1+=t0);
  119829. for(k=0;k<l1;k++){
  119830. c1[t2]=ch[t2];
  119831. t2+=ido;
  119832. }
  119833. }
  119834. if(nbd>l1)goto L139;
  119835. is= -ido-1;
  119836. t1=0;
  119837. for(j=1;j<ip;j++){
  119838. is+=ido;
  119839. t1+=t0;
  119840. idij=is;
  119841. t2=t1;
  119842. for(i=2;i<ido;i+=2){
  119843. t2+=2;
  119844. idij+=2;
  119845. t3=t2;
  119846. for(k=0;k<l1;k++){
  119847. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  119848. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  119849. t3+=ido;
  119850. }
  119851. }
  119852. }
  119853. return;
  119854. L139:
  119855. is= -ido-1;
  119856. t1=0;
  119857. for(j=1;j<ip;j++){
  119858. is+=ido;
  119859. t1+=t0;
  119860. t2=t1;
  119861. for(k=0;k<l1;k++){
  119862. idij=is;
  119863. t3=t2;
  119864. for(i=2;i<ido;i+=2){
  119865. idij+=2;
  119866. t3+=2;
  119867. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  119868. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  119869. }
  119870. t2+=ido;
  119871. }
  119872. }
  119873. }
  119874. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  119875. int i,k1,l1,l2;
  119876. int na;
  119877. int nf,ip,iw,ix2,ix3,ido,idl1;
  119878. nf=ifac[1];
  119879. na=0;
  119880. l1=1;
  119881. iw=1;
  119882. for(k1=0;k1<nf;k1++){
  119883. ip=ifac[k1 + 2];
  119884. l2=ip*l1;
  119885. ido=n/l2;
  119886. idl1=ido*l1;
  119887. if(ip!=4)goto L103;
  119888. ix2=iw+ido;
  119889. ix3=ix2+ido;
  119890. if(na!=0)
  119891. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119892. else
  119893. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119894. na=1-na;
  119895. goto L115;
  119896. L103:
  119897. if(ip!=2)goto L106;
  119898. if(na!=0)
  119899. dradb2(ido,l1,ch,c,wa+iw-1);
  119900. else
  119901. dradb2(ido,l1,c,ch,wa+iw-1);
  119902. na=1-na;
  119903. goto L115;
  119904. L106:
  119905. if(ip!=3)goto L109;
  119906. ix2=iw+ido;
  119907. if(na!=0)
  119908. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  119909. else
  119910. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  119911. na=1-na;
  119912. goto L115;
  119913. L109:
  119914. /* The radix five case can be translated later..... */
  119915. /* if(ip!=5)goto L112;
  119916. ix2=iw+ido;
  119917. ix3=ix2+ido;
  119918. ix4=ix3+ido;
  119919. if(na!=0)
  119920. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  119921. else
  119922. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  119923. na=1-na;
  119924. goto L115;
  119925. L112:*/
  119926. if(na!=0)
  119927. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119928. else
  119929. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119930. if(ido==1)na=1-na;
  119931. L115:
  119932. l1=l2;
  119933. iw+=(ip-1)*ido;
  119934. }
  119935. if(na==0)return;
  119936. for(i=0;i<n;i++)c[i]=ch[i];
  119937. }
  119938. void drft_forward(drft_lookup *l,float *data){
  119939. if(l->n==1)return;
  119940. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  119941. }
  119942. void drft_backward(drft_lookup *l,float *data){
  119943. if (l->n==1)return;
  119944. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  119945. }
  119946. void drft_init(drft_lookup *l,int n){
  119947. l->n=n;
  119948. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  119949. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  119950. fdrffti(n, l->trigcache, l->splitcache);
  119951. }
  119952. void drft_clear(drft_lookup *l){
  119953. if(l){
  119954. if(l->trigcache)_ogg_free(l->trigcache);
  119955. if(l->splitcache)_ogg_free(l->splitcache);
  119956. memset(l,0,sizeof(*l));
  119957. }
  119958. }
  119959. #endif
  119960. /*** End of inlined file: smallft.c ***/
  119961. /*** Start of inlined file: synthesis.c ***/
  119962. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119963. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119964. // tasks..
  119965. #if JUCE_MSVC
  119966. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119967. #endif
  119968. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119969. #if JUCE_USE_OGGVORBIS
  119970. #include <stdio.h>
  119971. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  119972. vorbis_dsp_state *vd=vb->vd;
  119973. private_state *b=(private_state*)vd->backend_state;
  119974. vorbis_info *vi=vd->vi;
  119975. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  119976. oggpack_buffer *opb=&vb->opb;
  119977. int type,mode,i;
  119978. /* first things first. Make sure decode is ready */
  119979. _vorbis_block_ripcord(vb);
  119980. oggpack_readinit(opb,op->packet,op->bytes);
  119981. /* Check the packet type */
  119982. if(oggpack_read(opb,1)!=0){
  119983. /* Oops. This is not an audio data packet */
  119984. return(OV_ENOTAUDIO);
  119985. }
  119986. /* read our mode and pre/post windowsize */
  119987. mode=oggpack_read(opb,b->modebits);
  119988. if(mode==-1)return(OV_EBADPACKET);
  119989. vb->mode=mode;
  119990. vb->W=ci->mode_param[mode]->blockflag;
  119991. if(vb->W){
  119992. /* this doesn;t get mapped through mode selection as it's used
  119993. only for window selection */
  119994. vb->lW=oggpack_read(opb,1);
  119995. vb->nW=oggpack_read(opb,1);
  119996. if(vb->nW==-1) return(OV_EBADPACKET);
  119997. }else{
  119998. vb->lW=0;
  119999. vb->nW=0;
  120000. }
  120001. /* more setup */
  120002. vb->granulepos=op->granulepos;
  120003. vb->sequence=op->packetno;
  120004. vb->eofflag=op->e_o_s;
  120005. /* alloc pcm passback storage */
  120006. vb->pcmend=ci->blocksizes[vb->W];
  120007. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120008. for(i=0;i<vi->channels;i++)
  120009. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120010. /* unpack_header enforces range checking */
  120011. type=ci->map_type[ci->mode_param[mode]->mapping];
  120012. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120013. mapping]));
  120014. }
  120015. /* used to track pcm position without actually performing decode.
  120016. Useful for sequential 'fast forward' */
  120017. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120018. vorbis_dsp_state *vd=vb->vd;
  120019. private_state *b=(private_state*)vd->backend_state;
  120020. vorbis_info *vi=vd->vi;
  120021. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120022. oggpack_buffer *opb=&vb->opb;
  120023. int mode;
  120024. /* first things first. Make sure decode is ready */
  120025. _vorbis_block_ripcord(vb);
  120026. oggpack_readinit(opb,op->packet,op->bytes);
  120027. /* Check the packet type */
  120028. if(oggpack_read(opb,1)!=0){
  120029. /* Oops. This is not an audio data packet */
  120030. return(OV_ENOTAUDIO);
  120031. }
  120032. /* read our mode and pre/post windowsize */
  120033. mode=oggpack_read(opb,b->modebits);
  120034. if(mode==-1)return(OV_EBADPACKET);
  120035. vb->mode=mode;
  120036. vb->W=ci->mode_param[mode]->blockflag;
  120037. if(vb->W){
  120038. vb->lW=oggpack_read(opb,1);
  120039. vb->nW=oggpack_read(opb,1);
  120040. if(vb->nW==-1) return(OV_EBADPACKET);
  120041. }else{
  120042. vb->lW=0;
  120043. vb->nW=0;
  120044. }
  120045. /* more setup */
  120046. vb->granulepos=op->granulepos;
  120047. vb->sequence=op->packetno;
  120048. vb->eofflag=op->e_o_s;
  120049. /* no pcm */
  120050. vb->pcmend=0;
  120051. vb->pcm=NULL;
  120052. return(0);
  120053. }
  120054. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120055. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120056. oggpack_buffer opb;
  120057. int mode;
  120058. oggpack_readinit(&opb,op->packet,op->bytes);
  120059. /* Check the packet type */
  120060. if(oggpack_read(&opb,1)!=0){
  120061. /* Oops. This is not an audio data packet */
  120062. return(OV_ENOTAUDIO);
  120063. }
  120064. {
  120065. int modebits=0;
  120066. int v=ci->modes;
  120067. while(v>1){
  120068. modebits++;
  120069. v>>=1;
  120070. }
  120071. /* read our mode and pre/post windowsize */
  120072. mode=oggpack_read(&opb,modebits);
  120073. }
  120074. if(mode==-1)return(OV_EBADPACKET);
  120075. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120076. }
  120077. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120078. /* set / clear half-sample-rate mode */
  120079. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120080. /* right now, our MDCT can't handle < 64 sample windows. */
  120081. if(ci->blocksizes[0]<=64 && flag)return -1;
  120082. ci->halfrate_flag=(flag?1:0);
  120083. return 0;
  120084. }
  120085. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120086. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120087. return ci->halfrate_flag;
  120088. }
  120089. #endif
  120090. /*** End of inlined file: synthesis.c ***/
  120091. /*** Start of inlined file: vorbisenc.c ***/
  120092. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120093. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120094. // tasks..
  120095. #if JUCE_MSVC
  120096. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120097. #endif
  120098. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120099. #if JUCE_USE_OGGVORBIS
  120100. #include <stdlib.h>
  120101. #include <string.h>
  120102. #include <math.h>
  120103. /* careful with this; it's using static array sizing to make managing
  120104. all the modes a little less annoying. If we use a residue backend
  120105. with > 12 partition types, or a different division of iteration,
  120106. this needs to be updated. */
  120107. typedef struct {
  120108. static_codebook *books[12][3];
  120109. } static_bookblock;
  120110. typedef struct {
  120111. int res_type;
  120112. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120113. vorbis_info_residue0 *res;
  120114. static_codebook *book_aux;
  120115. static_codebook *book_aux_managed;
  120116. static_bookblock *books_base;
  120117. static_bookblock *books_base_managed;
  120118. } vorbis_residue_template;
  120119. typedef struct {
  120120. vorbis_info_mapping0 *map;
  120121. vorbis_residue_template *res;
  120122. } vorbis_mapping_template;
  120123. typedef struct vp_adjblock{
  120124. int block[P_BANDS];
  120125. } vp_adjblock;
  120126. typedef struct {
  120127. int data[NOISE_COMPAND_LEVELS];
  120128. } compandblock;
  120129. /* high level configuration information for setting things up
  120130. step-by-step with the detailed vorbis_encode_ctl interface.
  120131. There's a fair amount of redundancy such that interactive setup
  120132. does not directly deal with any vorbis_info or codec_setup_info
  120133. initialization; it's all stored (until full init) in this highlevel
  120134. setup, then flushed out to the real codec setup structs later. */
  120135. typedef struct {
  120136. int att[P_NOISECURVES];
  120137. float boost;
  120138. float decay;
  120139. } att3;
  120140. typedef struct { int data[P_NOISECURVES]; } adj3;
  120141. typedef struct {
  120142. int pre[PACKETBLOBS];
  120143. int post[PACKETBLOBS];
  120144. float kHz[PACKETBLOBS];
  120145. float lowpasskHz[PACKETBLOBS];
  120146. } adj_stereo;
  120147. typedef struct {
  120148. int lo;
  120149. int hi;
  120150. int fixed;
  120151. } noiseguard;
  120152. typedef struct {
  120153. int data[P_NOISECURVES][17];
  120154. } noise3;
  120155. typedef struct {
  120156. int mappings;
  120157. double *rate_mapping;
  120158. double *quality_mapping;
  120159. int coupling_restriction;
  120160. long samplerate_min_restriction;
  120161. long samplerate_max_restriction;
  120162. int *blocksize_short;
  120163. int *blocksize_long;
  120164. att3 *psy_tone_masteratt;
  120165. int *psy_tone_0dB;
  120166. int *psy_tone_dBsuppress;
  120167. vp_adjblock *psy_tone_adj_impulse;
  120168. vp_adjblock *psy_tone_adj_long;
  120169. vp_adjblock *psy_tone_adj_other;
  120170. noiseguard *psy_noiseguards;
  120171. noise3 *psy_noise_bias_impulse;
  120172. noise3 *psy_noise_bias_padding;
  120173. noise3 *psy_noise_bias_trans;
  120174. noise3 *psy_noise_bias_long;
  120175. int *psy_noise_dBsuppress;
  120176. compandblock *psy_noise_compand;
  120177. double *psy_noise_compand_short_mapping;
  120178. double *psy_noise_compand_long_mapping;
  120179. int *psy_noise_normal_start[2];
  120180. int *psy_noise_normal_partition[2];
  120181. double *psy_noise_normal_thresh;
  120182. int *psy_ath_float;
  120183. int *psy_ath_abs;
  120184. double *psy_lowpass;
  120185. vorbis_info_psy_global *global_params;
  120186. double *global_mapping;
  120187. adj_stereo *stereo_modes;
  120188. static_codebook ***floor_books;
  120189. vorbis_info_floor1 *floor_params;
  120190. int *floor_short_mapping;
  120191. int *floor_long_mapping;
  120192. vorbis_mapping_template *maps;
  120193. } ve_setup_data_template;
  120194. /* a few static coder conventions */
  120195. static vorbis_info_mode _mode_template[2]={
  120196. {0,0,0,0},
  120197. {1,0,0,1}
  120198. };
  120199. static vorbis_info_mapping0 _map_nominal[2]={
  120200. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120201. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120202. };
  120203. /*** Start of inlined file: setup_44.h ***/
  120204. /*** Start of inlined file: floor_all.h ***/
  120205. /*** Start of inlined file: floor_books.h ***/
  120206. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120207. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120208. };
  120209. static static_codebook _huff_book_line_256x7_0sub1 = {
  120210. 1, 9,
  120211. _huff_lengthlist_line_256x7_0sub1,
  120212. 0, 0, 0, 0, 0,
  120213. NULL,
  120214. NULL,
  120215. NULL,
  120216. NULL,
  120217. 0
  120218. };
  120219. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120221. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120222. };
  120223. static static_codebook _huff_book_line_256x7_0sub2 = {
  120224. 1, 25,
  120225. _huff_lengthlist_line_256x7_0sub2,
  120226. 0, 0, 0, 0, 0,
  120227. NULL,
  120228. NULL,
  120229. NULL,
  120230. NULL,
  120231. 0
  120232. };
  120233. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120236. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120237. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120238. };
  120239. static static_codebook _huff_book_line_256x7_0sub3 = {
  120240. 1, 64,
  120241. _huff_lengthlist_line_256x7_0sub3,
  120242. 0, 0, 0, 0, 0,
  120243. NULL,
  120244. NULL,
  120245. NULL,
  120246. NULL,
  120247. 0
  120248. };
  120249. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120250. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120251. };
  120252. static static_codebook _huff_book_line_256x7_1sub1 = {
  120253. 1, 9,
  120254. _huff_lengthlist_line_256x7_1sub1,
  120255. 0, 0, 0, 0, 0,
  120256. NULL,
  120257. NULL,
  120258. NULL,
  120259. NULL,
  120260. 0
  120261. };
  120262. static long _huff_lengthlist_line_256x7_1sub2[] = {
  120263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  120264. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  120265. };
  120266. static static_codebook _huff_book_line_256x7_1sub2 = {
  120267. 1, 25,
  120268. _huff_lengthlist_line_256x7_1sub2,
  120269. 0, 0, 0, 0, 0,
  120270. NULL,
  120271. NULL,
  120272. NULL,
  120273. NULL,
  120274. 0
  120275. };
  120276. static long _huff_lengthlist_line_256x7_1sub3[] = {
  120277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  120279. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120280. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  120281. };
  120282. static static_codebook _huff_book_line_256x7_1sub3 = {
  120283. 1, 64,
  120284. _huff_lengthlist_line_256x7_1sub3,
  120285. 0, 0, 0, 0, 0,
  120286. NULL,
  120287. NULL,
  120288. NULL,
  120289. NULL,
  120290. 0
  120291. };
  120292. static long _huff_lengthlist_line_256x7_class0[] = {
  120293. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  120294. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  120295. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  120296. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  120297. };
  120298. static static_codebook _huff_book_line_256x7_class0 = {
  120299. 1, 64,
  120300. _huff_lengthlist_line_256x7_class0,
  120301. 0, 0, 0, 0, 0,
  120302. NULL,
  120303. NULL,
  120304. NULL,
  120305. NULL,
  120306. 0
  120307. };
  120308. static long _huff_lengthlist_line_256x7_class1[] = {
  120309. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120310. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120311. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120312. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120313. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120314. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120315. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120316. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120317. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120318. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120319. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120320. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120321. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120322. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120323. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120324. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120325. };
  120326. static static_codebook _huff_book_line_256x7_class1 = {
  120327. 1, 256,
  120328. _huff_lengthlist_line_256x7_class1,
  120329. 0, 0, 0, 0, 0,
  120330. NULL,
  120331. NULL,
  120332. NULL,
  120333. NULL,
  120334. 0
  120335. };
  120336. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120337. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120338. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120339. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120340. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120341. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120342. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120343. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120344. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120345. };
  120346. static static_codebook _huff_book_line_512x17_0sub0 = {
  120347. 1, 128,
  120348. _huff_lengthlist_line_512x17_0sub0,
  120349. 0, 0, 0, 0, 0,
  120350. NULL,
  120351. NULL,
  120352. NULL,
  120353. NULL,
  120354. 0
  120355. };
  120356. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120357. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120358. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120359. };
  120360. static static_codebook _huff_book_line_512x17_1sub0 = {
  120361. 1, 32,
  120362. _huff_lengthlist_line_512x17_1sub0,
  120363. 0, 0, 0, 0, 0,
  120364. NULL,
  120365. NULL,
  120366. NULL,
  120367. NULL,
  120368. 0
  120369. };
  120370. static long _huff_lengthlist_line_512x17_1sub1[] = {
  120371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120373. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  120374. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  120375. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  120376. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  120377. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  120378. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120379. };
  120380. static static_codebook _huff_book_line_512x17_1sub1 = {
  120381. 1, 128,
  120382. _huff_lengthlist_line_512x17_1sub1,
  120383. 0, 0, 0, 0, 0,
  120384. NULL,
  120385. NULL,
  120386. NULL,
  120387. NULL,
  120388. 0
  120389. };
  120390. static long _huff_lengthlist_line_512x17_2sub1[] = {
  120391. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  120392. 5, 3,
  120393. };
  120394. static static_codebook _huff_book_line_512x17_2sub1 = {
  120395. 1, 18,
  120396. _huff_lengthlist_line_512x17_2sub1,
  120397. 0, 0, 0, 0, 0,
  120398. NULL,
  120399. NULL,
  120400. NULL,
  120401. NULL,
  120402. 0
  120403. };
  120404. static long _huff_lengthlist_line_512x17_2sub2[] = {
  120405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120406. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  120407. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  120408. 9, 8,
  120409. };
  120410. static static_codebook _huff_book_line_512x17_2sub2 = {
  120411. 1, 50,
  120412. _huff_lengthlist_line_512x17_2sub2,
  120413. 0, 0, 0, 0, 0,
  120414. NULL,
  120415. NULL,
  120416. NULL,
  120417. NULL,
  120418. 0
  120419. };
  120420. static long _huff_lengthlist_line_512x17_2sub3[] = {
  120421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120424. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  120425. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  120426. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120427. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120428. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120429. };
  120430. static static_codebook _huff_book_line_512x17_2sub3 = {
  120431. 1, 128,
  120432. _huff_lengthlist_line_512x17_2sub3,
  120433. 0, 0, 0, 0, 0,
  120434. NULL,
  120435. NULL,
  120436. NULL,
  120437. NULL,
  120438. 0
  120439. };
  120440. static long _huff_lengthlist_line_512x17_3sub1[] = {
  120441. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  120442. 5, 5,
  120443. };
  120444. static static_codebook _huff_book_line_512x17_3sub1 = {
  120445. 1, 18,
  120446. _huff_lengthlist_line_512x17_3sub1,
  120447. 0, 0, 0, 0, 0,
  120448. NULL,
  120449. NULL,
  120450. NULL,
  120451. NULL,
  120452. 0
  120453. };
  120454. static long _huff_lengthlist_line_512x17_3sub2[] = {
  120455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120456. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  120457. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  120458. 11,14,
  120459. };
  120460. static static_codebook _huff_book_line_512x17_3sub2 = {
  120461. 1, 50,
  120462. _huff_lengthlist_line_512x17_3sub2,
  120463. 0, 0, 0, 0, 0,
  120464. NULL,
  120465. NULL,
  120466. NULL,
  120467. NULL,
  120468. 0
  120469. };
  120470. static long _huff_lengthlist_line_512x17_3sub3[] = {
  120471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120474. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  120475. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120476. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120477. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120478. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120479. };
  120480. static static_codebook _huff_book_line_512x17_3sub3 = {
  120481. 1, 128,
  120482. _huff_lengthlist_line_512x17_3sub3,
  120483. 0, 0, 0, 0, 0,
  120484. NULL,
  120485. NULL,
  120486. NULL,
  120487. NULL,
  120488. 0
  120489. };
  120490. static long _huff_lengthlist_line_512x17_class1[] = {
  120491. 1, 2, 3, 6, 5, 4, 7, 7,
  120492. };
  120493. static static_codebook _huff_book_line_512x17_class1 = {
  120494. 1, 8,
  120495. _huff_lengthlist_line_512x17_class1,
  120496. 0, 0, 0, 0, 0,
  120497. NULL,
  120498. NULL,
  120499. NULL,
  120500. NULL,
  120501. 0
  120502. };
  120503. static long _huff_lengthlist_line_512x17_class2[] = {
  120504. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  120505. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  120506. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  120507. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  120508. };
  120509. static static_codebook _huff_book_line_512x17_class2 = {
  120510. 1, 64,
  120511. _huff_lengthlist_line_512x17_class2,
  120512. 0, 0, 0, 0, 0,
  120513. NULL,
  120514. NULL,
  120515. NULL,
  120516. NULL,
  120517. 0
  120518. };
  120519. static long _huff_lengthlist_line_512x17_class3[] = {
  120520. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  120521. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  120522. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  120523. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  120524. };
  120525. static static_codebook _huff_book_line_512x17_class3 = {
  120526. 1, 64,
  120527. _huff_lengthlist_line_512x17_class3,
  120528. 0, 0, 0, 0, 0,
  120529. NULL,
  120530. NULL,
  120531. NULL,
  120532. NULL,
  120533. 0
  120534. };
  120535. static long _huff_lengthlist_line_128x4_class0[] = {
  120536. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  120537. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  120538. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  120539. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  120540. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  120541. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  120542. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  120543. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  120544. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  120545. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  120546. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  120547. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  120548. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  120549. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  120550. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  120551. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  120552. };
  120553. static static_codebook _huff_book_line_128x4_class0 = {
  120554. 1, 256,
  120555. _huff_lengthlist_line_128x4_class0,
  120556. 0, 0, 0, 0, 0,
  120557. NULL,
  120558. NULL,
  120559. NULL,
  120560. NULL,
  120561. 0
  120562. };
  120563. static long _huff_lengthlist_line_128x4_0sub0[] = {
  120564. 2, 2, 2, 2,
  120565. };
  120566. static static_codebook _huff_book_line_128x4_0sub0 = {
  120567. 1, 4,
  120568. _huff_lengthlist_line_128x4_0sub0,
  120569. 0, 0, 0, 0, 0,
  120570. NULL,
  120571. NULL,
  120572. NULL,
  120573. NULL,
  120574. 0
  120575. };
  120576. static long _huff_lengthlist_line_128x4_0sub1[] = {
  120577. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  120578. };
  120579. static static_codebook _huff_book_line_128x4_0sub1 = {
  120580. 1, 10,
  120581. _huff_lengthlist_line_128x4_0sub1,
  120582. 0, 0, 0, 0, 0,
  120583. NULL,
  120584. NULL,
  120585. NULL,
  120586. NULL,
  120587. 0
  120588. };
  120589. static long _huff_lengthlist_line_128x4_0sub2[] = {
  120590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  120591. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  120592. };
  120593. static static_codebook _huff_book_line_128x4_0sub2 = {
  120594. 1, 25,
  120595. _huff_lengthlist_line_128x4_0sub2,
  120596. 0, 0, 0, 0, 0,
  120597. NULL,
  120598. NULL,
  120599. NULL,
  120600. NULL,
  120601. 0
  120602. };
  120603. static long _huff_lengthlist_line_128x4_0sub3[] = {
  120604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120606. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  120607. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  120608. };
  120609. static static_codebook _huff_book_line_128x4_0sub3 = {
  120610. 1, 64,
  120611. _huff_lengthlist_line_128x4_0sub3,
  120612. 0, 0, 0, 0, 0,
  120613. NULL,
  120614. NULL,
  120615. NULL,
  120616. NULL,
  120617. 0
  120618. };
  120619. static long _huff_lengthlist_line_256x4_class0[] = {
  120620. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  120621. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  120622. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  120623. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  120624. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  120625. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  120626. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  120627. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  120628. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  120629. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  120630. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  120631. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  120632. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  120633. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  120634. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  120635. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  120636. };
  120637. static static_codebook _huff_book_line_256x4_class0 = {
  120638. 1, 256,
  120639. _huff_lengthlist_line_256x4_class0,
  120640. 0, 0, 0, 0, 0,
  120641. NULL,
  120642. NULL,
  120643. NULL,
  120644. NULL,
  120645. 0
  120646. };
  120647. static long _huff_lengthlist_line_256x4_0sub0[] = {
  120648. 2, 2, 2, 2,
  120649. };
  120650. static static_codebook _huff_book_line_256x4_0sub0 = {
  120651. 1, 4,
  120652. _huff_lengthlist_line_256x4_0sub0,
  120653. 0, 0, 0, 0, 0,
  120654. NULL,
  120655. NULL,
  120656. NULL,
  120657. NULL,
  120658. 0
  120659. };
  120660. static long _huff_lengthlist_line_256x4_0sub1[] = {
  120661. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  120662. };
  120663. static static_codebook _huff_book_line_256x4_0sub1 = {
  120664. 1, 10,
  120665. _huff_lengthlist_line_256x4_0sub1,
  120666. 0, 0, 0, 0, 0,
  120667. NULL,
  120668. NULL,
  120669. NULL,
  120670. NULL,
  120671. 0
  120672. };
  120673. static long _huff_lengthlist_line_256x4_0sub2[] = {
  120674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  120675. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  120676. };
  120677. static static_codebook _huff_book_line_256x4_0sub2 = {
  120678. 1, 25,
  120679. _huff_lengthlist_line_256x4_0sub2,
  120680. 0, 0, 0, 0, 0,
  120681. NULL,
  120682. NULL,
  120683. NULL,
  120684. NULL,
  120685. 0
  120686. };
  120687. static long _huff_lengthlist_line_256x4_0sub3[] = {
  120688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120690. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  120691. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  120692. };
  120693. static static_codebook _huff_book_line_256x4_0sub3 = {
  120694. 1, 64,
  120695. _huff_lengthlist_line_256x4_0sub3,
  120696. 0, 0, 0, 0, 0,
  120697. NULL,
  120698. NULL,
  120699. NULL,
  120700. NULL,
  120701. 0
  120702. };
  120703. static long _huff_lengthlist_line_128x7_class0[] = {
  120704. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  120705. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  120706. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  120707. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  120708. };
  120709. static static_codebook _huff_book_line_128x7_class0 = {
  120710. 1, 64,
  120711. _huff_lengthlist_line_128x7_class0,
  120712. 0, 0, 0, 0, 0,
  120713. NULL,
  120714. NULL,
  120715. NULL,
  120716. NULL,
  120717. 0
  120718. };
  120719. static long _huff_lengthlist_line_128x7_class1[] = {
  120720. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  120721. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  120722. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  120723. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  120724. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  120725. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  120726. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  120727. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  120728. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  120729. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  120730. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  120731. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  120732. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  120733. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  120734. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  120735. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  120736. };
  120737. static static_codebook _huff_book_line_128x7_class1 = {
  120738. 1, 256,
  120739. _huff_lengthlist_line_128x7_class1,
  120740. 0, 0, 0, 0, 0,
  120741. NULL,
  120742. NULL,
  120743. NULL,
  120744. NULL,
  120745. 0
  120746. };
  120747. static long _huff_lengthlist_line_128x7_0sub1[] = {
  120748. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  120749. };
  120750. static static_codebook _huff_book_line_128x7_0sub1 = {
  120751. 1, 9,
  120752. _huff_lengthlist_line_128x7_0sub1,
  120753. 0, 0, 0, 0, 0,
  120754. NULL,
  120755. NULL,
  120756. NULL,
  120757. NULL,
  120758. 0
  120759. };
  120760. static long _huff_lengthlist_line_128x7_0sub2[] = {
  120761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  120762. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  120763. };
  120764. static static_codebook _huff_book_line_128x7_0sub2 = {
  120765. 1, 25,
  120766. _huff_lengthlist_line_128x7_0sub2,
  120767. 0, 0, 0, 0, 0,
  120768. NULL,
  120769. NULL,
  120770. NULL,
  120771. NULL,
  120772. 0
  120773. };
  120774. static long _huff_lengthlist_line_128x7_0sub3[] = {
  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, 3, 5, 3, 5, 3, 5, 4,
  120777. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120778. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  120779. };
  120780. static static_codebook _huff_book_line_128x7_0sub3 = {
  120781. 1, 64,
  120782. _huff_lengthlist_line_128x7_0sub3,
  120783. 0, 0, 0, 0, 0,
  120784. NULL,
  120785. NULL,
  120786. NULL,
  120787. NULL,
  120788. 0
  120789. };
  120790. static long _huff_lengthlist_line_128x7_1sub1[] = {
  120791. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  120792. };
  120793. static static_codebook _huff_book_line_128x7_1sub1 = {
  120794. 1, 9,
  120795. _huff_lengthlist_line_128x7_1sub1,
  120796. 0, 0, 0, 0, 0,
  120797. NULL,
  120798. NULL,
  120799. NULL,
  120800. NULL,
  120801. 0
  120802. };
  120803. static long _huff_lengthlist_line_128x7_1sub2[] = {
  120804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  120805. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  120806. };
  120807. static static_codebook _huff_book_line_128x7_1sub2 = {
  120808. 1, 25,
  120809. _huff_lengthlist_line_128x7_1sub2,
  120810. 0, 0, 0, 0, 0,
  120811. NULL,
  120812. NULL,
  120813. NULL,
  120814. NULL,
  120815. 0
  120816. };
  120817. static long _huff_lengthlist_line_128x7_1sub3[] = {
  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, 1, 7, 2, 7, 3, 8, 4,
  120820. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  120821. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  120822. };
  120823. static static_codebook _huff_book_line_128x7_1sub3 = {
  120824. 1, 64,
  120825. _huff_lengthlist_line_128x7_1sub3,
  120826. 0, 0, 0, 0, 0,
  120827. NULL,
  120828. NULL,
  120829. NULL,
  120830. NULL,
  120831. 0
  120832. };
  120833. static long _huff_lengthlist_line_128x11_class1[] = {
  120834. 1, 6, 3, 7, 2, 4, 5, 7,
  120835. };
  120836. static static_codebook _huff_book_line_128x11_class1 = {
  120837. 1, 8,
  120838. _huff_lengthlist_line_128x11_class1,
  120839. 0, 0, 0, 0, 0,
  120840. NULL,
  120841. NULL,
  120842. NULL,
  120843. NULL,
  120844. 0
  120845. };
  120846. static long _huff_lengthlist_line_128x11_class2[] = {
  120847. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  120848. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  120849. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  120850. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  120851. };
  120852. static static_codebook _huff_book_line_128x11_class2 = {
  120853. 1, 64,
  120854. _huff_lengthlist_line_128x11_class2,
  120855. 0, 0, 0, 0, 0,
  120856. NULL,
  120857. NULL,
  120858. NULL,
  120859. NULL,
  120860. 0
  120861. };
  120862. static long _huff_lengthlist_line_128x11_class3[] = {
  120863. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  120864. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  120865. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  120866. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  120867. };
  120868. static static_codebook _huff_book_line_128x11_class3 = {
  120869. 1, 64,
  120870. _huff_lengthlist_line_128x11_class3,
  120871. 0, 0, 0, 0, 0,
  120872. NULL,
  120873. NULL,
  120874. NULL,
  120875. NULL,
  120876. 0
  120877. };
  120878. static long _huff_lengthlist_line_128x11_0sub0[] = {
  120879. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120880. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  120881. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  120882. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  120883. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  120884. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  120885. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  120886. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  120887. };
  120888. static static_codebook _huff_book_line_128x11_0sub0 = {
  120889. 1, 128,
  120890. _huff_lengthlist_line_128x11_0sub0,
  120891. 0, 0, 0, 0, 0,
  120892. NULL,
  120893. NULL,
  120894. NULL,
  120895. NULL,
  120896. 0
  120897. };
  120898. static long _huff_lengthlist_line_128x11_1sub0[] = {
  120899. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  120900. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  120901. };
  120902. static static_codebook _huff_book_line_128x11_1sub0 = {
  120903. 1, 32,
  120904. _huff_lengthlist_line_128x11_1sub0,
  120905. 0, 0, 0, 0, 0,
  120906. NULL,
  120907. NULL,
  120908. NULL,
  120909. NULL,
  120910. 0
  120911. };
  120912. static long _huff_lengthlist_line_128x11_1sub1[] = {
  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. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  120916. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  120917. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  120918. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  120919. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  120920. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  120921. };
  120922. static static_codebook _huff_book_line_128x11_1sub1 = {
  120923. 1, 128,
  120924. _huff_lengthlist_line_128x11_1sub1,
  120925. 0, 0, 0, 0, 0,
  120926. NULL,
  120927. NULL,
  120928. NULL,
  120929. NULL,
  120930. 0
  120931. };
  120932. static long _huff_lengthlist_line_128x11_2sub1[] = {
  120933. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  120934. 5, 5,
  120935. };
  120936. static static_codebook _huff_book_line_128x11_2sub1 = {
  120937. 1, 18,
  120938. _huff_lengthlist_line_128x11_2sub1,
  120939. 0, 0, 0, 0, 0,
  120940. NULL,
  120941. NULL,
  120942. NULL,
  120943. NULL,
  120944. 0
  120945. };
  120946. static long _huff_lengthlist_line_128x11_2sub2[] = {
  120947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120948. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  120949. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  120950. 8,11,
  120951. };
  120952. static static_codebook _huff_book_line_128x11_2sub2 = {
  120953. 1, 50,
  120954. _huff_lengthlist_line_128x11_2sub2,
  120955. 0, 0, 0, 0, 0,
  120956. NULL,
  120957. NULL,
  120958. NULL,
  120959. NULL,
  120960. 0
  120961. };
  120962. static long _huff_lengthlist_line_128x11_2sub3[] = {
  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, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  120967. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120968. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120969. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120970. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120971. };
  120972. static static_codebook _huff_book_line_128x11_2sub3 = {
  120973. 1, 128,
  120974. _huff_lengthlist_line_128x11_2sub3,
  120975. 0, 0, 0, 0, 0,
  120976. NULL,
  120977. NULL,
  120978. NULL,
  120979. NULL,
  120980. 0
  120981. };
  120982. static long _huff_lengthlist_line_128x11_3sub1[] = {
  120983. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  120984. 5, 4,
  120985. };
  120986. static static_codebook _huff_book_line_128x11_3sub1 = {
  120987. 1, 18,
  120988. _huff_lengthlist_line_128x11_3sub1,
  120989. 0, 0, 0, 0, 0,
  120990. NULL,
  120991. NULL,
  120992. NULL,
  120993. NULL,
  120994. 0
  120995. };
  120996. static long _huff_lengthlist_line_128x11_3sub2[] = {
  120997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120998. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  120999. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121000. 12, 6,
  121001. };
  121002. static static_codebook _huff_book_line_128x11_3sub2 = {
  121003. 1, 50,
  121004. _huff_lengthlist_line_128x11_3sub2,
  121005. 0, 0, 0, 0, 0,
  121006. NULL,
  121007. NULL,
  121008. NULL,
  121009. NULL,
  121010. 0
  121011. };
  121012. static long _huff_lengthlist_line_128x11_3sub3[] = {
  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, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121017. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121018. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121019. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121020. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121021. };
  121022. static static_codebook _huff_book_line_128x11_3sub3 = {
  121023. 1, 128,
  121024. _huff_lengthlist_line_128x11_3sub3,
  121025. 0, 0, 0, 0, 0,
  121026. NULL,
  121027. NULL,
  121028. NULL,
  121029. NULL,
  121030. 0
  121031. };
  121032. static long _huff_lengthlist_line_128x17_class1[] = {
  121033. 1, 3, 4, 7, 2, 5, 6, 7,
  121034. };
  121035. static static_codebook _huff_book_line_128x17_class1 = {
  121036. 1, 8,
  121037. _huff_lengthlist_line_128x17_class1,
  121038. 0, 0, 0, 0, 0,
  121039. NULL,
  121040. NULL,
  121041. NULL,
  121042. NULL,
  121043. 0
  121044. };
  121045. static long _huff_lengthlist_line_128x17_class2[] = {
  121046. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121047. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121048. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121049. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121050. };
  121051. static static_codebook _huff_book_line_128x17_class2 = {
  121052. 1, 64,
  121053. _huff_lengthlist_line_128x17_class2,
  121054. 0, 0, 0, 0, 0,
  121055. NULL,
  121056. NULL,
  121057. NULL,
  121058. NULL,
  121059. 0
  121060. };
  121061. static long _huff_lengthlist_line_128x17_class3[] = {
  121062. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121063. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121064. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121065. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121066. };
  121067. static static_codebook _huff_book_line_128x17_class3 = {
  121068. 1, 64,
  121069. _huff_lengthlist_line_128x17_class3,
  121070. 0, 0, 0, 0, 0,
  121071. NULL,
  121072. NULL,
  121073. NULL,
  121074. NULL,
  121075. 0
  121076. };
  121077. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121078. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121079. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121080. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121081. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121082. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121083. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121084. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121085. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121086. };
  121087. static static_codebook _huff_book_line_128x17_0sub0 = {
  121088. 1, 128,
  121089. _huff_lengthlist_line_128x17_0sub0,
  121090. 0, 0, 0, 0, 0,
  121091. NULL,
  121092. NULL,
  121093. NULL,
  121094. NULL,
  121095. 0
  121096. };
  121097. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121098. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121099. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121100. };
  121101. static static_codebook _huff_book_line_128x17_1sub0 = {
  121102. 1, 32,
  121103. _huff_lengthlist_line_128x17_1sub0,
  121104. 0, 0, 0, 0, 0,
  121105. NULL,
  121106. NULL,
  121107. NULL,
  121108. NULL,
  121109. 0
  121110. };
  121111. static long _huff_lengthlist_line_128x17_1sub1[] = {
  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. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121115. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121116. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121117. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121118. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121119. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121120. };
  121121. static static_codebook _huff_book_line_128x17_1sub1 = {
  121122. 1, 128,
  121123. _huff_lengthlist_line_128x17_1sub1,
  121124. 0, 0, 0, 0, 0,
  121125. NULL,
  121126. NULL,
  121127. NULL,
  121128. NULL,
  121129. 0
  121130. };
  121131. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121132. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121133. 9, 4,
  121134. };
  121135. static static_codebook _huff_book_line_128x17_2sub1 = {
  121136. 1, 18,
  121137. _huff_lengthlist_line_128x17_2sub1,
  121138. 0, 0, 0, 0, 0,
  121139. NULL,
  121140. NULL,
  121141. NULL,
  121142. NULL,
  121143. 0
  121144. };
  121145. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121147. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121148. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121149. 13,13,
  121150. };
  121151. static static_codebook _huff_book_line_128x17_2sub2 = {
  121152. 1, 50,
  121153. _huff_lengthlist_line_128x17_2sub2,
  121154. 0, 0, 0, 0, 0,
  121155. NULL,
  121156. NULL,
  121157. NULL,
  121158. NULL,
  121159. 0
  121160. };
  121161. static long _huff_lengthlist_line_128x17_2sub3[] = {
  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, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121166. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121167. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121168. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121169. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121170. };
  121171. static static_codebook _huff_book_line_128x17_2sub3 = {
  121172. 1, 128,
  121173. _huff_lengthlist_line_128x17_2sub3,
  121174. 0, 0, 0, 0, 0,
  121175. NULL,
  121176. NULL,
  121177. NULL,
  121178. NULL,
  121179. 0
  121180. };
  121181. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121182. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121183. 6, 4,
  121184. };
  121185. static static_codebook _huff_book_line_128x17_3sub1 = {
  121186. 1, 18,
  121187. _huff_lengthlist_line_128x17_3sub1,
  121188. 0, 0, 0, 0, 0,
  121189. NULL,
  121190. NULL,
  121191. NULL,
  121192. NULL,
  121193. 0
  121194. };
  121195. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121197. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121198. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121199. 10, 8,
  121200. };
  121201. static static_codebook _huff_book_line_128x17_3sub2 = {
  121202. 1, 50,
  121203. _huff_lengthlist_line_128x17_3sub2,
  121204. 0, 0, 0, 0, 0,
  121205. NULL,
  121206. NULL,
  121207. NULL,
  121208. NULL,
  121209. 0
  121210. };
  121211. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121215. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121216. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121217. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121218. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121219. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121220. };
  121221. static static_codebook _huff_book_line_128x17_3sub3 = {
  121222. 1, 128,
  121223. _huff_lengthlist_line_128x17_3sub3,
  121224. 0, 0, 0, 0, 0,
  121225. NULL,
  121226. NULL,
  121227. NULL,
  121228. NULL,
  121229. 0
  121230. };
  121231. static long _huff_lengthlist_line_1024x27_class1[] = {
  121232. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121233. };
  121234. static static_codebook _huff_book_line_1024x27_class1 = {
  121235. 1, 16,
  121236. _huff_lengthlist_line_1024x27_class1,
  121237. 0, 0, 0, 0, 0,
  121238. NULL,
  121239. NULL,
  121240. NULL,
  121241. NULL,
  121242. 0
  121243. };
  121244. static long _huff_lengthlist_line_1024x27_class2[] = {
  121245. 1, 4, 2, 6, 3, 7, 5, 7,
  121246. };
  121247. static static_codebook _huff_book_line_1024x27_class2 = {
  121248. 1, 8,
  121249. _huff_lengthlist_line_1024x27_class2,
  121250. 0, 0, 0, 0, 0,
  121251. NULL,
  121252. NULL,
  121253. NULL,
  121254. NULL,
  121255. 0
  121256. };
  121257. static long _huff_lengthlist_line_1024x27_class3[] = {
  121258. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121259. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121260. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121261. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121262. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  121263. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  121264. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  121265. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  121266. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  121267. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  121268. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  121269. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121270. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  121271. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  121272. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  121273. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121274. };
  121275. static static_codebook _huff_book_line_1024x27_class3 = {
  121276. 1, 256,
  121277. _huff_lengthlist_line_1024x27_class3,
  121278. 0, 0, 0, 0, 0,
  121279. NULL,
  121280. NULL,
  121281. NULL,
  121282. NULL,
  121283. 0
  121284. };
  121285. static long _huff_lengthlist_line_1024x27_class4[] = {
  121286. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  121287. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  121288. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  121289. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  121290. };
  121291. static static_codebook _huff_book_line_1024x27_class4 = {
  121292. 1, 64,
  121293. _huff_lengthlist_line_1024x27_class4,
  121294. 0, 0, 0, 0, 0,
  121295. NULL,
  121296. NULL,
  121297. NULL,
  121298. NULL,
  121299. 0
  121300. };
  121301. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  121302. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121303. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  121304. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121305. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121306. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121307. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121308. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121309. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121310. };
  121311. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121312. 1, 128,
  121313. _huff_lengthlist_line_1024x27_0sub0,
  121314. 0, 0, 0, 0, 0,
  121315. NULL,
  121316. NULL,
  121317. NULL,
  121318. NULL,
  121319. 0
  121320. };
  121321. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121322. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121323. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121324. };
  121325. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121326. 1, 32,
  121327. _huff_lengthlist_line_1024x27_1sub0,
  121328. 0, 0, 0, 0, 0,
  121329. NULL,
  121330. NULL,
  121331. NULL,
  121332. NULL,
  121333. 0
  121334. };
  121335. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121338. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121339. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121340. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121341. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121342. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121343. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121344. };
  121345. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121346. 1, 128,
  121347. _huff_lengthlist_line_1024x27_1sub1,
  121348. 0, 0, 0, 0, 0,
  121349. NULL,
  121350. NULL,
  121351. NULL,
  121352. NULL,
  121353. 0
  121354. };
  121355. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121356. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121357. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121358. };
  121359. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121360. 1, 32,
  121361. _huff_lengthlist_line_1024x27_2sub0,
  121362. 0, 0, 0, 0, 0,
  121363. NULL,
  121364. NULL,
  121365. NULL,
  121366. NULL,
  121367. 0
  121368. };
  121369. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  121370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121372. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  121373. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  121374. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  121375. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  121376. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  121377. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  121378. };
  121379. static static_codebook _huff_book_line_1024x27_2sub1 = {
  121380. 1, 128,
  121381. _huff_lengthlist_line_1024x27_2sub1,
  121382. 0, 0, 0, 0, 0,
  121383. NULL,
  121384. NULL,
  121385. NULL,
  121386. NULL,
  121387. 0
  121388. };
  121389. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  121390. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  121391. 5, 5,
  121392. };
  121393. static static_codebook _huff_book_line_1024x27_3sub1 = {
  121394. 1, 18,
  121395. _huff_lengthlist_line_1024x27_3sub1,
  121396. 0, 0, 0, 0, 0,
  121397. NULL,
  121398. NULL,
  121399. NULL,
  121400. NULL,
  121401. 0
  121402. };
  121403. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  121404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121405. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  121406. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  121407. 9,11,
  121408. };
  121409. static static_codebook _huff_book_line_1024x27_3sub2 = {
  121410. 1, 50,
  121411. _huff_lengthlist_line_1024x27_3sub2,
  121412. 0, 0, 0, 0, 0,
  121413. NULL,
  121414. NULL,
  121415. NULL,
  121416. NULL,
  121417. 0
  121418. };
  121419. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  121420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121423. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  121424. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  121425. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121426. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121427. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121428. };
  121429. static static_codebook _huff_book_line_1024x27_3sub3 = {
  121430. 1, 128,
  121431. _huff_lengthlist_line_1024x27_3sub3,
  121432. 0, 0, 0, 0, 0,
  121433. NULL,
  121434. NULL,
  121435. NULL,
  121436. NULL,
  121437. 0
  121438. };
  121439. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  121440. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  121441. 5, 4,
  121442. };
  121443. static static_codebook _huff_book_line_1024x27_4sub1 = {
  121444. 1, 18,
  121445. _huff_lengthlist_line_1024x27_4sub1,
  121446. 0, 0, 0, 0, 0,
  121447. NULL,
  121448. NULL,
  121449. NULL,
  121450. NULL,
  121451. 0
  121452. };
  121453. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  121454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121455. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  121456. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  121457. 9,12,
  121458. };
  121459. static static_codebook _huff_book_line_1024x27_4sub2 = {
  121460. 1, 50,
  121461. _huff_lengthlist_line_1024x27_4sub2,
  121462. 0, 0, 0, 0, 0,
  121463. NULL,
  121464. NULL,
  121465. NULL,
  121466. NULL,
  121467. 0
  121468. };
  121469. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  121470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121473. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  121474. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  121475. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121476. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121477. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  121478. };
  121479. static static_codebook _huff_book_line_1024x27_4sub3 = {
  121480. 1, 128,
  121481. _huff_lengthlist_line_1024x27_4sub3,
  121482. 0, 0, 0, 0, 0,
  121483. NULL,
  121484. NULL,
  121485. NULL,
  121486. NULL,
  121487. 0
  121488. };
  121489. static long _huff_lengthlist_line_2048x27_class1[] = {
  121490. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  121491. };
  121492. static static_codebook _huff_book_line_2048x27_class1 = {
  121493. 1, 16,
  121494. _huff_lengthlist_line_2048x27_class1,
  121495. 0, 0, 0, 0, 0,
  121496. NULL,
  121497. NULL,
  121498. NULL,
  121499. NULL,
  121500. 0
  121501. };
  121502. static long _huff_lengthlist_line_2048x27_class2[] = {
  121503. 1, 2, 3, 6, 4, 7, 5, 7,
  121504. };
  121505. static static_codebook _huff_book_line_2048x27_class2 = {
  121506. 1, 8,
  121507. _huff_lengthlist_line_2048x27_class2,
  121508. 0, 0, 0, 0, 0,
  121509. NULL,
  121510. NULL,
  121511. NULL,
  121512. NULL,
  121513. 0
  121514. };
  121515. static long _huff_lengthlist_line_2048x27_class3[] = {
  121516. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  121517. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  121518. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  121519. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  121520. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  121521. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  121522. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  121523. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  121524. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  121525. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  121526. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  121527. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121528. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  121529. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  121530. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121531. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121532. };
  121533. static static_codebook _huff_book_line_2048x27_class3 = {
  121534. 1, 256,
  121535. _huff_lengthlist_line_2048x27_class3,
  121536. 0, 0, 0, 0, 0,
  121537. NULL,
  121538. NULL,
  121539. NULL,
  121540. NULL,
  121541. 0
  121542. };
  121543. static long _huff_lengthlist_line_2048x27_class4[] = {
  121544. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  121545. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  121546. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  121547. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  121548. };
  121549. static static_codebook _huff_book_line_2048x27_class4 = {
  121550. 1, 64,
  121551. _huff_lengthlist_line_2048x27_class4,
  121552. 0, 0, 0, 0, 0,
  121553. NULL,
  121554. NULL,
  121555. NULL,
  121556. NULL,
  121557. 0
  121558. };
  121559. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  121560. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121561. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  121562. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  121563. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  121564. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  121565. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  121566. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  121567. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  121568. };
  121569. static static_codebook _huff_book_line_2048x27_0sub0 = {
  121570. 1, 128,
  121571. _huff_lengthlist_line_2048x27_0sub0,
  121572. 0, 0, 0, 0, 0,
  121573. NULL,
  121574. NULL,
  121575. NULL,
  121576. NULL,
  121577. 0
  121578. };
  121579. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  121580. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121581. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  121582. };
  121583. static static_codebook _huff_book_line_2048x27_1sub0 = {
  121584. 1, 32,
  121585. _huff_lengthlist_line_2048x27_1sub0,
  121586. 0, 0, 0, 0, 0,
  121587. NULL,
  121588. NULL,
  121589. NULL,
  121590. NULL,
  121591. 0
  121592. };
  121593. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  121594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121596. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  121597. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  121598. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  121599. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  121600. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  121601. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  121602. };
  121603. static static_codebook _huff_book_line_2048x27_1sub1 = {
  121604. 1, 128,
  121605. _huff_lengthlist_line_2048x27_1sub1,
  121606. 0, 0, 0, 0, 0,
  121607. NULL,
  121608. NULL,
  121609. NULL,
  121610. NULL,
  121611. 0
  121612. };
  121613. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  121614. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121615. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  121616. };
  121617. static static_codebook _huff_book_line_2048x27_2sub0 = {
  121618. 1, 32,
  121619. _huff_lengthlist_line_2048x27_2sub0,
  121620. 0, 0, 0, 0, 0,
  121621. NULL,
  121622. NULL,
  121623. NULL,
  121624. NULL,
  121625. 0
  121626. };
  121627. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  121628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121630. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  121631. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  121632. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  121633. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  121634. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  121635. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121636. };
  121637. static static_codebook _huff_book_line_2048x27_2sub1 = {
  121638. 1, 128,
  121639. _huff_lengthlist_line_2048x27_2sub1,
  121640. 0, 0, 0, 0, 0,
  121641. NULL,
  121642. NULL,
  121643. NULL,
  121644. NULL,
  121645. 0
  121646. };
  121647. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  121648. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  121649. 5, 5,
  121650. };
  121651. static static_codebook _huff_book_line_2048x27_3sub1 = {
  121652. 1, 18,
  121653. _huff_lengthlist_line_2048x27_3sub1,
  121654. 0, 0, 0, 0, 0,
  121655. NULL,
  121656. NULL,
  121657. NULL,
  121658. NULL,
  121659. 0
  121660. };
  121661. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  121662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121663. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  121664. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  121665. 10,12,
  121666. };
  121667. static static_codebook _huff_book_line_2048x27_3sub2 = {
  121668. 1, 50,
  121669. _huff_lengthlist_line_2048x27_3sub2,
  121670. 0, 0, 0, 0, 0,
  121671. NULL,
  121672. NULL,
  121673. NULL,
  121674. NULL,
  121675. 0
  121676. };
  121677. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  121678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121681. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  121682. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121683. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121684. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121685. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121686. };
  121687. static static_codebook _huff_book_line_2048x27_3sub3 = {
  121688. 1, 128,
  121689. _huff_lengthlist_line_2048x27_3sub3,
  121690. 0, 0, 0, 0, 0,
  121691. NULL,
  121692. NULL,
  121693. NULL,
  121694. NULL,
  121695. 0
  121696. };
  121697. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  121698. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  121699. 4, 5,
  121700. };
  121701. static static_codebook _huff_book_line_2048x27_4sub1 = {
  121702. 1, 18,
  121703. _huff_lengthlist_line_2048x27_4sub1,
  121704. 0, 0, 0, 0, 0,
  121705. NULL,
  121706. NULL,
  121707. NULL,
  121708. NULL,
  121709. 0
  121710. };
  121711. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  121712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121713. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  121714. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  121715. 10,10,
  121716. };
  121717. static static_codebook _huff_book_line_2048x27_4sub2 = {
  121718. 1, 50,
  121719. _huff_lengthlist_line_2048x27_4sub2,
  121720. 0, 0, 0, 0, 0,
  121721. NULL,
  121722. NULL,
  121723. NULL,
  121724. NULL,
  121725. 0
  121726. };
  121727. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  121728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121731. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  121732. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  121733. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121734. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121735. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121736. };
  121737. static static_codebook _huff_book_line_2048x27_4sub3 = {
  121738. 1, 128,
  121739. _huff_lengthlist_line_2048x27_4sub3,
  121740. 0, 0, 0, 0, 0,
  121741. NULL,
  121742. NULL,
  121743. NULL,
  121744. NULL,
  121745. 0
  121746. };
  121747. static long _huff_lengthlist_line_256x4low_class0[] = {
  121748. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  121749. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  121750. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  121751. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  121752. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  121753. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  121754. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  121755. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  121756. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  121757. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  121758. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  121759. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  121760. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  121761. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  121762. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  121763. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  121764. };
  121765. static static_codebook _huff_book_line_256x4low_class0 = {
  121766. 1, 256,
  121767. _huff_lengthlist_line_256x4low_class0,
  121768. 0, 0, 0, 0, 0,
  121769. NULL,
  121770. NULL,
  121771. NULL,
  121772. NULL,
  121773. 0
  121774. };
  121775. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  121776. 1, 3, 2, 3,
  121777. };
  121778. static static_codebook _huff_book_line_256x4low_0sub0 = {
  121779. 1, 4,
  121780. _huff_lengthlist_line_256x4low_0sub0,
  121781. 0, 0, 0, 0, 0,
  121782. NULL,
  121783. NULL,
  121784. NULL,
  121785. NULL,
  121786. 0
  121787. };
  121788. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  121789. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  121790. };
  121791. static static_codebook _huff_book_line_256x4low_0sub1 = {
  121792. 1, 10,
  121793. _huff_lengthlist_line_256x4low_0sub1,
  121794. 0, 0, 0, 0, 0,
  121795. NULL,
  121796. NULL,
  121797. NULL,
  121798. NULL,
  121799. 0
  121800. };
  121801. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  121802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  121803. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  121804. };
  121805. static static_codebook _huff_book_line_256x4low_0sub2 = {
  121806. 1, 25,
  121807. _huff_lengthlist_line_256x4low_0sub2,
  121808. 0, 0, 0, 0, 0,
  121809. NULL,
  121810. NULL,
  121811. NULL,
  121812. NULL,
  121813. 0
  121814. };
  121815. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  121816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  121818. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  121819. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  121820. };
  121821. static static_codebook _huff_book_line_256x4low_0sub3 = {
  121822. 1, 64,
  121823. _huff_lengthlist_line_256x4low_0sub3,
  121824. 0, 0, 0, 0, 0,
  121825. NULL,
  121826. NULL,
  121827. NULL,
  121828. NULL,
  121829. 0
  121830. };
  121831. /*** End of inlined file: floor_books.h ***/
  121832. static static_codebook *_floor_128x4_books[]={
  121833. &_huff_book_line_128x4_class0,
  121834. &_huff_book_line_128x4_0sub0,
  121835. &_huff_book_line_128x4_0sub1,
  121836. &_huff_book_line_128x4_0sub2,
  121837. &_huff_book_line_128x4_0sub3,
  121838. };
  121839. static static_codebook *_floor_256x4_books[]={
  121840. &_huff_book_line_256x4_class0,
  121841. &_huff_book_line_256x4_0sub0,
  121842. &_huff_book_line_256x4_0sub1,
  121843. &_huff_book_line_256x4_0sub2,
  121844. &_huff_book_line_256x4_0sub3,
  121845. };
  121846. static static_codebook *_floor_128x7_books[]={
  121847. &_huff_book_line_128x7_class0,
  121848. &_huff_book_line_128x7_class1,
  121849. &_huff_book_line_128x7_0sub1,
  121850. &_huff_book_line_128x7_0sub2,
  121851. &_huff_book_line_128x7_0sub3,
  121852. &_huff_book_line_128x7_1sub1,
  121853. &_huff_book_line_128x7_1sub2,
  121854. &_huff_book_line_128x7_1sub3,
  121855. };
  121856. static static_codebook *_floor_256x7_books[]={
  121857. &_huff_book_line_256x7_class0,
  121858. &_huff_book_line_256x7_class1,
  121859. &_huff_book_line_256x7_0sub1,
  121860. &_huff_book_line_256x7_0sub2,
  121861. &_huff_book_line_256x7_0sub3,
  121862. &_huff_book_line_256x7_1sub1,
  121863. &_huff_book_line_256x7_1sub2,
  121864. &_huff_book_line_256x7_1sub3,
  121865. };
  121866. static static_codebook *_floor_128x11_books[]={
  121867. &_huff_book_line_128x11_class1,
  121868. &_huff_book_line_128x11_class2,
  121869. &_huff_book_line_128x11_class3,
  121870. &_huff_book_line_128x11_0sub0,
  121871. &_huff_book_line_128x11_1sub0,
  121872. &_huff_book_line_128x11_1sub1,
  121873. &_huff_book_line_128x11_2sub1,
  121874. &_huff_book_line_128x11_2sub2,
  121875. &_huff_book_line_128x11_2sub3,
  121876. &_huff_book_line_128x11_3sub1,
  121877. &_huff_book_line_128x11_3sub2,
  121878. &_huff_book_line_128x11_3sub3,
  121879. };
  121880. static static_codebook *_floor_128x17_books[]={
  121881. &_huff_book_line_128x17_class1,
  121882. &_huff_book_line_128x17_class2,
  121883. &_huff_book_line_128x17_class3,
  121884. &_huff_book_line_128x17_0sub0,
  121885. &_huff_book_line_128x17_1sub0,
  121886. &_huff_book_line_128x17_1sub1,
  121887. &_huff_book_line_128x17_2sub1,
  121888. &_huff_book_line_128x17_2sub2,
  121889. &_huff_book_line_128x17_2sub3,
  121890. &_huff_book_line_128x17_3sub1,
  121891. &_huff_book_line_128x17_3sub2,
  121892. &_huff_book_line_128x17_3sub3,
  121893. };
  121894. static static_codebook *_floor_256x4low_books[]={
  121895. &_huff_book_line_256x4low_class0,
  121896. &_huff_book_line_256x4low_0sub0,
  121897. &_huff_book_line_256x4low_0sub1,
  121898. &_huff_book_line_256x4low_0sub2,
  121899. &_huff_book_line_256x4low_0sub3,
  121900. };
  121901. static static_codebook *_floor_1024x27_books[]={
  121902. &_huff_book_line_1024x27_class1,
  121903. &_huff_book_line_1024x27_class2,
  121904. &_huff_book_line_1024x27_class3,
  121905. &_huff_book_line_1024x27_class4,
  121906. &_huff_book_line_1024x27_0sub0,
  121907. &_huff_book_line_1024x27_1sub0,
  121908. &_huff_book_line_1024x27_1sub1,
  121909. &_huff_book_line_1024x27_2sub0,
  121910. &_huff_book_line_1024x27_2sub1,
  121911. &_huff_book_line_1024x27_3sub1,
  121912. &_huff_book_line_1024x27_3sub2,
  121913. &_huff_book_line_1024x27_3sub3,
  121914. &_huff_book_line_1024x27_4sub1,
  121915. &_huff_book_line_1024x27_4sub2,
  121916. &_huff_book_line_1024x27_4sub3,
  121917. };
  121918. static static_codebook *_floor_2048x27_books[]={
  121919. &_huff_book_line_2048x27_class1,
  121920. &_huff_book_line_2048x27_class2,
  121921. &_huff_book_line_2048x27_class3,
  121922. &_huff_book_line_2048x27_class4,
  121923. &_huff_book_line_2048x27_0sub0,
  121924. &_huff_book_line_2048x27_1sub0,
  121925. &_huff_book_line_2048x27_1sub1,
  121926. &_huff_book_line_2048x27_2sub0,
  121927. &_huff_book_line_2048x27_2sub1,
  121928. &_huff_book_line_2048x27_3sub1,
  121929. &_huff_book_line_2048x27_3sub2,
  121930. &_huff_book_line_2048x27_3sub3,
  121931. &_huff_book_line_2048x27_4sub1,
  121932. &_huff_book_line_2048x27_4sub2,
  121933. &_huff_book_line_2048x27_4sub3,
  121934. };
  121935. static static_codebook *_floor_512x17_books[]={
  121936. &_huff_book_line_512x17_class1,
  121937. &_huff_book_line_512x17_class2,
  121938. &_huff_book_line_512x17_class3,
  121939. &_huff_book_line_512x17_0sub0,
  121940. &_huff_book_line_512x17_1sub0,
  121941. &_huff_book_line_512x17_1sub1,
  121942. &_huff_book_line_512x17_2sub1,
  121943. &_huff_book_line_512x17_2sub2,
  121944. &_huff_book_line_512x17_2sub3,
  121945. &_huff_book_line_512x17_3sub1,
  121946. &_huff_book_line_512x17_3sub2,
  121947. &_huff_book_line_512x17_3sub3,
  121948. };
  121949. static static_codebook **_floor_books[10]={
  121950. _floor_128x4_books,
  121951. _floor_256x4_books,
  121952. _floor_128x7_books,
  121953. _floor_256x7_books,
  121954. _floor_128x11_books,
  121955. _floor_128x17_books,
  121956. _floor_256x4low_books,
  121957. _floor_1024x27_books,
  121958. _floor_2048x27_books,
  121959. _floor_512x17_books,
  121960. };
  121961. static vorbis_info_floor1 _floor[10]={
  121962. /* 128 x 4 */
  121963. {
  121964. 1,{0},{4},{2},{0},
  121965. {{1,2,3,4}},
  121966. 4,{0,128, 33,8,16,70},
  121967. 60,30,500, 1.,18., -1
  121968. },
  121969. /* 256 x 4 */
  121970. {
  121971. 1,{0},{4},{2},{0},
  121972. {{1,2,3,4}},
  121973. 4,{0,256, 66,16,32,140},
  121974. 60,30,500, 1.,18., -1
  121975. },
  121976. /* 128 x 7 */
  121977. {
  121978. 2,{0,1},{3,4},{2,2},{0,1},
  121979. {{-1,2,3,4},{-1,5,6,7}},
  121980. 4,{0,128, 14,4,58, 2,8,28,90},
  121981. 60,30,500, 1.,18., -1
  121982. },
  121983. /* 256 x 7 */
  121984. {
  121985. 2,{0,1},{3,4},{2,2},{0,1},
  121986. {{-1,2,3,4},{-1,5,6,7}},
  121987. 4,{0,256, 28,8,116, 4,16,56,180},
  121988. 60,30,500, 1.,18., -1
  121989. },
  121990. /* 128 x 11 */
  121991. {
  121992. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  121993. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  121994. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  121995. 60,30,500, 1,18., -1
  121996. },
  121997. /* 128 x 17 */
  121998. {
  121999. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122000. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122001. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122002. 60,30,500, 1,18., -1
  122003. },
  122004. /* 256 x 4 (low bitrate version) */
  122005. {
  122006. 1,{0},{4},{2},{0},
  122007. {{1,2,3,4}},
  122008. 4,{0,256, 66,16,32,140},
  122009. 60,30,500, 1.,18., -1
  122010. },
  122011. /* 1024 x 27 */
  122012. {
  122013. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122014. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122015. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122016. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122017. 60,30,500, 3,18., -1 /* lowpass */
  122018. },
  122019. /* 2048 x 27 */
  122020. {
  122021. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122022. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122023. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122024. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122025. 60,30,500, 3,18., -1 /* lowpass */
  122026. },
  122027. /* 512 x 17 */
  122028. {
  122029. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122030. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122031. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122032. 7,23,39, 55,79,110, 156,232,360},
  122033. 60,30,500, 1,18., -1 /* lowpass! */
  122034. },
  122035. };
  122036. /*** End of inlined file: floor_all.h ***/
  122037. /*** Start of inlined file: residue_44.h ***/
  122038. /*** Start of inlined file: res_books_stereo.h ***/
  122039. static long _vq_quantlist__16c0_s_p1_0[] = {
  122040. 1,
  122041. 0,
  122042. 2,
  122043. };
  122044. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122045. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122046. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122050. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122051. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122055. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122056. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122091. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  122096. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  122101. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122136. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122137. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122141. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122142. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  122143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122146. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122147. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122455. 0,
  122456. };
  122457. static float _vq_quantthresh__16c0_s_p1_0[] = {
  122458. -0.5, 0.5,
  122459. };
  122460. static long _vq_quantmap__16c0_s_p1_0[] = {
  122461. 1, 0, 2,
  122462. };
  122463. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  122464. _vq_quantthresh__16c0_s_p1_0,
  122465. _vq_quantmap__16c0_s_p1_0,
  122466. 3,
  122467. 3
  122468. };
  122469. static static_codebook _16c0_s_p1_0 = {
  122470. 8, 6561,
  122471. _vq_lengthlist__16c0_s_p1_0,
  122472. 1, -535822336, 1611661312, 2, 0,
  122473. _vq_quantlist__16c0_s_p1_0,
  122474. NULL,
  122475. &_vq_auxt__16c0_s_p1_0,
  122476. NULL,
  122477. 0
  122478. };
  122479. static long _vq_quantlist__16c0_s_p2_0[] = {
  122480. 2,
  122481. 1,
  122482. 3,
  122483. 0,
  122484. 4,
  122485. };
  122486. static long _vq_lengthlist__16c0_s_p2_0[] = {
  122487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122526. 0,
  122527. };
  122528. static float _vq_quantthresh__16c0_s_p2_0[] = {
  122529. -1.5, -0.5, 0.5, 1.5,
  122530. };
  122531. static long _vq_quantmap__16c0_s_p2_0[] = {
  122532. 3, 1, 0, 2, 4,
  122533. };
  122534. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  122535. _vq_quantthresh__16c0_s_p2_0,
  122536. _vq_quantmap__16c0_s_p2_0,
  122537. 5,
  122538. 5
  122539. };
  122540. static static_codebook _16c0_s_p2_0 = {
  122541. 4, 625,
  122542. _vq_lengthlist__16c0_s_p2_0,
  122543. 1, -533725184, 1611661312, 3, 0,
  122544. _vq_quantlist__16c0_s_p2_0,
  122545. NULL,
  122546. &_vq_auxt__16c0_s_p2_0,
  122547. NULL,
  122548. 0
  122549. };
  122550. static long _vq_quantlist__16c0_s_p3_0[] = {
  122551. 2,
  122552. 1,
  122553. 3,
  122554. 0,
  122555. 4,
  122556. };
  122557. static long _vq_lengthlist__16c0_s_p3_0[] = {
  122558. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  122560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122561. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  122563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122564. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  122565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122597. 0,
  122598. };
  122599. static float _vq_quantthresh__16c0_s_p3_0[] = {
  122600. -1.5, -0.5, 0.5, 1.5,
  122601. };
  122602. static long _vq_quantmap__16c0_s_p3_0[] = {
  122603. 3, 1, 0, 2, 4,
  122604. };
  122605. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  122606. _vq_quantthresh__16c0_s_p3_0,
  122607. _vq_quantmap__16c0_s_p3_0,
  122608. 5,
  122609. 5
  122610. };
  122611. static static_codebook _16c0_s_p3_0 = {
  122612. 4, 625,
  122613. _vq_lengthlist__16c0_s_p3_0,
  122614. 1, -533725184, 1611661312, 3, 0,
  122615. _vq_quantlist__16c0_s_p3_0,
  122616. NULL,
  122617. &_vq_auxt__16c0_s_p3_0,
  122618. NULL,
  122619. 0
  122620. };
  122621. static long _vq_quantlist__16c0_s_p4_0[] = {
  122622. 4,
  122623. 3,
  122624. 5,
  122625. 2,
  122626. 6,
  122627. 1,
  122628. 7,
  122629. 0,
  122630. 8,
  122631. };
  122632. static long _vq_lengthlist__16c0_s_p4_0[] = {
  122633. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  122634. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  122635. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122636. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  122637. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122638. 0,
  122639. };
  122640. static float _vq_quantthresh__16c0_s_p4_0[] = {
  122641. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122642. };
  122643. static long _vq_quantmap__16c0_s_p4_0[] = {
  122644. 7, 5, 3, 1, 0, 2, 4, 6,
  122645. 8,
  122646. };
  122647. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  122648. _vq_quantthresh__16c0_s_p4_0,
  122649. _vq_quantmap__16c0_s_p4_0,
  122650. 9,
  122651. 9
  122652. };
  122653. static static_codebook _16c0_s_p4_0 = {
  122654. 2, 81,
  122655. _vq_lengthlist__16c0_s_p4_0,
  122656. 1, -531628032, 1611661312, 4, 0,
  122657. _vq_quantlist__16c0_s_p4_0,
  122658. NULL,
  122659. &_vq_auxt__16c0_s_p4_0,
  122660. NULL,
  122661. 0
  122662. };
  122663. static long _vq_quantlist__16c0_s_p5_0[] = {
  122664. 4,
  122665. 3,
  122666. 5,
  122667. 2,
  122668. 6,
  122669. 1,
  122670. 7,
  122671. 0,
  122672. 8,
  122673. };
  122674. static long _vq_lengthlist__16c0_s_p5_0[] = {
  122675. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  122676. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  122677. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  122678. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  122679. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  122680. 10,
  122681. };
  122682. static float _vq_quantthresh__16c0_s_p5_0[] = {
  122683. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122684. };
  122685. static long _vq_quantmap__16c0_s_p5_0[] = {
  122686. 7, 5, 3, 1, 0, 2, 4, 6,
  122687. 8,
  122688. };
  122689. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  122690. _vq_quantthresh__16c0_s_p5_0,
  122691. _vq_quantmap__16c0_s_p5_0,
  122692. 9,
  122693. 9
  122694. };
  122695. static static_codebook _16c0_s_p5_0 = {
  122696. 2, 81,
  122697. _vq_lengthlist__16c0_s_p5_0,
  122698. 1, -531628032, 1611661312, 4, 0,
  122699. _vq_quantlist__16c0_s_p5_0,
  122700. NULL,
  122701. &_vq_auxt__16c0_s_p5_0,
  122702. NULL,
  122703. 0
  122704. };
  122705. static long _vq_quantlist__16c0_s_p6_0[] = {
  122706. 8,
  122707. 7,
  122708. 9,
  122709. 6,
  122710. 10,
  122711. 5,
  122712. 11,
  122713. 4,
  122714. 12,
  122715. 3,
  122716. 13,
  122717. 2,
  122718. 14,
  122719. 1,
  122720. 15,
  122721. 0,
  122722. 16,
  122723. };
  122724. static long _vq_lengthlist__16c0_s_p6_0[] = {
  122725. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  122726. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  122727. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  122728. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  122729. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  122730. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  122731. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  122732. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  122733. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  122734. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122735. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  122736. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  122737. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  122738. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  122739. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  122740. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  122741. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  122742. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  122743. 14,
  122744. };
  122745. static float _vq_quantthresh__16c0_s_p6_0[] = {
  122746. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122747. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122748. };
  122749. static long _vq_quantmap__16c0_s_p6_0[] = {
  122750. 15, 13, 11, 9, 7, 5, 3, 1,
  122751. 0, 2, 4, 6, 8, 10, 12, 14,
  122752. 16,
  122753. };
  122754. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  122755. _vq_quantthresh__16c0_s_p6_0,
  122756. _vq_quantmap__16c0_s_p6_0,
  122757. 17,
  122758. 17
  122759. };
  122760. static static_codebook _16c0_s_p6_0 = {
  122761. 2, 289,
  122762. _vq_lengthlist__16c0_s_p6_0,
  122763. 1, -529530880, 1611661312, 5, 0,
  122764. _vq_quantlist__16c0_s_p6_0,
  122765. NULL,
  122766. &_vq_auxt__16c0_s_p6_0,
  122767. NULL,
  122768. 0
  122769. };
  122770. static long _vq_quantlist__16c0_s_p7_0[] = {
  122771. 1,
  122772. 0,
  122773. 2,
  122774. };
  122775. static long _vq_lengthlist__16c0_s_p7_0[] = {
  122776. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  122777. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  122778. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  122779. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  122780. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  122781. 13,
  122782. };
  122783. static float _vq_quantthresh__16c0_s_p7_0[] = {
  122784. -5.5, 5.5,
  122785. };
  122786. static long _vq_quantmap__16c0_s_p7_0[] = {
  122787. 1, 0, 2,
  122788. };
  122789. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  122790. _vq_quantthresh__16c0_s_p7_0,
  122791. _vq_quantmap__16c0_s_p7_0,
  122792. 3,
  122793. 3
  122794. };
  122795. static static_codebook _16c0_s_p7_0 = {
  122796. 4, 81,
  122797. _vq_lengthlist__16c0_s_p7_0,
  122798. 1, -529137664, 1618345984, 2, 0,
  122799. _vq_quantlist__16c0_s_p7_0,
  122800. NULL,
  122801. &_vq_auxt__16c0_s_p7_0,
  122802. NULL,
  122803. 0
  122804. };
  122805. static long _vq_quantlist__16c0_s_p7_1[] = {
  122806. 5,
  122807. 4,
  122808. 6,
  122809. 3,
  122810. 7,
  122811. 2,
  122812. 8,
  122813. 1,
  122814. 9,
  122815. 0,
  122816. 10,
  122817. };
  122818. static long _vq_lengthlist__16c0_s_p7_1[] = {
  122819. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  122820. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  122821. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  122822. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  122823. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  122824. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  122825. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  122826. 11,11,11, 9, 9, 9, 9,10,10,
  122827. };
  122828. static float _vq_quantthresh__16c0_s_p7_1[] = {
  122829. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122830. 3.5, 4.5,
  122831. };
  122832. static long _vq_quantmap__16c0_s_p7_1[] = {
  122833. 9, 7, 5, 3, 1, 0, 2, 4,
  122834. 6, 8, 10,
  122835. };
  122836. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  122837. _vq_quantthresh__16c0_s_p7_1,
  122838. _vq_quantmap__16c0_s_p7_1,
  122839. 11,
  122840. 11
  122841. };
  122842. static static_codebook _16c0_s_p7_1 = {
  122843. 2, 121,
  122844. _vq_lengthlist__16c0_s_p7_1,
  122845. 1, -531365888, 1611661312, 4, 0,
  122846. _vq_quantlist__16c0_s_p7_1,
  122847. NULL,
  122848. &_vq_auxt__16c0_s_p7_1,
  122849. NULL,
  122850. 0
  122851. };
  122852. static long _vq_quantlist__16c0_s_p8_0[] = {
  122853. 6,
  122854. 5,
  122855. 7,
  122856. 4,
  122857. 8,
  122858. 3,
  122859. 9,
  122860. 2,
  122861. 10,
  122862. 1,
  122863. 11,
  122864. 0,
  122865. 12,
  122866. };
  122867. static long _vq_lengthlist__16c0_s_p8_0[] = {
  122868. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  122869. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  122870. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  122871. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  122872. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  122873. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  122874. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  122875. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  122876. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  122877. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  122878. 0,12,13,13,12,13,14,14,14,
  122879. };
  122880. static float _vq_quantthresh__16c0_s_p8_0[] = {
  122881. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122882. 12.5, 17.5, 22.5, 27.5,
  122883. };
  122884. static long _vq_quantmap__16c0_s_p8_0[] = {
  122885. 11, 9, 7, 5, 3, 1, 0, 2,
  122886. 4, 6, 8, 10, 12,
  122887. };
  122888. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  122889. _vq_quantthresh__16c0_s_p8_0,
  122890. _vq_quantmap__16c0_s_p8_0,
  122891. 13,
  122892. 13
  122893. };
  122894. static static_codebook _16c0_s_p8_0 = {
  122895. 2, 169,
  122896. _vq_lengthlist__16c0_s_p8_0,
  122897. 1, -526516224, 1616117760, 4, 0,
  122898. _vq_quantlist__16c0_s_p8_0,
  122899. NULL,
  122900. &_vq_auxt__16c0_s_p8_0,
  122901. NULL,
  122902. 0
  122903. };
  122904. static long _vq_quantlist__16c0_s_p8_1[] = {
  122905. 2,
  122906. 1,
  122907. 3,
  122908. 0,
  122909. 4,
  122910. };
  122911. static long _vq_lengthlist__16c0_s_p8_1[] = {
  122912. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  122913. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  122914. };
  122915. static float _vq_quantthresh__16c0_s_p8_1[] = {
  122916. -1.5, -0.5, 0.5, 1.5,
  122917. };
  122918. static long _vq_quantmap__16c0_s_p8_1[] = {
  122919. 3, 1, 0, 2, 4,
  122920. };
  122921. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  122922. _vq_quantthresh__16c0_s_p8_1,
  122923. _vq_quantmap__16c0_s_p8_1,
  122924. 5,
  122925. 5
  122926. };
  122927. static static_codebook _16c0_s_p8_1 = {
  122928. 2, 25,
  122929. _vq_lengthlist__16c0_s_p8_1,
  122930. 1, -533725184, 1611661312, 3, 0,
  122931. _vq_quantlist__16c0_s_p8_1,
  122932. NULL,
  122933. &_vq_auxt__16c0_s_p8_1,
  122934. NULL,
  122935. 0
  122936. };
  122937. static long _vq_quantlist__16c0_s_p9_0[] = {
  122938. 1,
  122939. 0,
  122940. 2,
  122941. };
  122942. static long _vq_lengthlist__16c0_s_p9_0[] = {
  122943. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122944. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122945. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122946. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122947. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122948. 7,
  122949. };
  122950. static float _vq_quantthresh__16c0_s_p9_0[] = {
  122951. -157.5, 157.5,
  122952. };
  122953. static long _vq_quantmap__16c0_s_p9_0[] = {
  122954. 1, 0, 2,
  122955. };
  122956. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  122957. _vq_quantthresh__16c0_s_p9_0,
  122958. _vq_quantmap__16c0_s_p9_0,
  122959. 3,
  122960. 3
  122961. };
  122962. static static_codebook _16c0_s_p9_0 = {
  122963. 4, 81,
  122964. _vq_lengthlist__16c0_s_p9_0,
  122965. 1, -518803456, 1628680192, 2, 0,
  122966. _vq_quantlist__16c0_s_p9_0,
  122967. NULL,
  122968. &_vq_auxt__16c0_s_p9_0,
  122969. NULL,
  122970. 0
  122971. };
  122972. static long _vq_quantlist__16c0_s_p9_1[] = {
  122973. 7,
  122974. 6,
  122975. 8,
  122976. 5,
  122977. 9,
  122978. 4,
  122979. 10,
  122980. 3,
  122981. 11,
  122982. 2,
  122983. 12,
  122984. 1,
  122985. 13,
  122986. 0,
  122987. 14,
  122988. };
  122989. static long _vq_lengthlist__16c0_s_p9_1[] = {
  122990. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  122991. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  122992. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  122993. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  122994. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122995. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122996. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122997. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122998. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122999. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123000. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123001. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123002. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123003. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123004. 10,
  123005. };
  123006. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123007. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123008. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123009. };
  123010. static long _vq_quantmap__16c0_s_p9_1[] = {
  123011. 13, 11, 9, 7, 5, 3, 1, 0,
  123012. 2, 4, 6, 8, 10, 12, 14,
  123013. };
  123014. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123015. _vq_quantthresh__16c0_s_p9_1,
  123016. _vq_quantmap__16c0_s_p9_1,
  123017. 15,
  123018. 15
  123019. };
  123020. static static_codebook _16c0_s_p9_1 = {
  123021. 2, 225,
  123022. _vq_lengthlist__16c0_s_p9_1,
  123023. 1, -520986624, 1620377600, 4, 0,
  123024. _vq_quantlist__16c0_s_p9_1,
  123025. NULL,
  123026. &_vq_auxt__16c0_s_p9_1,
  123027. NULL,
  123028. 0
  123029. };
  123030. static long _vq_quantlist__16c0_s_p9_2[] = {
  123031. 10,
  123032. 9,
  123033. 11,
  123034. 8,
  123035. 12,
  123036. 7,
  123037. 13,
  123038. 6,
  123039. 14,
  123040. 5,
  123041. 15,
  123042. 4,
  123043. 16,
  123044. 3,
  123045. 17,
  123046. 2,
  123047. 18,
  123048. 1,
  123049. 19,
  123050. 0,
  123051. 20,
  123052. };
  123053. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123054. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123055. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123056. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123057. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123058. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123059. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123060. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123061. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123062. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123063. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123064. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123065. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123066. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123067. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123068. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123069. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123070. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123071. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123072. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123073. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123074. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123075. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123076. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123077. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123078. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123079. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123080. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123081. 10,11,10,10,11, 9,10,10,10,
  123082. };
  123083. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123084. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123085. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123086. 6.5, 7.5, 8.5, 9.5,
  123087. };
  123088. static long _vq_quantmap__16c0_s_p9_2[] = {
  123089. 19, 17, 15, 13, 11, 9, 7, 5,
  123090. 3, 1, 0, 2, 4, 6, 8, 10,
  123091. 12, 14, 16, 18, 20,
  123092. };
  123093. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123094. _vq_quantthresh__16c0_s_p9_2,
  123095. _vq_quantmap__16c0_s_p9_2,
  123096. 21,
  123097. 21
  123098. };
  123099. static static_codebook _16c0_s_p9_2 = {
  123100. 2, 441,
  123101. _vq_lengthlist__16c0_s_p9_2,
  123102. 1, -529268736, 1611661312, 5, 0,
  123103. _vq_quantlist__16c0_s_p9_2,
  123104. NULL,
  123105. &_vq_auxt__16c0_s_p9_2,
  123106. NULL,
  123107. 0
  123108. };
  123109. static long _huff_lengthlist__16c0_s_single[] = {
  123110. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123111. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123112. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123113. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123114. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123115. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123116. 16,16,18,18,
  123117. };
  123118. static static_codebook _huff_book__16c0_s_single = {
  123119. 2, 100,
  123120. _huff_lengthlist__16c0_s_single,
  123121. 0, 0, 0, 0, 0,
  123122. NULL,
  123123. NULL,
  123124. NULL,
  123125. NULL,
  123126. 0
  123127. };
  123128. static long _huff_lengthlist__16c1_s_long[] = {
  123129. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123130. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123131. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123132. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123133. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123134. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123135. 12,11,11,13,
  123136. };
  123137. static static_codebook _huff_book__16c1_s_long = {
  123138. 2, 100,
  123139. _huff_lengthlist__16c1_s_long,
  123140. 0, 0, 0, 0, 0,
  123141. NULL,
  123142. NULL,
  123143. NULL,
  123144. NULL,
  123145. 0
  123146. };
  123147. static long _vq_quantlist__16c1_s_p1_0[] = {
  123148. 1,
  123149. 0,
  123150. 2,
  123151. };
  123152. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123153. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123154. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123158. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123159. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123163. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123164. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  123199. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123204. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123209. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123244. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123245. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123249. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123250. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  123251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123254. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123255. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  123256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123563. 0,
  123564. };
  123565. static float _vq_quantthresh__16c1_s_p1_0[] = {
  123566. -0.5, 0.5,
  123567. };
  123568. static long _vq_quantmap__16c1_s_p1_0[] = {
  123569. 1, 0, 2,
  123570. };
  123571. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  123572. _vq_quantthresh__16c1_s_p1_0,
  123573. _vq_quantmap__16c1_s_p1_0,
  123574. 3,
  123575. 3
  123576. };
  123577. static static_codebook _16c1_s_p1_0 = {
  123578. 8, 6561,
  123579. _vq_lengthlist__16c1_s_p1_0,
  123580. 1, -535822336, 1611661312, 2, 0,
  123581. _vq_quantlist__16c1_s_p1_0,
  123582. NULL,
  123583. &_vq_auxt__16c1_s_p1_0,
  123584. NULL,
  123585. 0
  123586. };
  123587. static long _vq_quantlist__16c1_s_p2_0[] = {
  123588. 2,
  123589. 1,
  123590. 3,
  123591. 0,
  123592. 4,
  123593. };
  123594. static long _vq_lengthlist__16c1_s_p2_0[] = {
  123595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123634. 0,
  123635. };
  123636. static float _vq_quantthresh__16c1_s_p2_0[] = {
  123637. -1.5, -0.5, 0.5, 1.5,
  123638. };
  123639. static long _vq_quantmap__16c1_s_p2_0[] = {
  123640. 3, 1, 0, 2, 4,
  123641. };
  123642. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  123643. _vq_quantthresh__16c1_s_p2_0,
  123644. _vq_quantmap__16c1_s_p2_0,
  123645. 5,
  123646. 5
  123647. };
  123648. static static_codebook _16c1_s_p2_0 = {
  123649. 4, 625,
  123650. _vq_lengthlist__16c1_s_p2_0,
  123651. 1, -533725184, 1611661312, 3, 0,
  123652. _vq_quantlist__16c1_s_p2_0,
  123653. NULL,
  123654. &_vq_auxt__16c1_s_p2_0,
  123655. NULL,
  123656. 0
  123657. };
  123658. static long _vq_quantlist__16c1_s_p3_0[] = {
  123659. 2,
  123660. 1,
  123661. 3,
  123662. 0,
  123663. 4,
  123664. };
  123665. static long _vq_lengthlist__16c1_s_p3_0[] = {
  123666. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  123668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123669. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  123671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123672. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123705. 0,
  123706. };
  123707. static float _vq_quantthresh__16c1_s_p3_0[] = {
  123708. -1.5, -0.5, 0.5, 1.5,
  123709. };
  123710. static long _vq_quantmap__16c1_s_p3_0[] = {
  123711. 3, 1, 0, 2, 4,
  123712. };
  123713. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  123714. _vq_quantthresh__16c1_s_p3_0,
  123715. _vq_quantmap__16c1_s_p3_0,
  123716. 5,
  123717. 5
  123718. };
  123719. static static_codebook _16c1_s_p3_0 = {
  123720. 4, 625,
  123721. _vq_lengthlist__16c1_s_p3_0,
  123722. 1, -533725184, 1611661312, 3, 0,
  123723. _vq_quantlist__16c1_s_p3_0,
  123724. NULL,
  123725. &_vq_auxt__16c1_s_p3_0,
  123726. NULL,
  123727. 0
  123728. };
  123729. static long _vq_quantlist__16c1_s_p4_0[] = {
  123730. 4,
  123731. 3,
  123732. 5,
  123733. 2,
  123734. 6,
  123735. 1,
  123736. 7,
  123737. 0,
  123738. 8,
  123739. };
  123740. static long _vq_lengthlist__16c1_s_p4_0[] = {
  123741. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123742. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123743. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123744. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  123745. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123746. 0,
  123747. };
  123748. static float _vq_quantthresh__16c1_s_p4_0[] = {
  123749. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123750. };
  123751. static long _vq_quantmap__16c1_s_p4_0[] = {
  123752. 7, 5, 3, 1, 0, 2, 4, 6,
  123753. 8,
  123754. };
  123755. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  123756. _vq_quantthresh__16c1_s_p4_0,
  123757. _vq_quantmap__16c1_s_p4_0,
  123758. 9,
  123759. 9
  123760. };
  123761. static static_codebook _16c1_s_p4_0 = {
  123762. 2, 81,
  123763. _vq_lengthlist__16c1_s_p4_0,
  123764. 1, -531628032, 1611661312, 4, 0,
  123765. _vq_quantlist__16c1_s_p4_0,
  123766. NULL,
  123767. &_vq_auxt__16c1_s_p4_0,
  123768. NULL,
  123769. 0
  123770. };
  123771. static long _vq_quantlist__16c1_s_p5_0[] = {
  123772. 4,
  123773. 3,
  123774. 5,
  123775. 2,
  123776. 6,
  123777. 1,
  123778. 7,
  123779. 0,
  123780. 8,
  123781. };
  123782. static long _vq_lengthlist__16c1_s_p5_0[] = {
  123783. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123784. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  123785. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  123786. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  123787. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123788. 10,
  123789. };
  123790. static float _vq_quantthresh__16c1_s_p5_0[] = {
  123791. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123792. };
  123793. static long _vq_quantmap__16c1_s_p5_0[] = {
  123794. 7, 5, 3, 1, 0, 2, 4, 6,
  123795. 8,
  123796. };
  123797. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  123798. _vq_quantthresh__16c1_s_p5_0,
  123799. _vq_quantmap__16c1_s_p5_0,
  123800. 9,
  123801. 9
  123802. };
  123803. static static_codebook _16c1_s_p5_0 = {
  123804. 2, 81,
  123805. _vq_lengthlist__16c1_s_p5_0,
  123806. 1, -531628032, 1611661312, 4, 0,
  123807. _vq_quantlist__16c1_s_p5_0,
  123808. NULL,
  123809. &_vq_auxt__16c1_s_p5_0,
  123810. NULL,
  123811. 0
  123812. };
  123813. static long _vq_quantlist__16c1_s_p6_0[] = {
  123814. 8,
  123815. 7,
  123816. 9,
  123817. 6,
  123818. 10,
  123819. 5,
  123820. 11,
  123821. 4,
  123822. 12,
  123823. 3,
  123824. 13,
  123825. 2,
  123826. 14,
  123827. 1,
  123828. 15,
  123829. 0,
  123830. 16,
  123831. };
  123832. static long _vq_lengthlist__16c1_s_p6_0[] = {
  123833. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  123834. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  123835. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  123836. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  123837. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  123838. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123839. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123840. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123841. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  123842. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123843. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  123844. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  123845. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  123846. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  123847. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  123848. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  123849. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  123850. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  123851. 14,
  123852. };
  123853. static float _vq_quantthresh__16c1_s_p6_0[] = {
  123854. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123855. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123856. };
  123857. static long _vq_quantmap__16c1_s_p6_0[] = {
  123858. 15, 13, 11, 9, 7, 5, 3, 1,
  123859. 0, 2, 4, 6, 8, 10, 12, 14,
  123860. 16,
  123861. };
  123862. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  123863. _vq_quantthresh__16c1_s_p6_0,
  123864. _vq_quantmap__16c1_s_p6_0,
  123865. 17,
  123866. 17
  123867. };
  123868. static static_codebook _16c1_s_p6_0 = {
  123869. 2, 289,
  123870. _vq_lengthlist__16c1_s_p6_0,
  123871. 1, -529530880, 1611661312, 5, 0,
  123872. _vq_quantlist__16c1_s_p6_0,
  123873. NULL,
  123874. &_vq_auxt__16c1_s_p6_0,
  123875. NULL,
  123876. 0
  123877. };
  123878. static long _vq_quantlist__16c1_s_p7_0[] = {
  123879. 1,
  123880. 0,
  123881. 2,
  123882. };
  123883. static long _vq_lengthlist__16c1_s_p7_0[] = {
  123884. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  123885. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123886. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  123887. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  123888. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  123889. 11,
  123890. };
  123891. static float _vq_quantthresh__16c1_s_p7_0[] = {
  123892. -5.5, 5.5,
  123893. };
  123894. static long _vq_quantmap__16c1_s_p7_0[] = {
  123895. 1, 0, 2,
  123896. };
  123897. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  123898. _vq_quantthresh__16c1_s_p7_0,
  123899. _vq_quantmap__16c1_s_p7_0,
  123900. 3,
  123901. 3
  123902. };
  123903. static static_codebook _16c1_s_p7_0 = {
  123904. 4, 81,
  123905. _vq_lengthlist__16c1_s_p7_0,
  123906. 1, -529137664, 1618345984, 2, 0,
  123907. _vq_quantlist__16c1_s_p7_0,
  123908. NULL,
  123909. &_vq_auxt__16c1_s_p7_0,
  123910. NULL,
  123911. 0
  123912. };
  123913. static long _vq_quantlist__16c1_s_p7_1[] = {
  123914. 5,
  123915. 4,
  123916. 6,
  123917. 3,
  123918. 7,
  123919. 2,
  123920. 8,
  123921. 1,
  123922. 9,
  123923. 0,
  123924. 10,
  123925. };
  123926. static long _vq_lengthlist__16c1_s_p7_1[] = {
  123927. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  123928. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  123929. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  123930. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  123931. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  123932. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  123933. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  123934. 10,10,10, 8, 8, 8, 8, 9, 9,
  123935. };
  123936. static float _vq_quantthresh__16c1_s_p7_1[] = {
  123937. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123938. 3.5, 4.5,
  123939. };
  123940. static long _vq_quantmap__16c1_s_p7_1[] = {
  123941. 9, 7, 5, 3, 1, 0, 2, 4,
  123942. 6, 8, 10,
  123943. };
  123944. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  123945. _vq_quantthresh__16c1_s_p7_1,
  123946. _vq_quantmap__16c1_s_p7_1,
  123947. 11,
  123948. 11
  123949. };
  123950. static static_codebook _16c1_s_p7_1 = {
  123951. 2, 121,
  123952. _vq_lengthlist__16c1_s_p7_1,
  123953. 1, -531365888, 1611661312, 4, 0,
  123954. _vq_quantlist__16c1_s_p7_1,
  123955. NULL,
  123956. &_vq_auxt__16c1_s_p7_1,
  123957. NULL,
  123958. 0
  123959. };
  123960. static long _vq_quantlist__16c1_s_p8_0[] = {
  123961. 6,
  123962. 5,
  123963. 7,
  123964. 4,
  123965. 8,
  123966. 3,
  123967. 9,
  123968. 2,
  123969. 10,
  123970. 1,
  123971. 11,
  123972. 0,
  123973. 12,
  123974. };
  123975. static long _vq_lengthlist__16c1_s_p8_0[] = {
  123976. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  123977. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  123978. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  123979. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  123980. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  123981. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  123982. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  123983. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  123984. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  123985. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  123986. 0,12,12,12,12,13,13,14,15,
  123987. };
  123988. static float _vq_quantthresh__16c1_s_p8_0[] = {
  123989. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123990. 12.5, 17.5, 22.5, 27.5,
  123991. };
  123992. static long _vq_quantmap__16c1_s_p8_0[] = {
  123993. 11, 9, 7, 5, 3, 1, 0, 2,
  123994. 4, 6, 8, 10, 12,
  123995. };
  123996. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  123997. _vq_quantthresh__16c1_s_p8_0,
  123998. _vq_quantmap__16c1_s_p8_0,
  123999. 13,
  124000. 13
  124001. };
  124002. static static_codebook _16c1_s_p8_0 = {
  124003. 2, 169,
  124004. _vq_lengthlist__16c1_s_p8_0,
  124005. 1, -526516224, 1616117760, 4, 0,
  124006. _vq_quantlist__16c1_s_p8_0,
  124007. NULL,
  124008. &_vq_auxt__16c1_s_p8_0,
  124009. NULL,
  124010. 0
  124011. };
  124012. static long _vq_quantlist__16c1_s_p8_1[] = {
  124013. 2,
  124014. 1,
  124015. 3,
  124016. 0,
  124017. 4,
  124018. };
  124019. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124020. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124021. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124022. };
  124023. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124024. -1.5, -0.5, 0.5, 1.5,
  124025. };
  124026. static long _vq_quantmap__16c1_s_p8_1[] = {
  124027. 3, 1, 0, 2, 4,
  124028. };
  124029. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124030. _vq_quantthresh__16c1_s_p8_1,
  124031. _vq_quantmap__16c1_s_p8_1,
  124032. 5,
  124033. 5
  124034. };
  124035. static static_codebook _16c1_s_p8_1 = {
  124036. 2, 25,
  124037. _vq_lengthlist__16c1_s_p8_1,
  124038. 1, -533725184, 1611661312, 3, 0,
  124039. _vq_quantlist__16c1_s_p8_1,
  124040. NULL,
  124041. &_vq_auxt__16c1_s_p8_1,
  124042. NULL,
  124043. 0
  124044. };
  124045. static long _vq_quantlist__16c1_s_p9_0[] = {
  124046. 6,
  124047. 5,
  124048. 7,
  124049. 4,
  124050. 8,
  124051. 3,
  124052. 9,
  124053. 2,
  124054. 10,
  124055. 1,
  124056. 11,
  124057. 0,
  124058. 12,
  124059. };
  124060. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124061. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124062. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124063. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124064. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124065. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124066. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124067. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124068. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124069. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124070. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124071. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124072. };
  124073. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124074. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124075. 787.5, 1102.5, 1417.5, 1732.5,
  124076. };
  124077. static long _vq_quantmap__16c1_s_p9_0[] = {
  124078. 11, 9, 7, 5, 3, 1, 0, 2,
  124079. 4, 6, 8, 10, 12,
  124080. };
  124081. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124082. _vq_quantthresh__16c1_s_p9_0,
  124083. _vq_quantmap__16c1_s_p9_0,
  124084. 13,
  124085. 13
  124086. };
  124087. static static_codebook _16c1_s_p9_0 = {
  124088. 2, 169,
  124089. _vq_lengthlist__16c1_s_p9_0,
  124090. 1, -513964032, 1628680192, 4, 0,
  124091. _vq_quantlist__16c1_s_p9_0,
  124092. NULL,
  124093. &_vq_auxt__16c1_s_p9_0,
  124094. NULL,
  124095. 0
  124096. };
  124097. static long _vq_quantlist__16c1_s_p9_1[] = {
  124098. 7,
  124099. 6,
  124100. 8,
  124101. 5,
  124102. 9,
  124103. 4,
  124104. 10,
  124105. 3,
  124106. 11,
  124107. 2,
  124108. 12,
  124109. 1,
  124110. 13,
  124111. 0,
  124112. 14,
  124113. };
  124114. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124115. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124116. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124117. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124118. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124119. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124120. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124121. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124122. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124123. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124124. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124125. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124126. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124127. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124128. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124129. 13,
  124130. };
  124131. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124132. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124133. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124134. };
  124135. static long _vq_quantmap__16c1_s_p9_1[] = {
  124136. 13, 11, 9, 7, 5, 3, 1, 0,
  124137. 2, 4, 6, 8, 10, 12, 14,
  124138. };
  124139. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124140. _vq_quantthresh__16c1_s_p9_1,
  124141. _vq_quantmap__16c1_s_p9_1,
  124142. 15,
  124143. 15
  124144. };
  124145. static static_codebook _16c1_s_p9_1 = {
  124146. 2, 225,
  124147. _vq_lengthlist__16c1_s_p9_1,
  124148. 1, -520986624, 1620377600, 4, 0,
  124149. _vq_quantlist__16c1_s_p9_1,
  124150. NULL,
  124151. &_vq_auxt__16c1_s_p9_1,
  124152. NULL,
  124153. 0
  124154. };
  124155. static long _vq_quantlist__16c1_s_p9_2[] = {
  124156. 10,
  124157. 9,
  124158. 11,
  124159. 8,
  124160. 12,
  124161. 7,
  124162. 13,
  124163. 6,
  124164. 14,
  124165. 5,
  124166. 15,
  124167. 4,
  124168. 16,
  124169. 3,
  124170. 17,
  124171. 2,
  124172. 18,
  124173. 1,
  124174. 19,
  124175. 0,
  124176. 20,
  124177. };
  124178. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124179. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124180. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124181. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124182. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124183. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124184. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124185. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124186. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124187. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124188. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124189. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124190. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124191. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124192. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124193. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124194. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124195. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124196. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124197. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124198. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124199. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124200. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124201. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124202. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124203. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124204. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124205. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124206. 11,11,11,11,12,11,11,12,11,
  124207. };
  124208. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124209. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124210. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124211. 6.5, 7.5, 8.5, 9.5,
  124212. };
  124213. static long _vq_quantmap__16c1_s_p9_2[] = {
  124214. 19, 17, 15, 13, 11, 9, 7, 5,
  124215. 3, 1, 0, 2, 4, 6, 8, 10,
  124216. 12, 14, 16, 18, 20,
  124217. };
  124218. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124219. _vq_quantthresh__16c1_s_p9_2,
  124220. _vq_quantmap__16c1_s_p9_2,
  124221. 21,
  124222. 21
  124223. };
  124224. static static_codebook _16c1_s_p9_2 = {
  124225. 2, 441,
  124226. _vq_lengthlist__16c1_s_p9_2,
  124227. 1, -529268736, 1611661312, 5, 0,
  124228. _vq_quantlist__16c1_s_p9_2,
  124229. NULL,
  124230. &_vq_auxt__16c1_s_p9_2,
  124231. NULL,
  124232. 0
  124233. };
  124234. static long _huff_lengthlist__16c1_s_short[] = {
  124235. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124236. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124237. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124238. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124239. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124240. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124241. 9, 9,10,13,
  124242. };
  124243. static static_codebook _huff_book__16c1_s_short = {
  124244. 2, 100,
  124245. _huff_lengthlist__16c1_s_short,
  124246. 0, 0, 0, 0, 0,
  124247. NULL,
  124248. NULL,
  124249. NULL,
  124250. NULL,
  124251. 0
  124252. };
  124253. static long _huff_lengthlist__16c2_s_long[] = {
  124254. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124255. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124256. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124257. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124258. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124259. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124260. 14,14,16,18,
  124261. };
  124262. static static_codebook _huff_book__16c2_s_long = {
  124263. 2, 100,
  124264. _huff_lengthlist__16c2_s_long,
  124265. 0, 0, 0, 0, 0,
  124266. NULL,
  124267. NULL,
  124268. NULL,
  124269. NULL,
  124270. 0
  124271. };
  124272. static long _vq_quantlist__16c2_s_p1_0[] = {
  124273. 1,
  124274. 0,
  124275. 2,
  124276. };
  124277. static long _vq_lengthlist__16c2_s_p1_0[] = {
  124278. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  124279. 0, 0, 4, 5, 5, 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,
  124284. };
  124285. static float _vq_quantthresh__16c2_s_p1_0[] = {
  124286. -0.5, 0.5,
  124287. };
  124288. static long _vq_quantmap__16c2_s_p1_0[] = {
  124289. 1, 0, 2,
  124290. };
  124291. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  124292. _vq_quantthresh__16c2_s_p1_0,
  124293. _vq_quantmap__16c2_s_p1_0,
  124294. 3,
  124295. 3
  124296. };
  124297. static static_codebook _16c2_s_p1_0 = {
  124298. 4, 81,
  124299. _vq_lengthlist__16c2_s_p1_0,
  124300. 1, -535822336, 1611661312, 2, 0,
  124301. _vq_quantlist__16c2_s_p1_0,
  124302. NULL,
  124303. &_vq_auxt__16c2_s_p1_0,
  124304. NULL,
  124305. 0
  124306. };
  124307. static long _vq_quantlist__16c2_s_p2_0[] = {
  124308. 2,
  124309. 1,
  124310. 3,
  124311. 0,
  124312. 4,
  124313. };
  124314. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124315. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124316. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124317. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124318. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124319. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124320. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124321. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124322. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  124323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124327. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  124328. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124329. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124330. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  124331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124335. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124336. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124337. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124338. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124343. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124344. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124345. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124346. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  124351. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124352. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124353. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124354. 13,
  124355. };
  124356. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124357. -1.5, -0.5, 0.5, 1.5,
  124358. };
  124359. static long _vq_quantmap__16c2_s_p2_0[] = {
  124360. 3, 1, 0, 2, 4,
  124361. };
  124362. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124363. _vq_quantthresh__16c2_s_p2_0,
  124364. _vq_quantmap__16c2_s_p2_0,
  124365. 5,
  124366. 5
  124367. };
  124368. static static_codebook _16c2_s_p2_0 = {
  124369. 4, 625,
  124370. _vq_lengthlist__16c2_s_p2_0,
  124371. 1, -533725184, 1611661312, 3, 0,
  124372. _vq_quantlist__16c2_s_p2_0,
  124373. NULL,
  124374. &_vq_auxt__16c2_s_p2_0,
  124375. NULL,
  124376. 0
  124377. };
  124378. static long _vq_quantlist__16c2_s_p3_0[] = {
  124379. 4,
  124380. 3,
  124381. 5,
  124382. 2,
  124383. 6,
  124384. 1,
  124385. 7,
  124386. 0,
  124387. 8,
  124388. };
  124389. static long _vq_lengthlist__16c2_s_p3_0[] = {
  124390. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  124391. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  124392. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124393. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  124394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124395. 0,
  124396. };
  124397. static float _vq_quantthresh__16c2_s_p3_0[] = {
  124398. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124399. };
  124400. static long _vq_quantmap__16c2_s_p3_0[] = {
  124401. 7, 5, 3, 1, 0, 2, 4, 6,
  124402. 8,
  124403. };
  124404. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  124405. _vq_quantthresh__16c2_s_p3_0,
  124406. _vq_quantmap__16c2_s_p3_0,
  124407. 9,
  124408. 9
  124409. };
  124410. static static_codebook _16c2_s_p3_0 = {
  124411. 2, 81,
  124412. _vq_lengthlist__16c2_s_p3_0,
  124413. 1, -531628032, 1611661312, 4, 0,
  124414. _vq_quantlist__16c2_s_p3_0,
  124415. NULL,
  124416. &_vq_auxt__16c2_s_p3_0,
  124417. NULL,
  124418. 0
  124419. };
  124420. static long _vq_quantlist__16c2_s_p4_0[] = {
  124421. 8,
  124422. 7,
  124423. 9,
  124424. 6,
  124425. 10,
  124426. 5,
  124427. 11,
  124428. 4,
  124429. 12,
  124430. 3,
  124431. 13,
  124432. 2,
  124433. 14,
  124434. 1,
  124435. 15,
  124436. 0,
  124437. 16,
  124438. };
  124439. static long _vq_lengthlist__16c2_s_p4_0[] = {
  124440. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  124441. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  124442. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  124443. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  124444. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  124445. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  124446. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  124447. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  124448. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  124449. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  124450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124458. 0,
  124459. };
  124460. static float _vq_quantthresh__16c2_s_p4_0[] = {
  124461. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124462. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124463. };
  124464. static long _vq_quantmap__16c2_s_p4_0[] = {
  124465. 15, 13, 11, 9, 7, 5, 3, 1,
  124466. 0, 2, 4, 6, 8, 10, 12, 14,
  124467. 16,
  124468. };
  124469. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  124470. _vq_quantthresh__16c2_s_p4_0,
  124471. _vq_quantmap__16c2_s_p4_0,
  124472. 17,
  124473. 17
  124474. };
  124475. static static_codebook _16c2_s_p4_0 = {
  124476. 2, 289,
  124477. _vq_lengthlist__16c2_s_p4_0,
  124478. 1, -529530880, 1611661312, 5, 0,
  124479. _vq_quantlist__16c2_s_p4_0,
  124480. NULL,
  124481. &_vq_auxt__16c2_s_p4_0,
  124482. NULL,
  124483. 0
  124484. };
  124485. static long _vq_quantlist__16c2_s_p5_0[] = {
  124486. 1,
  124487. 0,
  124488. 2,
  124489. };
  124490. static long _vq_lengthlist__16c2_s_p5_0[] = {
  124491. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  124492. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  124493. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  124494. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  124495. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  124496. 12,
  124497. };
  124498. static float _vq_quantthresh__16c2_s_p5_0[] = {
  124499. -5.5, 5.5,
  124500. };
  124501. static long _vq_quantmap__16c2_s_p5_0[] = {
  124502. 1, 0, 2,
  124503. };
  124504. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  124505. _vq_quantthresh__16c2_s_p5_0,
  124506. _vq_quantmap__16c2_s_p5_0,
  124507. 3,
  124508. 3
  124509. };
  124510. static static_codebook _16c2_s_p5_0 = {
  124511. 4, 81,
  124512. _vq_lengthlist__16c2_s_p5_0,
  124513. 1, -529137664, 1618345984, 2, 0,
  124514. _vq_quantlist__16c2_s_p5_0,
  124515. NULL,
  124516. &_vq_auxt__16c2_s_p5_0,
  124517. NULL,
  124518. 0
  124519. };
  124520. static long _vq_quantlist__16c2_s_p5_1[] = {
  124521. 5,
  124522. 4,
  124523. 6,
  124524. 3,
  124525. 7,
  124526. 2,
  124527. 8,
  124528. 1,
  124529. 9,
  124530. 0,
  124531. 10,
  124532. };
  124533. static long _vq_lengthlist__16c2_s_p5_1[] = {
  124534. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  124535. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  124536. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  124537. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  124538. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  124539. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  124540. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  124541. 11,11,11, 7, 7, 8, 8, 8, 8,
  124542. };
  124543. static float _vq_quantthresh__16c2_s_p5_1[] = {
  124544. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124545. 3.5, 4.5,
  124546. };
  124547. static long _vq_quantmap__16c2_s_p5_1[] = {
  124548. 9, 7, 5, 3, 1, 0, 2, 4,
  124549. 6, 8, 10,
  124550. };
  124551. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  124552. _vq_quantthresh__16c2_s_p5_1,
  124553. _vq_quantmap__16c2_s_p5_1,
  124554. 11,
  124555. 11
  124556. };
  124557. static static_codebook _16c2_s_p5_1 = {
  124558. 2, 121,
  124559. _vq_lengthlist__16c2_s_p5_1,
  124560. 1, -531365888, 1611661312, 4, 0,
  124561. _vq_quantlist__16c2_s_p5_1,
  124562. NULL,
  124563. &_vq_auxt__16c2_s_p5_1,
  124564. NULL,
  124565. 0
  124566. };
  124567. static long _vq_quantlist__16c2_s_p6_0[] = {
  124568. 6,
  124569. 5,
  124570. 7,
  124571. 4,
  124572. 8,
  124573. 3,
  124574. 9,
  124575. 2,
  124576. 10,
  124577. 1,
  124578. 11,
  124579. 0,
  124580. 12,
  124581. };
  124582. static long _vq_lengthlist__16c2_s_p6_0[] = {
  124583. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124584. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  124585. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  124586. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  124587. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  124588. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  124589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124593. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124594. };
  124595. static float _vq_quantthresh__16c2_s_p6_0[] = {
  124596. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124597. 12.5, 17.5, 22.5, 27.5,
  124598. };
  124599. static long _vq_quantmap__16c2_s_p6_0[] = {
  124600. 11, 9, 7, 5, 3, 1, 0, 2,
  124601. 4, 6, 8, 10, 12,
  124602. };
  124603. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  124604. _vq_quantthresh__16c2_s_p6_0,
  124605. _vq_quantmap__16c2_s_p6_0,
  124606. 13,
  124607. 13
  124608. };
  124609. static static_codebook _16c2_s_p6_0 = {
  124610. 2, 169,
  124611. _vq_lengthlist__16c2_s_p6_0,
  124612. 1, -526516224, 1616117760, 4, 0,
  124613. _vq_quantlist__16c2_s_p6_0,
  124614. NULL,
  124615. &_vq_auxt__16c2_s_p6_0,
  124616. NULL,
  124617. 0
  124618. };
  124619. static long _vq_quantlist__16c2_s_p6_1[] = {
  124620. 2,
  124621. 1,
  124622. 3,
  124623. 0,
  124624. 4,
  124625. };
  124626. static long _vq_lengthlist__16c2_s_p6_1[] = {
  124627. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124628. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124629. };
  124630. static float _vq_quantthresh__16c2_s_p6_1[] = {
  124631. -1.5, -0.5, 0.5, 1.5,
  124632. };
  124633. static long _vq_quantmap__16c2_s_p6_1[] = {
  124634. 3, 1, 0, 2, 4,
  124635. };
  124636. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  124637. _vq_quantthresh__16c2_s_p6_1,
  124638. _vq_quantmap__16c2_s_p6_1,
  124639. 5,
  124640. 5
  124641. };
  124642. static static_codebook _16c2_s_p6_1 = {
  124643. 2, 25,
  124644. _vq_lengthlist__16c2_s_p6_1,
  124645. 1, -533725184, 1611661312, 3, 0,
  124646. _vq_quantlist__16c2_s_p6_1,
  124647. NULL,
  124648. &_vq_auxt__16c2_s_p6_1,
  124649. NULL,
  124650. 0
  124651. };
  124652. static long _vq_quantlist__16c2_s_p7_0[] = {
  124653. 6,
  124654. 5,
  124655. 7,
  124656. 4,
  124657. 8,
  124658. 3,
  124659. 9,
  124660. 2,
  124661. 10,
  124662. 1,
  124663. 11,
  124664. 0,
  124665. 12,
  124666. };
  124667. static long _vq_lengthlist__16c2_s_p7_0[] = {
  124668. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124669. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  124670. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  124671. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  124672. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  124673. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  124674. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  124675. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  124676. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  124677. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  124678. 18,13,14,13,13,14,13,15,14,
  124679. };
  124680. static float _vq_quantthresh__16c2_s_p7_0[] = {
  124681. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  124682. 27.5, 38.5, 49.5, 60.5,
  124683. };
  124684. static long _vq_quantmap__16c2_s_p7_0[] = {
  124685. 11, 9, 7, 5, 3, 1, 0, 2,
  124686. 4, 6, 8, 10, 12,
  124687. };
  124688. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  124689. _vq_quantthresh__16c2_s_p7_0,
  124690. _vq_quantmap__16c2_s_p7_0,
  124691. 13,
  124692. 13
  124693. };
  124694. static static_codebook _16c2_s_p7_0 = {
  124695. 2, 169,
  124696. _vq_lengthlist__16c2_s_p7_0,
  124697. 1, -523206656, 1618345984, 4, 0,
  124698. _vq_quantlist__16c2_s_p7_0,
  124699. NULL,
  124700. &_vq_auxt__16c2_s_p7_0,
  124701. NULL,
  124702. 0
  124703. };
  124704. static long _vq_quantlist__16c2_s_p7_1[] = {
  124705. 5,
  124706. 4,
  124707. 6,
  124708. 3,
  124709. 7,
  124710. 2,
  124711. 8,
  124712. 1,
  124713. 9,
  124714. 0,
  124715. 10,
  124716. };
  124717. static long _vq_lengthlist__16c2_s_p7_1[] = {
  124718. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  124719. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  124720. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  124721. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124722. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  124723. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  124724. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  124725. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124726. };
  124727. static float _vq_quantthresh__16c2_s_p7_1[] = {
  124728. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124729. 3.5, 4.5,
  124730. };
  124731. static long _vq_quantmap__16c2_s_p7_1[] = {
  124732. 9, 7, 5, 3, 1, 0, 2, 4,
  124733. 6, 8, 10,
  124734. };
  124735. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  124736. _vq_quantthresh__16c2_s_p7_1,
  124737. _vq_quantmap__16c2_s_p7_1,
  124738. 11,
  124739. 11
  124740. };
  124741. static static_codebook _16c2_s_p7_1 = {
  124742. 2, 121,
  124743. _vq_lengthlist__16c2_s_p7_1,
  124744. 1, -531365888, 1611661312, 4, 0,
  124745. _vq_quantlist__16c2_s_p7_1,
  124746. NULL,
  124747. &_vq_auxt__16c2_s_p7_1,
  124748. NULL,
  124749. 0
  124750. };
  124751. static long _vq_quantlist__16c2_s_p8_0[] = {
  124752. 7,
  124753. 6,
  124754. 8,
  124755. 5,
  124756. 9,
  124757. 4,
  124758. 10,
  124759. 3,
  124760. 11,
  124761. 2,
  124762. 12,
  124763. 1,
  124764. 13,
  124765. 0,
  124766. 14,
  124767. };
  124768. static long _vq_lengthlist__16c2_s_p8_0[] = {
  124769. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  124770. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  124771. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  124772. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  124773. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  124774. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  124775. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  124776. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  124777. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  124778. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  124779. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  124780. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  124781. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  124782. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  124783. 13,
  124784. };
  124785. static float _vq_quantthresh__16c2_s_p8_0[] = {
  124786. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124787. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124788. };
  124789. static long _vq_quantmap__16c2_s_p8_0[] = {
  124790. 13, 11, 9, 7, 5, 3, 1, 0,
  124791. 2, 4, 6, 8, 10, 12, 14,
  124792. };
  124793. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  124794. _vq_quantthresh__16c2_s_p8_0,
  124795. _vq_quantmap__16c2_s_p8_0,
  124796. 15,
  124797. 15
  124798. };
  124799. static static_codebook _16c2_s_p8_0 = {
  124800. 2, 225,
  124801. _vq_lengthlist__16c2_s_p8_0,
  124802. 1, -520986624, 1620377600, 4, 0,
  124803. _vq_quantlist__16c2_s_p8_0,
  124804. NULL,
  124805. &_vq_auxt__16c2_s_p8_0,
  124806. NULL,
  124807. 0
  124808. };
  124809. static long _vq_quantlist__16c2_s_p8_1[] = {
  124810. 10,
  124811. 9,
  124812. 11,
  124813. 8,
  124814. 12,
  124815. 7,
  124816. 13,
  124817. 6,
  124818. 14,
  124819. 5,
  124820. 15,
  124821. 4,
  124822. 16,
  124823. 3,
  124824. 17,
  124825. 2,
  124826. 18,
  124827. 1,
  124828. 19,
  124829. 0,
  124830. 20,
  124831. };
  124832. static long _vq_lengthlist__16c2_s_p8_1[] = {
  124833. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  124834. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  124835. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  124836. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  124837. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  124838. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  124839. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  124840. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  124841. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  124842. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  124843. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  124844. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  124845. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  124846. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  124847. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  124848. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  124849. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  124850. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  124851. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  124852. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  124853. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  124854. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  124855. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  124856. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  124857. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  124858. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  124859. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  124860. 10,11,10,10,10,10,10,10,10,
  124861. };
  124862. static float _vq_quantthresh__16c2_s_p8_1[] = {
  124863. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124864. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124865. 6.5, 7.5, 8.5, 9.5,
  124866. };
  124867. static long _vq_quantmap__16c2_s_p8_1[] = {
  124868. 19, 17, 15, 13, 11, 9, 7, 5,
  124869. 3, 1, 0, 2, 4, 6, 8, 10,
  124870. 12, 14, 16, 18, 20,
  124871. };
  124872. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  124873. _vq_quantthresh__16c2_s_p8_1,
  124874. _vq_quantmap__16c2_s_p8_1,
  124875. 21,
  124876. 21
  124877. };
  124878. static static_codebook _16c2_s_p8_1 = {
  124879. 2, 441,
  124880. _vq_lengthlist__16c2_s_p8_1,
  124881. 1, -529268736, 1611661312, 5, 0,
  124882. _vq_quantlist__16c2_s_p8_1,
  124883. NULL,
  124884. &_vq_auxt__16c2_s_p8_1,
  124885. NULL,
  124886. 0
  124887. };
  124888. static long _vq_quantlist__16c2_s_p9_0[] = {
  124889. 6,
  124890. 5,
  124891. 7,
  124892. 4,
  124893. 8,
  124894. 3,
  124895. 9,
  124896. 2,
  124897. 10,
  124898. 1,
  124899. 11,
  124900. 0,
  124901. 12,
  124902. };
  124903. static long _vq_lengthlist__16c2_s_p9_0[] = {
  124904. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124905. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124906. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124907. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124908. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124909. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124910. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124911. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124912. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124913. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124914. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124915. };
  124916. static float _vq_quantthresh__16c2_s_p9_0[] = {
  124917. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  124918. 2327.5, 3258.5, 4189.5, 5120.5,
  124919. };
  124920. static long _vq_quantmap__16c2_s_p9_0[] = {
  124921. 11, 9, 7, 5, 3, 1, 0, 2,
  124922. 4, 6, 8, 10, 12,
  124923. };
  124924. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  124925. _vq_quantthresh__16c2_s_p9_0,
  124926. _vq_quantmap__16c2_s_p9_0,
  124927. 13,
  124928. 13
  124929. };
  124930. static static_codebook _16c2_s_p9_0 = {
  124931. 2, 169,
  124932. _vq_lengthlist__16c2_s_p9_0,
  124933. 1, -510275072, 1631393792, 4, 0,
  124934. _vq_quantlist__16c2_s_p9_0,
  124935. NULL,
  124936. &_vq_auxt__16c2_s_p9_0,
  124937. NULL,
  124938. 0
  124939. };
  124940. static long _vq_quantlist__16c2_s_p9_1[] = {
  124941. 8,
  124942. 7,
  124943. 9,
  124944. 6,
  124945. 10,
  124946. 5,
  124947. 11,
  124948. 4,
  124949. 12,
  124950. 3,
  124951. 13,
  124952. 2,
  124953. 14,
  124954. 1,
  124955. 15,
  124956. 0,
  124957. 16,
  124958. };
  124959. static long _vq_lengthlist__16c2_s_p9_1[] = {
  124960. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  124961. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  124962. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  124963. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  124964. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  124965. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  124966. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  124967. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  124968. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  124969. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  124970. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124971. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124972. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124973. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124974. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124975. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  124976. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  124977. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124978. 10,
  124979. };
  124980. static float _vq_quantthresh__16c2_s_p9_1[] = {
  124981. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  124982. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  124983. };
  124984. static long _vq_quantmap__16c2_s_p9_1[] = {
  124985. 15, 13, 11, 9, 7, 5, 3, 1,
  124986. 0, 2, 4, 6, 8, 10, 12, 14,
  124987. 16,
  124988. };
  124989. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  124990. _vq_quantthresh__16c2_s_p9_1,
  124991. _vq_quantmap__16c2_s_p9_1,
  124992. 17,
  124993. 17
  124994. };
  124995. static static_codebook _16c2_s_p9_1 = {
  124996. 2, 289,
  124997. _vq_lengthlist__16c2_s_p9_1,
  124998. 1, -518488064, 1622704128, 5, 0,
  124999. _vq_quantlist__16c2_s_p9_1,
  125000. NULL,
  125001. &_vq_auxt__16c2_s_p9_1,
  125002. NULL,
  125003. 0
  125004. };
  125005. static long _vq_quantlist__16c2_s_p9_2[] = {
  125006. 13,
  125007. 12,
  125008. 14,
  125009. 11,
  125010. 15,
  125011. 10,
  125012. 16,
  125013. 9,
  125014. 17,
  125015. 8,
  125016. 18,
  125017. 7,
  125018. 19,
  125019. 6,
  125020. 20,
  125021. 5,
  125022. 21,
  125023. 4,
  125024. 22,
  125025. 3,
  125026. 23,
  125027. 2,
  125028. 24,
  125029. 1,
  125030. 25,
  125031. 0,
  125032. 26,
  125033. };
  125034. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125035. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125036. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125037. };
  125038. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125039. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125040. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125041. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125042. 11.5, 12.5,
  125043. };
  125044. static long _vq_quantmap__16c2_s_p9_2[] = {
  125045. 25, 23, 21, 19, 17, 15, 13, 11,
  125046. 9, 7, 5, 3, 1, 0, 2, 4,
  125047. 6, 8, 10, 12, 14, 16, 18, 20,
  125048. 22, 24, 26,
  125049. };
  125050. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125051. _vq_quantthresh__16c2_s_p9_2,
  125052. _vq_quantmap__16c2_s_p9_2,
  125053. 27,
  125054. 27
  125055. };
  125056. static static_codebook _16c2_s_p9_2 = {
  125057. 1, 27,
  125058. _vq_lengthlist__16c2_s_p9_2,
  125059. 1, -528875520, 1611661312, 5, 0,
  125060. _vq_quantlist__16c2_s_p9_2,
  125061. NULL,
  125062. &_vq_auxt__16c2_s_p9_2,
  125063. NULL,
  125064. 0
  125065. };
  125066. static long _huff_lengthlist__16c2_s_short[] = {
  125067. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125068. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125069. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125070. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125071. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125072. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125073. 15,12,14,14,
  125074. };
  125075. static static_codebook _huff_book__16c2_s_short = {
  125076. 2, 100,
  125077. _huff_lengthlist__16c2_s_short,
  125078. 0, 0, 0, 0, 0,
  125079. NULL,
  125080. NULL,
  125081. NULL,
  125082. NULL,
  125083. 0
  125084. };
  125085. static long _vq_quantlist__8c0_s_p1_0[] = {
  125086. 1,
  125087. 0,
  125088. 2,
  125089. };
  125090. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125091. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125092. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125097. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125102. 0, 0, 0, 0, 7, 9, 8, 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, 5, 8, 8, 0, 0, 0, 0,
  125137. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  125142. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 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, 7, 9,10, 0, 0,
  125147. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125183. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125188. 0, 0, 0, 0, 0, 9,10,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125193. 0, 0, 0, 0, 0, 0, 8,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125501. 0,
  125502. };
  125503. static float _vq_quantthresh__8c0_s_p1_0[] = {
  125504. -0.5, 0.5,
  125505. };
  125506. static long _vq_quantmap__8c0_s_p1_0[] = {
  125507. 1, 0, 2,
  125508. };
  125509. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  125510. _vq_quantthresh__8c0_s_p1_0,
  125511. _vq_quantmap__8c0_s_p1_0,
  125512. 3,
  125513. 3
  125514. };
  125515. static static_codebook _8c0_s_p1_0 = {
  125516. 8, 6561,
  125517. _vq_lengthlist__8c0_s_p1_0,
  125518. 1, -535822336, 1611661312, 2, 0,
  125519. _vq_quantlist__8c0_s_p1_0,
  125520. NULL,
  125521. &_vq_auxt__8c0_s_p1_0,
  125522. NULL,
  125523. 0
  125524. };
  125525. static long _vq_quantlist__8c0_s_p2_0[] = {
  125526. 2,
  125527. 1,
  125528. 3,
  125529. 0,
  125530. 4,
  125531. };
  125532. static long _vq_lengthlist__8c0_s_p2_0[] = {
  125533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125572. 0,
  125573. };
  125574. static float _vq_quantthresh__8c0_s_p2_0[] = {
  125575. -1.5, -0.5, 0.5, 1.5,
  125576. };
  125577. static long _vq_quantmap__8c0_s_p2_0[] = {
  125578. 3, 1, 0, 2, 4,
  125579. };
  125580. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  125581. _vq_quantthresh__8c0_s_p2_0,
  125582. _vq_quantmap__8c0_s_p2_0,
  125583. 5,
  125584. 5
  125585. };
  125586. static static_codebook _8c0_s_p2_0 = {
  125587. 4, 625,
  125588. _vq_lengthlist__8c0_s_p2_0,
  125589. 1, -533725184, 1611661312, 3, 0,
  125590. _vq_quantlist__8c0_s_p2_0,
  125591. NULL,
  125592. &_vq_auxt__8c0_s_p2_0,
  125593. NULL,
  125594. 0
  125595. };
  125596. static long _vq_quantlist__8c0_s_p3_0[] = {
  125597. 2,
  125598. 1,
  125599. 3,
  125600. 0,
  125601. 4,
  125602. };
  125603. static long _vq_lengthlist__8c0_s_p3_0[] = {
  125604. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  125606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125607. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  125609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125610. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  125611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125643. 0,
  125644. };
  125645. static float _vq_quantthresh__8c0_s_p3_0[] = {
  125646. -1.5, -0.5, 0.5, 1.5,
  125647. };
  125648. static long _vq_quantmap__8c0_s_p3_0[] = {
  125649. 3, 1, 0, 2, 4,
  125650. };
  125651. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  125652. _vq_quantthresh__8c0_s_p3_0,
  125653. _vq_quantmap__8c0_s_p3_0,
  125654. 5,
  125655. 5
  125656. };
  125657. static static_codebook _8c0_s_p3_0 = {
  125658. 4, 625,
  125659. _vq_lengthlist__8c0_s_p3_0,
  125660. 1, -533725184, 1611661312, 3, 0,
  125661. _vq_quantlist__8c0_s_p3_0,
  125662. NULL,
  125663. &_vq_auxt__8c0_s_p3_0,
  125664. NULL,
  125665. 0
  125666. };
  125667. static long _vq_quantlist__8c0_s_p4_0[] = {
  125668. 4,
  125669. 3,
  125670. 5,
  125671. 2,
  125672. 6,
  125673. 1,
  125674. 7,
  125675. 0,
  125676. 8,
  125677. };
  125678. static long _vq_lengthlist__8c0_s_p4_0[] = {
  125679. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  125680. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  125681. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  125682. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  125683. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125684. 0,
  125685. };
  125686. static float _vq_quantthresh__8c0_s_p4_0[] = {
  125687. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125688. };
  125689. static long _vq_quantmap__8c0_s_p4_0[] = {
  125690. 7, 5, 3, 1, 0, 2, 4, 6,
  125691. 8,
  125692. };
  125693. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  125694. _vq_quantthresh__8c0_s_p4_0,
  125695. _vq_quantmap__8c0_s_p4_0,
  125696. 9,
  125697. 9
  125698. };
  125699. static static_codebook _8c0_s_p4_0 = {
  125700. 2, 81,
  125701. _vq_lengthlist__8c0_s_p4_0,
  125702. 1, -531628032, 1611661312, 4, 0,
  125703. _vq_quantlist__8c0_s_p4_0,
  125704. NULL,
  125705. &_vq_auxt__8c0_s_p4_0,
  125706. NULL,
  125707. 0
  125708. };
  125709. static long _vq_quantlist__8c0_s_p5_0[] = {
  125710. 4,
  125711. 3,
  125712. 5,
  125713. 2,
  125714. 6,
  125715. 1,
  125716. 7,
  125717. 0,
  125718. 8,
  125719. };
  125720. static long _vq_lengthlist__8c0_s_p5_0[] = {
  125721. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  125722. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  125723. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  125724. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  125725. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  125726. 10,
  125727. };
  125728. static float _vq_quantthresh__8c0_s_p5_0[] = {
  125729. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125730. };
  125731. static long _vq_quantmap__8c0_s_p5_0[] = {
  125732. 7, 5, 3, 1, 0, 2, 4, 6,
  125733. 8,
  125734. };
  125735. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  125736. _vq_quantthresh__8c0_s_p5_0,
  125737. _vq_quantmap__8c0_s_p5_0,
  125738. 9,
  125739. 9
  125740. };
  125741. static static_codebook _8c0_s_p5_0 = {
  125742. 2, 81,
  125743. _vq_lengthlist__8c0_s_p5_0,
  125744. 1, -531628032, 1611661312, 4, 0,
  125745. _vq_quantlist__8c0_s_p5_0,
  125746. NULL,
  125747. &_vq_auxt__8c0_s_p5_0,
  125748. NULL,
  125749. 0
  125750. };
  125751. static long _vq_quantlist__8c0_s_p6_0[] = {
  125752. 8,
  125753. 7,
  125754. 9,
  125755. 6,
  125756. 10,
  125757. 5,
  125758. 11,
  125759. 4,
  125760. 12,
  125761. 3,
  125762. 13,
  125763. 2,
  125764. 14,
  125765. 1,
  125766. 15,
  125767. 0,
  125768. 16,
  125769. };
  125770. static long _vq_lengthlist__8c0_s_p6_0[] = {
  125771. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  125772. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  125773. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  125774. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  125775. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  125776. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  125777. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  125778. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  125779. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  125780. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  125781. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  125782. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  125783. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  125784. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  125785. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  125786. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  125787. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  125788. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  125789. 14,
  125790. };
  125791. static float _vq_quantthresh__8c0_s_p6_0[] = {
  125792. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125793. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125794. };
  125795. static long _vq_quantmap__8c0_s_p6_0[] = {
  125796. 15, 13, 11, 9, 7, 5, 3, 1,
  125797. 0, 2, 4, 6, 8, 10, 12, 14,
  125798. 16,
  125799. };
  125800. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  125801. _vq_quantthresh__8c0_s_p6_0,
  125802. _vq_quantmap__8c0_s_p6_0,
  125803. 17,
  125804. 17
  125805. };
  125806. static static_codebook _8c0_s_p6_0 = {
  125807. 2, 289,
  125808. _vq_lengthlist__8c0_s_p6_0,
  125809. 1, -529530880, 1611661312, 5, 0,
  125810. _vq_quantlist__8c0_s_p6_0,
  125811. NULL,
  125812. &_vq_auxt__8c0_s_p6_0,
  125813. NULL,
  125814. 0
  125815. };
  125816. static long _vq_quantlist__8c0_s_p7_0[] = {
  125817. 1,
  125818. 0,
  125819. 2,
  125820. };
  125821. static long _vq_lengthlist__8c0_s_p7_0[] = {
  125822. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  125823. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  125824. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  125825. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  125826. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  125827. 10,
  125828. };
  125829. static float _vq_quantthresh__8c0_s_p7_0[] = {
  125830. -5.5, 5.5,
  125831. };
  125832. static long _vq_quantmap__8c0_s_p7_0[] = {
  125833. 1, 0, 2,
  125834. };
  125835. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  125836. _vq_quantthresh__8c0_s_p7_0,
  125837. _vq_quantmap__8c0_s_p7_0,
  125838. 3,
  125839. 3
  125840. };
  125841. static static_codebook _8c0_s_p7_0 = {
  125842. 4, 81,
  125843. _vq_lengthlist__8c0_s_p7_0,
  125844. 1, -529137664, 1618345984, 2, 0,
  125845. _vq_quantlist__8c0_s_p7_0,
  125846. NULL,
  125847. &_vq_auxt__8c0_s_p7_0,
  125848. NULL,
  125849. 0
  125850. };
  125851. static long _vq_quantlist__8c0_s_p7_1[] = {
  125852. 5,
  125853. 4,
  125854. 6,
  125855. 3,
  125856. 7,
  125857. 2,
  125858. 8,
  125859. 1,
  125860. 9,
  125861. 0,
  125862. 10,
  125863. };
  125864. static long _vq_lengthlist__8c0_s_p7_1[] = {
  125865. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  125866. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  125867. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  125868. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  125869. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  125870. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  125871. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  125872. 10,10,10, 9, 9, 9,10,10,10,
  125873. };
  125874. static float _vq_quantthresh__8c0_s_p7_1[] = {
  125875. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125876. 3.5, 4.5,
  125877. };
  125878. static long _vq_quantmap__8c0_s_p7_1[] = {
  125879. 9, 7, 5, 3, 1, 0, 2, 4,
  125880. 6, 8, 10,
  125881. };
  125882. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  125883. _vq_quantthresh__8c0_s_p7_1,
  125884. _vq_quantmap__8c0_s_p7_1,
  125885. 11,
  125886. 11
  125887. };
  125888. static static_codebook _8c0_s_p7_1 = {
  125889. 2, 121,
  125890. _vq_lengthlist__8c0_s_p7_1,
  125891. 1, -531365888, 1611661312, 4, 0,
  125892. _vq_quantlist__8c0_s_p7_1,
  125893. NULL,
  125894. &_vq_auxt__8c0_s_p7_1,
  125895. NULL,
  125896. 0
  125897. };
  125898. static long _vq_quantlist__8c0_s_p8_0[] = {
  125899. 6,
  125900. 5,
  125901. 7,
  125902. 4,
  125903. 8,
  125904. 3,
  125905. 9,
  125906. 2,
  125907. 10,
  125908. 1,
  125909. 11,
  125910. 0,
  125911. 12,
  125912. };
  125913. static long _vq_lengthlist__8c0_s_p8_0[] = {
  125914. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  125915. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  125916. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  125917. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  125918. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  125919. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  125920. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  125921. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  125922. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  125923. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  125924. 0, 0,13,13,11,13,13,11,12,
  125925. };
  125926. static float _vq_quantthresh__8c0_s_p8_0[] = {
  125927. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125928. 12.5, 17.5, 22.5, 27.5,
  125929. };
  125930. static long _vq_quantmap__8c0_s_p8_0[] = {
  125931. 11, 9, 7, 5, 3, 1, 0, 2,
  125932. 4, 6, 8, 10, 12,
  125933. };
  125934. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  125935. _vq_quantthresh__8c0_s_p8_0,
  125936. _vq_quantmap__8c0_s_p8_0,
  125937. 13,
  125938. 13
  125939. };
  125940. static static_codebook _8c0_s_p8_0 = {
  125941. 2, 169,
  125942. _vq_lengthlist__8c0_s_p8_0,
  125943. 1, -526516224, 1616117760, 4, 0,
  125944. _vq_quantlist__8c0_s_p8_0,
  125945. NULL,
  125946. &_vq_auxt__8c0_s_p8_0,
  125947. NULL,
  125948. 0
  125949. };
  125950. static long _vq_quantlist__8c0_s_p8_1[] = {
  125951. 2,
  125952. 1,
  125953. 3,
  125954. 0,
  125955. 4,
  125956. };
  125957. static long _vq_lengthlist__8c0_s_p8_1[] = {
  125958. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  125959. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  125960. };
  125961. static float _vq_quantthresh__8c0_s_p8_1[] = {
  125962. -1.5, -0.5, 0.5, 1.5,
  125963. };
  125964. static long _vq_quantmap__8c0_s_p8_1[] = {
  125965. 3, 1, 0, 2, 4,
  125966. };
  125967. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  125968. _vq_quantthresh__8c0_s_p8_1,
  125969. _vq_quantmap__8c0_s_p8_1,
  125970. 5,
  125971. 5
  125972. };
  125973. static static_codebook _8c0_s_p8_1 = {
  125974. 2, 25,
  125975. _vq_lengthlist__8c0_s_p8_1,
  125976. 1, -533725184, 1611661312, 3, 0,
  125977. _vq_quantlist__8c0_s_p8_1,
  125978. NULL,
  125979. &_vq_auxt__8c0_s_p8_1,
  125980. NULL,
  125981. 0
  125982. };
  125983. static long _vq_quantlist__8c0_s_p9_0[] = {
  125984. 1,
  125985. 0,
  125986. 2,
  125987. };
  125988. static long _vq_lengthlist__8c0_s_p9_0[] = {
  125989. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125990. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125991. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125992. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125993. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125994. 7,
  125995. };
  125996. static float _vq_quantthresh__8c0_s_p9_0[] = {
  125997. -157.5, 157.5,
  125998. };
  125999. static long _vq_quantmap__8c0_s_p9_0[] = {
  126000. 1, 0, 2,
  126001. };
  126002. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126003. _vq_quantthresh__8c0_s_p9_0,
  126004. _vq_quantmap__8c0_s_p9_0,
  126005. 3,
  126006. 3
  126007. };
  126008. static static_codebook _8c0_s_p9_0 = {
  126009. 4, 81,
  126010. _vq_lengthlist__8c0_s_p9_0,
  126011. 1, -518803456, 1628680192, 2, 0,
  126012. _vq_quantlist__8c0_s_p9_0,
  126013. NULL,
  126014. &_vq_auxt__8c0_s_p9_0,
  126015. NULL,
  126016. 0
  126017. };
  126018. static long _vq_quantlist__8c0_s_p9_1[] = {
  126019. 7,
  126020. 6,
  126021. 8,
  126022. 5,
  126023. 9,
  126024. 4,
  126025. 10,
  126026. 3,
  126027. 11,
  126028. 2,
  126029. 12,
  126030. 1,
  126031. 13,
  126032. 0,
  126033. 14,
  126034. };
  126035. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126036. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126037. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126038. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126039. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126040. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126041. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126042. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126043. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126044. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126045. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126046. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126047. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126048. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126049. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126050. 11,
  126051. };
  126052. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126053. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126054. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126055. };
  126056. static long _vq_quantmap__8c0_s_p9_1[] = {
  126057. 13, 11, 9, 7, 5, 3, 1, 0,
  126058. 2, 4, 6, 8, 10, 12, 14,
  126059. };
  126060. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126061. _vq_quantthresh__8c0_s_p9_1,
  126062. _vq_quantmap__8c0_s_p9_1,
  126063. 15,
  126064. 15
  126065. };
  126066. static static_codebook _8c0_s_p9_1 = {
  126067. 2, 225,
  126068. _vq_lengthlist__8c0_s_p9_1,
  126069. 1, -520986624, 1620377600, 4, 0,
  126070. _vq_quantlist__8c0_s_p9_1,
  126071. NULL,
  126072. &_vq_auxt__8c0_s_p9_1,
  126073. NULL,
  126074. 0
  126075. };
  126076. static long _vq_quantlist__8c0_s_p9_2[] = {
  126077. 10,
  126078. 9,
  126079. 11,
  126080. 8,
  126081. 12,
  126082. 7,
  126083. 13,
  126084. 6,
  126085. 14,
  126086. 5,
  126087. 15,
  126088. 4,
  126089. 16,
  126090. 3,
  126091. 17,
  126092. 2,
  126093. 18,
  126094. 1,
  126095. 19,
  126096. 0,
  126097. 20,
  126098. };
  126099. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126100. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126101. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126102. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126103. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126104. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126105. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126106. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126107. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126108. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126109. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126110. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126111. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126112. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126113. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126114. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126115. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126116. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126117. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126118. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126119. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126120. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126121. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126122. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126123. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126124. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126125. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126126. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126127. 10,11, 9,11,10, 9,10, 9,10,
  126128. };
  126129. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126130. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126131. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126132. 6.5, 7.5, 8.5, 9.5,
  126133. };
  126134. static long _vq_quantmap__8c0_s_p9_2[] = {
  126135. 19, 17, 15, 13, 11, 9, 7, 5,
  126136. 3, 1, 0, 2, 4, 6, 8, 10,
  126137. 12, 14, 16, 18, 20,
  126138. };
  126139. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126140. _vq_quantthresh__8c0_s_p9_2,
  126141. _vq_quantmap__8c0_s_p9_2,
  126142. 21,
  126143. 21
  126144. };
  126145. static static_codebook _8c0_s_p9_2 = {
  126146. 2, 441,
  126147. _vq_lengthlist__8c0_s_p9_2,
  126148. 1, -529268736, 1611661312, 5, 0,
  126149. _vq_quantlist__8c0_s_p9_2,
  126150. NULL,
  126151. &_vq_auxt__8c0_s_p9_2,
  126152. NULL,
  126153. 0
  126154. };
  126155. static long _huff_lengthlist__8c0_s_single[] = {
  126156. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126157. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126158. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126159. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126160. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126161. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126162. 17,16,17,17,
  126163. };
  126164. static static_codebook _huff_book__8c0_s_single = {
  126165. 2, 100,
  126166. _huff_lengthlist__8c0_s_single,
  126167. 0, 0, 0, 0, 0,
  126168. NULL,
  126169. NULL,
  126170. NULL,
  126171. NULL,
  126172. 0
  126173. };
  126174. static long _vq_quantlist__8c1_s_p1_0[] = {
  126175. 1,
  126176. 0,
  126177. 2,
  126178. };
  126179. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126180. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126181. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126186. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126191. 0, 0, 0, 0, 7, 9, 8, 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, 5, 8, 8, 0, 0, 0, 0,
  126226. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  126231. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  126236. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126272. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126277. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126282. 0, 0, 0, 0, 0, 0, 8,10, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126408. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126416. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126590. 0,
  126591. };
  126592. static float _vq_quantthresh__8c1_s_p1_0[] = {
  126593. -0.5, 0.5,
  126594. };
  126595. static long _vq_quantmap__8c1_s_p1_0[] = {
  126596. 1, 0, 2,
  126597. };
  126598. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  126599. _vq_quantthresh__8c1_s_p1_0,
  126600. _vq_quantmap__8c1_s_p1_0,
  126601. 3,
  126602. 3
  126603. };
  126604. static static_codebook _8c1_s_p1_0 = {
  126605. 8, 6561,
  126606. _vq_lengthlist__8c1_s_p1_0,
  126607. 1, -535822336, 1611661312, 2, 0,
  126608. _vq_quantlist__8c1_s_p1_0,
  126609. NULL,
  126610. &_vq_auxt__8c1_s_p1_0,
  126611. NULL,
  126612. 0
  126613. };
  126614. static long _vq_quantlist__8c1_s_p2_0[] = {
  126615. 2,
  126616. 1,
  126617. 3,
  126618. 0,
  126619. 4,
  126620. };
  126621. static long _vq_lengthlist__8c1_s_p2_0[] = {
  126622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126661. 0,
  126662. };
  126663. static float _vq_quantthresh__8c1_s_p2_0[] = {
  126664. -1.5, -0.5, 0.5, 1.5,
  126665. };
  126666. static long _vq_quantmap__8c1_s_p2_0[] = {
  126667. 3, 1, 0, 2, 4,
  126668. };
  126669. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  126670. _vq_quantthresh__8c1_s_p2_0,
  126671. _vq_quantmap__8c1_s_p2_0,
  126672. 5,
  126673. 5
  126674. };
  126675. static static_codebook _8c1_s_p2_0 = {
  126676. 4, 625,
  126677. _vq_lengthlist__8c1_s_p2_0,
  126678. 1, -533725184, 1611661312, 3, 0,
  126679. _vq_quantlist__8c1_s_p2_0,
  126680. NULL,
  126681. &_vq_auxt__8c1_s_p2_0,
  126682. NULL,
  126683. 0
  126684. };
  126685. static long _vq_quantlist__8c1_s_p3_0[] = {
  126686. 2,
  126687. 1,
  126688. 3,
  126689. 0,
  126690. 4,
  126691. };
  126692. static long _vq_lengthlist__8c1_s_p3_0[] = {
  126693. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  126695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126696. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  126698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126699. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126732. 0,
  126733. };
  126734. static float _vq_quantthresh__8c1_s_p3_0[] = {
  126735. -1.5, -0.5, 0.5, 1.5,
  126736. };
  126737. static long _vq_quantmap__8c1_s_p3_0[] = {
  126738. 3, 1, 0, 2, 4,
  126739. };
  126740. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  126741. _vq_quantthresh__8c1_s_p3_0,
  126742. _vq_quantmap__8c1_s_p3_0,
  126743. 5,
  126744. 5
  126745. };
  126746. static static_codebook _8c1_s_p3_0 = {
  126747. 4, 625,
  126748. _vq_lengthlist__8c1_s_p3_0,
  126749. 1, -533725184, 1611661312, 3, 0,
  126750. _vq_quantlist__8c1_s_p3_0,
  126751. NULL,
  126752. &_vq_auxt__8c1_s_p3_0,
  126753. NULL,
  126754. 0
  126755. };
  126756. static long _vq_quantlist__8c1_s_p4_0[] = {
  126757. 4,
  126758. 3,
  126759. 5,
  126760. 2,
  126761. 6,
  126762. 1,
  126763. 7,
  126764. 0,
  126765. 8,
  126766. };
  126767. static long _vq_lengthlist__8c1_s_p4_0[] = {
  126768. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126769. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126770. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126771. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126772. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126773. 0,
  126774. };
  126775. static float _vq_quantthresh__8c1_s_p4_0[] = {
  126776. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126777. };
  126778. static long _vq_quantmap__8c1_s_p4_0[] = {
  126779. 7, 5, 3, 1, 0, 2, 4, 6,
  126780. 8,
  126781. };
  126782. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  126783. _vq_quantthresh__8c1_s_p4_0,
  126784. _vq_quantmap__8c1_s_p4_0,
  126785. 9,
  126786. 9
  126787. };
  126788. static static_codebook _8c1_s_p4_0 = {
  126789. 2, 81,
  126790. _vq_lengthlist__8c1_s_p4_0,
  126791. 1, -531628032, 1611661312, 4, 0,
  126792. _vq_quantlist__8c1_s_p4_0,
  126793. NULL,
  126794. &_vq_auxt__8c1_s_p4_0,
  126795. NULL,
  126796. 0
  126797. };
  126798. static long _vq_quantlist__8c1_s_p5_0[] = {
  126799. 4,
  126800. 3,
  126801. 5,
  126802. 2,
  126803. 6,
  126804. 1,
  126805. 7,
  126806. 0,
  126807. 8,
  126808. };
  126809. static long _vq_lengthlist__8c1_s_p5_0[] = {
  126810. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  126811. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  126812. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  126813. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  126814. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126815. 10,
  126816. };
  126817. static float _vq_quantthresh__8c1_s_p5_0[] = {
  126818. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126819. };
  126820. static long _vq_quantmap__8c1_s_p5_0[] = {
  126821. 7, 5, 3, 1, 0, 2, 4, 6,
  126822. 8,
  126823. };
  126824. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  126825. _vq_quantthresh__8c1_s_p5_0,
  126826. _vq_quantmap__8c1_s_p5_0,
  126827. 9,
  126828. 9
  126829. };
  126830. static static_codebook _8c1_s_p5_0 = {
  126831. 2, 81,
  126832. _vq_lengthlist__8c1_s_p5_0,
  126833. 1, -531628032, 1611661312, 4, 0,
  126834. _vq_quantlist__8c1_s_p5_0,
  126835. NULL,
  126836. &_vq_auxt__8c1_s_p5_0,
  126837. NULL,
  126838. 0
  126839. };
  126840. static long _vq_quantlist__8c1_s_p6_0[] = {
  126841. 8,
  126842. 7,
  126843. 9,
  126844. 6,
  126845. 10,
  126846. 5,
  126847. 11,
  126848. 4,
  126849. 12,
  126850. 3,
  126851. 13,
  126852. 2,
  126853. 14,
  126854. 1,
  126855. 15,
  126856. 0,
  126857. 16,
  126858. };
  126859. static long _vq_lengthlist__8c1_s_p6_0[] = {
  126860. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  126861. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126862. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126863. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  126864. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  126865. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  126866. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  126867. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  126868. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  126869. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126870. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  126871. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  126872. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  126873. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  126874. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  126875. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  126876. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  126877. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  126878. 14,
  126879. };
  126880. static float _vq_quantthresh__8c1_s_p6_0[] = {
  126881. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126882. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126883. };
  126884. static long _vq_quantmap__8c1_s_p6_0[] = {
  126885. 15, 13, 11, 9, 7, 5, 3, 1,
  126886. 0, 2, 4, 6, 8, 10, 12, 14,
  126887. 16,
  126888. };
  126889. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  126890. _vq_quantthresh__8c1_s_p6_0,
  126891. _vq_quantmap__8c1_s_p6_0,
  126892. 17,
  126893. 17
  126894. };
  126895. static static_codebook _8c1_s_p6_0 = {
  126896. 2, 289,
  126897. _vq_lengthlist__8c1_s_p6_0,
  126898. 1, -529530880, 1611661312, 5, 0,
  126899. _vq_quantlist__8c1_s_p6_0,
  126900. NULL,
  126901. &_vq_auxt__8c1_s_p6_0,
  126902. NULL,
  126903. 0
  126904. };
  126905. static long _vq_quantlist__8c1_s_p7_0[] = {
  126906. 1,
  126907. 0,
  126908. 2,
  126909. };
  126910. static long _vq_lengthlist__8c1_s_p7_0[] = {
  126911. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  126912. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  126913. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  126914. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  126915. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  126916. 9,
  126917. };
  126918. static float _vq_quantthresh__8c1_s_p7_0[] = {
  126919. -5.5, 5.5,
  126920. };
  126921. static long _vq_quantmap__8c1_s_p7_0[] = {
  126922. 1, 0, 2,
  126923. };
  126924. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  126925. _vq_quantthresh__8c1_s_p7_0,
  126926. _vq_quantmap__8c1_s_p7_0,
  126927. 3,
  126928. 3
  126929. };
  126930. static static_codebook _8c1_s_p7_0 = {
  126931. 4, 81,
  126932. _vq_lengthlist__8c1_s_p7_0,
  126933. 1, -529137664, 1618345984, 2, 0,
  126934. _vq_quantlist__8c1_s_p7_0,
  126935. NULL,
  126936. &_vq_auxt__8c1_s_p7_0,
  126937. NULL,
  126938. 0
  126939. };
  126940. static long _vq_quantlist__8c1_s_p7_1[] = {
  126941. 5,
  126942. 4,
  126943. 6,
  126944. 3,
  126945. 7,
  126946. 2,
  126947. 8,
  126948. 1,
  126949. 9,
  126950. 0,
  126951. 10,
  126952. };
  126953. static long _vq_lengthlist__8c1_s_p7_1[] = {
  126954. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  126955. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  126956. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  126957. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  126958. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  126959. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  126960. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  126961. 10,10,10, 8, 8, 8, 8, 8, 8,
  126962. };
  126963. static float _vq_quantthresh__8c1_s_p7_1[] = {
  126964. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126965. 3.5, 4.5,
  126966. };
  126967. static long _vq_quantmap__8c1_s_p7_1[] = {
  126968. 9, 7, 5, 3, 1, 0, 2, 4,
  126969. 6, 8, 10,
  126970. };
  126971. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  126972. _vq_quantthresh__8c1_s_p7_1,
  126973. _vq_quantmap__8c1_s_p7_1,
  126974. 11,
  126975. 11
  126976. };
  126977. static static_codebook _8c1_s_p7_1 = {
  126978. 2, 121,
  126979. _vq_lengthlist__8c1_s_p7_1,
  126980. 1, -531365888, 1611661312, 4, 0,
  126981. _vq_quantlist__8c1_s_p7_1,
  126982. NULL,
  126983. &_vq_auxt__8c1_s_p7_1,
  126984. NULL,
  126985. 0
  126986. };
  126987. static long _vq_quantlist__8c1_s_p8_0[] = {
  126988. 6,
  126989. 5,
  126990. 7,
  126991. 4,
  126992. 8,
  126993. 3,
  126994. 9,
  126995. 2,
  126996. 10,
  126997. 1,
  126998. 11,
  126999. 0,
  127000. 12,
  127001. };
  127002. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127003. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127004. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127005. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127006. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127007. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127008. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127009. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127010. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127011. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127012. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127013. 0,12,12,11,10,12,11,13,12,
  127014. };
  127015. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127016. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127017. 12.5, 17.5, 22.5, 27.5,
  127018. };
  127019. static long _vq_quantmap__8c1_s_p8_0[] = {
  127020. 11, 9, 7, 5, 3, 1, 0, 2,
  127021. 4, 6, 8, 10, 12,
  127022. };
  127023. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127024. _vq_quantthresh__8c1_s_p8_0,
  127025. _vq_quantmap__8c1_s_p8_0,
  127026. 13,
  127027. 13
  127028. };
  127029. static static_codebook _8c1_s_p8_0 = {
  127030. 2, 169,
  127031. _vq_lengthlist__8c1_s_p8_0,
  127032. 1, -526516224, 1616117760, 4, 0,
  127033. _vq_quantlist__8c1_s_p8_0,
  127034. NULL,
  127035. &_vq_auxt__8c1_s_p8_0,
  127036. NULL,
  127037. 0
  127038. };
  127039. static long _vq_quantlist__8c1_s_p8_1[] = {
  127040. 2,
  127041. 1,
  127042. 3,
  127043. 0,
  127044. 4,
  127045. };
  127046. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127047. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127048. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127049. };
  127050. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127051. -1.5, -0.5, 0.5, 1.5,
  127052. };
  127053. static long _vq_quantmap__8c1_s_p8_1[] = {
  127054. 3, 1, 0, 2, 4,
  127055. };
  127056. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127057. _vq_quantthresh__8c1_s_p8_1,
  127058. _vq_quantmap__8c1_s_p8_1,
  127059. 5,
  127060. 5
  127061. };
  127062. static static_codebook _8c1_s_p8_1 = {
  127063. 2, 25,
  127064. _vq_lengthlist__8c1_s_p8_1,
  127065. 1, -533725184, 1611661312, 3, 0,
  127066. _vq_quantlist__8c1_s_p8_1,
  127067. NULL,
  127068. &_vq_auxt__8c1_s_p8_1,
  127069. NULL,
  127070. 0
  127071. };
  127072. static long _vq_quantlist__8c1_s_p9_0[] = {
  127073. 6,
  127074. 5,
  127075. 7,
  127076. 4,
  127077. 8,
  127078. 3,
  127079. 9,
  127080. 2,
  127081. 10,
  127082. 1,
  127083. 11,
  127084. 0,
  127085. 12,
  127086. };
  127087. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127088. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127089. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127090. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127091. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127092. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127093. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127094. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127095. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127096. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127097. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127098. 10,10,10,10,10, 9, 9, 9, 9,
  127099. };
  127100. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127101. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127102. 787.5, 1102.5, 1417.5, 1732.5,
  127103. };
  127104. static long _vq_quantmap__8c1_s_p9_0[] = {
  127105. 11, 9, 7, 5, 3, 1, 0, 2,
  127106. 4, 6, 8, 10, 12,
  127107. };
  127108. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127109. _vq_quantthresh__8c1_s_p9_0,
  127110. _vq_quantmap__8c1_s_p9_0,
  127111. 13,
  127112. 13
  127113. };
  127114. static static_codebook _8c1_s_p9_0 = {
  127115. 2, 169,
  127116. _vq_lengthlist__8c1_s_p9_0,
  127117. 1, -513964032, 1628680192, 4, 0,
  127118. _vq_quantlist__8c1_s_p9_0,
  127119. NULL,
  127120. &_vq_auxt__8c1_s_p9_0,
  127121. NULL,
  127122. 0
  127123. };
  127124. static long _vq_quantlist__8c1_s_p9_1[] = {
  127125. 7,
  127126. 6,
  127127. 8,
  127128. 5,
  127129. 9,
  127130. 4,
  127131. 10,
  127132. 3,
  127133. 11,
  127134. 2,
  127135. 12,
  127136. 1,
  127137. 13,
  127138. 0,
  127139. 14,
  127140. };
  127141. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127142. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127143. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127144. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127145. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127146. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127147. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127148. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127149. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127150. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127151. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127152. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127153. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127154. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127155. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127156. 15,
  127157. };
  127158. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127159. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127160. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127161. };
  127162. static long _vq_quantmap__8c1_s_p9_1[] = {
  127163. 13, 11, 9, 7, 5, 3, 1, 0,
  127164. 2, 4, 6, 8, 10, 12, 14,
  127165. };
  127166. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127167. _vq_quantthresh__8c1_s_p9_1,
  127168. _vq_quantmap__8c1_s_p9_1,
  127169. 15,
  127170. 15
  127171. };
  127172. static static_codebook _8c1_s_p9_1 = {
  127173. 2, 225,
  127174. _vq_lengthlist__8c1_s_p9_1,
  127175. 1, -520986624, 1620377600, 4, 0,
  127176. _vq_quantlist__8c1_s_p9_1,
  127177. NULL,
  127178. &_vq_auxt__8c1_s_p9_1,
  127179. NULL,
  127180. 0
  127181. };
  127182. static long _vq_quantlist__8c1_s_p9_2[] = {
  127183. 10,
  127184. 9,
  127185. 11,
  127186. 8,
  127187. 12,
  127188. 7,
  127189. 13,
  127190. 6,
  127191. 14,
  127192. 5,
  127193. 15,
  127194. 4,
  127195. 16,
  127196. 3,
  127197. 17,
  127198. 2,
  127199. 18,
  127200. 1,
  127201. 19,
  127202. 0,
  127203. 20,
  127204. };
  127205. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127206. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127207. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127208. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127209. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127210. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127211. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127212. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127213. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127214. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127215. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127216. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127217. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127218. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127219. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127220. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127221. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127222. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127223. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127224. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127225. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127226. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127227. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127228. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127229. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127230. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127231. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127232. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127233. 10,10,10,10,10,10,10,10,10,
  127234. };
  127235. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127236. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127237. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127238. 6.5, 7.5, 8.5, 9.5,
  127239. };
  127240. static long _vq_quantmap__8c1_s_p9_2[] = {
  127241. 19, 17, 15, 13, 11, 9, 7, 5,
  127242. 3, 1, 0, 2, 4, 6, 8, 10,
  127243. 12, 14, 16, 18, 20,
  127244. };
  127245. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127246. _vq_quantthresh__8c1_s_p9_2,
  127247. _vq_quantmap__8c1_s_p9_2,
  127248. 21,
  127249. 21
  127250. };
  127251. static static_codebook _8c1_s_p9_2 = {
  127252. 2, 441,
  127253. _vq_lengthlist__8c1_s_p9_2,
  127254. 1, -529268736, 1611661312, 5, 0,
  127255. _vq_quantlist__8c1_s_p9_2,
  127256. NULL,
  127257. &_vq_auxt__8c1_s_p9_2,
  127258. NULL,
  127259. 0
  127260. };
  127261. static long _huff_lengthlist__8c1_s_single[] = {
  127262. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  127263. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  127264. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  127265. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  127266. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  127267. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  127268. 9, 7, 7, 8,
  127269. };
  127270. static static_codebook _huff_book__8c1_s_single = {
  127271. 2, 100,
  127272. _huff_lengthlist__8c1_s_single,
  127273. 0, 0, 0, 0, 0,
  127274. NULL,
  127275. NULL,
  127276. NULL,
  127277. NULL,
  127278. 0
  127279. };
  127280. static long _huff_lengthlist__44c2_s_long[] = {
  127281. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  127282. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  127283. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  127284. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  127285. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  127286. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  127287. 10, 8, 8, 9,
  127288. };
  127289. static static_codebook _huff_book__44c2_s_long = {
  127290. 2, 100,
  127291. _huff_lengthlist__44c2_s_long,
  127292. 0, 0, 0, 0, 0,
  127293. NULL,
  127294. NULL,
  127295. NULL,
  127296. NULL,
  127297. 0
  127298. };
  127299. static long _vq_quantlist__44c2_s_p1_0[] = {
  127300. 1,
  127301. 0,
  127302. 2,
  127303. };
  127304. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127305. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127306. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127311. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127316. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  127351. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  127356. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  127361. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127397. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127402. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127407. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127519. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127527. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127715. 0,
  127716. };
  127717. static float _vq_quantthresh__44c2_s_p1_0[] = {
  127718. -0.5, 0.5,
  127719. };
  127720. static long _vq_quantmap__44c2_s_p1_0[] = {
  127721. 1, 0, 2,
  127722. };
  127723. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  127724. _vq_quantthresh__44c2_s_p1_0,
  127725. _vq_quantmap__44c2_s_p1_0,
  127726. 3,
  127727. 3
  127728. };
  127729. static static_codebook _44c2_s_p1_0 = {
  127730. 8, 6561,
  127731. _vq_lengthlist__44c2_s_p1_0,
  127732. 1, -535822336, 1611661312, 2, 0,
  127733. _vq_quantlist__44c2_s_p1_0,
  127734. NULL,
  127735. &_vq_auxt__44c2_s_p1_0,
  127736. NULL,
  127737. 0
  127738. };
  127739. static long _vq_quantlist__44c2_s_p2_0[] = {
  127740. 2,
  127741. 1,
  127742. 3,
  127743. 0,
  127744. 4,
  127745. };
  127746. static long _vq_lengthlist__44c2_s_p2_0[] = {
  127747. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  127748. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  127749. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  127750. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  127751. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127756. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  127757. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  127758. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  127759. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127764. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  127765. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  127766. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  127767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127772. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  127773. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  127774. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  127775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127786. 0,
  127787. };
  127788. static float _vq_quantthresh__44c2_s_p2_0[] = {
  127789. -1.5, -0.5, 0.5, 1.5,
  127790. };
  127791. static long _vq_quantmap__44c2_s_p2_0[] = {
  127792. 3, 1, 0, 2, 4,
  127793. };
  127794. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  127795. _vq_quantthresh__44c2_s_p2_0,
  127796. _vq_quantmap__44c2_s_p2_0,
  127797. 5,
  127798. 5
  127799. };
  127800. static static_codebook _44c2_s_p2_0 = {
  127801. 4, 625,
  127802. _vq_lengthlist__44c2_s_p2_0,
  127803. 1, -533725184, 1611661312, 3, 0,
  127804. _vq_quantlist__44c2_s_p2_0,
  127805. NULL,
  127806. &_vq_auxt__44c2_s_p2_0,
  127807. NULL,
  127808. 0
  127809. };
  127810. static long _vq_quantlist__44c2_s_p3_0[] = {
  127811. 2,
  127812. 1,
  127813. 3,
  127814. 0,
  127815. 4,
  127816. };
  127817. static long _vq_lengthlist__44c2_s_p3_0[] = {
  127818. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127821. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  127823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127824. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127857. 0,
  127858. };
  127859. static float _vq_quantthresh__44c2_s_p3_0[] = {
  127860. -1.5, -0.5, 0.5, 1.5,
  127861. };
  127862. static long _vq_quantmap__44c2_s_p3_0[] = {
  127863. 3, 1, 0, 2, 4,
  127864. };
  127865. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  127866. _vq_quantthresh__44c2_s_p3_0,
  127867. _vq_quantmap__44c2_s_p3_0,
  127868. 5,
  127869. 5
  127870. };
  127871. static static_codebook _44c2_s_p3_0 = {
  127872. 4, 625,
  127873. _vq_lengthlist__44c2_s_p3_0,
  127874. 1, -533725184, 1611661312, 3, 0,
  127875. _vq_quantlist__44c2_s_p3_0,
  127876. NULL,
  127877. &_vq_auxt__44c2_s_p3_0,
  127878. NULL,
  127879. 0
  127880. };
  127881. static long _vq_quantlist__44c2_s_p4_0[] = {
  127882. 4,
  127883. 3,
  127884. 5,
  127885. 2,
  127886. 6,
  127887. 1,
  127888. 7,
  127889. 0,
  127890. 8,
  127891. };
  127892. static long _vq_lengthlist__44c2_s_p4_0[] = {
  127893. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  127894. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  127895. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  127896. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  127897. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127898. 0,
  127899. };
  127900. static float _vq_quantthresh__44c2_s_p4_0[] = {
  127901. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127902. };
  127903. static long _vq_quantmap__44c2_s_p4_0[] = {
  127904. 7, 5, 3, 1, 0, 2, 4, 6,
  127905. 8,
  127906. };
  127907. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  127908. _vq_quantthresh__44c2_s_p4_0,
  127909. _vq_quantmap__44c2_s_p4_0,
  127910. 9,
  127911. 9
  127912. };
  127913. static static_codebook _44c2_s_p4_0 = {
  127914. 2, 81,
  127915. _vq_lengthlist__44c2_s_p4_0,
  127916. 1, -531628032, 1611661312, 4, 0,
  127917. _vq_quantlist__44c2_s_p4_0,
  127918. NULL,
  127919. &_vq_auxt__44c2_s_p4_0,
  127920. NULL,
  127921. 0
  127922. };
  127923. static long _vq_quantlist__44c2_s_p5_0[] = {
  127924. 4,
  127925. 3,
  127926. 5,
  127927. 2,
  127928. 6,
  127929. 1,
  127930. 7,
  127931. 0,
  127932. 8,
  127933. };
  127934. static long _vq_lengthlist__44c2_s_p5_0[] = {
  127935. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  127936. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  127937. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  127938. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  127939. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  127940. 11,
  127941. };
  127942. static float _vq_quantthresh__44c2_s_p5_0[] = {
  127943. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127944. };
  127945. static long _vq_quantmap__44c2_s_p5_0[] = {
  127946. 7, 5, 3, 1, 0, 2, 4, 6,
  127947. 8,
  127948. };
  127949. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  127950. _vq_quantthresh__44c2_s_p5_0,
  127951. _vq_quantmap__44c2_s_p5_0,
  127952. 9,
  127953. 9
  127954. };
  127955. static static_codebook _44c2_s_p5_0 = {
  127956. 2, 81,
  127957. _vq_lengthlist__44c2_s_p5_0,
  127958. 1, -531628032, 1611661312, 4, 0,
  127959. _vq_quantlist__44c2_s_p5_0,
  127960. NULL,
  127961. &_vq_auxt__44c2_s_p5_0,
  127962. NULL,
  127963. 0
  127964. };
  127965. static long _vq_quantlist__44c2_s_p6_0[] = {
  127966. 8,
  127967. 7,
  127968. 9,
  127969. 6,
  127970. 10,
  127971. 5,
  127972. 11,
  127973. 4,
  127974. 12,
  127975. 3,
  127976. 13,
  127977. 2,
  127978. 14,
  127979. 1,
  127980. 15,
  127981. 0,
  127982. 16,
  127983. };
  127984. static long _vq_lengthlist__44c2_s_p6_0[] = {
  127985. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  127986. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127987. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  127988. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  127989. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  127990. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  127991. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  127992. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  127993. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  127994. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127995. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127996. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  127997. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127998. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127999. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128000. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128001. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128002. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128003. 14,
  128004. };
  128005. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128006. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128007. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128008. };
  128009. static long _vq_quantmap__44c2_s_p6_0[] = {
  128010. 15, 13, 11, 9, 7, 5, 3, 1,
  128011. 0, 2, 4, 6, 8, 10, 12, 14,
  128012. 16,
  128013. };
  128014. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128015. _vq_quantthresh__44c2_s_p6_0,
  128016. _vq_quantmap__44c2_s_p6_0,
  128017. 17,
  128018. 17
  128019. };
  128020. static static_codebook _44c2_s_p6_0 = {
  128021. 2, 289,
  128022. _vq_lengthlist__44c2_s_p6_0,
  128023. 1, -529530880, 1611661312, 5, 0,
  128024. _vq_quantlist__44c2_s_p6_0,
  128025. NULL,
  128026. &_vq_auxt__44c2_s_p6_0,
  128027. NULL,
  128028. 0
  128029. };
  128030. static long _vq_quantlist__44c2_s_p7_0[] = {
  128031. 1,
  128032. 0,
  128033. 2,
  128034. };
  128035. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128036. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128037. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128038. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128039. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128040. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128041. 11,
  128042. };
  128043. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128044. -5.5, 5.5,
  128045. };
  128046. static long _vq_quantmap__44c2_s_p7_0[] = {
  128047. 1, 0, 2,
  128048. };
  128049. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128050. _vq_quantthresh__44c2_s_p7_0,
  128051. _vq_quantmap__44c2_s_p7_0,
  128052. 3,
  128053. 3
  128054. };
  128055. static static_codebook _44c2_s_p7_0 = {
  128056. 4, 81,
  128057. _vq_lengthlist__44c2_s_p7_0,
  128058. 1, -529137664, 1618345984, 2, 0,
  128059. _vq_quantlist__44c2_s_p7_0,
  128060. NULL,
  128061. &_vq_auxt__44c2_s_p7_0,
  128062. NULL,
  128063. 0
  128064. };
  128065. static long _vq_quantlist__44c2_s_p7_1[] = {
  128066. 5,
  128067. 4,
  128068. 6,
  128069. 3,
  128070. 7,
  128071. 2,
  128072. 8,
  128073. 1,
  128074. 9,
  128075. 0,
  128076. 10,
  128077. };
  128078. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128079. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128080. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128081. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128082. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128083. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128084. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128085. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128086. 10,10,10, 8, 8, 8, 8, 8, 8,
  128087. };
  128088. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128089. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128090. 3.5, 4.5,
  128091. };
  128092. static long _vq_quantmap__44c2_s_p7_1[] = {
  128093. 9, 7, 5, 3, 1, 0, 2, 4,
  128094. 6, 8, 10,
  128095. };
  128096. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128097. _vq_quantthresh__44c2_s_p7_1,
  128098. _vq_quantmap__44c2_s_p7_1,
  128099. 11,
  128100. 11
  128101. };
  128102. static static_codebook _44c2_s_p7_1 = {
  128103. 2, 121,
  128104. _vq_lengthlist__44c2_s_p7_1,
  128105. 1, -531365888, 1611661312, 4, 0,
  128106. _vq_quantlist__44c2_s_p7_1,
  128107. NULL,
  128108. &_vq_auxt__44c2_s_p7_1,
  128109. NULL,
  128110. 0
  128111. };
  128112. static long _vq_quantlist__44c2_s_p8_0[] = {
  128113. 6,
  128114. 5,
  128115. 7,
  128116. 4,
  128117. 8,
  128118. 3,
  128119. 9,
  128120. 2,
  128121. 10,
  128122. 1,
  128123. 11,
  128124. 0,
  128125. 12,
  128126. };
  128127. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128128. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128129. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128130. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128131. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128132. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128133. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128134. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128135. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128136. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128137. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128138. 0,12,12,12,12,13,12,14,14,
  128139. };
  128140. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128141. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128142. 12.5, 17.5, 22.5, 27.5,
  128143. };
  128144. static long _vq_quantmap__44c2_s_p8_0[] = {
  128145. 11, 9, 7, 5, 3, 1, 0, 2,
  128146. 4, 6, 8, 10, 12,
  128147. };
  128148. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128149. _vq_quantthresh__44c2_s_p8_0,
  128150. _vq_quantmap__44c2_s_p8_0,
  128151. 13,
  128152. 13
  128153. };
  128154. static static_codebook _44c2_s_p8_0 = {
  128155. 2, 169,
  128156. _vq_lengthlist__44c2_s_p8_0,
  128157. 1, -526516224, 1616117760, 4, 0,
  128158. _vq_quantlist__44c2_s_p8_0,
  128159. NULL,
  128160. &_vq_auxt__44c2_s_p8_0,
  128161. NULL,
  128162. 0
  128163. };
  128164. static long _vq_quantlist__44c2_s_p8_1[] = {
  128165. 2,
  128166. 1,
  128167. 3,
  128168. 0,
  128169. 4,
  128170. };
  128171. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128172. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128173. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128174. };
  128175. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128176. -1.5, -0.5, 0.5, 1.5,
  128177. };
  128178. static long _vq_quantmap__44c2_s_p8_1[] = {
  128179. 3, 1, 0, 2, 4,
  128180. };
  128181. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128182. _vq_quantthresh__44c2_s_p8_1,
  128183. _vq_quantmap__44c2_s_p8_1,
  128184. 5,
  128185. 5
  128186. };
  128187. static static_codebook _44c2_s_p8_1 = {
  128188. 2, 25,
  128189. _vq_lengthlist__44c2_s_p8_1,
  128190. 1, -533725184, 1611661312, 3, 0,
  128191. _vq_quantlist__44c2_s_p8_1,
  128192. NULL,
  128193. &_vq_auxt__44c2_s_p8_1,
  128194. NULL,
  128195. 0
  128196. };
  128197. static long _vq_quantlist__44c2_s_p9_0[] = {
  128198. 6,
  128199. 5,
  128200. 7,
  128201. 4,
  128202. 8,
  128203. 3,
  128204. 9,
  128205. 2,
  128206. 10,
  128207. 1,
  128208. 11,
  128209. 0,
  128210. 12,
  128211. };
  128212. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128213. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128214. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128215. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128216. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128217. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128218. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128219. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128220. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128221. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128222. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128223. 11,11,11,11,11,11,11,11,11,
  128224. };
  128225. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128226. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128227. 552.5, 773.5, 994.5, 1215.5,
  128228. };
  128229. static long _vq_quantmap__44c2_s_p9_0[] = {
  128230. 11, 9, 7, 5, 3, 1, 0, 2,
  128231. 4, 6, 8, 10, 12,
  128232. };
  128233. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128234. _vq_quantthresh__44c2_s_p9_0,
  128235. _vq_quantmap__44c2_s_p9_0,
  128236. 13,
  128237. 13
  128238. };
  128239. static static_codebook _44c2_s_p9_0 = {
  128240. 2, 169,
  128241. _vq_lengthlist__44c2_s_p9_0,
  128242. 1, -514541568, 1627103232, 4, 0,
  128243. _vq_quantlist__44c2_s_p9_0,
  128244. NULL,
  128245. &_vq_auxt__44c2_s_p9_0,
  128246. NULL,
  128247. 0
  128248. };
  128249. static long _vq_quantlist__44c2_s_p9_1[] = {
  128250. 6,
  128251. 5,
  128252. 7,
  128253. 4,
  128254. 8,
  128255. 3,
  128256. 9,
  128257. 2,
  128258. 10,
  128259. 1,
  128260. 11,
  128261. 0,
  128262. 12,
  128263. };
  128264. static long _vq_lengthlist__44c2_s_p9_1[] = {
  128265. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  128266. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  128267. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  128268. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  128269. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  128270. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  128271. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  128272. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  128273. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  128274. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  128275. 17,13,12,12,10,13,11,14,14,
  128276. };
  128277. static float _vq_quantthresh__44c2_s_p9_1[] = {
  128278. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  128279. 42.5, 59.5, 76.5, 93.5,
  128280. };
  128281. static long _vq_quantmap__44c2_s_p9_1[] = {
  128282. 11, 9, 7, 5, 3, 1, 0, 2,
  128283. 4, 6, 8, 10, 12,
  128284. };
  128285. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  128286. _vq_quantthresh__44c2_s_p9_1,
  128287. _vq_quantmap__44c2_s_p9_1,
  128288. 13,
  128289. 13
  128290. };
  128291. static static_codebook _44c2_s_p9_1 = {
  128292. 2, 169,
  128293. _vq_lengthlist__44c2_s_p9_1,
  128294. 1, -522616832, 1620115456, 4, 0,
  128295. _vq_quantlist__44c2_s_p9_1,
  128296. NULL,
  128297. &_vq_auxt__44c2_s_p9_1,
  128298. NULL,
  128299. 0
  128300. };
  128301. static long _vq_quantlist__44c2_s_p9_2[] = {
  128302. 8,
  128303. 7,
  128304. 9,
  128305. 6,
  128306. 10,
  128307. 5,
  128308. 11,
  128309. 4,
  128310. 12,
  128311. 3,
  128312. 13,
  128313. 2,
  128314. 14,
  128315. 1,
  128316. 15,
  128317. 0,
  128318. 16,
  128319. };
  128320. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128321. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128322. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128323. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128324. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128325. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128326. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128327. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128328. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128329. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128330. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128331. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128332. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128333. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128334. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128335. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128336. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128337. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128338. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128339. 10,
  128340. };
  128341. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128342. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128343. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128344. };
  128345. static long _vq_quantmap__44c2_s_p9_2[] = {
  128346. 15, 13, 11, 9, 7, 5, 3, 1,
  128347. 0, 2, 4, 6, 8, 10, 12, 14,
  128348. 16,
  128349. };
  128350. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128351. _vq_quantthresh__44c2_s_p9_2,
  128352. _vq_quantmap__44c2_s_p9_2,
  128353. 17,
  128354. 17
  128355. };
  128356. static static_codebook _44c2_s_p9_2 = {
  128357. 2, 289,
  128358. _vq_lengthlist__44c2_s_p9_2,
  128359. 1, -529530880, 1611661312, 5, 0,
  128360. _vq_quantlist__44c2_s_p9_2,
  128361. NULL,
  128362. &_vq_auxt__44c2_s_p9_2,
  128363. NULL,
  128364. 0
  128365. };
  128366. static long _huff_lengthlist__44c2_s_short[] = {
  128367. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128368. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128369. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128370. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  128371. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  128372. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  128373. 6, 8, 9,12,
  128374. };
  128375. static static_codebook _huff_book__44c2_s_short = {
  128376. 2, 100,
  128377. _huff_lengthlist__44c2_s_short,
  128378. 0, 0, 0, 0, 0,
  128379. NULL,
  128380. NULL,
  128381. NULL,
  128382. NULL,
  128383. 0
  128384. };
  128385. static long _huff_lengthlist__44c3_s_long[] = {
  128386. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  128387. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  128388. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  128389. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  128390. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  128391. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  128392. 9, 8, 8, 8,
  128393. };
  128394. static static_codebook _huff_book__44c3_s_long = {
  128395. 2, 100,
  128396. _huff_lengthlist__44c3_s_long,
  128397. 0, 0, 0, 0, 0,
  128398. NULL,
  128399. NULL,
  128400. NULL,
  128401. NULL,
  128402. 0
  128403. };
  128404. static long _vq_quantlist__44c3_s_p1_0[] = {
  128405. 1,
  128406. 0,
  128407. 2,
  128408. };
  128409. static long _vq_lengthlist__44c3_s_p1_0[] = {
  128410. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128411. 0, 0, 5, 6, 6, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128416. 0, 0, 0, 6, 7, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128421. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  128456. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  128461. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  128466. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128502. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128507. 0, 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128512. 0, 0, 0, 0, 0, 0, 8, 9, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128644. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128652. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128820. 0,
  128821. };
  128822. static float _vq_quantthresh__44c3_s_p1_0[] = {
  128823. -0.5, 0.5,
  128824. };
  128825. static long _vq_quantmap__44c3_s_p1_0[] = {
  128826. 1, 0, 2,
  128827. };
  128828. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  128829. _vq_quantthresh__44c3_s_p1_0,
  128830. _vq_quantmap__44c3_s_p1_0,
  128831. 3,
  128832. 3
  128833. };
  128834. static static_codebook _44c3_s_p1_0 = {
  128835. 8, 6561,
  128836. _vq_lengthlist__44c3_s_p1_0,
  128837. 1, -535822336, 1611661312, 2, 0,
  128838. _vq_quantlist__44c3_s_p1_0,
  128839. NULL,
  128840. &_vq_auxt__44c3_s_p1_0,
  128841. NULL,
  128842. 0
  128843. };
  128844. static long _vq_quantlist__44c3_s_p2_0[] = {
  128845. 2,
  128846. 1,
  128847. 3,
  128848. 0,
  128849. 4,
  128850. };
  128851. static long _vq_lengthlist__44c3_s_p2_0[] = {
  128852. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  128853. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  128854. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  128855. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  128856. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128861. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  128862. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  128863. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  128864. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128869. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  128870. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  128871. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  128872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128877. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  128878. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  128879. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  128880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128891. 0,
  128892. };
  128893. static float _vq_quantthresh__44c3_s_p2_0[] = {
  128894. -1.5, -0.5, 0.5, 1.5,
  128895. };
  128896. static long _vq_quantmap__44c3_s_p2_0[] = {
  128897. 3, 1, 0, 2, 4,
  128898. };
  128899. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  128900. _vq_quantthresh__44c3_s_p2_0,
  128901. _vq_quantmap__44c3_s_p2_0,
  128902. 5,
  128903. 5
  128904. };
  128905. static static_codebook _44c3_s_p2_0 = {
  128906. 4, 625,
  128907. _vq_lengthlist__44c3_s_p2_0,
  128908. 1, -533725184, 1611661312, 3, 0,
  128909. _vq_quantlist__44c3_s_p2_0,
  128910. NULL,
  128911. &_vq_auxt__44c3_s_p2_0,
  128912. NULL,
  128913. 0
  128914. };
  128915. static long _vq_quantlist__44c3_s_p3_0[] = {
  128916. 2,
  128917. 1,
  128918. 3,
  128919. 0,
  128920. 4,
  128921. };
  128922. static long _vq_lengthlist__44c3_s_p3_0[] = {
  128923. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128926. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128929. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128962. 0,
  128963. };
  128964. static float _vq_quantthresh__44c3_s_p3_0[] = {
  128965. -1.5, -0.5, 0.5, 1.5,
  128966. };
  128967. static long _vq_quantmap__44c3_s_p3_0[] = {
  128968. 3, 1, 0, 2, 4,
  128969. };
  128970. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  128971. _vq_quantthresh__44c3_s_p3_0,
  128972. _vq_quantmap__44c3_s_p3_0,
  128973. 5,
  128974. 5
  128975. };
  128976. static static_codebook _44c3_s_p3_0 = {
  128977. 4, 625,
  128978. _vq_lengthlist__44c3_s_p3_0,
  128979. 1, -533725184, 1611661312, 3, 0,
  128980. _vq_quantlist__44c3_s_p3_0,
  128981. NULL,
  128982. &_vq_auxt__44c3_s_p3_0,
  128983. NULL,
  128984. 0
  128985. };
  128986. static long _vq_quantlist__44c3_s_p4_0[] = {
  128987. 4,
  128988. 3,
  128989. 5,
  128990. 2,
  128991. 6,
  128992. 1,
  128993. 7,
  128994. 0,
  128995. 8,
  128996. };
  128997. static long _vq_lengthlist__44c3_s_p4_0[] = {
  128998. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  128999. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129000. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129001. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129002. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129003. 0,
  129004. };
  129005. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129006. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129007. };
  129008. static long _vq_quantmap__44c3_s_p4_0[] = {
  129009. 7, 5, 3, 1, 0, 2, 4, 6,
  129010. 8,
  129011. };
  129012. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129013. _vq_quantthresh__44c3_s_p4_0,
  129014. _vq_quantmap__44c3_s_p4_0,
  129015. 9,
  129016. 9
  129017. };
  129018. static static_codebook _44c3_s_p4_0 = {
  129019. 2, 81,
  129020. _vq_lengthlist__44c3_s_p4_0,
  129021. 1, -531628032, 1611661312, 4, 0,
  129022. _vq_quantlist__44c3_s_p4_0,
  129023. NULL,
  129024. &_vq_auxt__44c3_s_p4_0,
  129025. NULL,
  129026. 0
  129027. };
  129028. static long _vq_quantlist__44c3_s_p5_0[] = {
  129029. 4,
  129030. 3,
  129031. 5,
  129032. 2,
  129033. 6,
  129034. 1,
  129035. 7,
  129036. 0,
  129037. 8,
  129038. };
  129039. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129040. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129041. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129042. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129043. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129044. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129045. 11,
  129046. };
  129047. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129048. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129049. };
  129050. static long _vq_quantmap__44c3_s_p5_0[] = {
  129051. 7, 5, 3, 1, 0, 2, 4, 6,
  129052. 8,
  129053. };
  129054. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129055. _vq_quantthresh__44c3_s_p5_0,
  129056. _vq_quantmap__44c3_s_p5_0,
  129057. 9,
  129058. 9
  129059. };
  129060. static static_codebook _44c3_s_p5_0 = {
  129061. 2, 81,
  129062. _vq_lengthlist__44c3_s_p5_0,
  129063. 1, -531628032, 1611661312, 4, 0,
  129064. _vq_quantlist__44c3_s_p5_0,
  129065. NULL,
  129066. &_vq_auxt__44c3_s_p5_0,
  129067. NULL,
  129068. 0
  129069. };
  129070. static long _vq_quantlist__44c3_s_p6_0[] = {
  129071. 8,
  129072. 7,
  129073. 9,
  129074. 6,
  129075. 10,
  129076. 5,
  129077. 11,
  129078. 4,
  129079. 12,
  129080. 3,
  129081. 13,
  129082. 2,
  129083. 14,
  129084. 1,
  129085. 15,
  129086. 0,
  129087. 16,
  129088. };
  129089. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129090. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129091. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129092. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129093. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129094. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129095. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129096. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129097. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129098. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129099. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129100. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129101. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129102. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129103. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129104. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129105. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129106. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129107. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129108. 13,
  129109. };
  129110. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129111. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129112. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129113. };
  129114. static long _vq_quantmap__44c3_s_p6_0[] = {
  129115. 15, 13, 11, 9, 7, 5, 3, 1,
  129116. 0, 2, 4, 6, 8, 10, 12, 14,
  129117. 16,
  129118. };
  129119. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129120. _vq_quantthresh__44c3_s_p6_0,
  129121. _vq_quantmap__44c3_s_p6_0,
  129122. 17,
  129123. 17
  129124. };
  129125. static static_codebook _44c3_s_p6_0 = {
  129126. 2, 289,
  129127. _vq_lengthlist__44c3_s_p6_0,
  129128. 1, -529530880, 1611661312, 5, 0,
  129129. _vq_quantlist__44c3_s_p6_0,
  129130. NULL,
  129131. &_vq_auxt__44c3_s_p6_0,
  129132. NULL,
  129133. 0
  129134. };
  129135. static long _vq_quantlist__44c3_s_p7_0[] = {
  129136. 1,
  129137. 0,
  129138. 2,
  129139. };
  129140. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129141. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129142. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129143. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129144. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129145. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129146. 10,
  129147. };
  129148. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129149. -5.5, 5.5,
  129150. };
  129151. static long _vq_quantmap__44c3_s_p7_0[] = {
  129152. 1, 0, 2,
  129153. };
  129154. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129155. _vq_quantthresh__44c3_s_p7_0,
  129156. _vq_quantmap__44c3_s_p7_0,
  129157. 3,
  129158. 3
  129159. };
  129160. static static_codebook _44c3_s_p7_0 = {
  129161. 4, 81,
  129162. _vq_lengthlist__44c3_s_p7_0,
  129163. 1, -529137664, 1618345984, 2, 0,
  129164. _vq_quantlist__44c3_s_p7_0,
  129165. NULL,
  129166. &_vq_auxt__44c3_s_p7_0,
  129167. NULL,
  129168. 0
  129169. };
  129170. static long _vq_quantlist__44c3_s_p7_1[] = {
  129171. 5,
  129172. 4,
  129173. 6,
  129174. 3,
  129175. 7,
  129176. 2,
  129177. 8,
  129178. 1,
  129179. 9,
  129180. 0,
  129181. 10,
  129182. };
  129183. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129184. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129185. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129186. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129187. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129188. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129189. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129190. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129191. 10,10,10, 8, 8, 8, 8, 8, 8,
  129192. };
  129193. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129194. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129195. 3.5, 4.5,
  129196. };
  129197. static long _vq_quantmap__44c3_s_p7_1[] = {
  129198. 9, 7, 5, 3, 1, 0, 2, 4,
  129199. 6, 8, 10,
  129200. };
  129201. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129202. _vq_quantthresh__44c3_s_p7_1,
  129203. _vq_quantmap__44c3_s_p7_1,
  129204. 11,
  129205. 11
  129206. };
  129207. static static_codebook _44c3_s_p7_1 = {
  129208. 2, 121,
  129209. _vq_lengthlist__44c3_s_p7_1,
  129210. 1, -531365888, 1611661312, 4, 0,
  129211. _vq_quantlist__44c3_s_p7_1,
  129212. NULL,
  129213. &_vq_auxt__44c3_s_p7_1,
  129214. NULL,
  129215. 0
  129216. };
  129217. static long _vq_quantlist__44c3_s_p8_0[] = {
  129218. 6,
  129219. 5,
  129220. 7,
  129221. 4,
  129222. 8,
  129223. 3,
  129224. 9,
  129225. 2,
  129226. 10,
  129227. 1,
  129228. 11,
  129229. 0,
  129230. 12,
  129231. };
  129232. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129233. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129234. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129235. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129236. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129237. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129238. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129239. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129240. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129241. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129242. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129243. 0,13,13,12,12,13,12,14,13,
  129244. };
  129245. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129246. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129247. 12.5, 17.5, 22.5, 27.5,
  129248. };
  129249. static long _vq_quantmap__44c3_s_p8_0[] = {
  129250. 11, 9, 7, 5, 3, 1, 0, 2,
  129251. 4, 6, 8, 10, 12,
  129252. };
  129253. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129254. _vq_quantthresh__44c3_s_p8_0,
  129255. _vq_quantmap__44c3_s_p8_0,
  129256. 13,
  129257. 13
  129258. };
  129259. static static_codebook _44c3_s_p8_0 = {
  129260. 2, 169,
  129261. _vq_lengthlist__44c3_s_p8_0,
  129262. 1, -526516224, 1616117760, 4, 0,
  129263. _vq_quantlist__44c3_s_p8_0,
  129264. NULL,
  129265. &_vq_auxt__44c3_s_p8_0,
  129266. NULL,
  129267. 0
  129268. };
  129269. static long _vq_quantlist__44c3_s_p8_1[] = {
  129270. 2,
  129271. 1,
  129272. 3,
  129273. 0,
  129274. 4,
  129275. };
  129276. static long _vq_lengthlist__44c3_s_p8_1[] = {
  129277. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129278. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129279. };
  129280. static float _vq_quantthresh__44c3_s_p8_1[] = {
  129281. -1.5, -0.5, 0.5, 1.5,
  129282. };
  129283. static long _vq_quantmap__44c3_s_p8_1[] = {
  129284. 3, 1, 0, 2, 4,
  129285. };
  129286. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  129287. _vq_quantthresh__44c3_s_p8_1,
  129288. _vq_quantmap__44c3_s_p8_1,
  129289. 5,
  129290. 5
  129291. };
  129292. static static_codebook _44c3_s_p8_1 = {
  129293. 2, 25,
  129294. _vq_lengthlist__44c3_s_p8_1,
  129295. 1, -533725184, 1611661312, 3, 0,
  129296. _vq_quantlist__44c3_s_p8_1,
  129297. NULL,
  129298. &_vq_auxt__44c3_s_p8_1,
  129299. NULL,
  129300. 0
  129301. };
  129302. static long _vq_quantlist__44c3_s_p9_0[] = {
  129303. 6,
  129304. 5,
  129305. 7,
  129306. 4,
  129307. 8,
  129308. 3,
  129309. 9,
  129310. 2,
  129311. 10,
  129312. 1,
  129313. 11,
  129314. 0,
  129315. 12,
  129316. };
  129317. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129318. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129319. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129320. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129321. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129322. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129323. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129324. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129325. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129326. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129327. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129328. 11,11,11,11,11,11,11,11,11,
  129329. };
  129330. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129331. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129332. 637.5, 892.5, 1147.5, 1402.5,
  129333. };
  129334. static long _vq_quantmap__44c3_s_p9_0[] = {
  129335. 11, 9, 7, 5, 3, 1, 0, 2,
  129336. 4, 6, 8, 10, 12,
  129337. };
  129338. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129339. _vq_quantthresh__44c3_s_p9_0,
  129340. _vq_quantmap__44c3_s_p9_0,
  129341. 13,
  129342. 13
  129343. };
  129344. static static_codebook _44c3_s_p9_0 = {
  129345. 2, 169,
  129346. _vq_lengthlist__44c3_s_p9_0,
  129347. 1, -514332672, 1627381760, 4, 0,
  129348. _vq_quantlist__44c3_s_p9_0,
  129349. NULL,
  129350. &_vq_auxt__44c3_s_p9_0,
  129351. NULL,
  129352. 0
  129353. };
  129354. static long _vq_quantlist__44c3_s_p9_1[] = {
  129355. 7,
  129356. 6,
  129357. 8,
  129358. 5,
  129359. 9,
  129360. 4,
  129361. 10,
  129362. 3,
  129363. 11,
  129364. 2,
  129365. 12,
  129366. 1,
  129367. 13,
  129368. 0,
  129369. 14,
  129370. };
  129371. static long _vq_lengthlist__44c3_s_p9_1[] = {
  129372. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  129373. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  129374. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  129375. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  129376. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  129377. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  129378. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  129379. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  129380. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  129381. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  129382. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  129383. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  129384. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  129385. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  129386. 15,
  129387. };
  129388. static float _vq_quantthresh__44c3_s_p9_1[] = {
  129389. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  129390. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  129391. };
  129392. static long _vq_quantmap__44c3_s_p9_1[] = {
  129393. 13, 11, 9, 7, 5, 3, 1, 0,
  129394. 2, 4, 6, 8, 10, 12, 14,
  129395. };
  129396. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  129397. _vq_quantthresh__44c3_s_p9_1,
  129398. _vq_quantmap__44c3_s_p9_1,
  129399. 15,
  129400. 15
  129401. };
  129402. static static_codebook _44c3_s_p9_1 = {
  129403. 2, 225,
  129404. _vq_lengthlist__44c3_s_p9_1,
  129405. 1, -522338304, 1620115456, 4, 0,
  129406. _vq_quantlist__44c3_s_p9_1,
  129407. NULL,
  129408. &_vq_auxt__44c3_s_p9_1,
  129409. NULL,
  129410. 0
  129411. };
  129412. static long _vq_quantlist__44c3_s_p9_2[] = {
  129413. 8,
  129414. 7,
  129415. 9,
  129416. 6,
  129417. 10,
  129418. 5,
  129419. 11,
  129420. 4,
  129421. 12,
  129422. 3,
  129423. 13,
  129424. 2,
  129425. 14,
  129426. 1,
  129427. 15,
  129428. 0,
  129429. 16,
  129430. };
  129431. static long _vq_lengthlist__44c3_s_p9_2[] = {
  129432. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129433. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  129434. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  129435. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129436. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  129437. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129438. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  129439. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  129440. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  129441. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  129442. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  129443. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  129444. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  129445. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  129446. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  129447. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  129448. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  129449. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  129450. 10,
  129451. };
  129452. static float _vq_quantthresh__44c3_s_p9_2[] = {
  129453. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129454. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129455. };
  129456. static long _vq_quantmap__44c3_s_p9_2[] = {
  129457. 15, 13, 11, 9, 7, 5, 3, 1,
  129458. 0, 2, 4, 6, 8, 10, 12, 14,
  129459. 16,
  129460. };
  129461. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  129462. _vq_quantthresh__44c3_s_p9_2,
  129463. _vq_quantmap__44c3_s_p9_2,
  129464. 17,
  129465. 17
  129466. };
  129467. static static_codebook _44c3_s_p9_2 = {
  129468. 2, 289,
  129469. _vq_lengthlist__44c3_s_p9_2,
  129470. 1, -529530880, 1611661312, 5, 0,
  129471. _vq_quantlist__44c3_s_p9_2,
  129472. NULL,
  129473. &_vq_auxt__44c3_s_p9_2,
  129474. NULL,
  129475. 0
  129476. };
  129477. static long _huff_lengthlist__44c3_s_short[] = {
  129478. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  129479. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  129480. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  129481. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  129482. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  129483. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  129484. 6, 8, 9,11,
  129485. };
  129486. static static_codebook _huff_book__44c3_s_short = {
  129487. 2, 100,
  129488. _huff_lengthlist__44c3_s_short,
  129489. 0, 0, 0, 0, 0,
  129490. NULL,
  129491. NULL,
  129492. NULL,
  129493. NULL,
  129494. 0
  129495. };
  129496. static long _huff_lengthlist__44c4_s_long[] = {
  129497. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  129498. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  129499. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  129500. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  129501. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  129502. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  129503. 9, 8, 7, 7,
  129504. };
  129505. static static_codebook _huff_book__44c4_s_long = {
  129506. 2, 100,
  129507. _huff_lengthlist__44c4_s_long,
  129508. 0, 0, 0, 0, 0,
  129509. NULL,
  129510. NULL,
  129511. NULL,
  129512. NULL,
  129513. 0
  129514. };
  129515. static long _vq_quantlist__44c4_s_p1_0[] = {
  129516. 1,
  129517. 0,
  129518. 2,
  129519. };
  129520. static long _vq_lengthlist__44c4_s_p1_0[] = {
  129521. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129522. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129526. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129527. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129531. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129532. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129567. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129572. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  129577. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129612. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129613. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129617. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129618. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129622. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129623. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129931. 0,
  129932. };
  129933. static float _vq_quantthresh__44c4_s_p1_0[] = {
  129934. -0.5, 0.5,
  129935. };
  129936. static long _vq_quantmap__44c4_s_p1_0[] = {
  129937. 1, 0, 2,
  129938. };
  129939. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  129940. _vq_quantthresh__44c4_s_p1_0,
  129941. _vq_quantmap__44c4_s_p1_0,
  129942. 3,
  129943. 3
  129944. };
  129945. static static_codebook _44c4_s_p1_0 = {
  129946. 8, 6561,
  129947. _vq_lengthlist__44c4_s_p1_0,
  129948. 1, -535822336, 1611661312, 2, 0,
  129949. _vq_quantlist__44c4_s_p1_0,
  129950. NULL,
  129951. &_vq_auxt__44c4_s_p1_0,
  129952. NULL,
  129953. 0
  129954. };
  129955. static long _vq_quantlist__44c4_s_p2_0[] = {
  129956. 2,
  129957. 1,
  129958. 3,
  129959. 0,
  129960. 4,
  129961. };
  129962. static long _vq_lengthlist__44c4_s_p2_0[] = {
  129963. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129964. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129965. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129966. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129967. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129972. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  129973. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129974. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129975. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129980. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129981. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129982. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129988. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129989. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129990. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130002. 0,
  130003. };
  130004. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130005. -1.5, -0.5, 0.5, 1.5,
  130006. };
  130007. static long _vq_quantmap__44c4_s_p2_0[] = {
  130008. 3, 1, 0, 2, 4,
  130009. };
  130010. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130011. _vq_quantthresh__44c4_s_p2_0,
  130012. _vq_quantmap__44c4_s_p2_0,
  130013. 5,
  130014. 5
  130015. };
  130016. static static_codebook _44c4_s_p2_0 = {
  130017. 4, 625,
  130018. _vq_lengthlist__44c4_s_p2_0,
  130019. 1, -533725184, 1611661312, 3, 0,
  130020. _vq_quantlist__44c4_s_p2_0,
  130021. NULL,
  130022. &_vq_auxt__44c4_s_p2_0,
  130023. NULL,
  130024. 0
  130025. };
  130026. static long _vq_quantlist__44c4_s_p3_0[] = {
  130027. 2,
  130028. 1,
  130029. 3,
  130030. 0,
  130031. 4,
  130032. };
  130033. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130034. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130037. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130040. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130073. 0,
  130074. };
  130075. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130076. -1.5, -0.5, 0.5, 1.5,
  130077. };
  130078. static long _vq_quantmap__44c4_s_p3_0[] = {
  130079. 3, 1, 0, 2, 4,
  130080. };
  130081. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130082. _vq_quantthresh__44c4_s_p3_0,
  130083. _vq_quantmap__44c4_s_p3_0,
  130084. 5,
  130085. 5
  130086. };
  130087. static static_codebook _44c4_s_p3_0 = {
  130088. 4, 625,
  130089. _vq_lengthlist__44c4_s_p3_0,
  130090. 1, -533725184, 1611661312, 3, 0,
  130091. _vq_quantlist__44c4_s_p3_0,
  130092. NULL,
  130093. &_vq_auxt__44c4_s_p3_0,
  130094. NULL,
  130095. 0
  130096. };
  130097. static long _vq_quantlist__44c4_s_p4_0[] = {
  130098. 4,
  130099. 3,
  130100. 5,
  130101. 2,
  130102. 6,
  130103. 1,
  130104. 7,
  130105. 0,
  130106. 8,
  130107. };
  130108. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130109. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130110. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130111. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130112. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130113. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130114. 0,
  130115. };
  130116. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130117. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130118. };
  130119. static long _vq_quantmap__44c4_s_p4_0[] = {
  130120. 7, 5, 3, 1, 0, 2, 4, 6,
  130121. 8,
  130122. };
  130123. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130124. _vq_quantthresh__44c4_s_p4_0,
  130125. _vq_quantmap__44c4_s_p4_0,
  130126. 9,
  130127. 9
  130128. };
  130129. static static_codebook _44c4_s_p4_0 = {
  130130. 2, 81,
  130131. _vq_lengthlist__44c4_s_p4_0,
  130132. 1, -531628032, 1611661312, 4, 0,
  130133. _vq_quantlist__44c4_s_p4_0,
  130134. NULL,
  130135. &_vq_auxt__44c4_s_p4_0,
  130136. NULL,
  130137. 0
  130138. };
  130139. static long _vq_quantlist__44c4_s_p5_0[] = {
  130140. 4,
  130141. 3,
  130142. 5,
  130143. 2,
  130144. 6,
  130145. 1,
  130146. 7,
  130147. 0,
  130148. 8,
  130149. };
  130150. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130151. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130152. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130153. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130154. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130155. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130156. 10,
  130157. };
  130158. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130159. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130160. };
  130161. static long _vq_quantmap__44c4_s_p5_0[] = {
  130162. 7, 5, 3, 1, 0, 2, 4, 6,
  130163. 8,
  130164. };
  130165. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130166. _vq_quantthresh__44c4_s_p5_0,
  130167. _vq_quantmap__44c4_s_p5_0,
  130168. 9,
  130169. 9
  130170. };
  130171. static static_codebook _44c4_s_p5_0 = {
  130172. 2, 81,
  130173. _vq_lengthlist__44c4_s_p5_0,
  130174. 1, -531628032, 1611661312, 4, 0,
  130175. _vq_quantlist__44c4_s_p5_0,
  130176. NULL,
  130177. &_vq_auxt__44c4_s_p5_0,
  130178. NULL,
  130179. 0
  130180. };
  130181. static long _vq_quantlist__44c4_s_p6_0[] = {
  130182. 8,
  130183. 7,
  130184. 9,
  130185. 6,
  130186. 10,
  130187. 5,
  130188. 11,
  130189. 4,
  130190. 12,
  130191. 3,
  130192. 13,
  130193. 2,
  130194. 14,
  130195. 1,
  130196. 15,
  130197. 0,
  130198. 16,
  130199. };
  130200. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130201. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130202. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130203. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130204. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130205. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130206. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130207. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130208. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130209. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130210. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130211. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130212. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130213. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130214. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130215. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130216. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130217. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130218. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130219. 13,
  130220. };
  130221. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130222. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130223. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130224. };
  130225. static long _vq_quantmap__44c4_s_p6_0[] = {
  130226. 15, 13, 11, 9, 7, 5, 3, 1,
  130227. 0, 2, 4, 6, 8, 10, 12, 14,
  130228. 16,
  130229. };
  130230. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130231. _vq_quantthresh__44c4_s_p6_0,
  130232. _vq_quantmap__44c4_s_p6_0,
  130233. 17,
  130234. 17
  130235. };
  130236. static static_codebook _44c4_s_p6_0 = {
  130237. 2, 289,
  130238. _vq_lengthlist__44c4_s_p6_0,
  130239. 1, -529530880, 1611661312, 5, 0,
  130240. _vq_quantlist__44c4_s_p6_0,
  130241. NULL,
  130242. &_vq_auxt__44c4_s_p6_0,
  130243. NULL,
  130244. 0
  130245. };
  130246. static long _vq_quantlist__44c4_s_p7_0[] = {
  130247. 1,
  130248. 0,
  130249. 2,
  130250. };
  130251. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130252. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130253. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130254. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130255. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130256. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130257. 10,
  130258. };
  130259. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130260. -5.5, 5.5,
  130261. };
  130262. static long _vq_quantmap__44c4_s_p7_0[] = {
  130263. 1, 0, 2,
  130264. };
  130265. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  130266. _vq_quantthresh__44c4_s_p7_0,
  130267. _vq_quantmap__44c4_s_p7_0,
  130268. 3,
  130269. 3
  130270. };
  130271. static static_codebook _44c4_s_p7_0 = {
  130272. 4, 81,
  130273. _vq_lengthlist__44c4_s_p7_0,
  130274. 1, -529137664, 1618345984, 2, 0,
  130275. _vq_quantlist__44c4_s_p7_0,
  130276. NULL,
  130277. &_vq_auxt__44c4_s_p7_0,
  130278. NULL,
  130279. 0
  130280. };
  130281. static long _vq_quantlist__44c4_s_p7_1[] = {
  130282. 5,
  130283. 4,
  130284. 6,
  130285. 3,
  130286. 7,
  130287. 2,
  130288. 8,
  130289. 1,
  130290. 9,
  130291. 0,
  130292. 10,
  130293. };
  130294. static long _vq_lengthlist__44c4_s_p7_1[] = {
  130295. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130296. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130297. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130298. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130299. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130300. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130301. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130302. 10,10,10, 8, 8, 8, 8, 9, 9,
  130303. };
  130304. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130305. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130306. 3.5, 4.5,
  130307. };
  130308. static long _vq_quantmap__44c4_s_p7_1[] = {
  130309. 9, 7, 5, 3, 1, 0, 2, 4,
  130310. 6, 8, 10,
  130311. };
  130312. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130313. _vq_quantthresh__44c4_s_p7_1,
  130314. _vq_quantmap__44c4_s_p7_1,
  130315. 11,
  130316. 11
  130317. };
  130318. static static_codebook _44c4_s_p7_1 = {
  130319. 2, 121,
  130320. _vq_lengthlist__44c4_s_p7_1,
  130321. 1, -531365888, 1611661312, 4, 0,
  130322. _vq_quantlist__44c4_s_p7_1,
  130323. NULL,
  130324. &_vq_auxt__44c4_s_p7_1,
  130325. NULL,
  130326. 0
  130327. };
  130328. static long _vq_quantlist__44c4_s_p8_0[] = {
  130329. 6,
  130330. 5,
  130331. 7,
  130332. 4,
  130333. 8,
  130334. 3,
  130335. 9,
  130336. 2,
  130337. 10,
  130338. 1,
  130339. 11,
  130340. 0,
  130341. 12,
  130342. };
  130343. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130344. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130345. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130346. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130347. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130348. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130349. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130350. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130351. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130352. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130353. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130354. 0,13,12,12,12,12,12,13,13,
  130355. };
  130356. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130357. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130358. 12.5, 17.5, 22.5, 27.5,
  130359. };
  130360. static long _vq_quantmap__44c4_s_p8_0[] = {
  130361. 11, 9, 7, 5, 3, 1, 0, 2,
  130362. 4, 6, 8, 10, 12,
  130363. };
  130364. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130365. _vq_quantthresh__44c4_s_p8_0,
  130366. _vq_quantmap__44c4_s_p8_0,
  130367. 13,
  130368. 13
  130369. };
  130370. static static_codebook _44c4_s_p8_0 = {
  130371. 2, 169,
  130372. _vq_lengthlist__44c4_s_p8_0,
  130373. 1, -526516224, 1616117760, 4, 0,
  130374. _vq_quantlist__44c4_s_p8_0,
  130375. NULL,
  130376. &_vq_auxt__44c4_s_p8_0,
  130377. NULL,
  130378. 0
  130379. };
  130380. static long _vq_quantlist__44c4_s_p8_1[] = {
  130381. 2,
  130382. 1,
  130383. 3,
  130384. 0,
  130385. 4,
  130386. };
  130387. static long _vq_lengthlist__44c4_s_p8_1[] = {
  130388. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  130389. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130390. };
  130391. static float _vq_quantthresh__44c4_s_p8_1[] = {
  130392. -1.5, -0.5, 0.5, 1.5,
  130393. };
  130394. static long _vq_quantmap__44c4_s_p8_1[] = {
  130395. 3, 1, 0, 2, 4,
  130396. };
  130397. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  130398. _vq_quantthresh__44c4_s_p8_1,
  130399. _vq_quantmap__44c4_s_p8_1,
  130400. 5,
  130401. 5
  130402. };
  130403. static static_codebook _44c4_s_p8_1 = {
  130404. 2, 25,
  130405. _vq_lengthlist__44c4_s_p8_1,
  130406. 1, -533725184, 1611661312, 3, 0,
  130407. _vq_quantlist__44c4_s_p8_1,
  130408. NULL,
  130409. &_vq_auxt__44c4_s_p8_1,
  130410. NULL,
  130411. 0
  130412. };
  130413. static long _vq_quantlist__44c4_s_p9_0[] = {
  130414. 6,
  130415. 5,
  130416. 7,
  130417. 4,
  130418. 8,
  130419. 3,
  130420. 9,
  130421. 2,
  130422. 10,
  130423. 1,
  130424. 11,
  130425. 0,
  130426. 12,
  130427. };
  130428. static long _vq_lengthlist__44c4_s_p9_0[] = {
  130429. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  130430. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  130431. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130432. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130433. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130434. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130435. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130436. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130437. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130438. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130439. 12,12,12,12,12,12,12,12,12,
  130440. };
  130441. static float _vq_quantthresh__44c4_s_p9_0[] = {
  130442. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  130443. 787.5, 1102.5, 1417.5, 1732.5,
  130444. };
  130445. static long _vq_quantmap__44c4_s_p9_0[] = {
  130446. 11, 9, 7, 5, 3, 1, 0, 2,
  130447. 4, 6, 8, 10, 12,
  130448. };
  130449. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  130450. _vq_quantthresh__44c4_s_p9_0,
  130451. _vq_quantmap__44c4_s_p9_0,
  130452. 13,
  130453. 13
  130454. };
  130455. static static_codebook _44c4_s_p9_0 = {
  130456. 2, 169,
  130457. _vq_lengthlist__44c4_s_p9_0,
  130458. 1, -513964032, 1628680192, 4, 0,
  130459. _vq_quantlist__44c4_s_p9_0,
  130460. NULL,
  130461. &_vq_auxt__44c4_s_p9_0,
  130462. NULL,
  130463. 0
  130464. };
  130465. static long _vq_quantlist__44c4_s_p9_1[] = {
  130466. 7,
  130467. 6,
  130468. 8,
  130469. 5,
  130470. 9,
  130471. 4,
  130472. 10,
  130473. 3,
  130474. 11,
  130475. 2,
  130476. 12,
  130477. 1,
  130478. 13,
  130479. 0,
  130480. 14,
  130481. };
  130482. static long _vq_lengthlist__44c4_s_p9_1[] = {
  130483. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  130484. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  130485. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  130486. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  130487. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  130488. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  130489. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  130490. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  130491. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  130492. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  130493. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  130494. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  130495. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  130496. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  130497. 15,
  130498. };
  130499. static float _vq_quantthresh__44c4_s_p9_1[] = {
  130500. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130501. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130502. };
  130503. static long _vq_quantmap__44c4_s_p9_1[] = {
  130504. 13, 11, 9, 7, 5, 3, 1, 0,
  130505. 2, 4, 6, 8, 10, 12, 14,
  130506. };
  130507. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  130508. _vq_quantthresh__44c4_s_p9_1,
  130509. _vq_quantmap__44c4_s_p9_1,
  130510. 15,
  130511. 15
  130512. };
  130513. static static_codebook _44c4_s_p9_1 = {
  130514. 2, 225,
  130515. _vq_lengthlist__44c4_s_p9_1,
  130516. 1, -520986624, 1620377600, 4, 0,
  130517. _vq_quantlist__44c4_s_p9_1,
  130518. NULL,
  130519. &_vq_auxt__44c4_s_p9_1,
  130520. NULL,
  130521. 0
  130522. };
  130523. static long _vq_quantlist__44c4_s_p9_2[] = {
  130524. 10,
  130525. 9,
  130526. 11,
  130527. 8,
  130528. 12,
  130529. 7,
  130530. 13,
  130531. 6,
  130532. 14,
  130533. 5,
  130534. 15,
  130535. 4,
  130536. 16,
  130537. 3,
  130538. 17,
  130539. 2,
  130540. 18,
  130541. 1,
  130542. 19,
  130543. 0,
  130544. 20,
  130545. };
  130546. static long _vq_lengthlist__44c4_s_p9_2[] = {
  130547. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  130548. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130549. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  130550. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  130551. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130552. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  130553. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  130554. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  130555. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  130556. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  130557. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  130558. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  130559. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  130560. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  130561. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  130562. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  130563. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  130564. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  130565. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  130566. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  130567. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130568. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  130569. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  130570. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  130571. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  130572. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  130573. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  130574. 10,10,10,10,10,10,10,10,10,
  130575. };
  130576. static float _vq_quantthresh__44c4_s_p9_2[] = {
  130577. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130578. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130579. 6.5, 7.5, 8.5, 9.5,
  130580. };
  130581. static long _vq_quantmap__44c4_s_p9_2[] = {
  130582. 19, 17, 15, 13, 11, 9, 7, 5,
  130583. 3, 1, 0, 2, 4, 6, 8, 10,
  130584. 12, 14, 16, 18, 20,
  130585. };
  130586. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  130587. _vq_quantthresh__44c4_s_p9_2,
  130588. _vq_quantmap__44c4_s_p9_2,
  130589. 21,
  130590. 21
  130591. };
  130592. static static_codebook _44c4_s_p9_2 = {
  130593. 2, 441,
  130594. _vq_lengthlist__44c4_s_p9_2,
  130595. 1, -529268736, 1611661312, 5, 0,
  130596. _vq_quantlist__44c4_s_p9_2,
  130597. NULL,
  130598. &_vq_auxt__44c4_s_p9_2,
  130599. NULL,
  130600. 0
  130601. };
  130602. static long _huff_lengthlist__44c4_s_short[] = {
  130603. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  130604. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  130605. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  130606. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  130607. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  130608. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  130609. 7, 9,12,17,
  130610. };
  130611. static static_codebook _huff_book__44c4_s_short = {
  130612. 2, 100,
  130613. _huff_lengthlist__44c4_s_short,
  130614. 0, 0, 0, 0, 0,
  130615. NULL,
  130616. NULL,
  130617. NULL,
  130618. NULL,
  130619. 0
  130620. };
  130621. static long _huff_lengthlist__44c5_s_long[] = {
  130622. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  130623. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  130624. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  130625. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  130626. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  130627. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  130628. 9, 8, 7, 7,
  130629. };
  130630. static static_codebook _huff_book__44c5_s_long = {
  130631. 2, 100,
  130632. _huff_lengthlist__44c5_s_long,
  130633. 0, 0, 0, 0, 0,
  130634. NULL,
  130635. NULL,
  130636. NULL,
  130637. NULL,
  130638. 0
  130639. };
  130640. static long _vq_quantlist__44c5_s_p1_0[] = {
  130641. 1,
  130642. 0,
  130643. 2,
  130644. };
  130645. static long _vq_lengthlist__44c5_s_p1_0[] = {
  130646. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130647. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130651. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130652. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130656. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  130657. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130692. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130697. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  130698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130702. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  130703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130737. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130738. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130742. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  130743. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  130744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130747. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  130748. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  130749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131056. 0,
  131057. };
  131058. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131059. -0.5, 0.5,
  131060. };
  131061. static long _vq_quantmap__44c5_s_p1_0[] = {
  131062. 1, 0, 2,
  131063. };
  131064. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131065. _vq_quantthresh__44c5_s_p1_0,
  131066. _vq_quantmap__44c5_s_p1_0,
  131067. 3,
  131068. 3
  131069. };
  131070. static static_codebook _44c5_s_p1_0 = {
  131071. 8, 6561,
  131072. _vq_lengthlist__44c5_s_p1_0,
  131073. 1, -535822336, 1611661312, 2, 0,
  131074. _vq_quantlist__44c5_s_p1_0,
  131075. NULL,
  131076. &_vq_auxt__44c5_s_p1_0,
  131077. NULL,
  131078. 0
  131079. };
  131080. static long _vq_quantlist__44c5_s_p2_0[] = {
  131081. 2,
  131082. 1,
  131083. 3,
  131084. 0,
  131085. 4,
  131086. };
  131087. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131088. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131089. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131090. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131091. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131092. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131097. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131098. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131099. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131100. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131105. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131106. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131107. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  131108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131113. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131114. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131115. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  131116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131127. 0,
  131128. };
  131129. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131130. -1.5, -0.5, 0.5, 1.5,
  131131. };
  131132. static long _vq_quantmap__44c5_s_p2_0[] = {
  131133. 3, 1, 0, 2, 4,
  131134. };
  131135. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131136. _vq_quantthresh__44c5_s_p2_0,
  131137. _vq_quantmap__44c5_s_p2_0,
  131138. 5,
  131139. 5
  131140. };
  131141. static static_codebook _44c5_s_p2_0 = {
  131142. 4, 625,
  131143. _vq_lengthlist__44c5_s_p2_0,
  131144. 1, -533725184, 1611661312, 3, 0,
  131145. _vq_quantlist__44c5_s_p2_0,
  131146. NULL,
  131147. &_vq_auxt__44c5_s_p2_0,
  131148. NULL,
  131149. 0
  131150. };
  131151. static long _vq_quantlist__44c5_s_p3_0[] = {
  131152. 2,
  131153. 1,
  131154. 3,
  131155. 0,
  131156. 4,
  131157. };
  131158. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131159. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131162. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131165. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131198. 0,
  131199. };
  131200. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131201. -1.5, -0.5, 0.5, 1.5,
  131202. };
  131203. static long _vq_quantmap__44c5_s_p3_0[] = {
  131204. 3, 1, 0, 2, 4,
  131205. };
  131206. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131207. _vq_quantthresh__44c5_s_p3_0,
  131208. _vq_quantmap__44c5_s_p3_0,
  131209. 5,
  131210. 5
  131211. };
  131212. static static_codebook _44c5_s_p3_0 = {
  131213. 4, 625,
  131214. _vq_lengthlist__44c5_s_p3_0,
  131215. 1, -533725184, 1611661312, 3, 0,
  131216. _vq_quantlist__44c5_s_p3_0,
  131217. NULL,
  131218. &_vq_auxt__44c5_s_p3_0,
  131219. NULL,
  131220. 0
  131221. };
  131222. static long _vq_quantlist__44c5_s_p4_0[] = {
  131223. 4,
  131224. 3,
  131225. 5,
  131226. 2,
  131227. 6,
  131228. 1,
  131229. 7,
  131230. 0,
  131231. 8,
  131232. };
  131233. static long _vq_lengthlist__44c5_s_p4_0[] = {
  131234. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131235. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131236. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131237. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131238. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131239. 0,
  131240. };
  131241. static float _vq_quantthresh__44c5_s_p4_0[] = {
  131242. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131243. };
  131244. static long _vq_quantmap__44c5_s_p4_0[] = {
  131245. 7, 5, 3, 1, 0, 2, 4, 6,
  131246. 8,
  131247. };
  131248. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131249. _vq_quantthresh__44c5_s_p4_0,
  131250. _vq_quantmap__44c5_s_p4_0,
  131251. 9,
  131252. 9
  131253. };
  131254. static static_codebook _44c5_s_p4_0 = {
  131255. 2, 81,
  131256. _vq_lengthlist__44c5_s_p4_0,
  131257. 1, -531628032, 1611661312, 4, 0,
  131258. _vq_quantlist__44c5_s_p4_0,
  131259. NULL,
  131260. &_vq_auxt__44c5_s_p4_0,
  131261. NULL,
  131262. 0
  131263. };
  131264. static long _vq_quantlist__44c5_s_p5_0[] = {
  131265. 4,
  131266. 3,
  131267. 5,
  131268. 2,
  131269. 6,
  131270. 1,
  131271. 7,
  131272. 0,
  131273. 8,
  131274. };
  131275. static long _vq_lengthlist__44c5_s_p5_0[] = {
  131276. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131277. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131278. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  131279. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131280. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131281. 10,
  131282. };
  131283. static float _vq_quantthresh__44c5_s_p5_0[] = {
  131284. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131285. };
  131286. static long _vq_quantmap__44c5_s_p5_0[] = {
  131287. 7, 5, 3, 1, 0, 2, 4, 6,
  131288. 8,
  131289. };
  131290. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  131291. _vq_quantthresh__44c5_s_p5_0,
  131292. _vq_quantmap__44c5_s_p5_0,
  131293. 9,
  131294. 9
  131295. };
  131296. static static_codebook _44c5_s_p5_0 = {
  131297. 2, 81,
  131298. _vq_lengthlist__44c5_s_p5_0,
  131299. 1, -531628032, 1611661312, 4, 0,
  131300. _vq_quantlist__44c5_s_p5_0,
  131301. NULL,
  131302. &_vq_auxt__44c5_s_p5_0,
  131303. NULL,
  131304. 0
  131305. };
  131306. static long _vq_quantlist__44c5_s_p6_0[] = {
  131307. 8,
  131308. 7,
  131309. 9,
  131310. 6,
  131311. 10,
  131312. 5,
  131313. 11,
  131314. 4,
  131315. 12,
  131316. 3,
  131317. 13,
  131318. 2,
  131319. 14,
  131320. 1,
  131321. 15,
  131322. 0,
  131323. 16,
  131324. };
  131325. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131326. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131327. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131328. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131329. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131330. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131331. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131332. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131333. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131334. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131335. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131336. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131337. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131338. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131339. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131340. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131341. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131342. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131343. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131344. 13,
  131345. };
  131346. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131347. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131348. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131349. };
  131350. static long _vq_quantmap__44c5_s_p6_0[] = {
  131351. 15, 13, 11, 9, 7, 5, 3, 1,
  131352. 0, 2, 4, 6, 8, 10, 12, 14,
  131353. 16,
  131354. };
  131355. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131356. _vq_quantthresh__44c5_s_p6_0,
  131357. _vq_quantmap__44c5_s_p6_0,
  131358. 17,
  131359. 17
  131360. };
  131361. static static_codebook _44c5_s_p6_0 = {
  131362. 2, 289,
  131363. _vq_lengthlist__44c5_s_p6_0,
  131364. 1, -529530880, 1611661312, 5, 0,
  131365. _vq_quantlist__44c5_s_p6_0,
  131366. NULL,
  131367. &_vq_auxt__44c5_s_p6_0,
  131368. NULL,
  131369. 0
  131370. };
  131371. static long _vq_quantlist__44c5_s_p7_0[] = {
  131372. 1,
  131373. 0,
  131374. 2,
  131375. };
  131376. static long _vq_lengthlist__44c5_s_p7_0[] = {
  131377. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131378. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131379. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131380. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131381. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131382. 10,
  131383. };
  131384. static float _vq_quantthresh__44c5_s_p7_0[] = {
  131385. -5.5, 5.5,
  131386. };
  131387. static long _vq_quantmap__44c5_s_p7_0[] = {
  131388. 1, 0, 2,
  131389. };
  131390. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  131391. _vq_quantthresh__44c5_s_p7_0,
  131392. _vq_quantmap__44c5_s_p7_0,
  131393. 3,
  131394. 3
  131395. };
  131396. static static_codebook _44c5_s_p7_0 = {
  131397. 4, 81,
  131398. _vq_lengthlist__44c5_s_p7_0,
  131399. 1, -529137664, 1618345984, 2, 0,
  131400. _vq_quantlist__44c5_s_p7_0,
  131401. NULL,
  131402. &_vq_auxt__44c5_s_p7_0,
  131403. NULL,
  131404. 0
  131405. };
  131406. static long _vq_quantlist__44c5_s_p7_1[] = {
  131407. 5,
  131408. 4,
  131409. 6,
  131410. 3,
  131411. 7,
  131412. 2,
  131413. 8,
  131414. 1,
  131415. 9,
  131416. 0,
  131417. 10,
  131418. };
  131419. static long _vq_lengthlist__44c5_s_p7_1[] = {
  131420. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  131421. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131422. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131423. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  131424. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131425. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  131426. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131427. 10,10,10, 8, 8, 8, 8, 8, 8,
  131428. };
  131429. static float _vq_quantthresh__44c5_s_p7_1[] = {
  131430. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131431. 3.5, 4.5,
  131432. };
  131433. static long _vq_quantmap__44c5_s_p7_1[] = {
  131434. 9, 7, 5, 3, 1, 0, 2, 4,
  131435. 6, 8, 10,
  131436. };
  131437. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  131438. _vq_quantthresh__44c5_s_p7_1,
  131439. _vq_quantmap__44c5_s_p7_1,
  131440. 11,
  131441. 11
  131442. };
  131443. static static_codebook _44c5_s_p7_1 = {
  131444. 2, 121,
  131445. _vq_lengthlist__44c5_s_p7_1,
  131446. 1, -531365888, 1611661312, 4, 0,
  131447. _vq_quantlist__44c5_s_p7_1,
  131448. NULL,
  131449. &_vq_auxt__44c5_s_p7_1,
  131450. NULL,
  131451. 0
  131452. };
  131453. static long _vq_quantlist__44c5_s_p8_0[] = {
  131454. 6,
  131455. 5,
  131456. 7,
  131457. 4,
  131458. 8,
  131459. 3,
  131460. 9,
  131461. 2,
  131462. 10,
  131463. 1,
  131464. 11,
  131465. 0,
  131466. 12,
  131467. };
  131468. static long _vq_lengthlist__44c5_s_p8_0[] = {
  131469. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131470. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  131471. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131472. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131473. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  131474. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  131475. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  131476. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131477. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  131478. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131479. 0,12,12,12,12,12,12,13,13,
  131480. };
  131481. static float _vq_quantthresh__44c5_s_p8_0[] = {
  131482. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131483. 12.5, 17.5, 22.5, 27.5,
  131484. };
  131485. static long _vq_quantmap__44c5_s_p8_0[] = {
  131486. 11, 9, 7, 5, 3, 1, 0, 2,
  131487. 4, 6, 8, 10, 12,
  131488. };
  131489. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  131490. _vq_quantthresh__44c5_s_p8_0,
  131491. _vq_quantmap__44c5_s_p8_0,
  131492. 13,
  131493. 13
  131494. };
  131495. static static_codebook _44c5_s_p8_0 = {
  131496. 2, 169,
  131497. _vq_lengthlist__44c5_s_p8_0,
  131498. 1, -526516224, 1616117760, 4, 0,
  131499. _vq_quantlist__44c5_s_p8_0,
  131500. NULL,
  131501. &_vq_auxt__44c5_s_p8_0,
  131502. NULL,
  131503. 0
  131504. };
  131505. static long _vq_quantlist__44c5_s_p8_1[] = {
  131506. 2,
  131507. 1,
  131508. 3,
  131509. 0,
  131510. 4,
  131511. };
  131512. static long _vq_lengthlist__44c5_s_p8_1[] = {
  131513. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  131514. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131515. };
  131516. static float _vq_quantthresh__44c5_s_p8_1[] = {
  131517. -1.5, -0.5, 0.5, 1.5,
  131518. };
  131519. static long _vq_quantmap__44c5_s_p8_1[] = {
  131520. 3, 1, 0, 2, 4,
  131521. };
  131522. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  131523. _vq_quantthresh__44c5_s_p8_1,
  131524. _vq_quantmap__44c5_s_p8_1,
  131525. 5,
  131526. 5
  131527. };
  131528. static static_codebook _44c5_s_p8_1 = {
  131529. 2, 25,
  131530. _vq_lengthlist__44c5_s_p8_1,
  131531. 1, -533725184, 1611661312, 3, 0,
  131532. _vq_quantlist__44c5_s_p8_1,
  131533. NULL,
  131534. &_vq_auxt__44c5_s_p8_1,
  131535. NULL,
  131536. 0
  131537. };
  131538. static long _vq_quantlist__44c5_s_p9_0[] = {
  131539. 7,
  131540. 6,
  131541. 8,
  131542. 5,
  131543. 9,
  131544. 4,
  131545. 10,
  131546. 3,
  131547. 11,
  131548. 2,
  131549. 12,
  131550. 1,
  131551. 13,
  131552. 0,
  131553. 14,
  131554. };
  131555. static long _vq_lengthlist__44c5_s_p9_0[] = {
  131556. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  131557. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  131558. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131559. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131560. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131561. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131562. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131563. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131564. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131565. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131566. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131567. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131568. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131569. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  131570. 12,
  131571. };
  131572. static float _vq_quantthresh__44c5_s_p9_0[] = {
  131573. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  131574. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  131575. };
  131576. static long _vq_quantmap__44c5_s_p9_0[] = {
  131577. 13, 11, 9, 7, 5, 3, 1, 0,
  131578. 2, 4, 6, 8, 10, 12, 14,
  131579. };
  131580. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  131581. _vq_quantthresh__44c5_s_p9_0,
  131582. _vq_quantmap__44c5_s_p9_0,
  131583. 15,
  131584. 15
  131585. };
  131586. static static_codebook _44c5_s_p9_0 = {
  131587. 2, 225,
  131588. _vq_lengthlist__44c5_s_p9_0,
  131589. 1, -512522752, 1628852224, 4, 0,
  131590. _vq_quantlist__44c5_s_p9_0,
  131591. NULL,
  131592. &_vq_auxt__44c5_s_p9_0,
  131593. NULL,
  131594. 0
  131595. };
  131596. static long _vq_quantlist__44c5_s_p9_1[] = {
  131597. 8,
  131598. 7,
  131599. 9,
  131600. 6,
  131601. 10,
  131602. 5,
  131603. 11,
  131604. 4,
  131605. 12,
  131606. 3,
  131607. 13,
  131608. 2,
  131609. 14,
  131610. 1,
  131611. 15,
  131612. 0,
  131613. 16,
  131614. };
  131615. static long _vq_lengthlist__44c5_s_p9_1[] = {
  131616. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  131617. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  131618. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  131619. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  131620. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  131621. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  131622. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  131623. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  131624. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  131625. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  131626. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  131627. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  131628. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  131629. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  131630. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  131631. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  131632. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  131633. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  131634. 15,
  131635. };
  131636. static float _vq_quantthresh__44c5_s_p9_1[] = {
  131637. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  131638. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  131639. };
  131640. static long _vq_quantmap__44c5_s_p9_1[] = {
  131641. 15, 13, 11, 9, 7, 5, 3, 1,
  131642. 0, 2, 4, 6, 8, 10, 12, 14,
  131643. 16,
  131644. };
  131645. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  131646. _vq_quantthresh__44c5_s_p9_1,
  131647. _vq_quantmap__44c5_s_p9_1,
  131648. 17,
  131649. 17
  131650. };
  131651. static static_codebook _44c5_s_p9_1 = {
  131652. 2, 289,
  131653. _vq_lengthlist__44c5_s_p9_1,
  131654. 1, -520814592, 1620377600, 5, 0,
  131655. _vq_quantlist__44c5_s_p9_1,
  131656. NULL,
  131657. &_vq_auxt__44c5_s_p9_1,
  131658. NULL,
  131659. 0
  131660. };
  131661. static long _vq_quantlist__44c5_s_p9_2[] = {
  131662. 10,
  131663. 9,
  131664. 11,
  131665. 8,
  131666. 12,
  131667. 7,
  131668. 13,
  131669. 6,
  131670. 14,
  131671. 5,
  131672. 15,
  131673. 4,
  131674. 16,
  131675. 3,
  131676. 17,
  131677. 2,
  131678. 18,
  131679. 1,
  131680. 19,
  131681. 0,
  131682. 20,
  131683. };
  131684. static long _vq_lengthlist__44c5_s_p9_2[] = {
  131685. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131686. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  131687. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  131688. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  131689. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  131690. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  131691. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  131692. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  131693. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  131694. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131695. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131696. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  131697. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  131698. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  131699. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  131700. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  131701. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131702. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131703. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  131704. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  131705. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131706. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131707. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  131708. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  131709. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  131710. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131711. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  131712. 10,10,10,10,10,10,10,10,10,
  131713. };
  131714. static float _vq_quantthresh__44c5_s_p9_2[] = {
  131715. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131716. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131717. 6.5, 7.5, 8.5, 9.5,
  131718. };
  131719. static long _vq_quantmap__44c5_s_p9_2[] = {
  131720. 19, 17, 15, 13, 11, 9, 7, 5,
  131721. 3, 1, 0, 2, 4, 6, 8, 10,
  131722. 12, 14, 16, 18, 20,
  131723. };
  131724. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  131725. _vq_quantthresh__44c5_s_p9_2,
  131726. _vq_quantmap__44c5_s_p9_2,
  131727. 21,
  131728. 21
  131729. };
  131730. static static_codebook _44c5_s_p9_2 = {
  131731. 2, 441,
  131732. _vq_lengthlist__44c5_s_p9_2,
  131733. 1, -529268736, 1611661312, 5, 0,
  131734. _vq_quantlist__44c5_s_p9_2,
  131735. NULL,
  131736. &_vq_auxt__44c5_s_p9_2,
  131737. NULL,
  131738. 0
  131739. };
  131740. static long _huff_lengthlist__44c5_s_short[] = {
  131741. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  131742. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  131743. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  131744. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  131745. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  131746. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  131747. 6, 8,11,16,
  131748. };
  131749. static static_codebook _huff_book__44c5_s_short = {
  131750. 2, 100,
  131751. _huff_lengthlist__44c5_s_short,
  131752. 0, 0, 0, 0, 0,
  131753. NULL,
  131754. NULL,
  131755. NULL,
  131756. NULL,
  131757. 0
  131758. };
  131759. static long _huff_lengthlist__44c6_s_long[] = {
  131760. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  131761. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  131762. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  131763. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  131764. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  131765. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  131766. 11,10,10,12,
  131767. };
  131768. static static_codebook _huff_book__44c6_s_long = {
  131769. 2, 100,
  131770. _huff_lengthlist__44c6_s_long,
  131771. 0, 0, 0, 0, 0,
  131772. NULL,
  131773. NULL,
  131774. NULL,
  131775. NULL,
  131776. 0
  131777. };
  131778. static long _vq_quantlist__44c6_s_p1_0[] = {
  131779. 1,
  131780. 0,
  131781. 2,
  131782. };
  131783. static long _vq_lengthlist__44c6_s_p1_0[] = {
  131784. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  131785. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  131786. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  131787. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  131788. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  131789. 8,
  131790. };
  131791. static float _vq_quantthresh__44c6_s_p1_0[] = {
  131792. -0.5, 0.5,
  131793. };
  131794. static long _vq_quantmap__44c6_s_p1_0[] = {
  131795. 1, 0, 2,
  131796. };
  131797. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  131798. _vq_quantthresh__44c6_s_p1_0,
  131799. _vq_quantmap__44c6_s_p1_0,
  131800. 3,
  131801. 3
  131802. };
  131803. static static_codebook _44c6_s_p1_0 = {
  131804. 4, 81,
  131805. _vq_lengthlist__44c6_s_p1_0,
  131806. 1, -535822336, 1611661312, 2, 0,
  131807. _vq_quantlist__44c6_s_p1_0,
  131808. NULL,
  131809. &_vq_auxt__44c6_s_p1_0,
  131810. NULL,
  131811. 0
  131812. };
  131813. static long _vq_quantlist__44c6_s_p2_0[] = {
  131814. 2,
  131815. 1,
  131816. 3,
  131817. 0,
  131818. 4,
  131819. };
  131820. static long _vq_lengthlist__44c6_s_p2_0[] = {
  131821. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  131822. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  131823. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  131824. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  131825. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  131826. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  131827. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  131828. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  131829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131830. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  131831. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  131832. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  131833. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  131834. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  131835. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  131836. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  131837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131838. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  131839. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  131840. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  131841. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  131842. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  131843. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  131844. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131846. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  131847. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  131848. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  131849. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  131850. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  131851. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  131852. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  131857. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  131858. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  131859. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  131860. 13,
  131861. };
  131862. static float _vq_quantthresh__44c6_s_p2_0[] = {
  131863. -1.5, -0.5, 0.5, 1.5,
  131864. };
  131865. static long _vq_quantmap__44c6_s_p2_0[] = {
  131866. 3, 1, 0, 2, 4,
  131867. };
  131868. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  131869. _vq_quantthresh__44c6_s_p2_0,
  131870. _vq_quantmap__44c6_s_p2_0,
  131871. 5,
  131872. 5
  131873. };
  131874. static static_codebook _44c6_s_p2_0 = {
  131875. 4, 625,
  131876. _vq_lengthlist__44c6_s_p2_0,
  131877. 1, -533725184, 1611661312, 3, 0,
  131878. _vq_quantlist__44c6_s_p2_0,
  131879. NULL,
  131880. &_vq_auxt__44c6_s_p2_0,
  131881. NULL,
  131882. 0
  131883. };
  131884. static long _vq_quantlist__44c6_s_p3_0[] = {
  131885. 4,
  131886. 3,
  131887. 5,
  131888. 2,
  131889. 6,
  131890. 1,
  131891. 7,
  131892. 0,
  131893. 8,
  131894. };
  131895. static long _vq_lengthlist__44c6_s_p3_0[] = {
  131896. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131897. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  131898. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  131899. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  131900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131901. 0,
  131902. };
  131903. static float _vq_quantthresh__44c6_s_p3_0[] = {
  131904. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131905. };
  131906. static long _vq_quantmap__44c6_s_p3_0[] = {
  131907. 7, 5, 3, 1, 0, 2, 4, 6,
  131908. 8,
  131909. };
  131910. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  131911. _vq_quantthresh__44c6_s_p3_0,
  131912. _vq_quantmap__44c6_s_p3_0,
  131913. 9,
  131914. 9
  131915. };
  131916. static static_codebook _44c6_s_p3_0 = {
  131917. 2, 81,
  131918. _vq_lengthlist__44c6_s_p3_0,
  131919. 1, -531628032, 1611661312, 4, 0,
  131920. _vq_quantlist__44c6_s_p3_0,
  131921. NULL,
  131922. &_vq_auxt__44c6_s_p3_0,
  131923. NULL,
  131924. 0
  131925. };
  131926. static long _vq_quantlist__44c6_s_p4_0[] = {
  131927. 8,
  131928. 7,
  131929. 9,
  131930. 6,
  131931. 10,
  131932. 5,
  131933. 11,
  131934. 4,
  131935. 12,
  131936. 3,
  131937. 13,
  131938. 2,
  131939. 14,
  131940. 1,
  131941. 15,
  131942. 0,
  131943. 16,
  131944. };
  131945. static long _vq_lengthlist__44c6_s_p4_0[] = {
  131946. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  131947. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  131948. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  131949. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131950. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131951. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131952. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  131953. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  131954. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  131955. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  131956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131964. 0,
  131965. };
  131966. static float _vq_quantthresh__44c6_s_p4_0[] = {
  131967. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131968. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131969. };
  131970. static long _vq_quantmap__44c6_s_p4_0[] = {
  131971. 15, 13, 11, 9, 7, 5, 3, 1,
  131972. 0, 2, 4, 6, 8, 10, 12, 14,
  131973. 16,
  131974. };
  131975. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  131976. _vq_quantthresh__44c6_s_p4_0,
  131977. _vq_quantmap__44c6_s_p4_0,
  131978. 17,
  131979. 17
  131980. };
  131981. static static_codebook _44c6_s_p4_0 = {
  131982. 2, 289,
  131983. _vq_lengthlist__44c6_s_p4_0,
  131984. 1, -529530880, 1611661312, 5, 0,
  131985. _vq_quantlist__44c6_s_p4_0,
  131986. NULL,
  131987. &_vq_auxt__44c6_s_p4_0,
  131988. NULL,
  131989. 0
  131990. };
  131991. static long _vq_quantlist__44c6_s_p5_0[] = {
  131992. 1,
  131993. 0,
  131994. 2,
  131995. };
  131996. static long _vq_lengthlist__44c6_s_p5_0[] = {
  131997. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  131998. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  131999. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132000. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132001. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132002. 12,
  132003. };
  132004. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132005. -5.5, 5.5,
  132006. };
  132007. static long _vq_quantmap__44c6_s_p5_0[] = {
  132008. 1, 0, 2,
  132009. };
  132010. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132011. _vq_quantthresh__44c6_s_p5_0,
  132012. _vq_quantmap__44c6_s_p5_0,
  132013. 3,
  132014. 3
  132015. };
  132016. static static_codebook _44c6_s_p5_0 = {
  132017. 4, 81,
  132018. _vq_lengthlist__44c6_s_p5_0,
  132019. 1, -529137664, 1618345984, 2, 0,
  132020. _vq_quantlist__44c6_s_p5_0,
  132021. NULL,
  132022. &_vq_auxt__44c6_s_p5_0,
  132023. NULL,
  132024. 0
  132025. };
  132026. static long _vq_quantlist__44c6_s_p5_1[] = {
  132027. 5,
  132028. 4,
  132029. 6,
  132030. 3,
  132031. 7,
  132032. 2,
  132033. 8,
  132034. 1,
  132035. 9,
  132036. 0,
  132037. 10,
  132038. };
  132039. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132040. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132041. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132042. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132043. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132044. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132045. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132046. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132047. 11,10,10, 7, 7, 8, 8, 8, 8,
  132048. };
  132049. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132050. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132051. 3.5, 4.5,
  132052. };
  132053. static long _vq_quantmap__44c6_s_p5_1[] = {
  132054. 9, 7, 5, 3, 1, 0, 2, 4,
  132055. 6, 8, 10,
  132056. };
  132057. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132058. _vq_quantthresh__44c6_s_p5_1,
  132059. _vq_quantmap__44c6_s_p5_1,
  132060. 11,
  132061. 11
  132062. };
  132063. static static_codebook _44c6_s_p5_1 = {
  132064. 2, 121,
  132065. _vq_lengthlist__44c6_s_p5_1,
  132066. 1, -531365888, 1611661312, 4, 0,
  132067. _vq_quantlist__44c6_s_p5_1,
  132068. NULL,
  132069. &_vq_auxt__44c6_s_p5_1,
  132070. NULL,
  132071. 0
  132072. };
  132073. static long _vq_quantlist__44c6_s_p6_0[] = {
  132074. 6,
  132075. 5,
  132076. 7,
  132077. 4,
  132078. 8,
  132079. 3,
  132080. 9,
  132081. 2,
  132082. 10,
  132083. 1,
  132084. 11,
  132085. 0,
  132086. 12,
  132087. };
  132088. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132089. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132090. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132091. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132092. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132093. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132094. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132099. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132100. };
  132101. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132102. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132103. 12.5, 17.5, 22.5, 27.5,
  132104. };
  132105. static long _vq_quantmap__44c6_s_p6_0[] = {
  132106. 11, 9, 7, 5, 3, 1, 0, 2,
  132107. 4, 6, 8, 10, 12,
  132108. };
  132109. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132110. _vq_quantthresh__44c6_s_p6_0,
  132111. _vq_quantmap__44c6_s_p6_0,
  132112. 13,
  132113. 13
  132114. };
  132115. static static_codebook _44c6_s_p6_0 = {
  132116. 2, 169,
  132117. _vq_lengthlist__44c6_s_p6_0,
  132118. 1, -526516224, 1616117760, 4, 0,
  132119. _vq_quantlist__44c6_s_p6_0,
  132120. NULL,
  132121. &_vq_auxt__44c6_s_p6_0,
  132122. NULL,
  132123. 0
  132124. };
  132125. static long _vq_quantlist__44c6_s_p6_1[] = {
  132126. 2,
  132127. 1,
  132128. 3,
  132129. 0,
  132130. 4,
  132131. };
  132132. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132133. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132134. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132135. };
  132136. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132137. -1.5, -0.5, 0.5, 1.5,
  132138. };
  132139. static long _vq_quantmap__44c6_s_p6_1[] = {
  132140. 3, 1, 0, 2, 4,
  132141. };
  132142. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132143. _vq_quantthresh__44c6_s_p6_1,
  132144. _vq_quantmap__44c6_s_p6_1,
  132145. 5,
  132146. 5
  132147. };
  132148. static static_codebook _44c6_s_p6_1 = {
  132149. 2, 25,
  132150. _vq_lengthlist__44c6_s_p6_1,
  132151. 1, -533725184, 1611661312, 3, 0,
  132152. _vq_quantlist__44c6_s_p6_1,
  132153. NULL,
  132154. &_vq_auxt__44c6_s_p6_1,
  132155. NULL,
  132156. 0
  132157. };
  132158. static long _vq_quantlist__44c6_s_p7_0[] = {
  132159. 6,
  132160. 5,
  132161. 7,
  132162. 4,
  132163. 8,
  132164. 3,
  132165. 9,
  132166. 2,
  132167. 10,
  132168. 1,
  132169. 11,
  132170. 0,
  132171. 12,
  132172. };
  132173. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132174. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132175. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132176. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132177. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132178. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132179. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132180. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132181. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132182. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132183. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132184. 20,13,13,13,13,13,13,14,14,
  132185. };
  132186. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132187. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132188. 27.5, 38.5, 49.5, 60.5,
  132189. };
  132190. static long _vq_quantmap__44c6_s_p7_0[] = {
  132191. 11, 9, 7, 5, 3, 1, 0, 2,
  132192. 4, 6, 8, 10, 12,
  132193. };
  132194. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132195. _vq_quantthresh__44c6_s_p7_0,
  132196. _vq_quantmap__44c6_s_p7_0,
  132197. 13,
  132198. 13
  132199. };
  132200. static static_codebook _44c6_s_p7_0 = {
  132201. 2, 169,
  132202. _vq_lengthlist__44c6_s_p7_0,
  132203. 1, -523206656, 1618345984, 4, 0,
  132204. _vq_quantlist__44c6_s_p7_0,
  132205. NULL,
  132206. &_vq_auxt__44c6_s_p7_0,
  132207. NULL,
  132208. 0
  132209. };
  132210. static long _vq_quantlist__44c6_s_p7_1[] = {
  132211. 5,
  132212. 4,
  132213. 6,
  132214. 3,
  132215. 7,
  132216. 2,
  132217. 8,
  132218. 1,
  132219. 9,
  132220. 0,
  132221. 10,
  132222. };
  132223. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132224. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132225. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132226. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132227. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132228. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132229. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132230. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132231. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132232. };
  132233. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132234. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132235. 3.5, 4.5,
  132236. };
  132237. static long _vq_quantmap__44c6_s_p7_1[] = {
  132238. 9, 7, 5, 3, 1, 0, 2, 4,
  132239. 6, 8, 10,
  132240. };
  132241. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132242. _vq_quantthresh__44c6_s_p7_1,
  132243. _vq_quantmap__44c6_s_p7_1,
  132244. 11,
  132245. 11
  132246. };
  132247. static static_codebook _44c6_s_p7_1 = {
  132248. 2, 121,
  132249. _vq_lengthlist__44c6_s_p7_1,
  132250. 1, -531365888, 1611661312, 4, 0,
  132251. _vq_quantlist__44c6_s_p7_1,
  132252. NULL,
  132253. &_vq_auxt__44c6_s_p7_1,
  132254. NULL,
  132255. 0
  132256. };
  132257. static long _vq_quantlist__44c6_s_p8_0[] = {
  132258. 7,
  132259. 6,
  132260. 8,
  132261. 5,
  132262. 9,
  132263. 4,
  132264. 10,
  132265. 3,
  132266. 11,
  132267. 2,
  132268. 12,
  132269. 1,
  132270. 13,
  132271. 0,
  132272. 14,
  132273. };
  132274. static long _vq_lengthlist__44c6_s_p8_0[] = {
  132275. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  132276. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  132277. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  132278. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  132279. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  132280. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  132281. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  132282. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  132283. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  132284. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  132285. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  132286. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  132287. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  132288. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  132289. 14,
  132290. };
  132291. static float _vq_quantthresh__44c6_s_p8_0[] = {
  132292. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132293. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132294. };
  132295. static long _vq_quantmap__44c6_s_p8_0[] = {
  132296. 13, 11, 9, 7, 5, 3, 1, 0,
  132297. 2, 4, 6, 8, 10, 12, 14,
  132298. };
  132299. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  132300. _vq_quantthresh__44c6_s_p8_0,
  132301. _vq_quantmap__44c6_s_p8_0,
  132302. 15,
  132303. 15
  132304. };
  132305. static static_codebook _44c6_s_p8_0 = {
  132306. 2, 225,
  132307. _vq_lengthlist__44c6_s_p8_0,
  132308. 1, -520986624, 1620377600, 4, 0,
  132309. _vq_quantlist__44c6_s_p8_0,
  132310. NULL,
  132311. &_vq_auxt__44c6_s_p8_0,
  132312. NULL,
  132313. 0
  132314. };
  132315. static long _vq_quantlist__44c6_s_p8_1[] = {
  132316. 10,
  132317. 9,
  132318. 11,
  132319. 8,
  132320. 12,
  132321. 7,
  132322. 13,
  132323. 6,
  132324. 14,
  132325. 5,
  132326. 15,
  132327. 4,
  132328. 16,
  132329. 3,
  132330. 17,
  132331. 2,
  132332. 18,
  132333. 1,
  132334. 19,
  132335. 0,
  132336. 20,
  132337. };
  132338. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132339. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132340. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132341. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132342. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132343. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132344. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132345. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132346. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132347. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132348. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132349. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132350. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132351. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132352. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132353. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132354. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132355. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132356. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132357. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132358. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132359. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132360. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132361. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132362. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132363. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132364. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132365. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132366. 10,10,10,10,10,10,10,10,10,
  132367. };
  132368. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132369. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132370. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132371. 6.5, 7.5, 8.5, 9.5,
  132372. };
  132373. static long _vq_quantmap__44c6_s_p8_1[] = {
  132374. 19, 17, 15, 13, 11, 9, 7, 5,
  132375. 3, 1, 0, 2, 4, 6, 8, 10,
  132376. 12, 14, 16, 18, 20,
  132377. };
  132378. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  132379. _vq_quantthresh__44c6_s_p8_1,
  132380. _vq_quantmap__44c6_s_p8_1,
  132381. 21,
  132382. 21
  132383. };
  132384. static static_codebook _44c6_s_p8_1 = {
  132385. 2, 441,
  132386. _vq_lengthlist__44c6_s_p8_1,
  132387. 1, -529268736, 1611661312, 5, 0,
  132388. _vq_quantlist__44c6_s_p8_1,
  132389. NULL,
  132390. &_vq_auxt__44c6_s_p8_1,
  132391. NULL,
  132392. 0
  132393. };
  132394. static long _vq_quantlist__44c6_s_p9_0[] = {
  132395. 6,
  132396. 5,
  132397. 7,
  132398. 4,
  132399. 8,
  132400. 3,
  132401. 9,
  132402. 2,
  132403. 10,
  132404. 1,
  132405. 11,
  132406. 0,
  132407. 12,
  132408. };
  132409. static long _vq_lengthlist__44c6_s_p9_0[] = {
  132410. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  132411. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  132412. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132413. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132414. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132415. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132416. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132417. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132418. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132419. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132420. 10,10,10,10,10,10,10,10,10,
  132421. };
  132422. static float _vq_quantthresh__44c6_s_p9_0[] = {
  132423. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132424. 1592.5, 2229.5, 2866.5, 3503.5,
  132425. };
  132426. static long _vq_quantmap__44c6_s_p9_0[] = {
  132427. 11, 9, 7, 5, 3, 1, 0, 2,
  132428. 4, 6, 8, 10, 12,
  132429. };
  132430. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  132431. _vq_quantthresh__44c6_s_p9_0,
  132432. _vq_quantmap__44c6_s_p9_0,
  132433. 13,
  132434. 13
  132435. };
  132436. static static_codebook _44c6_s_p9_0 = {
  132437. 2, 169,
  132438. _vq_lengthlist__44c6_s_p9_0,
  132439. 1, -511845376, 1630791680, 4, 0,
  132440. _vq_quantlist__44c6_s_p9_0,
  132441. NULL,
  132442. &_vq_auxt__44c6_s_p9_0,
  132443. NULL,
  132444. 0
  132445. };
  132446. static long _vq_quantlist__44c6_s_p9_1[] = {
  132447. 6,
  132448. 5,
  132449. 7,
  132450. 4,
  132451. 8,
  132452. 3,
  132453. 9,
  132454. 2,
  132455. 10,
  132456. 1,
  132457. 11,
  132458. 0,
  132459. 12,
  132460. };
  132461. static long _vq_lengthlist__44c6_s_p9_1[] = {
  132462. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  132463. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  132464. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  132465. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  132466. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  132467. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  132468. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  132469. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  132470. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  132471. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  132472. 15,12,10,11,11,13,11,12,13,
  132473. };
  132474. static float _vq_quantthresh__44c6_s_p9_1[] = {
  132475. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  132476. 122.5, 171.5, 220.5, 269.5,
  132477. };
  132478. static long _vq_quantmap__44c6_s_p9_1[] = {
  132479. 11, 9, 7, 5, 3, 1, 0, 2,
  132480. 4, 6, 8, 10, 12,
  132481. };
  132482. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  132483. _vq_quantthresh__44c6_s_p9_1,
  132484. _vq_quantmap__44c6_s_p9_1,
  132485. 13,
  132486. 13
  132487. };
  132488. static static_codebook _44c6_s_p9_1 = {
  132489. 2, 169,
  132490. _vq_lengthlist__44c6_s_p9_1,
  132491. 1, -518889472, 1622704128, 4, 0,
  132492. _vq_quantlist__44c6_s_p9_1,
  132493. NULL,
  132494. &_vq_auxt__44c6_s_p9_1,
  132495. NULL,
  132496. 0
  132497. };
  132498. static long _vq_quantlist__44c6_s_p9_2[] = {
  132499. 24,
  132500. 23,
  132501. 25,
  132502. 22,
  132503. 26,
  132504. 21,
  132505. 27,
  132506. 20,
  132507. 28,
  132508. 19,
  132509. 29,
  132510. 18,
  132511. 30,
  132512. 17,
  132513. 31,
  132514. 16,
  132515. 32,
  132516. 15,
  132517. 33,
  132518. 14,
  132519. 34,
  132520. 13,
  132521. 35,
  132522. 12,
  132523. 36,
  132524. 11,
  132525. 37,
  132526. 10,
  132527. 38,
  132528. 9,
  132529. 39,
  132530. 8,
  132531. 40,
  132532. 7,
  132533. 41,
  132534. 6,
  132535. 42,
  132536. 5,
  132537. 43,
  132538. 4,
  132539. 44,
  132540. 3,
  132541. 45,
  132542. 2,
  132543. 46,
  132544. 1,
  132545. 47,
  132546. 0,
  132547. 48,
  132548. };
  132549. static long _vq_lengthlist__44c6_s_p9_2[] = {
  132550. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  132551. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132552. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132553. 7,
  132554. };
  132555. static float _vq_quantthresh__44c6_s_p9_2[] = {
  132556. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  132557. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  132558. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132559. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132560. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  132561. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  132562. };
  132563. static long _vq_quantmap__44c6_s_p9_2[] = {
  132564. 47, 45, 43, 41, 39, 37, 35, 33,
  132565. 31, 29, 27, 25, 23, 21, 19, 17,
  132566. 15, 13, 11, 9, 7, 5, 3, 1,
  132567. 0, 2, 4, 6, 8, 10, 12, 14,
  132568. 16, 18, 20, 22, 24, 26, 28, 30,
  132569. 32, 34, 36, 38, 40, 42, 44, 46,
  132570. 48,
  132571. };
  132572. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  132573. _vq_quantthresh__44c6_s_p9_2,
  132574. _vq_quantmap__44c6_s_p9_2,
  132575. 49,
  132576. 49
  132577. };
  132578. static static_codebook _44c6_s_p9_2 = {
  132579. 1, 49,
  132580. _vq_lengthlist__44c6_s_p9_2,
  132581. 1, -526909440, 1611661312, 6, 0,
  132582. _vq_quantlist__44c6_s_p9_2,
  132583. NULL,
  132584. &_vq_auxt__44c6_s_p9_2,
  132585. NULL,
  132586. 0
  132587. };
  132588. static long _huff_lengthlist__44c6_s_short[] = {
  132589. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  132590. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  132591. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  132592. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  132593. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  132594. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  132595. 9,10,17,18,
  132596. };
  132597. static static_codebook _huff_book__44c6_s_short = {
  132598. 2, 100,
  132599. _huff_lengthlist__44c6_s_short,
  132600. 0, 0, 0, 0, 0,
  132601. NULL,
  132602. NULL,
  132603. NULL,
  132604. NULL,
  132605. 0
  132606. };
  132607. static long _huff_lengthlist__44c7_s_long[] = {
  132608. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  132609. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  132610. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  132611. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  132612. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  132613. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  132614. 11,10,10,12,
  132615. };
  132616. static static_codebook _huff_book__44c7_s_long = {
  132617. 2, 100,
  132618. _huff_lengthlist__44c7_s_long,
  132619. 0, 0, 0, 0, 0,
  132620. NULL,
  132621. NULL,
  132622. NULL,
  132623. NULL,
  132624. 0
  132625. };
  132626. static long _vq_quantlist__44c7_s_p1_0[] = {
  132627. 1,
  132628. 0,
  132629. 2,
  132630. };
  132631. static long _vq_lengthlist__44c7_s_p1_0[] = {
  132632. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132633. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132634. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132635. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132636. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  132637. 8,
  132638. };
  132639. static float _vq_quantthresh__44c7_s_p1_0[] = {
  132640. -0.5, 0.5,
  132641. };
  132642. static long _vq_quantmap__44c7_s_p1_0[] = {
  132643. 1, 0, 2,
  132644. };
  132645. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  132646. _vq_quantthresh__44c7_s_p1_0,
  132647. _vq_quantmap__44c7_s_p1_0,
  132648. 3,
  132649. 3
  132650. };
  132651. static static_codebook _44c7_s_p1_0 = {
  132652. 4, 81,
  132653. _vq_lengthlist__44c7_s_p1_0,
  132654. 1, -535822336, 1611661312, 2, 0,
  132655. _vq_quantlist__44c7_s_p1_0,
  132656. NULL,
  132657. &_vq_auxt__44c7_s_p1_0,
  132658. NULL,
  132659. 0
  132660. };
  132661. static long _vq_quantlist__44c7_s_p2_0[] = {
  132662. 2,
  132663. 1,
  132664. 3,
  132665. 0,
  132666. 4,
  132667. };
  132668. static long _vq_lengthlist__44c7_s_p2_0[] = {
  132669. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132670. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132671. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132672. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132673. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  132674. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132675. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  132676. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132678. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132679. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132680. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132681. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132682. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132683. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  132684. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132686. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132687. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  132688. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  132689. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  132690. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  132691. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132692. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132694. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  132695. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132696. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132697. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  132698. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132699. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  132700. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132705. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  132706. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  132707. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132708. 13,
  132709. };
  132710. static float _vq_quantthresh__44c7_s_p2_0[] = {
  132711. -1.5, -0.5, 0.5, 1.5,
  132712. };
  132713. static long _vq_quantmap__44c7_s_p2_0[] = {
  132714. 3, 1, 0, 2, 4,
  132715. };
  132716. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  132717. _vq_quantthresh__44c7_s_p2_0,
  132718. _vq_quantmap__44c7_s_p2_0,
  132719. 5,
  132720. 5
  132721. };
  132722. static static_codebook _44c7_s_p2_0 = {
  132723. 4, 625,
  132724. _vq_lengthlist__44c7_s_p2_0,
  132725. 1, -533725184, 1611661312, 3, 0,
  132726. _vq_quantlist__44c7_s_p2_0,
  132727. NULL,
  132728. &_vq_auxt__44c7_s_p2_0,
  132729. NULL,
  132730. 0
  132731. };
  132732. static long _vq_quantlist__44c7_s_p3_0[] = {
  132733. 4,
  132734. 3,
  132735. 5,
  132736. 2,
  132737. 6,
  132738. 1,
  132739. 7,
  132740. 0,
  132741. 8,
  132742. };
  132743. static long _vq_lengthlist__44c7_s_p3_0[] = {
  132744. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132745. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  132746. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  132747. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  132748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132749. 0,
  132750. };
  132751. static float _vq_quantthresh__44c7_s_p3_0[] = {
  132752. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132753. };
  132754. static long _vq_quantmap__44c7_s_p3_0[] = {
  132755. 7, 5, 3, 1, 0, 2, 4, 6,
  132756. 8,
  132757. };
  132758. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  132759. _vq_quantthresh__44c7_s_p3_0,
  132760. _vq_quantmap__44c7_s_p3_0,
  132761. 9,
  132762. 9
  132763. };
  132764. static static_codebook _44c7_s_p3_0 = {
  132765. 2, 81,
  132766. _vq_lengthlist__44c7_s_p3_0,
  132767. 1, -531628032, 1611661312, 4, 0,
  132768. _vq_quantlist__44c7_s_p3_0,
  132769. NULL,
  132770. &_vq_auxt__44c7_s_p3_0,
  132771. NULL,
  132772. 0
  132773. };
  132774. static long _vq_quantlist__44c7_s_p4_0[] = {
  132775. 8,
  132776. 7,
  132777. 9,
  132778. 6,
  132779. 10,
  132780. 5,
  132781. 11,
  132782. 4,
  132783. 12,
  132784. 3,
  132785. 13,
  132786. 2,
  132787. 14,
  132788. 1,
  132789. 15,
  132790. 0,
  132791. 16,
  132792. };
  132793. static long _vq_lengthlist__44c7_s_p4_0[] = {
  132794. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  132795. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  132796. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  132797. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  132798. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  132799. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  132800. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  132801. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132802. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  132803. 9,10,10,11,11,12,12,13,13, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132806. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132812. 0,
  132813. };
  132814. static float _vq_quantthresh__44c7_s_p4_0[] = {
  132815. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132816. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132817. };
  132818. static long _vq_quantmap__44c7_s_p4_0[] = {
  132819. 15, 13, 11, 9, 7, 5, 3, 1,
  132820. 0, 2, 4, 6, 8, 10, 12, 14,
  132821. 16,
  132822. };
  132823. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  132824. _vq_quantthresh__44c7_s_p4_0,
  132825. _vq_quantmap__44c7_s_p4_0,
  132826. 17,
  132827. 17
  132828. };
  132829. static static_codebook _44c7_s_p4_0 = {
  132830. 2, 289,
  132831. _vq_lengthlist__44c7_s_p4_0,
  132832. 1, -529530880, 1611661312, 5, 0,
  132833. _vq_quantlist__44c7_s_p4_0,
  132834. NULL,
  132835. &_vq_auxt__44c7_s_p4_0,
  132836. NULL,
  132837. 0
  132838. };
  132839. static long _vq_quantlist__44c7_s_p5_0[] = {
  132840. 1,
  132841. 0,
  132842. 2,
  132843. };
  132844. static long _vq_lengthlist__44c7_s_p5_0[] = {
  132845. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  132846. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  132847. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  132848. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132849. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  132850. 12,
  132851. };
  132852. static float _vq_quantthresh__44c7_s_p5_0[] = {
  132853. -5.5, 5.5,
  132854. };
  132855. static long _vq_quantmap__44c7_s_p5_0[] = {
  132856. 1, 0, 2,
  132857. };
  132858. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  132859. _vq_quantthresh__44c7_s_p5_0,
  132860. _vq_quantmap__44c7_s_p5_0,
  132861. 3,
  132862. 3
  132863. };
  132864. static static_codebook _44c7_s_p5_0 = {
  132865. 4, 81,
  132866. _vq_lengthlist__44c7_s_p5_0,
  132867. 1, -529137664, 1618345984, 2, 0,
  132868. _vq_quantlist__44c7_s_p5_0,
  132869. NULL,
  132870. &_vq_auxt__44c7_s_p5_0,
  132871. NULL,
  132872. 0
  132873. };
  132874. static long _vq_quantlist__44c7_s_p5_1[] = {
  132875. 5,
  132876. 4,
  132877. 6,
  132878. 3,
  132879. 7,
  132880. 2,
  132881. 8,
  132882. 1,
  132883. 9,
  132884. 0,
  132885. 10,
  132886. };
  132887. static long _vq_lengthlist__44c7_s_p5_1[] = {
  132888. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132889. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  132890. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  132891. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  132892. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  132893. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  132894. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  132895. 11,11,11, 7, 7, 8, 8, 8, 8,
  132896. };
  132897. static float _vq_quantthresh__44c7_s_p5_1[] = {
  132898. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132899. 3.5, 4.5,
  132900. };
  132901. static long _vq_quantmap__44c7_s_p5_1[] = {
  132902. 9, 7, 5, 3, 1, 0, 2, 4,
  132903. 6, 8, 10,
  132904. };
  132905. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  132906. _vq_quantthresh__44c7_s_p5_1,
  132907. _vq_quantmap__44c7_s_p5_1,
  132908. 11,
  132909. 11
  132910. };
  132911. static static_codebook _44c7_s_p5_1 = {
  132912. 2, 121,
  132913. _vq_lengthlist__44c7_s_p5_1,
  132914. 1, -531365888, 1611661312, 4, 0,
  132915. _vq_quantlist__44c7_s_p5_1,
  132916. NULL,
  132917. &_vq_auxt__44c7_s_p5_1,
  132918. NULL,
  132919. 0
  132920. };
  132921. static long _vq_quantlist__44c7_s_p6_0[] = {
  132922. 6,
  132923. 5,
  132924. 7,
  132925. 4,
  132926. 8,
  132927. 3,
  132928. 9,
  132929. 2,
  132930. 10,
  132931. 1,
  132932. 11,
  132933. 0,
  132934. 12,
  132935. };
  132936. static long _vq_lengthlist__44c7_s_p6_0[] = {
  132937. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  132938. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  132939. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  132940. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  132941. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  132942. 12, 9, 9,10,10,11,11,11,11,12,12, 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,
  132948. };
  132949. static float _vq_quantthresh__44c7_s_p6_0[] = {
  132950. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132951. 12.5, 17.5, 22.5, 27.5,
  132952. };
  132953. static long _vq_quantmap__44c7_s_p6_0[] = {
  132954. 11, 9, 7, 5, 3, 1, 0, 2,
  132955. 4, 6, 8, 10, 12,
  132956. };
  132957. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  132958. _vq_quantthresh__44c7_s_p6_0,
  132959. _vq_quantmap__44c7_s_p6_0,
  132960. 13,
  132961. 13
  132962. };
  132963. static static_codebook _44c7_s_p6_0 = {
  132964. 2, 169,
  132965. _vq_lengthlist__44c7_s_p6_0,
  132966. 1, -526516224, 1616117760, 4, 0,
  132967. _vq_quantlist__44c7_s_p6_0,
  132968. NULL,
  132969. &_vq_auxt__44c7_s_p6_0,
  132970. NULL,
  132971. 0
  132972. };
  132973. static long _vq_quantlist__44c7_s_p6_1[] = {
  132974. 2,
  132975. 1,
  132976. 3,
  132977. 0,
  132978. 4,
  132979. };
  132980. static long _vq_lengthlist__44c7_s_p6_1[] = {
  132981. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132982. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132983. };
  132984. static float _vq_quantthresh__44c7_s_p6_1[] = {
  132985. -1.5, -0.5, 0.5, 1.5,
  132986. };
  132987. static long _vq_quantmap__44c7_s_p6_1[] = {
  132988. 3, 1, 0, 2, 4,
  132989. };
  132990. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  132991. _vq_quantthresh__44c7_s_p6_1,
  132992. _vq_quantmap__44c7_s_p6_1,
  132993. 5,
  132994. 5
  132995. };
  132996. static static_codebook _44c7_s_p6_1 = {
  132997. 2, 25,
  132998. _vq_lengthlist__44c7_s_p6_1,
  132999. 1, -533725184, 1611661312, 3, 0,
  133000. _vq_quantlist__44c7_s_p6_1,
  133001. NULL,
  133002. &_vq_auxt__44c7_s_p6_1,
  133003. NULL,
  133004. 0
  133005. };
  133006. static long _vq_quantlist__44c7_s_p7_0[] = {
  133007. 6,
  133008. 5,
  133009. 7,
  133010. 4,
  133011. 8,
  133012. 3,
  133013. 9,
  133014. 2,
  133015. 10,
  133016. 1,
  133017. 11,
  133018. 0,
  133019. 12,
  133020. };
  133021. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133022. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133023. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133024. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133025. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133026. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133027. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133028. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133029. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133030. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133031. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133032. 19,13,13,13,13,14,14,15,15,
  133033. };
  133034. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133035. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133036. 27.5, 38.5, 49.5, 60.5,
  133037. };
  133038. static long _vq_quantmap__44c7_s_p7_0[] = {
  133039. 11, 9, 7, 5, 3, 1, 0, 2,
  133040. 4, 6, 8, 10, 12,
  133041. };
  133042. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133043. _vq_quantthresh__44c7_s_p7_0,
  133044. _vq_quantmap__44c7_s_p7_0,
  133045. 13,
  133046. 13
  133047. };
  133048. static static_codebook _44c7_s_p7_0 = {
  133049. 2, 169,
  133050. _vq_lengthlist__44c7_s_p7_0,
  133051. 1, -523206656, 1618345984, 4, 0,
  133052. _vq_quantlist__44c7_s_p7_0,
  133053. NULL,
  133054. &_vq_auxt__44c7_s_p7_0,
  133055. NULL,
  133056. 0
  133057. };
  133058. static long _vq_quantlist__44c7_s_p7_1[] = {
  133059. 5,
  133060. 4,
  133061. 6,
  133062. 3,
  133063. 7,
  133064. 2,
  133065. 8,
  133066. 1,
  133067. 9,
  133068. 0,
  133069. 10,
  133070. };
  133071. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133072. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133073. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133074. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133075. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133076. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133077. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133078. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133079. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133080. };
  133081. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133082. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133083. 3.5, 4.5,
  133084. };
  133085. static long _vq_quantmap__44c7_s_p7_1[] = {
  133086. 9, 7, 5, 3, 1, 0, 2, 4,
  133087. 6, 8, 10,
  133088. };
  133089. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133090. _vq_quantthresh__44c7_s_p7_1,
  133091. _vq_quantmap__44c7_s_p7_1,
  133092. 11,
  133093. 11
  133094. };
  133095. static static_codebook _44c7_s_p7_1 = {
  133096. 2, 121,
  133097. _vq_lengthlist__44c7_s_p7_1,
  133098. 1, -531365888, 1611661312, 4, 0,
  133099. _vq_quantlist__44c7_s_p7_1,
  133100. NULL,
  133101. &_vq_auxt__44c7_s_p7_1,
  133102. NULL,
  133103. 0
  133104. };
  133105. static long _vq_quantlist__44c7_s_p8_0[] = {
  133106. 7,
  133107. 6,
  133108. 8,
  133109. 5,
  133110. 9,
  133111. 4,
  133112. 10,
  133113. 3,
  133114. 11,
  133115. 2,
  133116. 12,
  133117. 1,
  133118. 13,
  133119. 0,
  133120. 14,
  133121. };
  133122. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133123. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133124. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133125. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133126. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133127. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133128. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133129. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133130. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133131. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133132. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133133. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133134. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133135. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133136. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133137. 14,
  133138. };
  133139. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133140. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133141. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133142. };
  133143. static long _vq_quantmap__44c7_s_p8_0[] = {
  133144. 13, 11, 9, 7, 5, 3, 1, 0,
  133145. 2, 4, 6, 8, 10, 12, 14,
  133146. };
  133147. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133148. _vq_quantthresh__44c7_s_p8_0,
  133149. _vq_quantmap__44c7_s_p8_0,
  133150. 15,
  133151. 15
  133152. };
  133153. static static_codebook _44c7_s_p8_0 = {
  133154. 2, 225,
  133155. _vq_lengthlist__44c7_s_p8_0,
  133156. 1, -520986624, 1620377600, 4, 0,
  133157. _vq_quantlist__44c7_s_p8_0,
  133158. NULL,
  133159. &_vq_auxt__44c7_s_p8_0,
  133160. NULL,
  133161. 0
  133162. };
  133163. static long _vq_quantlist__44c7_s_p8_1[] = {
  133164. 10,
  133165. 9,
  133166. 11,
  133167. 8,
  133168. 12,
  133169. 7,
  133170. 13,
  133171. 6,
  133172. 14,
  133173. 5,
  133174. 15,
  133175. 4,
  133176. 16,
  133177. 3,
  133178. 17,
  133179. 2,
  133180. 18,
  133181. 1,
  133182. 19,
  133183. 0,
  133184. 20,
  133185. };
  133186. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133187. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133188. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133189. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133190. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133191. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133192. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133193. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133194. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133195. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133196. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133197. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133198. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133199. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133200. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133201. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133202. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133203. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133204. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133205. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133206. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133207. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133208. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133209. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133210. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133211. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133212. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133213. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133214. 10,10,10,10,10,10,10,10,10,
  133215. };
  133216. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133217. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133218. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133219. 6.5, 7.5, 8.5, 9.5,
  133220. };
  133221. static long _vq_quantmap__44c7_s_p8_1[] = {
  133222. 19, 17, 15, 13, 11, 9, 7, 5,
  133223. 3, 1, 0, 2, 4, 6, 8, 10,
  133224. 12, 14, 16, 18, 20,
  133225. };
  133226. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133227. _vq_quantthresh__44c7_s_p8_1,
  133228. _vq_quantmap__44c7_s_p8_1,
  133229. 21,
  133230. 21
  133231. };
  133232. static static_codebook _44c7_s_p8_1 = {
  133233. 2, 441,
  133234. _vq_lengthlist__44c7_s_p8_1,
  133235. 1, -529268736, 1611661312, 5, 0,
  133236. _vq_quantlist__44c7_s_p8_1,
  133237. NULL,
  133238. &_vq_auxt__44c7_s_p8_1,
  133239. NULL,
  133240. 0
  133241. };
  133242. static long _vq_quantlist__44c7_s_p9_0[] = {
  133243. 6,
  133244. 5,
  133245. 7,
  133246. 4,
  133247. 8,
  133248. 3,
  133249. 9,
  133250. 2,
  133251. 10,
  133252. 1,
  133253. 11,
  133254. 0,
  133255. 12,
  133256. };
  133257. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133258. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133259. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133260. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133261. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133262. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133263. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133264. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133265. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133266. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133267. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133268. 11,11,11,11,11,11,11,11,11,
  133269. };
  133270. static float _vq_quantthresh__44c7_s_p9_0[] = {
  133271. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133272. 1592.5, 2229.5, 2866.5, 3503.5,
  133273. };
  133274. static long _vq_quantmap__44c7_s_p9_0[] = {
  133275. 11, 9, 7, 5, 3, 1, 0, 2,
  133276. 4, 6, 8, 10, 12,
  133277. };
  133278. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  133279. _vq_quantthresh__44c7_s_p9_0,
  133280. _vq_quantmap__44c7_s_p9_0,
  133281. 13,
  133282. 13
  133283. };
  133284. static static_codebook _44c7_s_p9_0 = {
  133285. 2, 169,
  133286. _vq_lengthlist__44c7_s_p9_0,
  133287. 1, -511845376, 1630791680, 4, 0,
  133288. _vq_quantlist__44c7_s_p9_0,
  133289. NULL,
  133290. &_vq_auxt__44c7_s_p9_0,
  133291. NULL,
  133292. 0
  133293. };
  133294. static long _vq_quantlist__44c7_s_p9_1[] = {
  133295. 6,
  133296. 5,
  133297. 7,
  133298. 4,
  133299. 8,
  133300. 3,
  133301. 9,
  133302. 2,
  133303. 10,
  133304. 1,
  133305. 11,
  133306. 0,
  133307. 12,
  133308. };
  133309. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133310. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133311. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133312. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133313. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133314. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133315. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133316. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133317. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133318. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133319. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133320. 15,11,11,10,10,12,12,12,12,
  133321. };
  133322. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133323. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133324. 122.5, 171.5, 220.5, 269.5,
  133325. };
  133326. static long _vq_quantmap__44c7_s_p9_1[] = {
  133327. 11, 9, 7, 5, 3, 1, 0, 2,
  133328. 4, 6, 8, 10, 12,
  133329. };
  133330. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133331. _vq_quantthresh__44c7_s_p9_1,
  133332. _vq_quantmap__44c7_s_p9_1,
  133333. 13,
  133334. 13
  133335. };
  133336. static static_codebook _44c7_s_p9_1 = {
  133337. 2, 169,
  133338. _vq_lengthlist__44c7_s_p9_1,
  133339. 1, -518889472, 1622704128, 4, 0,
  133340. _vq_quantlist__44c7_s_p9_1,
  133341. NULL,
  133342. &_vq_auxt__44c7_s_p9_1,
  133343. NULL,
  133344. 0
  133345. };
  133346. static long _vq_quantlist__44c7_s_p9_2[] = {
  133347. 24,
  133348. 23,
  133349. 25,
  133350. 22,
  133351. 26,
  133352. 21,
  133353. 27,
  133354. 20,
  133355. 28,
  133356. 19,
  133357. 29,
  133358. 18,
  133359. 30,
  133360. 17,
  133361. 31,
  133362. 16,
  133363. 32,
  133364. 15,
  133365. 33,
  133366. 14,
  133367. 34,
  133368. 13,
  133369. 35,
  133370. 12,
  133371. 36,
  133372. 11,
  133373. 37,
  133374. 10,
  133375. 38,
  133376. 9,
  133377. 39,
  133378. 8,
  133379. 40,
  133380. 7,
  133381. 41,
  133382. 6,
  133383. 42,
  133384. 5,
  133385. 43,
  133386. 4,
  133387. 44,
  133388. 3,
  133389. 45,
  133390. 2,
  133391. 46,
  133392. 1,
  133393. 47,
  133394. 0,
  133395. 48,
  133396. };
  133397. static long _vq_lengthlist__44c7_s_p9_2[] = {
  133398. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133399. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133400. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133401. 7,
  133402. };
  133403. static float _vq_quantthresh__44c7_s_p9_2[] = {
  133404. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133405. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133406. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133407. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133408. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133409. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133410. };
  133411. static long _vq_quantmap__44c7_s_p9_2[] = {
  133412. 47, 45, 43, 41, 39, 37, 35, 33,
  133413. 31, 29, 27, 25, 23, 21, 19, 17,
  133414. 15, 13, 11, 9, 7, 5, 3, 1,
  133415. 0, 2, 4, 6, 8, 10, 12, 14,
  133416. 16, 18, 20, 22, 24, 26, 28, 30,
  133417. 32, 34, 36, 38, 40, 42, 44, 46,
  133418. 48,
  133419. };
  133420. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  133421. _vq_quantthresh__44c7_s_p9_2,
  133422. _vq_quantmap__44c7_s_p9_2,
  133423. 49,
  133424. 49
  133425. };
  133426. static static_codebook _44c7_s_p9_2 = {
  133427. 1, 49,
  133428. _vq_lengthlist__44c7_s_p9_2,
  133429. 1, -526909440, 1611661312, 6, 0,
  133430. _vq_quantlist__44c7_s_p9_2,
  133431. NULL,
  133432. &_vq_auxt__44c7_s_p9_2,
  133433. NULL,
  133434. 0
  133435. };
  133436. static long _huff_lengthlist__44c7_s_short[] = {
  133437. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  133438. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  133439. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  133440. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  133441. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  133442. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  133443. 10, 9,11,14,
  133444. };
  133445. static static_codebook _huff_book__44c7_s_short = {
  133446. 2, 100,
  133447. _huff_lengthlist__44c7_s_short,
  133448. 0, 0, 0, 0, 0,
  133449. NULL,
  133450. NULL,
  133451. NULL,
  133452. NULL,
  133453. 0
  133454. };
  133455. static long _huff_lengthlist__44c8_s_long[] = {
  133456. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  133457. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  133458. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  133459. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  133460. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  133461. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  133462. 11, 9, 9,10,
  133463. };
  133464. static static_codebook _huff_book__44c8_s_long = {
  133465. 2, 100,
  133466. _huff_lengthlist__44c8_s_long,
  133467. 0, 0, 0, 0, 0,
  133468. NULL,
  133469. NULL,
  133470. NULL,
  133471. NULL,
  133472. 0
  133473. };
  133474. static long _vq_quantlist__44c8_s_p1_0[] = {
  133475. 1,
  133476. 0,
  133477. 2,
  133478. };
  133479. static long _vq_lengthlist__44c8_s_p1_0[] = {
  133480. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  133481. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133482. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133483. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133484. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133485. 8,
  133486. };
  133487. static float _vq_quantthresh__44c8_s_p1_0[] = {
  133488. -0.5, 0.5,
  133489. };
  133490. static long _vq_quantmap__44c8_s_p1_0[] = {
  133491. 1, 0, 2,
  133492. };
  133493. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  133494. _vq_quantthresh__44c8_s_p1_0,
  133495. _vq_quantmap__44c8_s_p1_0,
  133496. 3,
  133497. 3
  133498. };
  133499. static static_codebook _44c8_s_p1_0 = {
  133500. 4, 81,
  133501. _vq_lengthlist__44c8_s_p1_0,
  133502. 1, -535822336, 1611661312, 2, 0,
  133503. _vq_quantlist__44c8_s_p1_0,
  133504. NULL,
  133505. &_vq_auxt__44c8_s_p1_0,
  133506. NULL,
  133507. 0
  133508. };
  133509. static long _vq_quantlist__44c8_s_p2_0[] = {
  133510. 2,
  133511. 1,
  133512. 3,
  133513. 0,
  133514. 4,
  133515. };
  133516. static long _vq_lengthlist__44c8_s_p2_0[] = {
  133517. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133518. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133519. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133520. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  133521. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133522. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  133523. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  133524. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133526. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133527. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  133528. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133529. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  133530. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  133531. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  133532. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  133533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133534. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  133535. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  133536. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  133537. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  133538. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  133539. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  133540. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133542. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133543. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  133544. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133545. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  133546. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  133547. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  133548. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133553. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  133554. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133555. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  133556. 13,
  133557. };
  133558. static float _vq_quantthresh__44c8_s_p2_0[] = {
  133559. -1.5, -0.5, 0.5, 1.5,
  133560. };
  133561. static long _vq_quantmap__44c8_s_p2_0[] = {
  133562. 3, 1, 0, 2, 4,
  133563. };
  133564. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  133565. _vq_quantthresh__44c8_s_p2_0,
  133566. _vq_quantmap__44c8_s_p2_0,
  133567. 5,
  133568. 5
  133569. };
  133570. static static_codebook _44c8_s_p2_0 = {
  133571. 4, 625,
  133572. _vq_lengthlist__44c8_s_p2_0,
  133573. 1, -533725184, 1611661312, 3, 0,
  133574. _vq_quantlist__44c8_s_p2_0,
  133575. NULL,
  133576. &_vq_auxt__44c8_s_p2_0,
  133577. NULL,
  133578. 0
  133579. };
  133580. static long _vq_quantlist__44c8_s_p3_0[] = {
  133581. 4,
  133582. 3,
  133583. 5,
  133584. 2,
  133585. 6,
  133586. 1,
  133587. 7,
  133588. 0,
  133589. 8,
  133590. };
  133591. static long _vq_lengthlist__44c8_s_p3_0[] = {
  133592. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133593. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133594. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133595. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133597. 0,
  133598. };
  133599. static float _vq_quantthresh__44c8_s_p3_0[] = {
  133600. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133601. };
  133602. static long _vq_quantmap__44c8_s_p3_0[] = {
  133603. 7, 5, 3, 1, 0, 2, 4, 6,
  133604. 8,
  133605. };
  133606. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  133607. _vq_quantthresh__44c8_s_p3_0,
  133608. _vq_quantmap__44c8_s_p3_0,
  133609. 9,
  133610. 9
  133611. };
  133612. static static_codebook _44c8_s_p3_0 = {
  133613. 2, 81,
  133614. _vq_lengthlist__44c8_s_p3_0,
  133615. 1, -531628032, 1611661312, 4, 0,
  133616. _vq_quantlist__44c8_s_p3_0,
  133617. NULL,
  133618. &_vq_auxt__44c8_s_p3_0,
  133619. NULL,
  133620. 0
  133621. };
  133622. static long _vq_quantlist__44c8_s_p4_0[] = {
  133623. 8,
  133624. 7,
  133625. 9,
  133626. 6,
  133627. 10,
  133628. 5,
  133629. 11,
  133630. 4,
  133631. 12,
  133632. 3,
  133633. 13,
  133634. 2,
  133635. 14,
  133636. 1,
  133637. 15,
  133638. 0,
  133639. 16,
  133640. };
  133641. static long _vq_lengthlist__44c8_s_p4_0[] = {
  133642. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133643. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  133644. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133645. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  133646. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  133647. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133648. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133649. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133650. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133651. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133660. 0,
  133661. };
  133662. static float _vq_quantthresh__44c8_s_p4_0[] = {
  133663. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133664. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133665. };
  133666. static long _vq_quantmap__44c8_s_p4_0[] = {
  133667. 15, 13, 11, 9, 7, 5, 3, 1,
  133668. 0, 2, 4, 6, 8, 10, 12, 14,
  133669. 16,
  133670. };
  133671. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  133672. _vq_quantthresh__44c8_s_p4_0,
  133673. _vq_quantmap__44c8_s_p4_0,
  133674. 17,
  133675. 17
  133676. };
  133677. static static_codebook _44c8_s_p4_0 = {
  133678. 2, 289,
  133679. _vq_lengthlist__44c8_s_p4_0,
  133680. 1, -529530880, 1611661312, 5, 0,
  133681. _vq_quantlist__44c8_s_p4_0,
  133682. NULL,
  133683. &_vq_auxt__44c8_s_p4_0,
  133684. NULL,
  133685. 0
  133686. };
  133687. static long _vq_quantlist__44c8_s_p5_0[] = {
  133688. 1,
  133689. 0,
  133690. 2,
  133691. };
  133692. static long _vq_lengthlist__44c8_s_p5_0[] = {
  133693. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  133694. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133695. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133696. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  133697. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  133698. 12,
  133699. };
  133700. static float _vq_quantthresh__44c8_s_p5_0[] = {
  133701. -5.5, 5.5,
  133702. };
  133703. static long _vq_quantmap__44c8_s_p5_0[] = {
  133704. 1, 0, 2,
  133705. };
  133706. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  133707. _vq_quantthresh__44c8_s_p5_0,
  133708. _vq_quantmap__44c8_s_p5_0,
  133709. 3,
  133710. 3
  133711. };
  133712. static static_codebook _44c8_s_p5_0 = {
  133713. 4, 81,
  133714. _vq_lengthlist__44c8_s_p5_0,
  133715. 1, -529137664, 1618345984, 2, 0,
  133716. _vq_quantlist__44c8_s_p5_0,
  133717. NULL,
  133718. &_vq_auxt__44c8_s_p5_0,
  133719. NULL,
  133720. 0
  133721. };
  133722. static long _vq_quantlist__44c8_s_p5_1[] = {
  133723. 5,
  133724. 4,
  133725. 6,
  133726. 3,
  133727. 7,
  133728. 2,
  133729. 8,
  133730. 1,
  133731. 9,
  133732. 0,
  133733. 10,
  133734. };
  133735. static long _vq_lengthlist__44c8_s_p5_1[] = {
  133736. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  133737. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  133738. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  133739. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  133740. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  133741. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  133742. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  133743. 11,11,11, 7, 7, 7, 7, 8, 8,
  133744. };
  133745. static float _vq_quantthresh__44c8_s_p5_1[] = {
  133746. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133747. 3.5, 4.5,
  133748. };
  133749. static long _vq_quantmap__44c8_s_p5_1[] = {
  133750. 9, 7, 5, 3, 1, 0, 2, 4,
  133751. 6, 8, 10,
  133752. };
  133753. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  133754. _vq_quantthresh__44c8_s_p5_1,
  133755. _vq_quantmap__44c8_s_p5_1,
  133756. 11,
  133757. 11
  133758. };
  133759. static static_codebook _44c8_s_p5_1 = {
  133760. 2, 121,
  133761. _vq_lengthlist__44c8_s_p5_1,
  133762. 1, -531365888, 1611661312, 4, 0,
  133763. _vq_quantlist__44c8_s_p5_1,
  133764. NULL,
  133765. &_vq_auxt__44c8_s_p5_1,
  133766. NULL,
  133767. 0
  133768. };
  133769. static long _vq_quantlist__44c8_s_p6_0[] = {
  133770. 6,
  133771. 5,
  133772. 7,
  133773. 4,
  133774. 8,
  133775. 3,
  133776. 9,
  133777. 2,
  133778. 10,
  133779. 1,
  133780. 11,
  133781. 0,
  133782. 12,
  133783. };
  133784. static long _vq_lengthlist__44c8_s_p6_0[] = {
  133785. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  133786. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  133787. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  133788. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  133789. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  133790. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  133791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133795. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133796. };
  133797. static float _vq_quantthresh__44c8_s_p6_0[] = {
  133798. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133799. 12.5, 17.5, 22.5, 27.5,
  133800. };
  133801. static long _vq_quantmap__44c8_s_p6_0[] = {
  133802. 11, 9, 7, 5, 3, 1, 0, 2,
  133803. 4, 6, 8, 10, 12,
  133804. };
  133805. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  133806. _vq_quantthresh__44c8_s_p6_0,
  133807. _vq_quantmap__44c8_s_p6_0,
  133808. 13,
  133809. 13
  133810. };
  133811. static static_codebook _44c8_s_p6_0 = {
  133812. 2, 169,
  133813. _vq_lengthlist__44c8_s_p6_0,
  133814. 1, -526516224, 1616117760, 4, 0,
  133815. _vq_quantlist__44c8_s_p6_0,
  133816. NULL,
  133817. &_vq_auxt__44c8_s_p6_0,
  133818. NULL,
  133819. 0
  133820. };
  133821. static long _vq_quantlist__44c8_s_p6_1[] = {
  133822. 2,
  133823. 1,
  133824. 3,
  133825. 0,
  133826. 4,
  133827. };
  133828. static long _vq_lengthlist__44c8_s_p6_1[] = {
  133829. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133830. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133831. };
  133832. static float _vq_quantthresh__44c8_s_p6_1[] = {
  133833. -1.5, -0.5, 0.5, 1.5,
  133834. };
  133835. static long _vq_quantmap__44c8_s_p6_1[] = {
  133836. 3, 1, 0, 2, 4,
  133837. };
  133838. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  133839. _vq_quantthresh__44c8_s_p6_1,
  133840. _vq_quantmap__44c8_s_p6_1,
  133841. 5,
  133842. 5
  133843. };
  133844. static static_codebook _44c8_s_p6_1 = {
  133845. 2, 25,
  133846. _vq_lengthlist__44c8_s_p6_1,
  133847. 1, -533725184, 1611661312, 3, 0,
  133848. _vq_quantlist__44c8_s_p6_1,
  133849. NULL,
  133850. &_vq_auxt__44c8_s_p6_1,
  133851. NULL,
  133852. 0
  133853. };
  133854. static long _vq_quantlist__44c8_s_p7_0[] = {
  133855. 6,
  133856. 5,
  133857. 7,
  133858. 4,
  133859. 8,
  133860. 3,
  133861. 9,
  133862. 2,
  133863. 10,
  133864. 1,
  133865. 11,
  133866. 0,
  133867. 12,
  133868. };
  133869. static long _vq_lengthlist__44c8_s_p7_0[] = {
  133870. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  133871. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133872. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  133873. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  133874. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  133875. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  133876. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  133877. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  133878. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  133879. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  133880. 20,13,13,13,13,14,13,15,15,
  133881. };
  133882. static float _vq_quantthresh__44c8_s_p7_0[] = {
  133883. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133884. 27.5, 38.5, 49.5, 60.5,
  133885. };
  133886. static long _vq_quantmap__44c8_s_p7_0[] = {
  133887. 11, 9, 7, 5, 3, 1, 0, 2,
  133888. 4, 6, 8, 10, 12,
  133889. };
  133890. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  133891. _vq_quantthresh__44c8_s_p7_0,
  133892. _vq_quantmap__44c8_s_p7_0,
  133893. 13,
  133894. 13
  133895. };
  133896. static static_codebook _44c8_s_p7_0 = {
  133897. 2, 169,
  133898. _vq_lengthlist__44c8_s_p7_0,
  133899. 1, -523206656, 1618345984, 4, 0,
  133900. _vq_quantlist__44c8_s_p7_0,
  133901. NULL,
  133902. &_vq_auxt__44c8_s_p7_0,
  133903. NULL,
  133904. 0
  133905. };
  133906. static long _vq_quantlist__44c8_s_p7_1[] = {
  133907. 5,
  133908. 4,
  133909. 6,
  133910. 3,
  133911. 7,
  133912. 2,
  133913. 8,
  133914. 1,
  133915. 9,
  133916. 0,
  133917. 10,
  133918. };
  133919. static long _vq_lengthlist__44c8_s_p7_1[] = {
  133920. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  133921. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  133922. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133923. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133924. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133925. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133926. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133927. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133928. };
  133929. static float _vq_quantthresh__44c8_s_p7_1[] = {
  133930. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133931. 3.5, 4.5,
  133932. };
  133933. static long _vq_quantmap__44c8_s_p7_1[] = {
  133934. 9, 7, 5, 3, 1, 0, 2, 4,
  133935. 6, 8, 10,
  133936. };
  133937. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  133938. _vq_quantthresh__44c8_s_p7_1,
  133939. _vq_quantmap__44c8_s_p7_1,
  133940. 11,
  133941. 11
  133942. };
  133943. static static_codebook _44c8_s_p7_1 = {
  133944. 2, 121,
  133945. _vq_lengthlist__44c8_s_p7_1,
  133946. 1, -531365888, 1611661312, 4, 0,
  133947. _vq_quantlist__44c8_s_p7_1,
  133948. NULL,
  133949. &_vq_auxt__44c8_s_p7_1,
  133950. NULL,
  133951. 0
  133952. };
  133953. static long _vq_quantlist__44c8_s_p8_0[] = {
  133954. 7,
  133955. 6,
  133956. 8,
  133957. 5,
  133958. 9,
  133959. 4,
  133960. 10,
  133961. 3,
  133962. 11,
  133963. 2,
  133964. 12,
  133965. 1,
  133966. 13,
  133967. 0,
  133968. 14,
  133969. };
  133970. static long _vq_lengthlist__44c8_s_p8_0[] = {
  133971. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  133972. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  133973. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  133974. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  133975. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  133976. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  133977. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  133978. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  133979. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  133980. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  133981. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  133982. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133983. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  133984. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  133985. 15,
  133986. };
  133987. static float _vq_quantthresh__44c8_s_p8_0[] = {
  133988. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133989. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133990. };
  133991. static long _vq_quantmap__44c8_s_p8_0[] = {
  133992. 13, 11, 9, 7, 5, 3, 1, 0,
  133993. 2, 4, 6, 8, 10, 12, 14,
  133994. };
  133995. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  133996. _vq_quantthresh__44c8_s_p8_0,
  133997. _vq_quantmap__44c8_s_p8_0,
  133998. 15,
  133999. 15
  134000. };
  134001. static static_codebook _44c8_s_p8_0 = {
  134002. 2, 225,
  134003. _vq_lengthlist__44c8_s_p8_0,
  134004. 1, -520986624, 1620377600, 4, 0,
  134005. _vq_quantlist__44c8_s_p8_0,
  134006. NULL,
  134007. &_vq_auxt__44c8_s_p8_0,
  134008. NULL,
  134009. 0
  134010. };
  134011. static long _vq_quantlist__44c8_s_p8_1[] = {
  134012. 10,
  134013. 9,
  134014. 11,
  134015. 8,
  134016. 12,
  134017. 7,
  134018. 13,
  134019. 6,
  134020. 14,
  134021. 5,
  134022. 15,
  134023. 4,
  134024. 16,
  134025. 3,
  134026. 17,
  134027. 2,
  134028. 18,
  134029. 1,
  134030. 19,
  134031. 0,
  134032. 20,
  134033. };
  134034. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134035. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134036. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134037. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134038. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134039. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134040. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134041. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134042. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134043. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134044. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134045. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134046. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134047. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134048. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134049. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134050. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134051. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134052. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134053. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134054. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134055. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134056. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134057. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134058. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134059. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134060. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134061. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134062. 10, 9, 9,10,10, 9,10, 9, 9,
  134063. };
  134064. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134065. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134066. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134067. 6.5, 7.5, 8.5, 9.5,
  134068. };
  134069. static long _vq_quantmap__44c8_s_p8_1[] = {
  134070. 19, 17, 15, 13, 11, 9, 7, 5,
  134071. 3, 1, 0, 2, 4, 6, 8, 10,
  134072. 12, 14, 16, 18, 20,
  134073. };
  134074. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134075. _vq_quantthresh__44c8_s_p8_1,
  134076. _vq_quantmap__44c8_s_p8_1,
  134077. 21,
  134078. 21
  134079. };
  134080. static static_codebook _44c8_s_p8_1 = {
  134081. 2, 441,
  134082. _vq_lengthlist__44c8_s_p8_1,
  134083. 1, -529268736, 1611661312, 5, 0,
  134084. _vq_quantlist__44c8_s_p8_1,
  134085. NULL,
  134086. &_vq_auxt__44c8_s_p8_1,
  134087. NULL,
  134088. 0
  134089. };
  134090. static long _vq_quantlist__44c8_s_p9_0[] = {
  134091. 8,
  134092. 7,
  134093. 9,
  134094. 6,
  134095. 10,
  134096. 5,
  134097. 11,
  134098. 4,
  134099. 12,
  134100. 3,
  134101. 13,
  134102. 2,
  134103. 14,
  134104. 1,
  134105. 15,
  134106. 0,
  134107. 16,
  134108. };
  134109. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134110. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134111. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134112. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134113. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134114. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134115. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134116. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134117. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134118. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134119. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134120. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134121. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134122. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134123. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134124. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134125. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134126. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134127. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134128. 10,
  134129. };
  134130. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134131. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134132. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134133. };
  134134. static long _vq_quantmap__44c8_s_p9_0[] = {
  134135. 15, 13, 11, 9, 7, 5, 3, 1,
  134136. 0, 2, 4, 6, 8, 10, 12, 14,
  134137. 16,
  134138. };
  134139. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134140. _vq_quantthresh__44c8_s_p9_0,
  134141. _vq_quantmap__44c8_s_p9_0,
  134142. 17,
  134143. 17
  134144. };
  134145. static static_codebook _44c8_s_p9_0 = {
  134146. 2, 289,
  134147. _vq_lengthlist__44c8_s_p9_0,
  134148. 1, -509798400, 1631393792, 5, 0,
  134149. _vq_quantlist__44c8_s_p9_0,
  134150. NULL,
  134151. &_vq_auxt__44c8_s_p9_0,
  134152. NULL,
  134153. 0
  134154. };
  134155. static long _vq_quantlist__44c8_s_p9_1[] = {
  134156. 9,
  134157. 8,
  134158. 10,
  134159. 7,
  134160. 11,
  134161. 6,
  134162. 12,
  134163. 5,
  134164. 13,
  134165. 4,
  134166. 14,
  134167. 3,
  134168. 15,
  134169. 2,
  134170. 16,
  134171. 1,
  134172. 17,
  134173. 0,
  134174. 18,
  134175. };
  134176. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134177. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134178. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134179. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134180. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134181. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134182. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134183. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134184. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134185. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134186. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134187. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134188. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134189. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134190. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134191. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134192. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134193. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134194. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134195. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134196. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134197. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134198. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134199. 14,13,13,14,14,15,14,15,14,
  134200. };
  134201. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134202. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134203. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134204. 367.5, 416.5,
  134205. };
  134206. static long _vq_quantmap__44c8_s_p9_1[] = {
  134207. 17, 15, 13, 11, 9, 7, 5, 3,
  134208. 1, 0, 2, 4, 6, 8, 10, 12,
  134209. 14, 16, 18,
  134210. };
  134211. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134212. _vq_quantthresh__44c8_s_p9_1,
  134213. _vq_quantmap__44c8_s_p9_1,
  134214. 19,
  134215. 19
  134216. };
  134217. static static_codebook _44c8_s_p9_1 = {
  134218. 2, 361,
  134219. _vq_lengthlist__44c8_s_p9_1,
  134220. 1, -518287360, 1622704128, 5, 0,
  134221. _vq_quantlist__44c8_s_p9_1,
  134222. NULL,
  134223. &_vq_auxt__44c8_s_p9_1,
  134224. NULL,
  134225. 0
  134226. };
  134227. static long _vq_quantlist__44c8_s_p9_2[] = {
  134228. 24,
  134229. 23,
  134230. 25,
  134231. 22,
  134232. 26,
  134233. 21,
  134234. 27,
  134235. 20,
  134236. 28,
  134237. 19,
  134238. 29,
  134239. 18,
  134240. 30,
  134241. 17,
  134242. 31,
  134243. 16,
  134244. 32,
  134245. 15,
  134246. 33,
  134247. 14,
  134248. 34,
  134249. 13,
  134250. 35,
  134251. 12,
  134252. 36,
  134253. 11,
  134254. 37,
  134255. 10,
  134256. 38,
  134257. 9,
  134258. 39,
  134259. 8,
  134260. 40,
  134261. 7,
  134262. 41,
  134263. 6,
  134264. 42,
  134265. 5,
  134266. 43,
  134267. 4,
  134268. 44,
  134269. 3,
  134270. 45,
  134271. 2,
  134272. 46,
  134273. 1,
  134274. 47,
  134275. 0,
  134276. 48,
  134277. };
  134278. static long _vq_lengthlist__44c8_s_p9_2[] = {
  134279. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134280. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134281. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134282. 7,
  134283. };
  134284. static float _vq_quantthresh__44c8_s_p9_2[] = {
  134285. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134286. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134287. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134288. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134289. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134290. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134291. };
  134292. static long _vq_quantmap__44c8_s_p9_2[] = {
  134293. 47, 45, 43, 41, 39, 37, 35, 33,
  134294. 31, 29, 27, 25, 23, 21, 19, 17,
  134295. 15, 13, 11, 9, 7, 5, 3, 1,
  134296. 0, 2, 4, 6, 8, 10, 12, 14,
  134297. 16, 18, 20, 22, 24, 26, 28, 30,
  134298. 32, 34, 36, 38, 40, 42, 44, 46,
  134299. 48,
  134300. };
  134301. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  134302. _vq_quantthresh__44c8_s_p9_2,
  134303. _vq_quantmap__44c8_s_p9_2,
  134304. 49,
  134305. 49
  134306. };
  134307. static static_codebook _44c8_s_p9_2 = {
  134308. 1, 49,
  134309. _vq_lengthlist__44c8_s_p9_2,
  134310. 1, -526909440, 1611661312, 6, 0,
  134311. _vq_quantlist__44c8_s_p9_2,
  134312. NULL,
  134313. &_vq_auxt__44c8_s_p9_2,
  134314. NULL,
  134315. 0
  134316. };
  134317. static long _huff_lengthlist__44c8_s_short[] = {
  134318. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134319. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134320. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134321. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134322. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134323. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134324. 10, 9,11,14,
  134325. };
  134326. static static_codebook _huff_book__44c8_s_short = {
  134327. 2, 100,
  134328. _huff_lengthlist__44c8_s_short,
  134329. 0, 0, 0, 0, 0,
  134330. NULL,
  134331. NULL,
  134332. NULL,
  134333. NULL,
  134334. 0
  134335. };
  134336. static long _huff_lengthlist__44c9_s_long[] = {
  134337. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134338. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134339. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134340. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134341. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134342. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134343. 10, 9, 8, 9,
  134344. };
  134345. static static_codebook _huff_book__44c9_s_long = {
  134346. 2, 100,
  134347. _huff_lengthlist__44c9_s_long,
  134348. 0, 0, 0, 0, 0,
  134349. NULL,
  134350. NULL,
  134351. NULL,
  134352. NULL,
  134353. 0
  134354. };
  134355. static long _vq_quantlist__44c9_s_p1_0[] = {
  134356. 1,
  134357. 0,
  134358. 2,
  134359. };
  134360. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134361. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134362. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134363. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134364. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134365. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134366. 7,
  134367. };
  134368. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134369. -0.5, 0.5,
  134370. };
  134371. static long _vq_quantmap__44c9_s_p1_0[] = {
  134372. 1, 0, 2,
  134373. };
  134374. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  134375. _vq_quantthresh__44c9_s_p1_0,
  134376. _vq_quantmap__44c9_s_p1_0,
  134377. 3,
  134378. 3
  134379. };
  134380. static static_codebook _44c9_s_p1_0 = {
  134381. 4, 81,
  134382. _vq_lengthlist__44c9_s_p1_0,
  134383. 1, -535822336, 1611661312, 2, 0,
  134384. _vq_quantlist__44c9_s_p1_0,
  134385. NULL,
  134386. &_vq_auxt__44c9_s_p1_0,
  134387. NULL,
  134388. 0
  134389. };
  134390. static long _vq_quantlist__44c9_s_p2_0[] = {
  134391. 2,
  134392. 1,
  134393. 3,
  134394. 0,
  134395. 4,
  134396. };
  134397. static long _vq_lengthlist__44c9_s_p2_0[] = {
  134398. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134399. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  134400. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  134401. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  134402. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  134403. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  134404. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  134405. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  134406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134407. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  134408. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  134409. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  134410. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  134411. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  134412. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  134413. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  134414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134415. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  134416. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  134417. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  134418. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  134419. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  134420. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  134421. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134423. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  134424. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  134425. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  134426. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  134427. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  134428. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  134429. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134434. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  134435. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  134436. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  134437. 12,
  134438. };
  134439. static float _vq_quantthresh__44c9_s_p2_0[] = {
  134440. -1.5, -0.5, 0.5, 1.5,
  134441. };
  134442. static long _vq_quantmap__44c9_s_p2_0[] = {
  134443. 3, 1, 0, 2, 4,
  134444. };
  134445. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  134446. _vq_quantthresh__44c9_s_p2_0,
  134447. _vq_quantmap__44c9_s_p2_0,
  134448. 5,
  134449. 5
  134450. };
  134451. static static_codebook _44c9_s_p2_0 = {
  134452. 4, 625,
  134453. _vq_lengthlist__44c9_s_p2_0,
  134454. 1, -533725184, 1611661312, 3, 0,
  134455. _vq_quantlist__44c9_s_p2_0,
  134456. NULL,
  134457. &_vq_auxt__44c9_s_p2_0,
  134458. NULL,
  134459. 0
  134460. };
  134461. static long _vq_quantlist__44c9_s_p3_0[] = {
  134462. 4,
  134463. 3,
  134464. 5,
  134465. 2,
  134466. 6,
  134467. 1,
  134468. 7,
  134469. 0,
  134470. 8,
  134471. };
  134472. static long _vq_lengthlist__44c9_s_p3_0[] = {
  134473. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  134474. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  134475. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  134476. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  134477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134478. 0,
  134479. };
  134480. static float _vq_quantthresh__44c9_s_p3_0[] = {
  134481. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134482. };
  134483. static long _vq_quantmap__44c9_s_p3_0[] = {
  134484. 7, 5, 3, 1, 0, 2, 4, 6,
  134485. 8,
  134486. };
  134487. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  134488. _vq_quantthresh__44c9_s_p3_0,
  134489. _vq_quantmap__44c9_s_p3_0,
  134490. 9,
  134491. 9
  134492. };
  134493. static static_codebook _44c9_s_p3_0 = {
  134494. 2, 81,
  134495. _vq_lengthlist__44c9_s_p3_0,
  134496. 1, -531628032, 1611661312, 4, 0,
  134497. _vq_quantlist__44c9_s_p3_0,
  134498. NULL,
  134499. &_vq_auxt__44c9_s_p3_0,
  134500. NULL,
  134501. 0
  134502. };
  134503. static long _vq_quantlist__44c9_s_p4_0[] = {
  134504. 8,
  134505. 7,
  134506. 9,
  134507. 6,
  134508. 10,
  134509. 5,
  134510. 11,
  134511. 4,
  134512. 12,
  134513. 3,
  134514. 13,
  134515. 2,
  134516. 14,
  134517. 1,
  134518. 15,
  134519. 0,
  134520. 16,
  134521. };
  134522. static long _vq_lengthlist__44c9_s_p4_0[] = {
  134523. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  134524. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  134525. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  134526. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  134527. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  134528. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  134529. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  134530. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134531. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134532. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  134533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134541. 0,
  134542. };
  134543. static float _vq_quantthresh__44c9_s_p4_0[] = {
  134544. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134545. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134546. };
  134547. static long _vq_quantmap__44c9_s_p4_0[] = {
  134548. 15, 13, 11, 9, 7, 5, 3, 1,
  134549. 0, 2, 4, 6, 8, 10, 12, 14,
  134550. 16,
  134551. };
  134552. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  134553. _vq_quantthresh__44c9_s_p4_0,
  134554. _vq_quantmap__44c9_s_p4_0,
  134555. 17,
  134556. 17
  134557. };
  134558. static static_codebook _44c9_s_p4_0 = {
  134559. 2, 289,
  134560. _vq_lengthlist__44c9_s_p4_0,
  134561. 1, -529530880, 1611661312, 5, 0,
  134562. _vq_quantlist__44c9_s_p4_0,
  134563. NULL,
  134564. &_vq_auxt__44c9_s_p4_0,
  134565. NULL,
  134566. 0
  134567. };
  134568. static long _vq_quantlist__44c9_s_p5_0[] = {
  134569. 1,
  134570. 0,
  134571. 2,
  134572. };
  134573. static long _vq_lengthlist__44c9_s_p5_0[] = {
  134574. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  134575. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  134576. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  134577. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  134578. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  134579. 12,
  134580. };
  134581. static float _vq_quantthresh__44c9_s_p5_0[] = {
  134582. -5.5, 5.5,
  134583. };
  134584. static long _vq_quantmap__44c9_s_p5_0[] = {
  134585. 1, 0, 2,
  134586. };
  134587. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  134588. _vq_quantthresh__44c9_s_p5_0,
  134589. _vq_quantmap__44c9_s_p5_0,
  134590. 3,
  134591. 3
  134592. };
  134593. static static_codebook _44c9_s_p5_0 = {
  134594. 4, 81,
  134595. _vq_lengthlist__44c9_s_p5_0,
  134596. 1, -529137664, 1618345984, 2, 0,
  134597. _vq_quantlist__44c9_s_p5_0,
  134598. NULL,
  134599. &_vq_auxt__44c9_s_p5_0,
  134600. NULL,
  134601. 0
  134602. };
  134603. static long _vq_quantlist__44c9_s_p5_1[] = {
  134604. 5,
  134605. 4,
  134606. 6,
  134607. 3,
  134608. 7,
  134609. 2,
  134610. 8,
  134611. 1,
  134612. 9,
  134613. 0,
  134614. 10,
  134615. };
  134616. static long _vq_lengthlist__44c9_s_p5_1[] = {
  134617. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  134618. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  134619. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  134620. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  134621. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  134622. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  134623. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  134624. 11,11,11, 7, 7, 7, 7, 7, 7,
  134625. };
  134626. static float _vq_quantthresh__44c9_s_p5_1[] = {
  134627. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134628. 3.5, 4.5,
  134629. };
  134630. static long _vq_quantmap__44c9_s_p5_1[] = {
  134631. 9, 7, 5, 3, 1, 0, 2, 4,
  134632. 6, 8, 10,
  134633. };
  134634. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  134635. _vq_quantthresh__44c9_s_p5_1,
  134636. _vq_quantmap__44c9_s_p5_1,
  134637. 11,
  134638. 11
  134639. };
  134640. static static_codebook _44c9_s_p5_1 = {
  134641. 2, 121,
  134642. _vq_lengthlist__44c9_s_p5_1,
  134643. 1, -531365888, 1611661312, 4, 0,
  134644. _vq_quantlist__44c9_s_p5_1,
  134645. NULL,
  134646. &_vq_auxt__44c9_s_p5_1,
  134647. NULL,
  134648. 0
  134649. };
  134650. static long _vq_quantlist__44c9_s_p6_0[] = {
  134651. 6,
  134652. 5,
  134653. 7,
  134654. 4,
  134655. 8,
  134656. 3,
  134657. 9,
  134658. 2,
  134659. 10,
  134660. 1,
  134661. 11,
  134662. 0,
  134663. 12,
  134664. };
  134665. static long _vq_lengthlist__44c9_s_p6_0[] = {
  134666. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  134667. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  134668. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  134669. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134670. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  134671. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  134672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134676. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134677. };
  134678. static float _vq_quantthresh__44c9_s_p6_0[] = {
  134679. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134680. 12.5, 17.5, 22.5, 27.5,
  134681. };
  134682. static long _vq_quantmap__44c9_s_p6_0[] = {
  134683. 11, 9, 7, 5, 3, 1, 0, 2,
  134684. 4, 6, 8, 10, 12,
  134685. };
  134686. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  134687. _vq_quantthresh__44c9_s_p6_0,
  134688. _vq_quantmap__44c9_s_p6_0,
  134689. 13,
  134690. 13
  134691. };
  134692. static static_codebook _44c9_s_p6_0 = {
  134693. 2, 169,
  134694. _vq_lengthlist__44c9_s_p6_0,
  134695. 1, -526516224, 1616117760, 4, 0,
  134696. _vq_quantlist__44c9_s_p6_0,
  134697. NULL,
  134698. &_vq_auxt__44c9_s_p6_0,
  134699. NULL,
  134700. 0
  134701. };
  134702. static long _vq_quantlist__44c9_s_p6_1[] = {
  134703. 2,
  134704. 1,
  134705. 3,
  134706. 0,
  134707. 4,
  134708. };
  134709. static long _vq_lengthlist__44c9_s_p6_1[] = {
  134710. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  134711. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  134712. };
  134713. static float _vq_quantthresh__44c9_s_p6_1[] = {
  134714. -1.5, -0.5, 0.5, 1.5,
  134715. };
  134716. static long _vq_quantmap__44c9_s_p6_1[] = {
  134717. 3, 1, 0, 2, 4,
  134718. };
  134719. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  134720. _vq_quantthresh__44c9_s_p6_1,
  134721. _vq_quantmap__44c9_s_p6_1,
  134722. 5,
  134723. 5
  134724. };
  134725. static static_codebook _44c9_s_p6_1 = {
  134726. 2, 25,
  134727. _vq_lengthlist__44c9_s_p6_1,
  134728. 1, -533725184, 1611661312, 3, 0,
  134729. _vq_quantlist__44c9_s_p6_1,
  134730. NULL,
  134731. &_vq_auxt__44c9_s_p6_1,
  134732. NULL,
  134733. 0
  134734. };
  134735. static long _vq_quantlist__44c9_s_p7_0[] = {
  134736. 6,
  134737. 5,
  134738. 7,
  134739. 4,
  134740. 8,
  134741. 3,
  134742. 9,
  134743. 2,
  134744. 10,
  134745. 1,
  134746. 11,
  134747. 0,
  134748. 12,
  134749. };
  134750. static long _vq_lengthlist__44c9_s_p7_0[] = {
  134751. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  134752. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  134753. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  134754. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  134755. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  134756. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  134757. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  134758. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  134759. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  134760. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  134761. 19,12,12,12,12,13,13,14,14,
  134762. };
  134763. static float _vq_quantthresh__44c9_s_p7_0[] = {
  134764. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134765. 27.5, 38.5, 49.5, 60.5,
  134766. };
  134767. static long _vq_quantmap__44c9_s_p7_0[] = {
  134768. 11, 9, 7, 5, 3, 1, 0, 2,
  134769. 4, 6, 8, 10, 12,
  134770. };
  134771. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  134772. _vq_quantthresh__44c9_s_p7_0,
  134773. _vq_quantmap__44c9_s_p7_0,
  134774. 13,
  134775. 13
  134776. };
  134777. static static_codebook _44c9_s_p7_0 = {
  134778. 2, 169,
  134779. _vq_lengthlist__44c9_s_p7_0,
  134780. 1, -523206656, 1618345984, 4, 0,
  134781. _vq_quantlist__44c9_s_p7_0,
  134782. NULL,
  134783. &_vq_auxt__44c9_s_p7_0,
  134784. NULL,
  134785. 0
  134786. };
  134787. static long _vq_quantlist__44c9_s_p7_1[] = {
  134788. 5,
  134789. 4,
  134790. 6,
  134791. 3,
  134792. 7,
  134793. 2,
  134794. 8,
  134795. 1,
  134796. 9,
  134797. 0,
  134798. 10,
  134799. };
  134800. static long _vq_lengthlist__44c9_s_p7_1[] = {
  134801. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  134802. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134803. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  134804. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134805. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134806. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134807. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134808. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134809. };
  134810. static float _vq_quantthresh__44c9_s_p7_1[] = {
  134811. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134812. 3.5, 4.5,
  134813. };
  134814. static long _vq_quantmap__44c9_s_p7_1[] = {
  134815. 9, 7, 5, 3, 1, 0, 2, 4,
  134816. 6, 8, 10,
  134817. };
  134818. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  134819. _vq_quantthresh__44c9_s_p7_1,
  134820. _vq_quantmap__44c9_s_p7_1,
  134821. 11,
  134822. 11
  134823. };
  134824. static static_codebook _44c9_s_p7_1 = {
  134825. 2, 121,
  134826. _vq_lengthlist__44c9_s_p7_1,
  134827. 1, -531365888, 1611661312, 4, 0,
  134828. _vq_quantlist__44c9_s_p7_1,
  134829. NULL,
  134830. &_vq_auxt__44c9_s_p7_1,
  134831. NULL,
  134832. 0
  134833. };
  134834. static long _vq_quantlist__44c9_s_p8_0[] = {
  134835. 7,
  134836. 6,
  134837. 8,
  134838. 5,
  134839. 9,
  134840. 4,
  134841. 10,
  134842. 3,
  134843. 11,
  134844. 2,
  134845. 12,
  134846. 1,
  134847. 13,
  134848. 0,
  134849. 14,
  134850. };
  134851. static long _vq_lengthlist__44c9_s_p8_0[] = {
  134852. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  134853. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  134854. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  134855. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  134856. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  134857. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  134858. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  134859. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  134860. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  134861. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  134862. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  134863. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  134864. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  134865. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  134866. 14,
  134867. };
  134868. static float _vq_quantthresh__44c9_s_p8_0[] = {
  134869. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134870. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134871. };
  134872. static long _vq_quantmap__44c9_s_p8_0[] = {
  134873. 13, 11, 9, 7, 5, 3, 1, 0,
  134874. 2, 4, 6, 8, 10, 12, 14,
  134875. };
  134876. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  134877. _vq_quantthresh__44c9_s_p8_0,
  134878. _vq_quantmap__44c9_s_p8_0,
  134879. 15,
  134880. 15
  134881. };
  134882. static static_codebook _44c9_s_p8_0 = {
  134883. 2, 225,
  134884. _vq_lengthlist__44c9_s_p8_0,
  134885. 1, -520986624, 1620377600, 4, 0,
  134886. _vq_quantlist__44c9_s_p8_0,
  134887. NULL,
  134888. &_vq_auxt__44c9_s_p8_0,
  134889. NULL,
  134890. 0
  134891. };
  134892. static long _vq_quantlist__44c9_s_p8_1[] = {
  134893. 10,
  134894. 9,
  134895. 11,
  134896. 8,
  134897. 12,
  134898. 7,
  134899. 13,
  134900. 6,
  134901. 14,
  134902. 5,
  134903. 15,
  134904. 4,
  134905. 16,
  134906. 3,
  134907. 17,
  134908. 2,
  134909. 18,
  134910. 1,
  134911. 19,
  134912. 0,
  134913. 20,
  134914. };
  134915. static long _vq_lengthlist__44c9_s_p8_1[] = {
  134916. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134917. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134918. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134919. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134920. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134921. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134922. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  134923. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134924. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134925. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134926. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134927. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134928. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134929. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134930. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134931. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  134932. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  134933. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  134934. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  134935. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  134936. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  134937. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  134938. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  134939. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  134940. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  134941. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  134942. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  134943. 9, 9, 9,10, 9, 9, 9, 9, 9,
  134944. };
  134945. static float _vq_quantthresh__44c9_s_p8_1[] = {
  134946. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134947. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134948. 6.5, 7.5, 8.5, 9.5,
  134949. };
  134950. static long _vq_quantmap__44c9_s_p8_1[] = {
  134951. 19, 17, 15, 13, 11, 9, 7, 5,
  134952. 3, 1, 0, 2, 4, 6, 8, 10,
  134953. 12, 14, 16, 18, 20,
  134954. };
  134955. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  134956. _vq_quantthresh__44c9_s_p8_1,
  134957. _vq_quantmap__44c9_s_p8_1,
  134958. 21,
  134959. 21
  134960. };
  134961. static static_codebook _44c9_s_p8_1 = {
  134962. 2, 441,
  134963. _vq_lengthlist__44c9_s_p8_1,
  134964. 1, -529268736, 1611661312, 5, 0,
  134965. _vq_quantlist__44c9_s_p8_1,
  134966. NULL,
  134967. &_vq_auxt__44c9_s_p8_1,
  134968. NULL,
  134969. 0
  134970. };
  134971. static long _vq_quantlist__44c9_s_p9_0[] = {
  134972. 9,
  134973. 8,
  134974. 10,
  134975. 7,
  134976. 11,
  134977. 6,
  134978. 12,
  134979. 5,
  134980. 13,
  134981. 4,
  134982. 14,
  134983. 3,
  134984. 15,
  134985. 2,
  134986. 16,
  134987. 1,
  134988. 17,
  134989. 0,
  134990. 18,
  134991. };
  134992. static long _vq_lengthlist__44c9_s_p9_0[] = {
  134993. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134994. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  134995. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  134996. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  134997. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134998. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134999. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135000. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135001. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135002. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135003. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135004. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135005. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135006. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135007. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135008. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135009. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135010. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135011. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135012. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135013. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135014. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135015. 11,11,11,11,11,11,11,11,11,
  135016. };
  135017. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135018. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135019. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135020. 6982.5, 7913.5,
  135021. };
  135022. static long _vq_quantmap__44c9_s_p9_0[] = {
  135023. 17, 15, 13, 11, 9, 7, 5, 3,
  135024. 1, 0, 2, 4, 6, 8, 10, 12,
  135025. 14, 16, 18,
  135026. };
  135027. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135028. _vq_quantthresh__44c9_s_p9_0,
  135029. _vq_quantmap__44c9_s_p9_0,
  135030. 19,
  135031. 19
  135032. };
  135033. static static_codebook _44c9_s_p9_0 = {
  135034. 2, 361,
  135035. _vq_lengthlist__44c9_s_p9_0,
  135036. 1, -508535424, 1631393792, 5, 0,
  135037. _vq_quantlist__44c9_s_p9_0,
  135038. NULL,
  135039. &_vq_auxt__44c9_s_p9_0,
  135040. NULL,
  135041. 0
  135042. };
  135043. static long _vq_quantlist__44c9_s_p9_1[] = {
  135044. 9,
  135045. 8,
  135046. 10,
  135047. 7,
  135048. 11,
  135049. 6,
  135050. 12,
  135051. 5,
  135052. 13,
  135053. 4,
  135054. 14,
  135055. 3,
  135056. 15,
  135057. 2,
  135058. 16,
  135059. 1,
  135060. 17,
  135061. 0,
  135062. 18,
  135063. };
  135064. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135065. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135066. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135067. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135068. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135069. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135070. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135071. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135072. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135073. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135074. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135075. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135076. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135077. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135078. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135079. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135080. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135081. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135082. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135083. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135084. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135085. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135086. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135087. 13,13,13,14,13,14,15,15,15,
  135088. };
  135089. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135090. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135091. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135092. 367.5, 416.5,
  135093. };
  135094. static long _vq_quantmap__44c9_s_p9_1[] = {
  135095. 17, 15, 13, 11, 9, 7, 5, 3,
  135096. 1, 0, 2, 4, 6, 8, 10, 12,
  135097. 14, 16, 18,
  135098. };
  135099. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135100. _vq_quantthresh__44c9_s_p9_1,
  135101. _vq_quantmap__44c9_s_p9_1,
  135102. 19,
  135103. 19
  135104. };
  135105. static static_codebook _44c9_s_p9_1 = {
  135106. 2, 361,
  135107. _vq_lengthlist__44c9_s_p9_1,
  135108. 1, -518287360, 1622704128, 5, 0,
  135109. _vq_quantlist__44c9_s_p9_1,
  135110. NULL,
  135111. &_vq_auxt__44c9_s_p9_1,
  135112. NULL,
  135113. 0
  135114. };
  135115. static long _vq_quantlist__44c9_s_p9_2[] = {
  135116. 24,
  135117. 23,
  135118. 25,
  135119. 22,
  135120. 26,
  135121. 21,
  135122. 27,
  135123. 20,
  135124. 28,
  135125. 19,
  135126. 29,
  135127. 18,
  135128. 30,
  135129. 17,
  135130. 31,
  135131. 16,
  135132. 32,
  135133. 15,
  135134. 33,
  135135. 14,
  135136. 34,
  135137. 13,
  135138. 35,
  135139. 12,
  135140. 36,
  135141. 11,
  135142. 37,
  135143. 10,
  135144. 38,
  135145. 9,
  135146. 39,
  135147. 8,
  135148. 40,
  135149. 7,
  135150. 41,
  135151. 6,
  135152. 42,
  135153. 5,
  135154. 43,
  135155. 4,
  135156. 44,
  135157. 3,
  135158. 45,
  135159. 2,
  135160. 46,
  135161. 1,
  135162. 47,
  135163. 0,
  135164. 48,
  135165. };
  135166. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135167. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135168. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135169. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135170. 7,
  135171. };
  135172. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135173. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135174. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135175. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135176. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135177. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135178. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135179. };
  135180. static long _vq_quantmap__44c9_s_p9_2[] = {
  135181. 47, 45, 43, 41, 39, 37, 35, 33,
  135182. 31, 29, 27, 25, 23, 21, 19, 17,
  135183. 15, 13, 11, 9, 7, 5, 3, 1,
  135184. 0, 2, 4, 6, 8, 10, 12, 14,
  135185. 16, 18, 20, 22, 24, 26, 28, 30,
  135186. 32, 34, 36, 38, 40, 42, 44, 46,
  135187. 48,
  135188. };
  135189. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135190. _vq_quantthresh__44c9_s_p9_2,
  135191. _vq_quantmap__44c9_s_p9_2,
  135192. 49,
  135193. 49
  135194. };
  135195. static static_codebook _44c9_s_p9_2 = {
  135196. 1, 49,
  135197. _vq_lengthlist__44c9_s_p9_2,
  135198. 1, -526909440, 1611661312, 6, 0,
  135199. _vq_quantlist__44c9_s_p9_2,
  135200. NULL,
  135201. &_vq_auxt__44c9_s_p9_2,
  135202. NULL,
  135203. 0
  135204. };
  135205. static long _huff_lengthlist__44c9_s_short[] = {
  135206. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135207. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135208. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135209. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135210. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135211. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135212. 9, 8,10,13,
  135213. };
  135214. static static_codebook _huff_book__44c9_s_short = {
  135215. 2, 100,
  135216. _huff_lengthlist__44c9_s_short,
  135217. 0, 0, 0, 0, 0,
  135218. NULL,
  135219. NULL,
  135220. NULL,
  135221. NULL,
  135222. 0
  135223. };
  135224. static long _huff_lengthlist__44c0_s_long[] = {
  135225. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135226. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135227. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135228. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135229. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135230. 12,
  135231. };
  135232. static static_codebook _huff_book__44c0_s_long = {
  135233. 2, 81,
  135234. _huff_lengthlist__44c0_s_long,
  135235. 0, 0, 0, 0, 0,
  135236. NULL,
  135237. NULL,
  135238. NULL,
  135239. NULL,
  135240. 0
  135241. };
  135242. static long _vq_quantlist__44c0_s_p1_0[] = {
  135243. 1,
  135244. 0,
  135245. 2,
  135246. };
  135247. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135248. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135249. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135254. 0, 0, 0, 7, 9, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135259. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135294. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135299. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135304. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  135305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135339. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135340. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135345. 0, 0, 0, 0, 0, 9, 9,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135350. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  135351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135658. 0,
  135659. };
  135660. static float _vq_quantthresh__44c0_s_p1_0[] = {
  135661. -0.5, 0.5,
  135662. };
  135663. static long _vq_quantmap__44c0_s_p1_0[] = {
  135664. 1, 0, 2,
  135665. };
  135666. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  135667. _vq_quantthresh__44c0_s_p1_0,
  135668. _vq_quantmap__44c0_s_p1_0,
  135669. 3,
  135670. 3
  135671. };
  135672. static static_codebook _44c0_s_p1_0 = {
  135673. 8, 6561,
  135674. _vq_lengthlist__44c0_s_p1_0,
  135675. 1, -535822336, 1611661312, 2, 0,
  135676. _vq_quantlist__44c0_s_p1_0,
  135677. NULL,
  135678. &_vq_auxt__44c0_s_p1_0,
  135679. NULL,
  135680. 0
  135681. };
  135682. static long _vq_quantlist__44c0_s_p2_0[] = {
  135683. 2,
  135684. 1,
  135685. 3,
  135686. 0,
  135687. 4,
  135688. };
  135689. static long _vq_lengthlist__44c0_s_p2_0[] = {
  135690. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  135692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135693. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  135695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135696. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  135697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135729. 0,
  135730. };
  135731. static float _vq_quantthresh__44c0_s_p2_0[] = {
  135732. -1.5, -0.5, 0.5, 1.5,
  135733. };
  135734. static long _vq_quantmap__44c0_s_p2_0[] = {
  135735. 3, 1, 0, 2, 4,
  135736. };
  135737. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  135738. _vq_quantthresh__44c0_s_p2_0,
  135739. _vq_quantmap__44c0_s_p2_0,
  135740. 5,
  135741. 5
  135742. };
  135743. static static_codebook _44c0_s_p2_0 = {
  135744. 4, 625,
  135745. _vq_lengthlist__44c0_s_p2_0,
  135746. 1, -533725184, 1611661312, 3, 0,
  135747. _vq_quantlist__44c0_s_p2_0,
  135748. NULL,
  135749. &_vq_auxt__44c0_s_p2_0,
  135750. NULL,
  135751. 0
  135752. };
  135753. static long _vq_quantlist__44c0_s_p3_0[] = {
  135754. 4,
  135755. 3,
  135756. 5,
  135757. 2,
  135758. 6,
  135759. 1,
  135760. 7,
  135761. 0,
  135762. 8,
  135763. };
  135764. static long _vq_lengthlist__44c0_s_p3_0[] = {
  135765. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  135766. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  135767. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  135768. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  135769. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135770. 0,
  135771. };
  135772. static float _vq_quantthresh__44c0_s_p3_0[] = {
  135773. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135774. };
  135775. static long _vq_quantmap__44c0_s_p3_0[] = {
  135776. 7, 5, 3, 1, 0, 2, 4, 6,
  135777. 8,
  135778. };
  135779. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  135780. _vq_quantthresh__44c0_s_p3_0,
  135781. _vq_quantmap__44c0_s_p3_0,
  135782. 9,
  135783. 9
  135784. };
  135785. static static_codebook _44c0_s_p3_0 = {
  135786. 2, 81,
  135787. _vq_lengthlist__44c0_s_p3_0,
  135788. 1, -531628032, 1611661312, 4, 0,
  135789. _vq_quantlist__44c0_s_p3_0,
  135790. NULL,
  135791. &_vq_auxt__44c0_s_p3_0,
  135792. NULL,
  135793. 0
  135794. };
  135795. static long _vq_quantlist__44c0_s_p4_0[] = {
  135796. 4,
  135797. 3,
  135798. 5,
  135799. 2,
  135800. 6,
  135801. 1,
  135802. 7,
  135803. 0,
  135804. 8,
  135805. };
  135806. static long _vq_lengthlist__44c0_s_p4_0[] = {
  135807. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  135808. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  135809. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  135810. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  135811. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  135812. 10,
  135813. };
  135814. static float _vq_quantthresh__44c0_s_p4_0[] = {
  135815. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135816. };
  135817. static long _vq_quantmap__44c0_s_p4_0[] = {
  135818. 7, 5, 3, 1, 0, 2, 4, 6,
  135819. 8,
  135820. };
  135821. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  135822. _vq_quantthresh__44c0_s_p4_0,
  135823. _vq_quantmap__44c0_s_p4_0,
  135824. 9,
  135825. 9
  135826. };
  135827. static static_codebook _44c0_s_p4_0 = {
  135828. 2, 81,
  135829. _vq_lengthlist__44c0_s_p4_0,
  135830. 1, -531628032, 1611661312, 4, 0,
  135831. _vq_quantlist__44c0_s_p4_0,
  135832. NULL,
  135833. &_vq_auxt__44c0_s_p4_0,
  135834. NULL,
  135835. 0
  135836. };
  135837. static long _vq_quantlist__44c0_s_p5_0[] = {
  135838. 8,
  135839. 7,
  135840. 9,
  135841. 6,
  135842. 10,
  135843. 5,
  135844. 11,
  135845. 4,
  135846. 12,
  135847. 3,
  135848. 13,
  135849. 2,
  135850. 14,
  135851. 1,
  135852. 15,
  135853. 0,
  135854. 16,
  135855. };
  135856. static long _vq_lengthlist__44c0_s_p5_0[] = {
  135857. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  135858. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  135859. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  135860. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  135861. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  135862. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  135863. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  135864. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  135865. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  135866. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  135867. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  135868. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  135869. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  135870. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  135871. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  135872. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  135873. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  135874. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  135875. 14,
  135876. };
  135877. static float _vq_quantthresh__44c0_s_p5_0[] = {
  135878. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135879. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135880. };
  135881. static long _vq_quantmap__44c0_s_p5_0[] = {
  135882. 15, 13, 11, 9, 7, 5, 3, 1,
  135883. 0, 2, 4, 6, 8, 10, 12, 14,
  135884. 16,
  135885. };
  135886. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  135887. _vq_quantthresh__44c0_s_p5_0,
  135888. _vq_quantmap__44c0_s_p5_0,
  135889. 17,
  135890. 17
  135891. };
  135892. static static_codebook _44c0_s_p5_0 = {
  135893. 2, 289,
  135894. _vq_lengthlist__44c0_s_p5_0,
  135895. 1, -529530880, 1611661312, 5, 0,
  135896. _vq_quantlist__44c0_s_p5_0,
  135897. NULL,
  135898. &_vq_auxt__44c0_s_p5_0,
  135899. NULL,
  135900. 0
  135901. };
  135902. static long _vq_quantlist__44c0_s_p6_0[] = {
  135903. 1,
  135904. 0,
  135905. 2,
  135906. };
  135907. static long _vq_lengthlist__44c0_s_p6_0[] = {
  135908. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  135909. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  135910. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  135911. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  135912. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  135913. 10,
  135914. };
  135915. static float _vq_quantthresh__44c0_s_p6_0[] = {
  135916. -5.5, 5.5,
  135917. };
  135918. static long _vq_quantmap__44c0_s_p6_0[] = {
  135919. 1, 0, 2,
  135920. };
  135921. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  135922. _vq_quantthresh__44c0_s_p6_0,
  135923. _vq_quantmap__44c0_s_p6_0,
  135924. 3,
  135925. 3
  135926. };
  135927. static static_codebook _44c0_s_p6_0 = {
  135928. 4, 81,
  135929. _vq_lengthlist__44c0_s_p6_0,
  135930. 1, -529137664, 1618345984, 2, 0,
  135931. _vq_quantlist__44c0_s_p6_0,
  135932. NULL,
  135933. &_vq_auxt__44c0_s_p6_0,
  135934. NULL,
  135935. 0
  135936. };
  135937. static long _vq_quantlist__44c0_s_p6_1[] = {
  135938. 5,
  135939. 4,
  135940. 6,
  135941. 3,
  135942. 7,
  135943. 2,
  135944. 8,
  135945. 1,
  135946. 9,
  135947. 0,
  135948. 10,
  135949. };
  135950. static long _vq_lengthlist__44c0_s_p6_1[] = {
  135951. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  135952. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  135953. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  135954. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  135955. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  135956. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  135957. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  135958. 10,10,10, 8, 8, 8, 8, 8, 8,
  135959. };
  135960. static float _vq_quantthresh__44c0_s_p6_1[] = {
  135961. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135962. 3.5, 4.5,
  135963. };
  135964. static long _vq_quantmap__44c0_s_p6_1[] = {
  135965. 9, 7, 5, 3, 1, 0, 2, 4,
  135966. 6, 8, 10,
  135967. };
  135968. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  135969. _vq_quantthresh__44c0_s_p6_1,
  135970. _vq_quantmap__44c0_s_p6_1,
  135971. 11,
  135972. 11
  135973. };
  135974. static static_codebook _44c0_s_p6_1 = {
  135975. 2, 121,
  135976. _vq_lengthlist__44c0_s_p6_1,
  135977. 1, -531365888, 1611661312, 4, 0,
  135978. _vq_quantlist__44c0_s_p6_1,
  135979. NULL,
  135980. &_vq_auxt__44c0_s_p6_1,
  135981. NULL,
  135982. 0
  135983. };
  135984. static long _vq_quantlist__44c0_s_p7_0[] = {
  135985. 6,
  135986. 5,
  135987. 7,
  135988. 4,
  135989. 8,
  135990. 3,
  135991. 9,
  135992. 2,
  135993. 10,
  135994. 1,
  135995. 11,
  135996. 0,
  135997. 12,
  135998. };
  135999. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136000. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136001. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136002. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136003. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136004. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136005. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136006. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136007. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136008. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136009. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136010. 0,12,12,11,11,12,12,13,13,
  136011. };
  136012. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136013. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136014. 12.5, 17.5, 22.5, 27.5,
  136015. };
  136016. static long _vq_quantmap__44c0_s_p7_0[] = {
  136017. 11, 9, 7, 5, 3, 1, 0, 2,
  136018. 4, 6, 8, 10, 12,
  136019. };
  136020. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136021. _vq_quantthresh__44c0_s_p7_0,
  136022. _vq_quantmap__44c0_s_p7_0,
  136023. 13,
  136024. 13
  136025. };
  136026. static static_codebook _44c0_s_p7_0 = {
  136027. 2, 169,
  136028. _vq_lengthlist__44c0_s_p7_0,
  136029. 1, -526516224, 1616117760, 4, 0,
  136030. _vq_quantlist__44c0_s_p7_0,
  136031. NULL,
  136032. &_vq_auxt__44c0_s_p7_0,
  136033. NULL,
  136034. 0
  136035. };
  136036. static long _vq_quantlist__44c0_s_p7_1[] = {
  136037. 2,
  136038. 1,
  136039. 3,
  136040. 0,
  136041. 4,
  136042. };
  136043. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136044. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136045. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136046. };
  136047. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136048. -1.5, -0.5, 0.5, 1.5,
  136049. };
  136050. static long _vq_quantmap__44c0_s_p7_1[] = {
  136051. 3, 1, 0, 2, 4,
  136052. };
  136053. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136054. _vq_quantthresh__44c0_s_p7_1,
  136055. _vq_quantmap__44c0_s_p7_1,
  136056. 5,
  136057. 5
  136058. };
  136059. static static_codebook _44c0_s_p7_1 = {
  136060. 2, 25,
  136061. _vq_lengthlist__44c0_s_p7_1,
  136062. 1, -533725184, 1611661312, 3, 0,
  136063. _vq_quantlist__44c0_s_p7_1,
  136064. NULL,
  136065. &_vq_auxt__44c0_s_p7_1,
  136066. NULL,
  136067. 0
  136068. };
  136069. static long _vq_quantlist__44c0_s_p8_0[] = {
  136070. 2,
  136071. 1,
  136072. 3,
  136073. 0,
  136074. 4,
  136075. };
  136076. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136077. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136078. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136079. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136080. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136081. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136082. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136083. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136084. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136085. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136086. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136087. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136088. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136089. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136090. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136091. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136092. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136093. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136094. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136095. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136096. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136097. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136098. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136099. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136100. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136101. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136102. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136103. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136104. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136105. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136106. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136107. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136108. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136109. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136110. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136111. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136112. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136113. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136114. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136115. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136116. 11,
  136117. };
  136118. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136119. -331.5, -110.5, 110.5, 331.5,
  136120. };
  136121. static long _vq_quantmap__44c0_s_p8_0[] = {
  136122. 3, 1, 0, 2, 4,
  136123. };
  136124. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136125. _vq_quantthresh__44c0_s_p8_0,
  136126. _vq_quantmap__44c0_s_p8_0,
  136127. 5,
  136128. 5
  136129. };
  136130. static static_codebook _44c0_s_p8_0 = {
  136131. 4, 625,
  136132. _vq_lengthlist__44c0_s_p8_0,
  136133. 1, -518283264, 1627103232, 3, 0,
  136134. _vq_quantlist__44c0_s_p8_0,
  136135. NULL,
  136136. &_vq_auxt__44c0_s_p8_0,
  136137. NULL,
  136138. 0
  136139. };
  136140. static long _vq_quantlist__44c0_s_p8_1[] = {
  136141. 6,
  136142. 5,
  136143. 7,
  136144. 4,
  136145. 8,
  136146. 3,
  136147. 9,
  136148. 2,
  136149. 10,
  136150. 1,
  136151. 11,
  136152. 0,
  136153. 12,
  136154. };
  136155. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136156. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136157. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136158. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136159. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136160. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136161. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136162. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136163. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136164. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136165. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136166. 16,13,13,12,12,14,14,15,13,
  136167. };
  136168. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136169. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136170. 42.5, 59.5, 76.5, 93.5,
  136171. };
  136172. static long _vq_quantmap__44c0_s_p8_1[] = {
  136173. 11, 9, 7, 5, 3, 1, 0, 2,
  136174. 4, 6, 8, 10, 12,
  136175. };
  136176. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136177. _vq_quantthresh__44c0_s_p8_1,
  136178. _vq_quantmap__44c0_s_p8_1,
  136179. 13,
  136180. 13
  136181. };
  136182. static static_codebook _44c0_s_p8_1 = {
  136183. 2, 169,
  136184. _vq_lengthlist__44c0_s_p8_1,
  136185. 1, -522616832, 1620115456, 4, 0,
  136186. _vq_quantlist__44c0_s_p8_1,
  136187. NULL,
  136188. &_vq_auxt__44c0_s_p8_1,
  136189. NULL,
  136190. 0
  136191. };
  136192. static long _vq_quantlist__44c0_s_p8_2[] = {
  136193. 8,
  136194. 7,
  136195. 9,
  136196. 6,
  136197. 10,
  136198. 5,
  136199. 11,
  136200. 4,
  136201. 12,
  136202. 3,
  136203. 13,
  136204. 2,
  136205. 14,
  136206. 1,
  136207. 15,
  136208. 0,
  136209. 16,
  136210. };
  136211. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136212. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136213. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136214. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136215. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136216. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136217. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136218. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136219. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136220. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136221. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136222. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136223. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136224. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136225. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136226. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136227. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136228. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136229. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136230. 10,
  136231. };
  136232. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136233. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136234. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136235. };
  136236. static long _vq_quantmap__44c0_s_p8_2[] = {
  136237. 15, 13, 11, 9, 7, 5, 3, 1,
  136238. 0, 2, 4, 6, 8, 10, 12, 14,
  136239. 16,
  136240. };
  136241. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136242. _vq_quantthresh__44c0_s_p8_2,
  136243. _vq_quantmap__44c0_s_p8_2,
  136244. 17,
  136245. 17
  136246. };
  136247. static static_codebook _44c0_s_p8_2 = {
  136248. 2, 289,
  136249. _vq_lengthlist__44c0_s_p8_2,
  136250. 1, -529530880, 1611661312, 5, 0,
  136251. _vq_quantlist__44c0_s_p8_2,
  136252. NULL,
  136253. &_vq_auxt__44c0_s_p8_2,
  136254. NULL,
  136255. 0
  136256. };
  136257. static long _huff_lengthlist__44c0_s_short[] = {
  136258. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136259. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136260. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136261. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136262. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  136263. 12,
  136264. };
  136265. static static_codebook _huff_book__44c0_s_short = {
  136266. 2, 81,
  136267. _huff_lengthlist__44c0_s_short,
  136268. 0, 0, 0, 0, 0,
  136269. NULL,
  136270. NULL,
  136271. NULL,
  136272. NULL,
  136273. 0
  136274. };
  136275. static long _huff_lengthlist__44c0_sm_long[] = {
  136276. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  136277. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  136278. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  136279. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  136280. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  136281. 13,
  136282. };
  136283. static static_codebook _huff_book__44c0_sm_long = {
  136284. 2, 81,
  136285. _huff_lengthlist__44c0_sm_long,
  136286. 0, 0, 0, 0, 0,
  136287. NULL,
  136288. NULL,
  136289. NULL,
  136290. NULL,
  136291. 0
  136292. };
  136293. static long _vq_quantlist__44c0_sm_p1_0[] = {
  136294. 1,
  136295. 0,
  136296. 2,
  136297. };
  136298. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  136299. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136300. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136305. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136310. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  136345. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136350. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136355. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136390. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136391. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136395. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136396. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  136397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136400. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136401. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  136402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136709. 0,
  136710. };
  136711. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  136712. -0.5, 0.5,
  136713. };
  136714. static long _vq_quantmap__44c0_sm_p1_0[] = {
  136715. 1, 0, 2,
  136716. };
  136717. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  136718. _vq_quantthresh__44c0_sm_p1_0,
  136719. _vq_quantmap__44c0_sm_p1_0,
  136720. 3,
  136721. 3
  136722. };
  136723. static static_codebook _44c0_sm_p1_0 = {
  136724. 8, 6561,
  136725. _vq_lengthlist__44c0_sm_p1_0,
  136726. 1, -535822336, 1611661312, 2, 0,
  136727. _vq_quantlist__44c0_sm_p1_0,
  136728. NULL,
  136729. &_vq_auxt__44c0_sm_p1_0,
  136730. NULL,
  136731. 0
  136732. };
  136733. static long _vq_quantlist__44c0_sm_p2_0[] = {
  136734. 2,
  136735. 1,
  136736. 3,
  136737. 0,
  136738. 4,
  136739. };
  136740. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  136741. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  136743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136744. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136747. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136780. 0,
  136781. };
  136782. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  136783. -1.5, -0.5, 0.5, 1.5,
  136784. };
  136785. static long _vq_quantmap__44c0_sm_p2_0[] = {
  136786. 3, 1, 0, 2, 4,
  136787. };
  136788. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  136789. _vq_quantthresh__44c0_sm_p2_0,
  136790. _vq_quantmap__44c0_sm_p2_0,
  136791. 5,
  136792. 5
  136793. };
  136794. static static_codebook _44c0_sm_p2_0 = {
  136795. 4, 625,
  136796. _vq_lengthlist__44c0_sm_p2_0,
  136797. 1, -533725184, 1611661312, 3, 0,
  136798. _vq_quantlist__44c0_sm_p2_0,
  136799. NULL,
  136800. &_vq_auxt__44c0_sm_p2_0,
  136801. NULL,
  136802. 0
  136803. };
  136804. static long _vq_quantlist__44c0_sm_p3_0[] = {
  136805. 4,
  136806. 3,
  136807. 5,
  136808. 2,
  136809. 6,
  136810. 1,
  136811. 7,
  136812. 0,
  136813. 8,
  136814. };
  136815. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  136816. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  136817. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  136818. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  136819. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  136820. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136821. 0,
  136822. };
  136823. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  136824. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136825. };
  136826. static long _vq_quantmap__44c0_sm_p3_0[] = {
  136827. 7, 5, 3, 1, 0, 2, 4, 6,
  136828. 8,
  136829. };
  136830. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  136831. _vq_quantthresh__44c0_sm_p3_0,
  136832. _vq_quantmap__44c0_sm_p3_0,
  136833. 9,
  136834. 9
  136835. };
  136836. static static_codebook _44c0_sm_p3_0 = {
  136837. 2, 81,
  136838. _vq_lengthlist__44c0_sm_p3_0,
  136839. 1, -531628032, 1611661312, 4, 0,
  136840. _vq_quantlist__44c0_sm_p3_0,
  136841. NULL,
  136842. &_vq_auxt__44c0_sm_p3_0,
  136843. NULL,
  136844. 0
  136845. };
  136846. static long _vq_quantlist__44c0_sm_p4_0[] = {
  136847. 4,
  136848. 3,
  136849. 5,
  136850. 2,
  136851. 6,
  136852. 1,
  136853. 7,
  136854. 0,
  136855. 8,
  136856. };
  136857. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  136858. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  136859. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  136860. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  136861. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  136862. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  136863. 11,
  136864. };
  136865. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  136866. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136867. };
  136868. static long _vq_quantmap__44c0_sm_p4_0[] = {
  136869. 7, 5, 3, 1, 0, 2, 4, 6,
  136870. 8,
  136871. };
  136872. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  136873. _vq_quantthresh__44c0_sm_p4_0,
  136874. _vq_quantmap__44c0_sm_p4_0,
  136875. 9,
  136876. 9
  136877. };
  136878. static static_codebook _44c0_sm_p4_0 = {
  136879. 2, 81,
  136880. _vq_lengthlist__44c0_sm_p4_0,
  136881. 1, -531628032, 1611661312, 4, 0,
  136882. _vq_quantlist__44c0_sm_p4_0,
  136883. NULL,
  136884. &_vq_auxt__44c0_sm_p4_0,
  136885. NULL,
  136886. 0
  136887. };
  136888. static long _vq_quantlist__44c0_sm_p5_0[] = {
  136889. 8,
  136890. 7,
  136891. 9,
  136892. 6,
  136893. 10,
  136894. 5,
  136895. 11,
  136896. 4,
  136897. 12,
  136898. 3,
  136899. 13,
  136900. 2,
  136901. 14,
  136902. 1,
  136903. 15,
  136904. 0,
  136905. 16,
  136906. };
  136907. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  136908. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  136909. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  136910. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136911. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  136912. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  136913. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  136914. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  136915. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136916. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  136917. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  136918. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136919. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136920. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  136921. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  136922. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  136923. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  136924. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  136925. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136926. 14,
  136927. };
  136928. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  136929. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136930. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136931. };
  136932. static long _vq_quantmap__44c0_sm_p5_0[] = {
  136933. 15, 13, 11, 9, 7, 5, 3, 1,
  136934. 0, 2, 4, 6, 8, 10, 12, 14,
  136935. 16,
  136936. };
  136937. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  136938. _vq_quantthresh__44c0_sm_p5_0,
  136939. _vq_quantmap__44c0_sm_p5_0,
  136940. 17,
  136941. 17
  136942. };
  136943. static static_codebook _44c0_sm_p5_0 = {
  136944. 2, 289,
  136945. _vq_lengthlist__44c0_sm_p5_0,
  136946. 1, -529530880, 1611661312, 5, 0,
  136947. _vq_quantlist__44c0_sm_p5_0,
  136948. NULL,
  136949. &_vq_auxt__44c0_sm_p5_0,
  136950. NULL,
  136951. 0
  136952. };
  136953. static long _vq_quantlist__44c0_sm_p6_0[] = {
  136954. 1,
  136955. 0,
  136956. 2,
  136957. };
  136958. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  136959. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  136960. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  136961. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  136962. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  136963. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136964. 11,
  136965. };
  136966. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  136967. -5.5, 5.5,
  136968. };
  136969. static long _vq_quantmap__44c0_sm_p6_0[] = {
  136970. 1, 0, 2,
  136971. };
  136972. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  136973. _vq_quantthresh__44c0_sm_p6_0,
  136974. _vq_quantmap__44c0_sm_p6_0,
  136975. 3,
  136976. 3
  136977. };
  136978. static static_codebook _44c0_sm_p6_0 = {
  136979. 4, 81,
  136980. _vq_lengthlist__44c0_sm_p6_0,
  136981. 1, -529137664, 1618345984, 2, 0,
  136982. _vq_quantlist__44c0_sm_p6_0,
  136983. NULL,
  136984. &_vq_auxt__44c0_sm_p6_0,
  136985. NULL,
  136986. 0
  136987. };
  136988. static long _vq_quantlist__44c0_sm_p6_1[] = {
  136989. 5,
  136990. 4,
  136991. 6,
  136992. 3,
  136993. 7,
  136994. 2,
  136995. 8,
  136996. 1,
  136997. 9,
  136998. 0,
  136999. 10,
  137000. };
  137001. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137002. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137003. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137004. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137005. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137006. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137007. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137008. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137009. 10,10,10, 8, 8, 8, 8, 8, 8,
  137010. };
  137011. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137012. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137013. 3.5, 4.5,
  137014. };
  137015. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137016. 9, 7, 5, 3, 1, 0, 2, 4,
  137017. 6, 8, 10,
  137018. };
  137019. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137020. _vq_quantthresh__44c0_sm_p6_1,
  137021. _vq_quantmap__44c0_sm_p6_1,
  137022. 11,
  137023. 11
  137024. };
  137025. static static_codebook _44c0_sm_p6_1 = {
  137026. 2, 121,
  137027. _vq_lengthlist__44c0_sm_p6_1,
  137028. 1, -531365888, 1611661312, 4, 0,
  137029. _vq_quantlist__44c0_sm_p6_1,
  137030. NULL,
  137031. &_vq_auxt__44c0_sm_p6_1,
  137032. NULL,
  137033. 0
  137034. };
  137035. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137036. 6,
  137037. 5,
  137038. 7,
  137039. 4,
  137040. 8,
  137041. 3,
  137042. 9,
  137043. 2,
  137044. 10,
  137045. 1,
  137046. 11,
  137047. 0,
  137048. 12,
  137049. };
  137050. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137051. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137052. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137053. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137054. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137055. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137056. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137057. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137058. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137059. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137060. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137061. 0,12,12,11,11,13,12,14,14,
  137062. };
  137063. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137064. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137065. 12.5, 17.5, 22.5, 27.5,
  137066. };
  137067. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137068. 11, 9, 7, 5, 3, 1, 0, 2,
  137069. 4, 6, 8, 10, 12,
  137070. };
  137071. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137072. _vq_quantthresh__44c0_sm_p7_0,
  137073. _vq_quantmap__44c0_sm_p7_0,
  137074. 13,
  137075. 13
  137076. };
  137077. static static_codebook _44c0_sm_p7_0 = {
  137078. 2, 169,
  137079. _vq_lengthlist__44c0_sm_p7_0,
  137080. 1, -526516224, 1616117760, 4, 0,
  137081. _vq_quantlist__44c0_sm_p7_0,
  137082. NULL,
  137083. &_vq_auxt__44c0_sm_p7_0,
  137084. NULL,
  137085. 0
  137086. };
  137087. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137088. 2,
  137089. 1,
  137090. 3,
  137091. 0,
  137092. 4,
  137093. };
  137094. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137095. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137096. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137097. };
  137098. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137099. -1.5, -0.5, 0.5, 1.5,
  137100. };
  137101. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137102. 3, 1, 0, 2, 4,
  137103. };
  137104. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137105. _vq_quantthresh__44c0_sm_p7_1,
  137106. _vq_quantmap__44c0_sm_p7_1,
  137107. 5,
  137108. 5
  137109. };
  137110. static static_codebook _44c0_sm_p7_1 = {
  137111. 2, 25,
  137112. _vq_lengthlist__44c0_sm_p7_1,
  137113. 1, -533725184, 1611661312, 3, 0,
  137114. _vq_quantlist__44c0_sm_p7_1,
  137115. NULL,
  137116. &_vq_auxt__44c0_sm_p7_1,
  137117. NULL,
  137118. 0
  137119. };
  137120. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137121. 4,
  137122. 3,
  137123. 5,
  137124. 2,
  137125. 6,
  137126. 1,
  137127. 7,
  137128. 0,
  137129. 8,
  137130. };
  137131. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137132. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137133. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137134. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137135. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137136. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137137. 12,
  137138. };
  137139. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137140. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137141. };
  137142. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137143. 7, 5, 3, 1, 0, 2, 4, 6,
  137144. 8,
  137145. };
  137146. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137147. _vq_quantthresh__44c0_sm_p8_0,
  137148. _vq_quantmap__44c0_sm_p8_0,
  137149. 9,
  137150. 9
  137151. };
  137152. static static_codebook _44c0_sm_p8_0 = {
  137153. 2, 81,
  137154. _vq_lengthlist__44c0_sm_p8_0,
  137155. 1, -516186112, 1627103232, 4, 0,
  137156. _vq_quantlist__44c0_sm_p8_0,
  137157. NULL,
  137158. &_vq_auxt__44c0_sm_p8_0,
  137159. NULL,
  137160. 0
  137161. };
  137162. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137163. 6,
  137164. 5,
  137165. 7,
  137166. 4,
  137167. 8,
  137168. 3,
  137169. 9,
  137170. 2,
  137171. 10,
  137172. 1,
  137173. 11,
  137174. 0,
  137175. 12,
  137176. };
  137177. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137178. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137179. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137180. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137181. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137182. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137183. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137184. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137185. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137186. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137187. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137188. 20,13,13,12,12,16,13,15,13,
  137189. };
  137190. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137191. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137192. 42.5, 59.5, 76.5, 93.5,
  137193. };
  137194. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137195. 11, 9, 7, 5, 3, 1, 0, 2,
  137196. 4, 6, 8, 10, 12,
  137197. };
  137198. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137199. _vq_quantthresh__44c0_sm_p8_1,
  137200. _vq_quantmap__44c0_sm_p8_1,
  137201. 13,
  137202. 13
  137203. };
  137204. static static_codebook _44c0_sm_p8_1 = {
  137205. 2, 169,
  137206. _vq_lengthlist__44c0_sm_p8_1,
  137207. 1, -522616832, 1620115456, 4, 0,
  137208. _vq_quantlist__44c0_sm_p8_1,
  137209. NULL,
  137210. &_vq_auxt__44c0_sm_p8_1,
  137211. NULL,
  137212. 0
  137213. };
  137214. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137215. 8,
  137216. 7,
  137217. 9,
  137218. 6,
  137219. 10,
  137220. 5,
  137221. 11,
  137222. 4,
  137223. 12,
  137224. 3,
  137225. 13,
  137226. 2,
  137227. 14,
  137228. 1,
  137229. 15,
  137230. 0,
  137231. 16,
  137232. };
  137233. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137234. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137235. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137236. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137237. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137238. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137239. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137240. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137241. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137242. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137243. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137244. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137245. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137246. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137247. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137248. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137249. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137250. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137251. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137252. 9,
  137253. };
  137254. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137255. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137256. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137257. };
  137258. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137259. 15, 13, 11, 9, 7, 5, 3, 1,
  137260. 0, 2, 4, 6, 8, 10, 12, 14,
  137261. 16,
  137262. };
  137263. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  137264. _vq_quantthresh__44c0_sm_p8_2,
  137265. _vq_quantmap__44c0_sm_p8_2,
  137266. 17,
  137267. 17
  137268. };
  137269. static static_codebook _44c0_sm_p8_2 = {
  137270. 2, 289,
  137271. _vq_lengthlist__44c0_sm_p8_2,
  137272. 1, -529530880, 1611661312, 5, 0,
  137273. _vq_quantlist__44c0_sm_p8_2,
  137274. NULL,
  137275. &_vq_auxt__44c0_sm_p8_2,
  137276. NULL,
  137277. 0
  137278. };
  137279. static long _huff_lengthlist__44c0_sm_short[] = {
  137280. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  137281. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  137282. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  137283. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  137284. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  137285. 12,
  137286. };
  137287. static static_codebook _huff_book__44c0_sm_short = {
  137288. 2, 81,
  137289. _huff_lengthlist__44c0_sm_short,
  137290. 0, 0, 0, 0, 0,
  137291. NULL,
  137292. NULL,
  137293. NULL,
  137294. NULL,
  137295. 0
  137296. };
  137297. static long _huff_lengthlist__44c1_s_long[] = {
  137298. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  137299. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  137300. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  137301. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  137302. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  137303. 11,
  137304. };
  137305. static static_codebook _huff_book__44c1_s_long = {
  137306. 2, 81,
  137307. _huff_lengthlist__44c1_s_long,
  137308. 0, 0, 0, 0, 0,
  137309. NULL,
  137310. NULL,
  137311. NULL,
  137312. NULL,
  137313. 0
  137314. };
  137315. static long _vq_quantlist__44c1_s_p1_0[] = {
  137316. 1,
  137317. 0,
  137318. 2,
  137319. };
  137320. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137321. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137322. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137327. 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137332. 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  137367. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137372. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  137373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  137377. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137413. 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  137418. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  137419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137422. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137423. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137731. 0,
  137732. };
  137733. static float _vq_quantthresh__44c1_s_p1_0[] = {
  137734. -0.5, 0.5,
  137735. };
  137736. static long _vq_quantmap__44c1_s_p1_0[] = {
  137737. 1, 0, 2,
  137738. };
  137739. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  137740. _vq_quantthresh__44c1_s_p1_0,
  137741. _vq_quantmap__44c1_s_p1_0,
  137742. 3,
  137743. 3
  137744. };
  137745. static static_codebook _44c1_s_p1_0 = {
  137746. 8, 6561,
  137747. _vq_lengthlist__44c1_s_p1_0,
  137748. 1, -535822336, 1611661312, 2, 0,
  137749. _vq_quantlist__44c1_s_p1_0,
  137750. NULL,
  137751. &_vq_auxt__44c1_s_p1_0,
  137752. NULL,
  137753. 0
  137754. };
  137755. static long _vq_quantlist__44c1_s_p2_0[] = {
  137756. 2,
  137757. 1,
  137758. 3,
  137759. 0,
  137760. 4,
  137761. };
  137762. static long _vq_lengthlist__44c1_s_p2_0[] = {
  137763. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  137765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137766. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  137768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137769. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137802. 0,
  137803. };
  137804. static float _vq_quantthresh__44c1_s_p2_0[] = {
  137805. -1.5, -0.5, 0.5, 1.5,
  137806. };
  137807. static long _vq_quantmap__44c1_s_p2_0[] = {
  137808. 3, 1, 0, 2, 4,
  137809. };
  137810. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  137811. _vq_quantthresh__44c1_s_p2_0,
  137812. _vq_quantmap__44c1_s_p2_0,
  137813. 5,
  137814. 5
  137815. };
  137816. static static_codebook _44c1_s_p2_0 = {
  137817. 4, 625,
  137818. _vq_lengthlist__44c1_s_p2_0,
  137819. 1, -533725184, 1611661312, 3, 0,
  137820. _vq_quantlist__44c1_s_p2_0,
  137821. NULL,
  137822. &_vq_auxt__44c1_s_p2_0,
  137823. NULL,
  137824. 0
  137825. };
  137826. static long _vq_quantlist__44c1_s_p3_0[] = {
  137827. 4,
  137828. 3,
  137829. 5,
  137830. 2,
  137831. 6,
  137832. 1,
  137833. 7,
  137834. 0,
  137835. 8,
  137836. };
  137837. static long _vq_lengthlist__44c1_s_p3_0[] = {
  137838. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  137839. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  137840. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  137841. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  137842. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137843. 0,
  137844. };
  137845. static float _vq_quantthresh__44c1_s_p3_0[] = {
  137846. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137847. };
  137848. static long _vq_quantmap__44c1_s_p3_0[] = {
  137849. 7, 5, 3, 1, 0, 2, 4, 6,
  137850. 8,
  137851. };
  137852. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  137853. _vq_quantthresh__44c1_s_p3_0,
  137854. _vq_quantmap__44c1_s_p3_0,
  137855. 9,
  137856. 9
  137857. };
  137858. static static_codebook _44c1_s_p3_0 = {
  137859. 2, 81,
  137860. _vq_lengthlist__44c1_s_p3_0,
  137861. 1, -531628032, 1611661312, 4, 0,
  137862. _vq_quantlist__44c1_s_p3_0,
  137863. NULL,
  137864. &_vq_auxt__44c1_s_p3_0,
  137865. NULL,
  137866. 0
  137867. };
  137868. static long _vq_quantlist__44c1_s_p4_0[] = {
  137869. 4,
  137870. 3,
  137871. 5,
  137872. 2,
  137873. 6,
  137874. 1,
  137875. 7,
  137876. 0,
  137877. 8,
  137878. };
  137879. static long _vq_lengthlist__44c1_s_p4_0[] = {
  137880. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  137881. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  137882. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  137883. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  137884. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137885. 11,
  137886. };
  137887. static float _vq_quantthresh__44c1_s_p4_0[] = {
  137888. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137889. };
  137890. static long _vq_quantmap__44c1_s_p4_0[] = {
  137891. 7, 5, 3, 1, 0, 2, 4, 6,
  137892. 8,
  137893. };
  137894. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  137895. _vq_quantthresh__44c1_s_p4_0,
  137896. _vq_quantmap__44c1_s_p4_0,
  137897. 9,
  137898. 9
  137899. };
  137900. static static_codebook _44c1_s_p4_0 = {
  137901. 2, 81,
  137902. _vq_lengthlist__44c1_s_p4_0,
  137903. 1, -531628032, 1611661312, 4, 0,
  137904. _vq_quantlist__44c1_s_p4_0,
  137905. NULL,
  137906. &_vq_auxt__44c1_s_p4_0,
  137907. NULL,
  137908. 0
  137909. };
  137910. static long _vq_quantlist__44c1_s_p5_0[] = {
  137911. 8,
  137912. 7,
  137913. 9,
  137914. 6,
  137915. 10,
  137916. 5,
  137917. 11,
  137918. 4,
  137919. 12,
  137920. 3,
  137921. 13,
  137922. 2,
  137923. 14,
  137924. 1,
  137925. 15,
  137926. 0,
  137927. 16,
  137928. };
  137929. static long _vq_lengthlist__44c1_s_p5_0[] = {
  137930. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  137931. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  137932. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137933. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  137934. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  137935. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  137936. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  137937. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137938. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  137939. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  137940. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137941. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137942. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  137943. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  137944. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  137945. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  137946. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  137947. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137948. 14,
  137949. };
  137950. static float _vq_quantthresh__44c1_s_p5_0[] = {
  137951. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137952. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137953. };
  137954. static long _vq_quantmap__44c1_s_p5_0[] = {
  137955. 15, 13, 11, 9, 7, 5, 3, 1,
  137956. 0, 2, 4, 6, 8, 10, 12, 14,
  137957. 16,
  137958. };
  137959. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  137960. _vq_quantthresh__44c1_s_p5_0,
  137961. _vq_quantmap__44c1_s_p5_0,
  137962. 17,
  137963. 17
  137964. };
  137965. static static_codebook _44c1_s_p5_0 = {
  137966. 2, 289,
  137967. _vq_lengthlist__44c1_s_p5_0,
  137968. 1, -529530880, 1611661312, 5, 0,
  137969. _vq_quantlist__44c1_s_p5_0,
  137970. NULL,
  137971. &_vq_auxt__44c1_s_p5_0,
  137972. NULL,
  137973. 0
  137974. };
  137975. static long _vq_quantlist__44c1_s_p6_0[] = {
  137976. 1,
  137977. 0,
  137978. 2,
  137979. };
  137980. static long _vq_lengthlist__44c1_s_p6_0[] = {
  137981. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137982. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  137983. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  137984. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  137985. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  137986. 11,
  137987. };
  137988. static float _vq_quantthresh__44c1_s_p6_0[] = {
  137989. -5.5, 5.5,
  137990. };
  137991. static long _vq_quantmap__44c1_s_p6_0[] = {
  137992. 1, 0, 2,
  137993. };
  137994. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  137995. _vq_quantthresh__44c1_s_p6_0,
  137996. _vq_quantmap__44c1_s_p6_0,
  137997. 3,
  137998. 3
  137999. };
  138000. static static_codebook _44c1_s_p6_0 = {
  138001. 4, 81,
  138002. _vq_lengthlist__44c1_s_p6_0,
  138003. 1, -529137664, 1618345984, 2, 0,
  138004. _vq_quantlist__44c1_s_p6_0,
  138005. NULL,
  138006. &_vq_auxt__44c1_s_p6_0,
  138007. NULL,
  138008. 0
  138009. };
  138010. static long _vq_quantlist__44c1_s_p6_1[] = {
  138011. 5,
  138012. 4,
  138013. 6,
  138014. 3,
  138015. 7,
  138016. 2,
  138017. 8,
  138018. 1,
  138019. 9,
  138020. 0,
  138021. 10,
  138022. };
  138023. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138024. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138025. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138026. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138027. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138028. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138029. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138030. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138031. 10,10,10, 8, 8, 8, 8, 8, 8,
  138032. };
  138033. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138034. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138035. 3.5, 4.5,
  138036. };
  138037. static long _vq_quantmap__44c1_s_p6_1[] = {
  138038. 9, 7, 5, 3, 1, 0, 2, 4,
  138039. 6, 8, 10,
  138040. };
  138041. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138042. _vq_quantthresh__44c1_s_p6_1,
  138043. _vq_quantmap__44c1_s_p6_1,
  138044. 11,
  138045. 11
  138046. };
  138047. static static_codebook _44c1_s_p6_1 = {
  138048. 2, 121,
  138049. _vq_lengthlist__44c1_s_p6_1,
  138050. 1, -531365888, 1611661312, 4, 0,
  138051. _vq_quantlist__44c1_s_p6_1,
  138052. NULL,
  138053. &_vq_auxt__44c1_s_p6_1,
  138054. NULL,
  138055. 0
  138056. };
  138057. static long _vq_quantlist__44c1_s_p7_0[] = {
  138058. 6,
  138059. 5,
  138060. 7,
  138061. 4,
  138062. 8,
  138063. 3,
  138064. 9,
  138065. 2,
  138066. 10,
  138067. 1,
  138068. 11,
  138069. 0,
  138070. 12,
  138071. };
  138072. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138073. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138074. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138075. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138076. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138077. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138078. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138079. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138080. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138081. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138082. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138083. 0,12,11,11,11,13,10,14,13,
  138084. };
  138085. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138086. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138087. 12.5, 17.5, 22.5, 27.5,
  138088. };
  138089. static long _vq_quantmap__44c1_s_p7_0[] = {
  138090. 11, 9, 7, 5, 3, 1, 0, 2,
  138091. 4, 6, 8, 10, 12,
  138092. };
  138093. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138094. _vq_quantthresh__44c1_s_p7_0,
  138095. _vq_quantmap__44c1_s_p7_0,
  138096. 13,
  138097. 13
  138098. };
  138099. static static_codebook _44c1_s_p7_0 = {
  138100. 2, 169,
  138101. _vq_lengthlist__44c1_s_p7_0,
  138102. 1, -526516224, 1616117760, 4, 0,
  138103. _vq_quantlist__44c1_s_p7_0,
  138104. NULL,
  138105. &_vq_auxt__44c1_s_p7_0,
  138106. NULL,
  138107. 0
  138108. };
  138109. static long _vq_quantlist__44c1_s_p7_1[] = {
  138110. 2,
  138111. 1,
  138112. 3,
  138113. 0,
  138114. 4,
  138115. };
  138116. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138117. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138118. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138119. };
  138120. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138121. -1.5, -0.5, 0.5, 1.5,
  138122. };
  138123. static long _vq_quantmap__44c1_s_p7_1[] = {
  138124. 3, 1, 0, 2, 4,
  138125. };
  138126. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138127. _vq_quantthresh__44c1_s_p7_1,
  138128. _vq_quantmap__44c1_s_p7_1,
  138129. 5,
  138130. 5
  138131. };
  138132. static static_codebook _44c1_s_p7_1 = {
  138133. 2, 25,
  138134. _vq_lengthlist__44c1_s_p7_1,
  138135. 1, -533725184, 1611661312, 3, 0,
  138136. _vq_quantlist__44c1_s_p7_1,
  138137. NULL,
  138138. &_vq_auxt__44c1_s_p7_1,
  138139. NULL,
  138140. 0
  138141. };
  138142. static long _vq_quantlist__44c1_s_p8_0[] = {
  138143. 6,
  138144. 5,
  138145. 7,
  138146. 4,
  138147. 8,
  138148. 3,
  138149. 9,
  138150. 2,
  138151. 10,
  138152. 1,
  138153. 11,
  138154. 0,
  138155. 12,
  138156. };
  138157. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138158. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138159. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138160. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138161. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138162. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138163. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138164. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138165. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138166. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138167. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138168. 10,10,10,10,10,10,10,10,10,
  138169. };
  138170. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138171. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138172. 552.5, 773.5, 994.5, 1215.5,
  138173. };
  138174. static long _vq_quantmap__44c1_s_p8_0[] = {
  138175. 11, 9, 7, 5, 3, 1, 0, 2,
  138176. 4, 6, 8, 10, 12,
  138177. };
  138178. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138179. _vq_quantthresh__44c1_s_p8_0,
  138180. _vq_quantmap__44c1_s_p8_0,
  138181. 13,
  138182. 13
  138183. };
  138184. static static_codebook _44c1_s_p8_0 = {
  138185. 2, 169,
  138186. _vq_lengthlist__44c1_s_p8_0,
  138187. 1, -514541568, 1627103232, 4, 0,
  138188. _vq_quantlist__44c1_s_p8_0,
  138189. NULL,
  138190. &_vq_auxt__44c1_s_p8_0,
  138191. NULL,
  138192. 0
  138193. };
  138194. static long _vq_quantlist__44c1_s_p8_1[] = {
  138195. 6,
  138196. 5,
  138197. 7,
  138198. 4,
  138199. 8,
  138200. 3,
  138201. 9,
  138202. 2,
  138203. 10,
  138204. 1,
  138205. 11,
  138206. 0,
  138207. 12,
  138208. };
  138209. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138210. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138211. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138212. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138213. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138214. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138215. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138216. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138217. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138218. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138219. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138220. 16,13,12,12,11,14,12,15,13,
  138221. };
  138222. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138223. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138224. 42.5, 59.5, 76.5, 93.5,
  138225. };
  138226. static long _vq_quantmap__44c1_s_p8_1[] = {
  138227. 11, 9, 7, 5, 3, 1, 0, 2,
  138228. 4, 6, 8, 10, 12,
  138229. };
  138230. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138231. _vq_quantthresh__44c1_s_p8_1,
  138232. _vq_quantmap__44c1_s_p8_1,
  138233. 13,
  138234. 13
  138235. };
  138236. static static_codebook _44c1_s_p8_1 = {
  138237. 2, 169,
  138238. _vq_lengthlist__44c1_s_p8_1,
  138239. 1, -522616832, 1620115456, 4, 0,
  138240. _vq_quantlist__44c1_s_p8_1,
  138241. NULL,
  138242. &_vq_auxt__44c1_s_p8_1,
  138243. NULL,
  138244. 0
  138245. };
  138246. static long _vq_quantlist__44c1_s_p8_2[] = {
  138247. 8,
  138248. 7,
  138249. 9,
  138250. 6,
  138251. 10,
  138252. 5,
  138253. 11,
  138254. 4,
  138255. 12,
  138256. 3,
  138257. 13,
  138258. 2,
  138259. 14,
  138260. 1,
  138261. 15,
  138262. 0,
  138263. 16,
  138264. };
  138265. static long _vq_lengthlist__44c1_s_p8_2[] = {
  138266. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138267. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138268. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138269. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138270. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138271. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138272. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138273. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  138274. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  138275. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138276. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  138277. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138278. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  138279. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  138280. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138281. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  138282. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138283. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  138284. 9,
  138285. };
  138286. static float _vq_quantthresh__44c1_s_p8_2[] = {
  138287. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138288. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138289. };
  138290. static long _vq_quantmap__44c1_s_p8_2[] = {
  138291. 15, 13, 11, 9, 7, 5, 3, 1,
  138292. 0, 2, 4, 6, 8, 10, 12, 14,
  138293. 16,
  138294. };
  138295. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  138296. _vq_quantthresh__44c1_s_p8_2,
  138297. _vq_quantmap__44c1_s_p8_2,
  138298. 17,
  138299. 17
  138300. };
  138301. static static_codebook _44c1_s_p8_2 = {
  138302. 2, 289,
  138303. _vq_lengthlist__44c1_s_p8_2,
  138304. 1, -529530880, 1611661312, 5, 0,
  138305. _vq_quantlist__44c1_s_p8_2,
  138306. NULL,
  138307. &_vq_auxt__44c1_s_p8_2,
  138308. NULL,
  138309. 0
  138310. };
  138311. static long _huff_lengthlist__44c1_s_short[] = {
  138312. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138313. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138314. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138315. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138316. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138317. 11,
  138318. };
  138319. static static_codebook _huff_book__44c1_s_short = {
  138320. 2, 81,
  138321. _huff_lengthlist__44c1_s_short,
  138322. 0, 0, 0, 0, 0,
  138323. NULL,
  138324. NULL,
  138325. NULL,
  138326. NULL,
  138327. 0
  138328. };
  138329. static long _huff_lengthlist__44c1_sm_long[] = {
  138330. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138331. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138332. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138333. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138334. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138335. 11,
  138336. };
  138337. static static_codebook _huff_book__44c1_sm_long = {
  138338. 2, 81,
  138339. _huff_lengthlist__44c1_sm_long,
  138340. 0, 0, 0, 0, 0,
  138341. NULL,
  138342. NULL,
  138343. NULL,
  138344. NULL,
  138345. 0
  138346. };
  138347. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138348. 1,
  138349. 0,
  138350. 2,
  138351. };
  138352. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138353. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138354. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138359. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138364. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  138399. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138404. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  138409. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138445. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138450. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138455. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138763. 0,
  138764. };
  138765. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  138766. -0.5, 0.5,
  138767. };
  138768. static long _vq_quantmap__44c1_sm_p1_0[] = {
  138769. 1, 0, 2,
  138770. };
  138771. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  138772. _vq_quantthresh__44c1_sm_p1_0,
  138773. _vq_quantmap__44c1_sm_p1_0,
  138774. 3,
  138775. 3
  138776. };
  138777. static static_codebook _44c1_sm_p1_0 = {
  138778. 8, 6561,
  138779. _vq_lengthlist__44c1_sm_p1_0,
  138780. 1, -535822336, 1611661312, 2, 0,
  138781. _vq_quantlist__44c1_sm_p1_0,
  138782. NULL,
  138783. &_vq_auxt__44c1_sm_p1_0,
  138784. NULL,
  138785. 0
  138786. };
  138787. static long _vq_quantlist__44c1_sm_p2_0[] = {
  138788. 2,
  138789. 1,
  138790. 3,
  138791. 0,
  138792. 4,
  138793. };
  138794. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  138795. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138798. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  138800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138801. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  138802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138834. 0,
  138835. };
  138836. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  138837. -1.5, -0.5, 0.5, 1.5,
  138838. };
  138839. static long _vq_quantmap__44c1_sm_p2_0[] = {
  138840. 3, 1, 0, 2, 4,
  138841. };
  138842. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  138843. _vq_quantthresh__44c1_sm_p2_0,
  138844. _vq_quantmap__44c1_sm_p2_0,
  138845. 5,
  138846. 5
  138847. };
  138848. static static_codebook _44c1_sm_p2_0 = {
  138849. 4, 625,
  138850. _vq_lengthlist__44c1_sm_p2_0,
  138851. 1, -533725184, 1611661312, 3, 0,
  138852. _vq_quantlist__44c1_sm_p2_0,
  138853. NULL,
  138854. &_vq_auxt__44c1_sm_p2_0,
  138855. NULL,
  138856. 0
  138857. };
  138858. static long _vq_quantlist__44c1_sm_p3_0[] = {
  138859. 4,
  138860. 3,
  138861. 5,
  138862. 2,
  138863. 6,
  138864. 1,
  138865. 7,
  138866. 0,
  138867. 8,
  138868. };
  138869. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  138870. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  138871. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  138872. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138873. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138874. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138875. 0,
  138876. };
  138877. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  138878. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138879. };
  138880. static long _vq_quantmap__44c1_sm_p3_0[] = {
  138881. 7, 5, 3, 1, 0, 2, 4, 6,
  138882. 8,
  138883. };
  138884. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  138885. _vq_quantthresh__44c1_sm_p3_0,
  138886. _vq_quantmap__44c1_sm_p3_0,
  138887. 9,
  138888. 9
  138889. };
  138890. static static_codebook _44c1_sm_p3_0 = {
  138891. 2, 81,
  138892. _vq_lengthlist__44c1_sm_p3_0,
  138893. 1, -531628032, 1611661312, 4, 0,
  138894. _vq_quantlist__44c1_sm_p3_0,
  138895. NULL,
  138896. &_vq_auxt__44c1_sm_p3_0,
  138897. NULL,
  138898. 0
  138899. };
  138900. static long _vq_quantlist__44c1_sm_p4_0[] = {
  138901. 4,
  138902. 3,
  138903. 5,
  138904. 2,
  138905. 6,
  138906. 1,
  138907. 7,
  138908. 0,
  138909. 8,
  138910. };
  138911. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  138912. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  138913. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  138914. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  138915. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  138916. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138917. 11,
  138918. };
  138919. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  138920. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138921. };
  138922. static long _vq_quantmap__44c1_sm_p4_0[] = {
  138923. 7, 5, 3, 1, 0, 2, 4, 6,
  138924. 8,
  138925. };
  138926. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  138927. _vq_quantthresh__44c1_sm_p4_0,
  138928. _vq_quantmap__44c1_sm_p4_0,
  138929. 9,
  138930. 9
  138931. };
  138932. static static_codebook _44c1_sm_p4_0 = {
  138933. 2, 81,
  138934. _vq_lengthlist__44c1_sm_p4_0,
  138935. 1, -531628032, 1611661312, 4, 0,
  138936. _vq_quantlist__44c1_sm_p4_0,
  138937. NULL,
  138938. &_vq_auxt__44c1_sm_p4_0,
  138939. NULL,
  138940. 0
  138941. };
  138942. static long _vq_quantlist__44c1_sm_p5_0[] = {
  138943. 8,
  138944. 7,
  138945. 9,
  138946. 6,
  138947. 10,
  138948. 5,
  138949. 11,
  138950. 4,
  138951. 12,
  138952. 3,
  138953. 13,
  138954. 2,
  138955. 14,
  138956. 1,
  138957. 15,
  138958. 0,
  138959. 16,
  138960. };
  138961. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  138962. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138963. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138964. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  138965. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138966. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138967. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  138968. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  138969. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138970. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138971. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  138972. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138973. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138974. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138975. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138976. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  138977. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138978. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  138979. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138980. 14,
  138981. };
  138982. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  138983. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138984. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138985. };
  138986. static long _vq_quantmap__44c1_sm_p5_0[] = {
  138987. 15, 13, 11, 9, 7, 5, 3, 1,
  138988. 0, 2, 4, 6, 8, 10, 12, 14,
  138989. 16,
  138990. };
  138991. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  138992. _vq_quantthresh__44c1_sm_p5_0,
  138993. _vq_quantmap__44c1_sm_p5_0,
  138994. 17,
  138995. 17
  138996. };
  138997. static static_codebook _44c1_sm_p5_0 = {
  138998. 2, 289,
  138999. _vq_lengthlist__44c1_sm_p5_0,
  139000. 1, -529530880, 1611661312, 5, 0,
  139001. _vq_quantlist__44c1_sm_p5_0,
  139002. NULL,
  139003. &_vq_auxt__44c1_sm_p5_0,
  139004. NULL,
  139005. 0
  139006. };
  139007. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139008. 1,
  139009. 0,
  139010. 2,
  139011. };
  139012. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139013. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139014. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139015. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139016. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139017. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139018. 11,
  139019. };
  139020. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139021. -5.5, 5.5,
  139022. };
  139023. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139024. 1, 0, 2,
  139025. };
  139026. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139027. _vq_quantthresh__44c1_sm_p6_0,
  139028. _vq_quantmap__44c1_sm_p6_0,
  139029. 3,
  139030. 3
  139031. };
  139032. static static_codebook _44c1_sm_p6_0 = {
  139033. 4, 81,
  139034. _vq_lengthlist__44c1_sm_p6_0,
  139035. 1, -529137664, 1618345984, 2, 0,
  139036. _vq_quantlist__44c1_sm_p6_0,
  139037. NULL,
  139038. &_vq_auxt__44c1_sm_p6_0,
  139039. NULL,
  139040. 0
  139041. };
  139042. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139043. 5,
  139044. 4,
  139045. 6,
  139046. 3,
  139047. 7,
  139048. 2,
  139049. 8,
  139050. 1,
  139051. 9,
  139052. 0,
  139053. 10,
  139054. };
  139055. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139056. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139057. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139058. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139059. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139060. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139061. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139062. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139063. 10,10,10, 8, 8, 8, 8, 8, 8,
  139064. };
  139065. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139066. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139067. 3.5, 4.5,
  139068. };
  139069. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139070. 9, 7, 5, 3, 1, 0, 2, 4,
  139071. 6, 8, 10,
  139072. };
  139073. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139074. _vq_quantthresh__44c1_sm_p6_1,
  139075. _vq_quantmap__44c1_sm_p6_1,
  139076. 11,
  139077. 11
  139078. };
  139079. static static_codebook _44c1_sm_p6_1 = {
  139080. 2, 121,
  139081. _vq_lengthlist__44c1_sm_p6_1,
  139082. 1, -531365888, 1611661312, 4, 0,
  139083. _vq_quantlist__44c1_sm_p6_1,
  139084. NULL,
  139085. &_vq_auxt__44c1_sm_p6_1,
  139086. NULL,
  139087. 0
  139088. };
  139089. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139090. 6,
  139091. 5,
  139092. 7,
  139093. 4,
  139094. 8,
  139095. 3,
  139096. 9,
  139097. 2,
  139098. 10,
  139099. 1,
  139100. 11,
  139101. 0,
  139102. 12,
  139103. };
  139104. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139105. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139106. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139107. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139108. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139109. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139110. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139111. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139112. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139113. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139114. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139115. 0,12,12,11,11,13,12,14,13,
  139116. };
  139117. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139118. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139119. 12.5, 17.5, 22.5, 27.5,
  139120. };
  139121. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139122. 11, 9, 7, 5, 3, 1, 0, 2,
  139123. 4, 6, 8, 10, 12,
  139124. };
  139125. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139126. _vq_quantthresh__44c1_sm_p7_0,
  139127. _vq_quantmap__44c1_sm_p7_0,
  139128. 13,
  139129. 13
  139130. };
  139131. static static_codebook _44c1_sm_p7_0 = {
  139132. 2, 169,
  139133. _vq_lengthlist__44c1_sm_p7_0,
  139134. 1, -526516224, 1616117760, 4, 0,
  139135. _vq_quantlist__44c1_sm_p7_0,
  139136. NULL,
  139137. &_vq_auxt__44c1_sm_p7_0,
  139138. NULL,
  139139. 0
  139140. };
  139141. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139142. 2,
  139143. 1,
  139144. 3,
  139145. 0,
  139146. 4,
  139147. };
  139148. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139149. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139150. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139151. };
  139152. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139153. -1.5, -0.5, 0.5, 1.5,
  139154. };
  139155. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139156. 3, 1, 0, 2, 4,
  139157. };
  139158. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139159. _vq_quantthresh__44c1_sm_p7_1,
  139160. _vq_quantmap__44c1_sm_p7_1,
  139161. 5,
  139162. 5
  139163. };
  139164. static static_codebook _44c1_sm_p7_1 = {
  139165. 2, 25,
  139166. _vq_lengthlist__44c1_sm_p7_1,
  139167. 1, -533725184, 1611661312, 3, 0,
  139168. _vq_quantlist__44c1_sm_p7_1,
  139169. NULL,
  139170. &_vq_auxt__44c1_sm_p7_1,
  139171. NULL,
  139172. 0
  139173. };
  139174. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139175. 6,
  139176. 5,
  139177. 7,
  139178. 4,
  139179. 8,
  139180. 3,
  139181. 9,
  139182. 2,
  139183. 10,
  139184. 1,
  139185. 11,
  139186. 0,
  139187. 12,
  139188. };
  139189. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139190. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139191. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139192. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139193. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139194. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139195. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139196. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139197. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139198. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139199. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139200. 13,13,13,13,13,13,13,13,13,
  139201. };
  139202. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139203. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139204. 552.5, 773.5, 994.5, 1215.5,
  139205. };
  139206. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139207. 11, 9, 7, 5, 3, 1, 0, 2,
  139208. 4, 6, 8, 10, 12,
  139209. };
  139210. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139211. _vq_quantthresh__44c1_sm_p8_0,
  139212. _vq_quantmap__44c1_sm_p8_0,
  139213. 13,
  139214. 13
  139215. };
  139216. static static_codebook _44c1_sm_p8_0 = {
  139217. 2, 169,
  139218. _vq_lengthlist__44c1_sm_p8_0,
  139219. 1, -514541568, 1627103232, 4, 0,
  139220. _vq_quantlist__44c1_sm_p8_0,
  139221. NULL,
  139222. &_vq_auxt__44c1_sm_p8_0,
  139223. NULL,
  139224. 0
  139225. };
  139226. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139227. 6,
  139228. 5,
  139229. 7,
  139230. 4,
  139231. 8,
  139232. 3,
  139233. 9,
  139234. 2,
  139235. 10,
  139236. 1,
  139237. 11,
  139238. 0,
  139239. 12,
  139240. };
  139241. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139242. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139243. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139244. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139245. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139246. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139247. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139248. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139249. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139250. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139251. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139252. 20,13,12,12,12,14,12,14,13,
  139253. };
  139254. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139255. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139256. 42.5, 59.5, 76.5, 93.5,
  139257. };
  139258. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139259. 11, 9, 7, 5, 3, 1, 0, 2,
  139260. 4, 6, 8, 10, 12,
  139261. };
  139262. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  139263. _vq_quantthresh__44c1_sm_p8_1,
  139264. _vq_quantmap__44c1_sm_p8_1,
  139265. 13,
  139266. 13
  139267. };
  139268. static static_codebook _44c1_sm_p8_1 = {
  139269. 2, 169,
  139270. _vq_lengthlist__44c1_sm_p8_1,
  139271. 1, -522616832, 1620115456, 4, 0,
  139272. _vq_quantlist__44c1_sm_p8_1,
  139273. NULL,
  139274. &_vq_auxt__44c1_sm_p8_1,
  139275. NULL,
  139276. 0
  139277. };
  139278. static long _vq_quantlist__44c1_sm_p8_2[] = {
  139279. 8,
  139280. 7,
  139281. 9,
  139282. 6,
  139283. 10,
  139284. 5,
  139285. 11,
  139286. 4,
  139287. 12,
  139288. 3,
  139289. 13,
  139290. 2,
  139291. 14,
  139292. 1,
  139293. 15,
  139294. 0,
  139295. 16,
  139296. };
  139297. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  139298. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139299. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139300. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139301. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139302. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139303. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139304. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139305. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139306. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139307. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139308. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139309. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139310. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139311. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139312. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139313. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139314. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139315. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139316. 9,
  139317. };
  139318. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139319. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139320. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139321. };
  139322. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139323. 15, 13, 11, 9, 7, 5, 3, 1,
  139324. 0, 2, 4, 6, 8, 10, 12, 14,
  139325. 16,
  139326. };
  139327. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139328. _vq_quantthresh__44c1_sm_p8_2,
  139329. _vq_quantmap__44c1_sm_p8_2,
  139330. 17,
  139331. 17
  139332. };
  139333. static static_codebook _44c1_sm_p8_2 = {
  139334. 2, 289,
  139335. _vq_lengthlist__44c1_sm_p8_2,
  139336. 1, -529530880, 1611661312, 5, 0,
  139337. _vq_quantlist__44c1_sm_p8_2,
  139338. NULL,
  139339. &_vq_auxt__44c1_sm_p8_2,
  139340. NULL,
  139341. 0
  139342. };
  139343. static long _huff_lengthlist__44c1_sm_short[] = {
  139344. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139345. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139346. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139347. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139348. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139349. 11,
  139350. };
  139351. static static_codebook _huff_book__44c1_sm_short = {
  139352. 2, 81,
  139353. _huff_lengthlist__44c1_sm_short,
  139354. 0, 0, 0, 0, 0,
  139355. NULL,
  139356. NULL,
  139357. NULL,
  139358. NULL,
  139359. 0
  139360. };
  139361. static long _huff_lengthlist__44cn1_s_long[] = {
  139362. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139363. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139364. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139365. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139366. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139367. 20,
  139368. };
  139369. static static_codebook _huff_book__44cn1_s_long = {
  139370. 2, 81,
  139371. _huff_lengthlist__44cn1_s_long,
  139372. 0, 0, 0, 0, 0,
  139373. NULL,
  139374. NULL,
  139375. NULL,
  139376. NULL,
  139377. 0
  139378. };
  139379. static long _vq_quantlist__44cn1_s_p1_0[] = {
  139380. 1,
  139381. 0,
  139382. 2,
  139383. };
  139384. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  139385. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139386. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139390. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139391. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139395. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  139396. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  139431. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  139432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  139436. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  139441. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  139442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139476. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  139477. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139481. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139482. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  139483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139486. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  139487. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  139488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139771. 0, 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, 0,
  139773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139776. 0, 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, 0,
  139778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139795. 0,
  139796. };
  139797. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  139798. -0.5, 0.5,
  139799. };
  139800. static long _vq_quantmap__44cn1_s_p1_0[] = {
  139801. 1, 0, 2,
  139802. };
  139803. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  139804. _vq_quantthresh__44cn1_s_p1_0,
  139805. _vq_quantmap__44cn1_s_p1_0,
  139806. 3,
  139807. 3
  139808. };
  139809. static static_codebook _44cn1_s_p1_0 = {
  139810. 8, 6561,
  139811. _vq_lengthlist__44cn1_s_p1_0,
  139812. 1, -535822336, 1611661312, 2, 0,
  139813. _vq_quantlist__44cn1_s_p1_0,
  139814. NULL,
  139815. &_vq_auxt__44cn1_s_p1_0,
  139816. NULL,
  139817. 0
  139818. };
  139819. static long _vq_quantlist__44cn1_s_p2_0[] = {
  139820. 2,
  139821. 1,
  139822. 3,
  139823. 0,
  139824. 4,
  139825. };
  139826. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  139827. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  139829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139830. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  139832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139833. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139866. 0,
  139867. };
  139868. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  139869. -1.5, -0.5, 0.5, 1.5,
  139870. };
  139871. static long _vq_quantmap__44cn1_s_p2_0[] = {
  139872. 3, 1, 0, 2, 4,
  139873. };
  139874. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  139875. _vq_quantthresh__44cn1_s_p2_0,
  139876. _vq_quantmap__44cn1_s_p2_0,
  139877. 5,
  139878. 5
  139879. };
  139880. static static_codebook _44cn1_s_p2_0 = {
  139881. 4, 625,
  139882. _vq_lengthlist__44cn1_s_p2_0,
  139883. 1, -533725184, 1611661312, 3, 0,
  139884. _vq_quantlist__44cn1_s_p2_0,
  139885. NULL,
  139886. &_vq_auxt__44cn1_s_p2_0,
  139887. NULL,
  139888. 0
  139889. };
  139890. static long _vq_quantlist__44cn1_s_p3_0[] = {
  139891. 4,
  139892. 3,
  139893. 5,
  139894. 2,
  139895. 6,
  139896. 1,
  139897. 7,
  139898. 0,
  139899. 8,
  139900. };
  139901. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  139902. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  139903. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  139904. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139905. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139906. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139907. 0,
  139908. };
  139909. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  139910. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139911. };
  139912. static long _vq_quantmap__44cn1_s_p3_0[] = {
  139913. 7, 5, 3, 1, 0, 2, 4, 6,
  139914. 8,
  139915. };
  139916. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  139917. _vq_quantthresh__44cn1_s_p3_0,
  139918. _vq_quantmap__44cn1_s_p3_0,
  139919. 9,
  139920. 9
  139921. };
  139922. static static_codebook _44cn1_s_p3_0 = {
  139923. 2, 81,
  139924. _vq_lengthlist__44cn1_s_p3_0,
  139925. 1, -531628032, 1611661312, 4, 0,
  139926. _vq_quantlist__44cn1_s_p3_0,
  139927. NULL,
  139928. &_vq_auxt__44cn1_s_p3_0,
  139929. NULL,
  139930. 0
  139931. };
  139932. static long _vq_quantlist__44cn1_s_p4_0[] = {
  139933. 4,
  139934. 3,
  139935. 5,
  139936. 2,
  139937. 6,
  139938. 1,
  139939. 7,
  139940. 0,
  139941. 8,
  139942. };
  139943. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  139944. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  139945. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  139946. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  139947. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  139948. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  139949. 11,
  139950. };
  139951. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  139952. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139953. };
  139954. static long _vq_quantmap__44cn1_s_p4_0[] = {
  139955. 7, 5, 3, 1, 0, 2, 4, 6,
  139956. 8,
  139957. };
  139958. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  139959. _vq_quantthresh__44cn1_s_p4_0,
  139960. _vq_quantmap__44cn1_s_p4_0,
  139961. 9,
  139962. 9
  139963. };
  139964. static static_codebook _44cn1_s_p4_0 = {
  139965. 2, 81,
  139966. _vq_lengthlist__44cn1_s_p4_0,
  139967. 1, -531628032, 1611661312, 4, 0,
  139968. _vq_quantlist__44cn1_s_p4_0,
  139969. NULL,
  139970. &_vq_auxt__44cn1_s_p4_0,
  139971. NULL,
  139972. 0
  139973. };
  139974. static long _vq_quantlist__44cn1_s_p5_0[] = {
  139975. 8,
  139976. 7,
  139977. 9,
  139978. 6,
  139979. 10,
  139980. 5,
  139981. 11,
  139982. 4,
  139983. 12,
  139984. 3,
  139985. 13,
  139986. 2,
  139987. 14,
  139988. 1,
  139989. 15,
  139990. 0,
  139991. 16,
  139992. };
  139993. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  139994. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  139995. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139996. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  139997. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139998. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139999. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140000. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140001. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140002. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140003. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140004. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140005. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140006. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140007. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140008. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140009. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140010. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140011. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140012. 14,
  140013. };
  140014. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140015. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140016. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140017. };
  140018. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140019. 15, 13, 11, 9, 7, 5, 3, 1,
  140020. 0, 2, 4, 6, 8, 10, 12, 14,
  140021. 16,
  140022. };
  140023. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140024. _vq_quantthresh__44cn1_s_p5_0,
  140025. _vq_quantmap__44cn1_s_p5_0,
  140026. 17,
  140027. 17
  140028. };
  140029. static static_codebook _44cn1_s_p5_0 = {
  140030. 2, 289,
  140031. _vq_lengthlist__44cn1_s_p5_0,
  140032. 1, -529530880, 1611661312, 5, 0,
  140033. _vq_quantlist__44cn1_s_p5_0,
  140034. NULL,
  140035. &_vq_auxt__44cn1_s_p5_0,
  140036. NULL,
  140037. 0
  140038. };
  140039. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140040. 1,
  140041. 0,
  140042. 2,
  140043. };
  140044. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140045. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140046. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140047. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140048. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140049. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140050. 10,
  140051. };
  140052. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140053. -5.5, 5.5,
  140054. };
  140055. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140056. 1, 0, 2,
  140057. };
  140058. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140059. _vq_quantthresh__44cn1_s_p6_0,
  140060. _vq_quantmap__44cn1_s_p6_0,
  140061. 3,
  140062. 3
  140063. };
  140064. static static_codebook _44cn1_s_p6_0 = {
  140065. 4, 81,
  140066. _vq_lengthlist__44cn1_s_p6_0,
  140067. 1, -529137664, 1618345984, 2, 0,
  140068. _vq_quantlist__44cn1_s_p6_0,
  140069. NULL,
  140070. &_vq_auxt__44cn1_s_p6_0,
  140071. NULL,
  140072. 0
  140073. };
  140074. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140075. 5,
  140076. 4,
  140077. 6,
  140078. 3,
  140079. 7,
  140080. 2,
  140081. 8,
  140082. 1,
  140083. 9,
  140084. 0,
  140085. 10,
  140086. };
  140087. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140088. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140089. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140090. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140091. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140092. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140093. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140094. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140095. 10,10,10, 9, 9, 9, 9, 9, 9,
  140096. };
  140097. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140098. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140099. 3.5, 4.5,
  140100. };
  140101. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140102. 9, 7, 5, 3, 1, 0, 2, 4,
  140103. 6, 8, 10,
  140104. };
  140105. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140106. _vq_quantthresh__44cn1_s_p6_1,
  140107. _vq_quantmap__44cn1_s_p6_1,
  140108. 11,
  140109. 11
  140110. };
  140111. static static_codebook _44cn1_s_p6_1 = {
  140112. 2, 121,
  140113. _vq_lengthlist__44cn1_s_p6_1,
  140114. 1, -531365888, 1611661312, 4, 0,
  140115. _vq_quantlist__44cn1_s_p6_1,
  140116. NULL,
  140117. &_vq_auxt__44cn1_s_p6_1,
  140118. NULL,
  140119. 0
  140120. };
  140121. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140122. 6,
  140123. 5,
  140124. 7,
  140125. 4,
  140126. 8,
  140127. 3,
  140128. 9,
  140129. 2,
  140130. 10,
  140131. 1,
  140132. 11,
  140133. 0,
  140134. 12,
  140135. };
  140136. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140137. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140138. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140139. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140140. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140141. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140142. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140143. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140144. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140145. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140146. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140147. 0,13,13,12,12,13,13,13,14,
  140148. };
  140149. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140150. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140151. 12.5, 17.5, 22.5, 27.5,
  140152. };
  140153. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140154. 11, 9, 7, 5, 3, 1, 0, 2,
  140155. 4, 6, 8, 10, 12,
  140156. };
  140157. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140158. _vq_quantthresh__44cn1_s_p7_0,
  140159. _vq_quantmap__44cn1_s_p7_0,
  140160. 13,
  140161. 13
  140162. };
  140163. static static_codebook _44cn1_s_p7_0 = {
  140164. 2, 169,
  140165. _vq_lengthlist__44cn1_s_p7_0,
  140166. 1, -526516224, 1616117760, 4, 0,
  140167. _vq_quantlist__44cn1_s_p7_0,
  140168. NULL,
  140169. &_vq_auxt__44cn1_s_p7_0,
  140170. NULL,
  140171. 0
  140172. };
  140173. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140174. 2,
  140175. 1,
  140176. 3,
  140177. 0,
  140178. 4,
  140179. };
  140180. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140181. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140182. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140183. };
  140184. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140185. -1.5, -0.5, 0.5, 1.5,
  140186. };
  140187. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140188. 3, 1, 0, 2, 4,
  140189. };
  140190. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140191. _vq_quantthresh__44cn1_s_p7_1,
  140192. _vq_quantmap__44cn1_s_p7_1,
  140193. 5,
  140194. 5
  140195. };
  140196. static static_codebook _44cn1_s_p7_1 = {
  140197. 2, 25,
  140198. _vq_lengthlist__44cn1_s_p7_1,
  140199. 1, -533725184, 1611661312, 3, 0,
  140200. _vq_quantlist__44cn1_s_p7_1,
  140201. NULL,
  140202. &_vq_auxt__44cn1_s_p7_1,
  140203. NULL,
  140204. 0
  140205. };
  140206. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140207. 2,
  140208. 1,
  140209. 3,
  140210. 0,
  140211. 4,
  140212. };
  140213. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140214. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140215. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140216. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140217. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140218. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140219. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140220. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140221. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140222. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140223. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140224. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140225. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140226. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140227. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140228. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140229. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140230. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140231. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140232. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140233. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140234. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140235. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140236. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140237. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140238. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140239. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140240. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140241. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140242. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140243. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140244. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140245. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140246. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140247. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  140248. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140249. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140250. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140251. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140252. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140253. 12,
  140254. };
  140255. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140256. -331.5, -110.5, 110.5, 331.5,
  140257. };
  140258. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140259. 3, 1, 0, 2, 4,
  140260. };
  140261. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140262. _vq_quantthresh__44cn1_s_p8_0,
  140263. _vq_quantmap__44cn1_s_p8_0,
  140264. 5,
  140265. 5
  140266. };
  140267. static static_codebook _44cn1_s_p8_0 = {
  140268. 4, 625,
  140269. _vq_lengthlist__44cn1_s_p8_0,
  140270. 1, -518283264, 1627103232, 3, 0,
  140271. _vq_quantlist__44cn1_s_p8_0,
  140272. NULL,
  140273. &_vq_auxt__44cn1_s_p8_0,
  140274. NULL,
  140275. 0
  140276. };
  140277. static long _vq_quantlist__44cn1_s_p8_1[] = {
  140278. 6,
  140279. 5,
  140280. 7,
  140281. 4,
  140282. 8,
  140283. 3,
  140284. 9,
  140285. 2,
  140286. 10,
  140287. 1,
  140288. 11,
  140289. 0,
  140290. 12,
  140291. };
  140292. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  140293. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  140294. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  140295. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  140296. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  140297. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  140298. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  140299. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  140300. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  140301. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  140302. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  140303. 15,12,12,11,11,14,12,13,14,
  140304. };
  140305. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140306. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140307. 42.5, 59.5, 76.5, 93.5,
  140308. };
  140309. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140310. 11, 9, 7, 5, 3, 1, 0, 2,
  140311. 4, 6, 8, 10, 12,
  140312. };
  140313. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140314. _vq_quantthresh__44cn1_s_p8_1,
  140315. _vq_quantmap__44cn1_s_p8_1,
  140316. 13,
  140317. 13
  140318. };
  140319. static static_codebook _44cn1_s_p8_1 = {
  140320. 2, 169,
  140321. _vq_lengthlist__44cn1_s_p8_1,
  140322. 1, -522616832, 1620115456, 4, 0,
  140323. _vq_quantlist__44cn1_s_p8_1,
  140324. NULL,
  140325. &_vq_auxt__44cn1_s_p8_1,
  140326. NULL,
  140327. 0
  140328. };
  140329. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140330. 8,
  140331. 7,
  140332. 9,
  140333. 6,
  140334. 10,
  140335. 5,
  140336. 11,
  140337. 4,
  140338. 12,
  140339. 3,
  140340. 13,
  140341. 2,
  140342. 14,
  140343. 1,
  140344. 15,
  140345. 0,
  140346. 16,
  140347. };
  140348. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140349. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140350. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140351. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140352. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140353. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140354. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140355. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140356. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140357. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140358. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140359. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140360. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140361. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140362. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140363. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140364. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140365. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140366. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140367. 9,
  140368. };
  140369. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140370. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140371. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140372. };
  140373. static long _vq_quantmap__44cn1_s_p8_2[] = {
  140374. 15, 13, 11, 9, 7, 5, 3, 1,
  140375. 0, 2, 4, 6, 8, 10, 12, 14,
  140376. 16,
  140377. };
  140378. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  140379. _vq_quantthresh__44cn1_s_p8_2,
  140380. _vq_quantmap__44cn1_s_p8_2,
  140381. 17,
  140382. 17
  140383. };
  140384. static static_codebook _44cn1_s_p8_2 = {
  140385. 2, 289,
  140386. _vq_lengthlist__44cn1_s_p8_2,
  140387. 1, -529530880, 1611661312, 5, 0,
  140388. _vq_quantlist__44cn1_s_p8_2,
  140389. NULL,
  140390. &_vq_auxt__44cn1_s_p8_2,
  140391. NULL,
  140392. 0
  140393. };
  140394. static long _huff_lengthlist__44cn1_s_short[] = {
  140395. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  140396. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  140397. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  140398. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  140399. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  140400. 10,
  140401. };
  140402. static static_codebook _huff_book__44cn1_s_short = {
  140403. 2, 81,
  140404. _huff_lengthlist__44cn1_s_short,
  140405. 0, 0, 0, 0, 0,
  140406. NULL,
  140407. NULL,
  140408. NULL,
  140409. NULL,
  140410. 0
  140411. };
  140412. static long _huff_lengthlist__44cn1_sm_long[] = {
  140413. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  140414. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  140415. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  140416. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  140417. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  140418. 17,
  140419. };
  140420. static static_codebook _huff_book__44cn1_sm_long = {
  140421. 2, 81,
  140422. _huff_lengthlist__44cn1_sm_long,
  140423. 0, 0, 0, 0, 0,
  140424. NULL,
  140425. NULL,
  140426. NULL,
  140427. NULL,
  140428. 0
  140429. };
  140430. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  140431. 1,
  140432. 0,
  140433. 2,
  140434. };
  140435. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  140436. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140437. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140441. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140442. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140446. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  140447. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140482. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  140487. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  140492. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  140493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140527. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140528. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140532. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140533. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  140534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140537. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  140538. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  140539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140846. 0,
  140847. };
  140848. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  140849. -0.5, 0.5,
  140850. };
  140851. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  140852. 1, 0, 2,
  140853. };
  140854. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  140855. _vq_quantthresh__44cn1_sm_p1_0,
  140856. _vq_quantmap__44cn1_sm_p1_0,
  140857. 3,
  140858. 3
  140859. };
  140860. static static_codebook _44cn1_sm_p1_0 = {
  140861. 8, 6561,
  140862. _vq_lengthlist__44cn1_sm_p1_0,
  140863. 1, -535822336, 1611661312, 2, 0,
  140864. _vq_quantlist__44cn1_sm_p1_0,
  140865. NULL,
  140866. &_vq_auxt__44cn1_sm_p1_0,
  140867. NULL,
  140868. 0
  140869. };
  140870. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  140871. 2,
  140872. 1,
  140873. 3,
  140874. 0,
  140875. 4,
  140876. };
  140877. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  140878. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140881. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140884. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140917. 0,
  140918. };
  140919. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  140920. -1.5, -0.5, 0.5, 1.5,
  140921. };
  140922. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  140923. 3, 1, 0, 2, 4,
  140924. };
  140925. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  140926. _vq_quantthresh__44cn1_sm_p2_0,
  140927. _vq_quantmap__44cn1_sm_p2_0,
  140928. 5,
  140929. 5
  140930. };
  140931. static static_codebook _44cn1_sm_p2_0 = {
  140932. 4, 625,
  140933. _vq_lengthlist__44cn1_sm_p2_0,
  140934. 1, -533725184, 1611661312, 3, 0,
  140935. _vq_quantlist__44cn1_sm_p2_0,
  140936. NULL,
  140937. &_vq_auxt__44cn1_sm_p2_0,
  140938. NULL,
  140939. 0
  140940. };
  140941. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  140942. 4,
  140943. 3,
  140944. 5,
  140945. 2,
  140946. 6,
  140947. 1,
  140948. 7,
  140949. 0,
  140950. 8,
  140951. };
  140952. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  140953. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  140954. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  140955. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  140956. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  140957. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140958. 0,
  140959. };
  140960. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  140961. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140962. };
  140963. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  140964. 7, 5, 3, 1, 0, 2, 4, 6,
  140965. 8,
  140966. };
  140967. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  140968. _vq_quantthresh__44cn1_sm_p3_0,
  140969. _vq_quantmap__44cn1_sm_p3_0,
  140970. 9,
  140971. 9
  140972. };
  140973. static static_codebook _44cn1_sm_p3_0 = {
  140974. 2, 81,
  140975. _vq_lengthlist__44cn1_sm_p3_0,
  140976. 1, -531628032, 1611661312, 4, 0,
  140977. _vq_quantlist__44cn1_sm_p3_0,
  140978. NULL,
  140979. &_vq_auxt__44cn1_sm_p3_0,
  140980. NULL,
  140981. 0
  140982. };
  140983. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  140984. 4,
  140985. 3,
  140986. 5,
  140987. 2,
  140988. 6,
  140989. 1,
  140990. 7,
  140991. 0,
  140992. 8,
  140993. };
  140994. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  140995. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  140996. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  140997. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  140998. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140999. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141000. 11,
  141001. };
  141002. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141003. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141004. };
  141005. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141006. 7, 5, 3, 1, 0, 2, 4, 6,
  141007. 8,
  141008. };
  141009. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141010. _vq_quantthresh__44cn1_sm_p4_0,
  141011. _vq_quantmap__44cn1_sm_p4_0,
  141012. 9,
  141013. 9
  141014. };
  141015. static static_codebook _44cn1_sm_p4_0 = {
  141016. 2, 81,
  141017. _vq_lengthlist__44cn1_sm_p4_0,
  141018. 1, -531628032, 1611661312, 4, 0,
  141019. _vq_quantlist__44cn1_sm_p4_0,
  141020. NULL,
  141021. &_vq_auxt__44cn1_sm_p4_0,
  141022. NULL,
  141023. 0
  141024. };
  141025. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141026. 8,
  141027. 7,
  141028. 9,
  141029. 6,
  141030. 10,
  141031. 5,
  141032. 11,
  141033. 4,
  141034. 12,
  141035. 3,
  141036. 13,
  141037. 2,
  141038. 14,
  141039. 1,
  141040. 15,
  141041. 0,
  141042. 16,
  141043. };
  141044. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141045. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141046. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141047. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141048. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141049. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141050. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141051. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141052. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141053. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141054. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141055. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141056. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141057. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141058. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141059. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141060. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141061. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141062. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141063. 14,
  141064. };
  141065. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141066. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141067. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141068. };
  141069. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141070. 15, 13, 11, 9, 7, 5, 3, 1,
  141071. 0, 2, 4, 6, 8, 10, 12, 14,
  141072. 16,
  141073. };
  141074. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141075. _vq_quantthresh__44cn1_sm_p5_0,
  141076. _vq_quantmap__44cn1_sm_p5_0,
  141077. 17,
  141078. 17
  141079. };
  141080. static static_codebook _44cn1_sm_p5_0 = {
  141081. 2, 289,
  141082. _vq_lengthlist__44cn1_sm_p5_0,
  141083. 1, -529530880, 1611661312, 5, 0,
  141084. _vq_quantlist__44cn1_sm_p5_0,
  141085. NULL,
  141086. &_vq_auxt__44cn1_sm_p5_0,
  141087. NULL,
  141088. 0
  141089. };
  141090. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141091. 1,
  141092. 0,
  141093. 2,
  141094. };
  141095. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141096. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141097. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141098. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141099. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141100. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141101. 10,
  141102. };
  141103. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141104. -5.5, 5.5,
  141105. };
  141106. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141107. 1, 0, 2,
  141108. };
  141109. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141110. _vq_quantthresh__44cn1_sm_p6_0,
  141111. _vq_quantmap__44cn1_sm_p6_0,
  141112. 3,
  141113. 3
  141114. };
  141115. static static_codebook _44cn1_sm_p6_0 = {
  141116. 4, 81,
  141117. _vq_lengthlist__44cn1_sm_p6_0,
  141118. 1, -529137664, 1618345984, 2, 0,
  141119. _vq_quantlist__44cn1_sm_p6_0,
  141120. NULL,
  141121. &_vq_auxt__44cn1_sm_p6_0,
  141122. NULL,
  141123. 0
  141124. };
  141125. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141126. 5,
  141127. 4,
  141128. 6,
  141129. 3,
  141130. 7,
  141131. 2,
  141132. 8,
  141133. 1,
  141134. 9,
  141135. 0,
  141136. 10,
  141137. };
  141138. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141139. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141140. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141141. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141142. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141143. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141144. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141145. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141146. 10,10,10, 8, 9, 8, 8, 9, 8,
  141147. };
  141148. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141149. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141150. 3.5, 4.5,
  141151. };
  141152. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141153. 9, 7, 5, 3, 1, 0, 2, 4,
  141154. 6, 8, 10,
  141155. };
  141156. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141157. _vq_quantthresh__44cn1_sm_p6_1,
  141158. _vq_quantmap__44cn1_sm_p6_1,
  141159. 11,
  141160. 11
  141161. };
  141162. static static_codebook _44cn1_sm_p6_1 = {
  141163. 2, 121,
  141164. _vq_lengthlist__44cn1_sm_p6_1,
  141165. 1, -531365888, 1611661312, 4, 0,
  141166. _vq_quantlist__44cn1_sm_p6_1,
  141167. NULL,
  141168. &_vq_auxt__44cn1_sm_p6_1,
  141169. NULL,
  141170. 0
  141171. };
  141172. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141173. 6,
  141174. 5,
  141175. 7,
  141176. 4,
  141177. 8,
  141178. 3,
  141179. 9,
  141180. 2,
  141181. 10,
  141182. 1,
  141183. 11,
  141184. 0,
  141185. 12,
  141186. };
  141187. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141188. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141189. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141190. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141191. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141192. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141193. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141194. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141195. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141196. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141197. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141198. 0,13,12,12,12,13,13,13,14,
  141199. };
  141200. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141201. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141202. 12.5, 17.5, 22.5, 27.5,
  141203. };
  141204. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141205. 11, 9, 7, 5, 3, 1, 0, 2,
  141206. 4, 6, 8, 10, 12,
  141207. };
  141208. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141209. _vq_quantthresh__44cn1_sm_p7_0,
  141210. _vq_quantmap__44cn1_sm_p7_0,
  141211. 13,
  141212. 13
  141213. };
  141214. static static_codebook _44cn1_sm_p7_0 = {
  141215. 2, 169,
  141216. _vq_lengthlist__44cn1_sm_p7_0,
  141217. 1, -526516224, 1616117760, 4, 0,
  141218. _vq_quantlist__44cn1_sm_p7_0,
  141219. NULL,
  141220. &_vq_auxt__44cn1_sm_p7_0,
  141221. NULL,
  141222. 0
  141223. };
  141224. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141225. 2,
  141226. 1,
  141227. 3,
  141228. 0,
  141229. 4,
  141230. };
  141231. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141232. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141233. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141234. };
  141235. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141236. -1.5, -0.5, 0.5, 1.5,
  141237. };
  141238. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141239. 3, 1, 0, 2, 4,
  141240. };
  141241. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141242. _vq_quantthresh__44cn1_sm_p7_1,
  141243. _vq_quantmap__44cn1_sm_p7_1,
  141244. 5,
  141245. 5
  141246. };
  141247. static static_codebook _44cn1_sm_p7_1 = {
  141248. 2, 25,
  141249. _vq_lengthlist__44cn1_sm_p7_1,
  141250. 1, -533725184, 1611661312, 3, 0,
  141251. _vq_quantlist__44cn1_sm_p7_1,
  141252. NULL,
  141253. &_vq_auxt__44cn1_sm_p7_1,
  141254. NULL,
  141255. 0
  141256. };
  141257. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141258. 4,
  141259. 3,
  141260. 5,
  141261. 2,
  141262. 6,
  141263. 1,
  141264. 7,
  141265. 0,
  141266. 8,
  141267. };
  141268. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  141269. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  141270. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  141271. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  141272. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  141273. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  141274. 14,
  141275. };
  141276. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  141277. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  141278. };
  141279. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  141280. 7, 5, 3, 1, 0, 2, 4, 6,
  141281. 8,
  141282. };
  141283. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  141284. _vq_quantthresh__44cn1_sm_p8_0,
  141285. _vq_quantmap__44cn1_sm_p8_0,
  141286. 9,
  141287. 9
  141288. };
  141289. static static_codebook _44cn1_sm_p8_0 = {
  141290. 2, 81,
  141291. _vq_lengthlist__44cn1_sm_p8_0,
  141292. 1, -516186112, 1627103232, 4, 0,
  141293. _vq_quantlist__44cn1_sm_p8_0,
  141294. NULL,
  141295. &_vq_auxt__44cn1_sm_p8_0,
  141296. NULL,
  141297. 0
  141298. };
  141299. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  141300. 6,
  141301. 5,
  141302. 7,
  141303. 4,
  141304. 8,
  141305. 3,
  141306. 9,
  141307. 2,
  141308. 10,
  141309. 1,
  141310. 11,
  141311. 0,
  141312. 12,
  141313. };
  141314. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141315. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141316. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141317. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141318. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141319. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141320. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141321. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141322. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141323. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141324. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141325. 17,12,12,11,10,13,11,13,13,
  141326. };
  141327. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141328. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141329. 42.5, 59.5, 76.5, 93.5,
  141330. };
  141331. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141332. 11, 9, 7, 5, 3, 1, 0, 2,
  141333. 4, 6, 8, 10, 12,
  141334. };
  141335. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141336. _vq_quantthresh__44cn1_sm_p8_1,
  141337. _vq_quantmap__44cn1_sm_p8_1,
  141338. 13,
  141339. 13
  141340. };
  141341. static static_codebook _44cn1_sm_p8_1 = {
  141342. 2, 169,
  141343. _vq_lengthlist__44cn1_sm_p8_1,
  141344. 1, -522616832, 1620115456, 4, 0,
  141345. _vq_quantlist__44cn1_sm_p8_1,
  141346. NULL,
  141347. &_vq_auxt__44cn1_sm_p8_1,
  141348. NULL,
  141349. 0
  141350. };
  141351. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141352. 8,
  141353. 7,
  141354. 9,
  141355. 6,
  141356. 10,
  141357. 5,
  141358. 11,
  141359. 4,
  141360. 12,
  141361. 3,
  141362. 13,
  141363. 2,
  141364. 14,
  141365. 1,
  141366. 15,
  141367. 0,
  141368. 16,
  141369. };
  141370. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  141371. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141372. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  141373. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  141374. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  141375. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  141376. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  141377. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  141378. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  141379. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  141380. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  141381. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  141382. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  141383. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  141384. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  141385. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  141386. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141387. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141388. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  141389. 9,
  141390. };
  141391. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  141392. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141393. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141394. };
  141395. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  141396. 15, 13, 11, 9, 7, 5, 3, 1,
  141397. 0, 2, 4, 6, 8, 10, 12, 14,
  141398. 16,
  141399. };
  141400. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  141401. _vq_quantthresh__44cn1_sm_p8_2,
  141402. _vq_quantmap__44cn1_sm_p8_2,
  141403. 17,
  141404. 17
  141405. };
  141406. static static_codebook _44cn1_sm_p8_2 = {
  141407. 2, 289,
  141408. _vq_lengthlist__44cn1_sm_p8_2,
  141409. 1, -529530880, 1611661312, 5, 0,
  141410. _vq_quantlist__44cn1_sm_p8_2,
  141411. NULL,
  141412. &_vq_auxt__44cn1_sm_p8_2,
  141413. NULL,
  141414. 0
  141415. };
  141416. static long _huff_lengthlist__44cn1_sm_short[] = {
  141417. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  141418. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  141419. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  141420. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  141421. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  141422. 9,
  141423. };
  141424. static static_codebook _huff_book__44cn1_sm_short = {
  141425. 2, 81,
  141426. _huff_lengthlist__44cn1_sm_short,
  141427. 0, 0, 0, 0, 0,
  141428. NULL,
  141429. NULL,
  141430. NULL,
  141431. NULL,
  141432. 0
  141433. };
  141434. /*** End of inlined file: res_books_stereo.h ***/
  141435. /***** residue backends *********************************************/
  141436. static vorbis_info_residue0 _residue_44_low={
  141437. 0,-1, -1, 9,-1,
  141438. /* 0 1 2 3 4 5 6 7 */
  141439. {0},
  141440. {-1},
  141441. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141442. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  141443. };
  141444. static vorbis_info_residue0 _residue_44_mid={
  141445. 0,-1, -1, 10,-1,
  141446. /* 0 1 2 3 4 5 6 7 8 */
  141447. {0},
  141448. {-1},
  141449. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141450. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  141451. };
  141452. static vorbis_info_residue0 _residue_44_high={
  141453. 0,-1, -1, 10,-1,
  141454. /* 0 1 2 3 4 5 6 7 8 */
  141455. {0},
  141456. {-1},
  141457. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  141458. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  141459. };
  141460. static static_bookblock _resbook_44s_n1={
  141461. {
  141462. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  141463. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  141464. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  141465. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  141466. }
  141467. };
  141468. static static_bookblock _resbook_44sm_n1={
  141469. {
  141470. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  141471. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  141472. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  141473. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  141474. }
  141475. };
  141476. static static_bookblock _resbook_44s_0={
  141477. {
  141478. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  141479. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  141480. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  141481. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  141482. }
  141483. };
  141484. static static_bookblock _resbook_44sm_0={
  141485. {
  141486. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  141487. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  141488. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  141489. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  141490. }
  141491. };
  141492. static static_bookblock _resbook_44s_1={
  141493. {
  141494. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  141495. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  141496. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  141497. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  141498. }
  141499. };
  141500. static static_bookblock _resbook_44sm_1={
  141501. {
  141502. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  141503. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  141504. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  141505. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  141506. }
  141507. };
  141508. static static_bookblock _resbook_44s_2={
  141509. {
  141510. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  141511. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  141512. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  141513. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  141514. }
  141515. };
  141516. static static_bookblock _resbook_44s_3={
  141517. {
  141518. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  141519. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  141520. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  141521. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  141522. }
  141523. };
  141524. static static_bookblock _resbook_44s_4={
  141525. {
  141526. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  141527. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  141528. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  141529. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  141530. }
  141531. };
  141532. static static_bookblock _resbook_44s_5={
  141533. {
  141534. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  141535. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  141536. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  141537. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  141538. }
  141539. };
  141540. static static_bookblock _resbook_44s_6={
  141541. {
  141542. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  141543. {0,0,&_44c6_s_p4_0},
  141544. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  141545. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  141546. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  141547. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  141548. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  141549. }
  141550. };
  141551. static static_bookblock _resbook_44s_7={
  141552. {
  141553. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  141554. {0,0,&_44c7_s_p4_0},
  141555. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  141556. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  141557. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  141558. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  141559. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  141560. }
  141561. };
  141562. static static_bookblock _resbook_44s_8={
  141563. {
  141564. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  141565. {0,0,&_44c8_s_p4_0},
  141566. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  141567. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  141568. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  141569. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  141570. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  141571. }
  141572. };
  141573. static static_bookblock _resbook_44s_9={
  141574. {
  141575. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  141576. {0,0,&_44c9_s_p4_0},
  141577. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  141578. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  141579. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  141580. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  141581. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  141582. }
  141583. };
  141584. static vorbis_residue_template _res_44s_n1[]={
  141585. {2,0, &_residue_44_low,
  141586. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  141587. &_resbook_44s_n1,&_resbook_44sm_n1},
  141588. {2,0, &_residue_44_low,
  141589. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  141590. &_resbook_44s_n1,&_resbook_44sm_n1}
  141591. };
  141592. static vorbis_residue_template _res_44s_0[]={
  141593. {2,0, &_residue_44_low,
  141594. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  141595. &_resbook_44s_0,&_resbook_44sm_0},
  141596. {2,0, &_residue_44_low,
  141597. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  141598. &_resbook_44s_0,&_resbook_44sm_0}
  141599. };
  141600. static vorbis_residue_template _res_44s_1[]={
  141601. {2,0, &_residue_44_low,
  141602. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  141603. &_resbook_44s_1,&_resbook_44sm_1},
  141604. {2,0, &_residue_44_low,
  141605. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  141606. &_resbook_44s_1,&_resbook_44sm_1}
  141607. };
  141608. static vorbis_residue_template _res_44s_2[]={
  141609. {2,0, &_residue_44_mid,
  141610. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  141611. &_resbook_44s_2,&_resbook_44s_2},
  141612. {2,0, &_residue_44_mid,
  141613. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  141614. &_resbook_44s_2,&_resbook_44s_2}
  141615. };
  141616. static vorbis_residue_template _res_44s_3[]={
  141617. {2,0, &_residue_44_mid,
  141618. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  141619. &_resbook_44s_3,&_resbook_44s_3},
  141620. {2,0, &_residue_44_mid,
  141621. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  141622. &_resbook_44s_3,&_resbook_44s_3}
  141623. };
  141624. static vorbis_residue_template _res_44s_4[]={
  141625. {2,0, &_residue_44_mid,
  141626. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  141627. &_resbook_44s_4,&_resbook_44s_4},
  141628. {2,0, &_residue_44_mid,
  141629. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  141630. &_resbook_44s_4,&_resbook_44s_4}
  141631. };
  141632. static vorbis_residue_template _res_44s_5[]={
  141633. {2,0, &_residue_44_mid,
  141634. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  141635. &_resbook_44s_5,&_resbook_44s_5},
  141636. {2,0, &_residue_44_mid,
  141637. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  141638. &_resbook_44s_5,&_resbook_44s_5}
  141639. };
  141640. static vorbis_residue_template _res_44s_6[]={
  141641. {2,0, &_residue_44_high,
  141642. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  141643. &_resbook_44s_6,&_resbook_44s_6},
  141644. {2,0, &_residue_44_high,
  141645. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  141646. &_resbook_44s_6,&_resbook_44s_6}
  141647. };
  141648. static vorbis_residue_template _res_44s_7[]={
  141649. {2,0, &_residue_44_high,
  141650. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  141651. &_resbook_44s_7,&_resbook_44s_7},
  141652. {2,0, &_residue_44_high,
  141653. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  141654. &_resbook_44s_7,&_resbook_44s_7}
  141655. };
  141656. static vorbis_residue_template _res_44s_8[]={
  141657. {2,0, &_residue_44_high,
  141658. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  141659. &_resbook_44s_8,&_resbook_44s_8},
  141660. {2,0, &_residue_44_high,
  141661. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  141662. &_resbook_44s_8,&_resbook_44s_8}
  141663. };
  141664. static vorbis_residue_template _res_44s_9[]={
  141665. {2,0, &_residue_44_high,
  141666. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  141667. &_resbook_44s_9,&_resbook_44s_9},
  141668. {2,0, &_residue_44_high,
  141669. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  141670. &_resbook_44s_9,&_resbook_44s_9}
  141671. };
  141672. static vorbis_mapping_template _mapres_template_44_stereo[]={
  141673. { _map_nominal, _res_44s_n1 }, /* -1 */
  141674. { _map_nominal, _res_44s_0 }, /* 0 */
  141675. { _map_nominal, _res_44s_1 }, /* 1 */
  141676. { _map_nominal, _res_44s_2 }, /* 2 */
  141677. { _map_nominal, _res_44s_3 }, /* 3 */
  141678. { _map_nominal, _res_44s_4 }, /* 4 */
  141679. { _map_nominal, _res_44s_5 }, /* 5 */
  141680. { _map_nominal, _res_44s_6 }, /* 6 */
  141681. { _map_nominal, _res_44s_7 }, /* 7 */
  141682. { _map_nominal, _res_44s_8 }, /* 8 */
  141683. { _map_nominal, _res_44s_9 }, /* 9 */
  141684. };
  141685. /*** End of inlined file: residue_44.h ***/
  141686. /*** Start of inlined file: psych_44.h ***/
  141687. /* preecho trigger settings *****************************************/
  141688. static vorbis_info_psy_global _psy_global_44[5]={
  141689. {8, /* lines per eighth octave */
  141690. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  141691. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  141692. -6.f,
  141693. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141694. },
  141695. {8, /* lines per eighth octave */
  141696. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141697. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  141698. -6.f,
  141699. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141700. },
  141701. {8, /* lines per eighth octave */
  141702. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141703. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  141704. -6.f,
  141705. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141706. },
  141707. {8, /* lines per eighth octave */
  141708. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  141709. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  141710. -6.f,
  141711. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141712. },
  141713. {8, /* lines per eighth octave */
  141714. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  141715. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  141716. -6.f,
  141717. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141718. },
  141719. };
  141720. /* noise compander lookups * low, mid, high quality ****************/
  141721. static compandblock _psy_compand_44[6]={
  141722. /* sub-mode Z short */
  141723. {{
  141724. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141725. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141726. 16,17,18,19,20,21,22, 23, /* 23dB */
  141727. 24,25,26,27,28,29,30, 31, /* 31dB */
  141728. 32,33,34,35,36,37,38, 39, /* 39dB */
  141729. }},
  141730. /* mode_Z nominal short */
  141731. {{
  141732. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  141733. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  141734. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  141735. 15,16,17,17,17,18,18, 19, /* 31dB */
  141736. 19,19,20,21,22,23,24, 25, /* 39dB */
  141737. }},
  141738. /* mode A short */
  141739. {{
  141740. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  141741. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  141742. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  141743. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  141744. 11,12,13,14,15,16,17, 18, /* 39dB */
  141745. }},
  141746. /* sub-mode Z long */
  141747. {{
  141748. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141749. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141750. 16,17,18,19,20,21,22, 23, /* 23dB */
  141751. 24,25,26,27,28,29,30, 31, /* 31dB */
  141752. 32,33,34,35,36,37,38, 39, /* 39dB */
  141753. }},
  141754. /* mode_Z nominal long */
  141755. {{
  141756. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141757. 8, 9,10,11,12,12,13, 13, /* 15dB */
  141758. 13,14,14,14,15,15,15, 15, /* 23dB */
  141759. 16,16,17,17,17,18,18, 19, /* 31dB */
  141760. 19,19,20,21,22,23,24, 25, /* 39dB */
  141761. }},
  141762. /* mode A long */
  141763. {{
  141764. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141765. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  141766. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  141767. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  141768. 11,12,13,14,15,16,17, 18, /* 39dB */
  141769. }}
  141770. };
  141771. /* tonal masking curve level adjustments *************************/
  141772. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  141773. /* 63 125 250 500 1 2 4 8 16 */
  141774. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  141775. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  141776. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  141777. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  141778. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  141779. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  141780. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  141781. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  141782. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  141783. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  141784. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  141785. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  141786. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  141787. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  141788. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  141789. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  141790. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  141791. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  141792. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  141793. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  141794. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  141795. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  141796. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  141797. };
  141798. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  141799. /* 63 125 250 500 1 2 4 8 16 */
  141800. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  141801. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  141802. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  141803. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  141804. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  141805. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  141806. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  141807. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  141808. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  141809. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  141810. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  141811. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  141812. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  141813. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  141814. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  141815. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  141816. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  141817. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  141818. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  141819. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  141820. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  141821. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  141822. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  141823. };
  141824. /* noise bias (transition block) */
  141825. static noise3 _psy_noisebias_trans[12]={
  141826. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  141827. /* -1 */
  141828. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141829. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  141830. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141831. /* 0
  141832. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141833. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  141834. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  141835. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141836. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  141837. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141838. /* 1
  141839. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141840. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  141841. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  141842. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141843. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  141844. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  141845. /* 2
  141846. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141847. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  141848. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  141849. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141850. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  141851. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  141852. /* 3
  141853. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141854. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  141855. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141856. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141857. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  141858. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141859. /* 4
  141860. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141861. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  141862. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141863. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141864. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  141865. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141866. /* 5
  141867. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141868. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  141869. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  141870. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141871. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  141872. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  141873. /* 6
  141874. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141875. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  141876. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  141877. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141878. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  141879. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  141880. /* 7
  141881. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141882. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  141883. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  141884. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141885. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  141886. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  141887. /* 8
  141888. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  141889. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  141890. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  141891. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  141892. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  141893. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  141894. /* 9
  141895. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141896. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  141897. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  141898. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141899. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  141900. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  141901. /* 10 */
  141902. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  141903. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  141904. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141905. };
  141906. /* noise bias (long block) */
  141907. static noise3 _psy_noisebias_long[12]={
  141908. /*63 125 250 500 1k 2k 4k 8k 16k*/
  141909. /* -1 */
  141910. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  141911. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  141912. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141913. /* 0 */
  141914. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  141915. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  141916. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  141917. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  141918. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  141919. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141920. /* 1 */
  141921. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141922. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  141923. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  141924. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141925. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  141926. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  141927. /* 2 */
  141928. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141929. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  141930. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141931. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141932. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  141933. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141934. /* 3 */
  141935. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141936. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  141937. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141938. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141939. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  141940. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  141941. /* 4 */
  141942. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141943. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  141944. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141945. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141946. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  141947. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  141948. /* 5 */
  141949. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141950. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  141951. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  141952. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141953. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  141954. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  141955. /* 6 */
  141956. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141957. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  141958. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  141959. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141960. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  141961. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  141962. /* 7 */
  141963. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141964. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  141965. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  141966. /* 8 */
  141967. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  141968. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  141969. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  141970. /* 9 */
  141971. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141972. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  141973. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  141974. /* 10 */
  141975. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  141976. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  141977. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141978. };
  141979. /* noise bias (impulse block) */
  141980. static noise3 _psy_noisebias_impulse[12]={
  141981. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  141982. /* -1 */
  141983. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141984. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  141985. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141986. /* 0 */
  141987. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  141988. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  141989. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  141990. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  141991. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  141992. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141993. /* 1 */
  141994. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  141995. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  141996. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  141997. /* 2 */
  141998. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  141999. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142000. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142001. /* 3 */
  142002. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142003. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142004. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142005. /* 4 */
  142006. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142007. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142008. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142009. /* 5 */
  142010. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142011. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142012. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142013. /* 6
  142014. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142015. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142016. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142017. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142018. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142019. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142020. /* 7 */
  142021. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142022. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142023. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142024. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142025. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142026. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142027. /* 8 */
  142028. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142029. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142030. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142031. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142032. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142033. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142034. /* 9 */
  142035. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142036. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142037. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142038. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142039. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142040. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142041. /* 10 */
  142042. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142043. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142044. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142045. };
  142046. /* noise bias (padding block) */
  142047. static noise3 _psy_noisebias_padding[12]={
  142048. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142049. /* -1 */
  142050. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142051. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142052. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142053. /* 0 */
  142054. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142055. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142056. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142057. /* 1 */
  142058. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142059. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142060. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142061. /* 2 */
  142062. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142063. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142064. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142065. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142066. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142067. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142068. /* 3 */
  142069. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142070. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142071. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142072. /* 4 */
  142073. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142074. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142075. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142076. /* 5 */
  142077. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142078. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142079. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142080. /* 6 */
  142081. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142082. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142083. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142084. /* 7 */
  142085. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142086. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142087. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142088. /* 8 */
  142089. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142090. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142091. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142092. /* 9 */
  142093. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142094. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142095. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142096. /* 10 */
  142097. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142098. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142099. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142100. };
  142101. static noiseguard _psy_noiseguards_44[4]={
  142102. {3,3,15},
  142103. {3,3,15},
  142104. {10,10,100},
  142105. {10,10,100},
  142106. };
  142107. static int _psy_tone_suppress[12]={
  142108. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142109. };
  142110. static int _psy_tone_0dB[12]={
  142111. 90,90,95,95,95,95,105,105,105,105,105,105,
  142112. };
  142113. static int _psy_noise_suppress[12]={
  142114. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142115. };
  142116. static vorbis_info_psy _psy_info_template={
  142117. /* blockflag */
  142118. -1,
  142119. /* ath_adjatt, ath_maxatt */
  142120. -140.,-140.,
  142121. /* tonemask att boost/decay,suppr,curves */
  142122. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142123. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142124. 1, -0.f, .5f, .5f, 0,0,0,
  142125. /* noiseoffset*3, noisecompand, max_curve_dB */
  142126. {{-1},{-1},{-1}},{-1},105.f,
  142127. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142128. 0,0,-1,-1,0.,
  142129. };
  142130. /* ath ****************/
  142131. static int _psy_ath_floater[12]={
  142132. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142133. };
  142134. static int _psy_ath_abs[12]={
  142135. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142136. };
  142137. /* stereo setup. These don't map directly to quality level, there's
  142138. an additional indirection as several of the below may be used in a
  142139. single bitmanaged stream
  142140. ****************/
  142141. /* various stereo possibilities */
  142142. /* stereo mode by base quality level */
  142143. static adj_stereo _psy_stereo_modes_44[12]={
  142144. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142145. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142146. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142147. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142148. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142149. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142150. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142151. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142152. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142153. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142154. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142155. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142156. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142157. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142158. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142159. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142160. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142161. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142162. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142163. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142164. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142165. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142166. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142167. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142168. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142169. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142170. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142171. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142172. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142173. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142174. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142175. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142176. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142177. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142178. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142179. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142180. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142181. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142182. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142183. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142184. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142185. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142186. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142187. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142188. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142189. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142190. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142191. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142192. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142193. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142194. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142195. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142196. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142197. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142198. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142199. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142200. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142201. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142202. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142203. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142204. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142205. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142206. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142207. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142208. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142209. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142210. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142211. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142212. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142213. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142214. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142215. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142216. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142217. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142218. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142219. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142220. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142221. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142222. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142223. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142224. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142225. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142226. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142227. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142228. };
  142229. /* tone master attenuation by base quality mode and bitrate tweak */
  142230. static att3 _psy_tone_masteratt_44[12]={
  142231. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142232. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142233. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142234. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142235. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142236. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142237. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142238. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142239. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142240. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142241. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142242. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142243. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142244. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142245. };
  142246. /* lowpass by mode **************/
  142247. static double _psy_lowpass_44[12]={
  142248. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142249. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142250. };
  142251. /* noise normalization **********/
  142252. static int _noise_start_short_44[11]={
  142253. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142254. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142255. };
  142256. static int _noise_start_long_44[11]={
  142257. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142258. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142259. };
  142260. static int _noise_part_short_44[11]={
  142261. 8,8,8,8,8,8,8,8,8,8,8
  142262. };
  142263. static int _noise_part_long_44[11]={
  142264. 32,32,32,32,32,32,32,32,32,32,32
  142265. };
  142266. static double _noise_thresh_44[11]={
  142267. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  142268. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  142269. };
  142270. static double _noise_thresh_5only[2]={
  142271. .5,.5,
  142272. };
  142273. /*** End of inlined file: psych_44.h ***/
  142274. static double rate_mapping_44_stereo[12]={
  142275. 22500.,32000.,40000.,48000.,56000.,64000.,
  142276. 80000.,96000.,112000.,128000.,160000.,250001.
  142277. };
  142278. static double quality_mapping_44[12]={
  142279. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  142280. };
  142281. static int blocksize_short_44[11]={
  142282. 512,256,256,256,256,256,256,256,256,256,256
  142283. };
  142284. static int blocksize_long_44[11]={
  142285. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  142286. };
  142287. static double _psy_compand_short_mapping[12]={
  142288. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  142289. };
  142290. static double _psy_compand_long_mapping[12]={
  142291. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  142292. };
  142293. static double _global_mapping_44[12]={
  142294. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  142295. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  142296. };
  142297. static int _floor_short_mapping_44[11]={
  142298. 1,0,0,2,2,4,5,5,5,5,5
  142299. };
  142300. static int _floor_long_mapping_44[11]={
  142301. 8,7,7,7,7,7,7,7,7,7,7
  142302. };
  142303. ve_setup_data_template ve_setup_44_stereo={
  142304. 11,
  142305. rate_mapping_44_stereo,
  142306. quality_mapping_44,
  142307. 2,
  142308. 40000,
  142309. 50000,
  142310. blocksize_short_44,
  142311. blocksize_long_44,
  142312. _psy_tone_masteratt_44,
  142313. _psy_tone_0dB,
  142314. _psy_tone_suppress,
  142315. _vp_tonemask_adj_otherblock,
  142316. _vp_tonemask_adj_longblock,
  142317. _vp_tonemask_adj_otherblock,
  142318. _psy_noiseguards_44,
  142319. _psy_noisebias_impulse,
  142320. _psy_noisebias_padding,
  142321. _psy_noisebias_trans,
  142322. _psy_noisebias_long,
  142323. _psy_noise_suppress,
  142324. _psy_compand_44,
  142325. _psy_compand_short_mapping,
  142326. _psy_compand_long_mapping,
  142327. {_noise_start_short_44,_noise_start_long_44},
  142328. {_noise_part_short_44,_noise_part_long_44},
  142329. _noise_thresh_44,
  142330. _psy_ath_floater,
  142331. _psy_ath_abs,
  142332. _psy_lowpass_44,
  142333. _psy_global_44,
  142334. _global_mapping_44,
  142335. _psy_stereo_modes_44,
  142336. _floor_books,
  142337. _floor,
  142338. _floor_short_mapping_44,
  142339. _floor_long_mapping_44,
  142340. _mapres_template_44_stereo
  142341. };
  142342. /*** End of inlined file: setup_44.h ***/
  142343. /*** Start of inlined file: setup_44u.h ***/
  142344. /*** Start of inlined file: residue_44u.h ***/
  142345. /*** Start of inlined file: res_books_uncoupled.h ***/
  142346. static long _vq_quantlist__16u0__p1_0[] = {
  142347. 1,
  142348. 0,
  142349. 2,
  142350. };
  142351. static long _vq_lengthlist__16u0__p1_0[] = {
  142352. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142353. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142354. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142355. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142356. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142357. 12,
  142358. };
  142359. static float _vq_quantthresh__16u0__p1_0[] = {
  142360. -0.5, 0.5,
  142361. };
  142362. static long _vq_quantmap__16u0__p1_0[] = {
  142363. 1, 0, 2,
  142364. };
  142365. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142366. _vq_quantthresh__16u0__p1_0,
  142367. _vq_quantmap__16u0__p1_0,
  142368. 3,
  142369. 3
  142370. };
  142371. static static_codebook _16u0__p1_0 = {
  142372. 4, 81,
  142373. _vq_lengthlist__16u0__p1_0,
  142374. 1, -535822336, 1611661312, 2, 0,
  142375. _vq_quantlist__16u0__p1_0,
  142376. NULL,
  142377. &_vq_auxt__16u0__p1_0,
  142378. NULL,
  142379. 0
  142380. };
  142381. static long _vq_quantlist__16u0__p2_0[] = {
  142382. 1,
  142383. 0,
  142384. 2,
  142385. };
  142386. static long _vq_lengthlist__16u0__p2_0[] = {
  142387. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  142388. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  142389. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  142390. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  142391. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  142392. 8,
  142393. };
  142394. static float _vq_quantthresh__16u0__p2_0[] = {
  142395. -0.5, 0.5,
  142396. };
  142397. static long _vq_quantmap__16u0__p2_0[] = {
  142398. 1, 0, 2,
  142399. };
  142400. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  142401. _vq_quantthresh__16u0__p2_0,
  142402. _vq_quantmap__16u0__p2_0,
  142403. 3,
  142404. 3
  142405. };
  142406. static static_codebook _16u0__p2_0 = {
  142407. 4, 81,
  142408. _vq_lengthlist__16u0__p2_0,
  142409. 1, -535822336, 1611661312, 2, 0,
  142410. _vq_quantlist__16u0__p2_0,
  142411. NULL,
  142412. &_vq_auxt__16u0__p2_0,
  142413. NULL,
  142414. 0
  142415. };
  142416. static long _vq_quantlist__16u0__p3_0[] = {
  142417. 2,
  142418. 1,
  142419. 3,
  142420. 0,
  142421. 4,
  142422. };
  142423. static long _vq_lengthlist__16u0__p3_0[] = {
  142424. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  142425. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  142426. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  142427. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  142428. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  142429. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  142430. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  142431. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  142432. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  142433. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  142434. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  142435. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  142436. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  142437. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  142438. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  142439. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  142440. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  142441. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  142442. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  142443. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  142444. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  142445. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  142446. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  142447. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  142448. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  142449. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  142450. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  142451. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  142452. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  142453. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  142454. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  142455. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  142456. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  142457. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  142458. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  142459. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  142460. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  142461. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  142462. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  142463. 18,
  142464. };
  142465. static float _vq_quantthresh__16u0__p3_0[] = {
  142466. -1.5, -0.5, 0.5, 1.5,
  142467. };
  142468. static long _vq_quantmap__16u0__p3_0[] = {
  142469. 3, 1, 0, 2, 4,
  142470. };
  142471. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  142472. _vq_quantthresh__16u0__p3_0,
  142473. _vq_quantmap__16u0__p3_0,
  142474. 5,
  142475. 5
  142476. };
  142477. static static_codebook _16u0__p3_0 = {
  142478. 4, 625,
  142479. _vq_lengthlist__16u0__p3_0,
  142480. 1, -533725184, 1611661312, 3, 0,
  142481. _vq_quantlist__16u0__p3_0,
  142482. NULL,
  142483. &_vq_auxt__16u0__p3_0,
  142484. NULL,
  142485. 0
  142486. };
  142487. static long _vq_quantlist__16u0__p4_0[] = {
  142488. 2,
  142489. 1,
  142490. 3,
  142491. 0,
  142492. 4,
  142493. };
  142494. static long _vq_lengthlist__16u0__p4_0[] = {
  142495. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  142496. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  142497. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  142498. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  142499. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  142500. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  142501. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  142502. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  142503. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  142504. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  142505. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  142506. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  142507. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  142508. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  142509. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  142510. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  142511. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  142512. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142513. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  142514. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  142515. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  142516. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  142517. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  142518. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  142519. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  142520. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  142521. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  142522. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  142523. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  142524. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  142525. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  142526. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  142527. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  142528. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  142529. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  142530. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  142531. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  142532. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  142533. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  142534. 11,
  142535. };
  142536. static float _vq_quantthresh__16u0__p4_0[] = {
  142537. -1.5, -0.5, 0.5, 1.5,
  142538. };
  142539. static long _vq_quantmap__16u0__p4_0[] = {
  142540. 3, 1, 0, 2, 4,
  142541. };
  142542. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  142543. _vq_quantthresh__16u0__p4_0,
  142544. _vq_quantmap__16u0__p4_0,
  142545. 5,
  142546. 5
  142547. };
  142548. static static_codebook _16u0__p4_0 = {
  142549. 4, 625,
  142550. _vq_lengthlist__16u0__p4_0,
  142551. 1, -533725184, 1611661312, 3, 0,
  142552. _vq_quantlist__16u0__p4_0,
  142553. NULL,
  142554. &_vq_auxt__16u0__p4_0,
  142555. NULL,
  142556. 0
  142557. };
  142558. static long _vq_quantlist__16u0__p5_0[] = {
  142559. 4,
  142560. 3,
  142561. 5,
  142562. 2,
  142563. 6,
  142564. 1,
  142565. 7,
  142566. 0,
  142567. 8,
  142568. };
  142569. static long _vq_lengthlist__16u0__p5_0[] = {
  142570. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142571. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142572. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  142573. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142574. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  142575. 12,
  142576. };
  142577. static float _vq_quantthresh__16u0__p5_0[] = {
  142578. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142579. };
  142580. static long _vq_quantmap__16u0__p5_0[] = {
  142581. 7, 5, 3, 1, 0, 2, 4, 6,
  142582. 8,
  142583. };
  142584. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  142585. _vq_quantthresh__16u0__p5_0,
  142586. _vq_quantmap__16u0__p5_0,
  142587. 9,
  142588. 9
  142589. };
  142590. static static_codebook _16u0__p5_0 = {
  142591. 2, 81,
  142592. _vq_lengthlist__16u0__p5_0,
  142593. 1, -531628032, 1611661312, 4, 0,
  142594. _vq_quantlist__16u0__p5_0,
  142595. NULL,
  142596. &_vq_auxt__16u0__p5_0,
  142597. NULL,
  142598. 0
  142599. };
  142600. static long _vq_quantlist__16u0__p6_0[] = {
  142601. 6,
  142602. 5,
  142603. 7,
  142604. 4,
  142605. 8,
  142606. 3,
  142607. 9,
  142608. 2,
  142609. 10,
  142610. 1,
  142611. 11,
  142612. 0,
  142613. 12,
  142614. };
  142615. static long _vq_lengthlist__16u0__p6_0[] = {
  142616. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  142617. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  142618. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  142619. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  142620. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  142621. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  142622. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  142623. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  142624. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  142625. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  142626. 18, 0,19, 0, 0, 0, 0, 0, 0,
  142627. };
  142628. static float _vq_quantthresh__16u0__p6_0[] = {
  142629. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142630. 12.5, 17.5, 22.5, 27.5,
  142631. };
  142632. static long _vq_quantmap__16u0__p6_0[] = {
  142633. 11, 9, 7, 5, 3, 1, 0, 2,
  142634. 4, 6, 8, 10, 12,
  142635. };
  142636. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  142637. _vq_quantthresh__16u0__p6_0,
  142638. _vq_quantmap__16u0__p6_0,
  142639. 13,
  142640. 13
  142641. };
  142642. static static_codebook _16u0__p6_0 = {
  142643. 2, 169,
  142644. _vq_lengthlist__16u0__p6_0,
  142645. 1, -526516224, 1616117760, 4, 0,
  142646. _vq_quantlist__16u0__p6_0,
  142647. NULL,
  142648. &_vq_auxt__16u0__p6_0,
  142649. NULL,
  142650. 0
  142651. };
  142652. static long _vq_quantlist__16u0__p6_1[] = {
  142653. 2,
  142654. 1,
  142655. 3,
  142656. 0,
  142657. 4,
  142658. };
  142659. static long _vq_lengthlist__16u0__p6_1[] = {
  142660. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  142661. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  142662. };
  142663. static float _vq_quantthresh__16u0__p6_1[] = {
  142664. -1.5, -0.5, 0.5, 1.5,
  142665. };
  142666. static long _vq_quantmap__16u0__p6_1[] = {
  142667. 3, 1, 0, 2, 4,
  142668. };
  142669. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  142670. _vq_quantthresh__16u0__p6_1,
  142671. _vq_quantmap__16u0__p6_1,
  142672. 5,
  142673. 5
  142674. };
  142675. static static_codebook _16u0__p6_1 = {
  142676. 2, 25,
  142677. _vq_lengthlist__16u0__p6_1,
  142678. 1, -533725184, 1611661312, 3, 0,
  142679. _vq_quantlist__16u0__p6_1,
  142680. NULL,
  142681. &_vq_auxt__16u0__p6_1,
  142682. NULL,
  142683. 0
  142684. };
  142685. static long _vq_quantlist__16u0__p7_0[] = {
  142686. 1,
  142687. 0,
  142688. 2,
  142689. };
  142690. static long _vq_lengthlist__16u0__p7_0[] = {
  142691. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142692. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142693. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142694. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142695. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142696. 7,
  142697. };
  142698. static float _vq_quantthresh__16u0__p7_0[] = {
  142699. -157.5, 157.5,
  142700. };
  142701. static long _vq_quantmap__16u0__p7_0[] = {
  142702. 1, 0, 2,
  142703. };
  142704. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  142705. _vq_quantthresh__16u0__p7_0,
  142706. _vq_quantmap__16u0__p7_0,
  142707. 3,
  142708. 3
  142709. };
  142710. static static_codebook _16u0__p7_0 = {
  142711. 4, 81,
  142712. _vq_lengthlist__16u0__p7_0,
  142713. 1, -518803456, 1628680192, 2, 0,
  142714. _vq_quantlist__16u0__p7_0,
  142715. NULL,
  142716. &_vq_auxt__16u0__p7_0,
  142717. NULL,
  142718. 0
  142719. };
  142720. static long _vq_quantlist__16u0__p7_1[] = {
  142721. 7,
  142722. 6,
  142723. 8,
  142724. 5,
  142725. 9,
  142726. 4,
  142727. 10,
  142728. 3,
  142729. 11,
  142730. 2,
  142731. 12,
  142732. 1,
  142733. 13,
  142734. 0,
  142735. 14,
  142736. };
  142737. static long _vq_lengthlist__16u0__p7_1[] = {
  142738. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  142739. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  142740. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  142741. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  142742. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  142743. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  142744. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142745. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142746. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142747. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142748. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142749. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142750. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142751. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142752. 10,
  142753. };
  142754. static float _vq_quantthresh__16u0__p7_1[] = {
  142755. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  142756. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  142757. };
  142758. static long _vq_quantmap__16u0__p7_1[] = {
  142759. 13, 11, 9, 7, 5, 3, 1, 0,
  142760. 2, 4, 6, 8, 10, 12, 14,
  142761. };
  142762. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  142763. _vq_quantthresh__16u0__p7_1,
  142764. _vq_quantmap__16u0__p7_1,
  142765. 15,
  142766. 15
  142767. };
  142768. static static_codebook _16u0__p7_1 = {
  142769. 2, 225,
  142770. _vq_lengthlist__16u0__p7_1,
  142771. 1, -520986624, 1620377600, 4, 0,
  142772. _vq_quantlist__16u0__p7_1,
  142773. NULL,
  142774. &_vq_auxt__16u0__p7_1,
  142775. NULL,
  142776. 0
  142777. };
  142778. static long _vq_quantlist__16u0__p7_2[] = {
  142779. 10,
  142780. 9,
  142781. 11,
  142782. 8,
  142783. 12,
  142784. 7,
  142785. 13,
  142786. 6,
  142787. 14,
  142788. 5,
  142789. 15,
  142790. 4,
  142791. 16,
  142792. 3,
  142793. 17,
  142794. 2,
  142795. 18,
  142796. 1,
  142797. 19,
  142798. 0,
  142799. 20,
  142800. };
  142801. static long _vq_lengthlist__16u0__p7_2[] = {
  142802. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  142803. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  142804. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  142805. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  142806. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  142807. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  142808. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  142809. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  142810. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  142811. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  142812. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  142813. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  142814. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  142815. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  142816. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  142817. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  142818. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  142819. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  142820. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  142821. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  142822. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  142823. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  142824. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  142825. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  142826. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  142827. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  142828. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  142829. 10,10,12,11,10,11,11,11,10,
  142830. };
  142831. static float _vq_quantthresh__16u0__p7_2[] = {
  142832. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  142833. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  142834. 6.5, 7.5, 8.5, 9.5,
  142835. };
  142836. static long _vq_quantmap__16u0__p7_2[] = {
  142837. 19, 17, 15, 13, 11, 9, 7, 5,
  142838. 3, 1, 0, 2, 4, 6, 8, 10,
  142839. 12, 14, 16, 18, 20,
  142840. };
  142841. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  142842. _vq_quantthresh__16u0__p7_2,
  142843. _vq_quantmap__16u0__p7_2,
  142844. 21,
  142845. 21
  142846. };
  142847. static static_codebook _16u0__p7_2 = {
  142848. 2, 441,
  142849. _vq_lengthlist__16u0__p7_2,
  142850. 1, -529268736, 1611661312, 5, 0,
  142851. _vq_quantlist__16u0__p7_2,
  142852. NULL,
  142853. &_vq_auxt__16u0__p7_2,
  142854. NULL,
  142855. 0
  142856. };
  142857. static long _huff_lengthlist__16u0__single[] = {
  142858. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  142859. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  142860. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  142861. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  142862. };
  142863. static static_codebook _huff_book__16u0__single = {
  142864. 2, 64,
  142865. _huff_lengthlist__16u0__single,
  142866. 0, 0, 0, 0, 0,
  142867. NULL,
  142868. NULL,
  142869. NULL,
  142870. NULL,
  142871. 0
  142872. };
  142873. static long _huff_lengthlist__16u1__long[] = {
  142874. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  142875. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  142876. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  142877. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  142878. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  142879. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  142880. 16,13,16,18,
  142881. };
  142882. static static_codebook _huff_book__16u1__long = {
  142883. 2, 100,
  142884. _huff_lengthlist__16u1__long,
  142885. 0, 0, 0, 0, 0,
  142886. NULL,
  142887. NULL,
  142888. NULL,
  142889. NULL,
  142890. 0
  142891. };
  142892. static long _vq_quantlist__16u1__p1_0[] = {
  142893. 1,
  142894. 0,
  142895. 2,
  142896. };
  142897. static long _vq_lengthlist__16u1__p1_0[] = {
  142898. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  142899. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  142900. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  142901. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  142902. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  142903. 11,
  142904. };
  142905. static float _vq_quantthresh__16u1__p1_0[] = {
  142906. -0.5, 0.5,
  142907. };
  142908. static long _vq_quantmap__16u1__p1_0[] = {
  142909. 1, 0, 2,
  142910. };
  142911. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  142912. _vq_quantthresh__16u1__p1_0,
  142913. _vq_quantmap__16u1__p1_0,
  142914. 3,
  142915. 3
  142916. };
  142917. static static_codebook _16u1__p1_0 = {
  142918. 4, 81,
  142919. _vq_lengthlist__16u1__p1_0,
  142920. 1, -535822336, 1611661312, 2, 0,
  142921. _vq_quantlist__16u1__p1_0,
  142922. NULL,
  142923. &_vq_auxt__16u1__p1_0,
  142924. NULL,
  142925. 0
  142926. };
  142927. static long _vq_quantlist__16u1__p2_0[] = {
  142928. 1,
  142929. 0,
  142930. 2,
  142931. };
  142932. static long _vq_lengthlist__16u1__p2_0[] = {
  142933. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  142934. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  142935. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  142936. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  142937. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  142938. 8,
  142939. };
  142940. static float _vq_quantthresh__16u1__p2_0[] = {
  142941. -0.5, 0.5,
  142942. };
  142943. static long _vq_quantmap__16u1__p2_0[] = {
  142944. 1, 0, 2,
  142945. };
  142946. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  142947. _vq_quantthresh__16u1__p2_0,
  142948. _vq_quantmap__16u1__p2_0,
  142949. 3,
  142950. 3
  142951. };
  142952. static static_codebook _16u1__p2_0 = {
  142953. 4, 81,
  142954. _vq_lengthlist__16u1__p2_0,
  142955. 1, -535822336, 1611661312, 2, 0,
  142956. _vq_quantlist__16u1__p2_0,
  142957. NULL,
  142958. &_vq_auxt__16u1__p2_0,
  142959. NULL,
  142960. 0
  142961. };
  142962. static long _vq_quantlist__16u1__p3_0[] = {
  142963. 2,
  142964. 1,
  142965. 3,
  142966. 0,
  142967. 4,
  142968. };
  142969. static long _vq_lengthlist__16u1__p3_0[] = {
  142970. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  142971. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  142972. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  142973. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  142974. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  142975. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  142976. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  142977. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  142978. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  142979. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  142980. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  142981. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  142982. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  142983. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  142984. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  142985. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  142986. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  142987. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  142988. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  142989. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  142990. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  142991. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  142992. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  142993. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  142994. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  142995. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  142996. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  142997. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  142998. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  142999. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143000. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143001. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143002. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143003. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143004. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143005. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143006. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143007. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143008. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143009. 16,
  143010. };
  143011. static float _vq_quantthresh__16u1__p3_0[] = {
  143012. -1.5, -0.5, 0.5, 1.5,
  143013. };
  143014. static long _vq_quantmap__16u1__p3_0[] = {
  143015. 3, 1, 0, 2, 4,
  143016. };
  143017. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143018. _vq_quantthresh__16u1__p3_0,
  143019. _vq_quantmap__16u1__p3_0,
  143020. 5,
  143021. 5
  143022. };
  143023. static static_codebook _16u1__p3_0 = {
  143024. 4, 625,
  143025. _vq_lengthlist__16u1__p3_0,
  143026. 1, -533725184, 1611661312, 3, 0,
  143027. _vq_quantlist__16u1__p3_0,
  143028. NULL,
  143029. &_vq_auxt__16u1__p3_0,
  143030. NULL,
  143031. 0
  143032. };
  143033. static long _vq_quantlist__16u1__p4_0[] = {
  143034. 2,
  143035. 1,
  143036. 3,
  143037. 0,
  143038. 4,
  143039. };
  143040. static long _vq_lengthlist__16u1__p4_0[] = {
  143041. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143042. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143043. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143044. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143045. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143046. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143047. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143048. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143049. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143050. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143051. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143052. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143053. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143054. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143055. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143056. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143057. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143058. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143059. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143060. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143061. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143062. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143063. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143064. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143065. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143066. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143067. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143068. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143069. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143070. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143071. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143072. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143073. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143074. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143075. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143076. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143077. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143078. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143079. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143080. 11,
  143081. };
  143082. static float _vq_quantthresh__16u1__p4_0[] = {
  143083. -1.5, -0.5, 0.5, 1.5,
  143084. };
  143085. static long _vq_quantmap__16u1__p4_0[] = {
  143086. 3, 1, 0, 2, 4,
  143087. };
  143088. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143089. _vq_quantthresh__16u1__p4_0,
  143090. _vq_quantmap__16u1__p4_0,
  143091. 5,
  143092. 5
  143093. };
  143094. static static_codebook _16u1__p4_0 = {
  143095. 4, 625,
  143096. _vq_lengthlist__16u1__p4_0,
  143097. 1, -533725184, 1611661312, 3, 0,
  143098. _vq_quantlist__16u1__p4_0,
  143099. NULL,
  143100. &_vq_auxt__16u1__p4_0,
  143101. NULL,
  143102. 0
  143103. };
  143104. static long _vq_quantlist__16u1__p5_0[] = {
  143105. 4,
  143106. 3,
  143107. 5,
  143108. 2,
  143109. 6,
  143110. 1,
  143111. 7,
  143112. 0,
  143113. 8,
  143114. };
  143115. static long _vq_lengthlist__16u1__p5_0[] = {
  143116. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143117. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143118. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143119. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143120. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143121. 13,
  143122. };
  143123. static float _vq_quantthresh__16u1__p5_0[] = {
  143124. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143125. };
  143126. static long _vq_quantmap__16u1__p5_0[] = {
  143127. 7, 5, 3, 1, 0, 2, 4, 6,
  143128. 8,
  143129. };
  143130. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143131. _vq_quantthresh__16u1__p5_0,
  143132. _vq_quantmap__16u1__p5_0,
  143133. 9,
  143134. 9
  143135. };
  143136. static static_codebook _16u1__p5_0 = {
  143137. 2, 81,
  143138. _vq_lengthlist__16u1__p5_0,
  143139. 1, -531628032, 1611661312, 4, 0,
  143140. _vq_quantlist__16u1__p5_0,
  143141. NULL,
  143142. &_vq_auxt__16u1__p5_0,
  143143. NULL,
  143144. 0
  143145. };
  143146. static long _vq_quantlist__16u1__p6_0[] = {
  143147. 4,
  143148. 3,
  143149. 5,
  143150. 2,
  143151. 6,
  143152. 1,
  143153. 7,
  143154. 0,
  143155. 8,
  143156. };
  143157. static long _vq_lengthlist__16u1__p6_0[] = {
  143158. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143159. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143160. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143161. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143162. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143163. 11,
  143164. };
  143165. static float _vq_quantthresh__16u1__p6_0[] = {
  143166. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143167. };
  143168. static long _vq_quantmap__16u1__p6_0[] = {
  143169. 7, 5, 3, 1, 0, 2, 4, 6,
  143170. 8,
  143171. };
  143172. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143173. _vq_quantthresh__16u1__p6_0,
  143174. _vq_quantmap__16u1__p6_0,
  143175. 9,
  143176. 9
  143177. };
  143178. static static_codebook _16u1__p6_0 = {
  143179. 2, 81,
  143180. _vq_lengthlist__16u1__p6_0,
  143181. 1, -531628032, 1611661312, 4, 0,
  143182. _vq_quantlist__16u1__p6_0,
  143183. NULL,
  143184. &_vq_auxt__16u1__p6_0,
  143185. NULL,
  143186. 0
  143187. };
  143188. static long _vq_quantlist__16u1__p7_0[] = {
  143189. 1,
  143190. 0,
  143191. 2,
  143192. };
  143193. static long _vq_lengthlist__16u1__p7_0[] = {
  143194. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143195. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143196. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143197. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143198. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143199. 13,
  143200. };
  143201. static float _vq_quantthresh__16u1__p7_0[] = {
  143202. -5.5, 5.5,
  143203. };
  143204. static long _vq_quantmap__16u1__p7_0[] = {
  143205. 1, 0, 2,
  143206. };
  143207. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143208. _vq_quantthresh__16u1__p7_0,
  143209. _vq_quantmap__16u1__p7_0,
  143210. 3,
  143211. 3
  143212. };
  143213. static static_codebook _16u1__p7_0 = {
  143214. 4, 81,
  143215. _vq_lengthlist__16u1__p7_0,
  143216. 1, -529137664, 1618345984, 2, 0,
  143217. _vq_quantlist__16u1__p7_0,
  143218. NULL,
  143219. &_vq_auxt__16u1__p7_0,
  143220. NULL,
  143221. 0
  143222. };
  143223. static long _vq_quantlist__16u1__p7_1[] = {
  143224. 5,
  143225. 4,
  143226. 6,
  143227. 3,
  143228. 7,
  143229. 2,
  143230. 8,
  143231. 1,
  143232. 9,
  143233. 0,
  143234. 10,
  143235. };
  143236. static long _vq_lengthlist__16u1__p7_1[] = {
  143237. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143238. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143239. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143240. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143241. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143242. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143243. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143244. 8, 9, 9,10,10,10,10,10,10,
  143245. };
  143246. static float _vq_quantthresh__16u1__p7_1[] = {
  143247. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143248. 3.5, 4.5,
  143249. };
  143250. static long _vq_quantmap__16u1__p7_1[] = {
  143251. 9, 7, 5, 3, 1, 0, 2, 4,
  143252. 6, 8, 10,
  143253. };
  143254. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143255. _vq_quantthresh__16u1__p7_1,
  143256. _vq_quantmap__16u1__p7_1,
  143257. 11,
  143258. 11
  143259. };
  143260. static static_codebook _16u1__p7_1 = {
  143261. 2, 121,
  143262. _vq_lengthlist__16u1__p7_1,
  143263. 1, -531365888, 1611661312, 4, 0,
  143264. _vq_quantlist__16u1__p7_1,
  143265. NULL,
  143266. &_vq_auxt__16u1__p7_1,
  143267. NULL,
  143268. 0
  143269. };
  143270. static long _vq_quantlist__16u1__p8_0[] = {
  143271. 5,
  143272. 4,
  143273. 6,
  143274. 3,
  143275. 7,
  143276. 2,
  143277. 8,
  143278. 1,
  143279. 9,
  143280. 0,
  143281. 10,
  143282. };
  143283. static long _vq_lengthlist__16u1__p8_0[] = {
  143284. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  143285. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  143286. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  143287. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  143288. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  143289. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  143290. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  143291. 13,14,14,15,15,16,16,15,16,
  143292. };
  143293. static float _vq_quantthresh__16u1__p8_0[] = {
  143294. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143295. 38.5, 49.5,
  143296. };
  143297. static long _vq_quantmap__16u1__p8_0[] = {
  143298. 9, 7, 5, 3, 1, 0, 2, 4,
  143299. 6, 8, 10,
  143300. };
  143301. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  143302. _vq_quantthresh__16u1__p8_0,
  143303. _vq_quantmap__16u1__p8_0,
  143304. 11,
  143305. 11
  143306. };
  143307. static static_codebook _16u1__p8_0 = {
  143308. 2, 121,
  143309. _vq_lengthlist__16u1__p8_0,
  143310. 1, -524582912, 1618345984, 4, 0,
  143311. _vq_quantlist__16u1__p8_0,
  143312. NULL,
  143313. &_vq_auxt__16u1__p8_0,
  143314. NULL,
  143315. 0
  143316. };
  143317. static long _vq_quantlist__16u1__p8_1[] = {
  143318. 5,
  143319. 4,
  143320. 6,
  143321. 3,
  143322. 7,
  143323. 2,
  143324. 8,
  143325. 1,
  143326. 9,
  143327. 0,
  143328. 10,
  143329. };
  143330. static long _vq_lengthlist__16u1__p8_1[] = {
  143331. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143332. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143333. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143334. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143335. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143336. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143337. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143338. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143339. };
  143340. static float _vq_quantthresh__16u1__p8_1[] = {
  143341. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143342. 3.5, 4.5,
  143343. };
  143344. static long _vq_quantmap__16u1__p8_1[] = {
  143345. 9, 7, 5, 3, 1, 0, 2, 4,
  143346. 6, 8, 10,
  143347. };
  143348. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143349. _vq_quantthresh__16u1__p8_1,
  143350. _vq_quantmap__16u1__p8_1,
  143351. 11,
  143352. 11
  143353. };
  143354. static static_codebook _16u1__p8_1 = {
  143355. 2, 121,
  143356. _vq_lengthlist__16u1__p8_1,
  143357. 1, -531365888, 1611661312, 4, 0,
  143358. _vq_quantlist__16u1__p8_1,
  143359. NULL,
  143360. &_vq_auxt__16u1__p8_1,
  143361. NULL,
  143362. 0
  143363. };
  143364. static long _vq_quantlist__16u1__p9_0[] = {
  143365. 7,
  143366. 6,
  143367. 8,
  143368. 5,
  143369. 9,
  143370. 4,
  143371. 10,
  143372. 3,
  143373. 11,
  143374. 2,
  143375. 12,
  143376. 1,
  143377. 13,
  143378. 0,
  143379. 14,
  143380. };
  143381. static long _vq_lengthlist__16u1__p9_0[] = {
  143382. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143383. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143384. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143385. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143386. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143387. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143388. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143389. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143390. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143391. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143392. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143393. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143394. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143395. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143396. 8,
  143397. };
  143398. static float _vq_quantthresh__16u1__p9_0[] = {
  143399. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143400. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143401. };
  143402. static long _vq_quantmap__16u1__p9_0[] = {
  143403. 13, 11, 9, 7, 5, 3, 1, 0,
  143404. 2, 4, 6, 8, 10, 12, 14,
  143405. };
  143406. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  143407. _vq_quantthresh__16u1__p9_0,
  143408. _vq_quantmap__16u1__p9_0,
  143409. 15,
  143410. 15
  143411. };
  143412. static static_codebook _16u1__p9_0 = {
  143413. 2, 225,
  143414. _vq_lengthlist__16u1__p9_0,
  143415. 1, -514071552, 1627381760, 4, 0,
  143416. _vq_quantlist__16u1__p9_0,
  143417. NULL,
  143418. &_vq_auxt__16u1__p9_0,
  143419. NULL,
  143420. 0
  143421. };
  143422. static long _vq_quantlist__16u1__p9_1[] = {
  143423. 7,
  143424. 6,
  143425. 8,
  143426. 5,
  143427. 9,
  143428. 4,
  143429. 10,
  143430. 3,
  143431. 11,
  143432. 2,
  143433. 12,
  143434. 1,
  143435. 13,
  143436. 0,
  143437. 14,
  143438. };
  143439. static long _vq_lengthlist__16u1__p9_1[] = {
  143440. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  143441. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  143442. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  143443. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  143444. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  143445. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  143446. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  143447. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  143448. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  143449. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143450. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  143451. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143452. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143453. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143454. 9,
  143455. };
  143456. static float _vq_quantthresh__16u1__p9_1[] = {
  143457. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143458. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143459. };
  143460. static long _vq_quantmap__16u1__p9_1[] = {
  143461. 13, 11, 9, 7, 5, 3, 1, 0,
  143462. 2, 4, 6, 8, 10, 12, 14,
  143463. };
  143464. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  143465. _vq_quantthresh__16u1__p9_1,
  143466. _vq_quantmap__16u1__p9_1,
  143467. 15,
  143468. 15
  143469. };
  143470. static static_codebook _16u1__p9_1 = {
  143471. 2, 225,
  143472. _vq_lengthlist__16u1__p9_1,
  143473. 1, -522338304, 1620115456, 4, 0,
  143474. _vq_quantlist__16u1__p9_1,
  143475. NULL,
  143476. &_vq_auxt__16u1__p9_1,
  143477. NULL,
  143478. 0
  143479. };
  143480. static long _vq_quantlist__16u1__p9_2[] = {
  143481. 8,
  143482. 7,
  143483. 9,
  143484. 6,
  143485. 10,
  143486. 5,
  143487. 11,
  143488. 4,
  143489. 12,
  143490. 3,
  143491. 13,
  143492. 2,
  143493. 14,
  143494. 1,
  143495. 15,
  143496. 0,
  143497. 16,
  143498. };
  143499. static long _vq_lengthlist__16u1__p9_2[] = {
  143500. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  143501. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  143502. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  143503. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  143504. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  143505. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  143506. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  143507. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  143508. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  143509. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  143510. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  143511. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  143512. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  143513. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  143514. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  143515. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  143516. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  143517. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  143518. 10,
  143519. };
  143520. static float _vq_quantthresh__16u1__p9_2[] = {
  143521. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143522. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143523. };
  143524. static long _vq_quantmap__16u1__p9_2[] = {
  143525. 15, 13, 11, 9, 7, 5, 3, 1,
  143526. 0, 2, 4, 6, 8, 10, 12, 14,
  143527. 16,
  143528. };
  143529. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  143530. _vq_quantthresh__16u1__p9_2,
  143531. _vq_quantmap__16u1__p9_2,
  143532. 17,
  143533. 17
  143534. };
  143535. static static_codebook _16u1__p9_2 = {
  143536. 2, 289,
  143537. _vq_lengthlist__16u1__p9_2,
  143538. 1, -529530880, 1611661312, 5, 0,
  143539. _vq_quantlist__16u1__p9_2,
  143540. NULL,
  143541. &_vq_auxt__16u1__p9_2,
  143542. NULL,
  143543. 0
  143544. };
  143545. static long _huff_lengthlist__16u1__short[] = {
  143546. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  143547. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  143548. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  143549. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  143550. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  143551. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  143552. 16,16,16,16,
  143553. };
  143554. static static_codebook _huff_book__16u1__short = {
  143555. 2, 100,
  143556. _huff_lengthlist__16u1__short,
  143557. 0, 0, 0, 0, 0,
  143558. NULL,
  143559. NULL,
  143560. NULL,
  143561. NULL,
  143562. 0
  143563. };
  143564. static long _huff_lengthlist__16u2__long[] = {
  143565. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  143566. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  143567. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  143568. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  143569. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  143570. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  143571. 13,14,18,18,
  143572. };
  143573. static static_codebook _huff_book__16u2__long = {
  143574. 2, 100,
  143575. _huff_lengthlist__16u2__long,
  143576. 0, 0, 0, 0, 0,
  143577. NULL,
  143578. NULL,
  143579. NULL,
  143580. NULL,
  143581. 0
  143582. };
  143583. static long _huff_lengthlist__16u2__short[] = {
  143584. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  143585. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  143586. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  143587. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  143588. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  143589. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  143590. 16,16,16,16,
  143591. };
  143592. static static_codebook _huff_book__16u2__short = {
  143593. 2, 100,
  143594. _huff_lengthlist__16u2__short,
  143595. 0, 0, 0, 0, 0,
  143596. NULL,
  143597. NULL,
  143598. NULL,
  143599. NULL,
  143600. 0
  143601. };
  143602. static long _vq_quantlist__16u2_p1_0[] = {
  143603. 1,
  143604. 0,
  143605. 2,
  143606. };
  143607. static long _vq_lengthlist__16u2_p1_0[] = {
  143608. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  143609. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  143610. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  143611. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  143612. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  143613. 10,
  143614. };
  143615. static float _vq_quantthresh__16u2_p1_0[] = {
  143616. -0.5, 0.5,
  143617. };
  143618. static long _vq_quantmap__16u2_p1_0[] = {
  143619. 1, 0, 2,
  143620. };
  143621. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  143622. _vq_quantthresh__16u2_p1_0,
  143623. _vq_quantmap__16u2_p1_0,
  143624. 3,
  143625. 3
  143626. };
  143627. static static_codebook _16u2_p1_0 = {
  143628. 4, 81,
  143629. _vq_lengthlist__16u2_p1_0,
  143630. 1, -535822336, 1611661312, 2, 0,
  143631. _vq_quantlist__16u2_p1_0,
  143632. NULL,
  143633. &_vq_auxt__16u2_p1_0,
  143634. NULL,
  143635. 0
  143636. };
  143637. static long _vq_quantlist__16u2_p2_0[] = {
  143638. 2,
  143639. 1,
  143640. 3,
  143641. 0,
  143642. 4,
  143643. };
  143644. static long _vq_lengthlist__16u2_p2_0[] = {
  143645. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143646. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143647. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  143648. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  143649. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  143650. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  143651. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  143652. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  143653. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143654. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  143655. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  143656. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143657. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  143658. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  143659. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  143660. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  143661. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  143662. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  143663. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  143664. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  143665. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  143666. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  143667. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  143668. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  143669. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  143670. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  143671. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  143672. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  143673. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  143674. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  143675. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  143676. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  143677. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  143678. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  143679. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  143680. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  143681. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  143682. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  143683. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  143684. 13,
  143685. };
  143686. static float _vq_quantthresh__16u2_p2_0[] = {
  143687. -1.5, -0.5, 0.5, 1.5,
  143688. };
  143689. static long _vq_quantmap__16u2_p2_0[] = {
  143690. 3, 1, 0, 2, 4,
  143691. };
  143692. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  143693. _vq_quantthresh__16u2_p2_0,
  143694. _vq_quantmap__16u2_p2_0,
  143695. 5,
  143696. 5
  143697. };
  143698. static static_codebook _16u2_p2_0 = {
  143699. 4, 625,
  143700. _vq_lengthlist__16u2_p2_0,
  143701. 1, -533725184, 1611661312, 3, 0,
  143702. _vq_quantlist__16u2_p2_0,
  143703. NULL,
  143704. &_vq_auxt__16u2_p2_0,
  143705. NULL,
  143706. 0
  143707. };
  143708. static long _vq_quantlist__16u2_p3_0[] = {
  143709. 4,
  143710. 3,
  143711. 5,
  143712. 2,
  143713. 6,
  143714. 1,
  143715. 7,
  143716. 0,
  143717. 8,
  143718. };
  143719. static long _vq_lengthlist__16u2_p3_0[] = {
  143720. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  143721. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  143722. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143723. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143724. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143725. 11,
  143726. };
  143727. static float _vq_quantthresh__16u2_p3_0[] = {
  143728. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143729. };
  143730. static long _vq_quantmap__16u2_p3_0[] = {
  143731. 7, 5, 3, 1, 0, 2, 4, 6,
  143732. 8,
  143733. };
  143734. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  143735. _vq_quantthresh__16u2_p3_0,
  143736. _vq_quantmap__16u2_p3_0,
  143737. 9,
  143738. 9
  143739. };
  143740. static static_codebook _16u2_p3_0 = {
  143741. 2, 81,
  143742. _vq_lengthlist__16u2_p3_0,
  143743. 1, -531628032, 1611661312, 4, 0,
  143744. _vq_quantlist__16u2_p3_0,
  143745. NULL,
  143746. &_vq_auxt__16u2_p3_0,
  143747. NULL,
  143748. 0
  143749. };
  143750. static long _vq_quantlist__16u2_p4_0[] = {
  143751. 8,
  143752. 7,
  143753. 9,
  143754. 6,
  143755. 10,
  143756. 5,
  143757. 11,
  143758. 4,
  143759. 12,
  143760. 3,
  143761. 13,
  143762. 2,
  143763. 14,
  143764. 1,
  143765. 15,
  143766. 0,
  143767. 16,
  143768. };
  143769. static long _vq_lengthlist__16u2_p4_0[] = {
  143770. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  143771. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  143772. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  143773. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  143774. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  143775. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  143776. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  143777. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  143778. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  143779. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  143780. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  143781. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  143782. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  143783. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  143784. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  143785. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  143786. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  143787. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  143788. 14,
  143789. };
  143790. static float _vq_quantthresh__16u2_p4_0[] = {
  143791. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143792. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143793. };
  143794. static long _vq_quantmap__16u2_p4_0[] = {
  143795. 15, 13, 11, 9, 7, 5, 3, 1,
  143796. 0, 2, 4, 6, 8, 10, 12, 14,
  143797. 16,
  143798. };
  143799. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  143800. _vq_quantthresh__16u2_p4_0,
  143801. _vq_quantmap__16u2_p4_0,
  143802. 17,
  143803. 17
  143804. };
  143805. static static_codebook _16u2_p4_0 = {
  143806. 2, 289,
  143807. _vq_lengthlist__16u2_p4_0,
  143808. 1, -529530880, 1611661312, 5, 0,
  143809. _vq_quantlist__16u2_p4_0,
  143810. NULL,
  143811. &_vq_auxt__16u2_p4_0,
  143812. NULL,
  143813. 0
  143814. };
  143815. static long _vq_quantlist__16u2_p5_0[] = {
  143816. 1,
  143817. 0,
  143818. 2,
  143819. };
  143820. static long _vq_lengthlist__16u2_p5_0[] = {
  143821. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  143822. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  143823. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  143824. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  143825. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  143826. 10,
  143827. };
  143828. static float _vq_quantthresh__16u2_p5_0[] = {
  143829. -5.5, 5.5,
  143830. };
  143831. static long _vq_quantmap__16u2_p5_0[] = {
  143832. 1, 0, 2,
  143833. };
  143834. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  143835. _vq_quantthresh__16u2_p5_0,
  143836. _vq_quantmap__16u2_p5_0,
  143837. 3,
  143838. 3
  143839. };
  143840. static static_codebook _16u2_p5_0 = {
  143841. 4, 81,
  143842. _vq_lengthlist__16u2_p5_0,
  143843. 1, -529137664, 1618345984, 2, 0,
  143844. _vq_quantlist__16u2_p5_0,
  143845. NULL,
  143846. &_vq_auxt__16u2_p5_0,
  143847. NULL,
  143848. 0
  143849. };
  143850. static long _vq_quantlist__16u2_p5_1[] = {
  143851. 5,
  143852. 4,
  143853. 6,
  143854. 3,
  143855. 7,
  143856. 2,
  143857. 8,
  143858. 1,
  143859. 9,
  143860. 0,
  143861. 10,
  143862. };
  143863. static long _vq_lengthlist__16u2_p5_1[] = {
  143864. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  143865. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  143866. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  143867. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143868. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143869. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143870. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143871. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143872. };
  143873. static float _vq_quantthresh__16u2_p5_1[] = {
  143874. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143875. 3.5, 4.5,
  143876. };
  143877. static long _vq_quantmap__16u2_p5_1[] = {
  143878. 9, 7, 5, 3, 1, 0, 2, 4,
  143879. 6, 8, 10,
  143880. };
  143881. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  143882. _vq_quantthresh__16u2_p5_1,
  143883. _vq_quantmap__16u2_p5_1,
  143884. 11,
  143885. 11
  143886. };
  143887. static static_codebook _16u2_p5_1 = {
  143888. 2, 121,
  143889. _vq_lengthlist__16u2_p5_1,
  143890. 1, -531365888, 1611661312, 4, 0,
  143891. _vq_quantlist__16u2_p5_1,
  143892. NULL,
  143893. &_vq_auxt__16u2_p5_1,
  143894. NULL,
  143895. 0
  143896. };
  143897. static long _vq_quantlist__16u2_p6_0[] = {
  143898. 6,
  143899. 5,
  143900. 7,
  143901. 4,
  143902. 8,
  143903. 3,
  143904. 9,
  143905. 2,
  143906. 10,
  143907. 1,
  143908. 11,
  143909. 0,
  143910. 12,
  143911. };
  143912. static long _vq_lengthlist__16u2_p6_0[] = {
  143913. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  143914. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  143915. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  143916. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  143917. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  143918. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  143919. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  143920. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  143921. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  143922. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  143923. 12,13,13,14,14,14,14,15,15,
  143924. };
  143925. static float _vq_quantthresh__16u2_p6_0[] = {
  143926. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143927. 12.5, 17.5, 22.5, 27.5,
  143928. };
  143929. static long _vq_quantmap__16u2_p6_0[] = {
  143930. 11, 9, 7, 5, 3, 1, 0, 2,
  143931. 4, 6, 8, 10, 12,
  143932. };
  143933. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  143934. _vq_quantthresh__16u2_p6_0,
  143935. _vq_quantmap__16u2_p6_0,
  143936. 13,
  143937. 13
  143938. };
  143939. static static_codebook _16u2_p6_0 = {
  143940. 2, 169,
  143941. _vq_lengthlist__16u2_p6_0,
  143942. 1, -526516224, 1616117760, 4, 0,
  143943. _vq_quantlist__16u2_p6_0,
  143944. NULL,
  143945. &_vq_auxt__16u2_p6_0,
  143946. NULL,
  143947. 0
  143948. };
  143949. static long _vq_quantlist__16u2_p6_1[] = {
  143950. 2,
  143951. 1,
  143952. 3,
  143953. 0,
  143954. 4,
  143955. };
  143956. static long _vq_lengthlist__16u2_p6_1[] = {
  143957. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  143958. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  143959. };
  143960. static float _vq_quantthresh__16u2_p6_1[] = {
  143961. -1.5, -0.5, 0.5, 1.5,
  143962. };
  143963. static long _vq_quantmap__16u2_p6_1[] = {
  143964. 3, 1, 0, 2, 4,
  143965. };
  143966. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  143967. _vq_quantthresh__16u2_p6_1,
  143968. _vq_quantmap__16u2_p6_1,
  143969. 5,
  143970. 5
  143971. };
  143972. static static_codebook _16u2_p6_1 = {
  143973. 2, 25,
  143974. _vq_lengthlist__16u2_p6_1,
  143975. 1, -533725184, 1611661312, 3, 0,
  143976. _vq_quantlist__16u2_p6_1,
  143977. NULL,
  143978. &_vq_auxt__16u2_p6_1,
  143979. NULL,
  143980. 0
  143981. };
  143982. static long _vq_quantlist__16u2_p7_0[] = {
  143983. 6,
  143984. 5,
  143985. 7,
  143986. 4,
  143987. 8,
  143988. 3,
  143989. 9,
  143990. 2,
  143991. 10,
  143992. 1,
  143993. 11,
  143994. 0,
  143995. 12,
  143996. };
  143997. static long _vq_lengthlist__16u2_p7_0[] = {
  143998. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  143999. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144000. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144001. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144002. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144003. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144004. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144005. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144006. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144007. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144008. 12,13,13,13,14,14,14,15,14,
  144009. };
  144010. static float _vq_quantthresh__16u2_p7_0[] = {
  144011. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144012. 27.5, 38.5, 49.5, 60.5,
  144013. };
  144014. static long _vq_quantmap__16u2_p7_0[] = {
  144015. 11, 9, 7, 5, 3, 1, 0, 2,
  144016. 4, 6, 8, 10, 12,
  144017. };
  144018. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144019. _vq_quantthresh__16u2_p7_0,
  144020. _vq_quantmap__16u2_p7_0,
  144021. 13,
  144022. 13
  144023. };
  144024. static static_codebook _16u2_p7_0 = {
  144025. 2, 169,
  144026. _vq_lengthlist__16u2_p7_0,
  144027. 1, -523206656, 1618345984, 4, 0,
  144028. _vq_quantlist__16u2_p7_0,
  144029. NULL,
  144030. &_vq_auxt__16u2_p7_0,
  144031. NULL,
  144032. 0
  144033. };
  144034. static long _vq_quantlist__16u2_p7_1[] = {
  144035. 5,
  144036. 4,
  144037. 6,
  144038. 3,
  144039. 7,
  144040. 2,
  144041. 8,
  144042. 1,
  144043. 9,
  144044. 0,
  144045. 10,
  144046. };
  144047. static long _vq_lengthlist__16u2_p7_1[] = {
  144048. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144049. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144050. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144051. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144052. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144053. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144054. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144055. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144056. };
  144057. static float _vq_quantthresh__16u2_p7_1[] = {
  144058. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144059. 3.5, 4.5,
  144060. };
  144061. static long _vq_quantmap__16u2_p7_1[] = {
  144062. 9, 7, 5, 3, 1, 0, 2, 4,
  144063. 6, 8, 10,
  144064. };
  144065. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144066. _vq_quantthresh__16u2_p7_1,
  144067. _vq_quantmap__16u2_p7_1,
  144068. 11,
  144069. 11
  144070. };
  144071. static static_codebook _16u2_p7_1 = {
  144072. 2, 121,
  144073. _vq_lengthlist__16u2_p7_1,
  144074. 1, -531365888, 1611661312, 4, 0,
  144075. _vq_quantlist__16u2_p7_1,
  144076. NULL,
  144077. &_vq_auxt__16u2_p7_1,
  144078. NULL,
  144079. 0
  144080. };
  144081. static long _vq_quantlist__16u2_p8_0[] = {
  144082. 7,
  144083. 6,
  144084. 8,
  144085. 5,
  144086. 9,
  144087. 4,
  144088. 10,
  144089. 3,
  144090. 11,
  144091. 2,
  144092. 12,
  144093. 1,
  144094. 13,
  144095. 0,
  144096. 14,
  144097. };
  144098. static long _vq_lengthlist__16u2_p8_0[] = {
  144099. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144100. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144101. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144102. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144103. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144104. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144105. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144106. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144107. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144108. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144109. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144110. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144111. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144112. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144113. 14,
  144114. };
  144115. static float _vq_quantthresh__16u2_p8_0[] = {
  144116. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144117. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144118. };
  144119. static long _vq_quantmap__16u2_p8_0[] = {
  144120. 13, 11, 9, 7, 5, 3, 1, 0,
  144121. 2, 4, 6, 8, 10, 12, 14,
  144122. };
  144123. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144124. _vq_quantthresh__16u2_p8_0,
  144125. _vq_quantmap__16u2_p8_0,
  144126. 15,
  144127. 15
  144128. };
  144129. static static_codebook _16u2_p8_0 = {
  144130. 2, 225,
  144131. _vq_lengthlist__16u2_p8_0,
  144132. 1, -520986624, 1620377600, 4, 0,
  144133. _vq_quantlist__16u2_p8_0,
  144134. NULL,
  144135. &_vq_auxt__16u2_p8_0,
  144136. NULL,
  144137. 0
  144138. };
  144139. static long _vq_quantlist__16u2_p8_1[] = {
  144140. 10,
  144141. 9,
  144142. 11,
  144143. 8,
  144144. 12,
  144145. 7,
  144146. 13,
  144147. 6,
  144148. 14,
  144149. 5,
  144150. 15,
  144151. 4,
  144152. 16,
  144153. 3,
  144154. 17,
  144155. 2,
  144156. 18,
  144157. 1,
  144158. 19,
  144159. 0,
  144160. 20,
  144161. };
  144162. static long _vq_lengthlist__16u2_p8_1[] = {
  144163. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144164. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144165. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144166. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144167. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144168. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144169. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144170. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144171. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144172. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144173. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144174. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144175. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144176. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144177. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144178. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144179. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144180. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144181. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144182. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144183. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144184. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144185. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144186. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144187. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144188. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144189. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144190. 11,11,10,11,11,11,10,11,11,
  144191. };
  144192. static float _vq_quantthresh__16u2_p8_1[] = {
  144193. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144194. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144195. 6.5, 7.5, 8.5, 9.5,
  144196. };
  144197. static long _vq_quantmap__16u2_p8_1[] = {
  144198. 19, 17, 15, 13, 11, 9, 7, 5,
  144199. 3, 1, 0, 2, 4, 6, 8, 10,
  144200. 12, 14, 16, 18, 20,
  144201. };
  144202. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144203. _vq_quantthresh__16u2_p8_1,
  144204. _vq_quantmap__16u2_p8_1,
  144205. 21,
  144206. 21
  144207. };
  144208. static static_codebook _16u2_p8_1 = {
  144209. 2, 441,
  144210. _vq_lengthlist__16u2_p8_1,
  144211. 1, -529268736, 1611661312, 5, 0,
  144212. _vq_quantlist__16u2_p8_1,
  144213. NULL,
  144214. &_vq_auxt__16u2_p8_1,
  144215. NULL,
  144216. 0
  144217. };
  144218. static long _vq_quantlist__16u2_p9_0[] = {
  144219. 5586,
  144220. 4655,
  144221. 6517,
  144222. 3724,
  144223. 7448,
  144224. 2793,
  144225. 8379,
  144226. 1862,
  144227. 9310,
  144228. 931,
  144229. 10241,
  144230. 0,
  144231. 11172,
  144232. 5521,
  144233. 5651,
  144234. };
  144235. static long _vq_lengthlist__16u2_p9_0[] = {
  144236. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144237. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144238. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144239. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144240. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144241. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144242. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144243. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144244. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144245. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144246. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144247. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144248. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144249. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144250. 5,
  144251. };
  144252. static float _vq_quantthresh__16u2_p9_0[] = {
  144253. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144254. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144255. };
  144256. static long _vq_quantmap__16u2_p9_0[] = {
  144257. 11, 9, 7, 5, 3, 1, 13, 0,
  144258. 14, 2, 4, 6, 8, 10, 12,
  144259. };
  144260. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144261. _vq_quantthresh__16u2_p9_0,
  144262. _vq_quantmap__16u2_p9_0,
  144263. 15,
  144264. 15
  144265. };
  144266. static static_codebook _16u2_p9_0 = {
  144267. 2, 225,
  144268. _vq_lengthlist__16u2_p9_0,
  144269. 1, -510275072, 1611661312, 14, 0,
  144270. _vq_quantlist__16u2_p9_0,
  144271. NULL,
  144272. &_vq_auxt__16u2_p9_0,
  144273. NULL,
  144274. 0
  144275. };
  144276. static long _vq_quantlist__16u2_p9_1[] = {
  144277. 392,
  144278. 343,
  144279. 441,
  144280. 294,
  144281. 490,
  144282. 245,
  144283. 539,
  144284. 196,
  144285. 588,
  144286. 147,
  144287. 637,
  144288. 98,
  144289. 686,
  144290. 49,
  144291. 735,
  144292. 0,
  144293. 784,
  144294. 388,
  144295. 396,
  144296. };
  144297. static long _vq_lengthlist__16u2_p9_1[] = {
  144298. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  144299. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  144300. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  144301. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  144302. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  144303. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  144304. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144305. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144306. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  144307. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144308. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144309. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144310. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144311. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144312. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144313. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144314. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144315. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144316. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144317. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144318. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144319. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144320. 11,11,11,11,11,11,11, 5, 4,
  144321. };
  144322. static float _vq_quantthresh__16u2_p9_1[] = {
  144323. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144324. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144325. 318.5, 367.5,
  144326. };
  144327. static long _vq_quantmap__16u2_p9_1[] = {
  144328. 15, 13, 11, 9, 7, 5, 3, 1,
  144329. 17, 0, 18, 2, 4, 6, 8, 10,
  144330. 12, 14, 16,
  144331. };
  144332. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144333. _vq_quantthresh__16u2_p9_1,
  144334. _vq_quantmap__16u2_p9_1,
  144335. 19,
  144336. 19
  144337. };
  144338. static static_codebook _16u2_p9_1 = {
  144339. 2, 361,
  144340. _vq_lengthlist__16u2_p9_1,
  144341. 1, -518488064, 1611661312, 10, 0,
  144342. _vq_quantlist__16u2_p9_1,
  144343. NULL,
  144344. &_vq_auxt__16u2_p9_1,
  144345. NULL,
  144346. 0
  144347. };
  144348. static long _vq_quantlist__16u2_p9_2[] = {
  144349. 24,
  144350. 23,
  144351. 25,
  144352. 22,
  144353. 26,
  144354. 21,
  144355. 27,
  144356. 20,
  144357. 28,
  144358. 19,
  144359. 29,
  144360. 18,
  144361. 30,
  144362. 17,
  144363. 31,
  144364. 16,
  144365. 32,
  144366. 15,
  144367. 33,
  144368. 14,
  144369. 34,
  144370. 13,
  144371. 35,
  144372. 12,
  144373. 36,
  144374. 11,
  144375. 37,
  144376. 10,
  144377. 38,
  144378. 9,
  144379. 39,
  144380. 8,
  144381. 40,
  144382. 7,
  144383. 41,
  144384. 6,
  144385. 42,
  144386. 5,
  144387. 43,
  144388. 4,
  144389. 44,
  144390. 3,
  144391. 45,
  144392. 2,
  144393. 46,
  144394. 1,
  144395. 47,
  144396. 0,
  144397. 48,
  144398. };
  144399. static long _vq_lengthlist__16u2_p9_2[] = {
  144400. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  144401. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  144402. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  144403. 11,
  144404. };
  144405. static float _vq_quantthresh__16u2_p9_2[] = {
  144406. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144407. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144408. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144409. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144410. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144411. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144412. };
  144413. static long _vq_quantmap__16u2_p9_2[] = {
  144414. 47, 45, 43, 41, 39, 37, 35, 33,
  144415. 31, 29, 27, 25, 23, 21, 19, 17,
  144416. 15, 13, 11, 9, 7, 5, 3, 1,
  144417. 0, 2, 4, 6, 8, 10, 12, 14,
  144418. 16, 18, 20, 22, 24, 26, 28, 30,
  144419. 32, 34, 36, 38, 40, 42, 44, 46,
  144420. 48,
  144421. };
  144422. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  144423. _vq_quantthresh__16u2_p9_2,
  144424. _vq_quantmap__16u2_p9_2,
  144425. 49,
  144426. 49
  144427. };
  144428. static static_codebook _16u2_p9_2 = {
  144429. 1, 49,
  144430. _vq_lengthlist__16u2_p9_2,
  144431. 1, -526909440, 1611661312, 6, 0,
  144432. _vq_quantlist__16u2_p9_2,
  144433. NULL,
  144434. &_vq_auxt__16u2_p9_2,
  144435. NULL,
  144436. 0
  144437. };
  144438. static long _vq_quantlist__8u0__p1_0[] = {
  144439. 1,
  144440. 0,
  144441. 2,
  144442. };
  144443. static long _vq_lengthlist__8u0__p1_0[] = {
  144444. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144445. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  144446. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  144447. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  144448. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  144449. 11,
  144450. };
  144451. static float _vq_quantthresh__8u0__p1_0[] = {
  144452. -0.5, 0.5,
  144453. };
  144454. static long _vq_quantmap__8u0__p1_0[] = {
  144455. 1, 0, 2,
  144456. };
  144457. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  144458. _vq_quantthresh__8u0__p1_0,
  144459. _vq_quantmap__8u0__p1_0,
  144460. 3,
  144461. 3
  144462. };
  144463. static static_codebook _8u0__p1_0 = {
  144464. 4, 81,
  144465. _vq_lengthlist__8u0__p1_0,
  144466. 1, -535822336, 1611661312, 2, 0,
  144467. _vq_quantlist__8u0__p1_0,
  144468. NULL,
  144469. &_vq_auxt__8u0__p1_0,
  144470. NULL,
  144471. 0
  144472. };
  144473. static long _vq_quantlist__8u0__p2_0[] = {
  144474. 1,
  144475. 0,
  144476. 2,
  144477. };
  144478. static long _vq_lengthlist__8u0__p2_0[] = {
  144479. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  144480. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  144481. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  144482. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  144483. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  144484. 8,
  144485. };
  144486. static float _vq_quantthresh__8u0__p2_0[] = {
  144487. -0.5, 0.5,
  144488. };
  144489. static long _vq_quantmap__8u0__p2_0[] = {
  144490. 1, 0, 2,
  144491. };
  144492. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  144493. _vq_quantthresh__8u0__p2_0,
  144494. _vq_quantmap__8u0__p2_0,
  144495. 3,
  144496. 3
  144497. };
  144498. static static_codebook _8u0__p2_0 = {
  144499. 4, 81,
  144500. _vq_lengthlist__8u0__p2_0,
  144501. 1, -535822336, 1611661312, 2, 0,
  144502. _vq_quantlist__8u0__p2_0,
  144503. NULL,
  144504. &_vq_auxt__8u0__p2_0,
  144505. NULL,
  144506. 0
  144507. };
  144508. static long _vq_quantlist__8u0__p3_0[] = {
  144509. 2,
  144510. 1,
  144511. 3,
  144512. 0,
  144513. 4,
  144514. };
  144515. static long _vq_lengthlist__8u0__p3_0[] = {
  144516. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  144517. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  144518. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  144519. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  144520. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  144521. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  144522. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  144523. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  144524. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  144525. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  144526. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  144527. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  144528. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  144529. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  144530. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  144531. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  144532. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  144533. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  144534. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  144535. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  144536. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  144537. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  144538. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  144539. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  144540. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  144541. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  144542. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  144543. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  144544. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  144545. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  144546. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  144547. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  144548. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  144549. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  144550. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  144551. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  144552. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  144553. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  144554. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  144555. 16,
  144556. };
  144557. static float _vq_quantthresh__8u0__p3_0[] = {
  144558. -1.5, -0.5, 0.5, 1.5,
  144559. };
  144560. static long _vq_quantmap__8u0__p3_0[] = {
  144561. 3, 1, 0, 2, 4,
  144562. };
  144563. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  144564. _vq_quantthresh__8u0__p3_0,
  144565. _vq_quantmap__8u0__p3_0,
  144566. 5,
  144567. 5
  144568. };
  144569. static static_codebook _8u0__p3_0 = {
  144570. 4, 625,
  144571. _vq_lengthlist__8u0__p3_0,
  144572. 1, -533725184, 1611661312, 3, 0,
  144573. _vq_quantlist__8u0__p3_0,
  144574. NULL,
  144575. &_vq_auxt__8u0__p3_0,
  144576. NULL,
  144577. 0
  144578. };
  144579. static long _vq_quantlist__8u0__p4_0[] = {
  144580. 2,
  144581. 1,
  144582. 3,
  144583. 0,
  144584. 4,
  144585. };
  144586. static long _vq_lengthlist__8u0__p4_0[] = {
  144587. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  144588. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  144589. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  144590. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  144591. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  144592. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  144593. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  144594. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  144595. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  144596. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  144597. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  144598. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  144599. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  144600. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  144601. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  144602. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  144603. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  144604. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  144605. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  144606. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  144607. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  144608. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  144609. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  144610. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  144611. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  144612. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  144613. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  144614. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  144615. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  144616. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  144617. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  144618. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  144619. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  144620. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  144621. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  144622. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  144623. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  144624. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  144625. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  144626. 12,
  144627. };
  144628. static float _vq_quantthresh__8u0__p4_0[] = {
  144629. -1.5, -0.5, 0.5, 1.5,
  144630. };
  144631. static long _vq_quantmap__8u0__p4_0[] = {
  144632. 3, 1, 0, 2, 4,
  144633. };
  144634. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  144635. _vq_quantthresh__8u0__p4_0,
  144636. _vq_quantmap__8u0__p4_0,
  144637. 5,
  144638. 5
  144639. };
  144640. static static_codebook _8u0__p4_0 = {
  144641. 4, 625,
  144642. _vq_lengthlist__8u0__p4_0,
  144643. 1, -533725184, 1611661312, 3, 0,
  144644. _vq_quantlist__8u0__p4_0,
  144645. NULL,
  144646. &_vq_auxt__8u0__p4_0,
  144647. NULL,
  144648. 0
  144649. };
  144650. static long _vq_quantlist__8u0__p5_0[] = {
  144651. 4,
  144652. 3,
  144653. 5,
  144654. 2,
  144655. 6,
  144656. 1,
  144657. 7,
  144658. 0,
  144659. 8,
  144660. };
  144661. static long _vq_lengthlist__8u0__p5_0[] = {
  144662. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  144663. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  144664. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  144665. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  144666. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  144667. 12,
  144668. };
  144669. static float _vq_quantthresh__8u0__p5_0[] = {
  144670. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144671. };
  144672. static long _vq_quantmap__8u0__p5_0[] = {
  144673. 7, 5, 3, 1, 0, 2, 4, 6,
  144674. 8,
  144675. };
  144676. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  144677. _vq_quantthresh__8u0__p5_0,
  144678. _vq_quantmap__8u0__p5_0,
  144679. 9,
  144680. 9
  144681. };
  144682. static static_codebook _8u0__p5_0 = {
  144683. 2, 81,
  144684. _vq_lengthlist__8u0__p5_0,
  144685. 1, -531628032, 1611661312, 4, 0,
  144686. _vq_quantlist__8u0__p5_0,
  144687. NULL,
  144688. &_vq_auxt__8u0__p5_0,
  144689. NULL,
  144690. 0
  144691. };
  144692. static long _vq_quantlist__8u0__p6_0[] = {
  144693. 6,
  144694. 5,
  144695. 7,
  144696. 4,
  144697. 8,
  144698. 3,
  144699. 9,
  144700. 2,
  144701. 10,
  144702. 1,
  144703. 11,
  144704. 0,
  144705. 12,
  144706. };
  144707. static long _vq_lengthlist__8u0__p6_0[] = {
  144708. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  144709. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  144710. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  144711. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  144712. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  144713. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  144714. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  144715. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  144716. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  144717. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  144718. 16, 0,15, 0,17, 0, 0, 0, 0,
  144719. };
  144720. static float _vq_quantthresh__8u0__p6_0[] = {
  144721. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144722. 12.5, 17.5, 22.5, 27.5,
  144723. };
  144724. static long _vq_quantmap__8u0__p6_0[] = {
  144725. 11, 9, 7, 5, 3, 1, 0, 2,
  144726. 4, 6, 8, 10, 12,
  144727. };
  144728. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  144729. _vq_quantthresh__8u0__p6_0,
  144730. _vq_quantmap__8u0__p6_0,
  144731. 13,
  144732. 13
  144733. };
  144734. static static_codebook _8u0__p6_0 = {
  144735. 2, 169,
  144736. _vq_lengthlist__8u0__p6_0,
  144737. 1, -526516224, 1616117760, 4, 0,
  144738. _vq_quantlist__8u0__p6_0,
  144739. NULL,
  144740. &_vq_auxt__8u0__p6_0,
  144741. NULL,
  144742. 0
  144743. };
  144744. static long _vq_quantlist__8u0__p6_1[] = {
  144745. 2,
  144746. 1,
  144747. 3,
  144748. 0,
  144749. 4,
  144750. };
  144751. static long _vq_lengthlist__8u0__p6_1[] = {
  144752. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  144753. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  144754. };
  144755. static float _vq_quantthresh__8u0__p6_1[] = {
  144756. -1.5, -0.5, 0.5, 1.5,
  144757. };
  144758. static long _vq_quantmap__8u0__p6_1[] = {
  144759. 3, 1, 0, 2, 4,
  144760. };
  144761. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  144762. _vq_quantthresh__8u0__p6_1,
  144763. _vq_quantmap__8u0__p6_1,
  144764. 5,
  144765. 5
  144766. };
  144767. static static_codebook _8u0__p6_1 = {
  144768. 2, 25,
  144769. _vq_lengthlist__8u0__p6_1,
  144770. 1, -533725184, 1611661312, 3, 0,
  144771. _vq_quantlist__8u0__p6_1,
  144772. NULL,
  144773. &_vq_auxt__8u0__p6_1,
  144774. NULL,
  144775. 0
  144776. };
  144777. static long _vq_quantlist__8u0__p7_0[] = {
  144778. 1,
  144779. 0,
  144780. 2,
  144781. };
  144782. static long _vq_lengthlist__8u0__p7_0[] = {
  144783. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144784. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144785. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144786. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144787. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144788. 7,
  144789. };
  144790. static float _vq_quantthresh__8u0__p7_0[] = {
  144791. -157.5, 157.5,
  144792. };
  144793. static long _vq_quantmap__8u0__p7_0[] = {
  144794. 1, 0, 2,
  144795. };
  144796. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  144797. _vq_quantthresh__8u0__p7_0,
  144798. _vq_quantmap__8u0__p7_0,
  144799. 3,
  144800. 3
  144801. };
  144802. static static_codebook _8u0__p7_0 = {
  144803. 4, 81,
  144804. _vq_lengthlist__8u0__p7_0,
  144805. 1, -518803456, 1628680192, 2, 0,
  144806. _vq_quantlist__8u0__p7_0,
  144807. NULL,
  144808. &_vq_auxt__8u0__p7_0,
  144809. NULL,
  144810. 0
  144811. };
  144812. static long _vq_quantlist__8u0__p7_1[] = {
  144813. 7,
  144814. 6,
  144815. 8,
  144816. 5,
  144817. 9,
  144818. 4,
  144819. 10,
  144820. 3,
  144821. 11,
  144822. 2,
  144823. 12,
  144824. 1,
  144825. 13,
  144826. 0,
  144827. 14,
  144828. };
  144829. static long _vq_lengthlist__8u0__p7_1[] = {
  144830. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  144831. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  144832. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  144833. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  144834. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  144835. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  144836. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144837. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144838. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144839. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144840. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144841. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144842. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  144843. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144844. 10,
  144845. };
  144846. static float _vq_quantthresh__8u0__p7_1[] = {
  144847. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144848. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144849. };
  144850. static long _vq_quantmap__8u0__p7_1[] = {
  144851. 13, 11, 9, 7, 5, 3, 1, 0,
  144852. 2, 4, 6, 8, 10, 12, 14,
  144853. };
  144854. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  144855. _vq_quantthresh__8u0__p7_1,
  144856. _vq_quantmap__8u0__p7_1,
  144857. 15,
  144858. 15
  144859. };
  144860. static static_codebook _8u0__p7_1 = {
  144861. 2, 225,
  144862. _vq_lengthlist__8u0__p7_1,
  144863. 1, -520986624, 1620377600, 4, 0,
  144864. _vq_quantlist__8u0__p7_1,
  144865. NULL,
  144866. &_vq_auxt__8u0__p7_1,
  144867. NULL,
  144868. 0
  144869. };
  144870. static long _vq_quantlist__8u0__p7_2[] = {
  144871. 10,
  144872. 9,
  144873. 11,
  144874. 8,
  144875. 12,
  144876. 7,
  144877. 13,
  144878. 6,
  144879. 14,
  144880. 5,
  144881. 15,
  144882. 4,
  144883. 16,
  144884. 3,
  144885. 17,
  144886. 2,
  144887. 18,
  144888. 1,
  144889. 19,
  144890. 0,
  144891. 20,
  144892. };
  144893. static long _vq_lengthlist__8u0__p7_2[] = {
  144894. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  144895. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  144896. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  144897. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  144898. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  144899. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  144900. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  144901. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  144902. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  144903. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  144904. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  144905. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  144906. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  144907. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  144908. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  144909. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  144910. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  144911. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  144912. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  144913. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  144914. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  144915. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  144916. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  144917. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  144918. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  144919. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  144920. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  144921. 11,12,11,11,11,10,10,11,11,
  144922. };
  144923. static float _vq_quantthresh__8u0__p7_2[] = {
  144924. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144925. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144926. 6.5, 7.5, 8.5, 9.5,
  144927. };
  144928. static long _vq_quantmap__8u0__p7_2[] = {
  144929. 19, 17, 15, 13, 11, 9, 7, 5,
  144930. 3, 1, 0, 2, 4, 6, 8, 10,
  144931. 12, 14, 16, 18, 20,
  144932. };
  144933. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  144934. _vq_quantthresh__8u0__p7_2,
  144935. _vq_quantmap__8u0__p7_2,
  144936. 21,
  144937. 21
  144938. };
  144939. static static_codebook _8u0__p7_2 = {
  144940. 2, 441,
  144941. _vq_lengthlist__8u0__p7_2,
  144942. 1, -529268736, 1611661312, 5, 0,
  144943. _vq_quantlist__8u0__p7_2,
  144944. NULL,
  144945. &_vq_auxt__8u0__p7_2,
  144946. NULL,
  144947. 0
  144948. };
  144949. static long _huff_lengthlist__8u0__single[] = {
  144950. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  144951. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  144952. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  144953. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  144954. };
  144955. static static_codebook _huff_book__8u0__single = {
  144956. 2, 64,
  144957. _huff_lengthlist__8u0__single,
  144958. 0, 0, 0, 0, 0,
  144959. NULL,
  144960. NULL,
  144961. NULL,
  144962. NULL,
  144963. 0
  144964. };
  144965. static long _vq_quantlist__8u1__p1_0[] = {
  144966. 1,
  144967. 0,
  144968. 2,
  144969. };
  144970. static long _vq_lengthlist__8u1__p1_0[] = {
  144971. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  144972. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  144973. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  144974. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  144975. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  144976. 10,
  144977. };
  144978. static float _vq_quantthresh__8u1__p1_0[] = {
  144979. -0.5, 0.5,
  144980. };
  144981. static long _vq_quantmap__8u1__p1_0[] = {
  144982. 1, 0, 2,
  144983. };
  144984. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  144985. _vq_quantthresh__8u1__p1_0,
  144986. _vq_quantmap__8u1__p1_0,
  144987. 3,
  144988. 3
  144989. };
  144990. static static_codebook _8u1__p1_0 = {
  144991. 4, 81,
  144992. _vq_lengthlist__8u1__p1_0,
  144993. 1, -535822336, 1611661312, 2, 0,
  144994. _vq_quantlist__8u1__p1_0,
  144995. NULL,
  144996. &_vq_auxt__8u1__p1_0,
  144997. NULL,
  144998. 0
  144999. };
  145000. static long _vq_quantlist__8u1__p2_0[] = {
  145001. 1,
  145002. 0,
  145003. 2,
  145004. };
  145005. static long _vq_lengthlist__8u1__p2_0[] = {
  145006. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145007. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145008. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145009. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145010. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145011. 7,
  145012. };
  145013. static float _vq_quantthresh__8u1__p2_0[] = {
  145014. -0.5, 0.5,
  145015. };
  145016. static long _vq_quantmap__8u1__p2_0[] = {
  145017. 1, 0, 2,
  145018. };
  145019. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145020. _vq_quantthresh__8u1__p2_0,
  145021. _vq_quantmap__8u1__p2_0,
  145022. 3,
  145023. 3
  145024. };
  145025. static static_codebook _8u1__p2_0 = {
  145026. 4, 81,
  145027. _vq_lengthlist__8u1__p2_0,
  145028. 1, -535822336, 1611661312, 2, 0,
  145029. _vq_quantlist__8u1__p2_0,
  145030. NULL,
  145031. &_vq_auxt__8u1__p2_0,
  145032. NULL,
  145033. 0
  145034. };
  145035. static long _vq_quantlist__8u1__p3_0[] = {
  145036. 2,
  145037. 1,
  145038. 3,
  145039. 0,
  145040. 4,
  145041. };
  145042. static long _vq_lengthlist__8u1__p3_0[] = {
  145043. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145044. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145045. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145046. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145047. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145048. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145049. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145050. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145051. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145052. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145053. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145054. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145055. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145056. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145057. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145058. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145059. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145060. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145061. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145062. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145063. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145064. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145065. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145066. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145067. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145068. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145069. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145070. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145071. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145072. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145073. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145074. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145075. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145076. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145077. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145078. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145079. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145080. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145081. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145082. 16,
  145083. };
  145084. static float _vq_quantthresh__8u1__p3_0[] = {
  145085. -1.5, -0.5, 0.5, 1.5,
  145086. };
  145087. static long _vq_quantmap__8u1__p3_0[] = {
  145088. 3, 1, 0, 2, 4,
  145089. };
  145090. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145091. _vq_quantthresh__8u1__p3_0,
  145092. _vq_quantmap__8u1__p3_0,
  145093. 5,
  145094. 5
  145095. };
  145096. static static_codebook _8u1__p3_0 = {
  145097. 4, 625,
  145098. _vq_lengthlist__8u1__p3_0,
  145099. 1, -533725184, 1611661312, 3, 0,
  145100. _vq_quantlist__8u1__p3_0,
  145101. NULL,
  145102. &_vq_auxt__8u1__p3_0,
  145103. NULL,
  145104. 0
  145105. };
  145106. static long _vq_quantlist__8u1__p4_0[] = {
  145107. 2,
  145108. 1,
  145109. 3,
  145110. 0,
  145111. 4,
  145112. };
  145113. static long _vq_lengthlist__8u1__p4_0[] = {
  145114. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145115. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145116. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145117. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145118. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145119. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145120. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145121. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145122. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145123. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145124. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145125. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145126. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145127. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145128. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145129. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145130. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145131. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145132. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145133. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145134. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145135. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145136. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145137. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145138. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145139. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145140. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145141. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145142. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145143. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145144. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145145. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145146. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145147. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145148. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145149. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145150. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145151. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145152. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145153. 10,
  145154. };
  145155. static float _vq_quantthresh__8u1__p4_0[] = {
  145156. -1.5, -0.5, 0.5, 1.5,
  145157. };
  145158. static long _vq_quantmap__8u1__p4_0[] = {
  145159. 3, 1, 0, 2, 4,
  145160. };
  145161. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145162. _vq_quantthresh__8u1__p4_0,
  145163. _vq_quantmap__8u1__p4_0,
  145164. 5,
  145165. 5
  145166. };
  145167. static static_codebook _8u1__p4_0 = {
  145168. 4, 625,
  145169. _vq_lengthlist__8u1__p4_0,
  145170. 1, -533725184, 1611661312, 3, 0,
  145171. _vq_quantlist__8u1__p4_0,
  145172. NULL,
  145173. &_vq_auxt__8u1__p4_0,
  145174. NULL,
  145175. 0
  145176. };
  145177. static long _vq_quantlist__8u1__p5_0[] = {
  145178. 4,
  145179. 3,
  145180. 5,
  145181. 2,
  145182. 6,
  145183. 1,
  145184. 7,
  145185. 0,
  145186. 8,
  145187. };
  145188. static long _vq_lengthlist__8u1__p5_0[] = {
  145189. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145190. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145191. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145192. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145193. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145194. 13,
  145195. };
  145196. static float _vq_quantthresh__8u1__p5_0[] = {
  145197. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145198. };
  145199. static long _vq_quantmap__8u1__p5_0[] = {
  145200. 7, 5, 3, 1, 0, 2, 4, 6,
  145201. 8,
  145202. };
  145203. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145204. _vq_quantthresh__8u1__p5_0,
  145205. _vq_quantmap__8u1__p5_0,
  145206. 9,
  145207. 9
  145208. };
  145209. static static_codebook _8u1__p5_0 = {
  145210. 2, 81,
  145211. _vq_lengthlist__8u1__p5_0,
  145212. 1, -531628032, 1611661312, 4, 0,
  145213. _vq_quantlist__8u1__p5_0,
  145214. NULL,
  145215. &_vq_auxt__8u1__p5_0,
  145216. NULL,
  145217. 0
  145218. };
  145219. static long _vq_quantlist__8u1__p6_0[] = {
  145220. 4,
  145221. 3,
  145222. 5,
  145223. 2,
  145224. 6,
  145225. 1,
  145226. 7,
  145227. 0,
  145228. 8,
  145229. };
  145230. static long _vq_lengthlist__8u1__p6_0[] = {
  145231. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145232. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145233. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145234. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145235. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145236. 10,
  145237. };
  145238. static float _vq_quantthresh__8u1__p6_0[] = {
  145239. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145240. };
  145241. static long _vq_quantmap__8u1__p6_0[] = {
  145242. 7, 5, 3, 1, 0, 2, 4, 6,
  145243. 8,
  145244. };
  145245. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145246. _vq_quantthresh__8u1__p6_0,
  145247. _vq_quantmap__8u1__p6_0,
  145248. 9,
  145249. 9
  145250. };
  145251. static static_codebook _8u1__p6_0 = {
  145252. 2, 81,
  145253. _vq_lengthlist__8u1__p6_0,
  145254. 1, -531628032, 1611661312, 4, 0,
  145255. _vq_quantlist__8u1__p6_0,
  145256. NULL,
  145257. &_vq_auxt__8u1__p6_0,
  145258. NULL,
  145259. 0
  145260. };
  145261. static long _vq_quantlist__8u1__p7_0[] = {
  145262. 1,
  145263. 0,
  145264. 2,
  145265. };
  145266. static long _vq_lengthlist__8u1__p7_0[] = {
  145267. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  145268. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  145269. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  145270. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  145271. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  145272. 11,
  145273. };
  145274. static float _vq_quantthresh__8u1__p7_0[] = {
  145275. -5.5, 5.5,
  145276. };
  145277. static long _vq_quantmap__8u1__p7_0[] = {
  145278. 1, 0, 2,
  145279. };
  145280. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  145281. _vq_quantthresh__8u1__p7_0,
  145282. _vq_quantmap__8u1__p7_0,
  145283. 3,
  145284. 3
  145285. };
  145286. static static_codebook _8u1__p7_0 = {
  145287. 4, 81,
  145288. _vq_lengthlist__8u1__p7_0,
  145289. 1, -529137664, 1618345984, 2, 0,
  145290. _vq_quantlist__8u1__p7_0,
  145291. NULL,
  145292. &_vq_auxt__8u1__p7_0,
  145293. NULL,
  145294. 0
  145295. };
  145296. static long _vq_quantlist__8u1__p7_1[] = {
  145297. 5,
  145298. 4,
  145299. 6,
  145300. 3,
  145301. 7,
  145302. 2,
  145303. 8,
  145304. 1,
  145305. 9,
  145306. 0,
  145307. 10,
  145308. };
  145309. static long _vq_lengthlist__8u1__p7_1[] = {
  145310. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145311. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145312. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145313. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145314. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145315. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145316. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145317. 9, 9, 9, 9, 9,10,10,10,10,
  145318. };
  145319. static float _vq_quantthresh__8u1__p7_1[] = {
  145320. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145321. 3.5, 4.5,
  145322. };
  145323. static long _vq_quantmap__8u1__p7_1[] = {
  145324. 9, 7, 5, 3, 1, 0, 2, 4,
  145325. 6, 8, 10,
  145326. };
  145327. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145328. _vq_quantthresh__8u1__p7_1,
  145329. _vq_quantmap__8u1__p7_1,
  145330. 11,
  145331. 11
  145332. };
  145333. static static_codebook _8u1__p7_1 = {
  145334. 2, 121,
  145335. _vq_lengthlist__8u1__p7_1,
  145336. 1, -531365888, 1611661312, 4, 0,
  145337. _vq_quantlist__8u1__p7_1,
  145338. NULL,
  145339. &_vq_auxt__8u1__p7_1,
  145340. NULL,
  145341. 0
  145342. };
  145343. static long _vq_quantlist__8u1__p8_0[] = {
  145344. 5,
  145345. 4,
  145346. 6,
  145347. 3,
  145348. 7,
  145349. 2,
  145350. 8,
  145351. 1,
  145352. 9,
  145353. 0,
  145354. 10,
  145355. };
  145356. static long _vq_lengthlist__8u1__p8_0[] = {
  145357. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145358. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145359. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145360. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145361. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145362. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145363. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145364. 12,13,13,14,14,15,15,15,15,
  145365. };
  145366. static float _vq_quantthresh__8u1__p8_0[] = {
  145367. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145368. 38.5, 49.5,
  145369. };
  145370. static long _vq_quantmap__8u1__p8_0[] = {
  145371. 9, 7, 5, 3, 1, 0, 2, 4,
  145372. 6, 8, 10,
  145373. };
  145374. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  145375. _vq_quantthresh__8u1__p8_0,
  145376. _vq_quantmap__8u1__p8_0,
  145377. 11,
  145378. 11
  145379. };
  145380. static static_codebook _8u1__p8_0 = {
  145381. 2, 121,
  145382. _vq_lengthlist__8u1__p8_0,
  145383. 1, -524582912, 1618345984, 4, 0,
  145384. _vq_quantlist__8u1__p8_0,
  145385. NULL,
  145386. &_vq_auxt__8u1__p8_0,
  145387. NULL,
  145388. 0
  145389. };
  145390. static long _vq_quantlist__8u1__p8_1[] = {
  145391. 5,
  145392. 4,
  145393. 6,
  145394. 3,
  145395. 7,
  145396. 2,
  145397. 8,
  145398. 1,
  145399. 9,
  145400. 0,
  145401. 10,
  145402. };
  145403. static long _vq_lengthlist__8u1__p8_1[] = {
  145404. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  145405. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  145406. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145407. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145408. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145409. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  145410. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  145411. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145412. };
  145413. static float _vq_quantthresh__8u1__p8_1[] = {
  145414. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145415. 3.5, 4.5,
  145416. };
  145417. static long _vq_quantmap__8u1__p8_1[] = {
  145418. 9, 7, 5, 3, 1, 0, 2, 4,
  145419. 6, 8, 10,
  145420. };
  145421. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  145422. _vq_quantthresh__8u1__p8_1,
  145423. _vq_quantmap__8u1__p8_1,
  145424. 11,
  145425. 11
  145426. };
  145427. static static_codebook _8u1__p8_1 = {
  145428. 2, 121,
  145429. _vq_lengthlist__8u1__p8_1,
  145430. 1, -531365888, 1611661312, 4, 0,
  145431. _vq_quantlist__8u1__p8_1,
  145432. NULL,
  145433. &_vq_auxt__8u1__p8_1,
  145434. NULL,
  145435. 0
  145436. };
  145437. static long _vq_quantlist__8u1__p9_0[] = {
  145438. 7,
  145439. 6,
  145440. 8,
  145441. 5,
  145442. 9,
  145443. 4,
  145444. 10,
  145445. 3,
  145446. 11,
  145447. 2,
  145448. 12,
  145449. 1,
  145450. 13,
  145451. 0,
  145452. 14,
  145453. };
  145454. static long _vq_lengthlist__8u1__p9_0[] = {
  145455. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  145456. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  145457. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145458. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145459. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145460. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145461. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145462. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145463. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145464. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145465. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145466. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145467. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  145468. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145469. 10,
  145470. };
  145471. static float _vq_quantthresh__8u1__p9_0[] = {
  145472. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145473. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145474. };
  145475. static long _vq_quantmap__8u1__p9_0[] = {
  145476. 13, 11, 9, 7, 5, 3, 1, 0,
  145477. 2, 4, 6, 8, 10, 12, 14,
  145478. };
  145479. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  145480. _vq_quantthresh__8u1__p9_0,
  145481. _vq_quantmap__8u1__p9_0,
  145482. 15,
  145483. 15
  145484. };
  145485. static static_codebook _8u1__p9_0 = {
  145486. 2, 225,
  145487. _vq_lengthlist__8u1__p9_0,
  145488. 1, -514071552, 1627381760, 4, 0,
  145489. _vq_quantlist__8u1__p9_0,
  145490. NULL,
  145491. &_vq_auxt__8u1__p9_0,
  145492. NULL,
  145493. 0
  145494. };
  145495. static long _vq_quantlist__8u1__p9_1[] = {
  145496. 7,
  145497. 6,
  145498. 8,
  145499. 5,
  145500. 9,
  145501. 4,
  145502. 10,
  145503. 3,
  145504. 11,
  145505. 2,
  145506. 12,
  145507. 1,
  145508. 13,
  145509. 0,
  145510. 14,
  145511. };
  145512. static long _vq_lengthlist__8u1__p9_1[] = {
  145513. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  145514. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  145515. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  145516. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  145517. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  145518. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  145519. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  145520. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  145521. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  145522. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  145523. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  145524. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  145525. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  145526. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  145527. 13,
  145528. };
  145529. static float _vq_quantthresh__8u1__p9_1[] = {
  145530. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145531. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145532. };
  145533. static long _vq_quantmap__8u1__p9_1[] = {
  145534. 13, 11, 9, 7, 5, 3, 1, 0,
  145535. 2, 4, 6, 8, 10, 12, 14,
  145536. };
  145537. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  145538. _vq_quantthresh__8u1__p9_1,
  145539. _vq_quantmap__8u1__p9_1,
  145540. 15,
  145541. 15
  145542. };
  145543. static static_codebook _8u1__p9_1 = {
  145544. 2, 225,
  145545. _vq_lengthlist__8u1__p9_1,
  145546. 1, -522338304, 1620115456, 4, 0,
  145547. _vq_quantlist__8u1__p9_1,
  145548. NULL,
  145549. &_vq_auxt__8u1__p9_1,
  145550. NULL,
  145551. 0
  145552. };
  145553. static long _vq_quantlist__8u1__p9_2[] = {
  145554. 8,
  145555. 7,
  145556. 9,
  145557. 6,
  145558. 10,
  145559. 5,
  145560. 11,
  145561. 4,
  145562. 12,
  145563. 3,
  145564. 13,
  145565. 2,
  145566. 14,
  145567. 1,
  145568. 15,
  145569. 0,
  145570. 16,
  145571. };
  145572. static long _vq_lengthlist__8u1__p9_2[] = {
  145573. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145574. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145575. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145576. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  145577. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145578. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  145579. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145580. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  145581. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145582. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  145583. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145584. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  145585. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145586. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145587. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  145588. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145589. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145590. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145591. 10,
  145592. };
  145593. static float _vq_quantthresh__8u1__p9_2[] = {
  145594. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145595. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145596. };
  145597. static long _vq_quantmap__8u1__p9_2[] = {
  145598. 15, 13, 11, 9, 7, 5, 3, 1,
  145599. 0, 2, 4, 6, 8, 10, 12, 14,
  145600. 16,
  145601. };
  145602. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  145603. _vq_quantthresh__8u1__p9_2,
  145604. _vq_quantmap__8u1__p9_2,
  145605. 17,
  145606. 17
  145607. };
  145608. static static_codebook _8u1__p9_2 = {
  145609. 2, 289,
  145610. _vq_lengthlist__8u1__p9_2,
  145611. 1, -529530880, 1611661312, 5, 0,
  145612. _vq_quantlist__8u1__p9_2,
  145613. NULL,
  145614. &_vq_auxt__8u1__p9_2,
  145615. NULL,
  145616. 0
  145617. };
  145618. static long _huff_lengthlist__8u1__single[] = {
  145619. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  145620. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  145621. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  145622. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  145623. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  145624. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  145625. 13, 8, 8,15,
  145626. };
  145627. static static_codebook _huff_book__8u1__single = {
  145628. 2, 100,
  145629. _huff_lengthlist__8u1__single,
  145630. 0, 0, 0, 0, 0,
  145631. NULL,
  145632. NULL,
  145633. NULL,
  145634. NULL,
  145635. 0
  145636. };
  145637. static long _huff_lengthlist__44u0__long[] = {
  145638. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  145639. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  145640. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  145641. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  145642. };
  145643. static static_codebook _huff_book__44u0__long = {
  145644. 2, 64,
  145645. _huff_lengthlist__44u0__long,
  145646. 0, 0, 0, 0, 0,
  145647. NULL,
  145648. NULL,
  145649. NULL,
  145650. NULL,
  145651. 0
  145652. };
  145653. static long _vq_quantlist__44u0__p1_0[] = {
  145654. 1,
  145655. 0,
  145656. 2,
  145657. };
  145658. static long _vq_lengthlist__44u0__p1_0[] = {
  145659. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  145660. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  145661. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  145662. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  145663. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  145664. 13,
  145665. };
  145666. static float _vq_quantthresh__44u0__p1_0[] = {
  145667. -0.5, 0.5,
  145668. };
  145669. static long _vq_quantmap__44u0__p1_0[] = {
  145670. 1, 0, 2,
  145671. };
  145672. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  145673. _vq_quantthresh__44u0__p1_0,
  145674. _vq_quantmap__44u0__p1_0,
  145675. 3,
  145676. 3
  145677. };
  145678. static static_codebook _44u0__p1_0 = {
  145679. 4, 81,
  145680. _vq_lengthlist__44u0__p1_0,
  145681. 1, -535822336, 1611661312, 2, 0,
  145682. _vq_quantlist__44u0__p1_0,
  145683. NULL,
  145684. &_vq_auxt__44u0__p1_0,
  145685. NULL,
  145686. 0
  145687. };
  145688. static long _vq_quantlist__44u0__p2_0[] = {
  145689. 1,
  145690. 0,
  145691. 2,
  145692. };
  145693. static long _vq_lengthlist__44u0__p2_0[] = {
  145694. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  145695. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  145696. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  145697. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  145698. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  145699. 9,
  145700. };
  145701. static float _vq_quantthresh__44u0__p2_0[] = {
  145702. -0.5, 0.5,
  145703. };
  145704. static long _vq_quantmap__44u0__p2_0[] = {
  145705. 1, 0, 2,
  145706. };
  145707. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  145708. _vq_quantthresh__44u0__p2_0,
  145709. _vq_quantmap__44u0__p2_0,
  145710. 3,
  145711. 3
  145712. };
  145713. static static_codebook _44u0__p2_0 = {
  145714. 4, 81,
  145715. _vq_lengthlist__44u0__p2_0,
  145716. 1, -535822336, 1611661312, 2, 0,
  145717. _vq_quantlist__44u0__p2_0,
  145718. NULL,
  145719. &_vq_auxt__44u0__p2_0,
  145720. NULL,
  145721. 0
  145722. };
  145723. static long _vq_quantlist__44u0__p3_0[] = {
  145724. 2,
  145725. 1,
  145726. 3,
  145727. 0,
  145728. 4,
  145729. };
  145730. static long _vq_lengthlist__44u0__p3_0[] = {
  145731. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  145732. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  145733. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  145734. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145735. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  145736. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  145737. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  145738. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  145739. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  145740. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  145741. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  145742. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  145743. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  145744. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  145745. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  145746. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  145747. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  145748. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  145749. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  145750. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  145751. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  145752. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  145753. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  145754. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  145755. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  145756. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  145757. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  145758. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  145759. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  145760. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  145761. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  145762. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  145763. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  145764. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  145765. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  145766. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  145767. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  145768. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  145769. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  145770. 19,
  145771. };
  145772. static float _vq_quantthresh__44u0__p3_0[] = {
  145773. -1.5, -0.5, 0.5, 1.5,
  145774. };
  145775. static long _vq_quantmap__44u0__p3_0[] = {
  145776. 3, 1, 0, 2, 4,
  145777. };
  145778. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  145779. _vq_quantthresh__44u0__p3_0,
  145780. _vq_quantmap__44u0__p3_0,
  145781. 5,
  145782. 5
  145783. };
  145784. static static_codebook _44u0__p3_0 = {
  145785. 4, 625,
  145786. _vq_lengthlist__44u0__p3_0,
  145787. 1, -533725184, 1611661312, 3, 0,
  145788. _vq_quantlist__44u0__p3_0,
  145789. NULL,
  145790. &_vq_auxt__44u0__p3_0,
  145791. NULL,
  145792. 0
  145793. };
  145794. static long _vq_quantlist__44u0__p4_0[] = {
  145795. 2,
  145796. 1,
  145797. 3,
  145798. 0,
  145799. 4,
  145800. };
  145801. static long _vq_lengthlist__44u0__p4_0[] = {
  145802. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  145803. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  145804. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  145805. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  145806. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  145807. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  145808. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  145809. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  145810. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  145811. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  145812. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  145813. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  145814. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  145815. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  145816. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  145817. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  145818. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  145819. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  145820. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  145821. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  145822. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  145823. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  145824. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  145825. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  145826. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  145827. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  145828. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  145829. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  145830. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  145831. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  145832. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  145833. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  145834. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  145835. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  145836. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  145837. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  145838. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  145839. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  145840. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  145841. 12,
  145842. };
  145843. static float _vq_quantthresh__44u0__p4_0[] = {
  145844. -1.5, -0.5, 0.5, 1.5,
  145845. };
  145846. static long _vq_quantmap__44u0__p4_0[] = {
  145847. 3, 1, 0, 2, 4,
  145848. };
  145849. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  145850. _vq_quantthresh__44u0__p4_0,
  145851. _vq_quantmap__44u0__p4_0,
  145852. 5,
  145853. 5
  145854. };
  145855. static static_codebook _44u0__p4_0 = {
  145856. 4, 625,
  145857. _vq_lengthlist__44u0__p4_0,
  145858. 1, -533725184, 1611661312, 3, 0,
  145859. _vq_quantlist__44u0__p4_0,
  145860. NULL,
  145861. &_vq_auxt__44u0__p4_0,
  145862. NULL,
  145863. 0
  145864. };
  145865. static long _vq_quantlist__44u0__p5_0[] = {
  145866. 4,
  145867. 3,
  145868. 5,
  145869. 2,
  145870. 6,
  145871. 1,
  145872. 7,
  145873. 0,
  145874. 8,
  145875. };
  145876. static long _vq_lengthlist__44u0__p5_0[] = {
  145877. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  145878. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  145879. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  145880. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145881. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  145882. 12,
  145883. };
  145884. static float _vq_quantthresh__44u0__p5_0[] = {
  145885. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145886. };
  145887. static long _vq_quantmap__44u0__p5_0[] = {
  145888. 7, 5, 3, 1, 0, 2, 4, 6,
  145889. 8,
  145890. };
  145891. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  145892. _vq_quantthresh__44u0__p5_0,
  145893. _vq_quantmap__44u0__p5_0,
  145894. 9,
  145895. 9
  145896. };
  145897. static static_codebook _44u0__p5_0 = {
  145898. 2, 81,
  145899. _vq_lengthlist__44u0__p5_0,
  145900. 1, -531628032, 1611661312, 4, 0,
  145901. _vq_quantlist__44u0__p5_0,
  145902. NULL,
  145903. &_vq_auxt__44u0__p5_0,
  145904. NULL,
  145905. 0
  145906. };
  145907. static long _vq_quantlist__44u0__p6_0[] = {
  145908. 6,
  145909. 5,
  145910. 7,
  145911. 4,
  145912. 8,
  145913. 3,
  145914. 9,
  145915. 2,
  145916. 10,
  145917. 1,
  145918. 11,
  145919. 0,
  145920. 12,
  145921. };
  145922. static long _vq_lengthlist__44u0__p6_0[] = {
  145923. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  145924. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  145925. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  145926. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  145927. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  145928. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  145929. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  145930. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  145931. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  145932. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  145933. 15,17,16,17,18,17,17,18, 0,
  145934. };
  145935. static float _vq_quantthresh__44u0__p6_0[] = {
  145936. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145937. 12.5, 17.5, 22.5, 27.5,
  145938. };
  145939. static long _vq_quantmap__44u0__p6_0[] = {
  145940. 11, 9, 7, 5, 3, 1, 0, 2,
  145941. 4, 6, 8, 10, 12,
  145942. };
  145943. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  145944. _vq_quantthresh__44u0__p6_0,
  145945. _vq_quantmap__44u0__p6_0,
  145946. 13,
  145947. 13
  145948. };
  145949. static static_codebook _44u0__p6_0 = {
  145950. 2, 169,
  145951. _vq_lengthlist__44u0__p6_0,
  145952. 1, -526516224, 1616117760, 4, 0,
  145953. _vq_quantlist__44u0__p6_0,
  145954. NULL,
  145955. &_vq_auxt__44u0__p6_0,
  145956. NULL,
  145957. 0
  145958. };
  145959. static long _vq_quantlist__44u0__p6_1[] = {
  145960. 2,
  145961. 1,
  145962. 3,
  145963. 0,
  145964. 4,
  145965. };
  145966. static long _vq_lengthlist__44u0__p6_1[] = {
  145967. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  145968. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  145969. };
  145970. static float _vq_quantthresh__44u0__p6_1[] = {
  145971. -1.5, -0.5, 0.5, 1.5,
  145972. };
  145973. static long _vq_quantmap__44u0__p6_1[] = {
  145974. 3, 1, 0, 2, 4,
  145975. };
  145976. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  145977. _vq_quantthresh__44u0__p6_1,
  145978. _vq_quantmap__44u0__p6_1,
  145979. 5,
  145980. 5
  145981. };
  145982. static static_codebook _44u0__p6_1 = {
  145983. 2, 25,
  145984. _vq_lengthlist__44u0__p6_1,
  145985. 1, -533725184, 1611661312, 3, 0,
  145986. _vq_quantlist__44u0__p6_1,
  145987. NULL,
  145988. &_vq_auxt__44u0__p6_1,
  145989. NULL,
  145990. 0
  145991. };
  145992. static long _vq_quantlist__44u0__p7_0[] = {
  145993. 2,
  145994. 1,
  145995. 3,
  145996. 0,
  145997. 4,
  145998. };
  145999. static long _vq_lengthlist__44u0__p7_0[] = {
  146000. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146001. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146002. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146003. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146004. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146005. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146006. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146007. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146008. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146009. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146010. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146011. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146012. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146013. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146014. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146015. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146016. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146017. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146018. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146019. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146020. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146021. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146022. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146023. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146024. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146025. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146026. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146027. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146028. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146029. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146030. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146031. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146032. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146033. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146034. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146035. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146036. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146037. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146038. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146039. 10,
  146040. };
  146041. static float _vq_quantthresh__44u0__p7_0[] = {
  146042. -253.5, -84.5, 84.5, 253.5,
  146043. };
  146044. static long _vq_quantmap__44u0__p7_0[] = {
  146045. 3, 1, 0, 2, 4,
  146046. };
  146047. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146048. _vq_quantthresh__44u0__p7_0,
  146049. _vq_quantmap__44u0__p7_0,
  146050. 5,
  146051. 5
  146052. };
  146053. static static_codebook _44u0__p7_0 = {
  146054. 4, 625,
  146055. _vq_lengthlist__44u0__p7_0,
  146056. 1, -518709248, 1626677248, 3, 0,
  146057. _vq_quantlist__44u0__p7_0,
  146058. NULL,
  146059. &_vq_auxt__44u0__p7_0,
  146060. NULL,
  146061. 0
  146062. };
  146063. static long _vq_quantlist__44u0__p7_1[] = {
  146064. 6,
  146065. 5,
  146066. 7,
  146067. 4,
  146068. 8,
  146069. 3,
  146070. 9,
  146071. 2,
  146072. 10,
  146073. 1,
  146074. 11,
  146075. 0,
  146076. 12,
  146077. };
  146078. static long _vq_lengthlist__44u0__p7_1[] = {
  146079. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146080. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146081. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146082. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146083. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146084. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146085. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146086. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146087. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146088. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146089. 15,15,15,15,15,15,15,15,15,
  146090. };
  146091. static float _vq_quantthresh__44u0__p7_1[] = {
  146092. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146093. 32.5, 45.5, 58.5, 71.5,
  146094. };
  146095. static long _vq_quantmap__44u0__p7_1[] = {
  146096. 11, 9, 7, 5, 3, 1, 0, 2,
  146097. 4, 6, 8, 10, 12,
  146098. };
  146099. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146100. _vq_quantthresh__44u0__p7_1,
  146101. _vq_quantmap__44u0__p7_1,
  146102. 13,
  146103. 13
  146104. };
  146105. static static_codebook _44u0__p7_1 = {
  146106. 2, 169,
  146107. _vq_lengthlist__44u0__p7_1,
  146108. 1, -523010048, 1618608128, 4, 0,
  146109. _vq_quantlist__44u0__p7_1,
  146110. NULL,
  146111. &_vq_auxt__44u0__p7_1,
  146112. NULL,
  146113. 0
  146114. };
  146115. static long _vq_quantlist__44u0__p7_2[] = {
  146116. 6,
  146117. 5,
  146118. 7,
  146119. 4,
  146120. 8,
  146121. 3,
  146122. 9,
  146123. 2,
  146124. 10,
  146125. 1,
  146126. 11,
  146127. 0,
  146128. 12,
  146129. };
  146130. static long _vq_lengthlist__44u0__p7_2[] = {
  146131. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146132. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146133. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146134. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146135. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146136. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146137. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146138. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146139. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146140. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146141. 9, 9, 9,10, 9, 9,10,10, 9,
  146142. };
  146143. static float _vq_quantthresh__44u0__p7_2[] = {
  146144. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146145. 2.5, 3.5, 4.5, 5.5,
  146146. };
  146147. static long _vq_quantmap__44u0__p7_2[] = {
  146148. 11, 9, 7, 5, 3, 1, 0, 2,
  146149. 4, 6, 8, 10, 12,
  146150. };
  146151. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146152. _vq_quantthresh__44u0__p7_2,
  146153. _vq_quantmap__44u0__p7_2,
  146154. 13,
  146155. 13
  146156. };
  146157. static static_codebook _44u0__p7_2 = {
  146158. 2, 169,
  146159. _vq_lengthlist__44u0__p7_2,
  146160. 1, -531103744, 1611661312, 4, 0,
  146161. _vq_quantlist__44u0__p7_2,
  146162. NULL,
  146163. &_vq_auxt__44u0__p7_2,
  146164. NULL,
  146165. 0
  146166. };
  146167. static long _huff_lengthlist__44u0__short[] = {
  146168. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146169. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146170. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146171. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146172. };
  146173. static static_codebook _huff_book__44u0__short = {
  146174. 2, 64,
  146175. _huff_lengthlist__44u0__short,
  146176. 0, 0, 0, 0, 0,
  146177. NULL,
  146178. NULL,
  146179. NULL,
  146180. NULL,
  146181. 0
  146182. };
  146183. static long _huff_lengthlist__44u1__long[] = {
  146184. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146185. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146186. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146187. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146188. };
  146189. static static_codebook _huff_book__44u1__long = {
  146190. 2, 64,
  146191. _huff_lengthlist__44u1__long,
  146192. 0, 0, 0, 0, 0,
  146193. NULL,
  146194. NULL,
  146195. NULL,
  146196. NULL,
  146197. 0
  146198. };
  146199. static long _vq_quantlist__44u1__p1_0[] = {
  146200. 1,
  146201. 0,
  146202. 2,
  146203. };
  146204. static long _vq_lengthlist__44u1__p1_0[] = {
  146205. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146206. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146207. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146208. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146209. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146210. 13,
  146211. };
  146212. static float _vq_quantthresh__44u1__p1_0[] = {
  146213. -0.5, 0.5,
  146214. };
  146215. static long _vq_quantmap__44u1__p1_0[] = {
  146216. 1, 0, 2,
  146217. };
  146218. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146219. _vq_quantthresh__44u1__p1_0,
  146220. _vq_quantmap__44u1__p1_0,
  146221. 3,
  146222. 3
  146223. };
  146224. static static_codebook _44u1__p1_0 = {
  146225. 4, 81,
  146226. _vq_lengthlist__44u1__p1_0,
  146227. 1, -535822336, 1611661312, 2, 0,
  146228. _vq_quantlist__44u1__p1_0,
  146229. NULL,
  146230. &_vq_auxt__44u1__p1_0,
  146231. NULL,
  146232. 0
  146233. };
  146234. static long _vq_quantlist__44u1__p2_0[] = {
  146235. 1,
  146236. 0,
  146237. 2,
  146238. };
  146239. static long _vq_lengthlist__44u1__p2_0[] = {
  146240. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146241. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146242. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146243. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146244. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146245. 9,
  146246. };
  146247. static float _vq_quantthresh__44u1__p2_0[] = {
  146248. -0.5, 0.5,
  146249. };
  146250. static long _vq_quantmap__44u1__p2_0[] = {
  146251. 1, 0, 2,
  146252. };
  146253. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146254. _vq_quantthresh__44u1__p2_0,
  146255. _vq_quantmap__44u1__p2_0,
  146256. 3,
  146257. 3
  146258. };
  146259. static static_codebook _44u1__p2_0 = {
  146260. 4, 81,
  146261. _vq_lengthlist__44u1__p2_0,
  146262. 1, -535822336, 1611661312, 2, 0,
  146263. _vq_quantlist__44u1__p2_0,
  146264. NULL,
  146265. &_vq_auxt__44u1__p2_0,
  146266. NULL,
  146267. 0
  146268. };
  146269. static long _vq_quantlist__44u1__p3_0[] = {
  146270. 2,
  146271. 1,
  146272. 3,
  146273. 0,
  146274. 4,
  146275. };
  146276. static long _vq_lengthlist__44u1__p3_0[] = {
  146277. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146278. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146279. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146280. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146281. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146282. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146283. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146284. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146285. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146286. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146287. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146288. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146289. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146290. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146291. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146292. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146293. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146294. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146295. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146296. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146297. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146298. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146299. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146300. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146301. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146302. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146303. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146304. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146305. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146306. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146307. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146308. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146309. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146310. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146311. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146312. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146313. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146314. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146315. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146316. 19,
  146317. };
  146318. static float _vq_quantthresh__44u1__p3_0[] = {
  146319. -1.5, -0.5, 0.5, 1.5,
  146320. };
  146321. static long _vq_quantmap__44u1__p3_0[] = {
  146322. 3, 1, 0, 2, 4,
  146323. };
  146324. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146325. _vq_quantthresh__44u1__p3_0,
  146326. _vq_quantmap__44u1__p3_0,
  146327. 5,
  146328. 5
  146329. };
  146330. static static_codebook _44u1__p3_0 = {
  146331. 4, 625,
  146332. _vq_lengthlist__44u1__p3_0,
  146333. 1, -533725184, 1611661312, 3, 0,
  146334. _vq_quantlist__44u1__p3_0,
  146335. NULL,
  146336. &_vq_auxt__44u1__p3_0,
  146337. NULL,
  146338. 0
  146339. };
  146340. static long _vq_quantlist__44u1__p4_0[] = {
  146341. 2,
  146342. 1,
  146343. 3,
  146344. 0,
  146345. 4,
  146346. };
  146347. static long _vq_lengthlist__44u1__p4_0[] = {
  146348. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146349. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146350. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146351. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146352. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146353. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146354. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146355. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146356. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146357. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146358. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146359. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146360. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146361. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146362. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146363. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146364. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146365. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146366. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146367. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146368. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146369. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146370. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146371. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146372. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146373. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146374. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146375. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146376. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146377. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146378. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146379. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146380. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146381. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146382. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146383. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146384. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146385. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146386. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146387. 12,
  146388. };
  146389. static float _vq_quantthresh__44u1__p4_0[] = {
  146390. -1.5, -0.5, 0.5, 1.5,
  146391. };
  146392. static long _vq_quantmap__44u1__p4_0[] = {
  146393. 3, 1, 0, 2, 4,
  146394. };
  146395. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  146396. _vq_quantthresh__44u1__p4_0,
  146397. _vq_quantmap__44u1__p4_0,
  146398. 5,
  146399. 5
  146400. };
  146401. static static_codebook _44u1__p4_0 = {
  146402. 4, 625,
  146403. _vq_lengthlist__44u1__p4_0,
  146404. 1, -533725184, 1611661312, 3, 0,
  146405. _vq_quantlist__44u1__p4_0,
  146406. NULL,
  146407. &_vq_auxt__44u1__p4_0,
  146408. NULL,
  146409. 0
  146410. };
  146411. static long _vq_quantlist__44u1__p5_0[] = {
  146412. 4,
  146413. 3,
  146414. 5,
  146415. 2,
  146416. 6,
  146417. 1,
  146418. 7,
  146419. 0,
  146420. 8,
  146421. };
  146422. static long _vq_lengthlist__44u1__p5_0[] = {
  146423. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146424. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146425. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146426. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146427. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146428. 12,
  146429. };
  146430. static float _vq_quantthresh__44u1__p5_0[] = {
  146431. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146432. };
  146433. static long _vq_quantmap__44u1__p5_0[] = {
  146434. 7, 5, 3, 1, 0, 2, 4, 6,
  146435. 8,
  146436. };
  146437. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  146438. _vq_quantthresh__44u1__p5_0,
  146439. _vq_quantmap__44u1__p5_0,
  146440. 9,
  146441. 9
  146442. };
  146443. static static_codebook _44u1__p5_0 = {
  146444. 2, 81,
  146445. _vq_lengthlist__44u1__p5_0,
  146446. 1, -531628032, 1611661312, 4, 0,
  146447. _vq_quantlist__44u1__p5_0,
  146448. NULL,
  146449. &_vq_auxt__44u1__p5_0,
  146450. NULL,
  146451. 0
  146452. };
  146453. static long _vq_quantlist__44u1__p6_0[] = {
  146454. 6,
  146455. 5,
  146456. 7,
  146457. 4,
  146458. 8,
  146459. 3,
  146460. 9,
  146461. 2,
  146462. 10,
  146463. 1,
  146464. 11,
  146465. 0,
  146466. 12,
  146467. };
  146468. static long _vq_lengthlist__44u1__p6_0[] = {
  146469. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146470. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146471. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146472. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146473. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146474. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146475. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146476. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146477. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146478. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146479. 15,17,16,17,18,17,17,18, 0,
  146480. };
  146481. static float _vq_quantthresh__44u1__p6_0[] = {
  146482. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146483. 12.5, 17.5, 22.5, 27.5,
  146484. };
  146485. static long _vq_quantmap__44u1__p6_0[] = {
  146486. 11, 9, 7, 5, 3, 1, 0, 2,
  146487. 4, 6, 8, 10, 12,
  146488. };
  146489. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  146490. _vq_quantthresh__44u1__p6_0,
  146491. _vq_quantmap__44u1__p6_0,
  146492. 13,
  146493. 13
  146494. };
  146495. static static_codebook _44u1__p6_0 = {
  146496. 2, 169,
  146497. _vq_lengthlist__44u1__p6_0,
  146498. 1, -526516224, 1616117760, 4, 0,
  146499. _vq_quantlist__44u1__p6_0,
  146500. NULL,
  146501. &_vq_auxt__44u1__p6_0,
  146502. NULL,
  146503. 0
  146504. };
  146505. static long _vq_quantlist__44u1__p6_1[] = {
  146506. 2,
  146507. 1,
  146508. 3,
  146509. 0,
  146510. 4,
  146511. };
  146512. static long _vq_lengthlist__44u1__p6_1[] = {
  146513. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146514. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146515. };
  146516. static float _vq_quantthresh__44u1__p6_1[] = {
  146517. -1.5, -0.5, 0.5, 1.5,
  146518. };
  146519. static long _vq_quantmap__44u1__p6_1[] = {
  146520. 3, 1, 0, 2, 4,
  146521. };
  146522. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  146523. _vq_quantthresh__44u1__p6_1,
  146524. _vq_quantmap__44u1__p6_1,
  146525. 5,
  146526. 5
  146527. };
  146528. static static_codebook _44u1__p6_1 = {
  146529. 2, 25,
  146530. _vq_lengthlist__44u1__p6_1,
  146531. 1, -533725184, 1611661312, 3, 0,
  146532. _vq_quantlist__44u1__p6_1,
  146533. NULL,
  146534. &_vq_auxt__44u1__p6_1,
  146535. NULL,
  146536. 0
  146537. };
  146538. static long _vq_quantlist__44u1__p7_0[] = {
  146539. 3,
  146540. 2,
  146541. 4,
  146542. 1,
  146543. 5,
  146544. 0,
  146545. 6,
  146546. };
  146547. static long _vq_lengthlist__44u1__p7_0[] = {
  146548. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146549. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146550. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146551. 8,
  146552. };
  146553. static float _vq_quantthresh__44u1__p7_0[] = {
  146554. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  146555. };
  146556. static long _vq_quantmap__44u1__p7_0[] = {
  146557. 5, 3, 1, 0, 2, 4, 6,
  146558. };
  146559. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  146560. _vq_quantthresh__44u1__p7_0,
  146561. _vq_quantmap__44u1__p7_0,
  146562. 7,
  146563. 7
  146564. };
  146565. static static_codebook _44u1__p7_0 = {
  146566. 2, 49,
  146567. _vq_lengthlist__44u1__p7_0,
  146568. 1, -518017024, 1626677248, 3, 0,
  146569. _vq_quantlist__44u1__p7_0,
  146570. NULL,
  146571. &_vq_auxt__44u1__p7_0,
  146572. NULL,
  146573. 0
  146574. };
  146575. static long _vq_quantlist__44u1__p7_1[] = {
  146576. 6,
  146577. 5,
  146578. 7,
  146579. 4,
  146580. 8,
  146581. 3,
  146582. 9,
  146583. 2,
  146584. 10,
  146585. 1,
  146586. 11,
  146587. 0,
  146588. 12,
  146589. };
  146590. static long _vq_lengthlist__44u1__p7_1[] = {
  146591. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146592. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146593. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146594. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146595. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146596. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146597. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146598. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146599. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146600. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146601. 15,15,15,15,15,15,15,15,15,
  146602. };
  146603. static float _vq_quantthresh__44u1__p7_1[] = {
  146604. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146605. 32.5, 45.5, 58.5, 71.5,
  146606. };
  146607. static long _vq_quantmap__44u1__p7_1[] = {
  146608. 11, 9, 7, 5, 3, 1, 0, 2,
  146609. 4, 6, 8, 10, 12,
  146610. };
  146611. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  146612. _vq_quantthresh__44u1__p7_1,
  146613. _vq_quantmap__44u1__p7_1,
  146614. 13,
  146615. 13
  146616. };
  146617. static static_codebook _44u1__p7_1 = {
  146618. 2, 169,
  146619. _vq_lengthlist__44u1__p7_1,
  146620. 1, -523010048, 1618608128, 4, 0,
  146621. _vq_quantlist__44u1__p7_1,
  146622. NULL,
  146623. &_vq_auxt__44u1__p7_1,
  146624. NULL,
  146625. 0
  146626. };
  146627. static long _vq_quantlist__44u1__p7_2[] = {
  146628. 6,
  146629. 5,
  146630. 7,
  146631. 4,
  146632. 8,
  146633. 3,
  146634. 9,
  146635. 2,
  146636. 10,
  146637. 1,
  146638. 11,
  146639. 0,
  146640. 12,
  146641. };
  146642. static long _vq_lengthlist__44u1__p7_2[] = {
  146643. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146644. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146645. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146646. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146647. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146648. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146649. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146650. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146651. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146652. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146653. 9, 9, 9,10, 9, 9,10,10, 9,
  146654. };
  146655. static float _vq_quantthresh__44u1__p7_2[] = {
  146656. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146657. 2.5, 3.5, 4.5, 5.5,
  146658. };
  146659. static long _vq_quantmap__44u1__p7_2[] = {
  146660. 11, 9, 7, 5, 3, 1, 0, 2,
  146661. 4, 6, 8, 10, 12,
  146662. };
  146663. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  146664. _vq_quantthresh__44u1__p7_2,
  146665. _vq_quantmap__44u1__p7_2,
  146666. 13,
  146667. 13
  146668. };
  146669. static static_codebook _44u1__p7_2 = {
  146670. 2, 169,
  146671. _vq_lengthlist__44u1__p7_2,
  146672. 1, -531103744, 1611661312, 4, 0,
  146673. _vq_quantlist__44u1__p7_2,
  146674. NULL,
  146675. &_vq_auxt__44u1__p7_2,
  146676. NULL,
  146677. 0
  146678. };
  146679. static long _huff_lengthlist__44u1__short[] = {
  146680. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146681. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146682. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146683. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146684. };
  146685. static static_codebook _huff_book__44u1__short = {
  146686. 2, 64,
  146687. _huff_lengthlist__44u1__short,
  146688. 0, 0, 0, 0, 0,
  146689. NULL,
  146690. NULL,
  146691. NULL,
  146692. NULL,
  146693. 0
  146694. };
  146695. static long _huff_lengthlist__44u2__long[] = {
  146696. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  146697. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  146698. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  146699. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  146700. };
  146701. static static_codebook _huff_book__44u2__long = {
  146702. 2, 64,
  146703. _huff_lengthlist__44u2__long,
  146704. 0, 0, 0, 0, 0,
  146705. NULL,
  146706. NULL,
  146707. NULL,
  146708. NULL,
  146709. 0
  146710. };
  146711. static long _vq_quantlist__44u2__p1_0[] = {
  146712. 1,
  146713. 0,
  146714. 2,
  146715. };
  146716. static long _vq_lengthlist__44u2__p1_0[] = {
  146717. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146718. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146719. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  146720. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  146721. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  146722. 13,
  146723. };
  146724. static float _vq_quantthresh__44u2__p1_0[] = {
  146725. -0.5, 0.5,
  146726. };
  146727. static long _vq_quantmap__44u2__p1_0[] = {
  146728. 1, 0, 2,
  146729. };
  146730. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  146731. _vq_quantthresh__44u2__p1_0,
  146732. _vq_quantmap__44u2__p1_0,
  146733. 3,
  146734. 3
  146735. };
  146736. static static_codebook _44u2__p1_0 = {
  146737. 4, 81,
  146738. _vq_lengthlist__44u2__p1_0,
  146739. 1, -535822336, 1611661312, 2, 0,
  146740. _vq_quantlist__44u2__p1_0,
  146741. NULL,
  146742. &_vq_auxt__44u2__p1_0,
  146743. NULL,
  146744. 0
  146745. };
  146746. static long _vq_quantlist__44u2__p2_0[] = {
  146747. 1,
  146748. 0,
  146749. 2,
  146750. };
  146751. static long _vq_lengthlist__44u2__p2_0[] = {
  146752. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  146753. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  146754. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146755. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  146756. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146757. 9,
  146758. };
  146759. static float _vq_quantthresh__44u2__p2_0[] = {
  146760. -0.5, 0.5,
  146761. };
  146762. static long _vq_quantmap__44u2__p2_0[] = {
  146763. 1, 0, 2,
  146764. };
  146765. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  146766. _vq_quantthresh__44u2__p2_0,
  146767. _vq_quantmap__44u2__p2_0,
  146768. 3,
  146769. 3
  146770. };
  146771. static static_codebook _44u2__p2_0 = {
  146772. 4, 81,
  146773. _vq_lengthlist__44u2__p2_0,
  146774. 1, -535822336, 1611661312, 2, 0,
  146775. _vq_quantlist__44u2__p2_0,
  146776. NULL,
  146777. &_vq_auxt__44u2__p2_0,
  146778. NULL,
  146779. 0
  146780. };
  146781. static long _vq_quantlist__44u2__p3_0[] = {
  146782. 2,
  146783. 1,
  146784. 3,
  146785. 0,
  146786. 4,
  146787. };
  146788. static long _vq_lengthlist__44u2__p3_0[] = {
  146789. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  146790. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  146791. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  146792. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  146793. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  146794. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  146795. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  146796. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  146797. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  146798. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  146799. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  146800. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  146801. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  146802. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  146803. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  146804. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  146805. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  146806. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  146807. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  146808. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  146809. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  146810. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  146811. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  146812. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  146813. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  146814. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  146815. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  146816. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  146817. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  146818. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  146819. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  146820. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  146821. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  146822. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  146823. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  146824. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  146825. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  146826. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  146827. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  146828. 0,
  146829. };
  146830. static float _vq_quantthresh__44u2__p3_0[] = {
  146831. -1.5, -0.5, 0.5, 1.5,
  146832. };
  146833. static long _vq_quantmap__44u2__p3_0[] = {
  146834. 3, 1, 0, 2, 4,
  146835. };
  146836. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  146837. _vq_quantthresh__44u2__p3_0,
  146838. _vq_quantmap__44u2__p3_0,
  146839. 5,
  146840. 5
  146841. };
  146842. static static_codebook _44u2__p3_0 = {
  146843. 4, 625,
  146844. _vq_lengthlist__44u2__p3_0,
  146845. 1, -533725184, 1611661312, 3, 0,
  146846. _vq_quantlist__44u2__p3_0,
  146847. NULL,
  146848. &_vq_auxt__44u2__p3_0,
  146849. NULL,
  146850. 0
  146851. };
  146852. static long _vq_quantlist__44u2__p4_0[] = {
  146853. 2,
  146854. 1,
  146855. 3,
  146856. 0,
  146857. 4,
  146858. };
  146859. static long _vq_lengthlist__44u2__p4_0[] = {
  146860. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  146861. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  146862. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  146863. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  146864. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  146865. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  146866. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  146867. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  146868. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  146869. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  146870. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  146871. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146872. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  146873. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  146874. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  146875. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  146876. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  146877. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  146878. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  146879. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  146880. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  146881. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  146882. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  146883. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  146884. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  146885. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  146886. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  146887. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  146888. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  146889. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  146890. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  146891. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  146892. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  146893. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  146894. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  146895. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  146896. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  146897. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  146898. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  146899. 13,
  146900. };
  146901. static float _vq_quantthresh__44u2__p4_0[] = {
  146902. -1.5, -0.5, 0.5, 1.5,
  146903. };
  146904. static long _vq_quantmap__44u2__p4_0[] = {
  146905. 3, 1, 0, 2, 4,
  146906. };
  146907. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  146908. _vq_quantthresh__44u2__p4_0,
  146909. _vq_quantmap__44u2__p4_0,
  146910. 5,
  146911. 5
  146912. };
  146913. static static_codebook _44u2__p4_0 = {
  146914. 4, 625,
  146915. _vq_lengthlist__44u2__p4_0,
  146916. 1, -533725184, 1611661312, 3, 0,
  146917. _vq_quantlist__44u2__p4_0,
  146918. NULL,
  146919. &_vq_auxt__44u2__p4_0,
  146920. NULL,
  146921. 0
  146922. };
  146923. static long _vq_quantlist__44u2__p5_0[] = {
  146924. 4,
  146925. 3,
  146926. 5,
  146927. 2,
  146928. 6,
  146929. 1,
  146930. 7,
  146931. 0,
  146932. 8,
  146933. };
  146934. static long _vq_lengthlist__44u2__p5_0[] = {
  146935. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  146936. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  146937. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  146938. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  146939. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  146940. 13,
  146941. };
  146942. static float _vq_quantthresh__44u2__p5_0[] = {
  146943. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146944. };
  146945. static long _vq_quantmap__44u2__p5_0[] = {
  146946. 7, 5, 3, 1, 0, 2, 4, 6,
  146947. 8,
  146948. };
  146949. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  146950. _vq_quantthresh__44u2__p5_0,
  146951. _vq_quantmap__44u2__p5_0,
  146952. 9,
  146953. 9
  146954. };
  146955. static static_codebook _44u2__p5_0 = {
  146956. 2, 81,
  146957. _vq_lengthlist__44u2__p5_0,
  146958. 1, -531628032, 1611661312, 4, 0,
  146959. _vq_quantlist__44u2__p5_0,
  146960. NULL,
  146961. &_vq_auxt__44u2__p5_0,
  146962. NULL,
  146963. 0
  146964. };
  146965. static long _vq_quantlist__44u2__p6_0[] = {
  146966. 6,
  146967. 5,
  146968. 7,
  146969. 4,
  146970. 8,
  146971. 3,
  146972. 9,
  146973. 2,
  146974. 10,
  146975. 1,
  146976. 11,
  146977. 0,
  146978. 12,
  146979. };
  146980. static long _vq_lengthlist__44u2__p6_0[] = {
  146981. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  146982. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  146983. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  146984. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  146985. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  146986. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  146987. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  146988. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  146989. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  146990. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  146991. 15,17,17,16,18,17,18, 0, 0,
  146992. };
  146993. static float _vq_quantthresh__44u2__p6_0[] = {
  146994. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146995. 12.5, 17.5, 22.5, 27.5,
  146996. };
  146997. static long _vq_quantmap__44u2__p6_0[] = {
  146998. 11, 9, 7, 5, 3, 1, 0, 2,
  146999. 4, 6, 8, 10, 12,
  147000. };
  147001. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147002. _vq_quantthresh__44u2__p6_0,
  147003. _vq_quantmap__44u2__p6_0,
  147004. 13,
  147005. 13
  147006. };
  147007. static static_codebook _44u2__p6_0 = {
  147008. 2, 169,
  147009. _vq_lengthlist__44u2__p6_0,
  147010. 1, -526516224, 1616117760, 4, 0,
  147011. _vq_quantlist__44u2__p6_0,
  147012. NULL,
  147013. &_vq_auxt__44u2__p6_0,
  147014. NULL,
  147015. 0
  147016. };
  147017. static long _vq_quantlist__44u2__p6_1[] = {
  147018. 2,
  147019. 1,
  147020. 3,
  147021. 0,
  147022. 4,
  147023. };
  147024. static long _vq_lengthlist__44u2__p6_1[] = {
  147025. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147026. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147027. };
  147028. static float _vq_quantthresh__44u2__p6_1[] = {
  147029. -1.5, -0.5, 0.5, 1.5,
  147030. };
  147031. static long _vq_quantmap__44u2__p6_1[] = {
  147032. 3, 1, 0, 2, 4,
  147033. };
  147034. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147035. _vq_quantthresh__44u2__p6_1,
  147036. _vq_quantmap__44u2__p6_1,
  147037. 5,
  147038. 5
  147039. };
  147040. static static_codebook _44u2__p6_1 = {
  147041. 2, 25,
  147042. _vq_lengthlist__44u2__p6_1,
  147043. 1, -533725184, 1611661312, 3, 0,
  147044. _vq_quantlist__44u2__p6_1,
  147045. NULL,
  147046. &_vq_auxt__44u2__p6_1,
  147047. NULL,
  147048. 0
  147049. };
  147050. static long _vq_quantlist__44u2__p7_0[] = {
  147051. 4,
  147052. 3,
  147053. 5,
  147054. 2,
  147055. 6,
  147056. 1,
  147057. 7,
  147058. 0,
  147059. 8,
  147060. };
  147061. static long _vq_lengthlist__44u2__p7_0[] = {
  147062. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147063. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147064. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147065. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147066. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147067. 11,
  147068. };
  147069. static float _vq_quantthresh__44u2__p7_0[] = {
  147070. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147071. };
  147072. static long _vq_quantmap__44u2__p7_0[] = {
  147073. 7, 5, 3, 1, 0, 2, 4, 6,
  147074. 8,
  147075. };
  147076. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147077. _vq_quantthresh__44u2__p7_0,
  147078. _vq_quantmap__44u2__p7_0,
  147079. 9,
  147080. 9
  147081. };
  147082. static static_codebook _44u2__p7_0 = {
  147083. 2, 81,
  147084. _vq_lengthlist__44u2__p7_0,
  147085. 1, -516612096, 1626677248, 4, 0,
  147086. _vq_quantlist__44u2__p7_0,
  147087. NULL,
  147088. &_vq_auxt__44u2__p7_0,
  147089. NULL,
  147090. 0
  147091. };
  147092. static long _vq_quantlist__44u2__p7_1[] = {
  147093. 6,
  147094. 5,
  147095. 7,
  147096. 4,
  147097. 8,
  147098. 3,
  147099. 9,
  147100. 2,
  147101. 10,
  147102. 1,
  147103. 11,
  147104. 0,
  147105. 12,
  147106. };
  147107. static long _vq_lengthlist__44u2__p7_1[] = {
  147108. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147109. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147110. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147111. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147112. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147113. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147114. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147115. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147116. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147117. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147118. 14,14,14,17,15,17,17,17,17,
  147119. };
  147120. static float _vq_quantthresh__44u2__p7_1[] = {
  147121. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147122. 32.5, 45.5, 58.5, 71.5,
  147123. };
  147124. static long _vq_quantmap__44u2__p7_1[] = {
  147125. 11, 9, 7, 5, 3, 1, 0, 2,
  147126. 4, 6, 8, 10, 12,
  147127. };
  147128. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147129. _vq_quantthresh__44u2__p7_1,
  147130. _vq_quantmap__44u2__p7_1,
  147131. 13,
  147132. 13
  147133. };
  147134. static static_codebook _44u2__p7_1 = {
  147135. 2, 169,
  147136. _vq_lengthlist__44u2__p7_1,
  147137. 1, -523010048, 1618608128, 4, 0,
  147138. _vq_quantlist__44u2__p7_1,
  147139. NULL,
  147140. &_vq_auxt__44u2__p7_1,
  147141. NULL,
  147142. 0
  147143. };
  147144. static long _vq_quantlist__44u2__p7_2[] = {
  147145. 6,
  147146. 5,
  147147. 7,
  147148. 4,
  147149. 8,
  147150. 3,
  147151. 9,
  147152. 2,
  147153. 10,
  147154. 1,
  147155. 11,
  147156. 0,
  147157. 12,
  147158. };
  147159. static long _vq_lengthlist__44u2__p7_2[] = {
  147160. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147161. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147162. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147163. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147164. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147165. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147166. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147167. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147168. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147169. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147170. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147171. };
  147172. static float _vq_quantthresh__44u2__p7_2[] = {
  147173. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147174. 2.5, 3.5, 4.5, 5.5,
  147175. };
  147176. static long _vq_quantmap__44u2__p7_2[] = {
  147177. 11, 9, 7, 5, 3, 1, 0, 2,
  147178. 4, 6, 8, 10, 12,
  147179. };
  147180. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147181. _vq_quantthresh__44u2__p7_2,
  147182. _vq_quantmap__44u2__p7_2,
  147183. 13,
  147184. 13
  147185. };
  147186. static static_codebook _44u2__p7_2 = {
  147187. 2, 169,
  147188. _vq_lengthlist__44u2__p7_2,
  147189. 1, -531103744, 1611661312, 4, 0,
  147190. _vq_quantlist__44u2__p7_2,
  147191. NULL,
  147192. &_vq_auxt__44u2__p7_2,
  147193. NULL,
  147194. 0
  147195. };
  147196. static long _huff_lengthlist__44u2__short[] = {
  147197. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147198. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147199. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147200. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147201. };
  147202. static static_codebook _huff_book__44u2__short = {
  147203. 2, 64,
  147204. _huff_lengthlist__44u2__short,
  147205. 0, 0, 0, 0, 0,
  147206. NULL,
  147207. NULL,
  147208. NULL,
  147209. NULL,
  147210. 0
  147211. };
  147212. static long _huff_lengthlist__44u3__long[] = {
  147213. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147214. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147215. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147216. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147217. };
  147218. static static_codebook _huff_book__44u3__long = {
  147219. 2, 64,
  147220. _huff_lengthlist__44u3__long,
  147221. 0, 0, 0, 0, 0,
  147222. NULL,
  147223. NULL,
  147224. NULL,
  147225. NULL,
  147226. 0
  147227. };
  147228. static long _vq_quantlist__44u3__p1_0[] = {
  147229. 1,
  147230. 0,
  147231. 2,
  147232. };
  147233. static long _vq_lengthlist__44u3__p1_0[] = {
  147234. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147235. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147236. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147237. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147238. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147239. 13,
  147240. };
  147241. static float _vq_quantthresh__44u3__p1_0[] = {
  147242. -0.5, 0.5,
  147243. };
  147244. static long _vq_quantmap__44u3__p1_0[] = {
  147245. 1, 0, 2,
  147246. };
  147247. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147248. _vq_quantthresh__44u3__p1_0,
  147249. _vq_quantmap__44u3__p1_0,
  147250. 3,
  147251. 3
  147252. };
  147253. static static_codebook _44u3__p1_0 = {
  147254. 4, 81,
  147255. _vq_lengthlist__44u3__p1_0,
  147256. 1, -535822336, 1611661312, 2, 0,
  147257. _vq_quantlist__44u3__p1_0,
  147258. NULL,
  147259. &_vq_auxt__44u3__p1_0,
  147260. NULL,
  147261. 0
  147262. };
  147263. static long _vq_quantlist__44u3__p2_0[] = {
  147264. 1,
  147265. 0,
  147266. 2,
  147267. };
  147268. static long _vq_lengthlist__44u3__p2_0[] = {
  147269. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147270. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  147271. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147272. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147273. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  147274. 9,
  147275. };
  147276. static float _vq_quantthresh__44u3__p2_0[] = {
  147277. -0.5, 0.5,
  147278. };
  147279. static long _vq_quantmap__44u3__p2_0[] = {
  147280. 1, 0, 2,
  147281. };
  147282. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  147283. _vq_quantthresh__44u3__p2_0,
  147284. _vq_quantmap__44u3__p2_0,
  147285. 3,
  147286. 3
  147287. };
  147288. static static_codebook _44u3__p2_0 = {
  147289. 4, 81,
  147290. _vq_lengthlist__44u3__p2_0,
  147291. 1, -535822336, 1611661312, 2, 0,
  147292. _vq_quantlist__44u3__p2_0,
  147293. NULL,
  147294. &_vq_auxt__44u3__p2_0,
  147295. NULL,
  147296. 0
  147297. };
  147298. static long _vq_quantlist__44u3__p3_0[] = {
  147299. 2,
  147300. 1,
  147301. 3,
  147302. 0,
  147303. 4,
  147304. };
  147305. static long _vq_lengthlist__44u3__p3_0[] = {
  147306. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147307. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147308. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147309. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147310. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147311. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147312. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147313. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147314. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147315. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147316. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147317. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147318. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147319. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147320. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147321. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147322. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147323. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147324. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147325. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147326. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147327. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147328. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147329. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147330. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147331. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147332. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147333. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147334. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147335. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147336. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147337. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147338. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147339. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147340. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147341. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147342. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147343. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147344. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147345. 0,
  147346. };
  147347. static float _vq_quantthresh__44u3__p3_0[] = {
  147348. -1.5, -0.5, 0.5, 1.5,
  147349. };
  147350. static long _vq_quantmap__44u3__p3_0[] = {
  147351. 3, 1, 0, 2, 4,
  147352. };
  147353. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147354. _vq_quantthresh__44u3__p3_0,
  147355. _vq_quantmap__44u3__p3_0,
  147356. 5,
  147357. 5
  147358. };
  147359. static static_codebook _44u3__p3_0 = {
  147360. 4, 625,
  147361. _vq_lengthlist__44u3__p3_0,
  147362. 1, -533725184, 1611661312, 3, 0,
  147363. _vq_quantlist__44u3__p3_0,
  147364. NULL,
  147365. &_vq_auxt__44u3__p3_0,
  147366. NULL,
  147367. 0
  147368. };
  147369. static long _vq_quantlist__44u3__p4_0[] = {
  147370. 2,
  147371. 1,
  147372. 3,
  147373. 0,
  147374. 4,
  147375. };
  147376. static long _vq_lengthlist__44u3__p4_0[] = {
  147377. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147378. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147379. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147380. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147381. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147382. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147383. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  147384. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  147385. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147386. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147387. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147388. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147389. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147390. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  147391. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147392. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147393. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147394. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147395. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147396. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147397. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147398. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147399. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147400. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147401. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  147402. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  147403. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  147404. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  147405. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147406. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  147407. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  147408. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147409. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147410. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147411. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  147412. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  147413. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  147414. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  147415. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  147416. 13,
  147417. };
  147418. static float _vq_quantthresh__44u3__p4_0[] = {
  147419. -1.5, -0.5, 0.5, 1.5,
  147420. };
  147421. static long _vq_quantmap__44u3__p4_0[] = {
  147422. 3, 1, 0, 2, 4,
  147423. };
  147424. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  147425. _vq_quantthresh__44u3__p4_0,
  147426. _vq_quantmap__44u3__p4_0,
  147427. 5,
  147428. 5
  147429. };
  147430. static static_codebook _44u3__p4_0 = {
  147431. 4, 625,
  147432. _vq_lengthlist__44u3__p4_0,
  147433. 1, -533725184, 1611661312, 3, 0,
  147434. _vq_quantlist__44u3__p4_0,
  147435. NULL,
  147436. &_vq_auxt__44u3__p4_0,
  147437. NULL,
  147438. 0
  147439. };
  147440. static long _vq_quantlist__44u3__p5_0[] = {
  147441. 4,
  147442. 3,
  147443. 5,
  147444. 2,
  147445. 6,
  147446. 1,
  147447. 7,
  147448. 0,
  147449. 8,
  147450. };
  147451. static long _vq_lengthlist__44u3__p5_0[] = {
  147452. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147453. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147454. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  147455. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147456. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  147457. 12,
  147458. };
  147459. static float _vq_quantthresh__44u3__p5_0[] = {
  147460. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147461. };
  147462. static long _vq_quantmap__44u3__p5_0[] = {
  147463. 7, 5, 3, 1, 0, 2, 4, 6,
  147464. 8,
  147465. };
  147466. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  147467. _vq_quantthresh__44u3__p5_0,
  147468. _vq_quantmap__44u3__p5_0,
  147469. 9,
  147470. 9
  147471. };
  147472. static static_codebook _44u3__p5_0 = {
  147473. 2, 81,
  147474. _vq_lengthlist__44u3__p5_0,
  147475. 1, -531628032, 1611661312, 4, 0,
  147476. _vq_quantlist__44u3__p5_0,
  147477. NULL,
  147478. &_vq_auxt__44u3__p5_0,
  147479. NULL,
  147480. 0
  147481. };
  147482. static long _vq_quantlist__44u3__p6_0[] = {
  147483. 6,
  147484. 5,
  147485. 7,
  147486. 4,
  147487. 8,
  147488. 3,
  147489. 9,
  147490. 2,
  147491. 10,
  147492. 1,
  147493. 11,
  147494. 0,
  147495. 12,
  147496. };
  147497. static long _vq_lengthlist__44u3__p6_0[] = {
  147498. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  147499. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  147500. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147501. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  147502. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  147503. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  147504. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  147505. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  147506. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  147507. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  147508. 15,16,16,16,17,18,16,20,18,
  147509. };
  147510. static float _vq_quantthresh__44u3__p6_0[] = {
  147511. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147512. 12.5, 17.5, 22.5, 27.5,
  147513. };
  147514. static long _vq_quantmap__44u3__p6_0[] = {
  147515. 11, 9, 7, 5, 3, 1, 0, 2,
  147516. 4, 6, 8, 10, 12,
  147517. };
  147518. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  147519. _vq_quantthresh__44u3__p6_0,
  147520. _vq_quantmap__44u3__p6_0,
  147521. 13,
  147522. 13
  147523. };
  147524. static static_codebook _44u3__p6_0 = {
  147525. 2, 169,
  147526. _vq_lengthlist__44u3__p6_0,
  147527. 1, -526516224, 1616117760, 4, 0,
  147528. _vq_quantlist__44u3__p6_0,
  147529. NULL,
  147530. &_vq_auxt__44u3__p6_0,
  147531. NULL,
  147532. 0
  147533. };
  147534. static long _vq_quantlist__44u3__p6_1[] = {
  147535. 2,
  147536. 1,
  147537. 3,
  147538. 0,
  147539. 4,
  147540. };
  147541. static long _vq_lengthlist__44u3__p6_1[] = {
  147542. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147543. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147544. };
  147545. static float _vq_quantthresh__44u3__p6_1[] = {
  147546. -1.5, -0.5, 0.5, 1.5,
  147547. };
  147548. static long _vq_quantmap__44u3__p6_1[] = {
  147549. 3, 1, 0, 2, 4,
  147550. };
  147551. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  147552. _vq_quantthresh__44u3__p6_1,
  147553. _vq_quantmap__44u3__p6_1,
  147554. 5,
  147555. 5
  147556. };
  147557. static static_codebook _44u3__p6_1 = {
  147558. 2, 25,
  147559. _vq_lengthlist__44u3__p6_1,
  147560. 1, -533725184, 1611661312, 3, 0,
  147561. _vq_quantlist__44u3__p6_1,
  147562. NULL,
  147563. &_vq_auxt__44u3__p6_1,
  147564. NULL,
  147565. 0
  147566. };
  147567. static long _vq_quantlist__44u3__p7_0[] = {
  147568. 4,
  147569. 3,
  147570. 5,
  147571. 2,
  147572. 6,
  147573. 1,
  147574. 7,
  147575. 0,
  147576. 8,
  147577. };
  147578. static long _vq_lengthlist__44u3__p7_0[] = {
  147579. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  147580. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147581. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147582. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147583. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147584. 9,
  147585. };
  147586. static float _vq_quantthresh__44u3__p7_0[] = {
  147587. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  147588. };
  147589. static long _vq_quantmap__44u3__p7_0[] = {
  147590. 7, 5, 3, 1, 0, 2, 4, 6,
  147591. 8,
  147592. };
  147593. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  147594. _vq_quantthresh__44u3__p7_0,
  147595. _vq_quantmap__44u3__p7_0,
  147596. 9,
  147597. 9
  147598. };
  147599. static static_codebook _44u3__p7_0 = {
  147600. 2, 81,
  147601. _vq_lengthlist__44u3__p7_0,
  147602. 1, -515907584, 1627381760, 4, 0,
  147603. _vq_quantlist__44u3__p7_0,
  147604. NULL,
  147605. &_vq_auxt__44u3__p7_0,
  147606. NULL,
  147607. 0
  147608. };
  147609. static long _vq_quantlist__44u3__p7_1[] = {
  147610. 7,
  147611. 6,
  147612. 8,
  147613. 5,
  147614. 9,
  147615. 4,
  147616. 10,
  147617. 3,
  147618. 11,
  147619. 2,
  147620. 12,
  147621. 1,
  147622. 13,
  147623. 0,
  147624. 14,
  147625. };
  147626. static long _vq_lengthlist__44u3__p7_1[] = {
  147627. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  147628. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  147629. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  147630. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  147631. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  147632. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  147633. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  147634. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  147635. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  147636. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  147637. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  147638. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  147639. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  147640. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  147641. 17,
  147642. };
  147643. static float _vq_quantthresh__44u3__p7_1[] = {
  147644. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  147645. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  147646. };
  147647. static long _vq_quantmap__44u3__p7_1[] = {
  147648. 13, 11, 9, 7, 5, 3, 1, 0,
  147649. 2, 4, 6, 8, 10, 12, 14,
  147650. };
  147651. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  147652. _vq_quantthresh__44u3__p7_1,
  147653. _vq_quantmap__44u3__p7_1,
  147654. 15,
  147655. 15
  147656. };
  147657. static static_codebook _44u3__p7_1 = {
  147658. 2, 225,
  147659. _vq_lengthlist__44u3__p7_1,
  147660. 1, -522338304, 1620115456, 4, 0,
  147661. _vq_quantlist__44u3__p7_1,
  147662. NULL,
  147663. &_vq_auxt__44u3__p7_1,
  147664. NULL,
  147665. 0
  147666. };
  147667. static long _vq_quantlist__44u3__p7_2[] = {
  147668. 8,
  147669. 7,
  147670. 9,
  147671. 6,
  147672. 10,
  147673. 5,
  147674. 11,
  147675. 4,
  147676. 12,
  147677. 3,
  147678. 13,
  147679. 2,
  147680. 14,
  147681. 1,
  147682. 15,
  147683. 0,
  147684. 16,
  147685. };
  147686. static long _vq_lengthlist__44u3__p7_2[] = {
  147687. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147688. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147689. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  147690. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147691. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  147692. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147693. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  147694. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147695. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  147696. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  147697. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  147698. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  147699. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  147700. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147701. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  147702. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  147703. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147704. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  147705. 11,
  147706. };
  147707. static float _vq_quantthresh__44u3__p7_2[] = {
  147708. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147709. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147710. };
  147711. static long _vq_quantmap__44u3__p7_2[] = {
  147712. 15, 13, 11, 9, 7, 5, 3, 1,
  147713. 0, 2, 4, 6, 8, 10, 12, 14,
  147714. 16,
  147715. };
  147716. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  147717. _vq_quantthresh__44u3__p7_2,
  147718. _vq_quantmap__44u3__p7_2,
  147719. 17,
  147720. 17
  147721. };
  147722. static static_codebook _44u3__p7_2 = {
  147723. 2, 289,
  147724. _vq_lengthlist__44u3__p7_2,
  147725. 1, -529530880, 1611661312, 5, 0,
  147726. _vq_quantlist__44u3__p7_2,
  147727. NULL,
  147728. &_vq_auxt__44u3__p7_2,
  147729. NULL,
  147730. 0
  147731. };
  147732. static long _huff_lengthlist__44u3__short[] = {
  147733. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  147734. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  147735. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  147736. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  147737. };
  147738. static static_codebook _huff_book__44u3__short = {
  147739. 2, 64,
  147740. _huff_lengthlist__44u3__short,
  147741. 0, 0, 0, 0, 0,
  147742. NULL,
  147743. NULL,
  147744. NULL,
  147745. NULL,
  147746. 0
  147747. };
  147748. static long _huff_lengthlist__44u4__long[] = {
  147749. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  147750. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  147751. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  147752. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  147753. };
  147754. static static_codebook _huff_book__44u4__long = {
  147755. 2, 64,
  147756. _huff_lengthlist__44u4__long,
  147757. 0, 0, 0, 0, 0,
  147758. NULL,
  147759. NULL,
  147760. NULL,
  147761. NULL,
  147762. 0
  147763. };
  147764. static long _vq_quantlist__44u4__p1_0[] = {
  147765. 1,
  147766. 0,
  147767. 2,
  147768. };
  147769. static long _vq_lengthlist__44u4__p1_0[] = {
  147770. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147771. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147772. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  147773. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147774. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  147775. 13,
  147776. };
  147777. static float _vq_quantthresh__44u4__p1_0[] = {
  147778. -0.5, 0.5,
  147779. };
  147780. static long _vq_quantmap__44u4__p1_0[] = {
  147781. 1, 0, 2,
  147782. };
  147783. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  147784. _vq_quantthresh__44u4__p1_0,
  147785. _vq_quantmap__44u4__p1_0,
  147786. 3,
  147787. 3
  147788. };
  147789. static static_codebook _44u4__p1_0 = {
  147790. 4, 81,
  147791. _vq_lengthlist__44u4__p1_0,
  147792. 1, -535822336, 1611661312, 2, 0,
  147793. _vq_quantlist__44u4__p1_0,
  147794. NULL,
  147795. &_vq_auxt__44u4__p1_0,
  147796. NULL,
  147797. 0
  147798. };
  147799. static long _vq_quantlist__44u4__p2_0[] = {
  147800. 1,
  147801. 0,
  147802. 2,
  147803. };
  147804. static long _vq_lengthlist__44u4__p2_0[] = {
  147805. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147806. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  147807. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147808. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  147809. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147810. 9,
  147811. };
  147812. static float _vq_quantthresh__44u4__p2_0[] = {
  147813. -0.5, 0.5,
  147814. };
  147815. static long _vq_quantmap__44u4__p2_0[] = {
  147816. 1, 0, 2,
  147817. };
  147818. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  147819. _vq_quantthresh__44u4__p2_0,
  147820. _vq_quantmap__44u4__p2_0,
  147821. 3,
  147822. 3
  147823. };
  147824. static static_codebook _44u4__p2_0 = {
  147825. 4, 81,
  147826. _vq_lengthlist__44u4__p2_0,
  147827. 1, -535822336, 1611661312, 2, 0,
  147828. _vq_quantlist__44u4__p2_0,
  147829. NULL,
  147830. &_vq_auxt__44u4__p2_0,
  147831. NULL,
  147832. 0
  147833. };
  147834. static long _vq_quantlist__44u4__p3_0[] = {
  147835. 2,
  147836. 1,
  147837. 3,
  147838. 0,
  147839. 4,
  147840. };
  147841. static long _vq_lengthlist__44u4__p3_0[] = {
  147842. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147843. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  147844. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  147845. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  147846. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  147847. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  147848. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  147849. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  147850. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  147851. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  147852. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  147853. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  147854. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  147855. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  147856. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  147857. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  147858. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  147859. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  147860. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  147861. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  147862. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  147863. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  147864. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  147865. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  147866. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  147867. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  147868. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  147869. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  147870. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  147871. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  147872. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  147873. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  147874. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  147875. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  147876. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  147877. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  147878. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  147879. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  147880. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  147881. 0,
  147882. };
  147883. static float _vq_quantthresh__44u4__p3_0[] = {
  147884. -1.5, -0.5, 0.5, 1.5,
  147885. };
  147886. static long _vq_quantmap__44u4__p3_0[] = {
  147887. 3, 1, 0, 2, 4,
  147888. };
  147889. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  147890. _vq_quantthresh__44u4__p3_0,
  147891. _vq_quantmap__44u4__p3_0,
  147892. 5,
  147893. 5
  147894. };
  147895. static static_codebook _44u4__p3_0 = {
  147896. 4, 625,
  147897. _vq_lengthlist__44u4__p3_0,
  147898. 1, -533725184, 1611661312, 3, 0,
  147899. _vq_quantlist__44u4__p3_0,
  147900. NULL,
  147901. &_vq_auxt__44u4__p3_0,
  147902. NULL,
  147903. 0
  147904. };
  147905. static long _vq_quantlist__44u4__p4_0[] = {
  147906. 2,
  147907. 1,
  147908. 3,
  147909. 0,
  147910. 4,
  147911. };
  147912. static long _vq_lengthlist__44u4__p4_0[] = {
  147913. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147914. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147915. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147916. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147917. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147918. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  147919. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  147920. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  147921. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147922. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147923. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147924. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147925. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147926. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  147927. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147928. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147929. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147930. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147931. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147932. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147933. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147934. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147935. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147936. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147937. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147938. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  147939. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  147940. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  147941. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  147942. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  147943. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  147944. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147945. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147946. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  147947. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147948. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  147949. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147950. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  147951. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  147952. 13,
  147953. };
  147954. static float _vq_quantthresh__44u4__p4_0[] = {
  147955. -1.5, -0.5, 0.5, 1.5,
  147956. };
  147957. static long _vq_quantmap__44u4__p4_0[] = {
  147958. 3, 1, 0, 2, 4,
  147959. };
  147960. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  147961. _vq_quantthresh__44u4__p4_0,
  147962. _vq_quantmap__44u4__p4_0,
  147963. 5,
  147964. 5
  147965. };
  147966. static static_codebook _44u4__p4_0 = {
  147967. 4, 625,
  147968. _vq_lengthlist__44u4__p4_0,
  147969. 1, -533725184, 1611661312, 3, 0,
  147970. _vq_quantlist__44u4__p4_0,
  147971. NULL,
  147972. &_vq_auxt__44u4__p4_0,
  147973. NULL,
  147974. 0
  147975. };
  147976. static long _vq_quantlist__44u4__p5_0[] = {
  147977. 4,
  147978. 3,
  147979. 5,
  147980. 2,
  147981. 6,
  147982. 1,
  147983. 7,
  147984. 0,
  147985. 8,
  147986. };
  147987. static long _vq_lengthlist__44u4__p5_0[] = {
  147988. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147989. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147990. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  147991. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147992. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  147993. 12,
  147994. };
  147995. static float _vq_quantthresh__44u4__p5_0[] = {
  147996. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147997. };
  147998. static long _vq_quantmap__44u4__p5_0[] = {
  147999. 7, 5, 3, 1, 0, 2, 4, 6,
  148000. 8,
  148001. };
  148002. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148003. _vq_quantthresh__44u4__p5_0,
  148004. _vq_quantmap__44u4__p5_0,
  148005. 9,
  148006. 9
  148007. };
  148008. static static_codebook _44u4__p5_0 = {
  148009. 2, 81,
  148010. _vq_lengthlist__44u4__p5_0,
  148011. 1, -531628032, 1611661312, 4, 0,
  148012. _vq_quantlist__44u4__p5_0,
  148013. NULL,
  148014. &_vq_auxt__44u4__p5_0,
  148015. NULL,
  148016. 0
  148017. };
  148018. static long _vq_quantlist__44u4__p6_0[] = {
  148019. 6,
  148020. 5,
  148021. 7,
  148022. 4,
  148023. 8,
  148024. 3,
  148025. 9,
  148026. 2,
  148027. 10,
  148028. 1,
  148029. 11,
  148030. 0,
  148031. 12,
  148032. };
  148033. static long _vq_lengthlist__44u4__p6_0[] = {
  148034. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148035. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148036. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148037. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148038. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148039. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148040. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148041. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148042. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148043. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148044. 16,16,16,17,17,18,17,20,21,
  148045. };
  148046. static float _vq_quantthresh__44u4__p6_0[] = {
  148047. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148048. 12.5, 17.5, 22.5, 27.5,
  148049. };
  148050. static long _vq_quantmap__44u4__p6_0[] = {
  148051. 11, 9, 7, 5, 3, 1, 0, 2,
  148052. 4, 6, 8, 10, 12,
  148053. };
  148054. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148055. _vq_quantthresh__44u4__p6_0,
  148056. _vq_quantmap__44u4__p6_0,
  148057. 13,
  148058. 13
  148059. };
  148060. static static_codebook _44u4__p6_0 = {
  148061. 2, 169,
  148062. _vq_lengthlist__44u4__p6_0,
  148063. 1, -526516224, 1616117760, 4, 0,
  148064. _vq_quantlist__44u4__p6_0,
  148065. NULL,
  148066. &_vq_auxt__44u4__p6_0,
  148067. NULL,
  148068. 0
  148069. };
  148070. static long _vq_quantlist__44u4__p6_1[] = {
  148071. 2,
  148072. 1,
  148073. 3,
  148074. 0,
  148075. 4,
  148076. };
  148077. static long _vq_lengthlist__44u4__p6_1[] = {
  148078. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148079. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148080. };
  148081. static float _vq_quantthresh__44u4__p6_1[] = {
  148082. -1.5, -0.5, 0.5, 1.5,
  148083. };
  148084. static long _vq_quantmap__44u4__p6_1[] = {
  148085. 3, 1, 0, 2, 4,
  148086. };
  148087. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148088. _vq_quantthresh__44u4__p6_1,
  148089. _vq_quantmap__44u4__p6_1,
  148090. 5,
  148091. 5
  148092. };
  148093. static static_codebook _44u4__p6_1 = {
  148094. 2, 25,
  148095. _vq_lengthlist__44u4__p6_1,
  148096. 1, -533725184, 1611661312, 3, 0,
  148097. _vq_quantlist__44u4__p6_1,
  148098. NULL,
  148099. &_vq_auxt__44u4__p6_1,
  148100. NULL,
  148101. 0
  148102. };
  148103. static long _vq_quantlist__44u4__p7_0[] = {
  148104. 6,
  148105. 5,
  148106. 7,
  148107. 4,
  148108. 8,
  148109. 3,
  148110. 9,
  148111. 2,
  148112. 10,
  148113. 1,
  148114. 11,
  148115. 0,
  148116. 12,
  148117. };
  148118. static long _vq_lengthlist__44u4__p7_0[] = {
  148119. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148120. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148121. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148122. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148123. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148124. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148125. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148126. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148127. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148128. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148129. 11,11,11,11,11,11,11,11,11,
  148130. };
  148131. static float _vq_quantthresh__44u4__p7_0[] = {
  148132. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148133. 637.5, 892.5, 1147.5, 1402.5,
  148134. };
  148135. static long _vq_quantmap__44u4__p7_0[] = {
  148136. 11, 9, 7, 5, 3, 1, 0, 2,
  148137. 4, 6, 8, 10, 12,
  148138. };
  148139. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148140. _vq_quantthresh__44u4__p7_0,
  148141. _vq_quantmap__44u4__p7_0,
  148142. 13,
  148143. 13
  148144. };
  148145. static static_codebook _44u4__p7_0 = {
  148146. 2, 169,
  148147. _vq_lengthlist__44u4__p7_0,
  148148. 1, -514332672, 1627381760, 4, 0,
  148149. _vq_quantlist__44u4__p7_0,
  148150. NULL,
  148151. &_vq_auxt__44u4__p7_0,
  148152. NULL,
  148153. 0
  148154. };
  148155. static long _vq_quantlist__44u4__p7_1[] = {
  148156. 7,
  148157. 6,
  148158. 8,
  148159. 5,
  148160. 9,
  148161. 4,
  148162. 10,
  148163. 3,
  148164. 11,
  148165. 2,
  148166. 12,
  148167. 1,
  148168. 13,
  148169. 0,
  148170. 14,
  148171. };
  148172. static long _vq_lengthlist__44u4__p7_1[] = {
  148173. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148174. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148175. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148176. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148177. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148178. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148179. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148180. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148181. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148182. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148183. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148184. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148185. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148186. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148187. 16,
  148188. };
  148189. static float _vq_quantthresh__44u4__p7_1[] = {
  148190. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148191. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148192. };
  148193. static long _vq_quantmap__44u4__p7_1[] = {
  148194. 13, 11, 9, 7, 5, 3, 1, 0,
  148195. 2, 4, 6, 8, 10, 12, 14,
  148196. };
  148197. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148198. _vq_quantthresh__44u4__p7_1,
  148199. _vq_quantmap__44u4__p7_1,
  148200. 15,
  148201. 15
  148202. };
  148203. static static_codebook _44u4__p7_1 = {
  148204. 2, 225,
  148205. _vq_lengthlist__44u4__p7_1,
  148206. 1, -522338304, 1620115456, 4, 0,
  148207. _vq_quantlist__44u4__p7_1,
  148208. NULL,
  148209. &_vq_auxt__44u4__p7_1,
  148210. NULL,
  148211. 0
  148212. };
  148213. static long _vq_quantlist__44u4__p7_2[] = {
  148214. 8,
  148215. 7,
  148216. 9,
  148217. 6,
  148218. 10,
  148219. 5,
  148220. 11,
  148221. 4,
  148222. 12,
  148223. 3,
  148224. 13,
  148225. 2,
  148226. 14,
  148227. 1,
  148228. 15,
  148229. 0,
  148230. 16,
  148231. };
  148232. static long _vq_lengthlist__44u4__p7_2[] = {
  148233. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148234. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148235. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148236. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148237. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148238. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148239. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148240. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148241. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148242. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148243. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148244. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148245. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148246. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148247. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148248. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148249. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148250. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148251. 10,
  148252. };
  148253. static float _vq_quantthresh__44u4__p7_2[] = {
  148254. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148255. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148256. };
  148257. static long _vq_quantmap__44u4__p7_2[] = {
  148258. 15, 13, 11, 9, 7, 5, 3, 1,
  148259. 0, 2, 4, 6, 8, 10, 12, 14,
  148260. 16,
  148261. };
  148262. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  148263. _vq_quantthresh__44u4__p7_2,
  148264. _vq_quantmap__44u4__p7_2,
  148265. 17,
  148266. 17
  148267. };
  148268. static static_codebook _44u4__p7_2 = {
  148269. 2, 289,
  148270. _vq_lengthlist__44u4__p7_2,
  148271. 1, -529530880, 1611661312, 5, 0,
  148272. _vq_quantlist__44u4__p7_2,
  148273. NULL,
  148274. &_vq_auxt__44u4__p7_2,
  148275. NULL,
  148276. 0
  148277. };
  148278. static long _huff_lengthlist__44u4__short[] = {
  148279. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  148280. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  148281. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  148282. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  148283. };
  148284. static static_codebook _huff_book__44u4__short = {
  148285. 2, 64,
  148286. _huff_lengthlist__44u4__short,
  148287. 0, 0, 0, 0, 0,
  148288. NULL,
  148289. NULL,
  148290. NULL,
  148291. NULL,
  148292. 0
  148293. };
  148294. static long _huff_lengthlist__44u5__long[] = {
  148295. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  148296. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  148297. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  148298. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  148299. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  148300. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  148301. 14, 8, 7, 8,
  148302. };
  148303. static static_codebook _huff_book__44u5__long = {
  148304. 2, 100,
  148305. _huff_lengthlist__44u5__long,
  148306. 0, 0, 0, 0, 0,
  148307. NULL,
  148308. NULL,
  148309. NULL,
  148310. NULL,
  148311. 0
  148312. };
  148313. static long _vq_quantlist__44u5__p1_0[] = {
  148314. 1,
  148315. 0,
  148316. 2,
  148317. };
  148318. static long _vq_lengthlist__44u5__p1_0[] = {
  148319. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148320. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148321. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148322. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148323. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148324. 12,
  148325. };
  148326. static float _vq_quantthresh__44u5__p1_0[] = {
  148327. -0.5, 0.5,
  148328. };
  148329. static long _vq_quantmap__44u5__p1_0[] = {
  148330. 1, 0, 2,
  148331. };
  148332. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148333. _vq_quantthresh__44u5__p1_0,
  148334. _vq_quantmap__44u5__p1_0,
  148335. 3,
  148336. 3
  148337. };
  148338. static static_codebook _44u5__p1_0 = {
  148339. 4, 81,
  148340. _vq_lengthlist__44u5__p1_0,
  148341. 1, -535822336, 1611661312, 2, 0,
  148342. _vq_quantlist__44u5__p1_0,
  148343. NULL,
  148344. &_vq_auxt__44u5__p1_0,
  148345. NULL,
  148346. 0
  148347. };
  148348. static long _vq_quantlist__44u5__p2_0[] = {
  148349. 1,
  148350. 0,
  148351. 2,
  148352. };
  148353. static long _vq_lengthlist__44u5__p2_0[] = {
  148354. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148355. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148356. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148357. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148358. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148359. 9,
  148360. };
  148361. static float _vq_quantthresh__44u5__p2_0[] = {
  148362. -0.5, 0.5,
  148363. };
  148364. static long _vq_quantmap__44u5__p2_0[] = {
  148365. 1, 0, 2,
  148366. };
  148367. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148368. _vq_quantthresh__44u5__p2_0,
  148369. _vq_quantmap__44u5__p2_0,
  148370. 3,
  148371. 3
  148372. };
  148373. static static_codebook _44u5__p2_0 = {
  148374. 4, 81,
  148375. _vq_lengthlist__44u5__p2_0,
  148376. 1, -535822336, 1611661312, 2, 0,
  148377. _vq_quantlist__44u5__p2_0,
  148378. NULL,
  148379. &_vq_auxt__44u5__p2_0,
  148380. NULL,
  148381. 0
  148382. };
  148383. static long _vq_quantlist__44u5__p3_0[] = {
  148384. 2,
  148385. 1,
  148386. 3,
  148387. 0,
  148388. 4,
  148389. };
  148390. static long _vq_lengthlist__44u5__p3_0[] = {
  148391. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148392. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148393. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148394. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  148395. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  148396. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  148397. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  148398. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  148399. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  148400. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148401. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  148402. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148403. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  148404. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  148405. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  148406. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  148407. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148408. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  148409. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  148410. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  148411. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  148412. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  148413. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  148414. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  148415. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  148416. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  148417. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  148418. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  148419. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  148420. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  148421. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  148422. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  148423. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  148424. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  148425. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  148426. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  148427. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  148428. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  148429. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  148430. 0,
  148431. };
  148432. static float _vq_quantthresh__44u5__p3_0[] = {
  148433. -1.5, -0.5, 0.5, 1.5,
  148434. };
  148435. static long _vq_quantmap__44u5__p3_0[] = {
  148436. 3, 1, 0, 2, 4,
  148437. };
  148438. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  148439. _vq_quantthresh__44u5__p3_0,
  148440. _vq_quantmap__44u5__p3_0,
  148441. 5,
  148442. 5
  148443. };
  148444. static static_codebook _44u5__p3_0 = {
  148445. 4, 625,
  148446. _vq_lengthlist__44u5__p3_0,
  148447. 1, -533725184, 1611661312, 3, 0,
  148448. _vq_quantlist__44u5__p3_0,
  148449. NULL,
  148450. &_vq_auxt__44u5__p3_0,
  148451. NULL,
  148452. 0
  148453. };
  148454. static long _vq_quantlist__44u5__p4_0[] = {
  148455. 2,
  148456. 1,
  148457. 3,
  148458. 0,
  148459. 4,
  148460. };
  148461. static long _vq_lengthlist__44u5__p4_0[] = {
  148462. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148463. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148464. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  148465. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  148466. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  148467. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  148468. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148469. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  148470. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148471. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  148472. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  148473. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148474. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148475. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  148476. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  148477. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  148478. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  148479. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148480. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148481. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  148482. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  148483. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  148484. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  148485. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  148486. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  148487. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  148488. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  148489. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  148490. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  148491. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  148492. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  148493. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148494. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  148495. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  148496. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  148497. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  148498. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  148499. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  148500. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  148501. 12,
  148502. };
  148503. static float _vq_quantthresh__44u5__p4_0[] = {
  148504. -1.5, -0.5, 0.5, 1.5,
  148505. };
  148506. static long _vq_quantmap__44u5__p4_0[] = {
  148507. 3, 1, 0, 2, 4,
  148508. };
  148509. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  148510. _vq_quantthresh__44u5__p4_0,
  148511. _vq_quantmap__44u5__p4_0,
  148512. 5,
  148513. 5
  148514. };
  148515. static static_codebook _44u5__p4_0 = {
  148516. 4, 625,
  148517. _vq_lengthlist__44u5__p4_0,
  148518. 1, -533725184, 1611661312, 3, 0,
  148519. _vq_quantlist__44u5__p4_0,
  148520. NULL,
  148521. &_vq_auxt__44u5__p4_0,
  148522. NULL,
  148523. 0
  148524. };
  148525. static long _vq_quantlist__44u5__p5_0[] = {
  148526. 4,
  148527. 3,
  148528. 5,
  148529. 2,
  148530. 6,
  148531. 1,
  148532. 7,
  148533. 0,
  148534. 8,
  148535. };
  148536. static long _vq_lengthlist__44u5__p5_0[] = {
  148537. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  148538. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  148539. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  148540. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  148541. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  148542. 14,
  148543. };
  148544. static float _vq_quantthresh__44u5__p5_0[] = {
  148545. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148546. };
  148547. static long _vq_quantmap__44u5__p5_0[] = {
  148548. 7, 5, 3, 1, 0, 2, 4, 6,
  148549. 8,
  148550. };
  148551. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  148552. _vq_quantthresh__44u5__p5_0,
  148553. _vq_quantmap__44u5__p5_0,
  148554. 9,
  148555. 9
  148556. };
  148557. static static_codebook _44u5__p5_0 = {
  148558. 2, 81,
  148559. _vq_lengthlist__44u5__p5_0,
  148560. 1, -531628032, 1611661312, 4, 0,
  148561. _vq_quantlist__44u5__p5_0,
  148562. NULL,
  148563. &_vq_auxt__44u5__p5_0,
  148564. NULL,
  148565. 0
  148566. };
  148567. static long _vq_quantlist__44u5__p6_0[] = {
  148568. 4,
  148569. 3,
  148570. 5,
  148571. 2,
  148572. 6,
  148573. 1,
  148574. 7,
  148575. 0,
  148576. 8,
  148577. };
  148578. static long _vq_lengthlist__44u5__p6_0[] = {
  148579. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  148580. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  148581. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  148582. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  148583. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  148584. 11,
  148585. };
  148586. static float _vq_quantthresh__44u5__p6_0[] = {
  148587. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148588. };
  148589. static long _vq_quantmap__44u5__p6_0[] = {
  148590. 7, 5, 3, 1, 0, 2, 4, 6,
  148591. 8,
  148592. };
  148593. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  148594. _vq_quantthresh__44u5__p6_0,
  148595. _vq_quantmap__44u5__p6_0,
  148596. 9,
  148597. 9
  148598. };
  148599. static static_codebook _44u5__p6_0 = {
  148600. 2, 81,
  148601. _vq_lengthlist__44u5__p6_0,
  148602. 1, -531628032, 1611661312, 4, 0,
  148603. _vq_quantlist__44u5__p6_0,
  148604. NULL,
  148605. &_vq_auxt__44u5__p6_0,
  148606. NULL,
  148607. 0
  148608. };
  148609. static long _vq_quantlist__44u5__p7_0[] = {
  148610. 1,
  148611. 0,
  148612. 2,
  148613. };
  148614. static long _vq_lengthlist__44u5__p7_0[] = {
  148615. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  148616. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  148617. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  148618. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  148619. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  148620. 12,
  148621. };
  148622. static float _vq_quantthresh__44u5__p7_0[] = {
  148623. -5.5, 5.5,
  148624. };
  148625. static long _vq_quantmap__44u5__p7_0[] = {
  148626. 1, 0, 2,
  148627. };
  148628. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  148629. _vq_quantthresh__44u5__p7_0,
  148630. _vq_quantmap__44u5__p7_0,
  148631. 3,
  148632. 3
  148633. };
  148634. static static_codebook _44u5__p7_0 = {
  148635. 4, 81,
  148636. _vq_lengthlist__44u5__p7_0,
  148637. 1, -529137664, 1618345984, 2, 0,
  148638. _vq_quantlist__44u5__p7_0,
  148639. NULL,
  148640. &_vq_auxt__44u5__p7_0,
  148641. NULL,
  148642. 0
  148643. };
  148644. static long _vq_quantlist__44u5__p7_1[] = {
  148645. 5,
  148646. 4,
  148647. 6,
  148648. 3,
  148649. 7,
  148650. 2,
  148651. 8,
  148652. 1,
  148653. 9,
  148654. 0,
  148655. 10,
  148656. };
  148657. static long _vq_lengthlist__44u5__p7_1[] = {
  148658. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  148659. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  148660. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  148661. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  148662. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  148663. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  148664. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  148665. 9, 9, 9, 9, 9,10,10,10,10,
  148666. };
  148667. static float _vq_quantthresh__44u5__p7_1[] = {
  148668. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148669. 3.5, 4.5,
  148670. };
  148671. static long _vq_quantmap__44u5__p7_1[] = {
  148672. 9, 7, 5, 3, 1, 0, 2, 4,
  148673. 6, 8, 10,
  148674. };
  148675. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  148676. _vq_quantthresh__44u5__p7_1,
  148677. _vq_quantmap__44u5__p7_1,
  148678. 11,
  148679. 11
  148680. };
  148681. static static_codebook _44u5__p7_1 = {
  148682. 2, 121,
  148683. _vq_lengthlist__44u5__p7_1,
  148684. 1, -531365888, 1611661312, 4, 0,
  148685. _vq_quantlist__44u5__p7_1,
  148686. NULL,
  148687. &_vq_auxt__44u5__p7_1,
  148688. NULL,
  148689. 0
  148690. };
  148691. static long _vq_quantlist__44u5__p8_0[] = {
  148692. 5,
  148693. 4,
  148694. 6,
  148695. 3,
  148696. 7,
  148697. 2,
  148698. 8,
  148699. 1,
  148700. 9,
  148701. 0,
  148702. 10,
  148703. };
  148704. static long _vq_lengthlist__44u5__p8_0[] = {
  148705. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  148706. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  148707. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  148708. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  148709. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  148710. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  148711. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  148712. 12,13,13,14,14,14,14,15,15,
  148713. };
  148714. static float _vq_quantthresh__44u5__p8_0[] = {
  148715. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  148716. 38.5, 49.5,
  148717. };
  148718. static long _vq_quantmap__44u5__p8_0[] = {
  148719. 9, 7, 5, 3, 1, 0, 2, 4,
  148720. 6, 8, 10,
  148721. };
  148722. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  148723. _vq_quantthresh__44u5__p8_0,
  148724. _vq_quantmap__44u5__p8_0,
  148725. 11,
  148726. 11
  148727. };
  148728. static static_codebook _44u5__p8_0 = {
  148729. 2, 121,
  148730. _vq_lengthlist__44u5__p8_0,
  148731. 1, -524582912, 1618345984, 4, 0,
  148732. _vq_quantlist__44u5__p8_0,
  148733. NULL,
  148734. &_vq_auxt__44u5__p8_0,
  148735. NULL,
  148736. 0
  148737. };
  148738. static long _vq_quantlist__44u5__p8_1[] = {
  148739. 5,
  148740. 4,
  148741. 6,
  148742. 3,
  148743. 7,
  148744. 2,
  148745. 8,
  148746. 1,
  148747. 9,
  148748. 0,
  148749. 10,
  148750. };
  148751. static long _vq_lengthlist__44u5__p8_1[] = {
  148752. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  148753. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  148754. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  148755. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  148756. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  148757. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  148758. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148759. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148760. };
  148761. static float _vq_quantthresh__44u5__p8_1[] = {
  148762. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148763. 3.5, 4.5,
  148764. };
  148765. static long _vq_quantmap__44u5__p8_1[] = {
  148766. 9, 7, 5, 3, 1, 0, 2, 4,
  148767. 6, 8, 10,
  148768. };
  148769. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  148770. _vq_quantthresh__44u5__p8_1,
  148771. _vq_quantmap__44u5__p8_1,
  148772. 11,
  148773. 11
  148774. };
  148775. static static_codebook _44u5__p8_1 = {
  148776. 2, 121,
  148777. _vq_lengthlist__44u5__p8_1,
  148778. 1, -531365888, 1611661312, 4, 0,
  148779. _vq_quantlist__44u5__p8_1,
  148780. NULL,
  148781. &_vq_auxt__44u5__p8_1,
  148782. NULL,
  148783. 0
  148784. };
  148785. static long _vq_quantlist__44u5__p9_0[] = {
  148786. 6,
  148787. 5,
  148788. 7,
  148789. 4,
  148790. 8,
  148791. 3,
  148792. 9,
  148793. 2,
  148794. 10,
  148795. 1,
  148796. 11,
  148797. 0,
  148798. 12,
  148799. };
  148800. static long _vq_lengthlist__44u5__p9_0[] = {
  148801. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  148802. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  148803. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  148804. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  148805. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148806. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148807. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148808. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148809. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  148810. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148811. 12,12,12,12,12,12,12,12,12,
  148812. };
  148813. static float _vq_quantthresh__44u5__p9_0[] = {
  148814. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148815. 637.5, 892.5, 1147.5, 1402.5,
  148816. };
  148817. static long _vq_quantmap__44u5__p9_0[] = {
  148818. 11, 9, 7, 5, 3, 1, 0, 2,
  148819. 4, 6, 8, 10, 12,
  148820. };
  148821. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  148822. _vq_quantthresh__44u5__p9_0,
  148823. _vq_quantmap__44u5__p9_0,
  148824. 13,
  148825. 13
  148826. };
  148827. static static_codebook _44u5__p9_0 = {
  148828. 2, 169,
  148829. _vq_lengthlist__44u5__p9_0,
  148830. 1, -514332672, 1627381760, 4, 0,
  148831. _vq_quantlist__44u5__p9_0,
  148832. NULL,
  148833. &_vq_auxt__44u5__p9_0,
  148834. NULL,
  148835. 0
  148836. };
  148837. static long _vq_quantlist__44u5__p9_1[] = {
  148838. 7,
  148839. 6,
  148840. 8,
  148841. 5,
  148842. 9,
  148843. 4,
  148844. 10,
  148845. 3,
  148846. 11,
  148847. 2,
  148848. 12,
  148849. 1,
  148850. 13,
  148851. 0,
  148852. 14,
  148853. };
  148854. static long _vq_lengthlist__44u5__p9_1[] = {
  148855. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  148856. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  148857. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  148858. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  148859. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  148860. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  148861. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  148862. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  148863. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  148864. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  148865. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  148866. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  148867. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  148868. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  148869. 14,
  148870. };
  148871. static float _vq_quantthresh__44u5__p9_1[] = {
  148872. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148873. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148874. };
  148875. static long _vq_quantmap__44u5__p9_1[] = {
  148876. 13, 11, 9, 7, 5, 3, 1, 0,
  148877. 2, 4, 6, 8, 10, 12, 14,
  148878. };
  148879. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  148880. _vq_quantthresh__44u5__p9_1,
  148881. _vq_quantmap__44u5__p9_1,
  148882. 15,
  148883. 15
  148884. };
  148885. static static_codebook _44u5__p9_1 = {
  148886. 2, 225,
  148887. _vq_lengthlist__44u5__p9_1,
  148888. 1, -522338304, 1620115456, 4, 0,
  148889. _vq_quantlist__44u5__p9_1,
  148890. NULL,
  148891. &_vq_auxt__44u5__p9_1,
  148892. NULL,
  148893. 0
  148894. };
  148895. static long _vq_quantlist__44u5__p9_2[] = {
  148896. 8,
  148897. 7,
  148898. 9,
  148899. 6,
  148900. 10,
  148901. 5,
  148902. 11,
  148903. 4,
  148904. 12,
  148905. 3,
  148906. 13,
  148907. 2,
  148908. 14,
  148909. 1,
  148910. 15,
  148911. 0,
  148912. 16,
  148913. };
  148914. static long _vq_lengthlist__44u5__p9_2[] = {
  148915. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148916. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148917. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148918. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148919. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148920. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  148921. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148922. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  148923. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  148924. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  148925. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  148926. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  148927. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148928. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148929. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148930. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148931. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  148932. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  148933. 10,
  148934. };
  148935. static float _vq_quantthresh__44u5__p9_2[] = {
  148936. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148937. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148938. };
  148939. static long _vq_quantmap__44u5__p9_2[] = {
  148940. 15, 13, 11, 9, 7, 5, 3, 1,
  148941. 0, 2, 4, 6, 8, 10, 12, 14,
  148942. 16,
  148943. };
  148944. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  148945. _vq_quantthresh__44u5__p9_2,
  148946. _vq_quantmap__44u5__p9_2,
  148947. 17,
  148948. 17
  148949. };
  148950. static static_codebook _44u5__p9_2 = {
  148951. 2, 289,
  148952. _vq_lengthlist__44u5__p9_2,
  148953. 1, -529530880, 1611661312, 5, 0,
  148954. _vq_quantlist__44u5__p9_2,
  148955. NULL,
  148956. &_vq_auxt__44u5__p9_2,
  148957. NULL,
  148958. 0
  148959. };
  148960. static long _huff_lengthlist__44u5__short[] = {
  148961. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  148962. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  148963. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  148964. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  148965. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  148966. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  148967. 6, 8,15,17,
  148968. };
  148969. static static_codebook _huff_book__44u5__short = {
  148970. 2, 100,
  148971. _huff_lengthlist__44u5__short,
  148972. 0, 0, 0, 0, 0,
  148973. NULL,
  148974. NULL,
  148975. NULL,
  148976. NULL,
  148977. 0
  148978. };
  148979. static long _huff_lengthlist__44u6__long[] = {
  148980. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  148981. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  148982. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  148983. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  148984. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  148985. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  148986. 13, 8, 7, 7,
  148987. };
  148988. static static_codebook _huff_book__44u6__long = {
  148989. 2, 100,
  148990. _huff_lengthlist__44u6__long,
  148991. 0, 0, 0, 0, 0,
  148992. NULL,
  148993. NULL,
  148994. NULL,
  148995. NULL,
  148996. 0
  148997. };
  148998. static long _vq_quantlist__44u6__p1_0[] = {
  148999. 1,
  149000. 0,
  149001. 2,
  149002. };
  149003. static long _vq_lengthlist__44u6__p1_0[] = {
  149004. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149005. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149006. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149007. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149008. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149009. 12,
  149010. };
  149011. static float _vq_quantthresh__44u6__p1_0[] = {
  149012. -0.5, 0.5,
  149013. };
  149014. static long _vq_quantmap__44u6__p1_0[] = {
  149015. 1, 0, 2,
  149016. };
  149017. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149018. _vq_quantthresh__44u6__p1_0,
  149019. _vq_quantmap__44u6__p1_0,
  149020. 3,
  149021. 3
  149022. };
  149023. static static_codebook _44u6__p1_0 = {
  149024. 4, 81,
  149025. _vq_lengthlist__44u6__p1_0,
  149026. 1, -535822336, 1611661312, 2, 0,
  149027. _vq_quantlist__44u6__p1_0,
  149028. NULL,
  149029. &_vq_auxt__44u6__p1_0,
  149030. NULL,
  149031. 0
  149032. };
  149033. static long _vq_quantlist__44u6__p2_0[] = {
  149034. 1,
  149035. 0,
  149036. 2,
  149037. };
  149038. static long _vq_lengthlist__44u6__p2_0[] = {
  149039. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149040. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149041. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149042. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149043. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149044. 9,
  149045. };
  149046. static float _vq_quantthresh__44u6__p2_0[] = {
  149047. -0.5, 0.5,
  149048. };
  149049. static long _vq_quantmap__44u6__p2_0[] = {
  149050. 1, 0, 2,
  149051. };
  149052. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149053. _vq_quantthresh__44u6__p2_0,
  149054. _vq_quantmap__44u6__p2_0,
  149055. 3,
  149056. 3
  149057. };
  149058. static static_codebook _44u6__p2_0 = {
  149059. 4, 81,
  149060. _vq_lengthlist__44u6__p2_0,
  149061. 1, -535822336, 1611661312, 2, 0,
  149062. _vq_quantlist__44u6__p2_0,
  149063. NULL,
  149064. &_vq_auxt__44u6__p2_0,
  149065. NULL,
  149066. 0
  149067. };
  149068. static long _vq_quantlist__44u6__p3_0[] = {
  149069. 2,
  149070. 1,
  149071. 3,
  149072. 0,
  149073. 4,
  149074. };
  149075. static long _vq_lengthlist__44u6__p3_0[] = {
  149076. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149077. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149078. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149079. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149080. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149081. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149082. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149083. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149084. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149085. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149086. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149087. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149088. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149089. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149090. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149091. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149092. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149093. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149094. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149095. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149096. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149097. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149098. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149099. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149100. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149101. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149102. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149103. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149104. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149105. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149106. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149107. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149108. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149109. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149110. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149111. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149112. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149113. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149114. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149115. 19,
  149116. };
  149117. static float _vq_quantthresh__44u6__p3_0[] = {
  149118. -1.5, -0.5, 0.5, 1.5,
  149119. };
  149120. static long _vq_quantmap__44u6__p3_0[] = {
  149121. 3, 1, 0, 2, 4,
  149122. };
  149123. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149124. _vq_quantthresh__44u6__p3_0,
  149125. _vq_quantmap__44u6__p3_0,
  149126. 5,
  149127. 5
  149128. };
  149129. static static_codebook _44u6__p3_0 = {
  149130. 4, 625,
  149131. _vq_lengthlist__44u6__p3_0,
  149132. 1, -533725184, 1611661312, 3, 0,
  149133. _vq_quantlist__44u6__p3_0,
  149134. NULL,
  149135. &_vq_auxt__44u6__p3_0,
  149136. NULL,
  149137. 0
  149138. };
  149139. static long _vq_quantlist__44u6__p4_0[] = {
  149140. 2,
  149141. 1,
  149142. 3,
  149143. 0,
  149144. 4,
  149145. };
  149146. static long _vq_lengthlist__44u6__p4_0[] = {
  149147. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149148. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149149. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149150. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149151. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149152. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149153. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149154. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149155. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149156. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149157. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149158. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149159. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149160. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149161. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149162. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149163. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149164. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149165. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149166. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149167. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149168. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149169. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149170. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149171. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149172. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149173. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149174. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149175. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149176. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149177. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149178. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149179. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149180. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149181. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149182. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149183. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149184. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149185. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149186. 13,
  149187. };
  149188. static float _vq_quantthresh__44u6__p4_0[] = {
  149189. -1.5, -0.5, 0.5, 1.5,
  149190. };
  149191. static long _vq_quantmap__44u6__p4_0[] = {
  149192. 3, 1, 0, 2, 4,
  149193. };
  149194. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149195. _vq_quantthresh__44u6__p4_0,
  149196. _vq_quantmap__44u6__p4_0,
  149197. 5,
  149198. 5
  149199. };
  149200. static static_codebook _44u6__p4_0 = {
  149201. 4, 625,
  149202. _vq_lengthlist__44u6__p4_0,
  149203. 1, -533725184, 1611661312, 3, 0,
  149204. _vq_quantlist__44u6__p4_0,
  149205. NULL,
  149206. &_vq_auxt__44u6__p4_0,
  149207. NULL,
  149208. 0
  149209. };
  149210. static long _vq_quantlist__44u6__p5_0[] = {
  149211. 4,
  149212. 3,
  149213. 5,
  149214. 2,
  149215. 6,
  149216. 1,
  149217. 7,
  149218. 0,
  149219. 8,
  149220. };
  149221. static long _vq_lengthlist__44u6__p5_0[] = {
  149222. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149223. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149224. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149225. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149226. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149227. 14,
  149228. };
  149229. static float _vq_quantthresh__44u6__p5_0[] = {
  149230. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149231. };
  149232. static long _vq_quantmap__44u6__p5_0[] = {
  149233. 7, 5, 3, 1, 0, 2, 4, 6,
  149234. 8,
  149235. };
  149236. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149237. _vq_quantthresh__44u6__p5_0,
  149238. _vq_quantmap__44u6__p5_0,
  149239. 9,
  149240. 9
  149241. };
  149242. static static_codebook _44u6__p5_0 = {
  149243. 2, 81,
  149244. _vq_lengthlist__44u6__p5_0,
  149245. 1, -531628032, 1611661312, 4, 0,
  149246. _vq_quantlist__44u6__p5_0,
  149247. NULL,
  149248. &_vq_auxt__44u6__p5_0,
  149249. NULL,
  149250. 0
  149251. };
  149252. static long _vq_quantlist__44u6__p6_0[] = {
  149253. 4,
  149254. 3,
  149255. 5,
  149256. 2,
  149257. 6,
  149258. 1,
  149259. 7,
  149260. 0,
  149261. 8,
  149262. };
  149263. static long _vq_lengthlist__44u6__p6_0[] = {
  149264. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149265. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  149266. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149267. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  149268. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  149269. 12,
  149270. };
  149271. static float _vq_quantthresh__44u6__p6_0[] = {
  149272. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149273. };
  149274. static long _vq_quantmap__44u6__p6_0[] = {
  149275. 7, 5, 3, 1, 0, 2, 4, 6,
  149276. 8,
  149277. };
  149278. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  149279. _vq_quantthresh__44u6__p6_0,
  149280. _vq_quantmap__44u6__p6_0,
  149281. 9,
  149282. 9
  149283. };
  149284. static static_codebook _44u6__p6_0 = {
  149285. 2, 81,
  149286. _vq_lengthlist__44u6__p6_0,
  149287. 1, -531628032, 1611661312, 4, 0,
  149288. _vq_quantlist__44u6__p6_0,
  149289. NULL,
  149290. &_vq_auxt__44u6__p6_0,
  149291. NULL,
  149292. 0
  149293. };
  149294. static long _vq_quantlist__44u6__p7_0[] = {
  149295. 1,
  149296. 0,
  149297. 2,
  149298. };
  149299. static long _vq_lengthlist__44u6__p7_0[] = {
  149300. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  149301. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  149302. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  149303. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  149304. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149305. 10,
  149306. };
  149307. static float _vq_quantthresh__44u6__p7_0[] = {
  149308. -5.5, 5.5,
  149309. };
  149310. static long _vq_quantmap__44u6__p7_0[] = {
  149311. 1, 0, 2,
  149312. };
  149313. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149314. _vq_quantthresh__44u6__p7_0,
  149315. _vq_quantmap__44u6__p7_0,
  149316. 3,
  149317. 3
  149318. };
  149319. static static_codebook _44u6__p7_0 = {
  149320. 4, 81,
  149321. _vq_lengthlist__44u6__p7_0,
  149322. 1, -529137664, 1618345984, 2, 0,
  149323. _vq_quantlist__44u6__p7_0,
  149324. NULL,
  149325. &_vq_auxt__44u6__p7_0,
  149326. NULL,
  149327. 0
  149328. };
  149329. static long _vq_quantlist__44u6__p7_1[] = {
  149330. 5,
  149331. 4,
  149332. 6,
  149333. 3,
  149334. 7,
  149335. 2,
  149336. 8,
  149337. 1,
  149338. 9,
  149339. 0,
  149340. 10,
  149341. };
  149342. static long _vq_lengthlist__44u6__p7_1[] = {
  149343. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149344. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149345. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149346. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149347. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149348. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149349. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149350. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149351. };
  149352. static float _vq_quantthresh__44u6__p7_1[] = {
  149353. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149354. 3.5, 4.5,
  149355. };
  149356. static long _vq_quantmap__44u6__p7_1[] = {
  149357. 9, 7, 5, 3, 1, 0, 2, 4,
  149358. 6, 8, 10,
  149359. };
  149360. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149361. _vq_quantthresh__44u6__p7_1,
  149362. _vq_quantmap__44u6__p7_1,
  149363. 11,
  149364. 11
  149365. };
  149366. static static_codebook _44u6__p7_1 = {
  149367. 2, 121,
  149368. _vq_lengthlist__44u6__p7_1,
  149369. 1, -531365888, 1611661312, 4, 0,
  149370. _vq_quantlist__44u6__p7_1,
  149371. NULL,
  149372. &_vq_auxt__44u6__p7_1,
  149373. NULL,
  149374. 0
  149375. };
  149376. static long _vq_quantlist__44u6__p8_0[] = {
  149377. 5,
  149378. 4,
  149379. 6,
  149380. 3,
  149381. 7,
  149382. 2,
  149383. 8,
  149384. 1,
  149385. 9,
  149386. 0,
  149387. 10,
  149388. };
  149389. static long _vq_lengthlist__44u6__p8_0[] = {
  149390. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149391. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149392. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  149393. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  149394. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  149395. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  149396. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  149397. 12,13,13,14,14,14,15,15,15,
  149398. };
  149399. static float _vq_quantthresh__44u6__p8_0[] = {
  149400. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149401. 38.5, 49.5,
  149402. };
  149403. static long _vq_quantmap__44u6__p8_0[] = {
  149404. 9, 7, 5, 3, 1, 0, 2, 4,
  149405. 6, 8, 10,
  149406. };
  149407. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  149408. _vq_quantthresh__44u6__p8_0,
  149409. _vq_quantmap__44u6__p8_0,
  149410. 11,
  149411. 11
  149412. };
  149413. static static_codebook _44u6__p8_0 = {
  149414. 2, 121,
  149415. _vq_lengthlist__44u6__p8_0,
  149416. 1, -524582912, 1618345984, 4, 0,
  149417. _vq_quantlist__44u6__p8_0,
  149418. NULL,
  149419. &_vq_auxt__44u6__p8_0,
  149420. NULL,
  149421. 0
  149422. };
  149423. static long _vq_quantlist__44u6__p8_1[] = {
  149424. 5,
  149425. 4,
  149426. 6,
  149427. 3,
  149428. 7,
  149429. 2,
  149430. 8,
  149431. 1,
  149432. 9,
  149433. 0,
  149434. 10,
  149435. };
  149436. static long _vq_lengthlist__44u6__p8_1[] = {
  149437. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  149438. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  149439. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  149440. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149441. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  149442. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149443. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  149444. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149445. };
  149446. static float _vq_quantthresh__44u6__p8_1[] = {
  149447. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149448. 3.5, 4.5,
  149449. };
  149450. static long _vq_quantmap__44u6__p8_1[] = {
  149451. 9, 7, 5, 3, 1, 0, 2, 4,
  149452. 6, 8, 10,
  149453. };
  149454. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  149455. _vq_quantthresh__44u6__p8_1,
  149456. _vq_quantmap__44u6__p8_1,
  149457. 11,
  149458. 11
  149459. };
  149460. static static_codebook _44u6__p8_1 = {
  149461. 2, 121,
  149462. _vq_lengthlist__44u6__p8_1,
  149463. 1, -531365888, 1611661312, 4, 0,
  149464. _vq_quantlist__44u6__p8_1,
  149465. NULL,
  149466. &_vq_auxt__44u6__p8_1,
  149467. NULL,
  149468. 0
  149469. };
  149470. static long _vq_quantlist__44u6__p9_0[] = {
  149471. 7,
  149472. 6,
  149473. 8,
  149474. 5,
  149475. 9,
  149476. 4,
  149477. 10,
  149478. 3,
  149479. 11,
  149480. 2,
  149481. 12,
  149482. 1,
  149483. 13,
  149484. 0,
  149485. 14,
  149486. };
  149487. static long _vq_lengthlist__44u6__p9_0[] = {
  149488. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  149489. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  149490. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  149491. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  149492. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149493. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149494. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149495. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149496. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149497. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149498. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149499. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149500. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149501. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149502. 14,
  149503. };
  149504. static float _vq_quantthresh__44u6__p9_0[] = {
  149505. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  149506. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  149507. };
  149508. static long _vq_quantmap__44u6__p9_0[] = {
  149509. 13, 11, 9, 7, 5, 3, 1, 0,
  149510. 2, 4, 6, 8, 10, 12, 14,
  149511. };
  149512. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  149513. _vq_quantthresh__44u6__p9_0,
  149514. _vq_quantmap__44u6__p9_0,
  149515. 15,
  149516. 15
  149517. };
  149518. static static_codebook _44u6__p9_0 = {
  149519. 2, 225,
  149520. _vq_lengthlist__44u6__p9_0,
  149521. 1, -514071552, 1627381760, 4, 0,
  149522. _vq_quantlist__44u6__p9_0,
  149523. NULL,
  149524. &_vq_auxt__44u6__p9_0,
  149525. NULL,
  149526. 0
  149527. };
  149528. static long _vq_quantlist__44u6__p9_1[] = {
  149529. 7,
  149530. 6,
  149531. 8,
  149532. 5,
  149533. 9,
  149534. 4,
  149535. 10,
  149536. 3,
  149537. 11,
  149538. 2,
  149539. 12,
  149540. 1,
  149541. 13,
  149542. 0,
  149543. 14,
  149544. };
  149545. static long _vq_lengthlist__44u6__p9_1[] = {
  149546. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  149547. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  149548. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  149549. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  149550. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  149551. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  149552. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  149553. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  149554. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  149555. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  149556. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  149557. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  149558. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  149559. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  149560. 13,
  149561. };
  149562. static float _vq_quantthresh__44u6__p9_1[] = {
  149563. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149564. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149565. };
  149566. static long _vq_quantmap__44u6__p9_1[] = {
  149567. 13, 11, 9, 7, 5, 3, 1, 0,
  149568. 2, 4, 6, 8, 10, 12, 14,
  149569. };
  149570. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  149571. _vq_quantthresh__44u6__p9_1,
  149572. _vq_quantmap__44u6__p9_1,
  149573. 15,
  149574. 15
  149575. };
  149576. static static_codebook _44u6__p9_1 = {
  149577. 2, 225,
  149578. _vq_lengthlist__44u6__p9_1,
  149579. 1, -522338304, 1620115456, 4, 0,
  149580. _vq_quantlist__44u6__p9_1,
  149581. NULL,
  149582. &_vq_auxt__44u6__p9_1,
  149583. NULL,
  149584. 0
  149585. };
  149586. static long _vq_quantlist__44u6__p9_2[] = {
  149587. 8,
  149588. 7,
  149589. 9,
  149590. 6,
  149591. 10,
  149592. 5,
  149593. 11,
  149594. 4,
  149595. 12,
  149596. 3,
  149597. 13,
  149598. 2,
  149599. 14,
  149600. 1,
  149601. 15,
  149602. 0,
  149603. 16,
  149604. };
  149605. static long _vq_lengthlist__44u6__p9_2[] = {
  149606. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  149607. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  149608. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  149609. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149610. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149611. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149612. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149613. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149614. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  149615. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  149616. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  149617. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149618. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  149619. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  149620. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  149621. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  149622. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  149623. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  149624. 10,
  149625. };
  149626. static float _vq_quantthresh__44u6__p9_2[] = {
  149627. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149628. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149629. };
  149630. static long _vq_quantmap__44u6__p9_2[] = {
  149631. 15, 13, 11, 9, 7, 5, 3, 1,
  149632. 0, 2, 4, 6, 8, 10, 12, 14,
  149633. 16,
  149634. };
  149635. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  149636. _vq_quantthresh__44u6__p9_2,
  149637. _vq_quantmap__44u6__p9_2,
  149638. 17,
  149639. 17
  149640. };
  149641. static static_codebook _44u6__p9_2 = {
  149642. 2, 289,
  149643. _vq_lengthlist__44u6__p9_2,
  149644. 1, -529530880, 1611661312, 5, 0,
  149645. _vq_quantlist__44u6__p9_2,
  149646. NULL,
  149647. &_vq_auxt__44u6__p9_2,
  149648. NULL,
  149649. 0
  149650. };
  149651. static long _huff_lengthlist__44u6__short[] = {
  149652. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  149653. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  149654. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  149655. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  149656. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  149657. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  149658. 7, 6, 9,16,
  149659. };
  149660. static static_codebook _huff_book__44u6__short = {
  149661. 2, 100,
  149662. _huff_lengthlist__44u6__short,
  149663. 0, 0, 0, 0, 0,
  149664. NULL,
  149665. NULL,
  149666. NULL,
  149667. NULL,
  149668. 0
  149669. };
  149670. static long _huff_lengthlist__44u7__long[] = {
  149671. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  149672. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  149673. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  149674. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  149675. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  149676. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  149677. 12, 8, 6, 7,
  149678. };
  149679. static static_codebook _huff_book__44u7__long = {
  149680. 2, 100,
  149681. _huff_lengthlist__44u7__long,
  149682. 0, 0, 0, 0, 0,
  149683. NULL,
  149684. NULL,
  149685. NULL,
  149686. NULL,
  149687. 0
  149688. };
  149689. static long _vq_quantlist__44u7__p1_0[] = {
  149690. 1,
  149691. 0,
  149692. 2,
  149693. };
  149694. static long _vq_lengthlist__44u7__p1_0[] = {
  149695. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149696. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  149697. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149698. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  149699. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  149700. 12,
  149701. };
  149702. static float _vq_quantthresh__44u7__p1_0[] = {
  149703. -0.5, 0.5,
  149704. };
  149705. static long _vq_quantmap__44u7__p1_0[] = {
  149706. 1, 0, 2,
  149707. };
  149708. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  149709. _vq_quantthresh__44u7__p1_0,
  149710. _vq_quantmap__44u7__p1_0,
  149711. 3,
  149712. 3
  149713. };
  149714. static static_codebook _44u7__p1_0 = {
  149715. 4, 81,
  149716. _vq_lengthlist__44u7__p1_0,
  149717. 1, -535822336, 1611661312, 2, 0,
  149718. _vq_quantlist__44u7__p1_0,
  149719. NULL,
  149720. &_vq_auxt__44u7__p1_0,
  149721. NULL,
  149722. 0
  149723. };
  149724. static long _vq_quantlist__44u7__p2_0[] = {
  149725. 1,
  149726. 0,
  149727. 2,
  149728. };
  149729. static long _vq_lengthlist__44u7__p2_0[] = {
  149730. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149731. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149732. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149733. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149734. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149735. 9,
  149736. };
  149737. static float _vq_quantthresh__44u7__p2_0[] = {
  149738. -0.5, 0.5,
  149739. };
  149740. static long _vq_quantmap__44u7__p2_0[] = {
  149741. 1, 0, 2,
  149742. };
  149743. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  149744. _vq_quantthresh__44u7__p2_0,
  149745. _vq_quantmap__44u7__p2_0,
  149746. 3,
  149747. 3
  149748. };
  149749. static static_codebook _44u7__p2_0 = {
  149750. 4, 81,
  149751. _vq_lengthlist__44u7__p2_0,
  149752. 1, -535822336, 1611661312, 2, 0,
  149753. _vq_quantlist__44u7__p2_0,
  149754. NULL,
  149755. &_vq_auxt__44u7__p2_0,
  149756. NULL,
  149757. 0
  149758. };
  149759. static long _vq_quantlist__44u7__p3_0[] = {
  149760. 2,
  149761. 1,
  149762. 3,
  149763. 0,
  149764. 4,
  149765. };
  149766. static long _vq_lengthlist__44u7__p3_0[] = {
  149767. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149768. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149769. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149770. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  149771. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  149772. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  149773. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149774. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  149775. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  149776. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  149777. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  149778. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  149779. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  149780. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  149781. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  149782. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  149783. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  149784. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149785. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  149786. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  149787. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  149788. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  149789. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  149790. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  149791. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  149792. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  149793. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  149794. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  149795. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  149796. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  149797. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  149798. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  149799. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  149800. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  149801. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  149802. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  149803. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  149804. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  149805. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  149806. 0,
  149807. };
  149808. static float _vq_quantthresh__44u7__p3_0[] = {
  149809. -1.5, -0.5, 0.5, 1.5,
  149810. };
  149811. static long _vq_quantmap__44u7__p3_0[] = {
  149812. 3, 1, 0, 2, 4,
  149813. };
  149814. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  149815. _vq_quantthresh__44u7__p3_0,
  149816. _vq_quantmap__44u7__p3_0,
  149817. 5,
  149818. 5
  149819. };
  149820. static static_codebook _44u7__p3_0 = {
  149821. 4, 625,
  149822. _vq_lengthlist__44u7__p3_0,
  149823. 1, -533725184, 1611661312, 3, 0,
  149824. _vq_quantlist__44u7__p3_0,
  149825. NULL,
  149826. &_vq_auxt__44u7__p3_0,
  149827. NULL,
  149828. 0
  149829. };
  149830. static long _vq_quantlist__44u7__p4_0[] = {
  149831. 2,
  149832. 1,
  149833. 3,
  149834. 0,
  149835. 4,
  149836. };
  149837. static long _vq_lengthlist__44u7__p4_0[] = {
  149838. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149839. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  149840. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  149841. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149842. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149843. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149844. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  149845. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  149846. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149847. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149848. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  149849. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149850. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149851. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  149852. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  149853. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149854. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  149855. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149856. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  149857. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  149858. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149859. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149860. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  149861. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149862. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  149863. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149864. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149865. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  149866. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  149867. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  149868. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  149869. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149870. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  149871. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149872. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  149873. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149874. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  149875. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  149876. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  149877. 14,
  149878. };
  149879. static float _vq_quantthresh__44u7__p4_0[] = {
  149880. -1.5, -0.5, 0.5, 1.5,
  149881. };
  149882. static long _vq_quantmap__44u7__p4_0[] = {
  149883. 3, 1, 0, 2, 4,
  149884. };
  149885. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  149886. _vq_quantthresh__44u7__p4_0,
  149887. _vq_quantmap__44u7__p4_0,
  149888. 5,
  149889. 5
  149890. };
  149891. static static_codebook _44u7__p4_0 = {
  149892. 4, 625,
  149893. _vq_lengthlist__44u7__p4_0,
  149894. 1, -533725184, 1611661312, 3, 0,
  149895. _vq_quantlist__44u7__p4_0,
  149896. NULL,
  149897. &_vq_auxt__44u7__p4_0,
  149898. NULL,
  149899. 0
  149900. };
  149901. static long _vq_quantlist__44u7__p5_0[] = {
  149902. 4,
  149903. 3,
  149904. 5,
  149905. 2,
  149906. 6,
  149907. 1,
  149908. 7,
  149909. 0,
  149910. 8,
  149911. };
  149912. static long _vq_lengthlist__44u7__p5_0[] = {
  149913. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149914. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  149915. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  149916. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  149917. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  149918. 14,
  149919. };
  149920. static float _vq_quantthresh__44u7__p5_0[] = {
  149921. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149922. };
  149923. static long _vq_quantmap__44u7__p5_0[] = {
  149924. 7, 5, 3, 1, 0, 2, 4, 6,
  149925. 8,
  149926. };
  149927. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  149928. _vq_quantthresh__44u7__p5_0,
  149929. _vq_quantmap__44u7__p5_0,
  149930. 9,
  149931. 9
  149932. };
  149933. static static_codebook _44u7__p5_0 = {
  149934. 2, 81,
  149935. _vq_lengthlist__44u7__p5_0,
  149936. 1, -531628032, 1611661312, 4, 0,
  149937. _vq_quantlist__44u7__p5_0,
  149938. NULL,
  149939. &_vq_auxt__44u7__p5_0,
  149940. NULL,
  149941. 0
  149942. };
  149943. static long _vq_quantlist__44u7__p6_0[] = {
  149944. 4,
  149945. 3,
  149946. 5,
  149947. 2,
  149948. 6,
  149949. 1,
  149950. 7,
  149951. 0,
  149952. 8,
  149953. };
  149954. static long _vq_lengthlist__44u7__p6_0[] = {
  149955. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  149956. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149957. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149958. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  149959. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  149960. 12,
  149961. };
  149962. static float _vq_quantthresh__44u7__p6_0[] = {
  149963. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149964. };
  149965. static long _vq_quantmap__44u7__p6_0[] = {
  149966. 7, 5, 3, 1, 0, 2, 4, 6,
  149967. 8,
  149968. };
  149969. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  149970. _vq_quantthresh__44u7__p6_0,
  149971. _vq_quantmap__44u7__p6_0,
  149972. 9,
  149973. 9
  149974. };
  149975. static static_codebook _44u7__p6_0 = {
  149976. 2, 81,
  149977. _vq_lengthlist__44u7__p6_0,
  149978. 1, -531628032, 1611661312, 4, 0,
  149979. _vq_quantlist__44u7__p6_0,
  149980. NULL,
  149981. &_vq_auxt__44u7__p6_0,
  149982. NULL,
  149983. 0
  149984. };
  149985. static long _vq_quantlist__44u7__p7_0[] = {
  149986. 1,
  149987. 0,
  149988. 2,
  149989. };
  149990. static long _vq_lengthlist__44u7__p7_0[] = {
  149991. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  149992. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  149993. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  149994. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  149995. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  149996. 10,
  149997. };
  149998. static float _vq_quantthresh__44u7__p7_0[] = {
  149999. -5.5, 5.5,
  150000. };
  150001. static long _vq_quantmap__44u7__p7_0[] = {
  150002. 1, 0, 2,
  150003. };
  150004. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150005. _vq_quantthresh__44u7__p7_0,
  150006. _vq_quantmap__44u7__p7_0,
  150007. 3,
  150008. 3
  150009. };
  150010. static static_codebook _44u7__p7_0 = {
  150011. 4, 81,
  150012. _vq_lengthlist__44u7__p7_0,
  150013. 1, -529137664, 1618345984, 2, 0,
  150014. _vq_quantlist__44u7__p7_0,
  150015. NULL,
  150016. &_vq_auxt__44u7__p7_0,
  150017. NULL,
  150018. 0
  150019. };
  150020. static long _vq_quantlist__44u7__p7_1[] = {
  150021. 5,
  150022. 4,
  150023. 6,
  150024. 3,
  150025. 7,
  150026. 2,
  150027. 8,
  150028. 1,
  150029. 9,
  150030. 0,
  150031. 10,
  150032. };
  150033. static long _vq_lengthlist__44u7__p7_1[] = {
  150034. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150035. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150036. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150037. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150038. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150039. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150040. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150041. 8, 9, 9, 9, 9, 9,10,10,10,
  150042. };
  150043. static float _vq_quantthresh__44u7__p7_1[] = {
  150044. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150045. 3.5, 4.5,
  150046. };
  150047. static long _vq_quantmap__44u7__p7_1[] = {
  150048. 9, 7, 5, 3, 1, 0, 2, 4,
  150049. 6, 8, 10,
  150050. };
  150051. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150052. _vq_quantthresh__44u7__p7_1,
  150053. _vq_quantmap__44u7__p7_1,
  150054. 11,
  150055. 11
  150056. };
  150057. static static_codebook _44u7__p7_1 = {
  150058. 2, 121,
  150059. _vq_lengthlist__44u7__p7_1,
  150060. 1, -531365888, 1611661312, 4, 0,
  150061. _vq_quantlist__44u7__p7_1,
  150062. NULL,
  150063. &_vq_auxt__44u7__p7_1,
  150064. NULL,
  150065. 0
  150066. };
  150067. static long _vq_quantlist__44u7__p8_0[] = {
  150068. 5,
  150069. 4,
  150070. 6,
  150071. 3,
  150072. 7,
  150073. 2,
  150074. 8,
  150075. 1,
  150076. 9,
  150077. 0,
  150078. 10,
  150079. };
  150080. static long _vq_lengthlist__44u7__p8_0[] = {
  150081. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150082. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150083. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150084. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150085. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150086. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150087. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150088. 12,13,13,14,14,15,15,15,16,
  150089. };
  150090. static float _vq_quantthresh__44u7__p8_0[] = {
  150091. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150092. 38.5, 49.5,
  150093. };
  150094. static long _vq_quantmap__44u7__p8_0[] = {
  150095. 9, 7, 5, 3, 1, 0, 2, 4,
  150096. 6, 8, 10,
  150097. };
  150098. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150099. _vq_quantthresh__44u7__p8_0,
  150100. _vq_quantmap__44u7__p8_0,
  150101. 11,
  150102. 11
  150103. };
  150104. static static_codebook _44u7__p8_0 = {
  150105. 2, 121,
  150106. _vq_lengthlist__44u7__p8_0,
  150107. 1, -524582912, 1618345984, 4, 0,
  150108. _vq_quantlist__44u7__p8_0,
  150109. NULL,
  150110. &_vq_auxt__44u7__p8_0,
  150111. NULL,
  150112. 0
  150113. };
  150114. static long _vq_quantlist__44u7__p8_1[] = {
  150115. 5,
  150116. 4,
  150117. 6,
  150118. 3,
  150119. 7,
  150120. 2,
  150121. 8,
  150122. 1,
  150123. 9,
  150124. 0,
  150125. 10,
  150126. };
  150127. static long _vq_lengthlist__44u7__p8_1[] = {
  150128. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150129. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150130. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150131. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150132. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150133. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150134. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150135. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150136. };
  150137. static float _vq_quantthresh__44u7__p8_1[] = {
  150138. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150139. 3.5, 4.5,
  150140. };
  150141. static long _vq_quantmap__44u7__p8_1[] = {
  150142. 9, 7, 5, 3, 1, 0, 2, 4,
  150143. 6, 8, 10,
  150144. };
  150145. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150146. _vq_quantthresh__44u7__p8_1,
  150147. _vq_quantmap__44u7__p8_1,
  150148. 11,
  150149. 11
  150150. };
  150151. static static_codebook _44u7__p8_1 = {
  150152. 2, 121,
  150153. _vq_lengthlist__44u7__p8_1,
  150154. 1, -531365888, 1611661312, 4, 0,
  150155. _vq_quantlist__44u7__p8_1,
  150156. NULL,
  150157. &_vq_auxt__44u7__p8_1,
  150158. NULL,
  150159. 0
  150160. };
  150161. static long _vq_quantlist__44u7__p9_0[] = {
  150162. 5,
  150163. 4,
  150164. 6,
  150165. 3,
  150166. 7,
  150167. 2,
  150168. 8,
  150169. 1,
  150170. 9,
  150171. 0,
  150172. 10,
  150173. };
  150174. static long _vq_lengthlist__44u7__p9_0[] = {
  150175. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150176. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150177. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150178. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150179. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150180. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150181. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150182. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150183. };
  150184. static float _vq_quantthresh__44u7__p9_0[] = {
  150185. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150186. 2229.5, 2866.5,
  150187. };
  150188. static long _vq_quantmap__44u7__p9_0[] = {
  150189. 9, 7, 5, 3, 1, 0, 2, 4,
  150190. 6, 8, 10,
  150191. };
  150192. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150193. _vq_quantthresh__44u7__p9_0,
  150194. _vq_quantmap__44u7__p9_0,
  150195. 11,
  150196. 11
  150197. };
  150198. static static_codebook _44u7__p9_0 = {
  150199. 2, 121,
  150200. _vq_lengthlist__44u7__p9_0,
  150201. 1, -512171520, 1630791680, 4, 0,
  150202. _vq_quantlist__44u7__p9_0,
  150203. NULL,
  150204. &_vq_auxt__44u7__p9_0,
  150205. NULL,
  150206. 0
  150207. };
  150208. static long _vq_quantlist__44u7__p9_1[] = {
  150209. 6,
  150210. 5,
  150211. 7,
  150212. 4,
  150213. 8,
  150214. 3,
  150215. 9,
  150216. 2,
  150217. 10,
  150218. 1,
  150219. 11,
  150220. 0,
  150221. 12,
  150222. };
  150223. static long _vq_lengthlist__44u7__p9_1[] = {
  150224. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150225. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150226. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150227. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150228. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150229. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150230. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150231. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150232. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150233. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150234. 15,15,15,15,17,17,16,17,16,
  150235. };
  150236. static float _vq_quantthresh__44u7__p9_1[] = {
  150237. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150238. 122.5, 171.5, 220.5, 269.5,
  150239. };
  150240. static long _vq_quantmap__44u7__p9_1[] = {
  150241. 11, 9, 7, 5, 3, 1, 0, 2,
  150242. 4, 6, 8, 10, 12,
  150243. };
  150244. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150245. _vq_quantthresh__44u7__p9_1,
  150246. _vq_quantmap__44u7__p9_1,
  150247. 13,
  150248. 13
  150249. };
  150250. static static_codebook _44u7__p9_1 = {
  150251. 2, 169,
  150252. _vq_lengthlist__44u7__p9_1,
  150253. 1, -518889472, 1622704128, 4, 0,
  150254. _vq_quantlist__44u7__p9_1,
  150255. NULL,
  150256. &_vq_auxt__44u7__p9_1,
  150257. NULL,
  150258. 0
  150259. };
  150260. static long _vq_quantlist__44u7__p9_2[] = {
  150261. 24,
  150262. 23,
  150263. 25,
  150264. 22,
  150265. 26,
  150266. 21,
  150267. 27,
  150268. 20,
  150269. 28,
  150270. 19,
  150271. 29,
  150272. 18,
  150273. 30,
  150274. 17,
  150275. 31,
  150276. 16,
  150277. 32,
  150278. 15,
  150279. 33,
  150280. 14,
  150281. 34,
  150282. 13,
  150283. 35,
  150284. 12,
  150285. 36,
  150286. 11,
  150287. 37,
  150288. 10,
  150289. 38,
  150290. 9,
  150291. 39,
  150292. 8,
  150293. 40,
  150294. 7,
  150295. 41,
  150296. 6,
  150297. 42,
  150298. 5,
  150299. 43,
  150300. 4,
  150301. 44,
  150302. 3,
  150303. 45,
  150304. 2,
  150305. 46,
  150306. 1,
  150307. 47,
  150308. 0,
  150309. 48,
  150310. };
  150311. static long _vq_lengthlist__44u7__p9_2[] = {
  150312. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150313. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150314. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150315. 8,
  150316. };
  150317. static float _vq_quantthresh__44u7__p9_2[] = {
  150318. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150319. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150320. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150321. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150322. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150323. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150324. };
  150325. static long _vq_quantmap__44u7__p9_2[] = {
  150326. 47, 45, 43, 41, 39, 37, 35, 33,
  150327. 31, 29, 27, 25, 23, 21, 19, 17,
  150328. 15, 13, 11, 9, 7, 5, 3, 1,
  150329. 0, 2, 4, 6, 8, 10, 12, 14,
  150330. 16, 18, 20, 22, 24, 26, 28, 30,
  150331. 32, 34, 36, 38, 40, 42, 44, 46,
  150332. 48,
  150333. };
  150334. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150335. _vq_quantthresh__44u7__p9_2,
  150336. _vq_quantmap__44u7__p9_2,
  150337. 49,
  150338. 49
  150339. };
  150340. static static_codebook _44u7__p9_2 = {
  150341. 1, 49,
  150342. _vq_lengthlist__44u7__p9_2,
  150343. 1, -526909440, 1611661312, 6, 0,
  150344. _vq_quantlist__44u7__p9_2,
  150345. NULL,
  150346. &_vq_auxt__44u7__p9_2,
  150347. NULL,
  150348. 0
  150349. };
  150350. static long _huff_lengthlist__44u7__short[] = {
  150351. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150352. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150353. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150354. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150355. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150356. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150357. 6, 8, 5, 9,
  150358. };
  150359. static static_codebook _huff_book__44u7__short = {
  150360. 2, 100,
  150361. _huff_lengthlist__44u7__short,
  150362. 0, 0, 0, 0, 0,
  150363. NULL,
  150364. NULL,
  150365. NULL,
  150366. NULL,
  150367. 0
  150368. };
  150369. static long _huff_lengthlist__44u8__long[] = {
  150370. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  150371. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  150372. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  150373. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  150374. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  150375. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  150376. 10, 8, 8, 9,
  150377. };
  150378. static static_codebook _huff_book__44u8__long = {
  150379. 2, 100,
  150380. _huff_lengthlist__44u8__long,
  150381. 0, 0, 0, 0, 0,
  150382. NULL,
  150383. NULL,
  150384. NULL,
  150385. NULL,
  150386. 0
  150387. };
  150388. static long _huff_lengthlist__44u8__short[] = {
  150389. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  150390. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  150391. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  150392. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  150393. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  150394. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  150395. 10,10,15,17,
  150396. };
  150397. static static_codebook _huff_book__44u8__short = {
  150398. 2, 100,
  150399. _huff_lengthlist__44u8__short,
  150400. 0, 0, 0, 0, 0,
  150401. NULL,
  150402. NULL,
  150403. NULL,
  150404. NULL,
  150405. 0
  150406. };
  150407. static long _vq_quantlist__44u8_p1_0[] = {
  150408. 1,
  150409. 0,
  150410. 2,
  150411. };
  150412. static long _vq_lengthlist__44u8_p1_0[] = {
  150413. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  150414. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  150415. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  150416. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  150417. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  150418. 10,
  150419. };
  150420. static float _vq_quantthresh__44u8_p1_0[] = {
  150421. -0.5, 0.5,
  150422. };
  150423. static long _vq_quantmap__44u8_p1_0[] = {
  150424. 1, 0, 2,
  150425. };
  150426. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  150427. _vq_quantthresh__44u8_p1_0,
  150428. _vq_quantmap__44u8_p1_0,
  150429. 3,
  150430. 3
  150431. };
  150432. static static_codebook _44u8_p1_0 = {
  150433. 4, 81,
  150434. _vq_lengthlist__44u8_p1_0,
  150435. 1, -535822336, 1611661312, 2, 0,
  150436. _vq_quantlist__44u8_p1_0,
  150437. NULL,
  150438. &_vq_auxt__44u8_p1_0,
  150439. NULL,
  150440. 0
  150441. };
  150442. static long _vq_quantlist__44u8_p2_0[] = {
  150443. 2,
  150444. 1,
  150445. 3,
  150446. 0,
  150447. 4,
  150448. };
  150449. static long _vq_lengthlist__44u8_p2_0[] = {
  150450. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150451. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  150452. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  150453. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  150454. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  150455. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  150456. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150457. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  150458. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  150459. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  150460. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  150461. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  150462. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  150463. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  150464. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  150465. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  150466. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  150467. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  150468. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  150469. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  150470. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  150471. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  150472. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  150473. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150474. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  150475. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  150476. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  150477. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  150478. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  150479. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  150480. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  150481. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150482. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  150483. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  150484. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  150485. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  150486. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  150487. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  150488. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  150489. 14,
  150490. };
  150491. static float _vq_quantthresh__44u8_p2_0[] = {
  150492. -1.5, -0.5, 0.5, 1.5,
  150493. };
  150494. static long _vq_quantmap__44u8_p2_0[] = {
  150495. 3, 1, 0, 2, 4,
  150496. };
  150497. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  150498. _vq_quantthresh__44u8_p2_0,
  150499. _vq_quantmap__44u8_p2_0,
  150500. 5,
  150501. 5
  150502. };
  150503. static static_codebook _44u8_p2_0 = {
  150504. 4, 625,
  150505. _vq_lengthlist__44u8_p2_0,
  150506. 1, -533725184, 1611661312, 3, 0,
  150507. _vq_quantlist__44u8_p2_0,
  150508. NULL,
  150509. &_vq_auxt__44u8_p2_0,
  150510. NULL,
  150511. 0
  150512. };
  150513. static long _vq_quantlist__44u8_p3_0[] = {
  150514. 4,
  150515. 3,
  150516. 5,
  150517. 2,
  150518. 6,
  150519. 1,
  150520. 7,
  150521. 0,
  150522. 8,
  150523. };
  150524. static long _vq_lengthlist__44u8_p3_0[] = {
  150525. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150526. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150527. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  150528. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  150529. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  150530. 12,
  150531. };
  150532. static float _vq_quantthresh__44u8_p3_0[] = {
  150533. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150534. };
  150535. static long _vq_quantmap__44u8_p3_0[] = {
  150536. 7, 5, 3, 1, 0, 2, 4, 6,
  150537. 8,
  150538. };
  150539. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  150540. _vq_quantthresh__44u8_p3_0,
  150541. _vq_quantmap__44u8_p3_0,
  150542. 9,
  150543. 9
  150544. };
  150545. static static_codebook _44u8_p3_0 = {
  150546. 2, 81,
  150547. _vq_lengthlist__44u8_p3_0,
  150548. 1, -531628032, 1611661312, 4, 0,
  150549. _vq_quantlist__44u8_p3_0,
  150550. NULL,
  150551. &_vq_auxt__44u8_p3_0,
  150552. NULL,
  150553. 0
  150554. };
  150555. static long _vq_quantlist__44u8_p4_0[] = {
  150556. 8,
  150557. 7,
  150558. 9,
  150559. 6,
  150560. 10,
  150561. 5,
  150562. 11,
  150563. 4,
  150564. 12,
  150565. 3,
  150566. 13,
  150567. 2,
  150568. 14,
  150569. 1,
  150570. 15,
  150571. 0,
  150572. 16,
  150573. };
  150574. static long _vq_lengthlist__44u8_p4_0[] = {
  150575. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  150576. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  150577. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  150578. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  150579. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  150580. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  150581. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  150582. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  150583. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  150584. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  150585. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  150586. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  150587. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  150588. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  150589. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  150590. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  150591. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  150592. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  150593. 14,
  150594. };
  150595. static float _vq_quantthresh__44u8_p4_0[] = {
  150596. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150597. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150598. };
  150599. static long _vq_quantmap__44u8_p4_0[] = {
  150600. 15, 13, 11, 9, 7, 5, 3, 1,
  150601. 0, 2, 4, 6, 8, 10, 12, 14,
  150602. 16,
  150603. };
  150604. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  150605. _vq_quantthresh__44u8_p4_0,
  150606. _vq_quantmap__44u8_p4_0,
  150607. 17,
  150608. 17
  150609. };
  150610. static static_codebook _44u8_p4_0 = {
  150611. 2, 289,
  150612. _vq_lengthlist__44u8_p4_0,
  150613. 1, -529530880, 1611661312, 5, 0,
  150614. _vq_quantlist__44u8_p4_0,
  150615. NULL,
  150616. &_vq_auxt__44u8_p4_0,
  150617. NULL,
  150618. 0
  150619. };
  150620. static long _vq_quantlist__44u8_p5_0[] = {
  150621. 1,
  150622. 0,
  150623. 2,
  150624. };
  150625. static long _vq_lengthlist__44u8_p5_0[] = {
  150626. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  150627. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  150628. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  150629. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  150630. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  150631. 10,
  150632. };
  150633. static float _vq_quantthresh__44u8_p5_0[] = {
  150634. -5.5, 5.5,
  150635. };
  150636. static long _vq_quantmap__44u8_p5_0[] = {
  150637. 1, 0, 2,
  150638. };
  150639. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  150640. _vq_quantthresh__44u8_p5_0,
  150641. _vq_quantmap__44u8_p5_0,
  150642. 3,
  150643. 3
  150644. };
  150645. static static_codebook _44u8_p5_0 = {
  150646. 4, 81,
  150647. _vq_lengthlist__44u8_p5_0,
  150648. 1, -529137664, 1618345984, 2, 0,
  150649. _vq_quantlist__44u8_p5_0,
  150650. NULL,
  150651. &_vq_auxt__44u8_p5_0,
  150652. NULL,
  150653. 0
  150654. };
  150655. static long _vq_quantlist__44u8_p5_1[] = {
  150656. 5,
  150657. 4,
  150658. 6,
  150659. 3,
  150660. 7,
  150661. 2,
  150662. 8,
  150663. 1,
  150664. 9,
  150665. 0,
  150666. 10,
  150667. };
  150668. static long _vq_lengthlist__44u8_p5_1[] = {
  150669. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  150670. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  150671. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  150672. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  150673. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  150674. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150675. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  150676. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  150677. };
  150678. static float _vq_quantthresh__44u8_p5_1[] = {
  150679. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150680. 3.5, 4.5,
  150681. };
  150682. static long _vq_quantmap__44u8_p5_1[] = {
  150683. 9, 7, 5, 3, 1, 0, 2, 4,
  150684. 6, 8, 10,
  150685. };
  150686. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  150687. _vq_quantthresh__44u8_p5_1,
  150688. _vq_quantmap__44u8_p5_1,
  150689. 11,
  150690. 11
  150691. };
  150692. static static_codebook _44u8_p5_1 = {
  150693. 2, 121,
  150694. _vq_lengthlist__44u8_p5_1,
  150695. 1, -531365888, 1611661312, 4, 0,
  150696. _vq_quantlist__44u8_p5_1,
  150697. NULL,
  150698. &_vq_auxt__44u8_p5_1,
  150699. NULL,
  150700. 0
  150701. };
  150702. static long _vq_quantlist__44u8_p6_0[] = {
  150703. 6,
  150704. 5,
  150705. 7,
  150706. 4,
  150707. 8,
  150708. 3,
  150709. 9,
  150710. 2,
  150711. 10,
  150712. 1,
  150713. 11,
  150714. 0,
  150715. 12,
  150716. };
  150717. static long _vq_lengthlist__44u8_p6_0[] = {
  150718. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  150719. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  150720. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  150721. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  150722. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  150723. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  150724. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  150725. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  150726. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  150727. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  150728. 11,11,11,11,11,12,11,12,12,
  150729. };
  150730. static float _vq_quantthresh__44u8_p6_0[] = {
  150731. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  150732. 12.5, 17.5, 22.5, 27.5,
  150733. };
  150734. static long _vq_quantmap__44u8_p6_0[] = {
  150735. 11, 9, 7, 5, 3, 1, 0, 2,
  150736. 4, 6, 8, 10, 12,
  150737. };
  150738. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  150739. _vq_quantthresh__44u8_p6_0,
  150740. _vq_quantmap__44u8_p6_0,
  150741. 13,
  150742. 13
  150743. };
  150744. static static_codebook _44u8_p6_0 = {
  150745. 2, 169,
  150746. _vq_lengthlist__44u8_p6_0,
  150747. 1, -526516224, 1616117760, 4, 0,
  150748. _vq_quantlist__44u8_p6_0,
  150749. NULL,
  150750. &_vq_auxt__44u8_p6_0,
  150751. NULL,
  150752. 0
  150753. };
  150754. static long _vq_quantlist__44u8_p6_1[] = {
  150755. 2,
  150756. 1,
  150757. 3,
  150758. 0,
  150759. 4,
  150760. };
  150761. static long _vq_lengthlist__44u8_p6_1[] = {
  150762. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  150763. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  150764. };
  150765. static float _vq_quantthresh__44u8_p6_1[] = {
  150766. -1.5, -0.5, 0.5, 1.5,
  150767. };
  150768. static long _vq_quantmap__44u8_p6_1[] = {
  150769. 3, 1, 0, 2, 4,
  150770. };
  150771. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  150772. _vq_quantthresh__44u8_p6_1,
  150773. _vq_quantmap__44u8_p6_1,
  150774. 5,
  150775. 5
  150776. };
  150777. static static_codebook _44u8_p6_1 = {
  150778. 2, 25,
  150779. _vq_lengthlist__44u8_p6_1,
  150780. 1, -533725184, 1611661312, 3, 0,
  150781. _vq_quantlist__44u8_p6_1,
  150782. NULL,
  150783. &_vq_auxt__44u8_p6_1,
  150784. NULL,
  150785. 0
  150786. };
  150787. static long _vq_quantlist__44u8_p7_0[] = {
  150788. 6,
  150789. 5,
  150790. 7,
  150791. 4,
  150792. 8,
  150793. 3,
  150794. 9,
  150795. 2,
  150796. 10,
  150797. 1,
  150798. 11,
  150799. 0,
  150800. 12,
  150801. };
  150802. static long _vq_lengthlist__44u8_p7_0[] = {
  150803. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  150804. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  150805. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  150806. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  150807. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  150808. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  150809. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  150810. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  150811. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  150812. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  150813. 13,13,14,14,14,15,15,15,16,
  150814. };
  150815. static float _vq_quantthresh__44u8_p7_0[] = {
  150816. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  150817. 27.5, 38.5, 49.5, 60.5,
  150818. };
  150819. static long _vq_quantmap__44u8_p7_0[] = {
  150820. 11, 9, 7, 5, 3, 1, 0, 2,
  150821. 4, 6, 8, 10, 12,
  150822. };
  150823. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  150824. _vq_quantthresh__44u8_p7_0,
  150825. _vq_quantmap__44u8_p7_0,
  150826. 13,
  150827. 13
  150828. };
  150829. static static_codebook _44u8_p7_0 = {
  150830. 2, 169,
  150831. _vq_lengthlist__44u8_p7_0,
  150832. 1, -523206656, 1618345984, 4, 0,
  150833. _vq_quantlist__44u8_p7_0,
  150834. NULL,
  150835. &_vq_auxt__44u8_p7_0,
  150836. NULL,
  150837. 0
  150838. };
  150839. static long _vq_quantlist__44u8_p7_1[] = {
  150840. 5,
  150841. 4,
  150842. 6,
  150843. 3,
  150844. 7,
  150845. 2,
  150846. 8,
  150847. 1,
  150848. 9,
  150849. 0,
  150850. 10,
  150851. };
  150852. static long _vq_lengthlist__44u8_p7_1[] = {
  150853. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150854. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  150855. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150856. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  150857. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  150858. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150859. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150860. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150861. };
  150862. static float _vq_quantthresh__44u8_p7_1[] = {
  150863. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150864. 3.5, 4.5,
  150865. };
  150866. static long _vq_quantmap__44u8_p7_1[] = {
  150867. 9, 7, 5, 3, 1, 0, 2, 4,
  150868. 6, 8, 10,
  150869. };
  150870. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  150871. _vq_quantthresh__44u8_p7_1,
  150872. _vq_quantmap__44u8_p7_1,
  150873. 11,
  150874. 11
  150875. };
  150876. static static_codebook _44u8_p7_1 = {
  150877. 2, 121,
  150878. _vq_lengthlist__44u8_p7_1,
  150879. 1, -531365888, 1611661312, 4, 0,
  150880. _vq_quantlist__44u8_p7_1,
  150881. NULL,
  150882. &_vq_auxt__44u8_p7_1,
  150883. NULL,
  150884. 0
  150885. };
  150886. static long _vq_quantlist__44u8_p8_0[] = {
  150887. 7,
  150888. 6,
  150889. 8,
  150890. 5,
  150891. 9,
  150892. 4,
  150893. 10,
  150894. 3,
  150895. 11,
  150896. 2,
  150897. 12,
  150898. 1,
  150899. 13,
  150900. 0,
  150901. 14,
  150902. };
  150903. static long _vq_lengthlist__44u8_p8_0[] = {
  150904. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  150905. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  150906. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  150907. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  150908. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  150909. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  150910. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  150911. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  150912. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  150913. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  150914. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  150915. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  150916. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  150917. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  150918. 17,
  150919. };
  150920. static float _vq_quantthresh__44u8_p8_0[] = {
  150921. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  150922. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  150923. };
  150924. static long _vq_quantmap__44u8_p8_0[] = {
  150925. 13, 11, 9, 7, 5, 3, 1, 0,
  150926. 2, 4, 6, 8, 10, 12, 14,
  150927. };
  150928. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  150929. _vq_quantthresh__44u8_p8_0,
  150930. _vq_quantmap__44u8_p8_0,
  150931. 15,
  150932. 15
  150933. };
  150934. static static_codebook _44u8_p8_0 = {
  150935. 2, 225,
  150936. _vq_lengthlist__44u8_p8_0,
  150937. 1, -520986624, 1620377600, 4, 0,
  150938. _vq_quantlist__44u8_p8_0,
  150939. NULL,
  150940. &_vq_auxt__44u8_p8_0,
  150941. NULL,
  150942. 0
  150943. };
  150944. static long _vq_quantlist__44u8_p8_1[] = {
  150945. 10,
  150946. 9,
  150947. 11,
  150948. 8,
  150949. 12,
  150950. 7,
  150951. 13,
  150952. 6,
  150953. 14,
  150954. 5,
  150955. 15,
  150956. 4,
  150957. 16,
  150958. 3,
  150959. 17,
  150960. 2,
  150961. 18,
  150962. 1,
  150963. 19,
  150964. 0,
  150965. 20,
  150966. };
  150967. static long _vq_lengthlist__44u8_p8_1[] = {
  150968. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  150969. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  150970. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  150971. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  150972. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150973. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150974. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  150975. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  150976. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  150977. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  150978. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  150979. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  150980. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  150981. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  150982. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  150983. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  150984. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  150985. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  150986. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  150987. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  150988. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150989. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  150990. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  150991. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  150992. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  150993. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  150994. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  150995. 10,10,10,10,10,10,10,10,10,
  150996. };
  150997. static float _vq_quantthresh__44u8_p8_1[] = {
  150998. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  150999. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151000. 6.5, 7.5, 8.5, 9.5,
  151001. };
  151002. static long _vq_quantmap__44u8_p8_1[] = {
  151003. 19, 17, 15, 13, 11, 9, 7, 5,
  151004. 3, 1, 0, 2, 4, 6, 8, 10,
  151005. 12, 14, 16, 18, 20,
  151006. };
  151007. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151008. _vq_quantthresh__44u8_p8_1,
  151009. _vq_quantmap__44u8_p8_1,
  151010. 21,
  151011. 21
  151012. };
  151013. static static_codebook _44u8_p8_1 = {
  151014. 2, 441,
  151015. _vq_lengthlist__44u8_p8_1,
  151016. 1, -529268736, 1611661312, 5, 0,
  151017. _vq_quantlist__44u8_p8_1,
  151018. NULL,
  151019. &_vq_auxt__44u8_p8_1,
  151020. NULL,
  151021. 0
  151022. };
  151023. static long _vq_quantlist__44u8_p9_0[] = {
  151024. 4,
  151025. 3,
  151026. 5,
  151027. 2,
  151028. 6,
  151029. 1,
  151030. 7,
  151031. 0,
  151032. 8,
  151033. };
  151034. static long _vq_lengthlist__44u8_p9_0[] = {
  151035. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151036. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151037. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151038. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151039. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151040. 8,
  151041. };
  151042. static float _vq_quantthresh__44u8_p9_0[] = {
  151043. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151044. };
  151045. static long _vq_quantmap__44u8_p9_0[] = {
  151046. 7, 5, 3, 1, 0, 2, 4, 6,
  151047. 8,
  151048. };
  151049. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151050. _vq_quantthresh__44u8_p9_0,
  151051. _vq_quantmap__44u8_p9_0,
  151052. 9,
  151053. 9
  151054. };
  151055. static static_codebook _44u8_p9_0 = {
  151056. 2, 81,
  151057. _vq_lengthlist__44u8_p9_0,
  151058. 1, -511895552, 1631393792, 4, 0,
  151059. _vq_quantlist__44u8_p9_0,
  151060. NULL,
  151061. &_vq_auxt__44u8_p9_0,
  151062. NULL,
  151063. 0
  151064. };
  151065. static long _vq_quantlist__44u8_p9_1[] = {
  151066. 9,
  151067. 8,
  151068. 10,
  151069. 7,
  151070. 11,
  151071. 6,
  151072. 12,
  151073. 5,
  151074. 13,
  151075. 4,
  151076. 14,
  151077. 3,
  151078. 15,
  151079. 2,
  151080. 16,
  151081. 1,
  151082. 17,
  151083. 0,
  151084. 18,
  151085. };
  151086. static long _vq_lengthlist__44u8_p9_1[] = {
  151087. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151088. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151089. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151090. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151091. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151092. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151093. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151094. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151095. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151096. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151097. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151098. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151099. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151100. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151101. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151102. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151103. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151104. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151105. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151106. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151107. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151108. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151109. 16,15,16,16,16,16,16,16,16,
  151110. };
  151111. static float _vq_quantthresh__44u8_p9_1[] = {
  151112. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151113. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151114. 367.5, 416.5,
  151115. };
  151116. static long _vq_quantmap__44u8_p9_1[] = {
  151117. 17, 15, 13, 11, 9, 7, 5, 3,
  151118. 1, 0, 2, 4, 6, 8, 10, 12,
  151119. 14, 16, 18,
  151120. };
  151121. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151122. _vq_quantthresh__44u8_p9_1,
  151123. _vq_quantmap__44u8_p9_1,
  151124. 19,
  151125. 19
  151126. };
  151127. static static_codebook _44u8_p9_1 = {
  151128. 2, 361,
  151129. _vq_lengthlist__44u8_p9_1,
  151130. 1, -518287360, 1622704128, 5, 0,
  151131. _vq_quantlist__44u8_p9_1,
  151132. NULL,
  151133. &_vq_auxt__44u8_p9_1,
  151134. NULL,
  151135. 0
  151136. };
  151137. static long _vq_quantlist__44u8_p9_2[] = {
  151138. 24,
  151139. 23,
  151140. 25,
  151141. 22,
  151142. 26,
  151143. 21,
  151144. 27,
  151145. 20,
  151146. 28,
  151147. 19,
  151148. 29,
  151149. 18,
  151150. 30,
  151151. 17,
  151152. 31,
  151153. 16,
  151154. 32,
  151155. 15,
  151156. 33,
  151157. 14,
  151158. 34,
  151159. 13,
  151160. 35,
  151161. 12,
  151162. 36,
  151163. 11,
  151164. 37,
  151165. 10,
  151166. 38,
  151167. 9,
  151168. 39,
  151169. 8,
  151170. 40,
  151171. 7,
  151172. 41,
  151173. 6,
  151174. 42,
  151175. 5,
  151176. 43,
  151177. 4,
  151178. 44,
  151179. 3,
  151180. 45,
  151181. 2,
  151182. 46,
  151183. 1,
  151184. 47,
  151185. 0,
  151186. 48,
  151187. };
  151188. static long _vq_lengthlist__44u8_p9_2[] = {
  151189. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151190. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151191. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151192. 7,
  151193. };
  151194. static float _vq_quantthresh__44u8_p9_2[] = {
  151195. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151196. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151197. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151198. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151199. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151200. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151201. };
  151202. static long _vq_quantmap__44u8_p9_2[] = {
  151203. 47, 45, 43, 41, 39, 37, 35, 33,
  151204. 31, 29, 27, 25, 23, 21, 19, 17,
  151205. 15, 13, 11, 9, 7, 5, 3, 1,
  151206. 0, 2, 4, 6, 8, 10, 12, 14,
  151207. 16, 18, 20, 22, 24, 26, 28, 30,
  151208. 32, 34, 36, 38, 40, 42, 44, 46,
  151209. 48,
  151210. };
  151211. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151212. _vq_quantthresh__44u8_p9_2,
  151213. _vq_quantmap__44u8_p9_2,
  151214. 49,
  151215. 49
  151216. };
  151217. static static_codebook _44u8_p9_2 = {
  151218. 1, 49,
  151219. _vq_lengthlist__44u8_p9_2,
  151220. 1, -526909440, 1611661312, 6, 0,
  151221. _vq_quantlist__44u8_p9_2,
  151222. NULL,
  151223. &_vq_auxt__44u8_p9_2,
  151224. NULL,
  151225. 0
  151226. };
  151227. static long _huff_lengthlist__44u9__long[] = {
  151228. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151229. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151230. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151231. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151232. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151233. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151234. 10, 8, 8, 9,
  151235. };
  151236. static static_codebook _huff_book__44u9__long = {
  151237. 2, 100,
  151238. _huff_lengthlist__44u9__long,
  151239. 0, 0, 0, 0, 0,
  151240. NULL,
  151241. NULL,
  151242. NULL,
  151243. NULL,
  151244. 0
  151245. };
  151246. static long _huff_lengthlist__44u9__short[] = {
  151247. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151248. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151249. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151250. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151251. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151252. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151253. 9, 9,12,15,
  151254. };
  151255. static static_codebook _huff_book__44u9__short = {
  151256. 2, 100,
  151257. _huff_lengthlist__44u9__short,
  151258. 0, 0, 0, 0, 0,
  151259. NULL,
  151260. NULL,
  151261. NULL,
  151262. NULL,
  151263. 0
  151264. };
  151265. static long _vq_quantlist__44u9_p1_0[] = {
  151266. 1,
  151267. 0,
  151268. 2,
  151269. };
  151270. static long _vq_lengthlist__44u9_p1_0[] = {
  151271. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  151272. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  151273. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  151274. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  151275. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  151276. 10,
  151277. };
  151278. static float _vq_quantthresh__44u9_p1_0[] = {
  151279. -0.5, 0.5,
  151280. };
  151281. static long _vq_quantmap__44u9_p1_0[] = {
  151282. 1, 0, 2,
  151283. };
  151284. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  151285. _vq_quantthresh__44u9_p1_0,
  151286. _vq_quantmap__44u9_p1_0,
  151287. 3,
  151288. 3
  151289. };
  151290. static static_codebook _44u9_p1_0 = {
  151291. 4, 81,
  151292. _vq_lengthlist__44u9_p1_0,
  151293. 1, -535822336, 1611661312, 2, 0,
  151294. _vq_quantlist__44u9_p1_0,
  151295. NULL,
  151296. &_vq_auxt__44u9_p1_0,
  151297. NULL,
  151298. 0
  151299. };
  151300. static long _vq_quantlist__44u9_p2_0[] = {
  151301. 2,
  151302. 1,
  151303. 3,
  151304. 0,
  151305. 4,
  151306. };
  151307. static long _vq_lengthlist__44u9_p2_0[] = {
  151308. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151309. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151310. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151311. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151312. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151313. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151314. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151315. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151316. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151317. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151318. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151319. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151320. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151321. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151322. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151323. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151324. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151325. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151326. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151327. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151328. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151329. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151330. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151331. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151332. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151333. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151334. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151335. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151336. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151337. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151338. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151339. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151340. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151341. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151342. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151343. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151344. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151345. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151346. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151347. 14,
  151348. };
  151349. static float _vq_quantthresh__44u9_p2_0[] = {
  151350. -1.5, -0.5, 0.5, 1.5,
  151351. };
  151352. static long _vq_quantmap__44u9_p2_0[] = {
  151353. 3, 1, 0, 2, 4,
  151354. };
  151355. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151356. _vq_quantthresh__44u9_p2_0,
  151357. _vq_quantmap__44u9_p2_0,
  151358. 5,
  151359. 5
  151360. };
  151361. static static_codebook _44u9_p2_0 = {
  151362. 4, 625,
  151363. _vq_lengthlist__44u9_p2_0,
  151364. 1, -533725184, 1611661312, 3, 0,
  151365. _vq_quantlist__44u9_p2_0,
  151366. NULL,
  151367. &_vq_auxt__44u9_p2_0,
  151368. NULL,
  151369. 0
  151370. };
  151371. static long _vq_quantlist__44u9_p3_0[] = {
  151372. 4,
  151373. 3,
  151374. 5,
  151375. 2,
  151376. 6,
  151377. 1,
  151378. 7,
  151379. 0,
  151380. 8,
  151381. };
  151382. static long _vq_lengthlist__44u9_p3_0[] = {
  151383. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  151384. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151385. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  151386. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  151387. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  151388. 11,
  151389. };
  151390. static float _vq_quantthresh__44u9_p3_0[] = {
  151391. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151392. };
  151393. static long _vq_quantmap__44u9_p3_0[] = {
  151394. 7, 5, 3, 1, 0, 2, 4, 6,
  151395. 8,
  151396. };
  151397. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  151398. _vq_quantthresh__44u9_p3_0,
  151399. _vq_quantmap__44u9_p3_0,
  151400. 9,
  151401. 9
  151402. };
  151403. static static_codebook _44u9_p3_0 = {
  151404. 2, 81,
  151405. _vq_lengthlist__44u9_p3_0,
  151406. 1, -531628032, 1611661312, 4, 0,
  151407. _vq_quantlist__44u9_p3_0,
  151408. NULL,
  151409. &_vq_auxt__44u9_p3_0,
  151410. NULL,
  151411. 0
  151412. };
  151413. static long _vq_quantlist__44u9_p4_0[] = {
  151414. 8,
  151415. 7,
  151416. 9,
  151417. 6,
  151418. 10,
  151419. 5,
  151420. 11,
  151421. 4,
  151422. 12,
  151423. 3,
  151424. 13,
  151425. 2,
  151426. 14,
  151427. 1,
  151428. 15,
  151429. 0,
  151430. 16,
  151431. };
  151432. static long _vq_lengthlist__44u9_p4_0[] = {
  151433. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  151434. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  151435. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  151436. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  151437. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  151438. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  151439. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  151440. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  151441. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  151442. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  151443. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  151444. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  151445. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  151446. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  151447. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  151448. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  151449. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  151450. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  151451. 14,
  151452. };
  151453. static float _vq_quantthresh__44u9_p4_0[] = {
  151454. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151455. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151456. };
  151457. static long _vq_quantmap__44u9_p4_0[] = {
  151458. 15, 13, 11, 9, 7, 5, 3, 1,
  151459. 0, 2, 4, 6, 8, 10, 12, 14,
  151460. 16,
  151461. };
  151462. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  151463. _vq_quantthresh__44u9_p4_0,
  151464. _vq_quantmap__44u9_p4_0,
  151465. 17,
  151466. 17
  151467. };
  151468. static static_codebook _44u9_p4_0 = {
  151469. 2, 289,
  151470. _vq_lengthlist__44u9_p4_0,
  151471. 1, -529530880, 1611661312, 5, 0,
  151472. _vq_quantlist__44u9_p4_0,
  151473. NULL,
  151474. &_vq_auxt__44u9_p4_0,
  151475. NULL,
  151476. 0
  151477. };
  151478. static long _vq_quantlist__44u9_p5_0[] = {
  151479. 1,
  151480. 0,
  151481. 2,
  151482. };
  151483. static long _vq_lengthlist__44u9_p5_0[] = {
  151484. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151485. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151486. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  151487. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151488. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151489. 10,
  151490. };
  151491. static float _vq_quantthresh__44u9_p5_0[] = {
  151492. -5.5, 5.5,
  151493. };
  151494. static long _vq_quantmap__44u9_p5_0[] = {
  151495. 1, 0, 2,
  151496. };
  151497. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  151498. _vq_quantthresh__44u9_p5_0,
  151499. _vq_quantmap__44u9_p5_0,
  151500. 3,
  151501. 3
  151502. };
  151503. static static_codebook _44u9_p5_0 = {
  151504. 4, 81,
  151505. _vq_lengthlist__44u9_p5_0,
  151506. 1, -529137664, 1618345984, 2, 0,
  151507. _vq_quantlist__44u9_p5_0,
  151508. NULL,
  151509. &_vq_auxt__44u9_p5_0,
  151510. NULL,
  151511. 0
  151512. };
  151513. static long _vq_quantlist__44u9_p5_1[] = {
  151514. 5,
  151515. 4,
  151516. 6,
  151517. 3,
  151518. 7,
  151519. 2,
  151520. 8,
  151521. 1,
  151522. 9,
  151523. 0,
  151524. 10,
  151525. };
  151526. static long _vq_lengthlist__44u9_p5_1[] = {
  151527. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  151528. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  151529. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  151530. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  151531. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  151532. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  151533. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  151534. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  151535. };
  151536. static float _vq_quantthresh__44u9_p5_1[] = {
  151537. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151538. 3.5, 4.5,
  151539. };
  151540. static long _vq_quantmap__44u9_p5_1[] = {
  151541. 9, 7, 5, 3, 1, 0, 2, 4,
  151542. 6, 8, 10,
  151543. };
  151544. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  151545. _vq_quantthresh__44u9_p5_1,
  151546. _vq_quantmap__44u9_p5_1,
  151547. 11,
  151548. 11
  151549. };
  151550. static static_codebook _44u9_p5_1 = {
  151551. 2, 121,
  151552. _vq_lengthlist__44u9_p5_1,
  151553. 1, -531365888, 1611661312, 4, 0,
  151554. _vq_quantlist__44u9_p5_1,
  151555. NULL,
  151556. &_vq_auxt__44u9_p5_1,
  151557. NULL,
  151558. 0
  151559. };
  151560. static long _vq_quantlist__44u9_p6_0[] = {
  151561. 6,
  151562. 5,
  151563. 7,
  151564. 4,
  151565. 8,
  151566. 3,
  151567. 9,
  151568. 2,
  151569. 10,
  151570. 1,
  151571. 11,
  151572. 0,
  151573. 12,
  151574. };
  151575. static long _vq_lengthlist__44u9_p6_0[] = {
  151576. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151577. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  151578. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151579. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  151580. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  151581. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151582. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151583. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  151584. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  151585. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151586. 10,11,11,11,11,12,11,12,12,
  151587. };
  151588. static float _vq_quantthresh__44u9_p6_0[] = {
  151589. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151590. 12.5, 17.5, 22.5, 27.5,
  151591. };
  151592. static long _vq_quantmap__44u9_p6_0[] = {
  151593. 11, 9, 7, 5, 3, 1, 0, 2,
  151594. 4, 6, 8, 10, 12,
  151595. };
  151596. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  151597. _vq_quantthresh__44u9_p6_0,
  151598. _vq_quantmap__44u9_p6_0,
  151599. 13,
  151600. 13
  151601. };
  151602. static static_codebook _44u9_p6_0 = {
  151603. 2, 169,
  151604. _vq_lengthlist__44u9_p6_0,
  151605. 1, -526516224, 1616117760, 4, 0,
  151606. _vq_quantlist__44u9_p6_0,
  151607. NULL,
  151608. &_vq_auxt__44u9_p6_0,
  151609. NULL,
  151610. 0
  151611. };
  151612. static long _vq_quantlist__44u9_p6_1[] = {
  151613. 2,
  151614. 1,
  151615. 3,
  151616. 0,
  151617. 4,
  151618. };
  151619. static long _vq_lengthlist__44u9_p6_1[] = {
  151620. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  151621. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151622. };
  151623. static float _vq_quantthresh__44u9_p6_1[] = {
  151624. -1.5, -0.5, 0.5, 1.5,
  151625. };
  151626. static long _vq_quantmap__44u9_p6_1[] = {
  151627. 3, 1, 0, 2, 4,
  151628. };
  151629. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  151630. _vq_quantthresh__44u9_p6_1,
  151631. _vq_quantmap__44u9_p6_1,
  151632. 5,
  151633. 5
  151634. };
  151635. static static_codebook _44u9_p6_1 = {
  151636. 2, 25,
  151637. _vq_lengthlist__44u9_p6_1,
  151638. 1, -533725184, 1611661312, 3, 0,
  151639. _vq_quantlist__44u9_p6_1,
  151640. NULL,
  151641. &_vq_auxt__44u9_p6_1,
  151642. NULL,
  151643. 0
  151644. };
  151645. static long _vq_quantlist__44u9_p7_0[] = {
  151646. 6,
  151647. 5,
  151648. 7,
  151649. 4,
  151650. 8,
  151651. 3,
  151652. 9,
  151653. 2,
  151654. 10,
  151655. 1,
  151656. 11,
  151657. 0,
  151658. 12,
  151659. };
  151660. static long _vq_lengthlist__44u9_p7_0[] = {
  151661. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  151662. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  151663. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  151664. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  151665. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151666. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151667. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  151668. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  151669. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  151670. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  151671. 12,13,13,14,14,14,15,15,15,
  151672. };
  151673. static float _vq_quantthresh__44u9_p7_0[] = {
  151674. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151675. 27.5, 38.5, 49.5, 60.5,
  151676. };
  151677. static long _vq_quantmap__44u9_p7_0[] = {
  151678. 11, 9, 7, 5, 3, 1, 0, 2,
  151679. 4, 6, 8, 10, 12,
  151680. };
  151681. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  151682. _vq_quantthresh__44u9_p7_0,
  151683. _vq_quantmap__44u9_p7_0,
  151684. 13,
  151685. 13
  151686. };
  151687. static static_codebook _44u9_p7_0 = {
  151688. 2, 169,
  151689. _vq_lengthlist__44u9_p7_0,
  151690. 1, -523206656, 1618345984, 4, 0,
  151691. _vq_quantlist__44u9_p7_0,
  151692. NULL,
  151693. &_vq_auxt__44u9_p7_0,
  151694. NULL,
  151695. 0
  151696. };
  151697. static long _vq_quantlist__44u9_p7_1[] = {
  151698. 5,
  151699. 4,
  151700. 6,
  151701. 3,
  151702. 7,
  151703. 2,
  151704. 8,
  151705. 1,
  151706. 9,
  151707. 0,
  151708. 10,
  151709. };
  151710. static long _vq_lengthlist__44u9_p7_1[] = {
  151711. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  151712. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151713. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  151714. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151715. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151716. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151717. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  151718. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151719. };
  151720. static float _vq_quantthresh__44u9_p7_1[] = {
  151721. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151722. 3.5, 4.5,
  151723. };
  151724. static long _vq_quantmap__44u9_p7_1[] = {
  151725. 9, 7, 5, 3, 1, 0, 2, 4,
  151726. 6, 8, 10,
  151727. };
  151728. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  151729. _vq_quantthresh__44u9_p7_1,
  151730. _vq_quantmap__44u9_p7_1,
  151731. 11,
  151732. 11
  151733. };
  151734. static static_codebook _44u9_p7_1 = {
  151735. 2, 121,
  151736. _vq_lengthlist__44u9_p7_1,
  151737. 1, -531365888, 1611661312, 4, 0,
  151738. _vq_quantlist__44u9_p7_1,
  151739. NULL,
  151740. &_vq_auxt__44u9_p7_1,
  151741. NULL,
  151742. 0
  151743. };
  151744. static long _vq_quantlist__44u9_p8_0[] = {
  151745. 7,
  151746. 6,
  151747. 8,
  151748. 5,
  151749. 9,
  151750. 4,
  151751. 10,
  151752. 3,
  151753. 11,
  151754. 2,
  151755. 12,
  151756. 1,
  151757. 13,
  151758. 0,
  151759. 14,
  151760. };
  151761. static long _vq_lengthlist__44u9_p8_0[] = {
  151762. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  151763. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151764. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  151765. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  151766. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  151767. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  151768. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  151769. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  151770. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  151771. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  151772. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  151773. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  151774. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  151775. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  151776. 15,
  151777. };
  151778. static float _vq_quantthresh__44u9_p8_0[] = {
  151779. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151780. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151781. };
  151782. static long _vq_quantmap__44u9_p8_0[] = {
  151783. 13, 11, 9, 7, 5, 3, 1, 0,
  151784. 2, 4, 6, 8, 10, 12, 14,
  151785. };
  151786. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  151787. _vq_quantthresh__44u9_p8_0,
  151788. _vq_quantmap__44u9_p8_0,
  151789. 15,
  151790. 15
  151791. };
  151792. static static_codebook _44u9_p8_0 = {
  151793. 2, 225,
  151794. _vq_lengthlist__44u9_p8_0,
  151795. 1, -520986624, 1620377600, 4, 0,
  151796. _vq_quantlist__44u9_p8_0,
  151797. NULL,
  151798. &_vq_auxt__44u9_p8_0,
  151799. NULL,
  151800. 0
  151801. };
  151802. static long _vq_quantlist__44u9_p8_1[] = {
  151803. 10,
  151804. 9,
  151805. 11,
  151806. 8,
  151807. 12,
  151808. 7,
  151809. 13,
  151810. 6,
  151811. 14,
  151812. 5,
  151813. 15,
  151814. 4,
  151815. 16,
  151816. 3,
  151817. 17,
  151818. 2,
  151819. 18,
  151820. 1,
  151821. 19,
  151822. 0,
  151823. 20,
  151824. };
  151825. static long _vq_lengthlist__44u9_p8_1[] = {
  151826. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151827. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151828. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  151829. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151830. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  151831. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151832. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151833. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  151834. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151835. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151836. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  151837. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  151838. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151839. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151840. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151841. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151842. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151843. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151844. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  151845. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151846. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151847. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  151848. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  151849. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  151850. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151851. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  151852. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151853. 10,10,10,10,10,10,10,10,10,
  151854. };
  151855. static float _vq_quantthresh__44u9_p8_1[] = {
  151856. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151857. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151858. 6.5, 7.5, 8.5, 9.5,
  151859. };
  151860. static long _vq_quantmap__44u9_p8_1[] = {
  151861. 19, 17, 15, 13, 11, 9, 7, 5,
  151862. 3, 1, 0, 2, 4, 6, 8, 10,
  151863. 12, 14, 16, 18, 20,
  151864. };
  151865. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  151866. _vq_quantthresh__44u9_p8_1,
  151867. _vq_quantmap__44u9_p8_1,
  151868. 21,
  151869. 21
  151870. };
  151871. static static_codebook _44u9_p8_1 = {
  151872. 2, 441,
  151873. _vq_lengthlist__44u9_p8_1,
  151874. 1, -529268736, 1611661312, 5, 0,
  151875. _vq_quantlist__44u9_p8_1,
  151876. NULL,
  151877. &_vq_auxt__44u9_p8_1,
  151878. NULL,
  151879. 0
  151880. };
  151881. static long _vq_quantlist__44u9_p9_0[] = {
  151882. 7,
  151883. 6,
  151884. 8,
  151885. 5,
  151886. 9,
  151887. 4,
  151888. 10,
  151889. 3,
  151890. 11,
  151891. 2,
  151892. 12,
  151893. 1,
  151894. 13,
  151895. 0,
  151896. 14,
  151897. };
  151898. static long _vq_lengthlist__44u9_p9_0[] = {
  151899. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  151900. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  151901. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151902. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151903. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151904. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151905. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151906. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151907. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151908. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151909. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151910. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151911. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151912. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151913. 10,
  151914. };
  151915. static float _vq_quantthresh__44u9_p9_0[] = {
  151916. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  151917. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  151918. };
  151919. static long _vq_quantmap__44u9_p9_0[] = {
  151920. 13, 11, 9, 7, 5, 3, 1, 0,
  151921. 2, 4, 6, 8, 10, 12, 14,
  151922. };
  151923. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  151924. _vq_quantthresh__44u9_p9_0,
  151925. _vq_quantmap__44u9_p9_0,
  151926. 15,
  151927. 15
  151928. };
  151929. static static_codebook _44u9_p9_0 = {
  151930. 2, 225,
  151931. _vq_lengthlist__44u9_p9_0,
  151932. 1, -510036736, 1631393792, 4, 0,
  151933. _vq_quantlist__44u9_p9_0,
  151934. NULL,
  151935. &_vq_auxt__44u9_p9_0,
  151936. NULL,
  151937. 0
  151938. };
  151939. static long _vq_quantlist__44u9_p9_1[] = {
  151940. 9,
  151941. 8,
  151942. 10,
  151943. 7,
  151944. 11,
  151945. 6,
  151946. 12,
  151947. 5,
  151948. 13,
  151949. 4,
  151950. 14,
  151951. 3,
  151952. 15,
  151953. 2,
  151954. 16,
  151955. 1,
  151956. 17,
  151957. 0,
  151958. 18,
  151959. };
  151960. static long _vq_lengthlist__44u9_p9_1[] = {
  151961. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  151962. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  151963. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  151964. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  151965. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  151966. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  151967. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  151968. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  151969. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  151970. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  151971. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  151972. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  151973. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  151974. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  151975. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  151976. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  151977. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  151978. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  151979. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  151980. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  151981. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  151982. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  151983. 17,17,15,17,15,17,16,16,17,
  151984. };
  151985. static float _vq_quantthresh__44u9_p9_1[] = {
  151986. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151987. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151988. 367.5, 416.5,
  151989. };
  151990. static long _vq_quantmap__44u9_p9_1[] = {
  151991. 17, 15, 13, 11, 9, 7, 5, 3,
  151992. 1, 0, 2, 4, 6, 8, 10, 12,
  151993. 14, 16, 18,
  151994. };
  151995. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  151996. _vq_quantthresh__44u9_p9_1,
  151997. _vq_quantmap__44u9_p9_1,
  151998. 19,
  151999. 19
  152000. };
  152001. static static_codebook _44u9_p9_1 = {
  152002. 2, 361,
  152003. _vq_lengthlist__44u9_p9_1,
  152004. 1, -518287360, 1622704128, 5, 0,
  152005. _vq_quantlist__44u9_p9_1,
  152006. NULL,
  152007. &_vq_auxt__44u9_p9_1,
  152008. NULL,
  152009. 0
  152010. };
  152011. static long _vq_quantlist__44u9_p9_2[] = {
  152012. 24,
  152013. 23,
  152014. 25,
  152015. 22,
  152016. 26,
  152017. 21,
  152018. 27,
  152019. 20,
  152020. 28,
  152021. 19,
  152022. 29,
  152023. 18,
  152024. 30,
  152025. 17,
  152026. 31,
  152027. 16,
  152028. 32,
  152029. 15,
  152030. 33,
  152031. 14,
  152032. 34,
  152033. 13,
  152034. 35,
  152035. 12,
  152036. 36,
  152037. 11,
  152038. 37,
  152039. 10,
  152040. 38,
  152041. 9,
  152042. 39,
  152043. 8,
  152044. 40,
  152045. 7,
  152046. 41,
  152047. 6,
  152048. 42,
  152049. 5,
  152050. 43,
  152051. 4,
  152052. 44,
  152053. 3,
  152054. 45,
  152055. 2,
  152056. 46,
  152057. 1,
  152058. 47,
  152059. 0,
  152060. 48,
  152061. };
  152062. static long _vq_lengthlist__44u9_p9_2[] = {
  152063. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152064. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152065. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152066. 7,
  152067. };
  152068. static float _vq_quantthresh__44u9_p9_2[] = {
  152069. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152070. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152071. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152072. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152073. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152074. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152075. };
  152076. static long _vq_quantmap__44u9_p9_2[] = {
  152077. 47, 45, 43, 41, 39, 37, 35, 33,
  152078. 31, 29, 27, 25, 23, 21, 19, 17,
  152079. 15, 13, 11, 9, 7, 5, 3, 1,
  152080. 0, 2, 4, 6, 8, 10, 12, 14,
  152081. 16, 18, 20, 22, 24, 26, 28, 30,
  152082. 32, 34, 36, 38, 40, 42, 44, 46,
  152083. 48,
  152084. };
  152085. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152086. _vq_quantthresh__44u9_p9_2,
  152087. _vq_quantmap__44u9_p9_2,
  152088. 49,
  152089. 49
  152090. };
  152091. static static_codebook _44u9_p9_2 = {
  152092. 1, 49,
  152093. _vq_lengthlist__44u9_p9_2,
  152094. 1, -526909440, 1611661312, 6, 0,
  152095. _vq_quantlist__44u9_p9_2,
  152096. NULL,
  152097. &_vq_auxt__44u9_p9_2,
  152098. NULL,
  152099. 0
  152100. };
  152101. static long _huff_lengthlist__44un1__long[] = {
  152102. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152103. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152104. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152105. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152106. };
  152107. static static_codebook _huff_book__44un1__long = {
  152108. 2, 64,
  152109. _huff_lengthlist__44un1__long,
  152110. 0, 0, 0, 0, 0,
  152111. NULL,
  152112. NULL,
  152113. NULL,
  152114. NULL,
  152115. 0
  152116. };
  152117. static long _vq_quantlist__44un1__p1_0[] = {
  152118. 1,
  152119. 0,
  152120. 2,
  152121. };
  152122. static long _vq_lengthlist__44un1__p1_0[] = {
  152123. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152124. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152125. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152126. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152127. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152128. 12,
  152129. };
  152130. static float _vq_quantthresh__44un1__p1_0[] = {
  152131. -0.5, 0.5,
  152132. };
  152133. static long _vq_quantmap__44un1__p1_0[] = {
  152134. 1, 0, 2,
  152135. };
  152136. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152137. _vq_quantthresh__44un1__p1_0,
  152138. _vq_quantmap__44un1__p1_0,
  152139. 3,
  152140. 3
  152141. };
  152142. static static_codebook _44un1__p1_0 = {
  152143. 4, 81,
  152144. _vq_lengthlist__44un1__p1_0,
  152145. 1, -535822336, 1611661312, 2, 0,
  152146. _vq_quantlist__44un1__p1_0,
  152147. NULL,
  152148. &_vq_auxt__44un1__p1_0,
  152149. NULL,
  152150. 0
  152151. };
  152152. static long _vq_quantlist__44un1__p2_0[] = {
  152153. 1,
  152154. 0,
  152155. 2,
  152156. };
  152157. static long _vq_lengthlist__44un1__p2_0[] = {
  152158. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152159. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152160. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152161. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152162. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152163. 8,
  152164. };
  152165. static float _vq_quantthresh__44un1__p2_0[] = {
  152166. -0.5, 0.5,
  152167. };
  152168. static long _vq_quantmap__44un1__p2_0[] = {
  152169. 1, 0, 2,
  152170. };
  152171. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152172. _vq_quantthresh__44un1__p2_0,
  152173. _vq_quantmap__44un1__p2_0,
  152174. 3,
  152175. 3
  152176. };
  152177. static static_codebook _44un1__p2_0 = {
  152178. 4, 81,
  152179. _vq_lengthlist__44un1__p2_0,
  152180. 1, -535822336, 1611661312, 2, 0,
  152181. _vq_quantlist__44un1__p2_0,
  152182. NULL,
  152183. &_vq_auxt__44un1__p2_0,
  152184. NULL,
  152185. 0
  152186. };
  152187. static long _vq_quantlist__44un1__p3_0[] = {
  152188. 2,
  152189. 1,
  152190. 3,
  152191. 0,
  152192. 4,
  152193. };
  152194. static long _vq_lengthlist__44un1__p3_0[] = {
  152195. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152196. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152197. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152198. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152199. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152200. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152201. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152202. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152203. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152204. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152205. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152206. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152207. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152208. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152209. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152210. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152211. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152212. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152213. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152214. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152215. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152216. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152217. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152218. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152219. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152220. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152221. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152222. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152223. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152224. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152225. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152226. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152227. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152228. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152229. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152230. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152231. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152232. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152233. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152234. 17,
  152235. };
  152236. static float _vq_quantthresh__44un1__p3_0[] = {
  152237. -1.5, -0.5, 0.5, 1.5,
  152238. };
  152239. static long _vq_quantmap__44un1__p3_0[] = {
  152240. 3, 1, 0, 2, 4,
  152241. };
  152242. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152243. _vq_quantthresh__44un1__p3_0,
  152244. _vq_quantmap__44un1__p3_0,
  152245. 5,
  152246. 5
  152247. };
  152248. static static_codebook _44un1__p3_0 = {
  152249. 4, 625,
  152250. _vq_lengthlist__44un1__p3_0,
  152251. 1, -533725184, 1611661312, 3, 0,
  152252. _vq_quantlist__44un1__p3_0,
  152253. NULL,
  152254. &_vq_auxt__44un1__p3_0,
  152255. NULL,
  152256. 0
  152257. };
  152258. static long _vq_quantlist__44un1__p4_0[] = {
  152259. 2,
  152260. 1,
  152261. 3,
  152262. 0,
  152263. 4,
  152264. };
  152265. static long _vq_lengthlist__44un1__p4_0[] = {
  152266. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  152267. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  152268. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  152269. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  152270. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  152271. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  152272. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  152273. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  152274. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  152275. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  152276. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  152277. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  152278. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  152279. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  152280. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  152281. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  152282. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  152283. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  152284. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  152285. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  152286. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  152287. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  152288. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  152289. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  152290. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  152291. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  152292. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  152293. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  152294. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  152295. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  152296. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  152297. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  152298. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  152299. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  152300. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  152301. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  152302. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  152303. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  152304. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152305. 12,
  152306. };
  152307. static float _vq_quantthresh__44un1__p4_0[] = {
  152308. -1.5, -0.5, 0.5, 1.5,
  152309. };
  152310. static long _vq_quantmap__44un1__p4_0[] = {
  152311. 3, 1, 0, 2, 4,
  152312. };
  152313. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152314. _vq_quantthresh__44un1__p4_0,
  152315. _vq_quantmap__44un1__p4_0,
  152316. 5,
  152317. 5
  152318. };
  152319. static static_codebook _44un1__p4_0 = {
  152320. 4, 625,
  152321. _vq_lengthlist__44un1__p4_0,
  152322. 1, -533725184, 1611661312, 3, 0,
  152323. _vq_quantlist__44un1__p4_0,
  152324. NULL,
  152325. &_vq_auxt__44un1__p4_0,
  152326. NULL,
  152327. 0
  152328. };
  152329. static long _vq_quantlist__44un1__p5_0[] = {
  152330. 4,
  152331. 3,
  152332. 5,
  152333. 2,
  152334. 6,
  152335. 1,
  152336. 7,
  152337. 0,
  152338. 8,
  152339. };
  152340. static long _vq_lengthlist__44un1__p5_0[] = {
  152341. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152342. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152343. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152344. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152345. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152346. 12,
  152347. };
  152348. static float _vq_quantthresh__44un1__p5_0[] = {
  152349. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152350. };
  152351. static long _vq_quantmap__44un1__p5_0[] = {
  152352. 7, 5, 3, 1, 0, 2, 4, 6,
  152353. 8,
  152354. };
  152355. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152356. _vq_quantthresh__44un1__p5_0,
  152357. _vq_quantmap__44un1__p5_0,
  152358. 9,
  152359. 9
  152360. };
  152361. static static_codebook _44un1__p5_0 = {
  152362. 2, 81,
  152363. _vq_lengthlist__44un1__p5_0,
  152364. 1, -531628032, 1611661312, 4, 0,
  152365. _vq_quantlist__44un1__p5_0,
  152366. NULL,
  152367. &_vq_auxt__44un1__p5_0,
  152368. NULL,
  152369. 0
  152370. };
  152371. static long _vq_quantlist__44un1__p6_0[] = {
  152372. 6,
  152373. 5,
  152374. 7,
  152375. 4,
  152376. 8,
  152377. 3,
  152378. 9,
  152379. 2,
  152380. 10,
  152381. 1,
  152382. 11,
  152383. 0,
  152384. 12,
  152385. };
  152386. static long _vq_lengthlist__44un1__p6_0[] = {
  152387. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  152388. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  152389. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  152390. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  152391. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  152392. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  152393. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  152394. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  152395. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  152396. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  152397. 16, 0,15,18,18, 0,16, 0, 0,
  152398. };
  152399. static float _vq_quantthresh__44un1__p6_0[] = {
  152400. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152401. 12.5, 17.5, 22.5, 27.5,
  152402. };
  152403. static long _vq_quantmap__44un1__p6_0[] = {
  152404. 11, 9, 7, 5, 3, 1, 0, 2,
  152405. 4, 6, 8, 10, 12,
  152406. };
  152407. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  152408. _vq_quantthresh__44un1__p6_0,
  152409. _vq_quantmap__44un1__p6_0,
  152410. 13,
  152411. 13
  152412. };
  152413. static static_codebook _44un1__p6_0 = {
  152414. 2, 169,
  152415. _vq_lengthlist__44un1__p6_0,
  152416. 1, -526516224, 1616117760, 4, 0,
  152417. _vq_quantlist__44un1__p6_0,
  152418. NULL,
  152419. &_vq_auxt__44un1__p6_0,
  152420. NULL,
  152421. 0
  152422. };
  152423. static long _vq_quantlist__44un1__p6_1[] = {
  152424. 2,
  152425. 1,
  152426. 3,
  152427. 0,
  152428. 4,
  152429. };
  152430. static long _vq_lengthlist__44un1__p6_1[] = {
  152431. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  152432. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  152433. };
  152434. static float _vq_quantthresh__44un1__p6_1[] = {
  152435. -1.5, -0.5, 0.5, 1.5,
  152436. };
  152437. static long _vq_quantmap__44un1__p6_1[] = {
  152438. 3, 1, 0, 2, 4,
  152439. };
  152440. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  152441. _vq_quantthresh__44un1__p6_1,
  152442. _vq_quantmap__44un1__p6_1,
  152443. 5,
  152444. 5
  152445. };
  152446. static static_codebook _44un1__p6_1 = {
  152447. 2, 25,
  152448. _vq_lengthlist__44un1__p6_1,
  152449. 1, -533725184, 1611661312, 3, 0,
  152450. _vq_quantlist__44un1__p6_1,
  152451. NULL,
  152452. &_vq_auxt__44un1__p6_1,
  152453. NULL,
  152454. 0
  152455. };
  152456. static long _vq_quantlist__44un1__p7_0[] = {
  152457. 2,
  152458. 1,
  152459. 3,
  152460. 0,
  152461. 4,
  152462. };
  152463. static long _vq_lengthlist__44un1__p7_0[] = {
  152464. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  152465. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  152466. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152467. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152468. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152469. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152470. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152471. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  152472. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152473. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152474. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  152475. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152476. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152477. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152478. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152479. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  152480. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152481. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  152482. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152483. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152484. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152485. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152486. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152487. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152488. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152489. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152490. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152491. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152492. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152493. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152494. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152495. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152496. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152497. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152498. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152499. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152500. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152501. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152502. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152503. 10,
  152504. };
  152505. static float _vq_quantthresh__44un1__p7_0[] = {
  152506. -253.5, -84.5, 84.5, 253.5,
  152507. };
  152508. static long _vq_quantmap__44un1__p7_0[] = {
  152509. 3, 1, 0, 2, 4,
  152510. };
  152511. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  152512. _vq_quantthresh__44un1__p7_0,
  152513. _vq_quantmap__44un1__p7_0,
  152514. 5,
  152515. 5
  152516. };
  152517. static static_codebook _44un1__p7_0 = {
  152518. 4, 625,
  152519. _vq_lengthlist__44un1__p7_0,
  152520. 1, -518709248, 1626677248, 3, 0,
  152521. _vq_quantlist__44un1__p7_0,
  152522. NULL,
  152523. &_vq_auxt__44un1__p7_0,
  152524. NULL,
  152525. 0
  152526. };
  152527. static long _vq_quantlist__44un1__p7_1[] = {
  152528. 6,
  152529. 5,
  152530. 7,
  152531. 4,
  152532. 8,
  152533. 3,
  152534. 9,
  152535. 2,
  152536. 10,
  152537. 1,
  152538. 11,
  152539. 0,
  152540. 12,
  152541. };
  152542. static long _vq_lengthlist__44un1__p7_1[] = {
  152543. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  152544. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  152545. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  152546. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  152547. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  152548. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  152549. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  152550. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  152551. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  152552. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  152553. 12,13,13,12,13,13,14,14,14,
  152554. };
  152555. static float _vq_quantthresh__44un1__p7_1[] = {
  152556. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  152557. 32.5, 45.5, 58.5, 71.5,
  152558. };
  152559. static long _vq_quantmap__44un1__p7_1[] = {
  152560. 11, 9, 7, 5, 3, 1, 0, 2,
  152561. 4, 6, 8, 10, 12,
  152562. };
  152563. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  152564. _vq_quantthresh__44un1__p7_1,
  152565. _vq_quantmap__44un1__p7_1,
  152566. 13,
  152567. 13
  152568. };
  152569. static static_codebook _44un1__p7_1 = {
  152570. 2, 169,
  152571. _vq_lengthlist__44un1__p7_1,
  152572. 1, -523010048, 1618608128, 4, 0,
  152573. _vq_quantlist__44un1__p7_1,
  152574. NULL,
  152575. &_vq_auxt__44un1__p7_1,
  152576. NULL,
  152577. 0
  152578. };
  152579. static long _vq_quantlist__44un1__p7_2[] = {
  152580. 6,
  152581. 5,
  152582. 7,
  152583. 4,
  152584. 8,
  152585. 3,
  152586. 9,
  152587. 2,
  152588. 10,
  152589. 1,
  152590. 11,
  152591. 0,
  152592. 12,
  152593. };
  152594. static long _vq_lengthlist__44un1__p7_2[] = {
  152595. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  152596. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  152597. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  152598. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  152599. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  152600. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  152601. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  152602. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  152603. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  152604. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  152605. 9, 9, 9,10,10,10,10,10,10,
  152606. };
  152607. static float _vq_quantthresh__44un1__p7_2[] = {
  152608. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  152609. 2.5, 3.5, 4.5, 5.5,
  152610. };
  152611. static long _vq_quantmap__44un1__p7_2[] = {
  152612. 11, 9, 7, 5, 3, 1, 0, 2,
  152613. 4, 6, 8, 10, 12,
  152614. };
  152615. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  152616. _vq_quantthresh__44un1__p7_2,
  152617. _vq_quantmap__44un1__p7_2,
  152618. 13,
  152619. 13
  152620. };
  152621. static static_codebook _44un1__p7_2 = {
  152622. 2, 169,
  152623. _vq_lengthlist__44un1__p7_2,
  152624. 1, -531103744, 1611661312, 4, 0,
  152625. _vq_quantlist__44un1__p7_2,
  152626. NULL,
  152627. &_vq_auxt__44un1__p7_2,
  152628. NULL,
  152629. 0
  152630. };
  152631. static long _huff_lengthlist__44un1__short[] = {
  152632. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  152633. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  152634. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  152635. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  152636. };
  152637. static static_codebook _huff_book__44un1__short = {
  152638. 2, 64,
  152639. _huff_lengthlist__44un1__short,
  152640. 0, 0, 0, 0, 0,
  152641. NULL,
  152642. NULL,
  152643. NULL,
  152644. NULL,
  152645. 0
  152646. };
  152647. /*** End of inlined file: res_books_uncoupled.h ***/
  152648. /***** residue backends *********************************************/
  152649. static vorbis_info_residue0 _residue_44_low_un={
  152650. 0,-1, -1, 8,-1,
  152651. {0},
  152652. {-1},
  152653. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  152654. { -1, 25, -1, 45, -1, -1, -1}
  152655. };
  152656. static vorbis_info_residue0 _residue_44_mid_un={
  152657. 0,-1, -1, 10,-1,
  152658. /* 0 1 2 3 4 5 6 7 8 9 */
  152659. {0},
  152660. {-1},
  152661. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  152662. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  152663. };
  152664. static vorbis_info_residue0 _residue_44_hi_un={
  152665. 0,-1, -1, 10,-1,
  152666. /* 0 1 2 3 4 5 6 7 8 9 */
  152667. {0},
  152668. {-1},
  152669. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  152670. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  152671. };
  152672. /* mapping conventions:
  152673. only one submap (this would change for efficient 5.1 support for example)*/
  152674. /* Four psychoacoustic profiles are used, one for each blocktype */
  152675. static vorbis_info_mapping0 _map_nominal_u[2]={
  152676. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  152677. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  152678. };
  152679. static static_bookblock _resbook_44u_n1={
  152680. {
  152681. {0},
  152682. {0,0,&_44un1__p1_0},
  152683. {0,0,&_44un1__p2_0},
  152684. {0,0,&_44un1__p3_0},
  152685. {0,0,&_44un1__p4_0},
  152686. {0,0,&_44un1__p5_0},
  152687. {&_44un1__p6_0,&_44un1__p6_1},
  152688. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  152689. }
  152690. };
  152691. static static_bookblock _resbook_44u_0={
  152692. {
  152693. {0},
  152694. {0,0,&_44u0__p1_0},
  152695. {0,0,&_44u0__p2_0},
  152696. {0,0,&_44u0__p3_0},
  152697. {0,0,&_44u0__p4_0},
  152698. {0,0,&_44u0__p5_0},
  152699. {&_44u0__p6_0,&_44u0__p6_1},
  152700. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  152701. }
  152702. };
  152703. static static_bookblock _resbook_44u_1={
  152704. {
  152705. {0},
  152706. {0,0,&_44u1__p1_0},
  152707. {0,0,&_44u1__p2_0},
  152708. {0,0,&_44u1__p3_0},
  152709. {0,0,&_44u1__p4_0},
  152710. {0,0,&_44u1__p5_0},
  152711. {&_44u1__p6_0,&_44u1__p6_1},
  152712. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  152713. }
  152714. };
  152715. static static_bookblock _resbook_44u_2={
  152716. {
  152717. {0},
  152718. {0,0,&_44u2__p1_0},
  152719. {0,0,&_44u2__p2_0},
  152720. {0,0,&_44u2__p3_0},
  152721. {0,0,&_44u2__p4_0},
  152722. {0,0,&_44u2__p5_0},
  152723. {&_44u2__p6_0,&_44u2__p6_1},
  152724. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  152725. }
  152726. };
  152727. static static_bookblock _resbook_44u_3={
  152728. {
  152729. {0},
  152730. {0,0,&_44u3__p1_0},
  152731. {0,0,&_44u3__p2_0},
  152732. {0,0,&_44u3__p3_0},
  152733. {0,0,&_44u3__p4_0},
  152734. {0,0,&_44u3__p5_0},
  152735. {&_44u3__p6_0,&_44u3__p6_1},
  152736. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  152737. }
  152738. };
  152739. static static_bookblock _resbook_44u_4={
  152740. {
  152741. {0},
  152742. {0,0,&_44u4__p1_0},
  152743. {0,0,&_44u4__p2_0},
  152744. {0,0,&_44u4__p3_0},
  152745. {0,0,&_44u4__p4_0},
  152746. {0,0,&_44u4__p5_0},
  152747. {&_44u4__p6_0,&_44u4__p6_1},
  152748. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  152749. }
  152750. };
  152751. static static_bookblock _resbook_44u_5={
  152752. {
  152753. {0},
  152754. {0,0,&_44u5__p1_0},
  152755. {0,0,&_44u5__p2_0},
  152756. {0,0,&_44u5__p3_0},
  152757. {0,0,&_44u5__p4_0},
  152758. {0,0,&_44u5__p5_0},
  152759. {0,0,&_44u5__p6_0},
  152760. {&_44u5__p7_0,&_44u5__p7_1},
  152761. {&_44u5__p8_0,&_44u5__p8_1},
  152762. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  152763. }
  152764. };
  152765. static static_bookblock _resbook_44u_6={
  152766. {
  152767. {0},
  152768. {0,0,&_44u6__p1_0},
  152769. {0,0,&_44u6__p2_0},
  152770. {0,0,&_44u6__p3_0},
  152771. {0,0,&_44u6__p4_0},
  152772. {0,0,&_44u6__p5_0},
  152773. {0,0,&_44u6__p6_0},
  152774. {&_44u6__p7_0,&_44u6__p7_1},
  152775. {&_44u6__p8_0,&_44u6__p8_1},
  152776. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  152777. }
  152778. };
  152779. static static_bookblock _resbook_44u_7={
  152780. {
  152781. {0},
  152782. {0,0,&_44u7__p1_0},
  152783. {0,0,&_44u7__p2_0},
  152784. {0,0,&_44u7__p3_0},
  152785. {0,0,&_44u7__p4_0},
  152786. {0,0,&_44u7__p5_0},
  152787. {0,0,&_44u7__p6_0},
  152788. {&_44u7__p7_0,&_44u7__p7_1},
  152789. {&_44u7__p8_0,&_44u7__p8_1},
  152790. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  152791. }
  152792. };
  152793. static static_bookblock _resbook_44u_8={
  152794. {
  152795. {0},
  152796. {0,0,&_44u8_p1_0},
  152797. {0,0,&_44u8_p2_0},
  152798. {0,0,&_44u8_p3_0},
  152799. {0,0,&_44u8_p4_0},
  152800. {&_44u8_p5_0,&_44u8_p5_1},
  152801. {&_44u8_p6_0,&_44u8_p6_1},
  152802. {&_44u8_p7_0,&_44u8_p7_1},
  152803. {&_44u8_p8_0,&_44u8_p8_1},
  152804. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  152805. }
  152806. };
  152807. static static_bookblock _resbook_44u_9={
  152808. {
  152809. {0},
  152810. {0,0,&_44u9_p1_0},
  152811. {0,0,&_44u9_p2_0},
  152812. {0,0,&_44u9_p3_0},
  152813. {0,0,&_44u9_p4_0},
  152814. {&_44u9_p5_0,&_44u9_p5_1},
  152815. {&_44u9_p6_0,&_44u9_p6_1},
  152816. {&_44u9_p7_0,&_44u9_p7_1},
  152817. {&_44u9_p8_0,&_44u9_p8_1},
  152818. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  152819. }
  152820. };
  152821. static vorbis_residue_template _res_44u_n1[]={
  152822. {1,0, &_residue_44_low_un,
  152823. &_huff_book__44un1__short,&_huff_book__44un1__short,
  152824. &_resbook_44u_n1,&_resbook_44u_n1},
  152825. {1,0, &_residue_44_low_un,
  152826. &_huff_book__44un1__long,&_huff_book__44un1__long,
  152827. &_resbook_44u_n1,&_resbook_44u_n1}
  152828. };
  152829. static vorbis_residue_template _res_44u_0[]={
  152830. {1,0, &_residue_44_low_un,
  152831. &_huff_book__44u0__short,&_huff_book__44u0__short,
  152832. &_resbook_44u_0,&_resbook_44u_0},
  152833. {1,0, &_residue_44_low_un,
  152834. &_huff_book__44u0__long,&_huff_book__44u0__long,
  152835. &_resbook_44u_0,&_resbook_44u_0}
  152836. };
  152837. static vorbis_residue_template _res_44u_1[]={
  152838. {1,0, &_residue_44_low_un,
  152839. &_huff_book__44u1__short,&_huff_book__44u1__short,
  152840. &_resbook_44u_1,&_resbook_44u_1},
  152841. {1,0, &_residue_44_low_un,
  152842. &_huff_book__44u1__long,&_huff_book__44u1__long,
  152843. &_resbook_44u_1,&_resbook_44u_1}
  152844. };
  152845. static vorbis_residue_template _res_44u_2[]={
  152846. {1,0, &_residue_44_low_un,
  152847. &_huff_book__44u2__short,&_huff_book__44u2__short,
  152848. &_resbook_44u_2,&_resbook_44u_2},
  152849. {1,0, &_residue_44_low_un,
  152850. &_huff_book__44u2__long,&_huff_book__44u2__long,
  152851. &_resbook_44u_2,&_resbook_44u_2}
  152852. };
  152853. static vorbis_residue_template _res_44u_3[]={
  152854. {1,0, &_residue_44_low_un,
  152855. &_huff_book__44u3__short,&_huff_book__44u3__short,
  152856. &_resbook_44u_3,&_resbook_44u_3},
  152857. {1,0, &_residue_44_low_un,
  152858. &_huff_book__44u3__long,&_huff_book__44u3__long,
  152859. &_resbook_44u_3,&_resbook_44u_3}
  152860. };
  152861. static vorbis_residue_template _res_44u_4[]={
  152862. {1,0, &_residue_44_low_un,
  152863. &_huff_book__44u4__short,&_huff_book__44u4__short,
  152864. &_resbook_44u_4,&_resbook_44u_4},
  152865. {1,0, &_residue_44_low_un,
  152866. &_huff_book__44u4__long,&_huff_book__44u4__long,
  152867. &_resbook_44u_4,&_resbook_44u_4}
  152868. };
  152869. static vorbis_residue_template _res_44u_5[]={
  152870. {1,0, &_residue_44_mid_un,
  152871. &_huff_book__44u5__short,&_huff_book__44u5__short,
  152872. &_resbook_44u_5,&_resbook_44u_5},
  152873. {1,0, &_residue_44_mid_un,
  152874. &_huff_book__44u5__long,&_huff_book__44u5__long,
  152875. &_resbook_44u_5,&_resbook_44u_5}
  152876. };
  152877. static vorbis_residue_template _res_44u_6[]={
  152878. {1,0, &_residue_44_mid_un,
  152879. &_huff_book__44u6__short,&_huff_book__44u6__short,
  152880. &_resbook_44u_6,&_resbook_44u_6},
  152881. {1,0, &_residue_44_mid_un,
  152882. &_huff_book__44u6__long,&_huff_book__44u6__long,
  152883. &_resbook_44u_6,&_resbook_44u_6}
  152884. };
  152885. static vorbis_residue_template _res_44u_7[]={
  152886. {1,0, &_residue_44_mid_un,
  152887. &_huff_book__44u7__short,&_huff_book__44u7__short,
  152888. &_resbook_44u_7,&_resbook_44u_7},
  152889. {1,0, &_residue_44_mid_un,
  152890. &_huff_book__44u7__long,&_huff_book__44u7__long,
  152891. &_resbook_44u_7,&_resbook_44u_7}
  152892. };
  152893. static vorbis_residue_template _res_44u_8[]={
  152894. {1,0, &_residue_44_hi_un,
  152895. &_huff_book__44u8__short,&_huff_book__44u8__short,
  152896. &_resbook_44u_8,&_resbook_44u_8},
  152897. {1,0, &_residue_44_hi_un,
  152898. &_huff_book__44u8__long,&_huff_book__44u8__long,
  152899. &_resbook_44u_8,&_resbook_44u_8}
  152900. };
  152901. static vorbis_residue_template _res_44u_9[]={
  152902. {1,0, &_residue_44_hi_un,
  152903. &_huff_book__44u9__short,&_huff_book__44u9__short,
  152904. &_resbook_44u_9,&_resbook_44u_9},
  152905. {1,0, &_residue_44_hi_un,
  152906. &_huff_book__44u9__long,&_huff_book__44u9__long,
  152907. &_resbook_44u_9,&_resbook_44u_9}
  152908. };
  152909. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  152910. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  152911. { _map_nominal_u, _res_44u_0 }, /* 0 */
  152912. { _map_nominal_u, _res_44u_1 }, /* 1 */
  152913. { _map_nominal_u, _res_44u_2 }, /* 2 */
  152914. { _map_nominal_u, _res_44u_3 }, /* 3 */
  152915. { _map_nominal_u, _res_44u_4 }, /* 4 */
  152916. { _map_nominal_u, _res_44u_5 }, /* 5 */
  152917. { _map_nominal_u, _res_44u_6 }, /* 6 */
  152918. { _map_nominal_u, _res_44u_7 }, /* 7 */
  152919. { _map_nominal_u, _res_44u_8 }, /* 8 */
  152920. { _map_nominal_u, _res_44u_9 }, /* 9 */
  152921. };
  152922. /*** End of inlined file: residue_44u.h ***/
  152923. static double rate_mapping_44_un[12]={
  152924. 32000.,48000.,60000.,70000.,80000.,86000.,
  152925. 96000.,110000.,120000.,140000.,160000.,240001.
  152926. };
  152927. ve_setup_data_template ve_setup_44_uncoupled={
  152928. 11,
  152929. rate_mapping_44_un,
  152930. quality_mapping_44,
  152931. -1,
  152932. 40000,
  152933. 50000,
  152934. blocksize_short_44,
  152935. blocksize_long_44,
  152936. _psy_tone_masteratt_44,
  152937. _psy_tone_0dB,
  152938. _psy_tone_suppress,
  152939. _vp_tonemask_adj_otherblock,
  152940. _vp_tonemask_adj_longblock,
  152941. _vp_tonemask_adj_otherblock,
  152942. _psy_noiseguards_44,
  152943. _psy_noisebias_impulse,
  152944. _psy_noisebias_padding,
  152945. _psy_noisebias_trans,
  152946. _psy_noisebias_long,
  152947. _psy_noise_suppress,
  152948. _psy_compand_44,
  152949. _psy_compand_short_mapping,
  152950. _psy_compand_long_mapping,
  152951. {_noise_start_short_44,_noise_start_long_44},
  152952. {_noise_part_short_44,_noise_part_long_44},
  152953. _noise_thresh_44,
  152954. _psy_ath_floater,
  152955. _psy_ath_abs,
  152956. _psy_lowpass_44,
  152957. _psy_global_44,
  152958. _global_mapping_44,
  152959. NULL,
  152960. _floor_books,
  152961. _floor,
  152962. _floor_short_mapping_44,
  152963. _floor_long_mapping_44,
  152964. _mapres_template_44_uncoupled
  152965. };
  152966. /*** End of inlined file: setup_44u.h ***/
  152967. /*** Start of inlined file: setup_32.h ***/
  152968. static double rate_mapping_32[12]={
  152969. 18000.,28000.,35000.,45000.,56000.,60000.,
  152970. 75000.,90000.,100000.,115000.,150000.,190000.,
  152971. };
  152972. static double rate_mapping_32_un[12]={
  152973. 30000.,42000.,52000.,64000.,72000.,78000.,
  152974. 86000.,92000.,110000.,120000.,140000.,190000.,
  152975. };
  152976. static double _psy_lowpass_32[12]={
  152977. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  152978. };
  152979. ve_setup_data_template ve_setup_32_stereo={
  152980. 11,
  152981. rate_mapping_32,
  152982. quality_mapping_44,
  152983. 2,
  152984. 26000,
  152985. 40000,
  152986. blocksize_short_44,
  152987. blocksize_long_44,
  152988. _psy_tone_masteratt_44,
  152989. _psy_tone_0dB,
  152990. _psy_tone_suppress,
  152991. _vp_tonemask_adj_otherblock,
  152992. _vp_tonemask_adj_longblock,
  152993. _vp_tonemask_adj_otherblock,
  152994. _psy_noiseguards_44,
  152995. _psy_noisebias_impulse,
  152996. _psy_noisebias_padding,
  152997. _psy_noisebias_trans,
  152998. _psy_noisebias_long,
  152999. _psy_noise_suppress,
  153000. _psy_compand_44,
  153001. _psy_compand_short_mapping,
  153002. _psy_compand_long_mapping,
  153003. {_noise_start_short_44,_noise_start_long_44},
  153004. {_noise_part_short_44,_noise_part_long_44},
  153005. _noise_thresh_44,
  153006. _psy_ath_floater,
  153007. _psy_ath_abs,
  153008. _psy_lowpass_32,
  153009. _psy_global_44,
  153010. _global_mapping_44,
  153011. _psy_stereo_modes_44,
  153012. _floor_books,
  153013. _floor,
  153014. _floor_short_mapping_44,
  153015. _floor_long_mapping_44,
  153016. _mapres_template_44_stereo
  153017. };
  153018. ve_setup_data_template ve_setup_32_uncoupled={
  153019. 11,
  153020. rate_mapping_32_un,
  153021. quality_mapping_44,
  153022. -1,
  153023. 26000,
  153024. 40000,
  153025. blocksize_short_44,
  153026. blocksize_long_44,
  153027. _psy_tone_masteratt_44,
  153028. _psy_tone_0dB,
  153029. _psy_tone_suppress,
  153030. _vp_tonemask_adj_otherblock,
  153031. _vp_tonemask_adj_longblock,
  153032. _vp_tonemask_adj_otherblock,
  153033. _psy_noiseguards_44,
  153034. _psy_noisebias_impulse,
  153035. _psy_noisebias_padding,
  153036. _psy_noisebias_trans,
  153037. _psy_noisebias_long,
  153038. _psy_noise_suppress,
  153039. _psy_compand_44,
  153040. _psy_compand_short_mapping,
  153041. _psy_compand_long_mapping,
  153042. {_noise_start_short_44,_noise_start_long_44},
  153043. {_noise_part_short_44,_noise_part_long_44},
  153044. _noise_thresh_44,
  153045. _psy_ath_floater,
  153046. _psy_ath_abs,
  153047. _psy_lowpass_32,
  153048. _psy_global_44,
  153049. _global_mapping_44,
  153050. NULL,
  153051. _floor_books,
  153052. _floor,
  153053. _floor_short_mapping_44,
  153054. _floor_long_mapping_44,
  153055. _mapres_template_44_uncoupled
  153056. };
  153057. /*** End of inlined file: setup_32.h ***/
  153058. /*** Start of inlined file: setup_8.h ***/
  153059. /*** Start of inlined file: psych_8.h ***/
  153060. static att3 _psy_tone_masteratt_8[3]={
  153061. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153062. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153063. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153064. };
  153065. static vp_adjblock _vp_tonemask_adj_8[3]={
  153066. /* adjust for mode zero */
  153067. /* 63 125 250 500 1 2 4 8 16 */
  153068. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153069. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153070. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153071. };
  153072. static noise3 _psy_noisebias_8[3]={
  153073. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153074. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153075. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153076. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153077. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153078. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153079. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153080. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153081. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153082. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153083. };
  153084. /* stereo mode by base quality level */
  153085. static adj_stereo _psy_stereo_modes_8[3]={
  153086. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153087. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153088. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153089. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153090. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153091. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153092. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153093. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153094. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153095. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153096. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153097. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153098. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153099. };
  153100. static noiseguard _psy_noiseguards_8[2]={
  153101. {10,10,-1},
  153102. {10,10,-1},
  153103. };
  153104. static compandblock _psy_compand_8[2]={
  153105. {{
  153106. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153107. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153108. 12,12,13,13,14,14,15, 15, /* 23dB */
  153109. 16,16,17,17,17,18,18, 19, /* 31dB */
  153110. 19,19,20,21,22,23,24, 25, /* 39dB */
  153111. }},
  153112. {{
  153113. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153114. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153115. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153116. 9,10,11,12,13,14,15, 16, /* 31dB */
  153117. 17,18,19,20,21,22,23, 24, /* 39dB */
  153118. }},
  153119. };
  153120. static double _psy_lowpass_8[3]={3.,4.,4.};
  153121. static int _noise_start_8[2]={
  153122. 64,64,
  153123. };
  153124. static int _noise_part_8[2]={
  153125. 8,8,
  153126. };
  153127. static int _psy_ath_floater_8[3]={
  153128. -100,-100,-105,
  153129. };
  153130. static int _psy_ath_abs_8[3]={
  153131. -130,-130,-140,
  153132. };
  153133. /*** End of inlined file: psych_8.h ***/
  153134. /*** Start of inlined file: residue_8.h ***/
  153135. /***** residue backends *********************************************/
  153136. static static_bookblock _resbook_8s_0={
  153137. {
  153138. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153139. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153140. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153141. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153142. }
  153143. };
  153144. static static_bookblock _resbook_8s_1={
  153145. {
  153146. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153147. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153148. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153149. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153150. }
  153151. };
  153152. static vorbis_residue_template _res_8s_0[]={
  153153. {2,0, &_residue_44_mid,
  153154. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153155. &_resbook_8s_0,&_resbook_8s_0},
  153156. };
  153157. static vorbis_residue_template _res_8s_1[]={
  153158. {2,0, &_residue_44_mid,
  153159. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153160. &_resbook_8s_1,&_resbook_8s_1},
  153161. };
  153162. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153163. { _map_nominal, _res_8s_0 }, /* 0 */
  153164. { _map_nominal, _res_8s_1 }, /* 1 */
  153165. };
  153166. static static_bookblock _resbook_8u_0={
  153167. {
  153168. {0},
  153169. {0,0,&_8u0__p1_0},
  153170. {0,0,&_8u0__p2_0},
  153171. {0,0,&_8u0__p3_0},
  153172. {0,0,&_8u0__p4_0},
  153173. {0,0,&_8u0__p5_0},
  153174. {&_8u0__p6_0,&_8u0__p6_1},
  153175. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153176. }
  153177. };
  153178. static static_bookblock _resbook_8u_1={
  153179. {
  153180. {0},
  153181. {0,0,&_8u1__p1_0},
  153182. {0,0,&_8u1__p2_0},
  153183. {0,0,&_8u1__p3_0},
  153184. {0,0,&_8u1__p4_0},
  153185. {0,0,&_8u1__p5_0},
  153186. {0,0,&_8u1__p6_0},
  153187. {&_8u1__p7_0,&_8u1__p7_1},
  153188. {&_8u1__p8_0,&_8u1__p8_1},
  153189. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153190. }
  153191. };
  153192. static vorbis_residue_template _res_8u_0[]={
  153193. {1,0, &_residue_44_low_un,
  153194. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153195. &_resbook_8u_0,&_resbook_8u_0},
  153196. };
  153197. static vorbis_residue_template _res_8u_1[]={
  153198. {1,0, &_residue_44_mid_un,
  153199. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153200. &_resbook_8u_1,&_resbook_8u_1},
  153201. };
  153202. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153203. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153204. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153205. };
  153206. /*** End of inlined file: residue_8.h ***/
  153207. static int blocksize_8[2]={
  153208. 512,512
  153209. };
  153210. static int _floor_mapping_8[2]={
  153211. 6,6,
  153212. };
  153213. static double rate_mapping_8[3]={
  153214. 6000.,9000.,32000.,
  153215. };
  153216. static double rate_mapping_8_uncoupled[3]={
  153217. 8000.,14000.,42000.,
  153218. };
  153219. static double quality_mapping_8[3]={
  153220. -.1,.0,1.
  153221. };
  153222. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153223. static double _global_mapping_8[3]={ 1., 2., 3. };
  153224. ve_setup_data_template ve_setup_8_stereo={
  153225. 2,
  153226. rate_mapping_8,
  153227. quality_mapping_8,
  153228. 2,
  153229. 8000,
  153230. 9000,
  153231. blocksize_8,
  153232. blocksize_8,
  153233. _psy_tone_masteratt_8,
  153234. _psy_tone_0dB,
  153235. _psy_tone_suppress,
  153236. _vp_tonemask_adj_8,
  153237. NULL,
  153238. _vp_tonemask_adj_8,
  153239. _psy_noiseguards_8,
  153240. _psy_noisebias_8,
  153241. _psy_noisebias_8,
  153242. NULL,
  153243. NULL,
  153244. _psy_noise_suppress,
  153245. _psy_compand_8,
  153246. _psy_compand_8_mapping,
  153247. NULL,
  153248. {_noise_start_8,_noise_start_8},
  153249. {_noise_part_8,_noise_part_8},
  153250. _noise_thresh_5only,
  153251. _psy_ath_floater_8,
  153252. _psy_ath_abs_8,
  153253. _psy_lowpass_8,
  153254. _psy_global_44,
  153255. _global_mapping_8,
  153256. _psy_stereo_modes_8,
  153257. _floor_books,
  153258. _floor,
  153259. _floor_mapping_8,
  153260. NULL,
  153261. _mapres_template_8_stereo
  153262. };
  153263. ve_setup_data_template ve_setup_8_uncoupled={
  153264. 2,
  153265. rate_mapping_8_uncoupled,
  153266. quality_mapping_8,
  153267. -1,
  153268. 8000,
  153269. 9000,
  153270. blocksize_8,
  153271. blocksize_8,
  153272. _psy_tone_masteratt_8,
  153273. _psy_tone_0dB,
  153274. _psy_tone_suppress,
  153275. _vp_tonemask_adj_8,
  153276. NULL,
  153277. _vp_tonemask_adj_8,
  153278. _psy_noiseguards_8,
  153279. _psy_noisebias_8,
  153280. _psy_noisebias_8,
  153281. NULL,
  153282. NULL,
  153283. _psy_noise_suppress,
  153284. _psy_compand_8,
  153285. _psy_compand_8_mapping,
  153286. NULL,
  153287. {_noise_start_8,_noise_start_8},
  153288. {_noise_part_8,_noise_part_8},
  153289. _noise_thresh_5only,
  153290. _psy_ath_floater_8,
  153291. _psy_ath_abs_8,
  153292. _psy_lowpass_8,
  153293. _psy_global_44,
  153294. _global_mapping_8,
  153295. _psy_stereo_modes_8,
  153296. _floor_books,
  153297. _floor,
  153298. _floor_mapping_8,
  153299. NULL,
  153300. _mapres_template_8_uncoupled
  153301. };
  153302. /*** End of inlined file: setup_8.h ***/
  153303. /*** Start of inlined file: setup_11.h ***/
  153304. /*** Start of inlined file: psych_11.h ***/
  153305. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153306. static att3 _psy_tone_masteratt_11[3]={
  153307. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153308. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153309. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153310. };
  153311. static vp_adjblock _vp_tonemask_adj_11[3]={
  153312. /* adjust for mode zero */
  153313. /* 63 125 250 500 1 2 4 8 16 */
  153314. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153315. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153316. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153317. };
  153318. static noise3 _psy_noisebias_11[3]={
  153319. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153320. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153321. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153322. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153323. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153324. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153325. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153326. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153327. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153328. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153329. };
  153330. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153331. /*** End of inlined file: psych_11.h ***/
  153332. static int blocksize_11[2]={
  153333. 512,512
  153334. };
  153335. static int _floor_mapping_11[2]={
  153336. 6,6,
  153337. };
  153338. static double rate_mapping_11[3]={
  153339. 8000.,13000.,44000.,
  153340. };
  153341. static double rate_mapping_11_uncoupled[3]={
  153342. 12000.,20000.,50000.,
  153343. };
  153344. static double quality_mapping_11[3]={
  153345. -.1,.0,1.
  153346. };
  153347. ve_setup_data_template ve_setup_11_stereo={
  153348. 2,
  153349. rate_mapping_11,
  153350. quality_mapping_11,
  153351. 2,
  153352. 9000,
  153353. 15000,
  153354. blocksize_11,
  153355. blocksize_11,
  153356. _psy_tone_masteratt_11,
  153357. _psy_tone_0dB,
  153358. _psy_tone_suppress,
  153359. _vp_tonemask_adj_11,
  153360. NULL,
  153361. _vp_tonemask_adj_11,
  153362. _psy_noiseguards_8,
  153363. _psy_noisebias_11,
  153364. _psy_noisebias_11,
  153365. NULL,
  153366. NULL,
  153367. _psy_noise_suppress,
  153368. _psy_compand_8,
  153369. _psy_compand_8_mapping,
  153370. NULL,
  153371. {_noise_start_8,_noise_start_8},
  153372. {_noise_part_8,_noise_part_8},
  153373. _noise_thresh_11,
  153374. _psy_ath_floater_8,
  153375. _psy_ath_abs_8,
  153376. _psy_lowpass_11,
  153377. _psy_global_44,
  153378. _global_mapping_8,
  153379. _psy_stereo_modes_8,
  153380. _floor_books,
  153381. _floor,
  153382. _floor_mapping_11,
  153383. NULL,
  153384. _mapres_template_8_stereo
  153385. };
  153386. ve_setup_data_template ve_setup_11_uncoupled={
  153387. 2,
  153388. rate_mapping_11_uncoupled,
  153389. quality_mapping_11,
  153390. -1,
  153391. 9000,
  153392. 15000,
  153393. blocksize_11,
  153394. blocksize_11,
  153395. _psy_tone_masteratt_11,
  153396. _psy_tone_0dB,
  153397. _psy_tone_suppress,
  153398. _vp_tonemask_adj_11,
  153399. NULL,
  153400. _vp_tonemask_adj_11,
  153401. _psy_noiseguards_8,
  153402. _psy_noisebias_11,
  153403. _psy_noisebias_11,
  153404. NULL,
  153405. NULL,
  153406. _psy_noise_suppress,
  153407. _psy_compand_8,
  153408. _psy_compand_8_mapping,
  153409. NULL,
  153410. {_noise_start_8,_noise_start_8},
  153411. {_noise_part_8,_noise_part_8},
  153412. _noise_thresh_11,
  153413. _psy_ath_floater_8,
  153414. _psy_ath_abs_8,
  153415. _psy_lowpass_11,
  153416. _psy_global_44,
  153417. _global_mapping_8,
  153418. _psy_stereo_modes_8,
  153419. _floor_books,
  153420. _floor,
  153421. _floor_mapping_11,
  153422. NULL,
  153423. _mapres_template_8_uncoupled
  153424. };
  153425. /*** End of inlined file: setup_11.h ***/
  153426. /*** Start of inlined file: setup_16.h ***/
  153427. /*** Start of inlined file: psych_16.h ***/
  153428. /* stereo mode by base quality level */
  153429. static adj_stereo _psy_stereo_modes_16[4]={
  153430. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153431. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153432. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153433. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  153434. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153435. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153436. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153437. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  153438. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153439. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153440. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153441. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153442. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153443. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153444. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153445. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  153446. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153447. };
  153448. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  153449. static att3 _psy_tone_masteratt_16[4]={
  153450. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153451. {{ 25, 22, 12}, 0, 0}, /* 0 */
  153452. {{ 20, 12, 0}, 0, 0}, /* 0 */
  153453. {{ 15, 0, -14}, 0, 0}, /* 0 */
  153454. };
  153455. static vp_adjblock _vp_tonemask_adj_16[4]={
  153456. /* adjust for mode zero */
  153457. /* 63 125 250 500 1 2 4 8 16 */
  153458. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  153459. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  153460. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153461. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153462. };
  153463. static noise3 _psy_noisebias_16_short[4]={
  153464. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153465. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153466. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153467. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153468. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153469. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  153470. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153471. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153472. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  153473. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153474. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153475. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153476. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153477. };
  153478. static noise3 _psy_noisebias_16_impulse[4]={
  153479. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153480. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153481. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153482. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153483. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  153484. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  153485. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153486. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  153487. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  153488. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153489. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153490. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  153491. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153492. };
  153493. static noise3 _psy_noisebias_16[4]={
  153494. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153495. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  153496. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153497. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153498. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153499. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153500. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153501. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153502. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  153503. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153504. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153505. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153506. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153507. };
  153508. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  153509. static int _noise_start_16[3]={ 256,256,9999 };
  153510. static int _noise_part_16[4]={ 8,8,8,8 };
  153511. static int _psy_ath_floater_16[4]={
  153512. -100,-100,-100,-105,
  153513. };
  153514. static int _psy_ath_abs_16[4]={
  153515. -130,-130,-130,-140,
  153516. };
  153517. /*** End of inlined file: psych_16.h ***/
  153518. /*** Start of inlined file: residue_16.h ***/
  153519. /***** residue backends *********************************************/
  153520. static static_bookblock _resbook_16s_0={
  153521. {
  153522. {0},
  153523. {0,0,&_16c0_s_p1_0},
  153524. {0,0,&_16c0_s_p2_0},
  153525. {0,0,&_16c0_s_p3_0},
  153526. {0,0,&_16c0_s_p4_0},
  153527. {0,0,&_16c0_s_p5_0},
  153528. {0,0,&_16c0_s_p6_0},
  153529. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  153530. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  153531. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  153532. }
  153533. };
  153534. static static_bookblock _resbook_16s_1={
  153535. {
  153536. {0},
  153537. {0,0,&_16c1_s_p1_0},
  153538. {0,0,&_16c1_s_p2_0},
  153539. {0,0,&_16c1_s_p3_0},
  153540. {0,0,&_16c1_s_p4_0},
  153541. {0,0,&_16c1_s_p5_0},
  153542. {0,0,&_16c1_s_p6_0},
  153543. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  153544. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  153545. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  153546. }
  153547. };
  153548. static static_bookblock _resbook_16s_2={
  153549. {
  153550. {0},
  153551. {0,0,&_16c2_s_p1_0},
  153552. {0,0,&_16c2_s_p2_0},
  153553. {0,0,&_16c2_s_p3_0},
  153554. {0,0,&_16c2_s_p4_0},
  153555. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  153556. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  153557. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  153558. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  153559. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  153560. }
  153561. };
  153562. static vorbis_residue_template _res_16s_0[]={
  153563. {2,0, &_residue_44_mid,
  153564. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  153565. &_resbook_16s_0,&_resbook_16s_0},
  153566. };
  153567. static vorbis_residue_template _res_16s_1[]={
  153568. {2,0, &_residue_44_mid,
  153569. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  153570. &_resbook_16s_1,&_resbook_16s_1},
  153571. {2,0, &_residue_44_mid,
  153572. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  153573. &_resbook_16s_1,&_resbook_16s_1}
  153574. };
  153575. static vorbis_residue_template _res_16s_2[]={
  153576. {2,0, &_residue_44_high,
  153577. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  153578. &_resbook_16s_2,&_resbook_16s_2},
  153579. {2,0, &_residue_44_high,
  153580. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  153581. &_resbook_16s_2,&_resbook_16s_2}
  153582. };
  153583. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  153584. { _map_nominal, _res_16s_0 }, /* 0 */
  153585. { _map_nominal, _res_16s_1 }, /* 1 */
  153586. { _map_nominal, _res_16s_2 }, /* 2 */
  153587. };
  153588. static static_bookblock _resbook_16u_0={
  153589. {
  153590. {0},
  153591. {0,0,&_16u0__p1_0},
  153592. {0,0,&_16u0__p2_0},
  153593. {0,0,&_16u0__p3_0},
  153594. {0,0,&_16u0__p4_0},
  153595. {0,0,&_16u0__p5_0},
  153596. {&_16u0__p6_0,&_16u0__p6_1},
  153597. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  153598. }
  153599. };
  153600. static static_bookblock _resbook_16u_1={
  153601. {
  153602. {0},
  153603. {0,0,&_16u1__p1_0},
  153604. {0,0,&_16u1__p2_0},
  153605. {0,0,&_16u1__p3_0},
  153606. {0,0,&_16u1__p4_0},
  153607. {0,0,&_16u1__p5_0},
  153608. {0,0,&_16u1__p6_0},
  153609. {&_16u1__p7_0,&_16u1__p7_1},
  153610. {&_16u1__p8_0,&_16u1__p8_1},
  153611. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  153612. }
  153613. };
  153614. static static_bookblock _resbook_16u_2={
  153615. {
  153616. {0},
  153617. {0,0,&_16u2_p1_0},
  153618. {0,0,&_16u2_p2_0},
  153619. {0,0,&_16u2_p3_0},
  153620. {0,0,&_16u2_p4_0},
  153621. {&_16u2_p5_0,&_16u2_p5_1},
  153622. {&_16u2_p6_0,&_16u2_p6_1},
  153623. {&_16u2_p7_0,&_16u2_p7_1},
  153624. {&_16u2_p8_0,&_16u2_p8_1},
  153625. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  153626. }
  153627. };
  153628. static vorbis_residue_template _res_16u_0[]={
  153629. {1,0, &_residue_44_low_un,
  153630. &_huff_book__16u0__single,&_huff_book__16u0__single,
  153631. &_resbook_16u_0,&_resbook_16u_0},
  153632. };
  153633. static vorbis_residue_template _res_16u_1[]={
  153634. {1,0, &_residue_44_mid_un,
  153635. &_huff_book__16u1__short,&_huff_book__16u1__short,
  153636. &_resbook_16u_1,&_resbook_16u_1},
  153637. {1,0, &_residue_44_mid_un,
  153638. &_huff_book__16u1__long,&_huff_book__16u1__long,
  153639. &_resbook_16u_1,&_resbook_16u_1}
  153640. };
  153641. static vorbis_residue_template _res_16u_2[]={
  153642. {1,0, &_residue_44_hi_un,
  153643. &_huff_book__16u2__short,&_huff_book__16u2__short,
  153644. &_resbook_16u_2,&_resbook_16u_2},
  153645. {1,0, &_residue_44_hi_un,
  153646. &_huff_book__16u2__long,&_huff_book__16u2__long,
  153647. &_resbook_16u_2,&_resbook_16u_2}
  153648. };
  153649. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  153650. { _map_nominal_u, _res_16u_0 }, /* 0 */
  153651. { _map_nominal_u, _res_16u_1 }, /* 1 */
  153652. { _map_nominal_u, _res_16u_2 }, /* 2 */
  153653. };
  153654. /*** End of inlined file: residue_16.h ***/
  153655. static int blocksize_16_short[3]={
  153656. 1024,512,512
  153657. };
  153658. static int blocksize_16_long[3]={
  153659. 1024,1024,1024
  153660. };
  153661. static int _floor_mapping_16_short[3]={
  153662. 9,3,3
  153663. };
  153664. static int _floor_mapping_16[3]={
  153665. 9,9,9
  153666. };
  153667. static double rate_mapping_16[4]={
  153668. 12000.,20000.,44000.,86000.
  153669. };
  153670. static double rate_mapping_16_uncoupled[4]={
  153671. 16000.,28000.,64000.,100000.
  153672. };
  153673. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  153674. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  153675. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  153676. ve_setup_data_template ve_setup_16_stereo={
  153677. 3,
  153678. rate_mapping_16,
  153679. quality_mapping_16,
  153680. 2,
  153681. 15000,
  153682. 19000,
  153683. blocksize_16_short,
  153684. blocksize_16_long,
  153685. _psy_tone_masteratt_16,
  153686. _psy_tone_0dB,
  153687. _psy_tone_suppress,
  153688. _vp_tonemask_adj_16,
  153689. _vp_tonemask_adj_16,
  153690. _vp_tonemask_adj_16,
  153691. _psy_noiseguards_8,
  153692. _psy_noisebias_16_impulse,
  153693. _psy_noisebias_16_short,
  153694. _psy_noisebias_16_short,
  153695. _psy_noisebias_16,
  153696. _psy_noise_suppress,
  153697. _psy_compand_8,
  153698. _psy_compand_16_mapping,
  153699. _psy_compand_16_mapping,
  153700. {_noise_start_16,_noise_start_16},
  153701. { _noise_part_16, _noise_part_16},
  153702. _noise_thresh_16,
  153703. _psy_ath_floater_16,
  153704. _psy_ath_abs_16,
  153705. _psy_lowpass_16,
  153706. _psy_global_44,
  153707. _global_mapping_16,
  153708. _psy_stereo_modes_16,
  153709. _floor_books,
  153710. _floor,
  153711. _floor_mapping_16_short,
  153712. _floor_mapping_16,
  153713. _mapres_template_16_stereo
  153714. };
  153715. ve_setup_data_template ve_setup_16_uncoupled={
  153716. 3,
  153717. rate_mapping_16_uncoupled,
  153718. quality_mapping_16,
  153719. -1,
  153720. 15000,
  153721. 19000,
  153722. blocksize_16_short,
  153723. blocksize_16_long,
  153724. _psy_tone_masteratt_16,
  153725. _psy_tone_0dB,
  153726. _psy_tone_suppress,
  153727. _vp_tonemask_adj_16,
  153728. _vp_tonemask_adj_16,
  153729. _vp_tonemask_adj_16,
  153730. _psy_noiseguards_8,
  153731. _psy_noisebias_16_impulse,
  153732. _psy_noisebias_16_short,
  153733. _psy_noisebias_16_short,
  153734. _psy_noisebias_16,
  153735. _psy_noise_suppress,
  153736. _psy_compand_8,
  153737. _psy_compand_16_mapping,
  153738. _psy_compand_16_mapping,
  153739. {_noise_start_16,_noise_start_16},
  153740. { _noise_part_16, _noise_part_16},
  153741. _noise_thresh_16,
  153742. _psy_ath_floater_16,
  153743. _psy_ath_abs_16,
  153744. _psy_lowpass_16,
  153745. _psy_global_44,
  153746. _global_mapping_16,
  153747. _psy_stereo_modes_16,
  153748. _floor_books,
  153749. _floor,
  153750. _floor_mapping_16_short,
  153751. _floor_mapping_16,
  153752. _mapres_template_16_uncoupled
  153753. };
  153754. /*** End of inlined file: setup_16.h ***/
  153755. /*** Start of inlined file: setup_22.h ***/
  153756. static double rate_mapping_22[4]={
  153757. 15000.,20000.,44000.,86000.
  153758. };
  153759. static double rate_mapping_22_uncoupled[4]={
  153760. 16000.,28000.,50000.,90000.
  153761. };
  153762. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  153763. ve_setup_data_template ve_setup_22_stereo={
  153764. 3,
  153765. rate_mapping_22,
  153766. quality_mapping_16,
  153767. 2,
  153768. 19000,
  153769. 26000,
  153770. blocksize_16_short,
  153771. blocksize_16_long,
  153772. _psy_tone_masteratt_16,
  153773. _psy_tone_0dB,
  153774. _psy_tone_suppress,
  153775. _vp_tonemask_adj_16,
  153776. _vp_tonemask_adj_16,
  153777. _vp_tonemask_adj_16,
  153778. _psy_noiseguards_8,
  153779. _psy_noisebias_16_impulse,
  153780. _psy_noisebias_16_short,
  153781. _psy_noisebias_16_short,
  153782. _psy_noisebias_16,
  153783. _psy_noise_suppress,
  153784. _psy_compand_8,
  153785. _psy_compand_8_mapping,
  153786. _psy_compand_8_mapping,
  153787. {_noise_start_16,_noise_start_16},
  153788. { _noise_part_16, _noise_part_16},
  153789. _noise_thresh_16,
  153790. _psy_ath_floater_16,
  153791. _psy_ath_abs_16,
  153792. _psy_lowpass_22,
  153793. _psy_global_44,
  153794. _global_mapping_16,
  153795. _psy_stereo_modes_16,
  153796. _floor_books,
  153797. _floor,
  153798. _floor_mapping_16_short,
  153799. _floor_mapping_16,
  153800. _mapres_template_16_stereo
  153801. };
  153802. ve_setup_data_template ve_setup_22_uncoupled={
  153803. 3,
  153804. rate_mapping_22_uncoupled,
  153805. quality_mapping_16,
  153806. -1,
  153807. 19000,
  153808. 26000,
  153809. blocksize_16_short,
  153810. blocksize_16_long,
  153811. _psy_tone_masteratt_16,
  153812. _psy_tone_0dB,
  153813. _psy_tone_suppress,
  153814. _vp_tonemask_adj_16,
  153815. _vp_tonemask_adj_16,
  153816. _vp_tonemask_adj_16,
  153817. _psy_noiseguards_8,
  153818. _psy_noisebias_16_impulse,
  153819. _psy_noisebias_16_short,
  153820. _psy_noisebias_16_short,
  153821. _psy_noisebias_16,
  153822. _psy_noise_suppress,
  153823. _psy_compand_8,
  153824. _psy_compand_8_mapping,
  153825. _psy_compand_8_mapping,
  153826. {_noise_start_16,_noise_start_16},
  153827. { _noise_part_16, _noise_part_16},
  153828. _noise_thresh_16,
  153829. _psy_ath_floater_16,
  153830. _psy_ath_abs_16,
  153831. _psy_lowpass_22,
  153832. _psy_global_44,
  153833. _global_mapping_16,
  153834. _psy_stereo_modes_16,
  153835. _floor_books,
  153836. _floor,
  153837. _floor_mapping_16_short,
  153838. _floor_mapping_16,
  153839. _mapres_template_16_uncoupled
  153840. };
  153841. /*** End of inlined file: setup_22.h ***/
  153842. /*** Start of inlined file: setup_X.h ***/
  153843. static double rate_mapping_X[12]={
  153844. -1.,-1.,-1.,-1.,-1.,-1.,
  153845. -1.,-1.,-1.,-1.,-1.,-1.
  153846. };
  153847. ve_setup_data_template ve_setup_X_stereo={
  153848. 11,
  153849. rate_mapping_X,
  153850. quality_mapping_44,
  153851. 2,
  153852. 50000,
  153853. 200000,
  153854. blocksize_short_44,
  153855. blocksize_long_44,
  153856. _psy_tone_masteratt_44,
  153857. _psy_tone_0dB,
  153858. _psy_tone_suppress,
  153859. _vp_tonemask_adj_otherblock,
  153860. _vp_tonemask_adj_longblock,
  153861. _vp_tonemask_adj_otherblock,
  153862. _psy_noiseguards_44,
  153863. _psy_noisebias_impulse,
  153864. _psy_noisebias_padding,
  153865. _psy_noisebias_trans,
  153866. _psy_noisebias_long,
  153867. _psy_noise_suppress,
  153868. _psy_compand_44,
  153869. _psy_compand_short_mapping,
  153870. _psy_compand_long_mapping,
  153871. {_noise_start_short_44,_noise_start_long_44},
  153872. {_noise_part_short_44,_noise_part_long_44},
  153873. _noise_thresh_44,
  153874. _psy_ath_floater,
  153875. _psy_ath_abs,
  153876. _psy_lowpass_44,
  153877. _psy_global_44,
  153878. _global_mapping_44,
  153879. _psy_stereo_modes_44,
  153880. _floor_books,
  153881. _floor,
  153882. _floor_short_mapping_44,
  153883. _floor_long_mapping_44,
  153884. _mapres_template_44_stereo
  153885. };
  153886. ve_setup_data_template ve_setup_X_uncoupled={
  153887. 11,
  153888. rate_mapping_X,
  153889. quality_mapping_44,
  153890. -1,
  153891. 50000,
  153892. 200000,
  153893. blocksize_short_44,
  153894. blocksize_long_44,
  153895. _psy_tone_masteratt_44,
  153896. _psy_tone_0dB,
  153897. _psy_tone_suppress,
  153898. _vp_tonemask_adj_otherblock,
  153899. _vp_tonemask_adj_longblock,
  153900. _vp_tonemask_adj_otherblock,
  153901. _psy_noiseguards_44,
  153902. _psy_noisebias_impulse,
  153903. _psy_noisebias_padding,
  153904. _psy_noisebias_trans,
  153905. _psy_noisebias_long,
  153906. _psy_noise_suppress,
  153907. _psy_compand_44,
  153908. _psy_compand_short_mapping,
  153909. _psy_compand_long_mapping,
  153910. {_noise_start_short_44,_noise_start_long_44},
  153911. {_noise_part_short_44,_noise_part_long_44},
  153912. _noise_thresh_44,
  153913. _psy_ath_floater,
  153914. _psy_ath_abs,
  153915. _psy_lowpass_44,
  153916. _psy_global_44,
  153917. _global_mapping_44,
  153918. NULL,
  153919. _floor_books,
  153920. _floor,
  153921. _floor_short_mapping_44,
  153922. _floor_long_mapping_44,
  153923. _mapres_template_44_uncoupled
  153924. };
  153925. ve_setup_data_template ve_setup_XX_stereo={
  153926. 2,
  153927. rate_mapping_X,
  153928. quality_mapping_8,
  153929. 2,
  153930. 0,
  153931. 8000,
  153932. blocksize_8,
  153933. blocksize_8,
  153934. _psy_tone_masteratt_8,
  153935. _psy_tone_0dB,
  153936. _psy_tone_suppress,
  153937. _vp_tonemask_adj_8,
  153938. NULL,
  153939. _vp_tonemask_adj_8,
  153940. _psy_noiseguards_8,
  153941. _psy_noisebias_8,
  153942. _psy_noisebias_8,
  153943. NULL,
  153944. NULL,
  153945. _psy_noise_suppress,
  153946. _psy_compand_8,
  153947. _psy_compand_8_mapping,
  153948. NULL,
  153949. {_noise_start_8,_noise_start_8},
  153950. {_noise_part_8,_noise_part_8},
  153951. _noise_thresh_5only,
  153952. _psy_ath_floater_8,
  153953. _psy_ath_abs_8,
  153954. _psy_lowpass_8,
  153955. _psy_global_44,
  153956. _global_mapping_8,
  153957. _psy_stereo_modes_8,
  153958. _floor_books,
  153959. _floor,
  153960. _floor_mapping_8,
  153961. NULL,
  153962. _mapres_template_8_stereo
  153963. };
  153964. ve_setup_data_template ve_setup_XX_uncoupled={
  153965. 2,
  153966. rate_mapping_X,
  153967. quality_mapping_8,
  153968. -1,
  153969. 0,
  153970. 8000,
  153971. blocksize_8,
  153972. blocksize_8,
  153973. _psy_tone_masteratt_8,
  153974. _psy_tone_0dB,
  153975. _psy_tone_suppress,
  153976. _vp_tonemask_adj_8,
  153977. NULL,
  153978. _vp_tonemask_adj_8,
  153979. _psy_noiseguards_8,
  153980. _psy_noisebias_8,
  153981. _psy_noisebias_8,
  153982. NULL,
  153983. NULL,
  153984. _psy_noise_suppress,
  153985. _psy_compand_8,
  153986. _psy_compand_8_mapping,
  153987. NULL,
  153988. {_noise_start_8,_noise_start_8},
  153989. {_noise_part_8,_noise_part_8},
  153990. _noise_thresh_5only,
  153991. _psy_ath_floater_8,
  153992. _psy_ath_abs_8,
  153993. _psy_lowpass_8,
  153994. _psy_global_44,
  153995. _global_mapping_8,
  153996. _psy_stereo_modes_8,
  153997. _floor_books,
  153998. _floor,
  153999. _floor_mapping_8,
  154000. NULL,
  154001. _mapres_template_8_uncoupled
  154002. };
  154003. /*** End of inlined file: setup_X.h ***/
  154004. static ve_setup_data_template *setup_list[]={
  154005. &ve_setup_44_stereo,
  154006. &ve_setup_44_uncoupled,
  154007. &ve_setup_32_stereo,
  154008. &ve_setup_32_uncoupled,
  154009. &ve_setup_22_stereo,
  154010. &ve_setup_22_uncoupled,
  154011. &ve_setup_16_stereo,
  154012. &ve_setup_16_uncoupled,
  154013. &ve_setup_11_stereo,
  154014. &ve_setup_11_uncoupled,
  154015. &ve_setup_8_stereo,
  154016. &ve_setup_8_uncoupled,
  154017. &ve_setup_X_stereo,
  154018. &ve_setup_X_uncoupled,
  154019. &ve_setup_XX_stereo,
  154020. &ve_setup_XX_uncoupled,
  154021. 0
  154022. };
  154023. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154024. if(vi && vi->codec_setup){
  154025. vi->version=0;
  154026. vi->channels=ch;
  154027. vi->rate=rate;
  154028. return(0);
  154029. }
  154030. return(OV_EINVAL);
  154031. }
  154032. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154033. static_codebook ***books,
  154034. vorbis_info_floor1 *in,
  154035. int *x){
  154036. int i,k,is=s;
  154037. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154038. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154039. memcpy(f,in+x[is],sizeof(*f));
  154040. /* fill in the lowpass field, even if it's temporary */
  154041. f->n=ci->blocksizes[block]>>1;
  154042. /* books */
  154043. {
  154044. int partitions=f->partitions;
  154045. int maxclass=-1;
  154046. int maxbook=-1;
  154047. for(i=0;i<partitions;i++)
  154048. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154049. for(i=0;i<=maxclass;i++){
  154050. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154051. f->class_book[i]+=ci->books;
  154052. for(k=0;k<(1<<f->class_subs[i]);k++){
  154053. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154054. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154055. }
  154056. }
  154057. for(i=0;i<=maxbook;i++)
  154058. ci->book_param[ci->books++]=books[x[is]][i];
  154059. }
  154060. /* for now, we're only using floor 1 */
  154061. ci->floor_type[ci->floors]=1;
  154062. ci->floor_param[ci->floors]=f;
  154063. ci->floors++;
  154064. return;
  154065. }
  154066. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154067. vorbis_info_psy_global *in,
  154068. double *x){
  154069. int i,is=s;
  154070. double ds=s-is;
  154071. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154072. vorbis_info_psy_global *g=&ci->psy_g_param;
  154073. memcpy(g,in+(int)x[is],sizeof(*g));
  154074. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154075. is=(int)ds;
  154076. ds-=is;
  154077. if(ds==0 && is>0){
  154078. is--;
  154079. ds=1.;
  154080. }
  154081. /* interpolate the trigger threshholds */
  154082. for(i=0;i<4;i++){
  154083. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154084. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154085. }
  154086. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154087. return;
  154088. }
  154089. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154090. highlevel_encode_setup *hi,
  154091. adj_stereo *p){
  154092. float s=hi->stereo_point_setting;
  154093. int i,is=s;
  154094. double ds=s-is;
  154095. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154096. vorbis_info_psy_global *g=&ci->psy_g_param;
  154097. if(p){
  154098. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154099. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154100. if(hi->managed){
  154101. /* interpolate the kHz threshholds */
  154102. for(i=0;i<PACKETBLOBS;i++){
  154103. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154104. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154105. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154106. g->coupling_pkHz[i]=kHz;
  154107. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154108. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154109. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154110. }
  154111. }else{
  154112. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154113. for(i=0;i<PACKETBLOBS;i++){
  154114. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154115. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154116. g->coupling_pkHz[i]=kHz;
  154117. }
  154118. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154119. for(i=0;i<PACKETBLOBS;i++){
  154120. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154121. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154122. }
  154123. }
  154124. }else{
  154125. for(i=0;i<PACKETBLOBS;i++){
  154126. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154127. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154128. }
  154129. }
  154130. return;
  154131. }
  154132. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154133. int *nn_start,
  154134. int *nn_partition,
  154135. double *nn_thresh,
  154136. int block){
  154137. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154138. vorbis_info_psy *p=ci->psy_param[block];
  154139. highlevel_encode_setup *hi=&ci->hi;
  154140. int is=s;
  154141. if(block>=ci->psys)
  154142. ci->psys=block+1;
  154143. if(!p){
  154144. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154145. ci->psy_param[block]=p;
  154146. }
  154147. memcpy(p,&_psy_info_template,sizeof(*p));
  154148. p->blockflag=block>>1;
  154149. if(hi->noise_normalize_p){
  154150. p->normal_channel_p=1;
  154151. p->normal_point_p=1;
  154152. p->normal_start=nn_start[is];
  154153. p->normal_partition=nn_partition[is];
  154154. p->normal_thresh=nn_thresh[is];
  154155. }
  154156. return;
  154157. }
  154158. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154159. att3 *att,
  154160. int *max,
  154161. vp_adjblock *in){
  154162. int i,is=s;
  154163. double ds=s-is;
  154164. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154165. vorbis_info_psy *p=ci->psy_param[block];
  154166. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154167. filling the values in here */
  154168. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154169. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154170. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154171. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154172. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154173. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154174. for(i=0;i<P_BANDS;i++)
  154175. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154176. return;
  154177. }
  154178. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154179. compandblock *in, double *x){
  154180. int i,is=s;
  154181. double ds=s-is;
  154182. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154183. vorbis_info_psy *p=ci->psy_param[block];
  154184. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154185. is=(int)ds;
  154186. ds-=is;
  154187. if(ds==0 && is>0){
  154188. is--;
  154189. ds=1.;
  154190. }
  154191. /* interpolate the compander settings */
  154192. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154193. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154194. return;
  154195. }
  154196. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154197. int *suppress){
  154198. int is=s;
  154199. double ds=s-is;
  154200. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154201. vorbis_info_psy *p=ci->psy_param[block];
  154202. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154203. return;
  154204. }
  154205. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154206. int *suppress,
  154207. noise3 *in,
  154208. noiseguard *guard,
  154209. double userbias){
  154210. int i,is=s,j;
  154211. double ds=s-is;
  154212. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154213. vorbis_info_psy *p=ci->psy_param[block];
  154214. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154215. p->noisewindowlomin=guard[block].lo;
  154216. p->noisewindowhimin=guard[block].hi;
  154217. p->noisewindowfixed=guard[block].fixed;
  154218. for(j=0;j<P_NOISECURVES;j++)
  154219. for(i=0;i<P_BANDS;i++)
  154220. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154221. /* impulse blocks may take a user specified bias to boost the
  154222. nominal/high noise encoding depth */
  154223. for(j=0;j<P_NOISECURVES;j++){
  154224. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154225. for(i=0;i<P_BANDS;i++){
  154226. p->noiseoff[j][i]+=userbias;
  154227. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154228. }
  154229. }
  154230. return;
  154231. }
  154232. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154233. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154234. vorbis_info_psy *p=ci->psy_param[block];
  154235. p->ath_adjatt=ci->hi.ath_floating_dB;
  154236. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154237. return;
  154238. }
  154239. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154240. int i;
  154241. for(i=0;i<ci->books;i++)
  154242. if(ci->book_param[i]==book)return(i);
  154243. return(ci->books++);
  154244. }
  154245. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154246. int *shortb,int *longb){
  154247. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154248. int is=s;
  154249. int blockshort=shortb[is];
  154250. int blocklong=longb[is];
  154251. ci->blocksizes[0]=blockshort;
  154252. ci->blocksizes[1]=blocklong;
  154253. }
  154254. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154255. int number, int block,
  154256. vorbis_residue_template *res){
  154257. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154258. int i,n;
  154259. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154260. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154261. memcpy(r,res->res,sizeof(*r));
  154262. if(ci->residues<=number)ci->residues=number+1;
  154263. switch(ci->blocksizes[block]){
  154264. case 64:case 128:case 256:
  154265. r->grouping=16;
  154266. break;
  154267. default:
  154268. r->grouping=32;
  154269. break;
  154270. }
  154271. ci->residue_type[number]=res->res_type;
  154272. /* to be adjusted by lowpass/pointlimit later */
  154273. n=r->end=ci->blocksizes[block]>>1;
  154274. if(res->res_type==2)
  154275. n=r->end*=vi->channels;
  154276. /* fill in all the books */
  154277. {
  154278. int booklist=0,k;
  154279. if(ci->hi.managed){
  154280. for(i=0;i<r->partitions;i++)
  154281. for(k=0;k<3;k++)
  154282. if(res->books_base_managed->books[i][k])
  154283. r->secondstages[i]|=(1<<k);
  154284. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  154285. ci->book_param[r->groupbook]=res->book_aux_managed;
  154286. for(i=0;i<r->partitions;i++){
  154287. for(k=0;k<3;k++){
  154288. if(res->books_base_managed->books[i][k]){
  154289. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  154290. r->booklist[booklist++]=bookid;
  154291. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  154292. }
  154293. }
  154294. }
  154295. }else{
  154296. for(i=0;i<r->partitions;i++)
  154297. for(k=0;k<3;k++)
  154298. if(res->books_base->books[i][k])
  154299. r->secondstages[i]|=(1<<k);
  154300. r->groupbook=book_dup_or_new(ci,res->book_aux);
  154301. ci->book_param[r->groupbook]=res->book_aux;
  154302. for(i=0;i<r->partitions;i++){
  154303. for(k=0;k<3;k++){
  154304. if(res->books_base->books[i][k]){
  154305. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154306. r->booklist[booklist++]=bookid;
  154307. ci->book_param[bookid]=res->books_base->books[i][k];
  154308. }
  154309. }
  154310. }
  154311. }
  154312. }
  154313. /* lowpass setup/pointlimit */
  154314. {
  154315. double freq=ci->hi.lowpass_kHz*1000.;
  154316. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154317. double nyq=vi->rate/2.;
  154318. long blocksize=ci->blocksizes[block]>>1;
  154319. /* lowpass needs to be set in the floor and the residue. */
  154320. if(freq>nyq)freq=nyq;
  154321. /* in the floor, the granularity can be very fine; it doesn't alter
  154322. the encoding structure, only the samples used to fit the floor
  154323. approximation */
  154324. f->n=freq/nyq*blocksize;
  154325. /* this res may by limited by the maximum pointlimit of the mode,
  154326. not the lowpass. the floor is always lowpass limited. */
  154327. if(res->limit_type){
  154328. if(ci->hi.managed)
  154329. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154330. else
  154331. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154332. if(freq>nyq)freq=nyq;
  154333. }
  154334. /* in the residue, we're constrained, physically, by partition
  154335. boundaries. We still lowpass 'wherever', but we have to round up
  154336. here to next boundary, or the vorbis spec will round it *down* to
  154337. previous boundary in encode/decode */
  154338. if(ci->residue_type[block]==2)
  154339. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154340. r->grouping;
  154341. else
  154342. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154343. r->grouping;
  154344. }
  154345. }
  154346. /* we assume two maps in this encoder */
  154347. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154348. vorbis_mapping_template *maps){
  154349. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154350. int i,j,is=s,modes=2;
  154351. vorbis_info_mapping0 *map=maps[is].map;
  154352. vorbis_info_mode *mode=_mode_template;
  154353. vorbis_residue_template *res=maps[is].res;
  154354. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154355. for(i=0;i<modes;i++){
  154356. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154357. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154358. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154359. if(i>=ci->modes)ci->modes=i+1;
  154360. ci->map_type[i]=0;
  154361. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154362. if(i>=ci->maps)ci->maps=i+1;
  154363. for(j=0;j<map[i].submaps;j++)
  154364. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154365. ,res+map[i].residuesubmap[j]);
  154366. }
  154367. }
  154368. static double setting_to_approx_bitrate(vorbis_info *vi){
  154369. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154370. highlevel_encode_setup *hi=&ci->hi;
  154371. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  154372. int is=hi->base_setting;
  154373. double ds=hi->base_setting-is;
  154374. int ch=vi->channels;
  154375. double *r=setup->rate_mapping;
  154376. if(r==NULL)
  154377. return(-1);
  154378. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  154379. }
  154380. static void get_setup_template(vorbis_info *vi,
  154381. long ch,long srate,
  154382. double req,int q_or_bitrate){
  154383. int i=0,j;
  154384. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154385. highlevel_encode_setup *hi=&ci->hi;
  154386. if(q_or_bitrate)req/=ch;
  154387. while(setup_list[i]){
  154388. if(setup_list[i]->coupling_restriction==-1 ||
  154389. setup_list[i]->coupling_restriction==ch){
  154390. if(srate>=setup_list[i]->samplerate_min_restriction &&
  154391. srate<=setup_list[i]->samplerate_max_restriction){
  154392. int mappings=setup_list[i]->mappings;
  154393. double *map=(q_or_bitrate?
  154394. setup_list[i]->rate_mapping:
  154395. setup_list[i]->quality_mapping);
  154396. /* the template matches. Does the requested quality mode
  154397. fall within this template's modes? */
  154398. if(req<map[0]){++i;continue;}
  154399. if(req>map[setup_list[i]->mappings]){++i;continue;}
  154400. for(j=0;j<mappings;j++)
  154401. if(req>=map[j] && req<map[j+1])break;
  154402. /* an all-points match */
  154403. hi->setup=setup_list[i];
  154404. if(j==mappings)
  154405. hi->base_setting=j-.001;
  154406. else{
  154407. float low=map[j];
  154408. float high=map[j+1];
  154409. float del=(req-low)/(high-low);
  154410. hi->base_setting=j+del;
  154411. }
  154412. return;
  154413. }
  154414. }
  154415. i++;
  154416. }
  154417. hi->setup=NULL;
  154418. }
  154419. /* encoders will need to use vorbis_info_init beforehand and call
  154420. vorbis_info clear when all done */
  154421. /* two interfaces; this, more detailed one, and later a convenience
  154422. layer on top */
  154423. /* the final setup call */
  154424. int vorbis_encode_setup_init(vorbis_info *vi){
  154425. int i0=0,singleblock=0;
  154426. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154427. ve_setup_data_template *setup=NULL;
  154428. highlevel_encode_setup *hi=&ci->hi;
  154429. if(ci==NULL)return(OV_EINVAL);
  154430. if(!hi->impulse_block_p)i0=1;
  154431. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  154432. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  154433. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  154434. /* again, bound this to avoid the app shooting itself int he foot
  154435. too badly */
  154436. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  154437. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  154438. /* get the appropriate setup template; matches the fetch in previous
  154439. stages */
  154440. setup=(ve_setup_data_template *)hi->setup;
  154441. if(setup==NULL)return(OV_EINVAL);
  154442. hi->set_in_stone=1;
  154443. /* choose block sizes from configured sizes as well as paying
  154444. attention to long_block_p and short_block_p. If the configured
  154445. short and long blocks are the same length, we set long_block_p
  154446. and unset short_block_p */
  154447. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  154448. setup->blocksize_short,
  154449. setup->blocksize_long);
  154450. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  154451. /* floor setup; choose proper floor params. Allocated on the floor
  154452. stack in order; if we alloc only long floor, it's 0 */
  154453. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  154454. setup->floor_books,
  154455. setup->floor_params,
  154456. setup->floor_short_mapping);
  154457. if(!singleblock)
  154458. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  154459. setup->floor_books,
  154460. setup->floor_params,
  154461. setup->floor_long_mapping);
  154462. /* setup of [mostly] short block detection and stereo*/
  154463. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  154464. setup->global_params,
  154465. setup->global_mapping);
  154466. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  154467. /* basic psych setup and noise normalization */
  154468. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154469. setup->psy_noise_normal_start[0],
  154470. setup->psy_noise_normal_partition[0],
  154471. setup->psy_noise_normal_thresh,
  154472. 0);
  154473. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154474. setup->psy_noise_normal_start[0],
  154475. setup->psy_noise_normal_partition[0],
  154476. setup->psy_noise_normal_thresh,
  154477. 1);
  154478. if(!singleblock){
  154479. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154480. setup->psy_noise_normal_start[1],
  154481. setup->psy_noise_normal_partition[1],
  154482. setup->psy_noise_normal_thresh,
  154483. 2);
  154484. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154485. setup->psy_noise_normal_start[1],
  154486. setup->psy_noise_normal_partition[1],
  154487. setup->psy_noise_normal_thresh,
  154488. 3);
  154489. }
  154490. /* tone masking setup */
  154491. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  154492. setup->psy_tone_masteratt,
  154493. setup->psy_tone_0dB,
  154494. setup->psy_tone_adj_impulse);
  154495. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  154496. setup->psy_tone_masteratt,
  154497. setup->psy_tone_0dB,
  154498. setup->psy_tone_adj_other);
  154499. if(!singleblock){
  154500. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  154501. setup->psy_tone_masteratt,
  154502. setup->psy_tone_0dB,
  154503. setup->psy_tone_adj_other);
  154504. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  154505. setup->psy_tone_masteratt,
  154506. setup->psy_tone_0dB,
  154507. setup->psy_tone_adj_long);
  154508. }
  154509. /* noise companding setup */
  154510. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  154511. setup->psy_noise_compand,
  154512. setup->psy_noise_compand_short_mapping);
  154513. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  154514. setup->psy_noise_compand,
  154515. setup->psy_noise_compand_short_mapping);
  154516. if(!singleblock){
  154517. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  154518. setup->psy_noise_compand,
  154519. setup->psy_noise_compand_long_mapping);
  154520. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  154521. setup->psy_noise_compand,
  154522. setup->psy_noise_compand_long_mapping);
  154523. }
  154524. /* peak guarding setup */
  154525. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  154526. setup->psy_tone_dBsuppress);
  154527. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  154528. setup->psy_tone_dBsuppress);
  154529. if(!singleblock){
  154530. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  154531. setup->psy_tone_dBsuppress);
  154532. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  154533. setup->psy_tone_dBsuppress);
  154534. }
  154535. /* noise bias setup */
  154536. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  154537. setup->psy_noise_dBsuppress,
  154538. setup->psy_noise_bias_impulse,
  154539. setup->psy_noiseguards,
  154540. (i0==0?hi->impulse_noisetune:0.));
  154541. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  154542. setup->psy_noise_dBsuppress,
  154543. setup->psy_noise_bias_padding,
  154544. setup->psy_noiseguards,0.);
  154545. if(!singleblock){
  154546. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  154547. setup->psy_noise_dBsuppress,
  154548. setup->psy_noise_bias_trans,
  154549. setup->psy_noiseguards,0.);
  154550. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  154551. setup->psy_noise_dBsuppress,
  154552. setup->psy_noise_bias_long,
  154553. setup->psy_noiseguards,0.);
  154554. }
  154555. vorbis_encode_ath_setup(vi,0);
  154556. vorbis_encode_ath_setup(vi,1);
  154557. if(!singleblock){
  154558. vorbis_encode_ath_setup(vi,2);
  154559. vorbis_encode_ath_setup(vi,3);
  154560. }
  154561. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  154562. /* set bitrate readonlies and management */
  154563. if(hi->bitrate_av>0)
  154564. vi->bitrate_nominal=hi->bitrate_av;
  154565. else{
  154566. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  154567. }
  154568. vi->bitrate_lower=hi->bitrate_min;
  154569. vi->bitrate_upper=hi->bitrate_max;
  154570. if(hi->bitrate_av)
  154571. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  154572. else
  154573. vi->bitrate_window=0.;
  154574. if(hi->managed){
  154575. ci->bi.avg_rate=hi->bitrate_av;
  154576. ci->bi.min_rate=hi->bitrate_min;
  154577. ci->bi.max_rate=hi->bitrate_max;
  154578. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  154579. ci->bi.reservoir_bias=
  154580. hi->bitrate_reservoir_bias;
  154581. ci->bi.slew_damp=hi->bitrate_av_damp;
  154582. }
  154583. return(0);
  154584. }
  154585. static int vorbis_encode_setup_setting(vorbis_info *vi,
  154586. long channels,
  154587. long rate){
  154588. int ret=0,i,is;
  154589. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154590. highlevel_encode_setup *hi=&ci->hi;
  154591. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  154592. double ds;
  154593. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  154594. if(ret)return(ret);
  154595. is=hi->base_setting;
  154596. ds=hi->base_setting-is;
  154597. hi->short_setting=hi->base_setting;
  154598. hi->long_setting=hi->base_setting;
  154599. hi->managed=0;
  154600. hi->impulse_block_p=1;
  154601. hi->noise_normalize_p=1;
  154602. hi->stereo_point_setting=hi->base_setting;
  154603. hi->lowpass_kHz=
  154604. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  154605. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  154606. setup->psy_ath_float[is+1]*ds;
  154607. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  154608. setup->psy_ath_abs[is+1]*ds;
  154609. hi->amplitude_track_dBpersec=-6.;
  154610. hi->trigger_setting=hi->base_setting;
  154611. for(i=0;i<4;i++){
  154612. hi->block[i].tone_mask_setting=hi->base_setting;
  154613. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  154614. hi->block[i].noise_bias_setting=hi->base_setting;
  154615. hi->block[i].noise_compand_setting=hi->base_setting;
  154616. }
  154617. return(ret);
  154618. }
  154619. int vorbis_encode_setup_vbr(vorbis_info *vi,
  154620. long channels,
  154621. long rate,
  154622. float quality){
  154623. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154624. highlevel_encode_setup *hi=&ci->hi;
  154625. quality+=.0000001;
  154626. if(quality>=1.)quality=.9999;
  154627. get_setup_template(vi,channels,rate,quality,0);
  154628. if(!hi->setup)return OV_EIMPL;
  154629. return vorbis_encode_setup_setting(vi,channels,rate);
  154630. }
  154631. int vorbis_encode_init_vbr(vorbis_info *vi,
  154632. long channels,
  154633. long rate,
  154634. float base_quality /* 0. to 1. */
  154635. ){
  154636. int ret=0;
  154637. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  154638. if(ret){
  154639. vorbis_info_clear(vi);
  154640. return ret;
  154641. }
  154642. ret=vorbis_encode_setup_init(vi);
  154643. if(ret)
  154644. vorbis_info_clear(vi);
  154645. return(ret);
  154646. }
  154647. int vorbis_encode_setup_managed(vorbis_info *vi,
  154648. long channels,
  154649. long rate,
  154650. long max_bitrate,
  154651. long nominal_bitrate,
  154652. long min_bitrate){
  154653. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154654. highlevel_encode_setup *hi=&ci->hi;
  154655. double tnominal=nominal_bitrate;
  154656. int ret=0;
  154657. if(nominal_bitrate<=0.){
  154658. if(max_bitrate>0.){
  154659. if(min_bitrate>0.)
  154660. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  154661. else
  154662. nominal_bitrate=max_bitrate*.875;
  154663. }else{
  154664. if(min_bitrate>0.){
  154665. nominal_bitrate=min_bitrate;
  154666. }else{
  154667. return(OV_EINVAL);
  154668. }
  154669. }
  154670. }
  154671. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  154672. if(!hi->setup)return OV_EIMPL;
  154673. ret=vorbis_encode_setup_setting(vi,channels,rate);
  154674. if(ret){
  154675. vorbis_info_clear(vi);
  154676. return ret;
  154677. }
  154678. /* initialize management with sane defaults */
  154679. hi->managed=1;
  154680. hi->bitrate_min=min_bitrate;
  154681. hi->bitrate_max=max_bitrate;
  154682. hi->bitrate_av=tnominal;
  154683. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  154684. hi->bitrate_reservoir=nominal_bitrate*2;
  154685. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  154686. return(ret);
  154687. }
  154688. int vorbis_encode_init(vorbis_info *vi,
  154689. long channels,
  154690. long rate,
  154691. long max_bitrate,
  154692. long nominal_bitrate,
  154693. long min_bitrate){
  154694. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  154695. max_bitrate,
  154696. nominal_bitrate,
  154697. min_bitrate);
  154698. if(ret){
  154699. vorbis_info_clear(vi);
  154700. return(ret);
  154701. }
  154702. ret=vorbis_encode_setup_init(vi);
  154703. if(ret)
  154704. vorbis_info_clear(vi);
  154705. return(ret);
  154706. }
  154707. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  154708. if(vi){
  154709. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154710. highlevel_encode_setup *hi=&ci->hi;
  154711. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  154712. if(setp && hi->set_in_stone)return(OV_EINVAL);
  154713. switch(number){
  154714. /* now deprecated *****************/
  154715. case OV_ECTL_RATEMANAGE_GET:
  154716. {
  154717. struct ovectl_ratemanage_arg *ai=
  154718. (struct ovectl_ratemanage_arg *)arg;
  154719. ai->management_active=hi->managed;
  154720. ai->bitrate_hard_window=ai->bitrate_av_window=
  154721. (double)hi->bitrate_reservoir/vi->rate;
  154722. ai->bitrate_av_window_center=1.;
  154723. ai->bitrate_hard_min=hi->bitrate_min;
  154724. ai->bitrate_hard_max=hi->bitrate_max;
  154725. ai->bitrate_av_lo=hi->bitrate_av;
  154726. ai->bitrate_av_hi=hi->bitrate_av;
  154727. }
  154728. return(0);
  154729. /* now deprecated *****************/
  154730. case OV_ECTL_RATEMANAGE_SET:
  154731. {
  154732. struct ovectl_ratemanage_arg *ai=
  154733. (struct ovectl_ratemanage_arg *)arg;
  154734. if(ai==NULL){
  154735. hi->managed=0;
  154736. }else{
  154737. hi->managed=ai->management_active;
  154738. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  154739. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  154740. }
  154741. }
  154742. return 0;
  154743. /* now deprecated *****************/
  154744. case OV_ECTL_RATEMANAGE_AVG:
  154745. {
  154746. struct ovectl_ratemanage_arg *ai=
  154747. (struct ovectl_ratemanage_arg *)arg;
  154748. if(ai==NULL){
  154749. hi->bitrate_av=0;
  154750. }else{
  154751. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  154752. }
  154753. }
  154754. return(0);
  154755. /* now deprecated *****************/
  154756. case OV_ECTL_RATEMANAGE_HARD:
  154757. {
  154758. struct ovectl_ratemanage_arg *ai=
  154759. (struct ovectl_ratemanage_arg *)arg;
  154760. if(ai==NULL){
  154761. hi->bitrate_min=0;
  154762. hi->bitrate_max=0;
  154763. }else{
  154764. hi->bitrate_min=ai->bitrate_hard_min;
  154765. hi->bitrate_max=ai->bitrate_hard_max;
  154766. hi->bitrate_reservoir=ai->bitrate_hard_window*
  154767. (hi->bitrate_max+hi->bitrate_min)*.5;
  154768. }
  154769. if(hi->bitrate_reservoir<128.)
  154770. hi->bitrate_reservoir=128.;
  154771. }
  154772. return(0);
  154773. /* replacement ratemanage interface */
  154774. case OV_ECTL_RATEMANAGE2_GET:
  154775. {
  154776. struct ovectl_ratemanage2_arg *ai=
  154777. (struct ovectl_ratemanage2_arg *)arg;
  154778. if(ai==NULL)return OV_EINVAL;
  154779. ai->management_active=hi->managed;
  154780. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  154781. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  154782. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  154783. ai->bitrate_average_damping=hi->bitrate_av_damp;
  154784. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  154785. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  154786. }
  154787. return (0);
  154788. case OV_ECTL_RATEMANAGE2_SET:
  154789. {
  154790. struct ovectl_ratemanage2_arg *ai=
  154791. (struct ovectl_ratemanage2_arg *)arg;
  154792. if(ai==NULL){
  154793. hi->managed=0;
  154794. }else{
  154795. /* sanity check; only catch invariant violations */
  154796. if(ai->bitrate_limit_min_kbps>0 &&
  154797. ai->bitrate_average_kbps>0 &&
  154798. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  154799. return OV_EINVAL;
  154800. if(ai->bitrate_limit_max_kbps>0 &&
  154801. ai->bitrate_average_kbps>0 &&
  154802. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  154803. return OV_EINVAL;
  154804. if(ai->bitrate_limit_min_kbps>0 &&
  154805. ai->bitrate_limit_max_kbps>0 &&
  154806. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  154807. return OV_EINVAL;
  154808. if(ai->bitrate_average_damping <= 0.)
  154809. return OV_EINVAL;
  154810. if(ai->bitrate_limit_reservoir_bits < 0)
  154811. return OV_EINVAL;
  154812. if(ai->bitrate_limit_reservoir_bias < 0.)
  154813. return OV_EINVAL;
  154814. if(ai->bitrate_limit_reservoir_bias > 1.)
  154815. return OV_EINVAL;
  154816. hi->managed=ai->management_active;
  154817. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  154818. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  154819. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  154820. hi->bitrate_av_damp=ai->bitrate_average_damping;
  154821. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  154822. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  154823. }
  154824. }
  154825. return 0;
  154826. case OV_ECTL_LOWPASS_GET:
  154827. {
  154828. double *farg=(double *)arg;
  154829. *farg=hi->lowpass_kHz;
  154830. }
  154831. return(0);
  154832. case OV_ECTL_LOWPASS_SET:
  154833. {
  154834. double *farg=(double *)arg;
  154835. hi->lowpass_kHz=*farg;
  154836. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  154837. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  154838. }
  154839. return(0);
  154840. case OV_ECTL_IBLOCK_GET:
  154841. {
  154842. double *farg=(double *)arg;
  154843. *farg=hi->impulse_noisetune;
  154844. }
  154845. return(0);
  154846. case OV_ECTL_IBLOCK_SET:
  154847. {
  154848. double *farg=(double *)arg;
  154849. hi->impulse_noisetune=*farg;
  154850. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  154851. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  154852. }
  154853. return(0);
  154854. }
  154855. return(OV_EIMPL);
  154856. }
  154857. return(OV_EINVAL);
  154858. }
  154859. #endif
  154860. /*** End of inlined file: vorbisenc.c ***/
  154861. /*** Start of inlined file: vorbisfile.c ***/
  154862. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  154863. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  154864. // tasks..
  154865. #if JUCE_MSVC
  154866. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  154867. #endif
  154868. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  154869. #if JUCE_USE_OGGVORBIS
  154870. #include <stdlib.h>
  154871. #include <stdio.h>
  154872. #include <errno.h>
  154873. #include <string.h>
  154874. #include <math.h>
  154875. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  154876. one logical bitstream arranged end to end (the only form of Ogg
  154877. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  154878. multiplexing] is not allowed in Vorbis) */
  154879. /* A Vorbis file can be played beginning to end (streamed) without
  154880. worrying ahead of time about chaining (see decoder_example.c). If
  154881. we have the whole file, however, and want random access
  154882. (seeking/scrubbing) or desire to know the total length/time of a
  154883. file, we need to account for the possibility of chaining. */
  154884. /* We can handle things a number of ways; we can determine the entire
  154885. bitstream structure right off the bat, or find pieces on demand.
  154886. This example determines and caches structure for the entire
  154887. bitstream, but builds a virtual decoder on the fly when moving
  154888. between links in the chain. */
  154889. /* There are also different ways to implement seeking. Enough
  154890. information exists in an Ogg bitstream to seek to
  154891. sample-granularity positions in the output. Or, one can seek by
  154892. picking some portion of the stream roughly in the desired area if
  154893. we only want coarse navigation through the stream. */
  154894. /*************************************************************************
  154895. * Many, many internal helpers. The intention is not to be confusing;
  154896. * rampant duplication and monolithic function implementation would be
  154897. * harder to understand anyway. The high level functions are last. Begin
  154898. * grokking near the end of the file */
  154899. /* read a little more data from the file/pipe into the ogg_sync framer
  154900. */
  154901. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  154902. over 8k gets what they deserve */
  154903. static long _get_data(OggVorbis_File *vf){
  154904. errno=0;
  154905. if(vf->datasource){
  154906. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  154907. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  154908. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  154909. if(bytes==0 && errno)return(-1);
  154910. return(bytes);
  154911. }else
  154912. return(0);
  154913. }
  154914. /* save a tiny smidge of verbosity to make the code more readable */
  154915. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  154916. if(vf->datasource){
  154917. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  154918. vf->offset=offset;
  154919. ogg_sync_reset(&vf->oy);
  154920. }else{
  154921. /* shouldn't happen unless someone writes a broken callback */
  154922. return;
  154923. }
  154924. }
  154925. /* The read/seek functions track absolute position within the stream */
  154926. /* from the head of the stream, get the next page. boundary specifies
  154927. if the function is allowed to fetch more data from the stream (and
  154928. how much) or only use internally buffered data.
  154929. boundary: -1) unbounded search
  154930. 0) read no additional data; use cached only
  154931. n) search for a new page beginning for n bytes
  154932. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  154933. n) found a page at absolute offset n */
  154934. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  154935. ogg_int64_t boundary){
  154936. if(boundary>0)boundary+=vf->offset;
  154937. while(1){
  154938. long more;
  154939. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  154940. more=ogg_sync_pageseek(&vf->oy,og);
  154941. if(more<0){
  154942. /* skipped n bytes */
  154943. vf->offset-=more;
  154944. }else{
  154945. if(more==0){
  154946. /* send more paramedics */
  154947. if(!boundary)return(OV_FALSE);
  154948. {
  154949. long ret=_get_data(vf);
  154950. if(ret==0)return(OV_EOF);
  154951. if(ret<0)return(OV_EREAD);
  154952. }
  154953. }else{
  154954. /* got a page. Return the offset at the page beginning,
  154955. advance the internal offset past the page end */
  154956. ogg_int64_t ret=vf->offset;
  154957. vf->offset+=more;
  154958. return(ret);
  154959. }
  154960. }
  154961. }
  154962. }
  154963. /* find the latest page beginning before the current stream cursor
  154964. position. Much dirtier than the above as Ogg doesn't have any
  154965. backward search linkage. no 'readp' as it will certainly have to
  154966. read. */
  154967. /* returns offset or OV_EREAD, OV_FAULT */
  154968. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  154969. ogg_int64_t begin=vf->offset;
  154970. ogg_int64_t end=begin;
  154971. ogg_int64_t ret;
  154972. ogg_int64_t offset=-1;
  154973. while(offset==-1){
  154974. begin-=CHUNKSIZE;
  154975. if(begin<0)
  154976. begin=0;
  154977. _seek_helper(vf,begin);
  154978. while(vf->offset<end){
  154979. ret=_get_next_page(vf,og,end-vf->offset);
  154980. if(ret==OV_EREAD)return(OV_EREAD);
  154981. if(ret<0){
  154982. break;
  154983. }else{
  154984. offset=ret;
  154985. }
  154986. }
  154987. }
  154988. /* we have the offset. Actually snork and hold the page now */
  154989. _seek_helper(vf,offset);
  154990. ret=_get_next_page(vf,og,CHUNKSIZE);
  154991. if(ret<0)
  154992. /* this shouldn't be possible */
  154993. return(OV_EFAULT);
  154994. return(offset);
  154995. }
  154996. /* finds each bitstream link one at a time using a bisection search
  154997. (has to begin by knowing the offset of the lb's initial page).
  154998. Recurses for each link so it can alloc the link storage after
  154999. finding them all, then unroll and fill the cache at the same time */
  155000. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155001. ogg_int64_t begin,
  155002. ogg_int64_t searched,
  155003. ogg_int64_t end,
  155004. long currentno,
  155005. long m){
  155006. ogg_int64_t endsearched=end;
  155007. ogg_int64_t next=end;
  155008. ogg_page og;
  155009. ogg_int64_t ret;
  155010. /* the below guards against garbage seperating the last and
  155011. first pages of two links. */
  155012. while(searched<endsearched){
  155013. ogg_int64_t bisect;
  155014. if(endsearched-searched<CHUNKSIZE){
  155015. bisect=searched;
  155016. }else{
  155017. bisect=(searched+endsearched)/2;
  155018. }
  155019. _seek_helper(vf,bisect);
  155020. ret=_get_next_page(vf,&og,-1);
  155021. if(ret==OV_EREAD)return(OV_EREAD);
  155022. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155023. endsearched=bisect;
  155024. if(ret>=0)next=ret;
  155025. }else{
  155026. searched=ret+og.header_len+og.body_len;
  155027. }
  155028. }
  155029. _seek_helper(vf,next);
  155030. ret=_get_next_page(vf,&og,-1);
  155031. if(ret==OV_EREAD)return(OV_EREAD);
  155032. if(searched>=end || ret<0){
  155033. vf->links=m+1;
  155034. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155035. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155036. vf->offsets[m+1]=searched;
  155037. }else{
  155038. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155039. end,ogg_page_serialno(&og),m+1);
  155040. if(ret==OV_EREAD)return(OV_EREAD);
  155041. }
  155042. vf->offsets[m]=begin;
  155043. vf->serialnos[m]=currentno;
  155044. return(0);
  155045. }
  155046. /* uses the local ogg_stream storage in vf; this is important for
  155047. non-streaming input sources */
  155048. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155049. long *serialno,ogg_page *og_ptr){
  155050. ogg_page og;
  155051. ogg_packet op;
  155052. int i,ret;
  155053. if(!og_ptr){
  155054. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155055. if(llret==OV_EREAD)return(OV_EREAD);
  155056. if(llret<0)return OV_ENOTVORBIS;
  155057. og_ptr=&og;
  155058. }
  155059. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155060. if(serialno)*serialno=vf->os.serialno;
  155061. vf->ready_state=STREAMSET;
  155062. /* extract the initial header from the first page and verify that the
  155063. Ogg bitstream is in fact Vorbis data */
  155064. vorbis_info_init(vi);
  155065. vorbis_comment_init(vc);
  155066. i=0;
  155067. while(i<3){
  155068. ogg_stream_pagein(&vf->os,og_ptr);
  155069. while(i<3){
  155070. int result=ogg_stream_packetout(&vf->os,&op);
  155071. if(result==0)break;
  155072. if(result==-1){
  155073. ret=OV_EBADHEADER;
  155074. goto bail_header;
  155075. }
  155076. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155077. goto bail_header;
  155078. }
  155079. i++;
  155080. }
  155081. if(i<3)
  155082. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155083. ret=OV_EBADHEADER;
  155084. goto bail_header;
  155085. }
  155086. }
  155087. return 0;
  155088. bail_header:
  155089. vorbis_info_clear(vi);
  155090. vorbis_comment_clear(vc);
  155091. vf->ready_state=OPENED;
  155092. return ret;
  155093. }
  155094. /* last step of the OggVorbis_File initialization; get all the
  155095. vorbis_info structs and PCM positions. Only called by the seekable
  155096. initialization (local stream storage is hacked slightly; pay
  155097. attention to how that's done) */
  155098. /* this is void and does not propogate errors up because we want to be
  155099. able to open and use damaged bitstreams as well as we can. Just
  155100. watch out for missing information for links in the OggVorbis_File
  155101. struct */
  155102. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155103. ogg_page og;
  155104. int i;
  155105. ogg_int64_t ret;
  155106. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155107. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155108. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155109. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155110. for(i=0;i<vf->links;i++){
  155111. if(i==0){
  155112. /* we already grabbed the initial header earlier. Just set the offset */
  155113. vf->dataoffsets[i]=dataoffset;
  155114. _seek_helper(vf,dataoffset);
  155115. }else{
  155116. /* seek to the location of the initial header */
  155117. _seek_helper(vf,vf->offsets[i]);
  155118. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155119. vf->dataoffsets[i]=-1;
  155120. }else{
  155121. vf->dataoffsets[i]=vf->offset;
  155122. }
  155123. }
  155124. /* fetch beginning PCM offset */
  155125. if(vf->dataoffsets[i]!=-1){
  155126. ogg_int64_t accumulated=0;
  155127. long lastblock=-1;
  155128. int result;
  155129. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155130. while(1){
  155131. ogg_packet op;
  155132. ret=_get_next_page(vf,&og,-1);
  155133. if(ret<0)
  155134. /* this should not be possible unless the file is
  155135. truncated/mangled */
  155136. break;
  155137. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155138. break;
  155139. /* count blocksizes of all frames in the page */
  155140. ogg_stream_pagein(&vf->os,&og);
  155141. while((result=ogg_stream_packetout(&vf->os,&op))){
  155142. if(result>0){ /* ignore holes */
  155143. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155144. if(lastblock!=-1)
  155145. accumulated+=(lastblock+thisblock)>>2;
  155146. lastblock=thisblock;
  155147. }
  155148. }
  155149. if(ogg_page_granulepos(&og)!=-1){
  155150. /* pcm offset of last packet on the first audio page */
  155151. accumulated= ogg_page_granulepos(&og)-accumulated;
  155152. break;
  155153. }
  155154. }
  155155. /* less than zero? This is a stream with samples trimmed off
  155156. the beginning, a normal occurrence; set the offset to zero */
  155157. if(accumulated<0)accumulated=0;
  155158. vf->pcmlengths[i*2]=accumulated;
  155159. }
  155160. /* get the PCM length of this link. To do this,
  155161. get the last page of the stream */
  155162. {
  155163. ogg_int64_t end=vf->offsets[i+1];
  155164. _seek_helper(vf,end);
  155165. while(1){
  155166. ret=_get_prev_page(vf,&og);
  155167. if(ret<0){
  155168. /* this should not be possible */
  155169. vorbis_info_clear(vf->vi+i);
  155170. vorbis_comment_clear(vf->vc+i);
  155171. break;
  155172. }
  155173. if(ogg_page_granulepos(&og)!=-1){
  155174. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155175. break;
  155176. }
  155177. vf->offset=ret;
  155178. }
  155179. }
  155180. }
  155181. }
  155182. static int _make_decode_ready(OggVorbis_File *vf){
  155183. if(vf->ready_state>STREAMSET)return 0;
  155184. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155185. if(vf->seekable){
  155186. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155187. return OV_EBADLINK;
  155188. }else{
  155189. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155190. return OV_EBADLINK;
  155191. }
  155192. vorbis_block_init(&vf->vd,&vf->vb);
  155193. vf->ready_state=INITSET;
  155194. vf->bittrack=0.f;
  155195. vf->samptrack=0.f;
  155196. return 0;
  155197. }
  155198. static int _open_seekable2(OggVorbis_File *vf){
  155199. long serialno=vf->current_serialno;
  155200. ogg_int64_t dataoffset=vf->offset, end;
  155201. ogg_page og;
  155202. /* we're partially open and have a first link header state in
  155203. storage in vf */
  155204. /* we can seek, so set out learning all about this file */
  155205. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155206. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155207. /* We get the offset for the last page of the physical bitstream.
  155208. Most OggVorbis files will contain a single logical bitstream */
  155209. end=_get_prev_page(vf,&og);
  155210. if(end<0)return(end);
  155211. /* more than one logical bitstream? */
  155212. if(ogg_page_serialno(&og)!=serialno){
  155213. /* Chained bitstream. Bisect-search each logical bitstream
  155214. section. Do so based on serial number only */
  155215. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155216. }else{
  155217. /* Only one logical bitstream */
  155218. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155219. }
  155220. /* the initial header memory is referenced by vf after; don't free it */
  155221. _prefetch_all_headers(vf,dataoffset);
  155222. return(ov_raw_seek(vf,0));
  155223. }
  155224. /* clear out the current logical bitstream decoder */
  155225. static void _decode_clear(OggVorbis_File *vf){
  155226. vorbis_dsp_clear(&vf->vd);
  155227. vorbis_block_clear(&vf->vb);
  155228. vf->ready_state=OPENED;
  155229. }
  155230. /* fetch and process a packet. Handles the case where we're at a
  155231. bitstream boundary and dumps the decoding machine. If the decoding
  155232. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155233. date (seek and read both use this. seek uses a special hack with
  155234. readp).
  155235. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155236. 0) need more data (only if readp==0)
  155237. 1) got a packet
  155238. */
  155239. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155240. ogg_packet *op_in,
  155241. int readp,
  155242. int spanp){
  155243. ogg_page og;
  155244. /* handle one packet. Try to fetch it from current stream state */
  155245. /* extract packets from page */
  155246. while(1){
  155247. /* process a packet if we can. If the machine isn't loaded,
  155248. neither is a page */
  155249. if(vf->ready_state==INITSET){
  155250. while(1) {
  155251. ogg_packet op;
  155252. ogg_packet *op_ptr=(op_in?op_in:&op);
  155253. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155254. ogg_int64_t granulepos;
  155255. op_in=NULL;
  155256. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155257. if(result>0){
  155258. /* got a packet. process it */
  155259. granulepos=op_ptr->granulepos;
  155260. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155261. header handling. The
  155262. header packets aren't
  155263. audio, so if/when we
  155264. submit them,
  155265. vorbis_synthesis will
  155266. reject them */
  155267. /* suck in the synthesis data and track bitrate */
  155268. {
  155269. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155270. /* for proper use of libvorbis within libvorbisfile,
  155271. oldsamples will always be zero. */
  155272. if(oldsamples)return(OV_EFAULT);
  155273. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155274. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  155275. vf->bittrack+=op_ptr->bytes*8;
  155276. }
  155277. /* update the pcm offset. */
  155278. if(granulepos!=-1 && !op_ptr->e_o_s){
  155279. int link=(vf->seekable?vf->current_link:0);
  155280. int i,samples;
  155281. /* this packet has a pcm_offset on it (the last packet
  155282. completed on a page carries the offset) After processing
  155283. (above), we know the pcm position of the *last* sample
  155284. ready to be returned. Find the offset of the *first*
  155285. As an aside, this trick is inaccurate if we begin
  155286. reading anew right at the last page; the end-of-stream
  155287. granulepos declares the last frame in the stream, and the
  155288. last packet of the last page may be a partial frame.
  155289. So, we need a previous granulepos from an in-sequence page
  155290. to have a reference point. Thus the !op_ptr->e_o_s clause
  155291. above */
  155292. if(vf->seekable && link>0)
  155293. granulepos-=vf->pcmlengths[link*2];
  155294. if(granulepos<0)granulepos=0; /* actually, this
  155295. shouldn't be possible
  155296. here unless the stream
  155297. is very broken */
  155298. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155299. granulepos-=samples;
  155300. for(i=0;i<link;i++)
  155301. granulepos+=vf->pcmlengths[i*2+1];
  155302. vf->pcm_offset=granulepos;
  155303. }
  155304. return(1);
  155305. }
  155306. }
  155307. else
  155308. break;
  155309. }
  155310. }
  155311. if(vf->ready_state>=OPENED){
  155312. ogg_int64_t ret;
  155313. if(!readp)return(0);
  155314. if((ret=_get_next_page(vf,&og,-1))<0){
  155315. return(OV_EOF); /* eof.
  155316. leave unitialized */
  155317. }
  155318. /* bitrate tracking; add the header's bytes here, the body bytes
  155319. are done by packet above */
  155320. vf->bittrack+=og.header_len*8;
  155321. /* has our decoding just traversed a bitstream boundary? */
  155322. if(vf->ready_state==INITSET){
  155323. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155324. if(!spanp)
  155325. return(OV_EOF);
  155326. _decode_clear(vf);
  155327. if(!vf->seekable){
  155328. vorbis_info_clear(vf->vi);
  155329. vorbis_comment_clear(vf->vc);
  155330. }
  155331. }
  155332. }
  155333. }
  155334. /* Do we need to load a new machine before submitting the page? */
  155335. /* This is different in the seekable and non-seekable cases.
  155336. In the seekable case, we already have all the header
  155337. information loaded and cached; we just initialize the machine
  155338. with it and continue on our merry way.
  155339. In the non-seekable (streaming) case, we'll only be at a
  155340. boundary if we just left the previous logical bitstream and
  155341. we're now nominally at the header of the next bitstream
  155342. */
  155343. if(vf->ready_state!=INITSET){
  155344. int link;
  155345. if(vf->ready_state<STREAMSET){
  155346. if(vf->seekable){
  155347. vf->current_serialno=ogg_page_serialno(&og);
  155348. /* match the serialno to bitstream section. We use this rather than
  155349. offset positions to avoid problems near logical bitstream
  155350. boundaries */
  155351. for(link=0;link<vf->links;link++)
  155352. if(vf->serialnos[link]==vf->current_serialno)break;
  155353. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155354. stream. error out,
  155355. leave machine
  155356. uninitialized */
  155357. vf->current_link=link;
  155358. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155359. vf->ready_state=STREAMSET;
  155360. }else{
  155361. /* we're streaming */
  155362. /* fetch the three header packets, build the info struct */
  155363. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155364. if(ret)return(ret);
  155365. vf->current_link++;
  155366. link=0;
  155367. }
  155368. }
  155369. {
  155370. int ret=_make_decode_ready(vf);
  155371. if(ret<0)return ret;
  155372. }
  155373. }
  155374. ogg_stream_pagein(&vf->os,&og);
  155375. }
  155376. }
  155377. /* if, eg, 64 bit stdio is configured by default, this will build with
  155378. fseek64 */
  155379. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  155380. if(f==NULL)return(-1);
  155381. return fseek(f,off,whence);
  155382. }
  155383. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  155384. long ibytes, ov_callbacks callbacks){
  155385. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  155386. int ret;
  155387. memset(vf,0,sizeof(*vf));
  155388. vf->datasource=f;
  155389. vf->callbacks = callbacks;
  155390. /* init the framing state */
  155391. ogg_sync_init(&vf->oy);
  155392. /* perhaps some data was previously read into a buffer for testing
  155393. against other stream types. Allow initialization from this
  155394. previously read data (as we may be reading from a non-seekable
  155395. stream) */
  155396. if(initial){
  155397. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  155398. memcpy(buffer,initial,ibytes);
  155399. ogg_sync_wrote(&vf->oy,ibytes);
  155400. }
  155401. /* can we seek? Stevens suggests the seek test was portable */
  155402. if(offsettest!=-1)vf->seekable=1;
  155403. /* No seeking yet; Set up a 'single' (current) logical bitstream
  155404. entry for partial open */
  155405. vf->links=1;
  155406. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  155407. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  155408. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  155409. /* Try to fetch the headers, maintaining all the storage */
  155410. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  155411. vf->datasource=NULL;
  155412. ov_clear(vf);
  155413. }else
  155414. vf->ready_state=PARTOPEN;
  155415. return(ret);
  155416. }
  155417. static int _ov_open2(OggVorbis_File *vf){
  155418. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  155419. vf->ready_state=OPENED;
  155420. if(vf->seekable){
  155421. int ret=_open_seekable2(vf);
  155422. if(ret){
  155423. vf->datasource=NULL;
  155424. ov_clear(vf);
  155425. }
  155426. return(ret);
  155427. }else
  155428. vf->ready_state=STREAMSET;
  155429. return 0;
  155430. }
  155431. /* clear out the OggVorbis_File struct */
  155432. int ov_clear(OggVorbis_File *vf){
  155433. if(vf){
  155434. vorbis_block_clear(&vf->vb);
  155435. vorbis_dsp_clear(&vf->vd);
  155436. ogg_stream_clear(&vf->os);
  155437. if(vf->vi && vf->links){
  155438. int i;
  155439. for(i=0;i<vf->links;i++){
  155440. vorbis_info_clear(vf->vi+i);
  155441. vorbis_comment_clear(vf->vc+i);
  155442. }
  155443. _ogg_free(vf->vi);
  155444. _ogg_free(vf->vc);
  155445. }
  155446. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  155447. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  155448. if(vf->serialnos)_ogg_free(vf->serialnos);
  155449. if(vf->offsets)_ogg_free(vf->offsets);
  155450. ogg_sync_clear(&vf->oy);
  155451. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  155452. memset(vf,0,sizeof(*vf));
  155453. }
  155454. #ifdef DEBUG_LEAKS
  155455. _VDBG_dump();
  155456. #endif
  155457. return(0);
  155458. }
  155459. /* inspects the OggVorbis file and finds/documents all the logical
  155460. bitstreams contained in it. Tries to be tolerant of logical
  155461. bitstream sections that are truncated/woogie.
  155462. return: -1) error
  155463. 0) OK
  155464. */
  155465. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155466. ov_callbacks callbacks){
  155467. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  155468. if(ret)return ret;
  155469. return _ov_open2(vf);
  155470. }
  155471. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155472. ov_callbacks callbacks = {
  155473. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155474. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155475. (int (*)(void *)) fclose,
  155476. (long (*)(void *)) ftell
  155477. };
  155478. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155479. }
  155480. /* cheap hack for game usage where downsampling is desirable; there's
  155481. no need for SRC as we can just do it cheaply in libvorbis. */
  155482. int ov_halfrate(OggVorbis_File *vf,int flag){
  155483. int i;
  155484. if(vf->vi==NULL)return OV_EINVAL;
  155485. if(!vf->seekable)return OV_EINVAL;
  155486. if(vf->ready_state>=STREAMSET)
  155487. _decode_clear(vf); /* clear out stream state; later on libvorbis
  155488. will be able to swap this on the fly, but
  155489. for now dumping the decode machine is needed
  155490. to reinit the MDCT lookups. 1.1 libvorbis
  155491. is planned to be able to switch on the fly */
  155492. for(i=0;i<vf->links;i++){
  155493. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  155494. ov_halfrate(vf,0);
  155495. return OV_EINVAL;
  155496. }
  155497. }
  155498. return 0;
  155499. }
  155500. int ov_halfrate_p(OggVorbis_File *vf){
  155501. if(vf->vi==NULL)return OV_EINVAL;
  155502. return vorbis_synthesis_halfrate_p(vf->vi);
  155503. }
  155504. /* Only partially open the vorbis file; test for Vorbisness, and load
  155505. the headers for the first chain. Do not seek (although test for
  155506. seekability). Use ov_test_open to finish opening the file, else
  155507. ov_clear to close/free it. Same return codes as open. */
  155508. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155509. ov_callbacks callbacks)
  155510. {
  155511. return _ov_open1(f,vf,initial,ibytes,callbacks);
  155512. }
  155513. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155514. ov_callbacks callbacks = {
  155515. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155516. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155517. (int (*)(void *)) fclose,
  155518. (long (*)(void *)) ftell
  155519. };
  155520. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155521. }
  155522. int ov_test_open(OggVorbis_File *vf){
  155523. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  155524. return _ov_open2(vf);
  155525. }
  155526. /* How many logical bitstreams in this physical bitstream? */
  155527. long ov_streams(OggVorbis_File *vf){
  155528. return vf->links;
  155529. }
  155530. /* Is the FILE * associated with vf seekable? */
  155531. long ov_seekable(OggVorbis_File *vf){
  155532. return vf->seekable;
  155533. }
  155534. /* returns the bitrate for a given logical bitstream or the entire
  155535. physical bitstream. If the file is open for random access, it will
  155536. find the *actual* average bitrate. If the file is streaming, it
  155537. returns the nominal bitrate (if set) else the average of the
  155538. upper/lower bounds (if set) else -1 (unset).
  155539. If you want the actual bitrate field settings, get them from the
  155540. vorbis_info structs */
  155541. long ov_bitrate(OggVorbis_File *vf,int i){
  155542. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155543. if(i>=vf->links)return(OV_EINVAL);
  155544. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  155545. if(i<0){
  155546. ogg_int64_t bits=0;
  155547. int i;
  155548. float br;
  155549. for(i=0;i<vf->links;i++)
  155550. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  155551. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  155552. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  155553. * so this is slightly transformed to make it work.
  155554. */
  155555. br = bits/ov_time_total(vf,-1);
  155556. return(rint(br));
  155557. }else{
  155558. if(vf->seekable){
  155559. /* return the actual bitrate */
  155560. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  155561. }else{
  155562. /* return nominal if set */
  155563. if(vf->vi[i].bitrate_nominal>0){
  155564. return vf->vi[i].bitrate_nominal;
  155565. }else{
  155566. if(vf->vi[i].bitrate_upper>0){
  155567. if(vf->vi[i].bitrate_lower>0){
  155568. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  155569. }else{
  155570. return vf->vi[i].bitrate_upper;
  155571. }
  155572. }
  155573. return(OV_FALSE);
  155574. }
  155575. }
  155576. }
  155577. }
  155578. /* returns the actual bitrate since last call. returns -1 if no
  155579. additional data to offer since last call (or at beginning of stream),
  155580. EINVAL if stream is only partially open
  155581. */
  155582. long ov_bitrate_instant(OggVorbis_File *vf){
  155583. int link=(vf->seekable?vf->current_link:0);
  155584. long ret;
  155585. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155586. if(vf->samptrack==0)return(OV_FALSE);
  155587. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  155588. vf->bittrack=0.f;
  155589. vf->samptrack=0.f;
  155590. return(ret);
  155591. }
  155592. /* Guess */
  155593. long ov_serialnumber(OggVorbis_File *vf,int i){
  155594. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  155595. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  155596. if(i<0){
  155597. return(vf->current_serialno);
  155598. }else{
  155599. return(vf->serialnos[i]);
  155600. }
  155601. }
  155602. /* returns: total raw (compressed) length of content if i==-1
  155603. raw (compressed) length of that logical bitstream for i==0 to n
  155604. OV_EINVAL if the stream is not seekable (we can't know the length)
  155605. or if stream is only partially open
  155606. */
  155607. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  155608. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155609. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155610. if(i<0){
  155611. ogg_int64_t acc=0;
  155612. int i;
  155613. for(i=0;i<vf->links;i++)
  155614. acc+=ov_raw_total(vf,i);
  155615. return(acc);
  155616. }else{
  155617. return(vf->offsets[i+1]-vf->offsets[i]);
  155618. }
  155619. }
  155620. /* returns: total PCM length (samples) of content if i==-1 PCM length
  155621. (samples) of that logical bitstream for i==0 to n
  155622. OV_EINVAL if the stream is not seekable (we can't know the
  155623. length) or only partially open
  155624. */
  155625. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  155626. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155627. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155628. if(i<0){
  155629. ogg_int64_t acc=0;
  155630. int i;
  155631. for(i=0;i<vf->links;i++)
  155632. acc+=ov_pcm_total(vf,i);
  155633. return(acc);
  155634. }else{
  155635. return(vf->pcmlengths[i*2+1]);
  155636. }
  155637. }
  155638. /* returns: total seconds of content if i==-1
  155639. seconds in that logical bitstream for i==0 to n
  155640. OV_EINVAL if the stream is not seekable (we can't know the
  155641. length) or only partially open
  155642. */
  155643. double ov_time_total(OggVorbis_File *vf,int i){
  155644. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155645. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155646. if(i<0){
  155647. double acc=0;
  155648. int i;
  155649. for(i=0;i<vf->links;i++)
  155650. acc+=ov_time_total(vf,i);
  155651. return(acc);
  155652. }else{
  155653. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  155654. }
  155655. }
  155656. /* seek to an offset relative to the *compressed* data. This also
  155657. scans packets to update the PCM cursor. It will cross a logical
  155658. bitstream boundary, but only if it can't get any packets out of the
  155659. tail of the bitstream we seek to (so no surprises).
  155660. returns zero on success, nonzero on failure */
  155661. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  155662. ogg_stream_state work_os;
  155663. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155664. if(!vf->seekable)
  155665. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  155666. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  155667. /* don't yet clear out decoding machine (if it's initialized), in
  155668. the case we're in the same link. Restart the decode lapping, and
  155669. let _fetch_and_process_packet deal with a potential bitstream
  155670. boundary */
  155671. vf->pcm_offset=-1;
  155672. ogg_stream_reset_serialno(&vf->os,
  155673. vf->current_serialno); /* must set serialno */
  155674. vorbis_synthesis_restart(&vf->vd);
  155675. _seek_helper(vf,pos);
  155676. /* we need to make sure the pcm_offset is set, but we don't want to
  155677. advance the raw cursor past good packets just to get to the first
  155678. with a granulepos. That's not equivalent behavior to beginning
  155679. decoding as immediately after the seek position as possible.
  155680. So, a hack. We use two stream states; a local scratch state and
  155681. the shared vf->os stream state. We use the local state to
  155682. scan, and the shared state as a buffer for later decode.
  155683. Unfortuantely, on the last page we still advance to last packet
  155684. because the granulepos on the last page is not necessarily on a
  155685. packet boundary, and we need to make sure the granpos is
  155686. correct.
  155687. */
  155688. {
  155689. ogg_page og;
  155690. ogg_packet op;
  155691. int lastblock=0;
  155692. int accblock=0;
  155693. int thisblock;
  155694. int eosflag;
  155695. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  155696. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  155697. return from not necessarily
  155698. starting from the beginning */
  155699. while(1){
  155700. if(vf->ready_state>=STREAMSET){
  155701. /* snarf/scan a packet if we can */
  155702. int result=ogg_stream_packetout(&work_os,&op);
  155703. if(result>0){
  155704. if(vf->vi[vf->current_link].codec_setup){
  155705. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  155706. if(thisblock<0){
  155707. ogg_stream_packetout(&vf->os,NULL);
  155708. thisblock=0;
  155709. }else{
  155710. if(eosflag)
  155711. ogg_stream_packetout(&vf->os,NULL);
  155712. else
  155713. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  155714. }
  155715. if(op.granulepos!=-1){
  155716. int i,link=vf->current_link;
  155717. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  155718. if(granulepos<0)granulepos=0;
  155719. for(i=0;i<link;i++)
  155720. granulepos+=vf->pcmlengths[i*2+1];
  155721. vf->pcm_offset=granulepos-accblock;
  155722. break;
  155723. }
  155724. lastblock=thisblock;
  155725. continue;
  155726. }else
  155727. ogg_stream_packetout(&vf->os,NULL);
  155728. }
  155729. }
  155730. if(!lastblock){
  155731. if(_get_next_page(vf,&og,-1)<0){
  155732. vf->pcm_offset=ov_pcm_total(vf,-1);
  155733. break;
  155734. }
  155735. }else{
  155736. /* huh? Bogus stream with packets but no granulepos */
  155737. vf->pcm_offset=-1;
  155738. break;
  155739. }
  155740. /* has our decoding just traversed a bitstream boundary? */
  155741. if(vf->ready_state>=STREAMSET)
  155742. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155743. _decode_clear(vf); /* clear out stream state */
  155744. ogg_stream_clear(&work_os);
  155745. }
  155746. if(vf->ready_state<STREAMSET){
  155747. int link;
  155748. vf->current_serialno=ogg_page_serialno(&og);
  155749. for(link=0;link<vf->links;link++)
  155750. if(vf->serialnos[link]==vf->current_serialno)break;
  155751. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  155752. error out, leave
  155753. machine uninitialized */
  155754. vf->current_link=link;
  155755. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155756. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  155757. vf->ready_state=STREAMSET;
  155758. }
  155759. ogg_stream_pagein(&vf->os,&og);
  155760. ogg_stream_pagein(&work_os,&og);
  155761. eosflag=ogg_page_eos(&og);
  155762. }
  155763. }
  155764. ogg_stream_clear(&work_os);
  155765. vf->bittrack=0.f;
  155766. vf->samptrack=0.f;
  155767. return(0);
  155768. seek_error:
  155769. /* dump the machine so we're in a known state */
  155770. vf->pcm_offset=-1;
  155771. ogg_stream_clear(&work_os);
  155772. _decode_clear(vf);
  155773. return OV_EBADLINK;
  155774. }
  155775. /* Page granularity seek (faster than sample granularity because we
  155776. don't do the last bit of decode to find a specific sample).
  155777. Seek to the last [granule marked] page preceeding the specified pos
  155778. location, such that decoding past the returned point will quickly
  155779. arrive at the requested position. */
  155780. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  155781. int link=-1;
  155782. ogg_int64_t result=0;
  155783. ogg_int64_t total=ov_pcm_total(vf,-1);
  155784. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155785. if(!vf->seekable)return(OV_ENOSEEK);
  155786. if(pos<0 || pos>total)return(OV_EINVAL);
  155787. /* which bitstream section does this pcm offset occur in? */
  155788. for(link=vf->links-1;link>=0;link--){
  155789. total-=vf->pcmlengths[link*2+1];
  155790. if(pos>=total)break;
  155791. }
  155792. /* search within the logical bitstream for the page with the highest
  155793. pcm_pos preceeding (or equal to) pos. There is a danger here;
  155794. missing pages or incorrect frame number information in the
  155795. bitstream could make our task impossible. Account for that (it
  155796. would be an error condition) */
  155797. /* new search algorithm by HB (Nicholas Vinen) */
  155798. {
  155799. ogg_int64_t end=vf->offsets[link+1];
  155800. ogg_int64_t begin=vf->offsets[link];
  155801. ogg_int64_t begintime = vf->pcmlengths[link*2];
  155802. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  155803. ogg_int64_t target=pos-total+begintime;
  155804. ogg_int64_t best=begin;
  155805. ogg_page og;
  155806. while(begin<end){
  155807. ogg_int64_t bisect;
  155808. if(end-begin<CHUNKSIZE){
  155809. bisect=begin;
  155810. }else{
  155811. /* take a (pretty decent) guess. */
  155812. bisect=begin +
  155813. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  155814. if(bisect<=begin)
  155815. bisect=begin+1;
  155816. }
  155817. _seek_helper(vf,bisect);
  155818. while(begin<end){
  155819. result=_get_next_page(vf,&og,end-vf->offset);
  155820. if(result==OV_EREAD) goto seek_error;
  155821. if(result<0){
  155822. if(bisect<=begin+1)
  155823. end=begin; /* found it */
  155824. else{
  155825. if(bisect==0) goto seek_error;
  155826. bisect-=CHUNKSIZE;
  155827. if(bisect<=begin)bisect=begin+1;
  155828. _seek_helper(vf,bisect);
  155829. }
  155830. }else{
  155831. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  155832. if(granulepos==-1)continue;
  155833. if(granulepos<target){
  155834. best=result; /* raw offset of packet with granulepos */
  155835. begin=vf->offset; /* raw offset of next page */
  155836. begintime=granulepos;
  155837. if(target-begintime>44100)break;
  155838. bisect=begin; /* *not* begin + 1 */
  155839. }else{
  155840. if(bisect<=begin+1)
  155841. end=begin; /* found it */
  155842. else{
  155843. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  155844. end=result;
  155845. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  155846. if(bisect<=begin)bisect=begin+1;
  155847. _seek_helper(vf,bisect);
  155848. }else{
  155849. end=result;
  155850. endtime=granulepos;
  155851. break;
  155852. }
  155853. }
  155854. }
  155855. }
  155856. }
  155857. }
  155858. /* found our page. seek to it, update pcm offset. Easier case than
  155859. raw_seek, don't keep packets preceeding granulepos. */
  155860. {
  155861. ogg_page og;
  155862. ogg_packet op;
  155863. /* seek */
  155864. _seek_helper(vf,best);
  155865. vf->pcm_offset=-1;
  155866. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  155867. if(link!=vf->current_link){
  155868. /* Different link; dump entire decode machine */
  155869. _decode_clear(vf);
  155870. vf->current_link=link;
  155871. vf->current_serialno=ogg_page_serialno(&og);
  155872. vf->ready_state=STREAMSET;
  155873. }else{
  155874. vorbis_synthesis_restart(&vf->vd);
  155875. }
  155876. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155877. ogg_stream_pagein(&vf->os,&og);
  155878. /* pull out all but last packet; the one with granulepos */
  155879. while(1){
  155880. result=ogg_stream_packetpeek(&vf->os,&op);
  155881. if(result==0){
  155882. /* !!! the packet finishing this page originated on a
  155883. preceeding page. Keep fetching previous pages until we
  155884. get one with a granulepos or without the 'continued' flag
  155885. set. Then just use raw_seek for simplicity. */
  155886. _seek_helper(vf,best);
  155887. while(1){
  155888. result=_get_prev_page(vf,&og);
  155889. if(result<0) goto seek_error;
  155890. if(ogg_page_granulepos(&og)>-1 ||
  155891. !ogg_page_continued(&og)){
  155892. return ov_raw_seek(vf,result);
  155893. }
  155894. vf->offset=result;
  155895. }
  155896. }
  155897. if(result<0){
  155898. result = OV_EBADPACKET;
  155899. goto seek_error;
  155900. }
  155901. if(op.granulepos!=-1){
  155902. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  155903. if(vf->pcm_offset<0)vf->pcm_offset=0;
  155904. vf->pcm_offset+=total;
  155905. break;
  155906. }else
  155907. result=ogg_stream_packetout(&vf->os,NULL);
  155908. }
  155909. }
  155910. }
  155911. /* verify result */
  155912. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  155913. result=OV_EFAULT;
  155914. goto seek_error;
  155915. }
  155916. vf->bittrack=0.f;
  155917. vf->samptrack=0.f;
  155918. return(0);
  155919. seek_error:
  155920. /* dump machine so we're in a known state */
  155921. vf->pcm_offset=-1;
  155922. _decode_clear(vf);
  155923. return (int)result;
  155924. }
  155925. /* seek to a sample offset relative to the decompressed pcm stream
  155926. returns zero on success, nonzero on failure */
  155927. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  155928. int thisblock,lastblock=0;
  155929. int ret=ov_pcm_seek_page(vf,pos);
  155930. if(ret<0)return(ret);
  155931. if((ret=_make_decode_ready(vf)))return ret;
  155932. /* discard leading packets we don't need for the lapping of the
  155933. position we want; don't decode them */
  155934. while(1){
  155935. ogg_packet op;
  155936. ogg_page og;
  155937. int ret=ogg_stream_packetpeek(&vf->os,&op);
  155938. if(ret>0){
  155939. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  155940. if(thisblock<0){
  155941. ogg_stream_packetout(&vf->os,NULL);
  155942. continue; /* non audio packet */
  155943. }
  155944. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  155945. if(vf->pcm_offset+((thisblock+
  155946. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  155947. /* remove the packet from packet queue and track its granulepos */
  155948. ogg_stream_packetout(&vf->os,NULL);
  155949. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  155950. only tracking, no
  155951. pcm_decode */
  155952. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155953. /* end of logical stream case is hard, especially with exact
  155954. length positioning. */
  155955. if(op.granulepos>-1){
  155956. int i;
  155957. /* always believe the stream markers */
  155958. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  155959. if(vf->pcm_offset<0)vf->pcm_offset=0;
  155960. for(i=0;i<vf->current_link;i++)
  155961. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  155962. }
  155963. lastblock=thisblock;
  155964. }else{
  155965. if(ret<0 && ret!=OV_HOLE)break;
  155966. /* suck in a new page */
  155967. if(_get_next_page(vf,&og,-1)<0)break;
  155968. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  155969. if(vf->ready_state<STREAMSET){
  155970. int link;
  155971. vf->current_serialno=ogg_page_serialno(&og);
  155972. for(link=0;link<vf->links;link++)
  155973. if(vf->serialnos[link]==vf->current_serialno)break;
  155974. if(link==vf->links)return(OV_EBADLINK);
  155975. vf->current_link=link;
  155976. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155977. vf->ready_state=STREAMSET;
  155978. ret=_make_decode_ready(vf);
  155979. if(ret)return ret;
  155980. lastblock=0;
  155981. }
  155982. ogg_stream_pagein(&vf->os,&og);
  155983. }
  155984. }
  155985. vf->bittrack=0.f;
  155986. vf->samptrack=0.f;
  155987. /* discard samples until we reach the desired position. Crossing a
  155988. logical bitstream boundary with abandon is OK. */
  155989. while(vf->pcm_offset<pos){
  155990. ogg_int64_t target=pos-vf->pcm_offset;
  155991. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155992. if(samples>target)samples=target;
  155993. vorbis_synthesis_read(&vf->vd,samples);
  155994. vf->pcm_offset+=samples;
  155995. if(samples<target)
  155996. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  155997. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  155998. }
  155999. return 0;
  156000. }
  156001. /* seek to a playback time relative to the decompressed pcm stream
  156002. returns zero on success, nonzero on failure */
  156003. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156004. /* translate time to PCM position and call ov_pcm_seek */
  156005. int link=-1;
  156006. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156007. double time_total=ov_time_total(vf,-1);
  156008. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156009. if(!vf->seekable)return(OV_ENOSEEK);
  156010. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156011. /* which bitstream section does this time offset occur in? */
  156012. for(link=vf->links-1;link>=0;link--){
  156013. pcm_total-=vf->pcmlengths[link*2+1];
  156014. time_total-=ov_time_total(vf,link);
  156015. if(seconds>=time_total)break;
  156016. }
  156017. /* enough information to convert time offset to pcm offset */
  156018. {
  156019. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156020. return(ov_pcm_seek(vf,target));
  156021. }
  156022. }
  156023. /* page-granularity version of ov_time_seek
  156024. returns zero on success, nonzero on failure */
  156025. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156026. /* translate time to PCM position and call ov_pcm_seek */
  156027. int link=-1;
  156028. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156029. double time_total=ov_time_total(vf,-1);
  156030. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156031. if(!vf->seekable)return(OV_ENOSEEK);
  156032. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156033. /* which bitstream section does this time offset occur in? */
  156034. for(link=vf->links-1;link>=0;link--){
  156035. pcm_total-=vf->pcmlengths[link*2+1];
  156036. time_total-=ov_time_total(vf,link);
  156037. if(seconds>=time_total)break;
  156038. }
  156039. /* enough information to convert time offset to pcm offset */
  156040. {
  156041. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156042. return(ov_pcm_seek_page(vf,target));
  156043. }
  156044. }
  156045. /* tell the current stream offset cursor. Note that seek followed by
  156046. tell will likely not give the set offset due to caching */
  156047. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156048. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156049. return(vf->offset);
  156050. }
  156051. /* return PCM offset (sample) of next PCM sample to be read */
  156052. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156053. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156054. return(vf->pcm_offset);
  156055. }
  156056. /* return time offset (seconds) of next PCM sample to be read */
  156057. double ov_time_tell(OggVorbis_File *vf){
  156058. int link=0;
  156059. ogg_int64_t pcm_total=0;
  156060. double time_total=0.f;
  156061. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156062. if(vf->seekable){
  156063. pcm_total=ov_pcm_total(vf,-1);
  156064. time_total=ov_time_total(vf,-1);
  156065. /* which bitstream section does this time offset occur in? */
  156066. for(link=vf->links-1;link>=0;link--){
  156067. pcm_total-=vf->pcmlengths[link*2+1];
  156068. time_total-=ov_time_total(vf,link);
  156069. if(vf->pcm_offset>=pcm_total)break;
  156070. }
  156071. }
  156072. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156073. }
  156074. /* link: -1) return the vorbis_info struct for the bitstream section
  156075. currently being decoded
  156076. 0-n) to request information for a specific bitstream section
  156077. In the case of a non-seekable bitstream, any call returns the
  156078. current bitstream. NULL in the case that the machine is not
  156079. initialized */
  156080. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156081. if(vf->seekable){
  156082. if(link<0)
  156083. if(vf->ready_state>=STREAMSET)
  156084. return vf->vi+vf->current_link;
  156085. else
  156086. return vf->vi;
  156087. else
  156088. if(link>=vf->links)
  156089. return NULL;
  156090. else
  156091. return vf->vi+link;
  156092. }else{
  156093. return vf->vi;
  156094. }
  156095. }
  156096. /* grr, strong typing, grr, no templates/inheritence, grr */
  156097. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156098. if(vf->seekable){
  156099. if(link<0)
  156100. if(vf->ready_state>=STREAMSET)
  156101. return vf->vc+vf->current_link;
  156102. else
  156103. return vf->vc;
  156104. else
  156105. if(link>=vf->links)
  156106. return NULL;
  156107. else
  156108. return vf->vc+link;
  156109. }else{
  156110. return vf->vc;
  156111. }
  156112. }
  156113. static int host_is_big_endian() {
  156114. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156115. unsigned char *bytewise = (unsigned char *)&pattern;
  156116. if (bytewise[0] == 0xfe) return 1;
  156117. return 0;
  156118. }
  156119. /* up to this point, everything could more or less hide the multiple
  156120. logical bitstream nature of chaining from the toplevel application
  156121. if the toplevel application didn't particularly care. However, at
  156122. the point that we actually read audio back, the multiple-section
  156123. nature must surface: Multiple bitstream sections do not necessarily
  156124. have to have the same number of channels or sampling rate.
  156125. ov_read returns the sequential logical bitstream number currently
  156126. being decoded along with the PCM data in order that the toplevel
  156127. application can take action on channel/sample rate changes. This
  156128. number will be incremented even for streamed (non-seekable) streams
  156129. (for seekable streams, it represents the actual logical bitstream
  156130. index within the physical bitstream. Note that the accessor
  156131. functions above are aware of this dichotomy).
  156132. input values: buffer) a buffer to hold packed PCM data for return
  156133. length) the byte length requested to be placed into buffer
  156134. bigendianp) should the data be packed LSB first (0) or
  156135. MSB first (1)
  156136. word) word size for output. currently 1 (byte) or
  156137. 2 (16 bit short)
  156138. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156139. 0) EOF
  156140. n) number of bytes of PCM actually returned. The
  156141. below works on a packet-by-packet basis, so the
  156142. return length is not related to the 'length' passed
  156143. in, just guaranteed to fit.
  156144. *section) set to the logical bitstream number */
  156145. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156146. int bigendianp,int word,int sgned,int *bitstream){
  156147. int i,j;
  156148. int host_endian = host_is_big_endian();
  156149. float **pcm;
  156150. long samples;
  156151. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156152. while(1){
  156153. if(vf->ready_state==INITSET){
  156154. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156155. if(samples)break;
  156156. }
  156157. /* suck in another packet */
  156158. {
  156159. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156160. if(ret==OV_EOF)
  156161. return(0);
  156162. if(ret<=0)
  156163. return(ret);
  156164. }
  156165. }
  156166. if(samples>0){
  156167. /* yay! proceed to pack data into the byte buffer */
  156168. long channels=ov_info(vf,-1)->channels;
  156169. long bytespersample=word * channels;
  156170. vorbis_fpu_control fpu;
  156171. (void) fpu; // (to avoid a warning about it being unused)
  156172. if(samples>length/bytespersample)samples=length/bytespersample;
  156173. if(samples <= 0)
  156174. return OV_EINVAL;
  156175. /* a tight loop to pack each size */
  156176. {
  156177. int val;
  156178. if(word==1){
  156179. int off=(sgned?0:128);
  156180. vorbis_fpu_setround(&fpu);
  156181. for(j=0;j<samples;j++)
  156182. for(i=0;i<channels;i++){
  156183. val=vorbis_ftoi(pcm[i][j]*128.f);
  156184. if(val>127)val=127;
  156185. else if(val<-128)val=-128;
  156186. *buffer++=val+off;
  156187. }
  156188. vorbis_fpu_restore(fpu);
  156189. }else{
  156190. int off=(sgned?0:32768);
  156191. if(host_endian==bigendianp){
  156192. if(sgned){
  156193. vorbis_fpu_setround(&fpu);
  156194. for(i=0;i<channels;i++) { /* It's faster in this order */
  156195. float *src=pcm[i];
  156196. short *dest=((short *)buffer)+i;
  156197. for(j=0;j<samples;j++) {
  156198. val=vorbis_ftoi(src[j]*32768.f);
  156199. if(val>32767)val=32767;
  156200. else if(val<-32768)val=-32768;
  156201. *dest=val;
  156202. dest+=channels;
  156203. }
  156204. }
  156205. vorbis_fpu_restore(fpu);
  156206. }else{
  156207. vorbis_fpu_setround(&fpu);
  156208. for(i=0;i<channels;i++) {
  156209. float *src=pcm[i];
  156210. short *dest=((short *)buffer)+i;
  156211. for(j=0;j<samples;j++) {
  156212. val=vorbis_ftoi(src[j]*32768.f);
  156213. if(val>32767)val=32767;
  156214. else if(val<-32768)val=-32768;
  156215. *dest=val+off;
  156216. dest+=channels;
  156217. }
  156218. }
  156219. vorbis_fpu_restore(fpu);
  156220. }
  156221. }else if(bigendianp){
  156222. vorbis_fpu_setround(&fpu);
  156223. for(j=0;j<samples;j++)
  156224. for(i=0;i<channels;i++){
  156225. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156226. if(val>32767)val=32767;
  156227. else if(val<-32768)val=-32768;
  156228. val+=off;
  156229. *buffer++=(val>>8);
  156230. *buffer++=(val&0xff);
  156231. }
  156232. vorbis_fpu_restore(fpu);
  156233. }else{
  156234. int val;
  156235. vorbis_fpu_setround(&fpu);
  156236. for(j=0;j<samples;j++)
  156237. for(i=0;i<channels;i++){
  156238. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156239. if(val>32767)val=32767;
  156240. else if(val<-32768)val=-32768;
  156241. val+=off;
  156242. *buffer++=(val&0xff);
  156243. *buffer++=(val>>8);
  156244. }
  156245. vorbis_fpu_restore(fpu);
  156246. }
  156247. }
  156248. }
  156249. vorbis_synthesis_read(&vf->vd,samples);
  156250. vf->pcm_offset+=samples;
  156251. if(bitstream)*bitstream=vf->current_link;
  156252. return(samples*bytespersample);
  156253. }else{
  156254. return(samples);
  156255. }
  156256. }
  156257. /* input values: pcm_channels) a float vector per channel of output
  156258. length) the sample length being read by the app
  156259. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156260. 0) EOF
  156261. n) number of samples of PCM actually returned. The
  156262. below works on a packet-by-packet basis, so the
  156263. return length is not related to the 'length' passed
  156264. in, just guaranteed to fit.
  156265. *section) set to the logical bitstream number */
  156266. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  156267. int *bitstream){
  156268. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156269. while(1){
  156270. if(vf->ready_state==INITSET){
  156271. float **pcm;
  156272. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156273. if(samples){
  156274. if(pcm_channels)*pcm_channels=pcm;
  156275. if(samples>length)samples=length;
  156276. vorbis_synthesis_read(&vf->vd,samples);
  156277. vf->pcm_offset+=samples;
  156278. if(bitstream)*bitstream=vf->current_link;
  156279. return samples;
  156280. }
  156281. }
  156282. /* suck in another packet */
  156283. {
  156284. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156285. if(ret==OV_EOF)return(0);
  156286. if(ret<=0)return(ret);
  156287. }
  156288. }
  156289. }
  156290. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  156291. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  156292. ogg_int64_t off);
  156293. static void _ov_splice(float **pcm,float **lappcm,
  156294. int n1, int n2,
  156295. int ch1, int ch2,
  156296. float *w1, float *w2){
  156297. int i,j;
  156298. float *w=w1;
  156299. int n=n1;
  156300. if(n1>n2){
  156301. n=n2;
  156302. w=w2;
  156303. }
  156304. /* splice */
  156305. for(j=0;j<ch1 && j<ch2;j++){
  156306. float *s=lappcm[j];
  156307. float *d=pcm[j];
  156308. for(i=0;i<n;i++){
  156309. float wd=w[i]*w[i];
  156310. float ws=1.-wd;
  156311. d[i]=d[i]*wd + s[i]*ws;
  156312. }
  156313. }
  156314. /* window from zero */
  156315. for(;j<ch2;j++){
  156316. float *d=pcm[j];
  156317. for(i=0;i<n;i++){
  156318. float wd=w[i]*w[i];
  156319. d[i]=d[i]*wd;
  156320. }
  156321. }
  156322. }
  156323. /* make sure vf is INITSET */
  156324. static int _ov_initset(OggVorbis_File *vf){
  156325. while(1){
  156326. if(vf->ready_state==INITSET)break;
  156327. /* suck in another packet */
  156328. {
  156329. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156330. if(ret<0 && ret!=OV_HOLE)return(ret);
  156331. }
  156332. }
  156333. return 0;
  156334. }
  156335. /* make sure vf is INITSET and that we have a primed buffer; if
  156336. we're crosslapping at a stream section boundary, this also makes
  156337. sure we're sanity checking against the right stream information */
  156338. static int _ov_initprime(OggVorbis_File *vf){
  156339. vorbis_dsp_state *vd=&vf->vd;
  156340. while(1){
  156341. if(vf->ready_state==INITSET)
  156342. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156343. /* suck in another packet */
  156344. {
  156345. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156346. if(ret<0 && ret!=OV_HOLE)return(ret);
  156347. }
  156348. }
  156349. return 0;
  156350. }
  156351. /* grab enough data for lapping from vf; this may be in the form of
  156352. unreturned, already-decoded pcm, remaining PCM we will need to
  156353. decode, or synthetic postextrapolation from last packets. */
  156354. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156355. float **lappcm,int lapsize){
  156356. int lapcount=0,i;
  156357. float **pcm;
  156358. /* try first to decode the lapping data */
  156359. while(lapcount<lapsize){
  156360. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156361. if(samples){
  156362. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156363. for(i=0;i<vi->channels;i++)
  156364. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156365. lapcount+=samples;
  156366. vorbis_synthesis_read(vd,samples);
  156367. }else{
  156368. /* suck in another packet */
  156369. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156370. if(ret==OV_EOF)break;
  156371. }
  156372. }
  156373. if(lapcount<lapsize){
  156374. /* failed to get lapping data from normal decode; pry it from the
  156375. postextrapolation buffering, or the second half of the MDCT
  156376. from the last packet */
  156377. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  156378. if(samples==0){
  156379. for(i=0;i<vi->channels;i++)
  156380. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  156381. lapcount=lapsize;
  156382. }else{
  156383. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156384. for(i=0;i<vi->channels;i++)
  156385. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156386. lapcount+=samples;
  156387. }
  156388. }
  156389. }
  156390. /* this sets up crosslapping of a sample by using trailing data from
  156391. sample 1 and lapping it into the windowing buffer of sample 2 */
  156392. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  156393. vorbis_info *vi1,*vi2;
  156394. float **lappcm;
  156395. float **pcm;
  156396. float *w1,*w2;
  156397. int n1,n2,i,ret,hs1,hs2;
  156398. if(vf1==vf2)return(0); /* degenerate case */
  156399. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  156400. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  156401. /* the relevant overlap buffers must be pre-checked and pre-primed
  156402. before looking at settings in the event that priming would cross
  156403. a bitstream boundary. So, do it now */
  156404. ret=_ov_initset(vf1);
  156405. if(ret)return(ret);
  156406. ret=_ov_initprime(vf2);
  156407. if(ret)return(ret);
  156408. vi1=ov_info(vf1,-1);
  156409. vi2=ov_info(vf2,-1);
  156410. hs1=ov_halfrate_p(vf1);
  156411. hs2=ov_halfrate_p(vf2);
  156412. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  156413. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  156414. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  156415. w1=vorbis_window(&vf1->vd,0);
  156416. w2=vorbis_window(&vf2->vd,0);
  156417. for(i=0;i<vi1->channels;i++)
  156418. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156419. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  156420. /* have a lapping buffer from vf1; now to splice it into the lapping
  156421. buffer of vf2 */
  156422. /* consolidate and expose the buffer. */
  156423. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  156424. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  156425. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  156426. /* splice */
  156427. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  156428. /* done */
  156429. return(0);
  156430. }
  156431. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  156432. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  156433. vorbis_info *vi;
  156434. float **lappcm;
  156435. float **pcm;
  156436. float *w1,*w2;
  156437. int n1,n2,ch1,ch2,hs;
  156438. int i,ret;
  156439. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156440. ret=_ov_initset(vf);
  156441. if(ret)return(ret);
  156442. vi=ov_info(vf,-1);
  156443. hs=ov_halfrate_p(vf);
  156444. ch1=vi->channels;
  156445. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156446. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156447. persistent; even if the decode state
  156448. from this link gets dumped, this
  156449. window array continues to exist */
  156450. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156451. for(i=0;i<ch1;i++)
  156452. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156453. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156454. /* have lapping data; seek and prime the buffer */
  156455. ret=localseek(vf,pos);
  156456. if(ret)return ret;
  156457. ret=_ov_initprime(vf);
  156458. if(ret)return(ret);
  156459. /* Guard against cross-link changes; they're perfectly legal */
  156460. vi=ov_info(vf,-1);
  156461. ch2=vi->channels;
  156462. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156463. w2=vorbis_window(&vf->vd,0);
  156464. /* consolidate and expose the buffer. */
  156465. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156466. /* splice */
  156467. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156468. /* done */
  156469. return(0);
  156470. }
  156471. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156472. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  156473. }
  156474. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156475. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  156476. }
  156477. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156478. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  156479. }
  156480. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  156481. int (*localseek)(OggVorbis_File *,double)){
  156482. vorbis_info *vi;
  156483. float **lappcm;
  156484. float **pcm;
  156485. float *w1,*w2;
  156486. int n1,n2,ch1,ch2,hs;
  156487. int i,ret;
  156488. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156489. ret=_ov_initset(vf);
  156490. if(ret)return(ret);
  156491. vi=ov_info(vf,-1);
  156492. hs=ov_halfrate_p(vf);
  156493. ch1=vi->channels;
  156494. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156495. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156496. persistent; even if the decode state
  156497. from this link gets dumped, this
  156498. window array continues to exist */
  156499. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156500. for(i=0;i<ch1;i++)
  156501. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156502. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156503. /* have lapping data; seek and prime the buffer */
  156504. ret=localseek(vf,pos);
  156505. if(ret)return ret;
  156506. ret=_ov_initprime(vf);
  156507. if(ret)return(ret);
  156508. /* Guard against cross-link changes; they're perfectly legal */
  156509. vi=ov_info(vf,-1);
  156510. ch2=vi->channels;
  156511. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156512. w2=vorbis_window(&vf->vd,0);
  156513. /* consolidate and expose the buffer. */
  156514. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156515. /* splice */
  156516. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156517. /* done */
  156518. return(0);
  156519. }
  156520. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  156521. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  156522. }
  156523. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  156524. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  156525. }
  156526. #endif
  156527. /*** End of inlined file: vorbisfile.c ***/
  156528. /*** Start of inlined file: window.c ***/
  156529. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  156530. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  156531. // tasks..
  156532. #if JUCE_MSVC
  156533. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  156534. #endif
  156535. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  156536. #if JUCE_USE_OGGVORBIS
  156537. #include <stdlib.h>
  156538. #include <math.h>
  156539. static float vwin64[32] = {
  156540. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  156541. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  156542. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  156543. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  156544. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  156545. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  156546. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  156547. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  156548. };
  156549. static float vwin128[64] = {
  156550. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  156551. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  156552. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  156553. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  156554. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  156555. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  156556. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  156557. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  156558. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  156559. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  156560. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  156561. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  156562. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  156563. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  156564. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  156565. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  156566. };
  156567. static float vwin256[128] = {
  156568. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  156569. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  156570. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  156571. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  156572. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  156573. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  156574. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  156575. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  156576. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  156577. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  156578. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  156579. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  156580. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  156581. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  156582. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  156583. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  156584. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  156585. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  156586. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  156587. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  156588. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  156589. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  156590. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  156591. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  156592. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  156593. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  156594. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  156595. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  156596. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  156597. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  156598. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  156599. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  156600. };
  156601. static float vwin512[256] = {
  156602. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  156603. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  156604. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  156605. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  156606. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  156607. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  156608. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  156609. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  156610. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  156611. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  156612. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  156613. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  156614. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  156615. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  156616. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  156617. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  156618. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  156619. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  156620. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  156621. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  156622. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  156623. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  156624. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  156625. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  156626. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  156627. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  156628. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  156629. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  156630. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  156631. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  156632. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  156633. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  156634. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  156635. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  156636. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  156637. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  156638. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  156639. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  156640. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  156641. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  156642. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  156643. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  156644. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  156645. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  156646. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  156647. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  156648. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  156649. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  156650. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  156651. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  156652. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  156653. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  156654. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  156655. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  156656. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  156657. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  156658. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  156659. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  156660. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  156661. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  156662. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  156663. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  156664. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  156665. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  156666. };
  156667. static float vwin1024[512] = {
  156668. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  156669. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  156670. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  156671. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  156672. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  156673. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  156674. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  156675. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  156676. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  156677. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  156678. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  156679. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  156680. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  156681. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  156682. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  156683. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  156684. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  156685. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  156686. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  156687. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  156688. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  156689. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  156690. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  156691. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  156692. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  156693. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  156694. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  156695. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  156696. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  156697. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  156698. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  156699. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  156700. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  156701. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  156702. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  156703. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  156704. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  156705. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  156706. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  156707. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  156708. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  156709. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  156710. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  156711. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  156712. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  156713. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  156714. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  156715. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  156716. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  156717. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  156718. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  156719. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  156720. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  156721. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  156722. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  156723. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  156724. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  156725. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  156726. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  156727. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  156728. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  156729. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  156730. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  156731. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  156732. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  156733. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  156734. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  156735. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  156736. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  156737. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  156738. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  156739. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  156740. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  156741. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  156742. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  156743. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  156744. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  156745. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  156746. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  156747. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  156748. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  156749. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  156750. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  156751. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  156752. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  156753. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  156754. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  156755. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  156756. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  156757. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  156758. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  156759. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  156760. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  156761. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  156762. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  156763. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  156764. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  156765. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  156766. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  156767. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  156768. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  156769. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  156770. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  156771. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  156772. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  156773. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  156774. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  156775. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  156776. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  156777. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  156778. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  156779. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  156780. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  156781. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  156782. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  156783. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  156784. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  156785. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  156786. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  156787. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  156788. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  156789. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  156790. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  156791. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  156792. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  156793. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  156794. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  156795. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  156796. };
  156797. static float vwin2048[1024] = {
  156798. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  156799. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  156800. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  156801. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  156802. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  156803. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  156804. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  156805. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  156806. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  156807. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  156808. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  156809. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  156810. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  156811. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  156812. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  156813. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  156814. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  156815. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  156816. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  156817. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  156818. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  156819. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  156820. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  156821. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  156822. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  156823. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  156824. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  156825. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  156826. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  156827. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  156828. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  156829. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  156830. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  156831. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  156832. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  156833. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  156834. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  156835. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  156836. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  156837. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  156838. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  156839. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  156840. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  156841. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  156842. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  156843. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  156844. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  156845. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  156846. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  156847. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  156848. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  156849. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  156850. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  156851. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  156852. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  156853. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  156854. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  156855. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  156856. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  156857. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  156858. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  156859. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  156860. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  156861. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  156862. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  156863. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  156864. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  156865. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  156866. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  156867. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  156868. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  156869. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  156870. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  156871. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  156872. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  156873. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  156874. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  156875. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  156876. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  156877. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  156878. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  156879. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  156880. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  156881. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  156882. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  156883. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  156884. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  156885. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  156886. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  156887. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  156888. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  156889. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  156890. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  156891. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  156892. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  156893. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  156894. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  156895. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  156896. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  156897. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  156898. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  156899. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  156900. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  156901. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  156902. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  156903. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  156904. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  156905. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  156906. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  156907. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  156908. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  156909. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  156910. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  156911. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  156912. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  156913. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  156914. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  156915. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  156916. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  156917. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  156918. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  156919. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  156920. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  156921. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  156922. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  156923. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  156924. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  156925. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  156926. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  156927. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  156928. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  156929. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  156930. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  156931. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  156932. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  156933. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  156934. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  156935. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  156936. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  156937. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  156938. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  156939. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  156940. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  156941. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  156942. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  156943. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  156944. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  156945. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  156946. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  156947. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  156948. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  156949. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  156950. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  156951. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  156952. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  156953. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  156954. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  156955. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  156956. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  156957. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  156958. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  156959. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  156960. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  156961. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  156962. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  156963. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  156964. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  156965. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  156966. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  156967. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  156968. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  156969. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  156970. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  156971. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  156972. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  156973. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  156974. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  156975. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  156976. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  156977. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  156978. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  156979. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  156980. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  156981. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  156982. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  156983. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  156984. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  156985. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  156986. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  156987. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  156988. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  156989. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  156990. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  156991. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  156992. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  156993. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  156994. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  156995. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  156996. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  156997. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  156998. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  156999. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157000. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157001. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157002. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157003. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157004. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157005. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157006. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157007. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157008. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157009. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157010. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157011. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157012. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157013. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157014. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157015. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157016. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157017. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157018. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157019. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157020. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157021. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157022. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157023. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157024. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157025. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157026. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157027. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157028. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157029. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157030. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157031. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157032. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157033. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157034. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157035. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157036. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157037. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157038. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157039. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157040. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157041. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157042. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157043. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157044. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157045. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157046. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157047. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157048. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157049. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157050. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157051. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157052. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157053. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157054. };
  157055. static float vwin4096[2048] = {
  157056. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157057. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157058. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157059. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157060. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157061. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157062. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157063. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157064. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157065. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157066. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157067. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157068. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157069. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157070. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157071. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157072. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157073. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157074. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157075. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157076. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157077. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157078. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157079. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157080. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157081. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157082. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157083. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157084. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157085. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157086. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157087. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157088. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157089. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157090. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157091. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157092. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157093. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157094. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157095. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157096. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157097. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157098. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157099. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157100. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157101. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157102. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157103. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157104. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157105. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157106. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157107. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157108. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157109. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157110. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157111. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157112. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157113. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157114. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157115. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157116. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157117. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157118. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157119. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157120. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157121. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157122. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157123. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157124. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157125. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157126. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157127. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157128. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157129. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157130. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157131. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157132. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157133. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157134. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157135. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157136. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157137. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157138. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157139. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157140. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157141. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157142. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157143. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157144. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157145. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157146. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157147. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157148. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157149. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157150. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157151. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157152. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157153. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157154. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157155. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157156. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157157. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157158. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157159. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157160. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157161. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157162. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157163. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157164. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157165. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157166. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157167. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157168. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157169. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157170. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157171. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157172. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157173. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157174. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157175. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157176. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157177. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157178. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157179. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157180. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157181. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157182. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157183. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157184. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157185. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157186. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157187. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157188. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157189. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157190. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157191. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157192. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157193. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157194. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157195. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157196. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157197. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157198. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157199. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157200. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157201. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157202. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157203. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157204. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157205. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157206. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157207. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157208. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157209. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157210. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157211. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157212. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157213. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157214. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157215. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157216. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157217. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157218. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157219. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157220. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157221. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157222. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157223. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157224. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157225. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157226. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157227. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157228. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157229. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157230. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157231. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157232. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157233. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157234. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157235. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157236. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157237. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157238. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157239. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157240. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157241. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157242. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157243. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157244. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157245. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157246. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157247. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157248. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157249. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157250. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157251. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157252. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157253. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157254. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157255. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157256. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157257. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157258. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157259. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157260. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157261. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157262. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  157263. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  157264. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  157265. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  157266. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  157267. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  157268. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  157269. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  157270. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  157271. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  157272. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  157273. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  157274. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  157275. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  157276. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  157277. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  157278. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  157279. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  157280. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  157281. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  157282. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  157283. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  157284. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  157285. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  157286. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  157287. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  157288. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  157289. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  157290. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  157291. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  157292. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  157293. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  157294. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  157295. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  157296. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  157297. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  157298. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  157299. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  157300. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  157301. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  157302. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  157303. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  157304. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157305. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157306. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157307. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157308. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157309. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157310. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157311. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157312. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157313. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157314. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157315. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157316. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157317. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157318. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157319. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157320. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157321. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157322. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157323. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157324. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157325. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157326. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157327. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157328. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157329. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157330. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157331. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157332. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157333. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157334. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157335. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157336. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157337. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157338. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157339. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157340. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157341. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157342. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157343. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157344. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157345. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157346. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157347. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157348. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157349. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157350. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157351. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157352. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157353. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157354. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157355. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157356. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157357. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157358. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157359. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157360. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157361. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157362. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157363. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157364. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157365. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157366. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157367. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157368. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157369. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157370. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  157371. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  157372. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  157373. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  157374. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  157375. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  157376. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  157377. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  157378. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  157379. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  157380. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  157381. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  157382. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  157383. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  157384. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  157385. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  157386. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  157387. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  157388. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  157389. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  157390. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  157391. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  157392. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  157393. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  157394. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  157395. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  157396. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  157397. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  157398. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  157399. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  157400. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  157401. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  157402. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  157403. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  157404. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  157405. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  157406. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  157407. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  157408. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  157409. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  157410. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  157411. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  157412. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  157413. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  157414. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  157415. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  157416. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  157417. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  157418. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  157419. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  157420. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  157421. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  157422. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  157423. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  157424. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  157425. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  157426. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  157427. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  157428. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  157429. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  157430. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  157431. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  157432. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  157433. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  157434. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  157435. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  157436. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  157437. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  157438. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  157439. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  157440. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  157441. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  157442. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  157443. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  157444. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  157445. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  157446. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  157447. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  157448. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  157449. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  157450. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  157451. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  157452. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  157453. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  157454. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  157455. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  157456. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  157457. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  157458. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  157459. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  157460. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  157461. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  157462. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  157463. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  157464. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  157465. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  157466. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  157467. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  157468. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  157469. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  157470. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  157471. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  157472. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  157473. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  157474. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  157475. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  157476. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  157477. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  157478. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  157479. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  157480. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  157481. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  157482. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  157483. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  157484. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  157485. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  157486. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  157487. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  157488. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  157489. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  157490. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  157491. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  157492. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  157493. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  157494. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  157495. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  157496. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  157497. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  157498. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  157499. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  157500. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  157501. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  157502. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  157503. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  157504. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  157505. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  157506. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  157507. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  157508. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  157509. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  157510. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  157511. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  157512. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  157513. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  157514. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  157515. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  157516. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  157517. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  157518. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  157519. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  157520. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  157521. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  157522. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  157523. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  157524. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  157525. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  157526. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  157527. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  157528. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  157529. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  157530. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  157531. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  157532. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  157533. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  157534. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  157535. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  157536. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  157537. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  157538. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  157539. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  157540. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  157541. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  157542. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  157543. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  157544. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  157545. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  157546. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  157547. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  157548. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  157549. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  157550. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  157551. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  157552. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  157553. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  157554. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  157555. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  157556. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  157557. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  157558. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  157559. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  157560. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  157561. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  157562. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  157563. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  157564. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  157565. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  157566. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  157567. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  157568. };
  157569. static float vwin8192[4096] = {
  157570. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  157571. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  157572. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  157573. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  157574. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  157575. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  157576. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  157577. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  157578. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  157579. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  157580. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  157581. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  157582. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  157583. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  157584. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  157585. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  157586. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  157587. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  157588. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  157589. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  157590. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  157591. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  157592. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  157593. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  157594. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  157595. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  157596. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  157597. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  157598. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  157599. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  157600. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  157601. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  157602. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  157603. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  157604. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  157605. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  157606. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  157607. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  157608. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  157609. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  157610. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  157611. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  157612. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  157613. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  157614. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  157615. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  157616. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  157617. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  157618. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  157619. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  157620. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  157621. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  157622. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  157623. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  157624. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  157625. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  157626. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  157627. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  157628. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  157629. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  157630. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  157631. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  157632. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  157633. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  157634. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  157635. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  157636. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  157637. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  157638. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  157639. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  157640. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  157641. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  157642. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  157643. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  157644. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  157645. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  157646. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  157647. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  157648. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  157649. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  157650. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  157651. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  157652. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  157653. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  157654. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  157655. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  157656. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  157657. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  157658. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  157659. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  157660. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  157661. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  157662. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  157663. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  157664. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  157665. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  157666. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  157667. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  157668. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  157669. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  157670. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  157671. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  157672. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  157673. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  157674. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  157675. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  157676. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  157677. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  157678. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  157679. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  157680. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  157681. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  157682. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  157683. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  157684. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  157685. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  157686. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  157687. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  157688. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  157689. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  157690. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  157691. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  157692. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  157693. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  157694. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  157695. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  157696. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  157697. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  157698. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  157699. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  157700. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  157701. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  157702. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  157703. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  157704. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  157705. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  157706. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  157707. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  157708. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  157709. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  157710. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  157711. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  157712. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  157713. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  157714. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  157715. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  157716. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  157717. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  157718. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  157719. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  157720. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  157721. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  157722. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  157723. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  157724. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  157725. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  157726. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  157727. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  157728. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  157729. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  157730. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  157731. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  157732. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  157733. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  157734. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  157735. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  157736. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  157737. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  157738. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  157739. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  157740. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  157741. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  157742. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  157743. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  157744. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  157745. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  157746. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  157747. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  157748. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  157749. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  157750. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  157751. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  157752. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  157753. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  157754. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  157755. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  157756. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  157757. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  157758. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  157759. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  157760. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  157761. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  157762. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  157763. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  157764. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  157765. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  157766. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  157767. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  157768. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  157769. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  157770. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  157771. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  157772. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  157773. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  157774. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  157775. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  157776. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  157777. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  157778. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  157779. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  157780. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  157781. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  157782. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  157783. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  157784. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  157785. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  157786. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  157787. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  157788. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  157789. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  157790. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  157791. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  157792. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  157793. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  157794. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  157795. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  157796. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  157797. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  157798. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  157799. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  157800. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  157801. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  157802. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  157803. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  157804. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  157805. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  157806. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  157807. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  157808. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  157809. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  157810. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  157811. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  157812. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  157813. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  157814. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  157815. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  157816. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  157817. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  157818. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  157819. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  157820. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  157821. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  157822. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  157823. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  157824. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  157825. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  157826. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  157827. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  157828. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  157829. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  157830. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  157831. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  157832. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  157833. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  157834. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  157835. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  157836. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  157837. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  157838. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  157839. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  157840. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  157841. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  157842. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  157843. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  157844. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  157845. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  157846. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  157847. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  157848. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  157849. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  157850. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  157851. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  157852. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  157853. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  157854. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  157855. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  157856. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  157857. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  157858. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  157859. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  157860. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  157861. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  157862. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  157863. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  157864. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  157865. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  157866. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  157867. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  157868. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  157869. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  157870. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  157871. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  157872. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  157873. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  157874. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  157875. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  157876. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  157877. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  157878. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  157879. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  157880. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  157881. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  157882. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  157883. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  157884. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  157885. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  157886. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  157887. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  157888. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  157889. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  157890. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  157891. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  157892. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  157893. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  157894. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  157895. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  157896. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  157897. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  157898. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  157899. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  157900. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  157901. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  157902. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  157903. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  157904. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  157905. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  157906. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  157907. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  157908. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  157909. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  157910. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  157911. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  157912. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  157913. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  157914. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  157915. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  157916. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  157917. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  157918. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  157919. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  157920. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  157921. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  157922. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  157923. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  157924. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  157925. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  157926. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  157927. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  157928. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  157929. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  157930. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  157931. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  157932. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  157933. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  157934. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  157935. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  157936. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  157937. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  157938. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  157939. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  157940. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  157941. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  157942. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  157943. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  157944. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  157945. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  157946. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  157947. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  157948. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  157949. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  157950. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  157951. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  157952. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  157953. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  157954. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  157955. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  157956. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  157957. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  157958. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  157959. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  157960. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  157961. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  157962. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  157963. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  157964. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  157965. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  157966. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  157967. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  157968. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  157969. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  157970. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  157971. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  157972. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  157973. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  157974. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  157975. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  157976. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  157977. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  157978. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  157979. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  157980. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  157981. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  157982. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  157983. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  157984. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  157985. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  157986. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  157987. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  157988. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  157989. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  157990. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  157991. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  157992. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  157993. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  157994. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  157995. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  157996. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  157997. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  157998. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  157999. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158000. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158001. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158002. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158003. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158004. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158005. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158006. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158007. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158008. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158009. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158010. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158011. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158012. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158013. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158014. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158015. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158016. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158017. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158018. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158019. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158020. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158021. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158022. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158023. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158024. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158025. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158026. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158027. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158028. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158029. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158030. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158031. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158032. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158033. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158034. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158035. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158036. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158037. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158038. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158039. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158040. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158041. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158042. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158043. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158044. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158045. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158046. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158047. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158048. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158049. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158050. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158051. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158052. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158053. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158054. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158055. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158056. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158057. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158058. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158059. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158060. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158061. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158062. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158063. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158064. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158065. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158066. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158067. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158068. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158069. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158070. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158071. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158072. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158073. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158074. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158075. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158076. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158077. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158078. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158079. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158080. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158081. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158082. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158083. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158084. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158085. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158086. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158087. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158088. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158089. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158090. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158091. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158092. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158093. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158094. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158095. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158096. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158097. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158098. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158099. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158100. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158101. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158102. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158103. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158104. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158105. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158106. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158107. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158108. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158109. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158110. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158111. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158112. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158113. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158114. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158115. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158116. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158117. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158118. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158119. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158120. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158121. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158122. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158123. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158124. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158125. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158126. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158127. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158128. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158129. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158130. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158131. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158132. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158133. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158134. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158135. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158136. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158137. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158138. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158139. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158140. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158141. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158142. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158143. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158144. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158145. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158146. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158147. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158148. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158149. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158150. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158151. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158152. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158153. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158154. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158155. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158156. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158157. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158158. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158159. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158160. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158161. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158162. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158163. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158164. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158165. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158166. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158167. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158168. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158169. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158170. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158171. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158172. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158173. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158174. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158175. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158176. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158177. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158178. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158179. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158180. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158181. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158182. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158183. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158184. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158185. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158186. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158187. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158188. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158189. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158190. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158191. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158192. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158193. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158194. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158195. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158196. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158197. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158198. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158199. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158200. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158201. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158202. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158203. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158204. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158205. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158206. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158207. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158208. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158209. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158210. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158211. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158212. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158213. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158214. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158215. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158216. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158217. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158218. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158219. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158220. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158221. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158222. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158223. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158224. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158225. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158226. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158227. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158228. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158229. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158230. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158231. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158232. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158233. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158234. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158235. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158236. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158237. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158238. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158239. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158240. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158241. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158242. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158243. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158244. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158245. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158246. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158247. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158248. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158249. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158250. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158251. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158252. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158253. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158254. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158255. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158256. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158257. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158258. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158259. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158260. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158261. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158262. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  158263. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  158264. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  158265. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  158266. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  158267. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  158268. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  158269. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  158270. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  158271. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  158272. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  158273. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  158274. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  158275. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  158276. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  158277. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  158278. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  158279. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  158280. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  158281. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  158282. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  158283. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  158284. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  158285. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  158286. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  158287. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  158288. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  158289. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  158290. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  158291. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  158292. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  158293. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  158294. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  158295. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  158296. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  158297. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  158298. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  158299. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  158300. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  158301. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  158302. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  158303. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  158304. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158305. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158306. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158307. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158308. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158309. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158310. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158311. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158312. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158313. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158314. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158315. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158316. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158317. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158318. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158319. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158320. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158321. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158322. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158323. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158324. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158325. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158326. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158327. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158328. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158329. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158330. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158331. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158332. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158333. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158334. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158335. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158336. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158337. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158338. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158339. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158340. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158341. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158342. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158343. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158344. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158345. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158346. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158347. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158348. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158349. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158350. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158351. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158352. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158353. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158354. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158355. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158356. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158357. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158358. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158359. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158360. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158361. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158362. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158363. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158364. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158365. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158366. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158367. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158368. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158369. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158370. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  158371. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  158372. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  158373. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  158374. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  158375. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  158376. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  158377. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  158378. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  158379. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  158380. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  158381. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  158382. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  158383. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  158384. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  158385. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  158386. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  158387. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  158388. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  158389. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  158390. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  158391. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  158392. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  158393. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  158394. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  158395. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  158396. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  158397. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  158398. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  158399. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  158400. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  158401. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  158402. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  158403. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  158404. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  158405. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  158406. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  158407. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  158408. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  158409. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  158410. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  158411. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  158412. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  158413. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  158414. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  158415. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  158416. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  158417. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  158418. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  158419. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  158420. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  158421. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  158422. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  158423. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  158424. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  158425. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  158426. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  158427. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  158428. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  158429. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  158430. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  158431. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  158432. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  158433. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  158434. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  158435. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  158436. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  158437. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  158438. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  158439. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  158440. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  158441. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  158442. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  158443. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  158444. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  158445. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  158446. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  158447. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  158448. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  158449. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  158450. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  158451. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  158452. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  158453. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  158454. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  158455. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  158456. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  158457. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  158458. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  158459. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  158460. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  158461. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  158462. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  158463. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  158464. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  158465. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  158466. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  158467. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  158468. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  158469. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  158470. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  158471. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  158472. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  158473. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  158474. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  158475. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  158476. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  158477. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  158478. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  158479. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  158480. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  158481. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  158482. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  158483. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  158484. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  158485. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  158486. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  158487. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  158488. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  158489. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  158490. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  158491. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  158492. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  158493. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  158494. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  158495. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  158496. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  158497. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  158498. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  158499. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  158500. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  158501. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  158502. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  158503. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  158504. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  158505. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  158506. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  158507. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  158508. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  158509. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  158510. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  158511. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  158512. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  158513. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  158514. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  158515. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  158516. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  158517. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  158518. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  158519. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  158520. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  158521. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  158522. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  158523. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  158524. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  158525. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  158526. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  158527. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  158528. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  158529. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  158530. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  158531. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  158532. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  158533. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  158534. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  158535. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  158536. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  158537. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  158538. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  158539. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  158540. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  158541. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  158542. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  158543. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  158544. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  158545. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  158546. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  158547. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  158548. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  158549. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  158550. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  158551. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  158552. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  158553. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  158554. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  158555. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  158556. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  158557. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  158558. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  158559. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  158560. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  158561. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  158562. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  158563. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  158564. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  158565. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  158566. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  158567. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  158568. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  158569. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  158570. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  158571. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  158572. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  158573. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  158574. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  158575. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  158576. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  158577. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  158578. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  158579. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  158580. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  158581. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  158582. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  158583. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  158584. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  158585. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  158586. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  158587. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  158588. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  158589. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  158590. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  158591. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  158592. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158593. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158594. };
  158595. static float *vwin[8] = {
  158596. vwin64,
  158597. vwin128,
  158598. vwin256,
  158599. vwin512,
  158600. vwin1024,
  158601. vwin2048,
  158602. vwin4096,
  158603. vwin8192,
  158604. };
  158605. float *_vorbis_window_get(int n){
  158606. return vwin[n];
  158607. }
  158608. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  158609. int lW,int W,int nW){
  158610. lW=(W?lW:0);
  158611. nW=(W?nW:0);
  158612. {
  158613. float *windowLW=vwin[winno[lW]];
  158614. float *windowNW=vwin[winno[nW]];
  158615. long n=blocksizes[W];
  158616. long ln=blocksizes[lW];
  158617. long rn=blocksizes[nW];
  158618. long leftbegin=n/4-ln/4;
  158619. long leftend=leftbegin+ln/2;
  158620. long rightbegin=n/2+n/4-rn/4;
  158621. long rightend=rightbegin+rn/2;
  158622. int i,p;
  158623. for(i=0;i<leftbegin;i++)
  158624. d[i]=0.f;
  158625. for(p=0;i<leftend;i++,p++)
  158626. d[i]*=windowLW[p];
  158627. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  158628. d[i]*=windowNW[p];
  158629. for(;i<n;i++)
  158630. d[i]=0.f;
  158631. }
  158632. }
  158633. #endif
  158634. /*** End of inlined file: window.c ***/
  158635. #else
  158636. #include <vorbis/vorbisenc.h>
  158637. #include <vorbis/codec.h>
  158638. #include <vorbis/vorbisfile.h>
  158639. #endif
  158640. }
  158641. #undef max
  158642. #undef min
  158643. BEGIN_JUCE_NAMESPACE
  158644. static const char* const oggFormatName = "Ogg-Vorbis file";
  158645. static const char* const oggExtensions[] = { ".ogg", 0 };
  158646. class OggReader : public AudioFormatReader
  158647. {
  158648. OggVorbisNamespace::OggVorbis_File ovFile;
  158649. OggVorbisNamespace::ov_callbacks callbacks;
  158650. AudioSampleBuffer reservoir;
  158651. int reservoirStart, samplesInReservoir;
  158652. public:
  158653. OggReader (InputStream* const inp)
  158654. : AudioFormatReader (inp, TRANS (oggFormatName)),
  158655. reservoir (2, 4096),
  158656. reservoirStart (0),
  158657. samplesInReservoir (0)
  158658. {
  158659. using namespace OggVorbisNamespace;
  158660. sampleRate = 0;
  158661. usesFloatingPointData = true;
  158662. callbacks.read_func = &oggReadCallback;
  158663. callbacks.seek_func = &oggSeekCallback;
  158664. callbacks.close_func = &oggCloseCallback;
  158665. callbacks.tell_func = &oggTellCallback;
  158666. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  158667. if (err == 0)
  158668. {
  158669. vorbis_info* info = ov_info (&ovFile, -1);
  158670. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  158671. numChannels = info->channels;
  158672. bitsPerSample = 16;
  158673. sampleRate = info->rate;
  158674. reservoir.setSize (numChannels,
  158675. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  158676. }
  158677. }
  158678. ~OggReader()
  158679. {
  158680. OggVorbisNamespace::ov_clear (&ovFile);
  158681. }
  158682. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  158683. int64 startSampleInFile, int numSamples)
  158684. {
  158685. while (numSamples > 0)
  158686. {
  158687. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  158688. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  158689. {
  158690. // got a few samples overlapping, so use them before seeking..
  158691. const int numToUse = jmin (numSamples, numAvailable);
  158692. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  158693. if (destSamples[i] != 0)
  158694. memcpy (destSamples[i] + startOffsetInDestBuffer,
  158695. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  158696. sizeof (float) * numToUse);
  158697. startSampleInFile += numToUse;
  158698. numSamples -= numToUse;
  158699. startOffsetInDestBuffer += numToUse;
  158700. if (numSamples == 0)
  158701. break;
  158702. }
  158703. if (startSampleInFile < reservoirStart
  158704. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  158705. {
  158706. // buffer miss, so refill the reservoir
  158707. int bitStream = 0;
  158708. reservoirStart = jmax (0, (int) startSampleInFile);
  158709. samplesInReservoir = reservoir.getNumSamples();
  158710. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  158711. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  158712. int offset = 0;
  158713. int numToRead = samplesInReservoir;
  158714. while (numToRead > 0)
  158715. {
  158716. float** dataIn = 0;
  158717. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  158718. if (samps <= 0)
  158719. break;
  158720. jassert (samps <= numToRead);
  158721. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  158722. {
  158723. memcpy (reservoir.getSampleData (i, offset),
  158724. dataIn[i],
  158725. sizeof (float) * samps);
  158726. }
  158727. numToRead -= samps;
  158728. offset += samps;
  158729. }
  158730. if (numToRead > 0)
  158731. reservoir.clear (offset, numToRead);
  158732. }
  158733. }
  158734. if (numSamples > 0)
  158735. {
  158736. for (int i = numDestChannels; --i >= 0;)
  158737. if (destSamples[i] != 0)
  158738. zeromem (destSamples[i] + startOffsetInDestBuffer,
  158739. sizeof (int) * numSamples);
  158740. }
  158741. return true;
  158742. }
  158743. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  158744. {
  158745. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  158746. }
  158747. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  158748. {
  158749. InputStream* const in = static_cast <InputStream*> (datasource);
  158750. if (whence == SEEK_CUR)
  158751. offset += in->getPosition();
  158752. else if (whence == SEEK_END)
  158753. offset += in->getTotalLength();
  158754. in->setPosition (offset);
  158755. return 0;
  158756. }
  158757. static int oggCloseCallback (void*)
  158758. {
  158759. return 0;
  158760. }
  158761. static long oggTellCallback (void* datasource)
  158762. {
  158763. return (long) static_cast <InputStream*> (datasource)->getPosition();
  158764. }
  158765. juce_UseDebuggingNewOperator
  158766. };
  158767. class OggWriter : public AudioFormatWriter
  158768. {
  158769. OggVorbisNamespace::ogg_stream_state os;
  158770. OggVorbisNamespace::ogg_page og;
  158771. OggVorbisNamespace::ogg_packet op;
  158772. OggVorbisNamespace::vorbis_info vi;
  158773. OggVorbisNamespace::vorbis_comment vc;
  158774. OggVorbisNamespace::vorbis_dsp_state vd;
  158775. OggVorbisNamespace::vorbis_block vb;
  158776. public:
  158777. bool ok;
  158778. OggWriter (OutputStream* const out,
  158779. const double sampleRate,
  158780. const int numChannels,
  158781. const int bitsPerSample,
  158782. const int qualityIndex)
  158783. : AudioFormatWriter (out, TRANS (oggFormatName),
  158784. sampleRate,
  158785. numChannels,
  158786. bitsPerSample)
  158787. {
  158788. using namespace OggVorbisNamespace;
  158789. ok = false;
  158790. vorbis_info_init (&vi);
  158791. if (vorbis_encode_init_vbr (&vi,
  158792. numChannels,
  158793. (int) sampleRate,
  158794. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  158795. {
  158796. vorbis_comment_init (&vc);
  158797. if (JUCEApplication::getInstance() != 0)
  158798. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  158799. vorbis_analysis_init (&vd, &vi);
  158800. vorbis_block_init (&vd, &vb);
  158801. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  158802. ogg_packet header;
  158803. ogg_packet header_comm;
  158804. ogg_packet header_code;
  158805. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  158806. ogg_stream_packetin (&os, &header);
  158807. ogg_stream_packetin (&os, &header_comm);
  158808. ogg_stream_packetin (&os, &header_code);
  158809. for (;;)
  158810. {
  158811. if (ogg_stream_flush (&os, &og) == 0)
  158812. break;
  158813. output->write (og.header, og.header_len);
  158814. output->write (og.body, og.body_len);
  158815. }
  158816. ok = true;
  158817. }
  158818. }
  158819. ~OggWriter()
  158820. {
  158821. using namespace OggVorbisNamespace;
  158822. if (ok)
  158823. {
  158824. // write a zero-length packet to show ogg that we're finished..
  158825. write (0, 0);
  158826. ogg_stream_clear (&os);
  158827. vorbis_block_clear (&vb);
  158828. vorbis_dsp_clear (&vd);
  158829. vorbis_comment_clear (&vc);
  158830. vorbis_info_clear (&vi);
  158831. output->flush();
  158832. }
  158833. else
  158834. {
  158835. vorbis_info_clear (&vi);
  158836. output = 0; // to stop the base class deleting this, as it needs to be returned
  158837. // to the caller of createWriter()
  158838. }
  158839. }
  158840. bool write (const int** samplesToWrite, int numSamples)
  158841. {
  158842. using namespace OggVorbisNamespace;
  158843. if (! ok)
  158844. return false;
  158845. if (numSamples > 0)
  158846. {
  158847. const double gain = 1.0 / 0x80000000u;
  158848. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  158849. for (int i = numChannels; --i >= 0;)
  158850. {
  158851. float* const dst = vorbisBuffer[i];
  158852. const int* const src = samplesToWrite [i];
  158853. if (src != 0 && dst != 0)
  158854. {
  158855. for (int j = 0; j < numSamples; ++j)
  158856. dst[j] = (float) (src[j] * gain);
  158857. }
  158858. }
  158859. }
  158860. vorbis_analysis_wrote (&vd, numSamples);
  158861. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  158862. {
  158863. vorbis_analysis (&vb, 0);
  158864. vorbis_bitrate_addblock (&vb);
  158865. while (vorbis_bitrate_flushpacket (&vd, &op))
  158866. {
  158867. ogg_stream_packetin (&os, &op);
  158868. for (;;)
  158869. {
  158870. if (ogg_stream_pageout (&os, &og) == 0)
  158871. break;
  158872. output->write (og.header, og.header_len);
  158873. output->write (og.body, og.body_len);
  158874. if (ogg_page_eos (&og))
  158875. break;
  158876. }
  158877. }
  158878. }
  158879. return true;
  158880. }
  158881. juce_UseDebuggingNewOperator
  158882. };
  158883. OggVorbisAudioFormat::OggVorbisAudioFormat()
  158884. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  158885. {
  158886. }
  158887. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  158888. {
  158889. }
  158890. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  158891. {
  158892. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  158893. return Array <int> (rates);
  158894. }
  158895. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  158896. {
  158897. Array <int> depths;
  158898. depths.add (32);
  158899. return depths;
  158900. }
  158901. bool OggVorbisAudioFormat::canDoStereo()
  158902. {
  158903. return true;
  158904. }
  158905. bool OggVorbisAudioFormat::canDoMono()
  158906. {
  158907. return true;
  158908. }
  158909. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  158910. const bool deleteStreamIfOpeningFails)
  158911. {
  158912. ScopedPointer <OggReader> r (new OggReader (in));
  158913. if (r->sampleRate != 0)
  158914. return r.release();
  158915. if (! deleteStreamIfOpeningFails)
  158916. r->input = 0;
  158917. return 0;
  158918. }
  158919. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  158920. double sampleRate,
  158921. unsigned int numChannels,
  158922. int bitsPerSample,
  158923. const StringPairArray& /*metadataValues*/,
  158924. int qualityOptionIndex)
  158925. {
  158926. ScopedPointer <OggWriter> w (new OggWriter (out,
  158927. sampleRate,
  158928. numChannels,
  158929. bitsPerSample,
  158930. qualityOptionIndex));
  158931. return w->ok ? w.release() : 0;
  158932. }
  158933. bool OggVorbisAudioFormat::isCompressed()
  158934. {
  158935. return true;
  158936. }
  158937. const StringArray OggVorbisAudioFormat::getQualityOptions()
  158938. {
  158939. StringArray s;
  158940. s.add ("Low Quality");
  158941. s.add ("Medium Quality");
  158942. s.add ("High Quality");
  158943. return s;
  158944. }
  158945. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  158946. {
  158947. FileInputStream* const in = source.createInputStream();
  158948. if (in != 0)
  158949. {
  158950. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  158951. if (r != 0)
  158952. {
  158953. const int64 numSamps = r->lengthInSamples;
  158954. r = 0;
  158955. const int64 fileNumSamps = source.getSize() / 4;
  158956. const double ratio = numSamps / (double) fileNumSamps;
  158957. if (ratio > 12.0)
  158958. return 0;
  158959. else if (ratio > 6.0)
  158960. return 1;
  158961. else
  158962. return 2;
  158963. }
  158964. }
  158965. return 1;
  158966. }
  158967. END_JUCE_NAMESPACE
  158968. #endif
  158969. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  158970. #endif
  158971. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  158972. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  158973. #if JUCE_MSVC
  158974. #pragma warning (push)
  158975. #endif
  158976. namespace jpeglibNamespace
  158977. {
  158978. #if JUCE_INCLUDE_JPEGLIB_CODE
  158979. #if JUCE_MINGW
  158980. typedef unsigned char boolean;
  158981. #endif
  158982. extern "C"
  158983. {
  158984. #define JPEG_INTERNALS
  158985. #undef FAR
  158986. /*** Start of inlined file: jpeglib.h ***/
  158987. #ifndef JPEGLIB_H
  158988. #define JPEGLIB_H
  158989. /*
  158990. * First we include the configuration files that record how this
  158991. * installation of the JPEG library is set up. jconfig.h can be
  158992. * generated automatically for many systems. jmorecfg.h contains
  158993. * manual configuration options that most people need not worry about.
  158994. */
  158995. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  158996. /*** Start of inlined file: jconfig.h ***/
  158997. /* see jconfig.doc for explanations */
  158998. // disable all the warnings under MSVC
  158999. #ifdef _MSC_VER
  159000. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159001. #endif
  159002. #ifdef __BORLANDC__
  159003. #pragma warn -8057
  159004. #pragma warn -8019
  159005. #pragma warn -8004
  159006. #pragma warn -8008
  159007. #endif
  159008. #define HAVE_PROTOTYPES
  159009. #define HAVE_UNSIGNED_CHAR
  159010. #define HAVE_UNSIGNED_SHORT
  159011. /* #define void char */
  159012. /* #define const */
  159013. #undef CHAR_IS_UNSIGNED
  159014. #define HAVE_STDDEF_H
  159015. #define HAVE_STDLIB_H
  159016. #undef NEED_BSD_STRINGS
  159017. #undef NEED_SYS_TYPES_H
  159018. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159019. #undef NEED_SHORT_EXTERNAL_NAMES
  159020. #undef INCOMPLETE_TYPES_BROKEN
  159021. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159022. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159023. typedef unsigned char boolean;
  159024. #endif
  159025. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159026. #ifdef JPEG_INTERNALS
  159027. #undef RIGHT_SHIFT_IS_UNSIGNED
  159028. #endif /* JPEG_INTERNALS */
  159029. #ifdef JPEG_CJPEG_DJPEG
  159030. #define BMP_SUPPORTED /* BMP image file format */
  159031. #define GIF_SUPPORTED /* GIF image file format */
  159032. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159033. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159034. #define TARGA_SUPPORTED /* Targa image file format */
  159035. #define TWO_FILE_COMMANDLINE /* optional */
  159036. #define USE_SETMODE /* Microsoft has setmode() */
  159037. #undef NEED_SIGNAL_CATCHER
  159038. #undef DONT_USE_B_MODE
  159039. #undef PROGRESS_REPORT /* optional */
  159040. #endif /* JPEG_CJPEG_DJPEG */
  159041. /*** End of inlined file: jconfig.h ***/
  159042. /* widely used configuration options */
  159043. #endif
  159044. /*** Start of inlined file: jmorecfg.h ***/
  159045. /*
  159046. * Define BITS_IN_JSAMPLE as either
  159047. * 8 for 8-bit sample values (the usual setting)
  159048. * 12 for 12-bit sample values
  159049. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159050. * JPEG standard, and the IJG code does not support anything else!
  159051. * We do not support run-time selection of data precision, sorry.
  159052. */
  159053. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159054. /*
  159055. * Maximum number of components (color channels) allowed in JPEG image.
  159056. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159057. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159058. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159059. * really short on memory. (Each allowed component costs a hundred or so
  159060. * bytes of storage, whether actually used in an image or not.)
  159061. */
  159062. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159063. /*
  159064. * Basic data types.
  159065. * You may need to change these if you have a machine with unusual data
  159066. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159067. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159068. * but it had better be at least 16.
  159069. */
  159070. /* Representation of a single sample (pixel element value).
  159071. * We frequently allocate large arrays of these, so it's important to keep
  159072. * them small. But if you have memory to burn and access to char or short
  159073. * arrays is very slow on your hardware, you might want to change these.
  159074. */
  159075. #if BITS_IN_JSAMPLE == 8
  159076. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159077. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159078. */
  159079. #ifdef HAVE_UNSIGNED_CHAR
  159080. typedef unsigned char JSAMPLE;
  159081. #define GETJSAMPLE(value) ((int) (value))
  159082. #else /* not HAVE_UNSIGNED_CHAR */
  159083. typedef char JSAMPLE;
  159084. #ifdef CHAR_IS_UNSIGNED
  159085. #define GETJSAMPLE(value) ((int) (value))
  159086. #else
  159087. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159088. #endif /* CHAR_IS_UNSIGNED */
  159089. #endif /* HAVE_UNSIGNED_CHAR */
  159090. #define MAXJSAMPLE 255
  159091. #define CENTERJSAMPLE 128
  159092. #endif /* BITS_IN_JSAMPLE == 8 */
  159093. #if BITS_IN_JSAMPLE == 12
  159094. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159095. * On nearly all machines "short" will do nicely.
  159096. */
  159097. typedef short JSAMPLE;
  159098. #define GETJSAMPLE(value) ((int) (value))
  159099. #define MAXJSAMPLE 4095
  159100. #define CENTERJSAMPLE 2048
  159101. #endif /* BITS_IN_JSAMPLE == 12 */
  159102. /* Representation of a DCT frequency coefficient.
  159103. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159104. * Again, we allocate large arrays of these, but you can change to int
  159105. * if you have memory to burn and "short" is really slow.
  159106. */
  159107. typedef short JCOEF;
  159108. /* Compressed datastreams are represented as arrays of JOCTET.
  159109. * These must be EXACTLY 8 bits wide, at least once they are written to
  159110. * external storage. Note that when using the stdio data source/destination
  159111. * managers, this is also the data type passed to fread/fwrite.
  159112. */
  159113. #ifdef HAVE_UNSIGNED_CHAR
  159114. typedef unsigned char JOCTET;
  159115. #define GETJOCTET(value) (value)
  159116. #else /* not HAVE_UNSIGNED_CHAR */
  159117. typedef char JOCTET;
  159118. #ifdef CHAR_IS_UNSIGNED
  159119. #define GETJOCTET(value) (value)
  159120. #else
  159121. #define GETJOCTET(value) ((value) & 0xFF)
  159122. #endif /* CHAR_IS_UNSIGNED */
  159123. #endif /* HAVE_UNSIGNED_CHAR */
  159124. /* These typedefs are used for various table entries and so forth.
  159125. * They must be at least as wide as specified; but making them too big
  159126. * won't cost a huge amount of memory, so we don't provide special
  159127. * extraction code like we did for JSAMPLE. (In other words, these
  159128. * typedefs live at a different point on the speed/space tradeoff curve.)
  159129. */
  159130. /* UINT8 must hold at least the values 0..255. */
  159131. #ifdef HAVE_UNSIGNED_CHAR
  159132. typedef unsigned char UINT8;
  159133. #else /* not HAVE_UNSIGNED_CHAR */
  159134. #ifdef CHAR_IS_UNSIGNED
  159135. typedef char UINT8;
  159136. #else /* not CHAR_IS_UNSIGNED */
  159137. typedef short UINT8;
  159138. #endif /* CHAR_IS_UNSIGNED */
  159139. #endif /* HAVE_UNSIGNED_CHAR */
  159140. /* UINT16 must hold at least the values 0..65535. */
  159141. #ifdef HAVE_UNSIGNED_SHORT
  159142. typedef unsigned short UINT16;
  159143. #else /* not HAVE_UNSIGNED_SHORT */
  159144. typedef unsigned int UINT16;
  159145. #endif /* HAVE_UNSIGNED_SHORT */
  159146. /* INT16 must hold at least the values -32768..32767. */
  159147. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159148. typedef short INT16;
  159149. #endif
  159150. /* INT32 must hold at least signed 32-bit values. */
  159151. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159152. typedef long INT32;
  159153. #endif
  159154. /* Datatype used for image dimensions. The JPEG standard only supports
  159155. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159156. * "unsigned int" is sufficient on all machines. However, if you need to
  159157. * handle larger images and you don't mind deviating from the spec, you
  159158. * can change this datatype.
  159159. */
  159160. typedef unsigned int JDIMENSION;
  159161. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159162. /* These macros are used in all function definitions and extern declarations.
  159163. * You could modify them if you need to change function linkage conventions;
  159164. * in particular, you'll need to do that to make the library a Windows DLL.
  159165. * Another application is to make all functions global for use with debuggers
  159166. * or code profilers that require it.
  159167. */
  159168. /* a function called through method pointers: */
  159169. #define METHODDEF(type) static type
  159170. /* a function used only in its module: */
  159171. #define LOCAL(type) static type
  159172. /* a function referenced thru EXTERNs: */
  159173. #define GLOBAL(type) type
  159174. /* a reference to a GLOBAL function: */
  159175. #define EXTERN(type) extern type
  159176. /* This macro is used to declare a "method", that is, a function pointer.
  159177. * We want to supply prototype parameters if the compiler can cope.
  159178. * Note that the arglist parameter must be parenthesized!
  159179. * Again, you can customize this if you need special linkage keywords.
  159180. */
  159181. #ifdef HAVE_PROTOTYPES
  159182. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159183. #else
  159184. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159185. #endif
  159186. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159187. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159188. * by just saying "FAR *" where such a pointer is needed. In a few places
  159189. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159190. */
  159191. #ifdef NEED_FAR_POINTERS
  159192. #define FAR far
  159193. #else
  159194. #define FAR
  159195. #endif
  159196. /*
  159197. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159198. * in standard header files. Or you may have conflicts with application-
  159199. * specific header files that you want to include together with these files.
  159200. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159201. */
  159202. #ifndef HAVE_BOOLEAN
  159203. typedef int boolean;
  159204. #endif
  159205. #ifndef FALSE /* in case these macros already exist */
  159206. #define FALSE 0 /* values of boolean */
  159207. #endif
  159208. #ifndef TRUE
  159209. #define TRUE 1
  159210. #endif
  159211. /*
  159212. * The remaining options affect code selection within the JPEG library,
  159213. * but they don't need to be visible to most applications using the library.
  159214. * To minimize application namespace pollution, the symbols won't be
  159215. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159216. */
  159217. #ifdef JPEG_INTERNALS
  159218. #define JPEG_INTERNAL_OPTIONS
  159219. #endif
  159220. #ifdef JPEG_INTERNAL_OPTIONS
  159221. /*
  159222. * These defines indicate whether to include various optional functions.
  159223. * Undefining some of these symbols will produce a smaller but less capable
  159224. * library. Note that you can leave certain source files out of the
  159225. * compilation/linking process if you've #undef'd the corresponding symbols.
  159226. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159227. */
  159228. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159229. /* Capability options common to encoder and decoder: */
  159230. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159231. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159232. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159233. /* Encoder capability options: */
  159234. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159235. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159236. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159237. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159238. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159239. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159240. * precision, so jchuff.c normally uses entropy optimization to compute
  159241. * usable tables for higher precision. If you don't want to do optimization,
  159242. * you'll have to supply different default Huffman tables.
  159243. * The exact same statements apply for progressive JPEG: the default tables
  159244. * don't work for progressive mode. (This may get fixed, however.)
  159245. */
  159246. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159247. /* Decoder capability options: */
  159248. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159249. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159250. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159251. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159252. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159253. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159254. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159255. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159256. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159257. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159258. /* more capability options later, no doubt */
  159259. /*
  159260. * Ordering of RGB data in scanlines passed to or from the application.
  159261. * If your application wants to deal with data in the order B,G,R, just
  159262. * change these macros. You can also deal with formats such as R,G,B,X
  159263. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159264. * the offsets will also change the order in which colormap data is organized.
  159265. * RESTRICTIONS:
  159266. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159267. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159268. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159269. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159270. * is not 3 (they don't understand about dummy color components!). So you
  159271. * can't use color quantization if you change that value.
  159272. */
  159273. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  159274. #define RGB_GREEN 1 /* Offset of Green */
  159275. #define RGB_BLUE 2 /* Offset of Blue */
  159276. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  159277. /* Definitions for speed-related optimizations. */
  159278. /* If your compiler supports inline functions, define INLINE
  159279. * as the inline keyword; otherwise define it as empty.
  159280. */
  159281. #ifndef INLINE
  159282. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  159283. #define INLINE __inline__
  159284. #endif
  159285. #ifndef INLINE
  159286. #define INLINE /* default is to define it as empty */
  159287. #endif
  159288. #endif
  159289. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  159290. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  159291. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  159292. */
  159293. #ifndef MULTIPLIER
  159294. #define MULTIPLIER int /* type for fastest integer multiply */
  159295. #endif
  159296. /* FAST_FLOAT should be either float or double, whichever is done faster
  159297. * by your compiler. (Note that this type is only used in the floating point
  159298. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  159299. * Typically, float is faster in ANSI C compilers, while double is faster in
  159300. * pre-ANSI compilers (because they insist on converting to double anyway).
  159301. * The code below therefore chooses float if we have ANSI-style prototypes.
  159302. */
  159303. #ifndef FAST_FLOAT
  159304. #ifdef HAVE_PROTOTYPES
  159305. #define FAST_FLOAT float
  159306. #else
  159307. #define FAST_FLOAT double
  159308. #endif
  159309. #endif
  159310. #endif /* JPEG_INTERNAL_OPTIONS */
  159311. /*** End of inlined file: jmorecfg.h ***/
  159312. /* seldom changed options */
  159313. /* Version ID for the JPEG library.
  159314. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159315. */
  159316. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159317. /* Various constants determining the sizes of things.
  159318. * All of these are specified by the JPEG standard, so don't change them
  159319. * if you want to be compatible.
  159320. */
  159321. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159322. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159323. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159324. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159325. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159326. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159327. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159328. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159329. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159330. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159331. * to handle it. We even let you do this from the jconfig.h file. However,
  159332. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159333. * sometimes emits noncompliant files doesn't mean you should too.
  159334. */
  159335. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159336. #ifndef D_MAX_BLOCKS_IN_MCU
  159337. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159338. #endif
  159339. /* Data structures for images (arrays of samples and of DCT coefficients).
  159340. * On 80x86 machines, the image arrays are too big for near pointers,
  159341. * but the pointer arrays can fit in near memory.
  159342. */
  159343. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159344. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159345. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159346. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159347. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159348. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159349. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159350. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159351. /* Types for JPEG compression parameters and working tables. */
  159352. /* DCT coefficient quantization tables. */
  159353. typedef struct {
  159354. /* This array gives the coefficient quantizers in natural array order
  159355. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159356. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159357. */
  159358. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159359. /* This field is used only during compression. It's initialized FALSE when
  159360. * the table is created, and set TRUE when it's been output to the file.
  159361. * You could suppress output of a table by setting this to TRUE.
  159362. * (See jpeg_suppress_tables for an example.)
  159363. */
  159364. boolean sent_table; /* TRUE when table has been output */
  159365. } JQUANT_TBL;
  159366. /* Huffman coding tables. */
  159367. typedef struct {
  159368. /* These two fields directly represent the contents of a JPEG DHT marker */
  159369. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159370. /* length k bits; bits[0] is unused */
  159371. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159372. /* This field is used only during compression. It's initialized FALSE when
  159373. * the table is created, and set TRUE when it's been output to the file.
  159374. * You could suppress output of a table by setting this to TRUE.
  159375. * (See jpeg_suppress_tables for an example.)
  159376. */
  159377. boolean sent_table; /* TRUE when table has been output */
  159378. } JHUFF_TBL;
  159379. /* Basic info about one component (color channel). */
  159380. typedef struct {
  159381. /* These values are fixed over the whole image. */
  159382. /* For compression, they must be supplied by parameter setup; */
  159383. /* for decompression, they are read from the SOF marker. */
  159384. int component_id; /* identifier for this component (0..255) */
  159385. int component_index; /* its index in SOF or cinfo->comp_info[] */
  159386. int h_samp_factor; /* horizontal sampling factor (1..4) */
  159387. int v_samp_factor; /* vertical sampling factor (1..4) */
  159388. int quant_tbl_no; /* quantization table selector (0..3) */
  159389. /* These values may vary between scans. */
  159390. /* For compression, they must be supplied by parameter setup; */
  159391. /* for decompression, they are read from the SOS marker. */
  159392. /* The decompressor output side may not use these variables. */
  159393. int dc_tbl_no; /* DC entropy table selector (0..3) */
  159394. int ac_tbl_no; /* AC entropy table selector (0..3) */
  159395. /* Remaining fields should be treated as private by applications. */
  159396. /* These values are computed during compression or decompression startup: */
  159397. /* Component's size in DCT blocks.
  159398. * Any dummy blocks added to complete an MCU are not counted; therefore
  159399. * these values do not depend on whether a scan is interleaved or not.
  159400. */
  159401. JDIMENSION width_in_blocks;
  159402. JDIMENSION height_in_blocks;
  159403. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  159404. * For decompression this is the size of the output from one DCT block,
  159405. * reflecting any scaling we choose to apply during the IDCT step.
  159406. * Values of 1,2,4,8 are likely to be supported. Note that different
  159407. * components may receive different IDCT scalings.
  159408. */
  159409. int DCT_scaled_size;
  159410. /* The downsampled dimensions are the component's actual, unpadded number
  159411. * of samples at the main buffer (preprocessing/compression interface), thus
  159412. * downsampled_width = ceil(image_width * Hi/Hmax)
  159413. * and similarly for height. For decompression, IDCT scaling is included, so
  159414. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  159415. */
  159416. JDIMENSION downsampled_width; /* actual width in samples */
  159417. JDIMENSION downsampled_height; /* actual height in samples */
  159418. /* This flag is used only for decompression. In cases where some of the
  159419. * components will be ignored (eg grayscale output from YCbCr image),
  159420. * we can skip most computations for the unused components.
  159421. */
  159422. boolean component_needed; /* do we need the value of this component? */
  159423. /* These values are computed before starting a scan of the component. */
  159424. /* The decompressor output side may not use these variables. */
  159425. int MCU_width; /* number of blocks per MCU, horizontally */
  159426. int MCU_height; /* number of blocks per MCU, vertically */
  159427. int MCU_blocks; /* MCU_width * MCU_height */
  159428. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  159429. int last_col_width; /* # of non-dummy blocks across in last MCU */
  159430. int last_row_height; /* # of non-dummy blocks down in last MCU */
  159431. /* Saved quantization table for component; NULL if none yet saved.
  159432. * See jdinput.c comments about the need for this information.
  159433. * This field is currently used only for decompression.
  159434. */
  159435. JQUANT_TBL * quant_table;
  159436. /* Private per-component storage for DCT or IDCT subsystem. */
  159437. void * dct_table;
  159438. } jpeg_component_info;
  159439. /* The script for encoding a multiple-scan file is an array of these: */
  159440. typedef struct {
  159441. int comps_in_scan; /* number of components encoded in this scan */
  159442. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  159443. int Ss, Se; /* progressive JPEG spectral selection parms */
  159444. int Ah, Al; /* progressive JPEG successive approx. parms */
  159445. } jpeg_scan_info;
  159446. /* The decompressor can save APPn and COM markers in a list of these: */
  159447. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  159448. struct jpeg_marker_struct {
  159449. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  159450. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  159451. unsigned int original_length; /* # bytes of data in the file */
  159452. unsigned int data_length; /* # bytes of data saved at data[] */
  159453. JOCTET FAR * data; /* the data contained in the marker */
  159454. /* the marker length word is not counted in data_length or original_length */
  159455. };
  159456. /* Known color spaces. */
  159457. typedef enum {
  159458. JCS_UNKNOWN, /* error/unspecified */
  159459. JCS_GRAYSCALE, /* monochrome */
  159460. JCS_RGB, /* red/green/blue */
  159461. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  159462. JCS_CMYK, /* C/M/Y/K */
  159463. JCS_YCCK /* Y/Cb/Cr/K */
  159464. } J_COLOR_SPACE;
  159465. /* DCT/IDCT algorithm options. */
  159466. typedef enum {
  159467. JDCT_ISLOW, /* slow but accurate integer algorithm */
  159468. JDCT_IFAST, /* faster, less accurate integer method */
  159469. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  159470. } J_DCT_METHOD;
  159471. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  159472. #define JDCT_DEFAULT JDCT_ISLOW
  159473. #endif
  159474. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  159475. #define JDCT_FASTEST JDCT_IFAST
  159476. #endif
  159477. /* Dithering options for decompression. */
  159478. typedef enum {
  159479. JDITHER_NONE, /* no dithering */
  159480. JDITHER_ORDERED, /* simple ordered dither */
  159481. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  159482. } J_DITHER_MODE;
  159483. /* Common fields between JPEG compression and decompression master structs. */
  159484. #define jpeg_common_fields \
  159485. struct jpeg_error_mgr * err; /* Error handler module */\
  159486. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  159487. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  159488. void * client_data; /* Available for use by application */\
  159489. boolean is_decompressor; /* So common code can tell which is which */\
  159490. int global_state /* For checking call sequence validity */
  159491. /* Routines that are to be used by both halves of the library are declared
  159492. * to receive a pointer to this structure. There are no actual instances of
  159493. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  159494. */
  159495. struct jpeg_common_struct {
  159496. jpeg_common_fields; /* Fields common to both master struct types */
  159497. /* Additional fields follow in an actual jpeg_compress_struct or
  159498. * jpeg_decompress_struct. All three structs must agree on these
  159499. * initial fields! (This would be a lot cleaner in C++.)
  159500. */
  159501. };
  159502. typedef struct jpeg_common_struct * j_common_ptr;
  159503. typedef struct jpeg_compress_struct * j_compress_ptr;
  159504. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  159505. /* Master record for a compression instance */
  159506. struct jpeg_compress_struct {
  159507. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  159508. /* Destination for compressed data */
  159509. struct jpeg_destination_mgr * dest;
  159510. /* Description of source image --- these fields must be filled in by
  159511. * outer application before starting compression. in_color_space must
  159512. * be correct before you can even call jpeg_set_defaults().
  159513. */
  159514. JDIMENSION image_width; /* input image width */
  159515. JDIMENSION image_height; /* input image height */
  159516. int input_components; /* # of color components in input image */
  159517. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  159518. double input_gamma; /* image gamma of input image */
  159519. /* Compression parameters --- these fields must be set before calling
  159520. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  159521. * initialize everything to reasonable defaults, then changing anything
  159522. * the application specifically wants to change. That way you won't get
  159523. * burnt when new parameters are added. Also note that there are several
  159524. * helper routines to simplify changing parameters.
  159525. */
  159526. int data_precision; /* bits of precision in image data */
  159527. int num_components; /* # of color components in JPEG image */
  159528. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159529. jpeg_component_info * comp_info;
  159530. /* comp_info[i] describes component that appears i'th in SOF */
  159531. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159532. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159533. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159534. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159535. /* ptrs to Huffman coding tables, or NULL if not defined */
  159536. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159537. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159538. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159539. int num_scans; /* # of entries in scan_info array */
  159540. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  159541. /* The default value of scan_info is NULL, which causes a single-scan
  159542. * sequential JPEG file to be emitted. To create a multi-scan file,
  159543. * set num_scans and scan_info to point to an array of scan definitions.
  159544. */
  159545. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  159546. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159547. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  159548. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159549. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  159550. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  159551. /* The restart interval can be specified in absolute MCUs by setting
  159552. * restart_interval, or in MCU rows by setting restart_in_rows
  159553. * (in which case the correct restart_interval will be figured
  159554. * for each scan).
  159555. */
  159556. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  159557. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  159558. /* Parameters controlling emission of special markers. */
  159559. boolean write_JFIF_header; /* should a JFIF marker be written? */
  159560. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  159561. UINT8 JFIF_minor_version;
  159562. /* These three values are not used by the JPEG code, merely copied */
  159563. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  159564. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  159565. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  159566. UINT8 density_unit; /* JFIF code for pixel size units */
  159567. UINT16 X_density; /* Horizontal pixel density */
  159568. UINT16 Y_density; /* Vertical pixel density */
  159569. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  159570. /* State variable: index of next scanline to be written to
  159571. * jpeg_write_scanlines(). Application may use this to control its
  159572. * processing loop, e.g., "while (next_scanline < image_height)".
  159573. */
  159574. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  159575. /* Remaining fields are known throughout compressor, but generally
  159576. * should not be touched by a surrounding application.
  159577. */
  159578. /*
  159579. * These fields are computed during compression startup
  159580. */
  159581. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  159582. int max_h_samp_factor; /* largest h_samp_factor */
  159583. int max_v_samp_factor; /* largest v_samp_factor */
  159584. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  159585. /* The coefficient controller receives data in units of MCU rows as defined
  159586. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  159587. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  159588. * "iMCU" (interleaved MCU) row.
  159589. */
  159590. /*
  159591. * These fields are valid during any one scan.
  159592. * They describe the components and MCUs actually appearing in the scan.
  159593. */
  159594. int comps_in_scan; /* # of JPEG components in this scan */
  159595. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159596. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159597. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159598. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159599. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159600. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  159601. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159602. /* i'th block in an MCU */
  159603. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159604. /*
  159605. * Links to compression subobjects (methods and private variables of modules)
  159606. */
  159607. struct jpeg_comp_master * master;
  159608. struct jpeg_c_main_controller * main;
  159609. struct jpeg_c_prep_controller * prep;
  159610. struct jpeg_c_coef_controller * coef;
  159611. struct jpeg_marker_writer * marker;
  159612. struct jpeg_color_converter * cconvert;
  159613. struct jpeg_downsampler * downsample;
  159614. struct jpeg_forward_dct * fdct;
  159615. struct jpeg_entropy_encoder * entropy;
  159616. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  159617. int script_space_size;
  159618. };
  159619. /* Master record for a decompression instance */
  159620. struct jpeg_decompress_struct {
  159621. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  159622. /* Source of compressed data */
  159623. struct jpeg_source_mgr * src;
  159624. /* Basic description of image --- filled in by jpeg_read_header(). */
  159625. /* Application may inspect these values to decide how to process image. */
  159626. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  159627. JDIMENSION image_height; /* nominal image height */
  159628. int num_components; /* # of color components in JPEG image */
  159629. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159630. /* Decompression processing parameters --- these fields must be set before
  159631. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  159632. * them to default values.
  159633. */
  159634. J_COLOR_SPACE out_color_space; /* colorspace for output */
  159635. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  159636. double output_gamma; /* image gamma wanted in output */
  159637. boolean buffered_image; /* TRUE=multiple output passes */
  159638. boolean raw_data_out; /* TRUE=downsampled data wanted */
  159639. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  159640. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  159641. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  159642. boolean quantize_colors; /* TRUE=colormapped output wanted */
  159643. /* the following are ignored if not quantize_colors: */
  159644. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  159645. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  159646. int desired_number_of_colors; /* max # colors to use in created colormap */
  159647. /* these are significant only in buffered-image mode: */
  159648. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  159649. boolean enable_external_quant;/* enable future use of external colormap */
  159650. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  159651. /* Description of actual output image that will be returned to application.
  159652. * These fields are computed by jpeg_start_decompress().
  159653. * You can also use jpeg_calc_output_dimensions() to determine these values
  159654. * in advance of calling jpeg_start_decompress().
  159655. */
  159656. JDIMENSION output_width; /* scaled image width */
  159657. JDIMENSION output_height; /* scaled image height */
  159658. int out_color_components; /* # of color components in out_color_space */
  159659. int output_components; /* # of color components returned */
  159660. /* output_components is 1 (a colormap index) when quantizing colors;
  159661. * otherwise it equals out_color_components.
  159662. */
  159663. int rec_outbuf_height; /* min recommended height of scanline buffer */
  159664. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  159665. * high, space and time will be wasted due to unnecessary data copying.
  159666. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  159667. */
  159668. /* When quantizing colors, the output colormap is described by these fields.
  159669. * The application can supply a colormap by setting colormap non-NULL before
  159670. * calling jpeg_start_decompress; otherwise a colormap is created during
  159671. * jpeg_start_decompress or jpeg_start_output.
  159672. * The map has out_color_components rows and actual_number_of_colors columns.
  159673. */
  159674. int actual_number_of_colors; /* number of entries in use */
  159675. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  159676. /* State variables: these variables indicate the progress of decompression.
  159677. * The application may examine these but must not modify them.
  159678. */
  159679. /* Row index of next scanline to be read from jpeg_read_scanlines().
  159680. * Application may use this to control its processing loop, e.g.,
  159681. * "while (output_scanline < output_height)".
  159682. */
  159683. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  159684. /* Current input scan number and number of iMCU rows completed in scan.
  159685. * These indicate the progress of the decompressor input side.
  159686. */
  159687. int input_scan_number; /* Number of SOS markers seen so far */
  159688. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  159689. /* The "output scan number" is the notional scan being displayed by the
  159690. * output side. The decompressor will not allow output scan/row number
  159691. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  159692. */
  159693. int output_scan_number; /* Nominal scan number being displayed */
  159694. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  159695. /* Current progression status. coef_bits[c][i] indicates the precision
  159696. * with which component c's DCT coefficient i (in zigzag order) is known.
  159697. * It is -1 when no data has yet been received, otherwise it is the point
  159698. * transform (shift) value for the most recent scan of the coefficient
  159699. * (thus, 0 at completion of the progression).
  159700. * This pointer is NULL when reading a non-progressive file.
  159701. */
  159702. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  159703. /* Internal JPEG parameters --- the application usually need not look at
  159704. * these fields. Note that the decompressor output side may not use
  159705. * any parameters that can change between scans.
  159706. */
  159707. /* Quantization and Huffman tables are carried forward across input
  159708. * datastreams when processing abbreviated JPEG datastreams.
  159709. */
  159710. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159711. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159712. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159713. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159714. /* ptrs to Huffman coding tables, or NULL if not defined */
  159715. /* These parameters are never carried across datastreams, since they
  159716. * are given in SOF/SOS markers or defined to be reset by SOI.
  159717. */
  159718. int data_precision; /* bits of precision in image data */
  159719. jpeg_component_info * comp_info;
  159720. /* comp_info[i] describes component that appears i'th in SOF */
  159721. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  159722. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159723. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159724. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159725. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159726. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  159727. /* These fields record data obtained from optional markers recognized by
  159728. * the JPEG library.
  159729. */
  159730. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  159731. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  159732. UINT8 JFIF_major_version; /* JFIF version number */
  159733. UINT8 JFIF_minor_version;
  159734. UINT8 density_unit; /* JFIF code for pixel size units */
  159735. UINT16 X_density; /* Horizontal pixel density */
  159736. UINT16 Y_density; /* Vertical pixel density */
  159737. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  159738. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  159739. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159740. /* Aside from the specific data retained from APPn markers known to the
  159741. * library, the uninterpreted contents of any or all APPn and COM markers
  159742. * can be saved in a list for examination by the application.
  159743. */
  159744. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  159745. /* Remaining fields are known throughout decompressor, but generally
  159746. * should not be touched by a surrounding application.
  159747. */
  159748. /*
  159749. * These fields are computed during decompression startup
  159750. */
  159751. int max_h_samp_factor; /* largest h_samp_factor */
  159752. int max_v_samp_factor; /* largest v_samp_factor */
  159753. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  159754. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  159755. /* The coefficient controller's input and output progress is measured in
  159756. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  159757. * in fully interleaved JPEG scans, but are used whether the scan is
  159758. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  159759. * rows of each component. Therefore, the IDCT output contains
  159760. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  159761. */
  159762. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  159763. /*
  159764. * These fields are valid during any one scan.
  159765. * They describe the components and MCUs actually appearing in the scan.
  159766. * Note that the decompressor output side must not use these fields.
  159767. */
  159768. int comps_in_scan; /* # of JPEG components in this scan */
  159769. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159770. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159771. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159772. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159773. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159774. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  159775. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159776. /* i'th block in an MCU */
  159777. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159778. /* This field is shared between entropy decoder and marker parser.
  159779. * It is either zero or the code of a JPEG marker that has been
  159780. * read from the data source, but has not yet been processed.
  159781. */
  159782. int unread_marker;
  159783. /*
  159784. * Links to decompression subobjects (methods, private variables of modules)
  159785. */
  159786. struct jpeg_decomp_master * master;
  159787. struct jpeg_d_main_controller * main;
  159788. struct jpeg_d_coef_controller * coef;
  159789. struct jpeg_d_post_controller * post;
  159790. struct jpeg_input_controller * inputctl;
  159791. struct jpeg_marker_reader * marker;
  159792. struct jpeg_entropy_decoder * entropy;
  159793. struct jpeg_inverse_dct * idct;
  159794. struct jpeg_upsampler * upsample;
  159795. struct jpeg_color_deconverter * cconvert;
  159796. struct jpeg_color_quantizer * cquantize;
  159797. };
  159798. /* "Object" declarations for JPEG modules that may be supplied or called
  159799. * directly by the surrounding application.
  159800. * As with all objects in the JPEG library, these structs only define the
  159801. * publicly visible methods and state variables of a module. Additional
  159802. * private fields may exist after the public ones.
  159803. */
  159804. /* Error handler object */
  159805. struct jpeg_error_mgr {
  159806. /* Error exit handler: does not return to caller */
  159807. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  159808. /* Conditionally emit a trace or warning message */
  159809. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  159810. /* Routine that actually outputs a trace or error message */
  159811. JMETHOD(void, output_message, (j_common_ptr cinfo));
  159812. /* Format a message string for the most recent JPEG error or message */
  159813. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  159814. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  159815. /* Reset error state variables at start of a new image */
  159816. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  159817. /* The message ID code and any parameters are saved here.
  159818. * A message can have one string parameter or up to 8 int parameters.
  159819. */
  159820. int msg_code;
  159821. #define JMSG_STR_PARM_MAX 80
  159822. union {
  159823. int i[8];
  159824. char s[JMSG_STR_PARM_MAX];
  159825. } msg_parm;
  159826. /* Standard state variables for error facility */
  159827. int trace_level; /* max msg_level that will be displayed */
  159828. /* For recoverable corrupt-data errors, we emit a warning message,
  159829. * but keep going unless emit_message chooses to abort. emit_message
  159830. * should count warnings in num_warnings. The surrounding application
  159831. * can check for bad data by seeing if num_warnings is nonzero at the
  159832. * end of processing.
  159833. */
  159834. long num_warnings; /* number of corrupt-data warnings */
  159835. /* These fields point to the table(s) of error message strings.
  159836. * An application can change the table pointer to switch to a different
  159837. * message list (typically, to change the language in which errors are
  159838. * reported). Some applications may wish to add additional error codes
  159839. * that will be handled by the JPEG library error mechanism; the second
  159840. * table pointer is used for this purpose.
  159841. *
  159842. * First table includes all errors generated by JPEG library itself.
  159843. * Error code 0 is reserved for a "no such error string" message.
  159844. */
  159845. const char * const * jpeg_message_table; /* Library errors */
  159846. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  159847. /* Second table can be added by application (see cjpeg/djpeg for example).
  159848. * It contains strings numbered first_addon_message..last_addon_message.
  159849. */
  159850. const char * const * addon_message_table; /* Non-library errors */
  159851. int first_addon_message; /* code for first string in addon table */
  159852. int last_addon_message; /* code for last string in addon table */
  159853. };
  159854. /* Progress monitor object */
  159855. struct jpeg_progress_mgr {
  159856. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  159857. long pass_counter; /* work units completed in this pass */
  159858. long pass_limit; /* total number of work units in this pass */
  159859. int completed_passes; /* passes completed so far */
  159860. int total_passes; /* total number of passes expected */
  159861. };
  159862. /* Data destination object for compression */
  159863. struct jpeg_destination_mgr {
  159864. JOCTET * next_output_byte; /* => next byte to write in buffer */
  159865. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  159866. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  159867. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  159868. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  159869. };
  159870. /* Data source object for decompression */
  159871. struct jpeg_source_mgr {
  159872. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  159873. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  159874. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  159875. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  159876. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  159877. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  159878. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  159879. };
  159880. /* Memory manager object.
  159881. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  159882. * and "really big" objects (virtual arrays with backing store if needed).
  159883. * The memory manager does not allow individual objects to be freed; rather,
  159884. * each created object is assigned to a pool, and whole pools can be freed
  159885. * at once. This is faster and more convenient than remembering exactly what
  159886. * to free, especially where malloc()/free() are not too speedy.
  159887. * NB: alloc routines never return NULL. They exit to error_exit if not
  159888. * successful.
  159889. */
  159890. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  159891. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  159892. #define JPOOL_NUMPOOLS 2
  159893. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  159894. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  159895. struct jpeg_memory_mgr {
  159896. /* Method pointers */
  159897. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  159898. size_t sizeofobject));
  159899. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  159900. size_t sizeofobject));
  159901. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  159902. JDIMENSION samplesperrow,
  159903. JDIMENSION numrows));
  159904. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  159905. JDIMENSION blocksperrow,
  159906. JDIMENSION numrows));
  159907. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  159908. int pool_id,
  159909. boolean pre_zero,
  159910. JDIMENSION samplesperrow,
  159911. JDIMENSION numrows,
  159912. JDIMENSION maxaccess));
  159913. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  159914. int pool_id,
  159915. boolean pre_zero,
  159916. JDIMENSION blocksperrow,
  159917. JDIMENSION numrows,
  159918. JDIMENSION maxaccess));
  159919. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  159920. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  159921. jvirt_sarray_ptr ptr,
  159922. JDIMENSION start_row,
  159923. JDIMENSION num_rows,
  159924. boolean writable));
  159925. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  159926. jvirt_barray_ptr ptr,
  159927. JDIMENSION start_row,
  159928. JDIMENSION num_rows,
  159929. boolean writable));
  159930. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  159931. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  159932. /* Limit on memory allocation for this JPEG object. (Note that this is
  159933. * merely advisory, not a guaranteed maximum; it only affects the space
  159934. * used for virtual-array buffers.) May be changed by outer application
  159935. * after creating the JPEG object.
  159936. */
  159937. long max_memory_to_use;
  159938. /* Maximum allocation request accepted by alloc_large. */
  159939. long max_alloc_chunk;
  159940. };
  159941. /* Routine signature for application-supplied marker processing methods.
  159942. * Need not pass marker code since it is stored in cinfo->unread_marker.
  159943. */
  159944. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  159945. /* Declarations for routines called by application.
  159946. * The JPP macro hides prototype parameters from compilers that can't cope.
  159947. * Note JPP requires double parentheses.
  159948. */
  159949. #ifdef HAVE_PROTOTYPES
  159950. #define JPP(arglist) arglist
  159951. #else
  159952. #define JPP(arglist) ()
  159953. #endif
  159954. /* Short forms of external names for systems with brain-damaged linkers.
  159955. * We shorten external names to be unique in the first six letters, which
  159956. * is good enough for all known systems.
  159957. * (If your compiler itself needs names to be unique in less than 15
  159958. * characters, you are out of luck. Get a better compiler.)
  159959. */
  159960. #ifdef NEED_SHORT_EXTERNAL_NAMES
  159961. #define jpeg_std_error jStdError
  159962. #define jpeg_CreateCompress jCreaCompress
  159963. #define jpeg_CreateDecompress jCreaDecompress
  159964. #define jpeg_destroy_compress jDestCompress
  159965. #define jpeg_destroy_decompress jDestDecompress
  159966. #define jpeg_stdio_dest jStdDest
  159967. #define jpeg_stdio_src jStdSrc
  159968. #define jpeg_set_defaults jSetDefaults
  159969. #define jpeg_set_colorspace jSetColorspace
  159970. #define jpeg_default_colorspace jDefColorspace
  159971. #define jpeg_set_quality jSetQuality
  159972. #define jpeg_set_linear_quality jSetLQuality
  159973. #define jpeg_add_quant_table jAddQuantTable
  159974. #define jpeg_quality_scaling jQualityScaling
  159975. #define jpeg_simple_progression jSimProgress
  159976. #define jpeg_suppress_tables jSuppressTables
  159977. #define jpeg_alloc_quant_table jAlcQTable
  159978. #define jpeg_alloc_huff_table jAlcHTable
  159979. #define jpeg_start_compress jStrtCompress
  159980. #define jpeg_write_scanlines jWrtScanlines
  159981. #define jpeg_finish_compress jFinCompress
  159982. #define jpeg_write_raw_data jWrtRawData
  159983. #define jpeg_write_marker jWrtMarker
  159984. #define jpeg_write_m_header jWrtMHeader
  159985. #define jpeg_write_m_byte jWrtMByte
  159986. #define jpeg_write_tables jWrtTables
  159987. #define jpeg_read_header jReadHeader
  159988. #define jpeg_start_decompress jStrtDecompress
  159989. #define jpeg_read_scanlines jReadScanlines
  159990. #define jpeg_finish_decompress jFinDecompress
  159991. #define jpeg_read_raw_data jReadRawData
  159992. #define jpeg_has_multiple_scans jHasMultScn
  159993. #define jpeg_start_output jStrtOutput
  159994. #define jpeg_finish_output jFinOutput
  159995. #define jpeg_input_complete jInComplete
  159996. #define jpeg_new_colormap jNewCMap
  159997. #define jpeg_consume_input jConsumeInput
  159998. #define jpeg_calc_output_dimensions jCalcDimensions
  159999. #define jpeg_save_markers jSaveMarkers
  160000. #define jpeg_set_marker_processor jSetMarker
  160001. #define jpeg_read_coefficients jReadCoefs
  160002. #define jpeg_write_coefficients jWrtCoefs
  160003. #define jpeg_copy_critical_parameters jCopyCrit
  160004. #define jpeg_abort_compress jAbrtCompress
  160005. #define jpeg_abort_decompress jAbrtDecompress
  160006. #define jpeg_abort jAbort
  160007. #define jpeg_destroy jDestroy
  160008. #define jpeg_resync_to_restart jResyncRestart
  160009. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160010. /* Default error-management setup */
  160011. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160012. JPP((struct jpeg_error_mgr * err));
  160013. /* Initialization of JPEG compression objects.
  160014. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160015. * names that applications should call. These expand to calls on
  160016. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160017. * passed for version mismatch checking.
  160018. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160019. */
  160020. #define jpeg_create_compress(cinfo) \
  160021. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160022. (size_t) sizeof(struct jpeg_compress_struct))
  160023. #define jpeg_create_decompress(cinfo) \
  160024. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160025. (size_t) sizeof(struct jpeg_decompress_struct))
  160026. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160027. int version, size_t structsize));
  160028. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160029. int version, size_t structsize));
  160030. /* Destruction of JPEG compression objects */
  160031. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160032. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160033. /* Standard data source and destination managers: stdio streams. */
  160034. /* Caller is responsible for opening the file before and closing after. */
  160035. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160036. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160037. /* Default parameter setup for compression */
  160038. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160039. /* Compression parameter setup aids */
  160040. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160041. J_COLOR_SPACE colorspace));
  160042. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160043. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160044. boolean force_baseline));
  160045. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160046. int scale_factor,
  160047. boolean force_baseline));
  160048. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160049. const unsigned int *basic_table,
  160050. int scale_factor,
  160051. boolean force_baseline));
  160052. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160053. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160054. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160055. boolean suppress));
  160056. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160057. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160058. /* Main entry points for compression */
  160059. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160060. boolean write_all_tables));
  160061. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160062. JSAMPARRAY scanlines,
  160063. JDIMENSION num_lines));
  160064. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160065. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160066. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160067. JSAMPIMAGE data,
  160068. JDIMENSION num_lines));
  160069. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160070. EXTERN(void) jpeg_write_marker
  160071. JPP((j_compress_ptr cinfo, int marker,
  160072. const JOCTET * dataptr, unsigned int datalen));
  160073. /* Same, but piecemeal. */
  160074. EXTERN(void) jpeg_write_m_header
  160075. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160076. EXTERN(void) jpeg_write_m_byte
  160077. JPP((j_compress_ptr cinfo, int val));
  160078. /* Alternate compression function: just write an abbreviated table file */
  160079. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160080. /* Decompression startup: read start of JPEG datastream to see what's there */
  160081. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160082. boolean require_image));
  160083. /* Return value is one of: */
  160084. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160085. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160086. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160087. /* If you pass require_image = TRUE (normal case), you need not check for
  160088. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160089. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160090. * give a suspension return (the stdio source module doesn't).
  160091. */
  160092. /* Main entry points for decompression */
  160093. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160094. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160095. JSAMPARRAY scanlines,
  160096. JDIMENSION max_lines));
  160097. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160098. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160099. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160100. JSAMPIMAGE data,
  160101. JDIMENSION max_lines));
  160102. /* Additional entry points for buffered-image mode. */
  160103. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160104. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160105. int scan_number));
  160106. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160107. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160108. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160109. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160110. /* Return value is one of: */
  160111. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160112. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160113. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160114. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160115. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160116. /* Precalculate output dimensions for current decompression parameters. */
  160117. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160118. /* Control saving of COM and APPn markers into marker_list. */
  160119. EXTERN(void) jpeg_save_markers
  160120. JPP((j_decompress_ptr cinfo, int marker_code,
  160121. unsigned int length_limit));
  160122. /* Install a special processing method for COM or APPn markers. */
  160123. EXTERN(void) jpeg_set_marker_processor
  160124. JPP((j_decompress_ptr cinfo, int marker_code,
  160125. jpeg_marker_parser_method routine));
  160126. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160127. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160128. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160129. jvirt_barray_ptr * coef_arrays));
  160130. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160131. j_compress_ptr dstinfo));
  160132. /* If you choose to abort compression or decompression before completing
  160133. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160134. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160135. * if you're done with the JPEG object, but if you want to clean it up and
  160136. * reuse it, call this:
  160137. */
  160138. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160139. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160140. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160141. * flavor of JPEG object. These may be more convenient in some places.
  160142. */
  160143. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160144. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160145. /* Default restart-marker-resync procedure for use by data source modules */
  160146. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160147. int desired));
  160148. /* These marker codes are exported since applications and data source modules
  160149. * are likely to want to use them.
  160150. */
  160151. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160152. #define JPEG_EOI 0xD9 /* EOI marker code */
  160153. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160154. #define JPEG_COM 0xFE /* COM marker code */
  160155. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160156. * for structure definitions that are never filled in, keep it quiet by
  160157. * supplying dummy definitions for the various substructures.
  160158. */
  160159. #ifdef INCOMPLETE_TYPES_BROKEN
  160160. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160161. struct jvirt_sarray_control { long dummy; };
  160162. struct jvirt_barray_control { long dummy; };
  160163. struct jpeg_comp_master { long dummy; };
  160164. struct jpeg_c_main_controller { long dummy; };
  160165. struct jpeg_c_prep_controller { long dummy; };
  160166. struct jpeg_c_coef_controller { long dummy; };
  160167. struct jpeg_marker_writer { long dummy; };
  160168. struct jpeg_color_converter { long dummy; };
  160169. struct jpeg_downsampler { long dummy; };
  160170. struct jpeg_forward_dct { long dummy; };
  160171. struct jpeg_entropy_encoder { long dummy; };
  160172. struct jpeg_decomp_master { long dummy; };
  160173. struct jpeg_d_main_controller { long dummy; };
  160174. struct jpeg_d_coef_controller { long dummy; };
  160175. struct jpeg_d_post_controller { long dummy; };
  160176. struct jpeg_input_controller { long dummy; };
  160177. struct jpeg_marker_reader { long dummy; };
  160178. struct jpeg_entropy_decoder { long dummy; };
  160179. struct jpeg_inverse_dct { long dummy; };
  160180. struct jpeg_upsampler { long dummy; };
  160181. struct jpeg_color_deconverter { long dummy; };
  160182. struct jpeg_color_quantizer { long dummy; };
  160183. #endif /* JPEG_INTERNALS */
  160184. #endif /* INCOMPLETE_TYPES_BROKEN */
  160185. /*
  160186. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160187. * The internal structure declarations are read only when that is true.
  160188. * Applications using the library should not include jpegint.h, but may wish
  160189. * to include jerror.h.
  160190. */
  160191. #ifdef JPEG_INTERNALS
  160192. /*** Start of inlined file: jpegint.h ***/
  160193. /* Declarations for both compression & decompression */
  160194. typedef enum { /* Operating modes for buffer controllers */
  160195. JBUF_PASS_THRU, /* Plain stripwise operation */
  160196. /* Remaining modes require a full-image buffer to have been created */
  160197. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160198. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160199. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160200. } J_BUF_MODE;
  160201. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160202. #define CSTATE_START 100 /* after create_compress */
  160203. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160204. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160205. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160206. #define DSTATE_START 200 /* after create_decompress */
  160207. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160208. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160209. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160210. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160211. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160212. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160213. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160214. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160215. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160216. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160217. /* Declarations for compression modules */
  160218. /* Master control module */
  160219. struct jpeg_comp_master {
  160220. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160221. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160222. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160223. /* State variables made visible to other modules */
  160224. boolean call_pass_startup; /* True if pass_startup must be called */
  160225. boolean is_last_pass; /* True during last pass */
  160226. };
  160227. /* Main buffer control (downsampled-data buffer) */
  160228. struct jpeg_c_main_controller {
  160229. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160230. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160231. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160232. JDIMENSION in_rows_avail));
  160233. };
  160234. /* Compression preprocessing (downsampling input buffer control) */
  160235. struct jpeg_c_prep_controller {
  160236. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160237. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160238. JSAMPARRAY input_buf,
  160239. JDIMENSION *in_row_ctr,
  160240. JDIMENSION in_rows_avail,
  160241. JSAMPIMAGE output_buf,
  160242. JDIMENSION *out_row_group_ctr,
  160243. JDIMENSION out_row_groups_avail));
  160244. };
  160245. /* Coefficient buffer control */
  160246. struct jpeg_c_coef_controller {
  160247. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160248. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160249. JSAMPIMAGE input_buf));
  160250. };
  160251. /* Colorspace conversion */
  160252. struct jpeg_color_converter {
  160253. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160254. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160255. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160256. JDIMENSION output_row, int num_rows));
  160257. };
  160258. /* Downsampling */
  160259. struct jpeg_downsampler {
  160260. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160261. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160262. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160263. JSAMPIMAGE output_buf,
  160264. JDIMENSION out_row_group_index));
  160265. boolean need_context_rows; /* TRUE if need rows above & below */
  160266. };
  160267. /* Forward DCT (also controls coefficient quantization) */
  160268. struct jpeg_forward_dct {
  160269. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160270. /* perhaps this should be an array??? */
  160271. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160272. jpeg_component_info * compptr,
  160273. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160274. JDIMENSION start_row, JDIMENSION start_col,
  160275. JDIMENSION num_blocks));
  160276. };
  160277. /* Entropy encoding */
  160278. struct jpeg_entropy_encoder {
  160279. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  160280. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  160281. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160282. };
  160283. /* Marker writing */
  160284. struct jpeg_marker_writer {
  160285. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  160286. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  160287. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  160288. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  160289. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  160290. /* These routines are exported to allow insertion of extra markers */
  160291. /* Probably only COM and APPn markers should be written this way */
  160292. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  160293. unsigned int datalen));
  160294. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  160295. };
  160296. /* Declarations for decompression modules */
  160297. /* Master control module */
  160298. struct jpeg_decomp_master {
  160299. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  160300. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  160301. /* State variables made visible to other modules */
  160302. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  160303. };
  160304. /* Input control module */
  160305. struct jpeg_input_controller {
  160306. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160307. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160308. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160309. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160310. /* State variables made visible to other modules */
  160311. boolean has_multiple_scans; /* True if file has multiple scans */
  160312. boolean eoi_reached; /* True when EOI has been consumed */
  160313. };
  160314. /* Main buffer control (downsampled-data buffer) */
  160315. struct jpeg_d_main_controller {
  160316. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160317. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160318. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160319. JDIMENSION out_rows_avail));
  160320. };
  160321. /* Coefficient buffer control */
  160322. struct jpeg_d_coef_controller {
  160323. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160324. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160325. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160326. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160327. JSAMPIMAGE output_buf));
  160328. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160329. jvirt_barray_ptr *coef_arrays;
  160330. };
  160331. /* Decompression postprocessing (color quantization buffer control) */
  160332. struct jpeg_d_post_controller {
  160333. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160334. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160335. JSAMPIMAGE input_buf,
  160336. JDIMENSION *in_row_group_ctr,
  160337. JDIMENSION in_row_groups_avail,
  160338. JSAMPARRAY output_buf,
  160339. JDIMENSION *out_row_ctr,
  160340. JDIMENSION out_rows_avail));
  160341. };
  160342. /* Marker reading & parsing */
  160343. struct jpeg_marker_reader {
  160344. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160345. /* Read markers until SOS or EOI.
  160346. * Returns same codes as are defined for jpeg_consume_input:
  160347. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160348. */
  160349. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160350. /* Read a restart marker --- exported for use by entropy decoder only */
  160351. jpeg_marker_parser_method read_restart_marker;
  160352. /* State of marker reader --- nominally internal, but applications
  160353. * supplying COM or APPn handlers might like to know the state.
  160354. */
  160355. boolean saw_SOI; /* found SOI? */
  160356. boolean saw_SOF; /* found SOF? */
  160357. int next_restart_num; /* next restart number expected (0-7) */
  160358. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160359. };
  160360. /* Entropy decoding */
  160361. struct jpeg_entropy_decoder {
  160362. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160363. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160364. JBLOCKROW *MCU_data));
  160365. /* This is here to share code between baseline and progressive decoders; */
  160366. /* other modules probably should not use it */
  160367. boolean insufficient_data; /* set TRUE after emitting warning */
  160368. };
  160369. /* Inverse DCT (also performs dequantization) */
  160370. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160371. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160372. JCOEFPTR coef_block,
  160373. JSAMPARRAY output_buf, JDIMENSION output_col));
  160374. struct jpeg_inverse_dct {
  160375. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160376. /* It is useful to allow each component to have a separate IDCT method. */
  160377. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160378. };
  160379. /* Upsampling (note that upsampler must also call color converter) */
  160380. struct jpeg_upsampler {
  160381. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160382. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  160383. JSAMPIMAGE input_buf,
  160384. JDIMENSION *in_row_group_ctr,
  160385. JDIMENSION in_row_groups_avail,
  160386. JSAMPARRAY output_buf,
  160387. JDIMENSION *out_row_ctr,
  160388. JDIMENSION out_rows_avail));
  160389. boolean need_context_rows; /* TRUE if need rows above & below */
  160390. };
  160391. /* Colorspace conversion */
  160392. struct jpeg_color_deconverter {
  160393. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160394. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  160395. JSAMPIMAGE input_buf, JDIMENSION input_row,
  160396. JSAMPARRAY output_buf, int num_rows));
  160397. };
  160398. /* Color quantization or color precision reduction */
  160399. struct jpeg_color_quantizer {
  160400. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  160401. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  160402. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  160403. int num_rows));
  160404. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  160405. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  160406. };
  160407. /* Miscellaneous useful macros */
  160408. #undef MAX
  160409. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  160410. #undef MIN
  160411. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  160412. /* We assume that right shift corresponds to signed division by 2 with
  160413. * rounding towards minus infinity. This is correct for typical "arithmetic
  160414. * shift" instructions that shift in copies of the sign bit. But some
  160415. * C compilers implement >> with an unsigned shift. For these machines you
  160416. * must define RIGHT_SHIFT_IS_UNSIGNED.
  160417. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  160418. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  160419. * included in the variables of any routine using RIGHT_SHIFT.
  160420. */
  160421. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160422. #define SHIFT_TEMPS INT32 shift_temp;
  160423. #define RIGHT_SHIFT(x,shft) \
  160424. ((shift_temp = (x)) < 0 ? \
  160425. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  160426. (shift_temp >> (shft)))
  160427. #else
  160428. #define SHIFT_TEMPS
  160429. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  160430. #endif
  160431. /* Short forms of external names for systems with brain-damaged linkers. */
  160432. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160433. #define jinit_compress_master jICompress
  160434. #define jinit_c_master_control jICMaster
  160435. #define jinit_c_main_controller jICMainC
  160436. #define jinit_c_prep_controller jICPrepC
  160437. #define jinit_c_coef_controller jICCoefC
  160438. #define jinit_color_converter jICColor
  160439. #define jinit_downsampler jIDownsampler
  160440. #define jinit_forward_dct jIFDCT
  160441. #define jinit_huff_encoder jIHEncoder
  160442. #define jinit_phuff_encoder jIPHEncoder
  160443. #define jinit_marker_writer jIMWriter
  160444. #define jinit_master_decompress jIDMaster
  160445. #define jinit_d_main_controller jIDMainC
  160446. #define jinit_d_coef_controller jIDCoefC
  160447. #define jinit_d_post_controller jIDPostC
  160448. #define jinit_input_controller jIInCtlr
  160449. #define jinit_marker_reader jIMReader
  160450. #define jinit_huff_decoder jIHDecoder
  160451. #define jinit_phuff_decoder jIPHDecoder
  160452. #define jinit_inverse_dct jIIDCT
  160453. #define jinit_upsampler jIUpsampler
  160454. #define jinit_color_deconverter jIDColor
  160455. #define jinit_1pass_quantizer jI1Quant
  160456. #define jinit_2pass_quantizer jI2Quant
  160457. #define jinit_merged_upsampler jIMUpsampler
  160458. #define jinit_memory_mgr jIMemMgr
  160459. #define jdiv_round_up jDivRound
  160460. #define jround_up jRound
  160461. #define jcopy_sample_rows jCopySamples
  160462. #define jcopy_block_row jCopyBlocks
  160463. #define jzero_far jZeroFar
  160464. #define jpeg_zigzag_order jZIGTable
  160465. #define jpeg_natural_order jZAGTable
  160466. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160467. /* Compression module initialization routines */
  160468. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  160469. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  160470. boolean transcode_only));
  160471. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  160472. boolean need_full_buffer));
  160473. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  160474. boolean need_full_buffer));
  160475. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  160476. boolean need_full_buffer));
  160477. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  160478. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  160479. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  160480. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  160481. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  160482. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  160483. /* Decompression module initialization routines */
  160484. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  160485. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  160486. boolean need_full_buffer));
  160487. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  160488. boolean need_full_buffer));
  160489. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  160490. boolean need_full_buffer));
  160491. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  160492. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  160493. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  160494. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  160495. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  160496. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  160497. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  160498. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  160499. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  160500. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  160501. /* Memory manager initialization */
  160502. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  160503. /* Utility routines in jutils.c */
  160504. EXTERN(long) jdiv_round_up JPP((long a, long b));
  160505. EXTERN(long) jround_up JPP((long a, long b));
  160506. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  160507. JSAMPARRAY output_array, int dest_row,
  160508. int num_rows, JDIMENSION num_cols));
  160509. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  160510. JDIMENSION num_blocks));
  160511. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  160512. /* Constant tables in jutils.c */
  160513. #if 0 /* This table is not actually needed in v6a */
  160514. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  160515. #endif
  160516. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  160517. /* Suppress undefined-structure complaints if necessary. */
  160518. #ifdef INCOMPLETE_TYPES_BROKEN
  160519. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  160520. struct jvirt_sarray_control { long dummy; };
  160521. struct jvirt_barray_control { long dummy; };
  160522. #endif
  160523. #endif /* INCOMPLETE_TYPES_BROKEN */
  160524. /*** End of inlined file: jpegint.h ***/
  160525. /* fetch private declarations */
  160526. /*** Start of inlined file: jerror.h ***/
  160527. /*
  160528. * To define the enum list of message codes, include this file without
  160529. * defining macro JMESSAGE. To create a message string table, include it
  160530. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  160531. */
  160532. #ifndef JMESSAGE
  160533. #ifndef JERROR_H
  160534. /* First time through, define the enum list */
  160535. #define JMAKE_ENUM_LIST
  160536. #else
  160537. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  160538. #define JMESSAGE(code,string)
  160539. #endif /* JERROR_H */
  160540. #endif /* JMESSAGE */
  160541. #ifdef JMAKE_ENUM_LIST
  160542. typedef enum {
  160543. #define JMESSAGE(code,string) code ,
  160544. #endif /* JMAKE_ENUM_LIST */
  160545. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  160546. /* For maintenance convenience, list is alphabetical by message code name */
  160547. JMESSAGE(JERR_ARITH_NOTIMPL,
  160548. "Sorry, there are legal restrictions on arithmetic coding")
  160549. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  160550. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  160551. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  160552. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  160553. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  160554. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  160555. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  160556. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  160557. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  160558. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  160559. JMESSAGE(JERR_BAD_LIB_VERSION,
  160560. "Wrong JPEG library version: library is %d, caller expects %d")
  160561. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  160562. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  160563. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  160564. JMESSAGE(JERR_BAD_PROGRESSION,
  160565. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  160566. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  160567. "Invalid progressive parameters at scan script entry %d")
  160568. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  160569. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  160570. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  160571. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  160572. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  160573. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  160574. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  160575. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  160576. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  160577. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  160578. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  160579. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  160580. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  160581. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  160582. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  160583. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  160584. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  160585. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  160586. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  160587. JMESSAGE(JERR_FILE_READ, "Input file read error")
  160588. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  160589. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  160590. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  160591. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  160592. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  160593. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  160594. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  160595. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  160596. "Cannot transcode due to multiple use of quantization table %d")
  160597. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  160598. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  160599. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  160600. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  160601. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  160602. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  160603. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  160604. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  160605. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  160606. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  160607. JMESSAGE(JERR_QUANT_COMPONENTS,
  160608. "Cannot quantize more than %d color components")
  160609. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  160610. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  160611. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  160612. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  160613. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  160614. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  160615. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  160616. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  160617. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  160618. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  160619. JMESSAGE(JERR_TFILE_WRITE,
  160620. "Write failed on temporary file --- out of disk space?")
  160621. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  160622. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  160623. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  160624. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  160625. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  160626. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  160627. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  160628. JMESSAGE(JMSG_VERSION, JVERSION)
  160629. JMESSAGE(JTRC_16BIT_TABLES,
  160630. "Caution: quantization tables are too coarse for baseline JPEG")
  160631. JMESSAGE(JTRC_ADOBE,
  160632. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  160633. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  160634. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  160635. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  160636. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  160637. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  160638. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  160639. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  160640. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  160641. JMESSAGE(JTRC_EOI, "End Of Image")
  160642. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  160643. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  160644. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  160645. "Warning: thumbnail image size does not match data length %u")
  160646. JMESSAGE(JTRC_JFIF_EXTENSION,
  160647. "JFIF extension marker: type 0x%02x, length %u")
  160648. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  160649. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  160650. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  160651. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  160652. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  160653. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  160654. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  160655. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  160656. JMESSAGE(JTRC_RST, "RST%d")
  160657. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  160658. "Smoothing not supported with nonstandard sampling ratios")
  160659. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  160660. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  160661. JMESSAGE(JTRC_SOI, "Start of Image")
  160662. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  160663. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  160664. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  160665. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  160666. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  160667. JMESSAGE(JTRC_THUMB_JPEG,
  160668. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  160669. JMESSAGE(JTRC_THUMB_PALETTE,
  160670. "JFIF extension marker: palette thumbnail image, length %u")
  160671. JMESSAGE(JTRC_THUMB_RGB,
  160672. "JFIF extension marker: RGB thumbnail image, length %u")
  160673. JMESSAGE(JTRC_UNKNOWN_IDS,
  160674. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  160675. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  160676. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  160677. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  160678. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  160679. "Inconsistent progression sequence for component %d coefficient %d")
  160680. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  160681. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  160682. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  160683. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  160684. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  160685. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  160686. JMESSAGE(JWRN_MUST_RESYNC,
  160687. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  160688. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  160689. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  160690. #ifdef JMAKE_ENUM_LIST
  160691. JMSG_LASTMSGCODE
  160692. } J_MESSAGE_CODE;
  160693. #undef JMAKE_ENUM_LIST
  160694. #endif /* JMAKE_ENUM_LIST */
  160695. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  160696. #undef JMESSAGE
  160697. #ifndef JERROR_H
  160698. #define JERROR_H
  160699. /* Macros to simplify using the error and trace message stuff */
  160700. /* The first parameter is either type of cinfo pointer */
  160701. /* Fatal errors (print message and exit) */
  160702. #define ERREXIT(cinfo,code) \
  160703. ((cinfo)->err->msg_code = (code), \
  160704. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160705. #define ERREXIT1(cinfo,code,p1) \
  160706. ((cinfo)->err->msg_code = (code), \
  160707. (cinfo)->err->msg_parm.i[0] = (p1), \
  160708. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160709. #define ERREXIT2(cinfo,code,p1,p2) \
  160710. ((cinfo)->err->msg_code = (code), \
  160711. (cinfo)->err->msg_parm.i[0] = (p1), \
  160712. (cinfo)->err->msg_parm.i[1] = (p2), \
  160713. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160714. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  160715. ((cinfo)->err->msg_code = (code), \
  160716. (cinfo)->err->msg_parm.i[0] = (p1), \
  160717. (cinfo)->err->msg_parm.i[1] = (p2), \
  160718. (cinfo)->err->msg_parm.i[2] = (p3), \
  160719. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160720. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  160721. ((cinfo)->err->msg_code = (code), \
  160722. (cinfo)->err->msg_parm.i[0] = (p1), \
  160723. (cinfo)->err->msg_parm.i[1] = (p2), \
  160724. (cinfo)->err->msg_parm.i[2] = (p3), \
  160725. (cinfo)->err->msg_parm.i[3] = (p4), \
  160726. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160727. #define ERREXITS(cinfo,code,str) \
  160728. ((cinfo)->err->msg_code = (code), \
  160729. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160730. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160731. #define MAKESTMT(stuff) do { stuff } while (0)
  160732. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  160733. #define WARNMS(cinfo,code) \
  160734. ((cinfo)->err->msg_code = (code), \
  160735. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160736. #define WARNMS1(cinfo,code,p1) \
  160737. ((cinfo)->err->msg_code = (code), \
  160738. (cinfo)->err->msg_parm.i[0] = (p1), \
  160739. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160740. #define WARNMS2(cinfo,code,p1,p2) \
  160741. ((cinfo)->err->msg_code = (code), \
  160742. (cinfo)->err->msg_parm.i[0] = (p1), \
  160743. (cinfo)->err->msg_parm.i[1] = (p2), \
  160744. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160745. /* Informational/debugging messages */
  160746. #define TRACEMS(cinfo,lvl,code) \
  160747. ((cinfo)->err->msg_code = (code), \
  160748. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160749. #define TRACEMS1(cinfo,lvl,code,p1) \
  160750. ((cinfo)->err->msg_code = (code), \
  160751. (cinfo)->err->msg_parm.i[0] = (p1), \
  160752. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160753. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  160754. ((cinfo)->err->msg_code = (code), \
  160755. (cinfo)->err->msg_parm.i[0] = (p1), \
  160756. (cinfo)->err->msg_parm.i[1] = (p2), \
  160757. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160758. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  160759. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160760. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  160761. (cinfo)->err->msg_code = (code); \
  160762. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160763. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  160764. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160765. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160766. (cinfo)->err->msg_code = (code); \
  160767. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160768. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  160769. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160770. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160771. _mp[4] = (p5); \
  160772. (cinfo)->err->msg_code = (code); \
  160773. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160774. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  160775. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160776. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160777. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  160778. (cinfo)->err->msg_code = (code); \
  160779. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160780. #define TRACEMSS(cinfo,lvl,code,str) \
  160781. ((cinfo)->err->msg_code = (code), \
  160782. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160783. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160784. #endif /* JERROR_H */
  160785. /*** End of inlined file: jerror.h ***/
  160786. /* fetch error codes too */
  160787. #endif
  160788. #endif /* JPEGLIB_H */
  160789. /*** End of inlined file: jpeglib.h ***/
  160790. /*** Start of inlined file: jcapimin.c ***/
  160791. #define JPEG_INTERNALS
  160792. /*** Start of inlined file: jinclude.h ***/
  160793. /* Include auto-config file to find out which system include files we need. */
  160794. #ifndef __jinclude_h__
  160795. #define __jinclude_h__
  160796. /*** Start of inlined file: jconfig.h ***/
  160797. /* see jconfig.doc for explanations */
  160798. // disable all the warnings under MSVC
  160799. #ifdef _MSC_VER
  160800. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  160801. #endif
  160802. #ifdef __BORLANDC__
  160803. #pragma warn -8057
  160804. #pragma warn -8019
  160805. #pragma warn -8004
  160806. #pragma warn -8008
  160807. #endif
  160808. #define HAVE_PROTOTYPES
  160809. #define HAVE_UNSIGNED_CHAR
  160810. #define HAVE_UNSIGNED_SHORT
  160811. /* #define void char */
  160812. /* #define const */
  160813. #undef CHAR_IS_UNSIGNED
  160814. #define HAVE_STDDEF_H
  160815. #define HAVE_STDLIB_H
  160816. #undef NEED_BSD_STRINGS
  160817. #undef NEED_SYS_TYPES_H
  160818. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  160819. #undef NEED_SHORT_EXTERNAL_NAMES
  160820. #undef INCOMPLETE_TYPES_BROKEN
  160821. /* Define "boolean" as unsigned char, not int, per Windows custom */
  160822. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  160823. typedef unsigned char boolean;
  160824. #endif
  160825. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  160826. #ifdef JPEG_INTERNALS
  160827. #undef RIGHT_SHIFT_IS_UNSIGNED
  160828. #endif /* JPEG_INTERNALS */
  160829. #ifdef JPEG_CJPEG_DJPEG
  160830. #define BMP_SUPPORTED /* BMP image file format */
  160831. #define GIF_SUPPORTED /* GIF image file format */
  160832. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  160833. #undef RLE_SUPPORTED /* Utah RLE image file format */
  160834. #define TARGA_SUPPORTED /* Targa image file format */
  160835. #define TWO_FILE_COMMANDLINE /* optional */
  160836. #define USE_SETMODE /* Microsoft has setmode() */
  160837. #undef NEED_SIGNAL_CATCHER
  160838. #undef DONT_USE_B_MODE
  160839. #undef PROGRESS_REPORT /* optional */
  160840. #endif /* JPEG_CJPEG_DJPEG */
  160841. /*** End of inlined file: jconfig.h ***/
  160842. /* auto configuration options */
  160843. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  160844. /*
  160845. * We need the NULL macro and size_t typedef.
  160846. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  160847. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  160848. * pull in <sys/types.h> as well.
  160849. * Note that the core JPEG library does not require <stdio.h>;
  160850. * only the default error handler and data source/destination modules do.
  160851. * But we must pull it in because of the references to FILE in jpeglib.h.
  160852. * You can remove those references if you want to compile without <stdio.h>.
  160853. */
  160854. #ifdef HAVE_STDDEF_H
  160855. #include <stddef.h>
  160856. #endif
  160857. #ifdef HAVE_STDLIB_H
  160858. #include <stdlib.h>
  160859. #endif
  160860. #ifdef NEED_SYS_TYPES_H
  160861. #include <sys/types.h>
  160862. #endif
  160863. #include <stdio.h>
  160864. /*
  160865. * We need memory copying and zeroing functions, plus strncpy().
  160866. * ANSI and System V implementations declare these in <string.h>.
  160867. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  160868. * Some systems may declare memset and memcpy in <memory.h>.
  160869. *
  160870. * NOTE: we assume the size parameters to these functions are of type size_t.
  160871. * Change the casts in these macros if not!
  160872. */
  160873. #ifdef NEED_BSD_STRINGS
  160874. #include <strings.h>
  160875. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  160876. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  160877. #else /* not BSD, assume ANSI/SysV string lib */
  160878. #include <string.h>
  160879. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  160880. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  160881. #endif
  160882. /*
  160883. * In ANSI C, and indeed any rational implementation, size_t is also the
  160884. * type returned by sizeof(). However, it seems there are some irrational
  160885. * implementations out there, in which sizeof() returns an int even though
  160886. * size_t is defined as long or unsigned long. To ensure consistent results
  160887. * we always use this SIZEOF() macro in place of using sizeof() directly.
  160888. */
  160889. #define SIZEOF(object) ((size_t) sizeof(object))
  160890. /*
  160891. * The modules that use fread() and fwrite() always invoke them through
  160892. * these macros. On some systems you may need to twiddle the argument casts.
  160893. * CAUTION: argument order is different from underlying functions!
  160894. */
  160895. #define JFREAD(file,buf,sizeofbuf) \
  160896. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  160897. #define JFWRITE(file,buf,sizeofbuf) \
  160898. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  160899. typedef enum { /* JPEG marker codes */
  160900. M_SOF0 = 0xc0,
  160901. M_SOF1 = 0xc1,
  160902. M_SOF2 = 0xc2,
  160903. M_SOF3 = 0xc3,
  160904. M_SOF5 = 0xc5,
  160905. M_SOF6 = 0xc6,
  160906. M_SOF7 = 0xc7,
  160907. M_JPG = 0xc8,
  160908. M_SOF9 = 0xc9,
  160909. M_SOF10 = 0xca,
  160910. M_SOF11 = 0xcb,
  160911. M_SOF13 = 0xcd,
  160912. M_SOF14 = 0xce,
  160913. M_SOF15 = 0xcf,
  160914. M_DHT = 0xc4,
  160915. M_DAC = 0xcc,
  160916. M_RST0 = 0xd0,
  160917. M_RST1 = 0xd1,
  160918. M_RST2 = 0xd2,
  160919. M_RST3 = 0xd3,
  160920. M_RST4 = 0xd4,
  160921. M_RST5 = 0xd5,
  160922. M_RST6 = 0xd6,
  160923. M_RST7 = 0xd7,
  160924. M_SOI = 0xd8,
  160925. M_EOI = 0xd9,
  160926. M_SOS = 0xda,
  160927. M_DQT = 0xdb,
  160928. M_DNL = 0xdc,
  160929. M_DRI = 0xdd,
  160930. M_DHP = 0xde,
  160931. M_EXP = 0xdf,
  160932. M_APP0 = 0xe0,
  160933. M_APP1 = 0xe1,
  160934. M_APP2 = 0xe2,
  160935. M_APP3 = 0xe3,
  160936. M_APP4 = 0xe4,
  160937. M_APP5 = 0xe5,
  160938. M_APP6 = 0xe6,
  160939. M_APP7 = 0xe7,
  160940. M_APP8 = 0xe8,
  160941. M_APP9 = 0xe9,
  160942. M_APP10 = 0xea,
  160943. M_APP11 = 0xeb,
  160944. M_APP12 = 0xec,
  160945. M_APP13 = 0xed,
  160946. M_APP14 = 0xee,
  160947. M_APP15 = 0xef,
  160948. M_JPG0 = 0xf0,
  160949. M_JPG13 = 0xfd,
  160950. M_COM = 0xfe,
  160951. M_TEM = 0x01,
  160952. M_ERROR = 0x100
  160953. } JPEG_MARKER;
  160954. /*
  160955. * Figure F.12: extend sign bit.
  160956. * On some machines, a shift and add will be faster than a table lookup.
  160957. */
  160958. #ifdef AVOID_TABLES
  160959. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  160960. #else
  160961. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  160962. static const int extend_test[16] = /* entry n is 2**(n-1) */
  160963. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  160964. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  160965. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  160966. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  160967. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  160968. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  160969. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  160970. #endif /* AVOID_TABLES */
  160971. #endif
  160972. /*** End of inlined file: jinclude.h ***/
  160973. /*
  160974. * Initialization of a JPEG compression object.
  160975. * The error manager must already be set up (in case memory manager fails).
  160976. */
  160977. GLOBAL(void)
  160978. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  160979. {
  160980. int i;
  160981. /* Guard against version mismatches between library and caller. */
  160982. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  160983. if (version != JPEG_LIB_VERSION)
  160984. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  160985. if (structsize != SIZEOF(struct jpeg_compress_struct))
  160986. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  160987. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  160988. /* For debugging purposes, we zero the whole master structure.
  160989. * But the application has already set the err pointer, and may have set
  160990. * client_data, so we have to save and restore those fields.
  160991. * Note: if application hasn't set client_data, tools like Purify may
  160992. * complain here.
  160993. */
  160994. {
  160995. struct jpeg_error_mgr * err = cinfo->err;
  160996. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  160997. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  160998. cinfo->err = err;
  160999. cinfo->client_data = client_data;
  161000. }
  161001. cinfo->is_decompressor = FALSE;
  161002. /* Initialize a memory manager instance for this object */
  161003. jinit_memory_mgr((j_common_ptr) cinfo);
  161004. /* Zero out pointers to permanent structures. */
  161005. cinfo->progress = NULL;
  161006. cinfo->dest = NULL;
  161007. cinfo->comp_info = NULL;
  161008. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161009. cinfo->quant_tbl_ptrs[i] = NULL;
  161010. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161011. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161012. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161013. }
  161014. cinfo->script_space = NULL;
  161015. cinfo->input_gamma = 1.0; /* in case application forgets */
  161016. /* OK, I'm ready */
  161017. cinfo->global_state = CSTATE_START;
  161018. }
  161019. /*
  161020. * Destruction of a JPEG compression object
  161021. */
  161022. GLOBAL(void)
  161023. jpeg_destroy_compress (j_compress_ptr cinfo)
  161024. {
  161025. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161026. }
  161027. /*
  161028. * Abort processing of a JPEG compression operation,
  161029. * but don't destroy the object itself.
  161030. */
  161031. GLOBAL(void)
  161032. jpeg_abort_compress (j_compress_ptr cinfo)
  161033. {
  161034. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161035. }
  161036. /*
  161037. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161038. * Marks all currently defined tables as already written (if suppress)
  161039. * or not written (if !suppress). This will control whether they get emitted
  161040. * by a subsequent jpeg_start_compress call.
  161041. *
  161042. * This routine is exported for use by applications that want to produce
  161043. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161044. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161045. * jcparam.o would be linked whether the application used it or not.
  161046. */
  161047. GLOBAL(void)
  161048. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161049. {
  161050. int i;
  161051. JQUANT_TBL * qtbl;
  161052. JHUFF_TBL * htbl;
  161053. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161054. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161055. qtbl->sent_table = suppress;
  161056. }
  161057. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161058. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161059. htbl->sent_table = suppress;
  161060. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161061. htbl->sent_table = suppress;
  161062. }
  161063. }
  161064. /*
  161065. * Finish JPEG compression.
  161066. *
  161067. * If a multipass operating mode was selected, this may do a great deal of
  161068. * work including most of the actual output.
  161069. */
  161070. GLOBAL(void)
  161071. jpeg_finish_compress (j_compress_ptr cinfo)
  161072. {
  161073. JDIMENSION iMCU_row;
  161074. if (cinfo->global_state == CSTATE_SCANNING ||
  161075. cinfo->global_state == CSTATE_RAW_OK) {
  161076. /* Terminate first pass */
  161077. if (cinfo->next_scanline < cinfo->image_height)
  161078. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161079. (*cinfo->master->finish_pass) (cinfo);
  161080. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161081. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161082. /* Perform any remaining passes */
  161083. while (! cinfo->master->is_last_pass) {
  161084. (*cinfo->master->prepare_for_pass) (cinfo);
  161085. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161086. if (cinfo->progress != NULL) {
  161087. cinfo->progress->pass_counter = (long) iMCU_row;
  161088. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161089. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161090. }
  161091. /* We bypass the main controller and invoke coef controller directly;
  161092. * all work is being done from the coefficient buffer.
  161093. */
  161094. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161095. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161096. }
  161097. (*cinfo->master->finish_pass) (cinfo);
  161098. }
  161099. /* Write EOI, do final cleanup */
  161100. (*cinfo->marker->write_file_trailer) (cinfo);
  161101. (*cinfo->dest->term_destination) (cinfo);
  161102. /* We can use jpeg_abort to release memory and reset global_state */
  161103. jpeg_abort((j_common_ptr) cinfo);
  161104. }
  161105. /*
  161106. * Write a special marker.
  161107. * This is only recommended for writing COM or APPn markers.
  161108. * Must be called after jpeg_start_compress() and before
  161109. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161110. */
  161111. GLOBAL(void)
  161112. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161113. const JOCTET *dataptr, unsigned int datalen)
  161114. {
  161115. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161116. if (cinfo->next_scanline != 0 ||
  161117. (cinfo->global_state != CSTATE_SCANNING &&
  161118. cinfo->global_state != CSTATE_RAW_OK &&
  161119. cinfo->global_state != CSTATE_WRCOEFS))
  161120. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161121. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161122. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161123. while (datalen--) {
  161124. (*write_marker_byte) (cinfo, *dataptr);
  161125. dataptr++;
  161126. }
  161127. }
  161128. /* Same, but piecemeal. */
  161129. GLOBAL(void)
  161130. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161131. {
  161132. if (cinfo->next_scanline != 0 ||
  161133. (cinfo->global_state != CSTATE_SCANNING &&
  161134. cinfo->global_state != CSTATE_RAW_OK &&
  161135. cinfo->global_state != CSTATE_WRCOEFS))
  161136. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161137. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161138. }
  161139. GLOBAL(void)
  161140. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161141. {
  161142. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161143. }
  161144. /*
  161145. * Alternate compression function: just write an abbreviated table file.
  161146. * Before calling this, all parameters and a data destination must be set up.
  161147. *
  161148. * To produce a pair of files containing abbreviated tables and abbreviated
  161149. * image data, one would proceed as follows:
  161150. *
  161151. * initialize JPEG object
  161152. * set JPEG parameters
  161153. * set destination to table file
  161154. * jpeg_write_tables(cinfo);
  161155. * set destination to image file
  161156. * jpeg_start_compress(cinfo, FALSE);
  161157. * write data...
  161158. * jpeg_finish_compress(cinfo);
  161159. *
  161160. * jpeg_write_tables has the side effect of marking all tables written
  161161. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161162. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161163. */
  161164. GLOBAL(void)
  161165. jpeg_write_tables (j_compress_ptr cinfo)
  161166. {
  161167. if (cinfo->global_state != CSTATE_START)
  161168. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161169. /* (Re)initialize error mgr and destination modules */
  161170. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161171. (*cinfo->dest->init_destination) (cinfo);
  161172. /* Initialize the marker writer ... bit of a crock to do it here. */
  161173. jinit_marker_writer(cinfo);
  161174. /* Write them tables! */
  161175. (*cinfo->marker->write_tables_only) (cinfo);
  161176. /* And clean up. */
  161177. (*cinfo->dest->term_destination) (cinfo);
  161178. /*
  161179. * In library releases up through v6a, we called jpeg_abort() here to free
  161180. * any working memory allocated by the destination manager and marker
  161181. * writer. Some applications had a problem with that: they allocated space
  161182. * of their own from the library memory manager, and didn't want it to go
  161183. * away during write_tables. So now we do nothing. This will cause a
  161184. * memory leak if an app calls write_tables repeatedly without doing a full
  161185. * compression cycle or otherwise resetting the JPEG object. However, that
  161186. * seems less bad than unexpectedly freeing memory in the normal case.
  161187. * An app that prefers the old behavior can call jpeg_abort for itself after
  161188. * each call to jpeg_write_tables().
  161189. */
  161190. }
  161191. /*** End of inlined file: jcapimin.c ***/
  161192. /*** Start of inlined file: jcapistd.c ***/
  161193. #define JPEG_INTERNALS
  161194. /*
  161195. * Compression initialization.
  161196. * Before calling this, all parameters and a data destination must be set up.
  161197. *
  161198. * We require a write_all_tables parameter as a failsafe check when writing
  161199. * multiple datastreams from the same compression object. Since prior runs
  161200. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161201. * would emit an abbreviated stream (no tables) by default. This may be what
  161202. * is wanted, but for safety's sake it should not be the default behavior:
  161203. * programmers should have to make a deliberate choice to emit abbreviated
  161204. * images. Therefore the documentation and examples should encourage people
  161205. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161206. * wrong thing.
  161207. */
  161208. GLOBAL(void)
  161209. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161210. {
  161211. if (cinfo->global_state != CSTATE_START)
  161212. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161213. if (write_all_tables)
  161214. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161215. /* (Re)initialize error mgr and destination modules */
  161216. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161217. (*cinfo->dest->init_destination) (cinfo);
  161218. /* Perform master selection of active modules */
  161219. jinit_compress_master(cinfo);
  161220. /* Set up for the first pass */
  161221. (*cinfo->master->prepare_for_pass) (cinfo);
  161222. /* Ready for application to drive first pass through jpeg_write_scanlines
  161223. * or jpeg_write_raw_data.
  161224. */
  161225. cinfo->next_scanline = 0;
  161226. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161227. }
  161228. /*
  161229. * Write some scanlines of data to the JPEG compressor.
  161230. *
  161231. * The return value will be the number of lines actually written.
  161232. * This should be less than the supplied num_lines only in case that
  161233. * the data destination module has requested suspension of the compressor,
  161234. * or if more than image_height scanlines are passed in.
  161235. *
  161236. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161237. * this likely signals an application programmer error. However,
  161238. * excess scanlines passed in the last valid call are *silently* ignored,
  161239. * so that the application need not adjust num_lines for end-of-image
  161240. * when using a multiple-scanline buffer.
  161241. */
  161242. GLOBAL(JDIMENSION)
  161243. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161244. JDIMENSION num_lines)
  161245. {
  161246. JDIMENSION row_ctr, rows_left;
  161247. if (cinfo->global_state != CSTATE_SCANNING)
  161248. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161249. if (cinfo->next_scanline >= cinfo->image_height)
  161250. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161251. /* Call progress monitor hook if present */
  161252. if (cinfo->progress != NULL) {
  161253. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161254. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161255. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161256. }
  161257. /* Give master control module another chance if this is first call to
  161258. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161259. * delayed so that application can write COM, etc, markers between
  161260. * jpeg_start_compress and jpeg_write_scanlines.
  161261. */
  161262. if (cinfo->master->call_pass_startup)
  161263. (*cinfo->master->pass_startup) (cinfo);
  161264. /* Ignore any extra scanlines at bottom of image. */
  161265. rows_left = cinfo->image_height - cinfo->next_scanline;
  161266. if (num_lines > rows_left)
  161267. num_lines = rows_left;
  161268. row_ctr = 0;
  161269. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161270. cinfo->next_scanline += row_ctr;
  161271. return row_ctr;
  161272. }
  161273. /*
  161274. * Alternate entry point to write raw data.
  161275. * Processes exactly one iMCU row per call, unless suspended.
  161276. */
  161277. GLOBAL(JDIMENSION)
  161278. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  161279. JDIMENSION num_lines)
  161280. {
  161281. JDIMENSION lines_per_iMCU_row;
  161282. if (cinfo->global_state != CSTATE_RAW_OK)
  161283. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161284. if (cinfo->next_scanline >= cinfo->image_height) {
  161285. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161286. return 0;
  161287. }
  161288. /* Call progress monitor hook if present */
  161289. if (cinfo->progress != NULL) {
  161290. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161291. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161292. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161293. }
  161294. /* Give master control module another chance if this is first call to
  161295. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  161296. * delayed so that application can write COM, etc, markers between
  161297. * jpeg_start_compress and jpeg_write_raw_data.
  161298. */
  161299. if (cinfo->master->call_pass_startup)
  161300. (*cinfo->master->pass_startup) (cinfo);
  161301. /* Verify that at least one iMCU row has been passed. */
  161302. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  161303. if (num_lines < lines_per_iMCU_row)
  161304. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161305. /* Directly compress the row. */
  161306. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161307. /* If compressor did not consume the whole row, suspend processing. */
  161308. return 0;
  161309. }
  161310. /* OK, we processed one iMCU row. */
  161311. cinfo->next_scanline += lines_per_iMCU_row;
  161312. return lines_per_iMCU_row;
  161313. }
  161314. /*** End of inlined file: jcapistd.c ***/
  161315. /*** Start of inlined file: jccoefct.c ***/
  161316. #define JPEG_INTERNALS
  161317. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161318. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161319. * step is run during the first pass, and subsequent passes need only read
  161320. * the buffered coefficients.
  161321. */
  161322. #ifdef ENTROPY_OPT_SUPPORTED
  161323. #define FULL_COEF_BUFFER_SUPPORTED
  161324. #else
  161325. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161326. #define FULL_COEF_BUFFER_SUPPORTED
  161327. #endif
  161328. #endif
  161329. /* Private buffer controller object */
  161330. typedef struct {
  161331. struct jpeg_c_coef_controller pub; /* public fields */
  161332. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161333. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161334. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161335. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161336. /* For single-pass compression, it's sufficient to buffer just one MCU
  161337. * (although this may prove a bit slow in practice). We allocate a
  161338. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161339. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161340. * it's not really very big; this is to keep the module interfaces unchanged
  161341. * when a large coefficient buffer is necessary.)
  161342. * In multi-pass modes, this array points to the current MCU's blocks
  161343. * within the virtual arrays.
  161344. */
  161345. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161346. /* In multi-pass modes, we need a virtual block array for each component. */
  161347. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161348. } my_coef_controller;
  161349. typedef my_coef_controller * my_coef_ptr;
  161350. /* Forward declarations */
  161351. METHODDEF(boolean) compress_data
  161352. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161353. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161354. METHODDEF(boolean) compress_first_pass
  161355. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161356. METHODDEF(boolean) compress_output
  161357. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161358. #endif
  161359. LOCAL(void)
  161360. start_iMCU_row (j_compress_ptr cinfo)
  161361. /* Reset within-iMCU-row counters for a new row */
  161362. {
  161363. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161364. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161365. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161366. * But at the bottom of the image, process only what's left.
  161367. */
  161368. if (cinfo->comps_in_scan > 1) {
  161369. coef->MCU_rows_per_iMCU_row = 1;
  161370. } else {
  161371. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161372. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161373. else
  161374. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161375. }
  161376. coef->mcu_ctr = 0;
  161377. coef->MCU_vert_offset = 0;
  161378. }
  161379. /*
  161380. * Initialize for a processing pass.
  161381. */
  161382. METHODDEF(void)
  161383. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161384. {
  161385. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161386. coef->iMCU_row_num = 0;
  161387. start_iMCU_row(cinfo);
  161388. switch (pass_mode) {
  161389. case JBUF_PASS_THRU:
  161390. if (coef->whole_image[0] != NULL)
  161391. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161392. coef->pub.compress_data = compress_data;
  161393. break;
  161394. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161395. case JBUF_SAVE_AND_PASS:
  161396. if (coef->whole_image[0] == NULL)
  161397. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161398. coef->pub.compress_data = compress_first_pass;
  161399. break;
  161400. case JBUF_CRANK_DEST:
  161401. if (coef->whole_image[0] == NULL)
  161402. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161403. coef->pub.compress_data = compress_output;
  161404. break;
  161405. #endif
  161406. default:
  161407. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161408. break;
  161409. }
  161410. }
  161411. /*
  161412. * Process some data in the single-pass case.
  161413. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161414. * per call, ie, v_samp_factor block rows for each component in the image.
  161415. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161416. *
  161417. * NB: input_buf contains a plane for each component in image,
  161418. * which we index according to the component's SOF position.
  161419. */
  161420. METHODDEF(boolean)
  161421. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161422. {
  161423. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161424. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161425. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161426. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161427. int blkn, bi, ci, yindex, yoffset, blockcnt;
  161428. JDIMENSION ypos, xpos;
  161429. jpeg_component_info *compptr;
  161430. /* Loop to write as much as one whole iMCU row */
  161431. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161432. yoffset++) {
  161433. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  161434. MCU_col_num++) {
  161435. /* Determine where data comes from in input_buf and do the DCT thing.
  161436. * Each call on forward_DCT processes a horizontal row of DCT blocks
  161437. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  161438. * sequentially. Dummy blocks at the right or bottom edge are filled in
  161439. * specially. The data in them does not matter for image reconstruction,
  161440. * so we fill them with values that will encode to the smallest amount of
  161441. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  161442. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  161443. */
  161444. blkn = 0;
  161445. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161446. compptr = cinfo->cur_comp_info[ci];
  161447. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161448. : compptr->last_col_width;
  161449. xpos = MCU_col_num * compptr->MCU_sample_width;
  161450. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  161451. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161452. if (coef->iMCU_row_num < last_iMCU_row ||
  161453. yoffset+yindex < compptr->last_row_height) {
  161454. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161455. input_buf[compptr->component_index],
  161456. coef->MCU_buffer[blkn],
  161457. ypos, xpos, (JDIMENSION) blockcnt);
  161458. if (blockcnt < compptr->MCU_width) {
  161459. /* Create some dummy blocks at the right edge of the image. */
  161460. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  161461. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  161462. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  161463. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  161464. }
  161465. }
  161466. } else {
  161467. /* Create a row of dummy blocks at the bottom of the image. */
  161468. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  161469. compptr->MCU_width * SIZEOF(JBLOCK));
  161470. for (bi = 0; bi < compptr->MCU_width; bi++) {
  161471. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  161472. }
  161473. }
  161474. blkn += compptr->MCU_width;
  161475. ypos += DCTSIZE;
  161476. }
  161477. }
  161478. /* Try to write the MCU. In event of a suspension failure, we will
  161479. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  161480. */
  161481. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161482. /* Suspension forced; update state counters and exit */
  161483. coef->MCU_vert_offset = yoffset;
  161484. coef->mcu_ctr = MCU_col_num;
  161485. return FALSE;
  161486. }
  161487. }
  161488. /* Completed an MCU row, but perhaps not an iMCU row */
  161489. coef->mcu_ctr = 0;
  161490. }
  161491. /* Completed the iMCU row, advance counters for next one */
  161492. coef->iMCU_row_num++;
  161493. start_iMCU_row(cinfo);
  161494. return TRUE;
  161495. }
  161496. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161497. /*
  161498. * Process some data in the first pass of a multi-pass case.
  161499. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161500. * per call, ie, v_samp_factor block rows for each component in the image.
  161501. * This amount of data is read from the source buffer, DCT'd and quantized,
  161502. * and saved into the virtual arrays. We also generate suitable dummy blocks
  161503. * as needed at the right and lower edges. (The dummy blocks are constructed
  161504. * in the virtual arrays, which have been padded appropriately.) This makes
  161505. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  161506. *
  161507. * We must also emit the data to the entropy encoder. This is conveniently
  161508. * done by calling compress_output() after we've loaded the current strip
  161509. * of the virtual arrays.
  161510. *
  161511. * NB: input_buf contains a plane for each component in image. All
  161512. * components are DCT'd and loaded into the virtual arrays in this pass.
  161513. * However, it may be that only a subset of the components are emitted to
  161514. * the entropy encoder during this first pass; be careful about looking
  161515. * at the scan-dependent variables (MCU dimensions, etc).
  161516. */
  161517. METHODDEF(boolean)
  161518. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161519. {
  161520. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161521. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161522. JDIMENSION blocks_across, MCUs_across, MCUindex;
  161523. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  161524. JCOEF lastDC;
  161525. jpeg_component_info *compptr;
  161526. JBLOCKARRAY buffer;
  161527. JBLOCKROW thisblockrow, lastblockrow;
  161528. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161529. ci++, compptr++) {
  161530. /* Align the virtual buffer for this component. */
  161531. buffer = (*cinfo->mem->access_virt_barray)
  161532. ((j_common_ptr) cinfo, coef->whole_image[ci],
  161533. coef->iMCU_row_num * compptr->v_samp_factor,
  161534. (JDIMENSION) compptr->v_samp_factor, TRUE);
  161535. /* Count non-dummy DCT block rows in this iMCU row. */
  161536. if (coef->iMCU_row_num < last_iMCU_row)
  161537. block_rows = compptr->v_samp_factor;
  161538. else {
  161539. /* NB: can't use last_row_height here, since may not be set! */
  161540. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  161541. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  161542. }
  161543. blocks_across = compptr->width_in_blocks;
  161544. h_samp_factor = compptr->h_samp_factor;
  161545. /* Count number of dummy blocks to be added at the right margin. */
  161546. ndummy = (int) (blocks_across % h_samp_factor);
  161547. if (ndummy > 0)
  161548. ndummy = h_samp_factor - ndummy;
  161549. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  161550. * on forward_DCT processes a complete horizontal row of DCT blocks.
  161551. */
  161552. for (block_row = 0; block_row < block_rows; block_row++) {
  161553. thisblockrow = buffer[block_row];
  161554. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161555. input_buf[ci], thisblockrow,
  161556. (JDIMENSION) (block_row * DCTSIZE),
  161557. (JDIMENSION) 0, blocks_across);
  161558. if (ndummy > 0) {
  161559. /* Create dummy blocks at the right edge of the image. */
  161560. thisblockrow += blocks_across; /* => first dummy block */
  161561. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  161562. lastDC = thisblockrow[-1][0];
  161563. for (bi = 0; bi < ndummy; bi++) {
  161564. thisblockrow[bi][0] = lastDC;
  161565. }
  161566. }
  161567. }
  161568. /* If at end of image, create dummy block rows as needed.
  161569. * The tricky part here is that within each MCU, we want the DC values
  161570. * of the dummy blocks to match the last real block's DC value.
  161571. * This squeezes a few more bytes out of the resulting file...
  161572. */
  161573. if (coef->iMCU_row_num == last_iMCU_row) {
  161574. blocks_across += ndummy; /* include lower right corner */
  161575. MCUs_across = blocks_across / h_samp_factor;
  161576. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  161577. block_row++) {
  161578. thisblockrow = buffer[block_row];
  161579. lastblockrow = buffer[block_row-1];
  161580. jzero_far((void FAR *) thisblockrow,
  161581. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  161582. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  161583. lastDC = lastblockrow[h_samp_factor-1][0];
  161584. for (bi = 0; bi < h_samp_factor; bi++) {
  161585. thisblockrow[bi][0] = lastDC;
  161586. }
  161587. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  161588. lastblockrow += h_samp_factor;
  161589. }
  161590. }
  161591. }
  161592. }
  161593. /* NB: compress_output will increment iMCU_row_num if successful.
  161594. * A suspension return will result in redoing all the work above next time.
  161595. */
  161596. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  161597. return compress_output(cinfo, input_buf);
  161598. }
  161599. /*
  161600. * Process some data in subsequent passes of a multi-pass case.
  161601. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161602. * per call, ie, v_samp_factor block rows for each component in the scan.
  161603. * The data is obtained from the virtual arrays and fed to the entropy coder.
  161604. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161605. *
  161606. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  161607. */
  161608. METHODDEF(boolean)
  161609. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  161610. {
  161611. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161612. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161613. int blkn, ci, xindex, yindex, yoffset;
  161614. JDIMENSION start_col;
  161615. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  161616. JBLOCKROW buffer_ptr;
  161617. jpeg_component_info *compptr;
  161618. /* Align the virtual buffers for the components used in this scan.
  161619. * NB: during first pass, this is safe only because the buffers will
  161620. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  161621. */
  161622. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161623. compptr = cinfo->cur_comp_info[ci];
  161624. buffer[ci] = (*cinfo->mem->access_virt_barray)
  161625. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  161626. coef->iMCU_row_num * compptr->v_samp_factor,
  161627. (JDIMENSION) compptr->v_samp_factor, FALSE);
  161628. }
  161629. /* Loop to process one whole iMCU row */
  161630. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161631. yoffset++) {
  161632. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  161633. MCU_col_num++) {
  161634. /* Construct list of pointers to DCT blocks belonging to this MCU */
  161635. blkn = 0; /* index of current DCT block within MCU */
  161636. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161637. compptr = cinfo->cur_comp_info[ci];
  161638. start_col = MCU_col_num * compptr->MCU_width;
  161639. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161640. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  161641. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  161642. coef->MCU_buffer[blkn++] = buffer_ptr++;
  161643. }
  161644. }
  161645. }
  161646. /* Try to write the MCU. */
  161647. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161648. /* Suspension forced; update state counters and exit */
  161649. coef->MCU_vert_offset = yoffset;
  161650. coef->mcu_ctr = MCU_col_num;
  161651. return FALSE;
  161652. }
  161653. }
  161654. /* Completed an MCU row, but perhaps not an iMCU row */
  161655. coef->mcu_ctr = 0;
  161656. }
  161657. /* Completed the iMCU row, advance counters for next one */
  161658. coef->iMCU_row_num++;
  161659. start_iMCU_row(cinfo);
  161660. return TRUE;
  161661. }
  161662. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  161663. /*
  161664. * Initialize coefficient buffer controller.
  161665. */
  161666. GLOBAL(void)
  161667. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  161668. {
  161669. my_coef_ptr coef;
  161670. coef = (my_coef_ptr)
  161671. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161672. SIZEOF(my_coef_controller));
  161673. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  161674. coef->pub.start_pass = start_pass_coef;
  161675. /* Create the coefficient buffer. */
  161676. if (need_full_buffer) {
  161677. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161678. /* Allocate a full-image virtual array for each component, */
  161679. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  161680. int ci;
  161681. jpeg_component_info *compptr;
  161682. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161683. ci++, compptr++) {
  161684. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  161685. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  161686. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  161687. (long) compptr->h_samp_factor),
  161688. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  161689. (long) compptr->v_samp_factor),
  161690. (JDIMENSION) compptr->v_samp_factor);
  161691. }
  161692. #else
  161693. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161694. #endif
  161695. } else {
  161696. /* We only need a single-MCU buffer. */
  161697. JBLOCKROW buffer;
  161698. int i;
  161699. buffer = (JBLOCKROW)
  161700. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161701. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  161702. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  161703. coef->MCU_buffer[i] = buffer + i;
  161704. }
  161705. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  161706. }
  161707. }
  161708. /*** End of inlined file: jccoefct.c ***/
  161709. /*** Start of inlined file: jccolor.c ***/
  161710. #define JPEG_INTERNALS
  161711. /* Private subobject */
  161712. typedef struct {
  161713. struct jpeg_color_converter pub; /* public fields */
  161714. /* Private state for RGB->YCC conversion */
  161715. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  161716. } my_color_converter;
  161717. typedef my_color_converter * my_cconvert_ptr;
  161718. /**************** RGB -> YCbCr conversion: most common case **************/
  161719. /*
  161720. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  161721. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  161722. * The conversion equations to be implemented are therefore
  161723. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  161724. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  161725. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  161726. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  161727. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  161728. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  161729. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  161730. * were not represented exactly. Now we sacrifice exact representation of
  161731. * maximum red and maximum blue in order to get exact grayscales.
  161732. *
  161733. * To avoid floating-point arithmetic, we represent the fractional constants
  161734. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  161735. * the products by 2^16, with appropriate rounding, to get the correct answer.
  161736. *
  161737. * For even more speed, we avoid doing any multiplications in the inner loop
  161738. * by precalculating the constants times R,G,B for all possible values.
  161739. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  161740. * for 12-bit samples it is still acceptable. It's not very reasonable for
  161741. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  161742. * colorspace anyway.
  161743. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  161744. * in the tables to save adding them separately in the inner loop.
  161745. */
  161746. #define SCALEBITS 16 /* speediest right-shift on some machines */
  161747. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  161748. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  161749. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  161750. /* We allocate one big table and divide it up into eight parts, instead of
  161751. * doing eight alloc_small requests. This lets us use a single table base
  161752. * address, which can be held in a register in the inner loops on many
  161753. * machines (more than can hold all eight addresses, anyway).
  161754. */
  161755. #define R_Y_OFF 0 /* offset to R => Y section */
  161756. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  161757. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  161758. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  161759. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  161760. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  161761. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  161762. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  161763. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  161764. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  161765. /*
  161766. * Initialize for RGB->YCC colorspace conversion.
  161767. */
  161768. METHODDEF(void)
  161769. rgb_ycc_start (j_compress_ptr cinfo)
  161770. {
  161771. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161772. INT32 * rgb_ycc_tab;
  161773. INT32 i;
  161774. /* Allocate and fill in the conversion tables. */
  161775. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  161776. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161777. (TABLE_SIZE * SIZEOF(INT32)));
  161778. for (i = 0; i <= MAXJSAMPLE; i++) {
  161779. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  161780. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  161781. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  161782. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  161783. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  161784. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  161785. * This ensures that the maximum output will round to MAXJSAMPLE
  161786. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  161787. */
  161788. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  161789. /* B=>Cb and R=>Cr tables are the same
  161790. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  161791. */
  161792. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  161793. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  161794. }
  161795. }
  161796. /*
  161797. * Convert some rows of samples to the JPEG colorspace.
  161798. *
  161799. * Note that we change from the application's interleaved-pixel format
  161800. * to our internal noninterleaved, one-plane-per-component format.
  161801. * The input buffer is therefore three times as wide as the output buffer.
  161802. *
  161803. * A starting row offset is provided only for the output buffer. The caller
  161804. * can easily adjust the passed input_buf value to accommodate any row
  161805. * offset required on that side.
  161806. */
  161807. METHODDEF(void)
  161808. rgb_ycc_convert (j_compress_ptr cinfo,
  161809. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161810. JDIMENSION output_row, int num_rows)
  161811. {
  161812. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161813. register int r, g, b;
  161814. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161815. register JSAMPROW inptr;
  161816. register JSAMPROW outptr0, outptr1, outptr2;
  161817. register JDIMENSION col;
  161818. JDIMENSION num_cols = cinfo->image_width;
  161819. while (--num_rows >= 0) {
  161820. inptr = *input_buf++;
  161821. outptr0 = output_buf[0][output_row];
  161822. outptr1 = output_buf[1][output_row];
  161823. outptr2 = output_buf[2][output_row];
  161824. output_row++;
  161825. for (col = 0; col < num_cols; col++) {
  161826. r = GETJSAMPLE(inptr[RGB_RED]);
  161827. g = GETJSAMPLE(inptr[RGB_GREEN]);
  161828. b = GETJSAMPLE(inptr[RGB_BLUE]);
  161829. inptr += RGB_PIXELSIZE;
  161830. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  161831. * must be too; we do not need an explicit range-limiting operation.
  161832. * Hence the value being shifted is never negative, and we don't
  161833. * need the general RIGHT_SHIFT macro.
  161834. */
  161835. /* Y */
  161836. outptr0[col] = (JSAMPLE)
  161837. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161838. >> SCALEBITS);
  161839. /* Cb */
  161840. outptr1[col] = (JSAMPLE)
  161841. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  161842. >> SCALEBITS);
  161843. /* Cr */
  161844. outptr2[col] = (JSAMPLE)
  161845. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  161846. >> SCALEBITS);
  161847. }
  161848. }
  161849. }
  161850. /**************** Cases other than RGB -> YCbCr **************/
  161851. /*
  161852. * Convert some rows of samples to the JPEG colorspace.
  161853. * This version handles RGB->grayscale conversion, which is the same
  161854. * as the RGB->Y portion of RGB->YCbCr.
  161855. * We assume rgb_ycc_start has been called (we only use the Y tables).
  161856. */
  161857. METHODDEF(void)
  161858. rgb_gray_convert (j_compress_ptr cinfo,
  161859. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161860. JDIMENSION output_row, int num_rows)
  161861. {
  161862. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161863. register int r, g, b;
  161864. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161865. register JSAMPROW inptr;
  161866. register JSAMPROW outptr;
  161867. register JDIMENSION col;
  161868. JDIMENSION num_cols = cinfo->image_width;
  161869. while (--num_rows >= 0) {
  161870. inptr = *input_buf++;
  161871. outptr = output_buf[0][output_row];
  161872. output_row++;
  161873. for (col = 0; col < num_cols; col++) {
  161874. r = GETJSAMPLE(inptr[RGB_RED]);
  161875. g = GETJSAMPLE(inptr[RGB_GREEN]);
  161876. b = GETJSAMPLE(inptr[RGB_BLUE]);
  161877. inptr += RGB_PIXELSIZE;
  161878. /* Y */
  161879. outptr[col] = (JSAMPLE)
  161880. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161881. >> SCALEBITS);
  161882. }
  161883. }
  161884. }
  161885. /*
  161886. * Convert some rows of samples to the JPEG colorspace.
  161887. * This version handles Adobe-style CMYK->YCCK conversion,
  161888. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  161889. * conversion as above, while passing K (black) unchanged.
  161890. * We assume rgb_ycc_start has been called.
  161891. */
  161892. METHODDEF(void)
  161893. cmyk_ycck_convert (j_compress_ptr cinfo,
  161894. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161895. JDIMENSION output_row, int num_rows)
  161896. {
  161897. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161898. register int r, g, b;
  161899. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161900. register JSAMPROW inptr;
  161901. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  161902. register JDIMENSION col;
  161903. JDIMENSION num_cols = cinfo->image_width;
  161904. while (--num_rows >= 0) {
  161905. inptr = *input_buf++;
  161906. outptr0 = output_buf[0][output_row];
  161907. outptr1 = output_buf[1][output_row];
  161908. outptr2 = output_buf[2][output_row];
  161909. outptr3 = output_buf[3][output_row];
  161910. output_row++;
  161911. for (col = 0; col < num_cols; col++) {
  161912. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  161913. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  161914. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  161915. /* K passes through as-is */
  161916. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  161917. inptr += 4;
  161918. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  161919. * must be too; we do not need an explicit range-limiting operation.
  161920. * Hence the value being shifted is never negative, and we don't
  161921. * need the general RIGHT_SHIFT macro.
  161922. */
  161923. /* Y */
  161924. outptr0[col] = (JSAMPLE)
  161925. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161926. >> SCALEBITS);
  161927. /* Cb */
  161928. outptr1[col] = (JSAMPLE)
  161929. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  161930. >> SCALEBITS);
  161931. /* Cr */
  161932. outptr2[col] = (JSAMPLE)
  161933. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  161934. >> SCALEBITS);
  161935. }
  161936. }
  161937. }
  161938. /*
  161939. * Convert some rows of samples to the JPEG colorspace.
  161940. * This version handles grayscale output with no conversion.
  161941. * The source can be either plain grayscale or YCbCr (since Y == gray).
  161942. */
  161943. METHODDEF(void)
  161944. grayscale_convert (j_compress_ptr cinfo,
  161945. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161946. JDIMENSION output_row, int num_rows)
  161947. {
  161948. register JSAMPROW inptr;
  161949. register JSAMPROW outptr;
  161950. register JDIMENSION col;
  161951. JDIMENSION num_cols = cinfo->image_width;
  161952. int instride = cinfo->input_components;
  161953. while (--num_rows >= 0) {
  161954. inptr = *input_buf++;
  161955. outptr = output_buf[0][output_row];
  161956. output_row++;
  161957. for (col = 0; col < num_cols; col++) {
  161958. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  161959. inptr += instride;
  161960. }
  161961. }
  161962. }
  161963. /*
  161964. * Convert some rows of samples to the JPEG colorspace.
  161965. * This version handles multi-component colorspaces without conversion.
  161966. * We assume input_components == num_components.
  161967. */
  161968. METHODDEF(void)
  161969. null_convert (j_compress_ptr cinfo,
  161970. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161971. JDIMENSION output_row, int num_rows)
  161972. {
  161973. register JSAMPROW inptr;
  161974. register JSAMPROW outptr;
  161975. register JDIMENSION col;
  161976. register int ci;
  161977. int nc = cinfo->num_components;
  161978. JDIMENSION num_cols = cinfo->image_width;
  161979. while (--num_rows >= 0) {
  161980. /* It seems fastest to make a separate pass for each component. */
  161981. for (ci = 0; ci < nc; ci++) {
  161982. inptr = *input_buf;
  161983. outptr = output_buf[ci][output_row];
  161984. for (col = 0; col < num_cols; col++) {
  161985. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  161986. inptr += nc;
  161987. }
  161988. }
  161989. input_buf++;
  161990. output_row++;
  161991. }
  161992. }
  161993. /*
  161994. * Empty method for start_pass.
  161995. */
  161996. METHODDEF(void)
  161997. null_method (j_compress_ptr)
  161998. {
  161999. /* no work needed */
  162000. }
  162001. /*
  162002. * Module initialization routine for input colorspace conversion.
  162003. */
  162004. GLOBAL(void)
  162005. jinit_color_converter (j_compress_ptr cinfo)
  162006. {
  162007. my_cconvert_ptr cconvert;
  162008. cconvert = (my_cconvert_ptr)
  162009. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162010. SIZEOF(my_color_converter));
  162011. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162012. /* set start_pass to null method until we find out differently */
  162013. cconvert->pub.start_pass = null_method;
  162014. /* Make sure input_components agrees with in_color_space */
  162015. switch (cinfo->in_color_space) {
  162016. case JCS_GRAYSCALE:
  162017. if (cinfo->input_components != 1)
  162018. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162019. break;
  162020. case JCS_RGB:
  162021. #if RGB_PIXELSIZE != 3
  162022. if (cinfo->input_components != RGB_PIXELSIZE)
  162023. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162024. break;
  162025. #endif /* else share code with YCbCr */
  162026. case JCS_YCbCr:
  162027. if (cinfo->input_components != 3)
  162028. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162029. break;
  162030. case JCS_CMYK:
  162031. case JCS_YCCK:
  162032. if (cinfo->input_components != 4)
  162033. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162034. break;
  162035. default: /* JCS_UNKNOWN can be anything */
  162036. if (cinfo->input_components < 1)
  162037. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162038. break;
  162039. }
  162040. /* Check num_components, set conversion method based on requested space */
  162041. switch (cinfo->jpeg_color_space) {
  162042. case JCS_GRAYSCALE:
  162043. if (cinfo->num_components != 1)
  162044. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162045. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162046. cconvert->pub.color_convert = grayscale_convert;
  162047. else if (cinfo->in_color_space == JCS_RGB) {
  162048. cconvert->pub.start_pass = rgb_ycc_start;
  162049. cconvert->pub.color_convert = rgb_gray_convert;
  162050. } else if (cinfo->in_color_space == JCS_YCbCr)
  162051. cconvert->pub.color_convert = grayscale_convert;
  162052. else
  162053. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162054. break;
  162055. case JCS_RGB:
  162056. if (cinfo->num_components != 3)
  162057. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162058. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162059. cconvert->pub.color_convert = null_convert;
  162060. else
  162061. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162062. break;
  162063. case JCS_YCbCr:
  162064. if (cinfo->num_components != 3)
  162065. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162066. if (cinfo->in_color_space == JCS_RGB) {
  162067. cconvert->pub.start_pass = rgb_ycc_start;
  162068. cconvert->pub.color_convert = rgb_ycc_convert;
  162069. } else if (cinfo->in_color_space == JCS_YCbCr)
  162070. cconvert->pub.color_convert = null_convert;
  162071. else
  162072. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162073. break;
  162074. case JCS_CMYK:
  162075. if (cinfo->num_components != 4)
  162076. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162077. if (cinfo->in_color_space == JCS_CMYK)
  162078. cconvert->pub.color_convert = null_convert;
  162079. else
  162080. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162081. break;
  162082. case JCS_YCCK:
  162083. if (cinfo->num_components != 4)
  162084. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162085. if (cinfo->in_color_space == JCS_CMYK) {
  162086. cconvert->pub.start_pass = rgb_ycc_start;
  162087. cconvert->pub.color_convert = cmyk_ycck_convert;
  162088. } else if (cinfo->in_color_space == JCS_YCCK)
  162089. cconvert->pub.color_convert = null_convert;
  162090. else
  162091. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162092. break;
  162093. default: /* allow null conversion of JCS_UNKNOWN */
  162094. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162095. cinfo->num_components != cinfo->input_components)
  162096. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162097. cconvert->pub.color_convert = null_convert;
  162098. break;
  162099. }
  162100. }
  162101. /*** End of inlined file: jccolor.c ***/
  162102. #undef FIX
  162103. /*** Start of inlined file: jcdctmgr.c ***/
  162104. #define JPEG_INTERNALS
  162105. /*** Start of inlined file: jdct.h ***/
  162106. /*
  162107. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162108. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162109. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162110. * implementations use an array of type FAST_FLOAT, instead.)
  162111. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162112. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162113. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162114. * convention improves accuracy in integer implementations and saves some
  162115. * work in floating-point ones.
  162116. * Quantization of the output coefficients is done by jcdctmgr.c.
  162117. */
  162118. #ifndef __jdct_h__
  162119. #define __jdct_h__
  162120. #if BITS_IN_JSAMPLE == 8
  162121. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162122. #else
  162123. typedef INT32 DCTELEM; /* must have 32 bits */
  162124. #endif
  162125. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162126. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162127. /*
  162128. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162129. * to an output sample array. The routine must dequantize the input data as
  162130. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162131. * pointed to by compptr->dct_table. The output data is to be placed into the
  162132. * sample array starting at a specified column. (Any row offset needed will
  162133. * be applied to the array pointer before it is passed to the IDCT code.)
  162134. * Note that the number of samples emitted by the IDCT routine is
  162135. * DCT_scaled_size * DCT_scaled_size.
  162136. */
  162137. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162138. /*
  162139. * Each IDCT routine has its own ideas about the best dct_table element type.
  162140. */
  162141. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162142. #if BITS_IN_JSAMPLE == 8
  162143. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162144. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162145. #else
  162146. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162147. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162148. #endif
  162149. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162150. /*
  162151. * Each IDCT routine is responsible for range-limiting its results and
  162152. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162153. * be quite far out of range if the input data is corrupt, so a bulletproof
  162154. * range-limiting step is required. We use a mask-and-table-lookup method
  162155. * to do the combined operations quickly. See the comments with
  162156. * prepare_range_limit_table (in jdmaster.c) for more info.
  162157. */
  162158. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162159. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162160. /* Short forms of external names for systems with brain-damaged linkers. */
  162161. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162162. #define jpeg_fdct_islow jFDislow
  162163. #define jpeg_fdct_ifast jFDifast
  162164. #define jpeg_fdct_float jFDfloat
  162165. #define jpeg_idct_islow jRDislow
  162166. #define jpeg_idct_ifast jRDifast
  162167. #define jpeg_idct_float jRDfloat
  162168. #define jpeg_idct_4x4 jRD4x4
  162169. #define jpeg_idct_2x2 jRD2x2
  162170. #define jpeg_idct_1x1 jRD1x1
  162171. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162172. /* Extern declarations for the forward and inverse DCT routines. */
  162173. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162174. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162175. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162176. EXTERN(void) jpeg_idct_islow
  162177. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162178. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162179. EXTERN(void) jpeg_idct_ifast
  162180. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162181. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162182. EXTERN(void) jpeg_idct_float
  162183. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162184. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162185. EXTERN(void) jpeg_idct_4x4
  162186. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162187. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162188. EXTERN(void) jpeg_idct_2x2
  162189. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162190. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162191. EXTERN(void) jpeg_idct_1x1
  162192. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162193. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162194. /*
  162195. * Macros for handling fixed-point arithmetic; these are used by many
  162196. * but not all of the DCT/IDCT modules.
  162197. *
  162198. * All values are expected to be of type INT32.
  162199. * Fractional constants are scaled left by CONST_BITS bits.
  162200. * CONST_BITS is defined within each module using these macros,
  162201. * and may differ from one module to the next.
  162202. */
  162203. #define ONE ((INT32) 1)
  162204. #define CONST_SCALE (ONE << CONST_BITS)
  162205. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162206. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162207. * thus causing a lot of useless floating-point operations at run time.
  162208. */
  162209. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162210. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162211. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162212. * the fudge factor is correct for either sign of X.
  162213. */
  162214. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162215. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162216. * This macro is used only when the two inputs will actually be no more than
  162217. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162218. * full 32x32 multiply. This provides a useful speedup on many machines.
  162219. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162220. * in C, but some C compilers will do the right thing if you provide the
  162221. * correct combination of casts.
  162222. */
  162223. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162224. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162225. #endif
  162226. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162227. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162228. #endif
  162229. #ifndef MULTIPLY16C16 /* default definition */
  162230. #define MULTIPLY16C16(var,const) ((var) * (const))
  162231. #endif
  162232. /* Same except both inputs are variables. */
  162233. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162234. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162235. #endif
  162236. #ifndef MULTIPLY16V16 /* default definition */
  162237. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162238. #endif
  162239. #endif
  162240. /*** End of inlined file: jdct.h ***/
  162241. /* Private declarations for DCT subsystem */
  162242. /* Private subobject for this module */
  162243. typedef struct {
  162244. struct jpeg_forward_dct pub; /* public fields */
  162245. /* Pointer to the DCT routine actually in use */
  162246. forward_DCT_method_ptr do_dct;
  162247. /* The actual post-DCT divisors --- not identical to the quant table
  162248. * entries, because of scaling (especially for an unnormalized DCT).
  162249. * Each table is given in normal array order.
  162250. */
  162251. DCTELEM * divisors[NUM_QUANT_TBLS];
  162252. #ifdef DCT_FLOAT_SUPPORTED
  162253. /* Same as above for the floating-point case. */
  162254. float_DCT_method_ptr do_float_dct;
  162255. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162256. #endif
  162257. } my_fdct_controller;
  162258. typedef my_fdct_controller * my_fdct_ptr;
  162259. /*
  162260. * Initialize for a processing pass.
  162261. * Verify that all referenced Q-tables are present, and set up
  162262. * the divisor table for each one.
  162263. * In the current implementation, DCT of all components is done during
  162264. * the first pass, even if only some components will be output in the
  162265. * first scan. Hence all components should be examined here.
  162266. */
  162267. METHODDEF(void)
  162268. start_pass_fdctmgr (j_compress_ptr cinfo)
  162269. {
  162270. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162271. int ci, qtblno, i;
  162272. jpeg_component_info *compptr;
  162273. JQUANT_TBL * qtbl;
  162274. DCTELEM * dtbl;
  162275. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162276. ci++, compptr++) {
  162277. qtblno = compptr->quant_tbl_no;
  162278. /* Make sure specified quantization table is present */
  162279. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  162280. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  162281. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  162282. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  162283. /* Compute divisors for this quant table */
  162284. /* We may do this more than once for same table, but it's not a big deal */
  162285. switch (cinfo->dct_method) {
  162286. #ifdef DCT_ISLOW_SUPPORTED
  162287. case JDCT_ISLOW:
  162288. /* For LL&M IDCT method, divisors are equal to raw quantization
  162289. * coefficients multiplied by 8 (to counteract scaling).
  162290. */
  162291. if (fdct->divisors[qtblno] == NULL) {
  162292. fdct->divisors[qtblno] = (DCTELEM *)
  162293. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162294. DCTSIZE2 * SIZEOF(DCTELEM));
  162295. }
  162296. dtbl = fdct->divisors[qtblno];
  162297. for (i = 0; i < DCTSIZE2; i++) {
  162298. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  162299. }
  162300. break;
  162301. #endif
  162302. #ifdef DCT_IFAST_SUPPORTED
  162303. case JDCT_IFAST:
  162304. {
  162305. /* For AA&N IDCT method, divisors are equal to quantization
  162306. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162307. * scalefactor[0] = 1
  162308. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162309. * We apply a further scale factor of 8.
  162310. */
  162311. #define CONST_BITS 14
  162312. static const INT16 aanscales[DCTSIZE2] = {
  162313. /* precomputed values scaled up by 14 bits */
  162314. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162315. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162316. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162317. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162318. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162319. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162320. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162321. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162322. };
  162323. SHIFT_TEMPS
  162324. if (fdct->divisors[qtblno] == NULL) {
  162325. fdct->divisors[qtblno] = (DCTELEM *)
  162326. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162327. DCTSIZE2 * SIZEOF(DCTELEM));
  162328. }
  162329. dtbl = fdct->divisors[qtblno];
  162330. for (i = 0; i < DCTSIZE2; i++) {
  162331. dtbl[i] = (DCTELEM)
  162332. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162333. (INT32) aanscales[i]),
  162334. CONST_BITS-3);
  162335. }
  162336. }
  162337. break;
  162338. #endif
  162339. #ifdef DCT_FLOAT_SUPPORTED
  162340. case JDCT_FLOAT:
  162341. {
  162342. /* For float AA&N IDCT method, divisors are equal to quantization
  162343. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162344. * scalefactor[0] = 1
  162345. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162346. * We apply a further scale factor of 8.
  162347. * What's actually stored is 1/divisor so that the inner loop can
  162348. * use a multiplication rather than a division.
  162349. */
  162350. FAST_FLOAT * fdtbl;
  162351. int row, col;
  162352. static const double aanscalefactor[DCTSIZE] = {
  162353. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162354. 1.0, 0.785694958, 0.541196100, 0.275899379
  162355. };
  162356. if (fdct->float_divisors[qtblno] == NULL) {
  162357. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162358. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162359. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162360. }
  162361. fdtbl = fdct->float_divisors[qtblno];
  162362. i = 0;
  162363. for (row = 0; row < DCTSIZE; row++) {
  162364. for (col = 0; col < DCTSIZE; col++) {
  162365. fdtbl[i] = (FAST_FLOAT)
  162366. (1.0 / (((double) qtbl->quantval[i] *
  162367. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162368. i++;
  162369. }
  162370. }
  162371. }
  162372. break;
  162373. #endif
  162374. default:
  162375. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162376. break;
  162377. }
  162378. }
  162379. }
  162380. /*
  162381. * Perform forward DCT on one or more blocks of a component.
  162382. *
  162383. * The input samples are taken from the sample_data[] array starting at
  162384. * position start_row/start_col, and moving to the right for any additional
  162385. * blocks. The quantized coefficients are returned in coef_blocks[].
  162386. */
  162387. METHODDEF(void)
  162388. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162389. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162390. JDIMENSION start_row, JDIMENSION start_col,
  162391. JDIMENSION num_blocks)
  162392. /* This version is used for integer DCT implementations. */
  162393. {
  162394. /* This routine is heavily used, so it's worth coding it tightly. */
  162395. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162396. forward_DCT_method_ptr do_dct = fdct->do_dct;
  162397. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  162398. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162399. JDIMENSION bi;
  162400. sample_data += start_row; /* fold in the vertical offset once */
  162401. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162402. /* Load data into workspace, applying unsigned->signed conversion */
  162403. { register DCTELEM *workspaceptr;
  162404. register JSAMPROW elemptr;
  162405. register int elemr;
  162406. workspaceptr = workspace;
  162407. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162408. elemptr = sample_data[elemr] + start_col;
  162409. #if DCTSIZE == 8 /* unroll the inner loop */
  162410. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162411. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162412. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162413. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162414. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162415. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162416. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162417. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162418. #else
  162419. { register int elemc;
  162420. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162421. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162422. }
  162423. }
  162424. #endif
  162425. }
  162426. }
  162427. /* Perform the DCT */
  162428. (*do_dct) (workspace);
  162429. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162430. { register DCTELEM temp, qval;
  162431. register int i;
  162432. register JCOEFPTR output_ptr = coef_blocks[bi];
  162433. for (i = 0; i < DCTSIZE2; i++) {
  162434. qval = divisors[i];
  162435. temp = workspace[i];
  162436. /* Divide the coefficient value by qval, ensuring proper rounding.
  162437. * Since C does not specify the direction of rounding for negative
  162438. * quotients, we have to force the dividend positive for portability.
  162439. *
  162440. * In most files, at least half of the output values will be zero
  162441. * (at default quantization settings, more like three-quarters...)
  162442. * so we should ensure that this case is fast. On many machines,
  162443. * a comparison is enough cheaper than a divide to make a special test
  162444. * a win. Since both inputs will be nonnegative, we need only test
  162445. * for a < b to discover whether a/b is 0.
  162446. * If your machine's division is fast enough, define FAST_DIVIDE.
  162447. */
  162448. #ifdef FAST_DIVIDE
  162449. #define DIVIDE_BY(a,b) a /= b
  162450. #else
  162451. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  162452. #endif
  162453. if (temp < 0) {
  162454. temp = -temp;
  162455. temp += qval>>1; /* for rounding */
  162456. DIVIDE_BY(temp, qval);
  162457. temp = -temp;
  162458. } else {
  162459. temp += qval>>1; /* for rounding */
  162460. DIVIDE_BY(temp, qval);
  162461. }
  162462. output_ptr[i] = (JCOEF) temp;
  162463. }
  162464. }
  162465. }
  162466. }
  162467. #ifdef DCT_FLOAT_SUPPORTED
  162468. METHODDEF(void)
  162469. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162470. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162471. JDIMENSION start_row, JDIMENSION start_col,
  162472. JDIMENSION num_blocks)
  162473. /* This version is used for floating-point DCT implementations. */
  162474. {
  162475. /* This routine is heavily used, so it's worth coding it tightly. */
  162476. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162477. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  162478. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  162479. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162480. JDIMENSION bi;
  162481. sample_data += start_row; /* fold in the vertical offset once */
  162482. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162483. /* Load data into workspace, applying unsigned->signed conversion */
  162484. { register FAST_FLOAT *workspaceptr;
  162485. register JSAMPROW elemptr;
  162486. register int elemr;
  162487. workspaceptr = workspace;
  162488. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162489. elemptr = sample_data[elemr] + start_col;
  162490. #if DCTSIZE == 8 /* unroll the inner loop */
  162491. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162492. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162493. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162494. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162495. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162496. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162497. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162498. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162499. #else
  162500. { register int elemc;
  162501. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162502. *workspaceptr++ = (FAST_FLOAT)
  162503. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162504. }
  162505. }
  162506. #endif
  162507. }
  162508. }
  162509. /* Perform the DCT */
  162510. (*do_dct) (workspace);
  162511. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162512. { register FAST_FLOAT temp;
  162513. register int i;
  162514. register JCOEFPTR output_ptr = coef_blocks[bi];
  162515. for (i = 0; i < DCTSIZE2; i++) {
  162516. /* Apply the quantization and scaling factor */
  162517. temp = workspace[i] * divisors[i];
  162518. /* Round to nearest integer.
  162519. * Since C does not specify the direction of rounding for negative
  162520. * quotients, we have to force the dividend positive for portability.
  162521. * The maximum coefficient size is +-16K (for 12-bit data), so this
  162522. * code should work for either 16-bit or 32-bit ints.
  162523. */
  162524. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  162525. }
  162526. }
  162527. }
  162528. }
  162529. #endif /* DCT_FLOAT_SUPPORTED */
  162530. /*
  162531. * Initialize FDCT manager.
  162532. */
  162533. GLOBAL(void)
  162534. jinit_forward_dct (j_compress_ptr cinfo)
  162535. {
  162536. my_fdct_ptr fdct;
  162537. int i;
  162538. fdct = (my_fdct_ptr)
  162539. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162540. SIZEOF(my_fdct_controller));
  162541. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  162542. fdct->pub.start_pass = start_pass_fdctmgr;
  162543. switch (cinfo->dct_method) {
  162544. #ifdef DCT_ISLOW_SUPPORTED
  162545. case JDCT_ISLOW:
  162546. fdct->pub.forward_DCT = forward_DCT;
  162547. fdct->do_dct = jpeg_fdct_islow;
  162548. break;
  162549. #endif
  162550. #ifdef DCT_IFAST_SUPPORTED
  162551. case JDCT_IFAST:
  162552. fdct->pub.forward_DCT = forward_DCT;
  162553. fdct->do_dct = jpeg_fdct_ifast;
  162554. break;
  162555. #endif
  162556. #ifdef DCT_FLOAT_SUPPORTED
  162557. case JDCT_FLOAT:
  162558. fdct->pub.forward_DCT = forward_DCT_float;
  162559. fdct->do_float_dct = jpeg_fdct_float;
  162560. break;
  162561. #endif
  162562. default:
  162563. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162564. break;
  162565. }
  162566. /* Mark divisor tables unallocated */
  162567. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  162568. fdct->divisors[i] = NULL;
  162569. #ifdef DCT_FLOAT_SUPPORTED
  162570. fdct->float_divisors[i] = NULL;
  162571. #endif
  162572. }
  162573. }
  162574. /*** End of inlined file: jcdctmgr.c ***/
  162575. #undef CONST_BITS
  162576. /*** Start of inlined file: jchuff.c ***/
  162577. #define JPEG_INTERNALS
  162578. /*** Start of inlined file: jchuff.h ***/
  162579. /* The legal range of a DCT coefficient is
  162580. * -1024 .. +1023 for 8-bit data;
  162581. * -16384 .. +16383 for 12-bit data.
  162582. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  162583. */
  162584. #ifndef _jchuff_h_
  162585. #define _jchuff_h_
  162586. #if BITS_IN_JSAMPLE == 8
  162587. #define MAX_COEF_BITS 10
  162588. #else
  162589. #define MAX_COEF_BITS 14
  162590. #endif
  162591. /* Derived data constructed for each Huffman table */
  162592. typedef struct {
  162593. unsigned int ehufco[256]; /* code for each symbol */
  162594. char ehufsi[256]; /* length of code for each symbol */
  162595. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  162596. } c_derived_tbl;
  162597. /* Short forms of external names for systems with brain-damaged linkers. */
  162598. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162599. #define jpeg_make_c_derived_tbl jMkCDerived
  162600. #define jpeg_gen_optimal_table jGenOptTbl
  162601. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162602. /* Expand a Huffman table definition into the derived format */
  162603. EXTERN(void) jpeg_make_c_derived_tbl
  162604. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  162605. c_derived_tbl ** pdtbl));
  162606. /* Generate an optimal table definition given the specified counts */
  162607. EXTERN(void) jpeg_gen_optimal_table
  162608. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  162609. #endif
  162610. /*** End of inlined file: jchuff.h ***/
  162611. /* Declarations shared with jcphuff.c */
  162612. /* Expanded entropy encoder object for Huffman encoding.
  162613. *
  162614. * The savable_state subrecord contains fields that change within an MCU,
  162615. * but must not be updated permanently until we complete the MCU.
  162616. */
  162617. typedef struct {
  162618. INT32 put_buffer; /* current bit-accumulation buffer */
  162619. int put_bits; /* # of bits now in it */
  162620. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  162621. } savable_state;
  162622. /* This macro is to work around compilers with missing or broken
  162623. * structure assignment. You'll need to fix this code if you have
  162624. * such a compiler and you change MAX_COMPS_IN_SCAN.
  162625. */
  162626. #ifndef NO_STRUCT_ASSIGN
  162627. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  162628. #else
  162629. #if MAX_COMPS_IN_SCAN == 4
  162630. #define ASSIGN_STATE(dest,src) \
  162631. ((dest).put_buffer = (src).put_buffer, \
  162632. (dest).put_bits = (src).put_bits, \
  162633. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  162634. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  162635. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  162636. (dest).last_dc_val[3] = (src).last_dc_val[3])
  162637. #endif
  162638. #endif
  162639. typedef struct {
  162640. struct jpeg_entropy_encoder pub; /* public fields */
  162641. savable_state saved; /* Bit buffer & DC state at start of MCU */
  162642. /* These fields are NOT loaded into local working state. */
  162643. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  162644. int next_restart_num; /* next restart number to write (0-7) */
  162645. /* Pointers to derived tables (these workspaces have image lifespan) */
  162646. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  162647. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  162648. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  162649. long * dc_count_ptrs[NUM_HUFF_TBLS];
  162650. long * ac_count_ptrs[NUM_HUFF_TBLS];
  162651. #endif
  162652. } huff_entropy_encoder;
  162653. typedef huff_entropy_encoder * huff_entropy_ptr;
  162654. /* Working state while writing an MCU.
  162655. * This struct contains all the fields that are needed by subroutines.
  162656. */
  162657. typedef struct {
  162658. JOCTET * next_output_byte; /* => next byte to write in buffer */
  162659. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  162660. savable_state cur; /* Current bit buffer & DC state */
  162661. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  162662. } working_state;
  162663. /* Forward declarations */
  162664. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  162665. JBLOCKROW *MCU_data));
  162666. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  162667. #ifdef ENTROPY_OPT_SUPPORTED
  162668. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  162669. JBLOCKROW *MCU_data));
  162670. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  162671. #endif
  162672. /*
  162673. * Initialize for a Huffman-compressed scan.
  162674. * If gather_statistics is TRUE, we do not output anything during the scan,
  162675. * just count the Huffman symbols used and generate Huffman code tables.
  162676. */
  162677. METHODDEF(void)
  162678. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  162679. {
  162680. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162681. int ci, dctbl, actbl;
  162682. jpeg_component_info * compptr;
  162683. if (gather_statistics) {
  162684. #ifdef ENTROPY_OPT_SUPPORTED
  162685. entropy->pub.encode_mcu = encode_mcu_gather;
  162686. entropy->pub.finish_pass = finish_pass_gather;
  162687. #else
  162688. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162689. #endif
  162690. } else {
  162691. entropy->pub.encode_mcu = encode_mcu_huff;
  162692. entropy->pub.finish_pass = finish_pass_huff;
  162693. }
  162694. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162695. compptr = cinfo->cur_comp_info[ci];
  162696. dctbl = compptr->dc_tbl_no;
  162697. actbl = compptr->ac_tbl_no;
  162698. if (gather_statistics) {
  162699. #ifdef ENTROPY_OPT_SUPPORTED
  162700. /* Check for invalid table indexes */
  162701. /* (make_c_derived_tbl does this in the other path) */
  162702. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  162703. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  162704. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  162705. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  162706. /* Allocate and zero the statistics tables */
  162707. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  162708. if (entropy->dc_count_ptrs[dctbl] == NULL)
  162709. entropy->dc_count_ptrs[dctbl] = (long *)
  162710. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162711. 257 * SIZEOF(long));
  162712. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  162713. if (entropy->ac_count_ptrs[actbl] == NULL)
  162714. entropy->ac_count_ptrs[actbl] = (long *)
  162715. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162716. 257 * SIZEOF(long));
  162717. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  162718. #endif
  162719. } else {
  162720. /* Compute derived values for Huffman tables */
  162721. /* We may do this more than once for a table, but it's not expensive */
  162722. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  162723. & entropy->dc_derived_tbls[dctbl]);
  162724. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  162725. & entropy->ac_derived_tbls[actbl]);
  162726. }
  162727. /* Initialize DC predictions to 0 */
  162728. entropy->saved.last_dc_val[ci] = 0;
  162729. }
  162730. /* Initialize bit buffer to empty */
  162731. entropy->saved.put_buffer = 0;
  162732. entropy->saved.put_bits = 0;
  162733. /* Initialize restart stuff */
  162734. entropy->restarts_to_go = cinfo->restart_interval;
  162735. entropy->next_restart_num = 0;
  162736. }
  162737. /*
  162738. * Compute the derived values for a Huffman table.
  162739. * This routine also performs some validation checks on the table.
  162740. *
  162741. * Note this is also used by jcphuff.c.
  162742. */
  162743. GLOBAL(void)
  162744. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  162745. c_derived_tbl ** pdtbl)
  162746. {
  162747. JHUFF_TBL *htbl;
  162748. c_derived_tbl *dtbl;
  162749. int p, i, l, lastp, si, maxsymbol;
  162750. char huffsize[257];
  162751. unsigned int huffcode[257];
  162752. unsigned int code;
  162753. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  162754. * paralleling the order of the symbols themselves in htbl->huffval[].
  162755. */
  162756. /* Find the input Huffman table */
  162757. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  162758. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  162759. htbl =
  162760. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  162761. if (htbl == NULL)
  162762. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  162763. /* Allocate a workspace if we haven't already done so. */
  162764. if (*pdtbl == NULL)
  162765. *pdtbl = (c_derived_tbl *)
  162766. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162767. SIZEOF(c_derived_tbl));
  162768. dtbl = *pdtbl;
  162769. /* Figure C.1: make table of Huffman code length for each symbol */
  162770. p = 0;
  162771. for (l = 1; l <= 16; l++) {
  162772. i = (int) htbl->bits[l];
  162773. if (i < 0 || p + i > 256) /* protect against table overrun */
  162774. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162775. while (i--)
  162776. huffsize[p++] = (char) l;
  162777. }
  162778. huffsize[p] = 0;
  162779. lastp = p;
  162780. /* Figure C.2: generate the codes themselves */
  162781. /* We also validate that the counts represent a legal Huffman code tree. */
  162782. code = 0;
  162783. si = huffsize[0];
  162784. p = 0;
  162785. while (huffsize[p]) {
  162786. while (((int) huffsize[p]) == si) {
  162787. huffcode[p++] = code;
  162788. code++;
  162789. }
  162790. /* code is now 1 more than the last code used for codelength si; but
  162791. * it must still fit in si bits, since no code is allowed to be all ones.
  162792. */
  162793. if (((INT32) code) >= (((INT32) 1) << si))
  162794. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162795. code <<= 1;
  162796. si++;
  162797. }
  162798. /* Figure C.3: generate encoding tables */
  162799. /* These are code and size indexed by symbol value */
  162800. /* Set all codeless symbols to have code length 0;
  162801. * this lets us detect duplicate VAL entries here, and later
  162802. * allows emit_bits to detect any attempt to emit such symbols.
  162803. */
  162804. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  162805. /* This is also a convenient place to check for out-of-range
  162806. * and duplicated VAL entries. We allow 0..255 for AC symbols
  162807. * but only 0..15 for DC. (We could constrain them further
  162808. * based on data depth and mode, but this seems enough.)
  162809. */
  162810. maxsymbol = isDC ? 15 : 255;
  162811. for (p = 0; p < lastp; p++) {
  162812. i = htbl->huffval[p];
  162813. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  162814. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162815. dtbl->ehufco[i] = huffcode[p];
  162816. dtbl->ehufsi[i] = huffsize[p];
  162817. }
  162818. }
  162819. /* Outputting bytes to the file */
  162820. /* Emit a byte, taking 'action' if must suspend. */
  162821. #define emit_byte(state,val,action) \
  162822. { *(state)->next_output_byte++ = (JOCTET) (val); \
  162823. if (--(state)->free_in_buffer == 0) \
  162824. if (! dump_buffer(state)) \
  162825. { action; } }
  162826. LOCAL(boolean)
  162827. dump_buffer (working_state * state)
  162828. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  162829. {
  162830. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  162831. if (! (*dest->empty_output_buffer) (state->cinfo))
  162832. return FALSE;
  162833. /* After a successful buffer dump, must reset buffer pointers */
  162834. state->next_output_byte = dest->next_output_byte;
  162835. state->free_in_buffer = dest->free_in_buffer;
  162836. return TRUE;
  162837. }
  162838. /* Outputting bits to the file */
  162839. /* Only the right 24 bits of put_buffer are used; the valid bits are
  162840. * left-justified in this part. At most 16 bits can be passed to emit_bits
  162841. * in one call, and we never retain more than 7 bits in put_buffer
  162842. * between calls, so 24 bits are sufficient.
  162843. */
  162844. INLINE
  162845. LOCAL(boolean)
  162846. emit_bits (working_state * state, unsigned int code, int size)
  162847. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  162848. {
  162849. /* This routine is heavily used, so it's worth coding tightly. */
  162850. register INT32 put_buffer = (INT32) code;
  162851. register int put_bits = state->cur.put_bits;
  162852. /* if size is 0, caller used an invalid Huffman table entry */
  162853. if (size == 0)
  162854. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  162855. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  162856. put_bits += size; /* new number of bits in buffer */
  162857. put_buffer <<= 24 - put_bits; /* align incoming bits */
  162858. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  162859. while (put_bits >= 8) {
  162860. int c = (int) ((put_buffer >> 16) & 0xFF);
  162861. emit_byte(state, c, return FALSE);
  162862. if (c == 0xFF) { /* need to stuff a zero byte? */
  162863. emit_byte(state, 0, return FALSE);
  162864. }
  162865. put_buffer <<= 8;
  162866. put_bits -= 8;
  162867. }
  162868. state->cur.put_buffer = put_buffer; /* update state variables */
  162869. state->cur.put_bits = put_bits;
  162870. return TRUE;
  162871. }
  162872. LOCAL(boolean)
  162873. flush_bits (working_state * state)
  162874. {
  162875. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  162876. return FALSE;
  162877. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  162878. state->cur.put_bits = 0;
  162879. return TRUE;
  162880. }
  162881. /* Encode a single block's worth of coefficients */
  162882. LOCAL(boolean)
  162883. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  162884. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  162885. {
  162886. register int temp, temp2;
  162887. register int nbits;
  162888. register int k, r, i;
  162889. /* Encode the DC coefficient difference per section F.1.2.1 */
  162890. temp = temp2 = block[0] - last_dc_val;
  162891. if (temp < 0) {
  162892. temp = -temp; /* temp is abs value of input */
  162893. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  162894. /* This code assumes we are on a two's complement machine */
  162895. temp2--;
  162896. }
  162897. /* Find the number of bits needed for the magnitude of the coefficient */
  162898. nbits = 0;
  162899. while (temp) {
  162900. nbits++;
  162901. temp >>= 1;
  162902. }
  162903. /* Check for out-of-range coefficient values.
  162904. * Since we're encoding a difference, the range limit is twice as much.
  162905. */
  162906. if (nbits > MAX_COEF_BITS+1)
  162907. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  162908. /* Emit the Huffman-coded symbol for the number of bits */
  162909. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  162910. return FALSE;
  162911. /* Emit that number of bits of the value, if positive, */
  162912. /* or the complement of its magnitude, if negative. */
  162913. if (nbits) /* emit_bits rejects calls with size 0 */
  162914. if (! emit_bits(state, (unsigned int) temp2, nbits))
  162915. return FALSE;
  162916. /* Encode the AC coefficients per section F.1.2.2 */
  162917. r = 0; /* r = run length of zeros */
  162918. for (k = 1; k < DCTSIZE2; k++) {
  162919. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  162920. r++;
  162921. } else {
  162922. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  162923. while (r > 15) {
  162924. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  162925. return FALSE;
  162926. r -= 16;
  162927. }
  162928. temp2 = temp;
  162929. if (temp < 0) {
  162930. temp = -temp; /* temp is abs value of input */
  162931. /* This code assumes we are on a two's complement machine */
  162932. temp2--;
  162933. }
  162934. /* Find the number of bits needed for the magnitude of the coefficient */
  162935. nbits = 1; /* there must be at least one 1 bit */
  162936. while ((temp >>= 1))
  162937. nbits++;
  162938. /* Check for out-of-range coefficient values */
  162939. if (nbits > MAX_COEF_BITS)
  162940. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  162941. /* Emit Huffman symbol for run length / number of bits */
  162942. i = (r << 4) + nbits;
  162943. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  162944. return FALSE;
  162945. /* Emit that number of bits of the value, if positive, */
  162946. /* or the complement of its magnitude, if negative. */
  162947. if (! emit_bits(state, (unsigned int) temp2, nbits))
  162948. return FALSE;
  162949. r = 0;
  162950. }
  162951. }
  162952. /* If the last coef(s) were zero, emit an end-of-block code */
  162953. if (r > 0)
  162954. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  162955. return FALSE;
  162956. return TRUE;
  162957. }
  162958. /*
  162959. * Emit a restart marker & resynchronize predictions.
  162960. */
  162961. LOCAL(boolean)
  162962. emit_restart (working_state * state, int restart_num)
  162963. {
  162964. int ci;
  162965. if (! flush_bits(state))
  162966. return FALSE;
  162967. emit_byte(state, 0xFF, return FALSE);
  162968. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  162969. /* Re-initialize DC predictions to 0 */
  162970. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  162971. state->cur.last_dc_val[ci] = 0;
  162972. /* The restart counter is not updated until we successfully write the MCU. */
  162973. return TRUE;
  162974. }
  162975. /*
  162976. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  162977. */
  162978. METHODDEF(boolean)
  162979. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162980. {
  162981. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162982. working_state state;
  162983. int blkn, ci;
  162984. jpeg_component_info * compptr;
  162985. /* Load up working state */
  162986. state.next_output_byte = cinfo->dest->next_output_byte;
  162987. state.free_in_buffer = cinfo->dest->free_in_buffer;
  162988. ASSIGN_STATE(state.cur, entropy->saved);
  162989. state.cinfo = cinfo;
  162990. /* Emit restart marker if needed */
  162991. if (cinfo->restart_interval) {
  162992. if (entropy->restarts_to_go == 0)
  162993. if (! emit_restart(&state, entropy->next_restart_num))
  162994. return FALSE;
  162995. }
  162996. /* Encode the MCU data blocks */
  162997. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  162998. ci = cinfo->MCU_membership[blkn];
  162999. compptr = cinfo->cur_comp_info[ci];
  163000. if (! encode_one_block(&state,
  163001. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163002. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163003. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163004. return FALSE;
  163005. /* Update last_dc_val */
  163006. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163007. }
  163008. /* Completed MCU, so update state */
  163009. cinfo->dest->next_output_byte = state.next_output_byte;
  163010. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163011. ASSIGN_STATE(entropy->saved, state.cur);
  163012. /* Update restart-interval state too */
  163013. if (cinfo->restart_interval) {
  163014. if (entropy->restarts_to_go == 0) {
  163015. entropy->restarts_to_go = cinfo->restart_interval;
  163016. entropy->next_restart_num++;
  163017. entropy->next_restart_num &= 7;
  163018. }
  163019. entropy->restarts_to_go--;
  163020. }
  163021. return TRUE;
  163022. }
  163023. /*
  163024. * Finish up at the end of a Huffman-compressed scan.
  163025. */
  163026. METHODDEF(void)
  163027. finish_pass_huff (j_compress_ptr cinfo)
  163028. {
  163029. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163030. working_state state;
  163031. /* Load up working state ... flush_bits needs it */
  163032. state.next_output_byte = cinfo->dest->next_output_byte;
  163033. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163034. ASSIGN_STATE(state.cur, entropy->saved);
  163035. state.cinfo = cinfo;
  163036. /* Flush out the last data */
  163037. if (! flush_bits(&state))
  163038. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163039. /* Update state */
  163040. cinfo->dest->next_output_byte = state.next_output_byte;
  163041. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163042. ASSIGN_STATE(entropy->saved, state.cur);
  163043. }
  163044. /*
  163045. * Huffman coding optimization.
  163046. *
  163047. * We first scan the supplied data and count the number of uses of each symbol
  163048. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163049. * Then we build a Huffman coding tree for the observed counts.
  163050. * Symbols which are not needed at all for the particular image are not
  163051. * assigned any code, which saves space in the DHT marker as well as in
  163052. * the compressed data.
  163053. */
  163054. #ifdef ENTROPY_OPT_SUPPORTED
  163055. /* Process a single block's worth of coefficients */
  163056. LOCAL(void)
  163057. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163058. long dc_counts[], long ac_counts[])
  163059. {
  163060. register int temp;
  163061. register int nbits;
  163062. register int k, r;
  163063. /* Encode the DC coefficient difference per section F.1.2.1 */
  163064. temp = block[0] - last_dc_val;
  163065. if (temp < 0)
  163066. temp = -temp;
  163067. /* Find the number of bits needed for the magnitude of the coefficient */
  163068. nbits = 0;
  163069. while (temp) {
  163070. nbits++;
  163071. temp >>= 1;
  163072. }
  163073. /* Check for out-of-range coefficient values.
  163074. * Since we're encoding a difference, the range limit is twice as much.
  163075. */
  163076. if (nbits > MAX_COEF_BITS+1)
  163077. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163078. /* Count the Huffman symbol for the number of bits */
  163079. dc_counts[nbits]++;
  163080. /* Encode the AC coefficients per section F.1.2.2 */
  163081. r = 0; /* r = run length of zeros */
  163082. for (k = 1; k < DCTSIZE2; k++) {
  163083. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163084. r++;
  163085. } else {
  163086. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163087. while (r > 15) {
  163088. ac_counts[0xF0]++;
  163089. r -= 16;
  163090. }
  163091. /* Find the number of bits needed for the magnitude of the coefficient */
  163092. if (temp < 0)
  163093. temp = -temp;
  163094. /* Find the number of bits needed for the magnitude of the coefficient */
  163095. nbits = 1; /* there must be at least one 1 bit */
  163096. while ((temp >>= 1))
  163097. nbits++;
  163098. /* Check for out-of-range coefficient values */
  163099. if (nbits > MAX_COEF_BITS)
  163100. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163101. /* Count Huffman symbol for run length / number of bits */
  163102. ac_counts[(r << 4) + nbits]++;
  163103. r = 0;
  163104. }
  163105. }
  163106. /* If the last coef(s) were zero, emit an end-of-block code */
  163107. if (r > 0)
  163108. ac_counts[0]++;
  163109. }
  163110. /*
  163111. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163112. * No data is actually output, so no suspension return is possible.
  163113. */
  163114. METHODDEF(boolean)
  163115. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163116. {
  163117. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163118. int blkn, ci;
  163119. jpeg_component_info * compptr;
  163120. /* Take care of restart intervals if needed */
  163121. if (cinfo->restart_interval) {
  163122. if (entropy->restarts_to_go == 0) {
  163123. /* Re-initialize DC predictions to 0 */
  163124. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163125. entropy->saved.last_dc_val[ci] = 0;
  163126. /* Update restart state */
  163127. entropy->restarts_to_go = cinfo->restart_interval;
  163128. }
  163129. entropy->restarts_to_go--;
  163130. }
  163131. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163132. ci = cinfo->MCU_membership[blkn];
  163133. compptr = cinfo->cur_comp_info[ci];
  163134. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163135. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163136. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163137. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163138. }
  163139. return TRUE;
  163140. }
  163141. /*
  163142. * Generate the best Huffman code table for the given counts, fill htbl.
  163143. * Note this is also used by jcphuff.c.
  163144. *
  163145. * The JPEG standard requires that no symbol be assigned a codeword of all
  163146. * one bits (so that padding bits added at the end of a compressed segment
  163147. * can't look like a valid code). Because of the canonical ordering of
  163148. * codewords, this just means that there must be an unused slot in the
  163149. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163150. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163151. * with count 1. In theory that's not optimal; giving it count zero but
  163152. * including it in the symbol set anyway should give a better Huffman code.
  163153. * But the theoretically better code actually seems to come out worse in
  163154. * practice, because it produces more all-ones bytes (which incur stuffed
  163155. * zero bytes in the final file). In any case the difference is tiny.
  163156. *
  163157. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163158. * If some symbols have a very small but nonzero probability, the Huffman tree
  163159. * must be adjusted to meet the code length restriction. We currently use
  163160. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163161. * optimal; it may not choose the best possible limited-length code. But
  163162. * typically only very-low-frequency symbols will be given less-than-optimal
  163163. * lengths, so the code is almost optimal. Experimental comparisons against
  163164. * an optimal limited-length-code algorithm indicate that the difference is
  163165. * microscopic --- usually less than a hundredth of a percent of total size.
  163166. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163167. */
  163168. GLOBAL(void)
  163169. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163170. {
  163171. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163172. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163173. int codesize[257]; /* codesize[k] = code length of symbol k */
  163174. int others[257]; /* next symbol in current branch of tree */
  163175. int c1, c2;
  163176. int p, i, j;
  163177. long v;
  163178. /* This algorithm is explained in section K.2 of the JPEG standard */
  163179. MEMZERO(bits, SIZEOF(bits));
  163180. MEMZERO(codesize, SIZEOF(codesize));
  163181. for (i = 0; i < 257; i++)
  163182. others[i] = -1; /* init links to empty */
  163183. freq[256] = 1; /* make sure 256 has a nonzero count */
  163184. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163185. * that no real symbol is given code-value of all ones, because 256
  163186. * will be placed last in the largest codeword category.
  163187. */
  163188. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163189. for (;;) {
  163190. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163191. /* In case of ties, take the larger symbol number */
  163192. c1 = -1;
  163193. v = 1000000000L;
  163194. for (i = 0; i <= 256; i++) {
  163195. if (freq[i] && freq[i] <= v) {
  163196. v = freq[i];
  163197. c1 = i;
  163198. }
  163199. }
  163200. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163201. /* In case of ties, take the larger symbol number */
  163202. c2 = -1;
  163203. v = 1000000000L;
  163204. for (i = 0; i <= 256; i++) {
  163205. if (freq[i] && freq[i] <= v && i != c1) {
  163206. v = freq[i];
  163207. c2 = i;
  163208. }
  163209. }
  163210. /* Done if we've merged everything into one frequency */
  163211. if (c2 < 0)
  163212. break;
  163213. /* Else merge the two counts/trees */
  163214. freq[c1] += freq[c2];
  163215. freq[c2] = 0;
  163216. /* Increment the codesize of everything in c1's tree branch */
  163217. codesize[c1]++;
  163218. while (others[c1] >= 0) {
  163219. c1 = others[c1];
  163220. codesize[c1]++;
  163221. }
  163222. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163223. /* Increment the codesize of everything in c2's tree branch */
  163224. codesize[c2]++;
  163225. while (others[c2] >= 0) {
  163226. c2 = others[c2];
  163227. codesize[c2]++;
  163228. }
  163229. }
  163230. /* Now count the number of symbols of each code length */
  163231. for (i = 0; i <= 256; i++) {
  163232. if (codesize[i]) {
  163233. /* The JPEG standard seems to think that this can't happen, */
  163234. /* but I'm paranoid... */
  163235. if (codesize[i] > MAX_CLEN)
  163236. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163237. bits[codesize[i]]++;
  163238. }
  163239. }
  163240. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163241. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163242. * Here is what the JPEG spec says about how this next bit works:
  163243. * Since symbols are paired for the longest Huffman code, the symbols are
  163244. * removed from this length category two at a time. The prefix for the pair
  163245. * (which is one bit shorter) is allocated to one of the pair; then,
  163246. * skipping the BITS entry for that prefix length, a code word from the next
  163247. * shortest nonzero BITS entry is converted into a prefix for two code words
  163248. * one bit longer.
  163249. */
  163250. for (i = MAX_CLEN; i > 16; i--) {
  163251. while (bits[i] > 0) {
  163252. j = i - 2; /* find length of new prefix to be used */
  163253. while (bits[j] == 0)
  163254. j--;
  163255. bits[i] -= 2; /* remove two symbols */
  163256. bits[i-1]++; /* one goes in this length */
  163257. bits[j+1] += 2; /* two new symbols in this length */
  163258. bits[j]--; /* symbol of this length is now a prefix */
  163259. }
  163260. }
  163261. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163262. while (bits[i] == 0) /* find largest codelength still in use */
  163263. i--;
  163264. bits[i]--;
  163265. /* Return final symbol counts (only for lengths 0..16) */
  163266. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163267. /* Return a list of the symbols sorted by code length */
  163268. /* It's not real clear to me why we don't need to consider the codelength
  163269. * changes made above, but the JPEG spec seems to think this works.
  163270. */
  163271. p = 0;
  163272. for (i = 1; i <= MAX_CLEN; i++) {
  163273. for (j = 0; j <= 255; j++) {
  163274. if (codesize[j] == i) {
  163275. htbl->huffval[p] = (UINT8) j;
  163276. p++;
  163277. }
  163278. }
  163279. }
  163280. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  163281. htbl->sent_table = FALSE;
  163282. }
  163283. /*
  163284. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163285. */
  163286. METHODDEF(void)
  163287. finish_pass_gather (j_compress_ptr cinfo)
  163288. {
  163289. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163290. int ci, dctbl, actbl;
  163291. jpeg_component_info * compptr;
  163292. JHUFF_TBL **htblptr;
  163293. boolean did_dc[NUM_HUFF_TBLS];
  163294. boolean did_ac[NUM_HUFF_TBLS];
  163295. /* It's important not to apply jpeg_gen_optimal_table more than once
  163296. * per table, because it clobbers the input frequency counts!
  163297. */
  163298. MEMZERO(did_dc, SIZEOF(did_dc));
  163299. MEMZERO(did_ac, SIZEOF(did_ac));
  163300. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163301. compptr = cinfo->cur_comp_info[ci];
  163302. dctbl = compptr->dc_tbl_no;
  163303. actbl = compptr->ac_tbl_no;
  163304. if (! did_dc[dctbl]) {
  163305. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163306. if (*htblptr == NULL)
  163307. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163308. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163309. did_dc[dctbl] = TRUE;
  163310. }
  163311. if (! did_ac[actbl]) {
  163312. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163313. if (*htblptr == NULL)
  163314. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163315. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163316. did_ac[actbl] = TRUE;
  163317. }
  163318. }
  163319. }
  163320. #endif /* ENTROPY_OPT_SUPPORTED */
  163321. /*
  163322. * Module initialization routine for Huffman entropy encoding.
  163323. */
  163324. GLOBAL(void)
  163325. jinit_huff_encoder (j_compress_ptr cinfo)
  163326. {
  163327. huff_entropy_ptr entropy;
  163328. int i;
  163329. entropy = (huff_entropy_ptr)
  163330. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163331. SIZEOF(huff_entropy_encoder));
  163332. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163333. entropy->pub.start_pass = start_pass_huff;
  163334. /* Mark tables unallocated */
  163335. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163336. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163337. #ifdef ENTROPY_OPT_SUPPORTED
  163338. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163339. #endif
  163340. }
  163341. }
  163342. /*** End of inlined file: jchuff.c ***/
  163343. #undef emit_byte
  163344. /*** Start of inlined file: jcinit.c ***/
  163345. #define JPEG_INTERNALS
  163346. /*
  163347. * Master selection of compression modules.
  163348. * This is done once at the start of processing an image. We determine
  163349. * which modules will be used and give them appropriate initialization calls.
  163350. */
  163351. GLOBAL(void)
  163352. jinit_compress_master (j_compress_ptr cinfo)
  163353. {
  163354. /* Initialize master control (includes parameter checking/processing) */
  163355. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163356. /* Preprocessing */
  163357. if (! cinfo->raw_data_in) {
  163358. jinit_color_converter(cinfo);
  163359. jinit_downsampler(cinfo);
  163360. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163361. }
  163362. /* Forward DCT */
  163363. jinit_forward_dct(cinfo);
  163364. /* Entropy encoding: either Huffman or arithmetic coding. */
  163365. if (cinfo->arith_code) {
  163366. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163367. } else {
  163368. if (cinfo->progressive_mode) {
  163369. #ifdef C_PROGRESSIVE_SUPPORTED
  163370. jinit_phuff_encoder(cinfo);
  163371. #else
  163372. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163373. #endif
  163374. } else
  163375. jinit_huff_encoder(cinfo);
  163376. }
  163377. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163378. jinit_c_coef_controller(cinfo,
  163379. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163380. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163381. jinit_marker_writer(cinfo);
  163382. /* We can now tell the memory manager to allocate virtual arrays. */
  163383. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163384. /* Write the datastream header (SOI) immediately.
  163385. * Frame and scan headers are postponed till later.
  163386. * This lets application insert special markers after the SOI.
  163387. */
  163388. (*cinfo->marker->write_file_header) (cinfo);
  163389. }
  163390. /*** End of inlined file: jcinit.c ***/
  163391. /*** Start of inlined file: jcmainct.c ***/
  163392. #define JPEG_INTERNALS
  163393. /* Note: currently, there is no operating mode in which a full-image buffer
  163394. * is needed at this step. If there were, that mode could not be used with
  163395. * "raw data" input, since this module is bypassed in that case. However,
  163396. * we've left the code here for possible use in special applications.
  163397. */
  163398. #undef FULL_MAIN_BUFFER_SUPPORTED
  163399. /* Private buffer controller object */
  163400. typedef struct {
  163401. struct jpeg_c_main_controller pub; /* public fields */
  163402. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  163403. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  163404. boolean suspended; /* remember if we suspended output */
  163405. J_BUF_MODE pass_mode; /* current operating mode */
  163406. /* If using just a strip buffer, this points to the entire set of buffers
  163407. * (we allocate one for each component). In the full-image case, this
  163408. * points to the currently accessible strips of the virtual arrays.
  163409. */
  163410. JSAMPARRAY buffer[MAX_COMPONENTS];
  163411. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163412. /* If using full-image storage, this array holds pointers to virtual-array
  163413. * control blocks for each component. Unused if not full-image storage.
  163414. */
  163415. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  163416. #endif
  163417. } my_main_controller;
  163418. typedef my_main_controller * my_main_ptr;
  163419. /* Forward declarations */
  163420. METHODDEF(void) process_data_simple_main
  163421. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163422. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163423. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163424. METHODDEF(void) process_data_buffer_main
  163425. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163426. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163427. #endif
  163428. /*
  163429. * Initialize for a processing pass.
  163430. */
  163431. METHODDEF(void)
  163432. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163433. {
  163434. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163435. /* Do nothing in raw-data mode. */
  163436. if (cinfo->raw_data_in)
  163437. return;
  163438. main_->cur_iMCU_row = 0; /* initialize counters */
  163439. main_->rowgroup_ctr = 0;
  163440. main_->suspended = FALSE;
  163441. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  163442. switch (pass_mode) {
  163443. case JBUF_PASS_THRU:
  163444. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163445. if (main_->whole_image[0] != NULL)
  163446. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163447. #endif
  163448. main_->pub.process_data = process_data_simple_main;
  163449. break;
  163450. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163451. case JBUF_SAVE_SOURCE:
  163452. case JBUF_CRANK_DEST:
  163453. case JBUF_SAVE_AND_PASS:
  163454. if (main_->whole_image[0] == NULL)
  163455. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163456. main_->pub.process_data = process_data_buffer_main;
  163457. break;
  163458. #endif
  163459. default:
  163460. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163461. break;
  163462. }
  163463. }
  163464. /*
  163465. * Process some data.
  163466. * This routine handles the simple pass-through mode,
  163467. * where we have only a strip buffer.
  163468. */
  163469. METHODDEF(void)
  163470. process_data_simple_main (j_compress_ptr cinfo,
  163471. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163472. JDIMENSION in_rows_avail)
  163473. {
  163474. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163475. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163476. /* Read input data if we haven't filled the main buffer yet */
  163477. if (main_->rowgroup_ctr < DCTSIZE)
  163478. (*cinfo->prep->pre_process_data) (cinfo,
  163479. input_buf, in_row_ctr, in_rows_avail,
  163480. main_->buffer, &main_->rowgroup_ctr,
  163481. (JDIMENSION) DCTSIZE);
  163482. /* If we don't have a full iMCU row buffered, return to application for
  163483. * more data. Note that preprocessor will always pad to fill the iMCU row
  163484. * at the bottom of the image.
  163485. */
  163486. if (main_->rowgroup_ctr != DCTSIZE)
  163487. return;
  163488. /* Send the completed row to the compressor */
  163489. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  163490. /* If compressor did not consume the whole row, then we must need to
  163491. * suspend processing and return to the application. In this situation
  163492. * we pretend we didn't yet consume the last input row; otherwise, if
  163493. * it happened to be the last row of the image, the application would
  163494. * think we were done.
  163495. */
  163496. if (! main_->suspended) {
  163497. (*in_row_ctr)--;
  163498. main_->suspended = TRUE;
  163499. }
  163500. return;
  163501. }
  163502. /* We did finish the row. Undo our little suspension hack if a previous
  163503. * call suspended; then mark the main buffer empty.
  163504. */
  163505. if (main_->suspended) {
  163506. (*in_row_ctr)++;
  163507. main_->suspended = FALSE;
  163508. }
  163509. main_->rowgroup_ctr = 0;
  163510. main_->cur_iMCU_row++;
  163511. }
  163512. }
  163513. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163514. /*
  163515. * Process some data.
  163516. * This routine handles all of the modes that use a full-size buffer.
  163517. */
  163518. METHODDEF(void)
  163519. process_data_buffer_main (j_compress_ptr cinfo,
  163520. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163521. JDIMENSION in_rows_avail)
  163522. {
  163523. my_main_ptr main = (my_main_ptr) cinfo->main;
  163524. int ci;
  163525. jpeg_component_info *compptr;
  163526. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  163527. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163528. /* Realign the virtual buffers if at the start of an iMCU row. */
  163529. if (main->rowgroup_ctr == 0) {
  163530. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163531. ci++, compptr++) {
  163532. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  163533. ((j_common_ptr) cinfo, main->whole_image[ci],
  163534. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  163535. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  163536. }
  163537. /* In a read pass, pretend we just read some source data. */
  163538. if (! writing) {
  163539. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  163540. main->rowgroup_ctr = DCTSIZE;
  163541. }
  163542. }
  163543. /* If a write pass, read input data until the current iMCU row is full. */
  163544. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  163545. if (writing) {
  163546. (*cinfo->prep->pre_process_data) (cinfo,
  163547. input_buf, in_row_ctr, in_rows_avail,
  163548. main->buffer, &main->rowgroup_ctr,
  163549. (JDIMENSION) DCTSIZE);
  163550. /* Return to application if we need more data to fill the iMCU row. */
  163551. if (main->rowgroup_ctr < DCTSIZE)
  163552. return;
  163553. }
  163554. /* Emit data, unless this is a sink-only pass. */
  163555. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  163556. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  163557. /* If compressor did not consume the whole row, then we must need to
  163558. * suspend processing and return to the application. In this situation
  163559. * we pretend we didn't yet consume the last input row; otherwise, if
  163560. * it happened to be the last row of the image, the application would
  163561. * think we were done.
  163562. */
  163563. if (! main->suspended) {
  163564. (*in_row_ctr)--;
  163565. main->suspended = TRUE;
  163566. }
  163567. return;
  163568. }
  163569. /* We did finish the row. Undo our little suspension hack if a previous
  163570. * call suspended; then mark the main buffer empty.
  163571. */
  163572. if (main->suspended) {
  163573. (*in_row_ctr)++;
  163574. main->suspended = FALSE;
  163575. }
  163576. }
  163577. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  163578. main->rowgroup_ctr = 0;
  163579. main->cur_iMCU_row++;
  163580. }
  163581. }
  163582. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  163583. /*
  163584. * Initialize main buffer controller.
  163585. */
  163586. GLOBAL(void)
  163587. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  163588. {
  163589. my_main_ptr main_;
  163590. int ci;
  163591. jpeg_component_info *compptr;
  163592. main_ = (my_main_ptr)
  163593. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163594. SIZEOF(my_main_controller));
  163595. cinfo->main = (struct jpeg_c_main_controller *) main_;
  163596. main_->pub.start_pass = start_pass_main;
  163597. /* We don't need to create a buffer in raw-data mode. */
  163598. if (cinfo->raw_data_in)
  163599. return;
  163600. /* Create the buffer. It holds downsampled data, so each component
  163601. * may be of a different size.
  163602. */
  163603. if (need_full_buffer) {
  163604. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163605. /* Allocate a full-image virtual array for each component */
  163606. /* Note we pad the bottom to a multiple of the iMCU height */
  163607. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163608. ci++, compptr++) {
  163609. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  163610. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  163611. compptr->width_in_blocks * DCTSIZE,
  163612. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  163613. (long) compptr->v_samp_factor) * DCTSIZE,
  163614. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163615. }
  163616. #else
  163617. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163618. #endif
  163619. } else {
  163620. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163621. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  163622. #endif
  163623. /* Allocate a strip buffer for each component */
  163624. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163625. ci++, compptr++) {
  163626. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  163627. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163628. compptr->width_in_blocks * DCTSIZE,
  163629. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163630. }
  163631. }
  163632. }
  163633. /*** End of inlined file: jcmainct.c ***/
  163634. /*** Start of inlined file: jcmarker.c ***/
  163635. #define JPEG_INTERNALS
  163636. /* Private state */
  163637. typedef struct {
  163638. struct jpeg_marker_writer pub; /* public fields */
  163639. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  163640. } my_marker_writer;
  163641. typedef my_marker_writer * my_marker_ptr;
  163642. /*
  163643. * Basic output routines.
  163644. *
  163645. * Note that we do not support suspension while writing a marker.
  163646. * Therefore, an application using suspension must ensure that there is
  163647. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  163648. * calling jpeg_start_compress, and enough space to write the trailing EOI
  163649. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  163650. * modes are not supported at all with suspension, so those two are the only
  163651. * points where markers will be written.
  163652. */
  163653. LOCAL(void)
  163654. emit_byte (j_compress_ptr cinfo, int val)
  163655. /* Emit a byte */
  163656. {
  163657. struct jpeg_destination_mgr * dest = cinfo->dest;
  163658. *(dest->next_output_byte)++ = (JOCTET) val;
  163659. if (--dest->free_in_buffer == 0) {
  163660. if (! (*dest->empty_output_buffer) (cinfo))
  163661. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163662. }
  163663. }
  163664. LOCAL(void)
  163665. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  163666. /* Emit a marker code */
  163667. {
  163668. emit_byte(cinfo, 0xFF);
  163669. emit_byte(cinfo, (int) mark);
  163670. }
  163671. LOCAL(void)
  163672. emit_2bytes (j_compress_ptr cinfo, int value)
  163673. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  163674. {
  163675. emit_byte(cinfo, (value >> 8) & 0xFF);
  163676. emit_byte(cinfo, value & 0xFF);
  163677. }
  163678. /*
  163679. * Routines to write specific marker types.
  163680. */
  163681. LOCAL(int)
  163682. emit_dqt (j_compress_ptr cinfo, int index)
  163683. /* Emit a DQT marker */
  163684. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  163685. {
  163686. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  163687. int prec;
  163688. int i;
  163689. if (qtbl == NULL)
  163690. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  163691. prec = 0;
  163692. for (i = 0; i < DCTSIZE2; i++) {
  163693. if (qtbl->quantval[i] > 255)
  163694. prec = 1;
  163695. }
  163696. if (! qtbl->sent_table) {
  163697. emit_marker(cinfo, M_DQT);
  163698. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  163699. emit_byte(cinfo, index + (prec<<4));
  163700. for (i = 0; i < DCTSIZE2; i++) {
  163701. /* The table entries must be emitted in zigzag order. */
  163702. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  163703. if (prec)
  163704. emit_byte(cinfo, (int) (qval >> 8));
  163705. emit_byte(cinfo, (int) (qval & 0xFF));
  163706. }
  163707. qtbl->sent_table = TRUE;
  163708. }
  163709. return prec;
  163710. }
  163711. LOCAL(void)
  163712. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  163713. /* Emit a DHT marker */
  163714. {
  163715. JHUFF_TBL * htbl;
  163716. int length, i;
  163717. if (is_ac) {
  163718. htbl = cinfo->ac_huff_tbl_ptrs[index];
  163719. index += 0x10; /* output index has AC bit set */
  163720. } else {
  163721. htbl = cinfo->dc_huff_tbl_ptrs[index];
  163722. }
  163723. if (htbl == NULL)
  163724. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  163725. if (! htbl->sent_table) {
  163726. emit_marker(cinfo, M_DHT);
  163727. length = 0;
  163728. for (i = 1; i <= 16; i++)
  163729. length += htbl->bits[i];
  163730. emit_2bytes(cinfo, length + 2 + 1 + 16);
  163731. emit_byte(cinfo, index);
  163732. for (i = 1; i <= 16; i++)
  163733. emit_byte(cinfo, htbl->bits[i]);
  163734. for (i = 0; i < length; i++)
  163735. emit_byte(cinfo, htbl->huffval[i]);
  163736. htbl->sent_table = TRUE;
  163737. }
  163738. }
  163739. LOCAL(void)
  163740. emit_dac (j_compress_ptr)
  163741. /* Emit a DAC marker */
  163742. /* Since the useful info is so small, we want to emit all the tables in */
  163743. /* one DAC marker. Therefore this routine does its own scan of the table. */
  163744. {
  163745. #ifdef C_ARITH_CODING_SUPPORTED
  163746. char dc_in_use[NUM_ARITH_TBLS];
  163747. char ac_in_use[NUM_ARITH_TBLS];
  163748. int length, i;
  163749. jpeg_component_info *compptr;
  163750. for (i = 0; i < NUM_ARITH_TBLS; i++)
  163751. dc_in_use[i] = ac_in_use[i] = 0;
  163752. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163753. compptr = cinfo->cur_comp_info[i];
  163754. dc_in_use[compptr->dc_tbl_no] = 1;
  163755. ac_in_use[compptr->ac_tbl_no] = 1;
  163756. }
  163757. length = 0;
  163758. for (i = 0; i < NUM_ARITH_TBLS; i++)
  163759. length += dc_in_use[i] + ac_in_use[i];
  163760. emit_marker(cinfo, M_DAC);
  163761. emit_2bytes(cinfo, length*2 + 2);
  163762. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  163763. if (dc_in_use[i]) {
  163764. emit_byte(cinfo, i);
  163765. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  163766. }
  163767. if (ac_in_use[i]) {
  163768. emit_byte(cinfo, i + 0x10);
  163769. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  163770. }
  163771. }
  163772. #endif /* C_ARITH_CODING_SUPPORTED */
  163773. }
  163774. LOCAL(void)
  163775. emit_dri (j_compress_ptr cinfo)
  163776. /* Emit a DRI marker */
  163777. {
  163778. emit_marker(cinfo, M_DRI);
  163779. emit_2bytes(cinfo, 4); /* fixed length */
  163780. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  163781. }
  163782. LOCAL(void)
  163783. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  163784. /* Emit a SOF marker */
  163785. {
  163786. int ci;
  163787. jpeg_component_info *compptr;
  163788. emit_marker(cinfo, code);
  163789. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  163790. /* Make sure image isn't bigger than SOF field can handle */
  163791. if ((long) cinfo->image_height > 65535L ||
  163792. (long) cinfo->image_width > 65535L)
  163793. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  163794. emit_byte(cinfo, cinfo->data_precision);
  163795. emit_2bytes(cinfo, (int) cinfo->image_height);
  163796. emit_2bytes(cinfo, (int) cinfo->image_width);
  163797. emit_byte(cinfo, cinfo->num_components);
  163798. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163799. ci++, compptr++) {
  163800. emit_byte(cinfo, compptr->component_id);
  163801. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  163802. emit_byte(cinfo, compptr->quant_tbl_no);
  163803. }
  163804. }
  163805. LOCAL(void)
  163806. emit_sos (j_compress_ptr cinfo)
  163807. /* Emit a SOS marker */
  163808. {
  163809. int i, td, ta;
  163810. jpeg_component_info *compptr;
  163811. emit_marker(cinfo, M_SOS);
  163812. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  163813. emit_byte(cinfo, cinfo->comps_in_scan);
  163814. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163815. compptr = cinfo->cur_comp_info[i];
  163816. emit_byte(cinfo, compptr->component_id);
  163817. td = compptr->dc_tbl_no;
  163818. ta = compptr->ac_tbl_no;
  163819. if (cinfo->progressive_mode) {
  163820. /* Progressive mode: only DC or only AC tables are used in one scan;
  163821. * furthermore, Huffman coding of DC refinement uses no table at all.
  163822. * We emit 0 for unused field(s); this is recommended by the P&M text
  163823. * but does not seem to be specified in the standard.
  163824. */
  163825. if (cinfo->Ss == 0) {
  163826. ta = 0; /* DC scan */
  163827. if (cinfo->Ah != 0 && !cinfo->arith_code)
  163828. td = 0; /* no DC table either */
  163829. } else {
  163830. td = 0; /* AC scan */
  163831. }
  163832. }
  163833. emit_byte(cinfo, (td << 4) + ta);
  163834. }
  163835. emit_byte(cinfo, cinfo->Ss);
  163836. emit_byte(cinfo, cinfo->Se);
  163837. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  163838. }
  163839. LOCAL(void)
  163840. emit_jfif_app0 (j_compress_ptr cinfo)
  163841. /* Emit a JFIF-compliant APP0 marker */
  163842. {
  163843. /*
  163844. * Length of APP0 block (2 bytes)
  163845. * Block ID (4 bytes - ASCII "JFIF")
  163846. * Zero byte (1 byte to terminate the ID string)
  163847. * Version Major, Minor (2 bytes - major first)
  163848. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  163849. * Xdpu (2 bytes - dots per unit horizontal)
  163850. * Ydpu (2 bytes - dots per unit vertical)
  163851. * Thumbnail X size (1 byte)
  163852. * Thumbnail Y size (1 byte)
  163853. */
  163854. emit_marker(cinfo, M_APP0);
  163855. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  163856. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  163857. emit_byte(cinfo, 0x46);
  163858. emit_byte(cinfo, 0x49);
  163859. emit_byte(cinfo, 0x46);
  163860. emit_byte(cinfo, 0);
  163861. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  163862. emit_byte(cinfo, cinfo->JFIF_minor_version);
  163863. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  163864. emit_2bytes(cinfo, (int) cinfo->X_density);
  163865. emit_2bytes(cinfo, (int) cinfo->Y_density);
  163866. emit_byte(cinfo, 0); /* No thumbnail image */
  163867. emit_byte(cinfo, 0);
  163868. }
  163869. LOCAL(void)
  163870. emit_adobe_app14 (j_compress_ptr cinfo)
  163871. /* Emit an Adobe APP14 marker */
  163872. {
  163873. /*
  163874. * Length of APP14 block (2 bytes)
  163875. * Block ID (5 bytes - ASCII "Adobe")
  163876. * Version Number (2 bytes - currently 100)
  163877. * Flags0 (2 bytes - currently 0)
  163878. * Flags1 (2 bytes - currently 0)
  163879. * Color transform (1 byte)
  163880. *
  163881. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  163882. * now in circulation seem to use Version = 100, so that's what we write.
  163883. *
  163884. * We write the color transform byte as 1 if the JPEG color space is
  163885. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  163886. * whether the encoder performed a transformation, which is pretty useless.
  163887. */
  163888. emit_marker(cinfo, M_APP14);
  163889. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  163890. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  163891. emit_byte(cinfo, 0x64);
  163892. emit_byte(cinfo, 0x6F);
  163893. emit_byte(cinfo, 0x62);
  163894. emit_byte(cinfo, 0x65);
  163895. emit_2bytes(cinfo, 100); /* Version */
  163896. emit_2bytes(cinfo, 0); /* Flags0 */
  163897. emit_2bytes(cinfo, 0); /* Flags1 */
  163898. switch (cinfo->jpeg_color_space) {
  163899. case JCS_YCbCr:
  163900. emit_byte(cinfo, 1); /* Color transform = 1 */
  163901. break;
  163902. case JCS_YCCK:
  163903. emit_byte(cinfo, 2); /* Color transform = 2 */
  163904. break;
  163905. default:
  163906. emit_byte(cinfo, 0); /* Color transform = 0 */
  163907. break;
  163908. }
  163909. }
  163910. /*
  163911. * These routines allow writing an arbitrary marker with parameters.
  163912. * The only intended use is to emit COM or APPn markers after calling
  163913. * write_file_header and before calling write_frame_header.
  163914. * Other uses are not guaranteed to produce desirable results.
  163915. * Counting the parameter bytes properly is the caller's responsibility.
  163916. */
  163917. METHODDEF(void)
  163918. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  163919. /* Emit an arbitrary marker header */
  163920. {
  163921. if (datalen > (unsigned int) 65533) /* safety check */
  163922. ERREXIT(cinfo, JERR_BAD_LENGTH);
  163923. emit_marker(cinfo, (JPEG_MARKER) marker);
  163924. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  163925. }
  163926. METHODDEF(void)
  163927. write_marker_byte (j_compress_ptr cinfo, int val)
  163928. /* Emit one byte of marker parameters following write_marker_header */
  163929. {
  163930. emit_byte(cinfo, val);
  163931. }
  163932. /*
  163933. * Write datastream header.
  163934. * This consists of an SOI and optional APPn markers.
  163935. * We recommend use of the JFIF marker, but not the Adobe marker,
  163936. * when using YCbCr or grayscale data. The JFIF marker should NOT
  163937. * be used for any other JPEG colorspace. The Adobe marker is helpful
  163938. * to distinguish RGB, CMYK, and YCCK colorspaces.
  163939. * Note that an application can write additional header markers after
  163940. * jpeg_start_compress returns.
  163941. */
  163942. METHODDEF(void)
  163943. write_file_header (j_compress_ptr cinfo)
  163944. {
  163945. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  163946. emit_marker(cinfo, M_SOI); /* first the SOI */
  163947. /* SOI is defined to reset restart interval to 0 */
  163948. marker->last_restart_interval = 0;
  163949. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  163950. emit_jfif_app0(cinfo);
  163951. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  163952. emit_adobe_app14(cinfo);
  163953. }
  163954. /*
  163955. * Write frame header.
  163956. * This consists of DQT and SOFn markers.
  163957. * Note that we do not emit the SOF until we have emitted the DQT(s).
  163958. * This avoids compatibility problems with incorrect implementations that
  163959. * try to error-check the quant table numbers as soon as they see the SOF.
  163960. */
  163961. METHODDEF(void)
  163962. write_frame_header (j_compress_ptr cinfo)
  163963. {
  163964. int ci, prec;
  163965. boolean is_baseline;
  163966. jpeg_component_info *compptr;
  163967. /* Emit DQT for each quantization table.
  163968. * Note that emit_dqt() suppresses any duplicate tables.
  163969. */
  163970. prec = 0;
  163971. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163972. ci++, compptr++) {
  163973. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  163974. }
  163975. /* now prec is nonzero iff there are any 16-bit quant tables. */
  163976. /* Check for a non-baseline specification.
  163977. * Note we assume that Huffman table numbers won't be changed later.
  163978. */
  163979. if (cinfo->arith_code || cinfo->progressive_mode ||
  163980. cinfo->data_precision != 8) {
  163981. is_baseline = FALSE;
  163982. } else {
  163983. is_baseline = TRUE;
  163984. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163985. ci++, compptr++) {
  163986. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  163987. is_baseline = FALSE;
  163988. }
  163989. if (prec && is_baseline) {
  163990. is_baseline = FALSE;
  163991. /* If it's baseline except for quantizer size, warn the user */
  163992. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  163993. }
  163994. }
  163995. /* Emit the proper SOF marker */
  163996. if (cinfo->arith_code) {
  163997. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  163998. } else {
  163999. if (cinfo->progressive_mode)
  164000. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164001. else if (is_baseline)
  164002. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164003. else
  164004. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164005. }
  164006. }
  164007. /*
  164008. * Write scan header.
  164009. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164010. * Compressed data will be written following the SOS.
  164011. */
  164012. METHODDEF(void)
  164013. write_scan_header (j_compress_ptr cinfo)
  164014. {
  164015. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164016. int i;
  164017. jpeg_component_info *compptr;
  164018. if (cinfo->arith_code) {
  164019. /* Emit arith conditioning info. We may have some duplication
  164020. * if the file has multiple scans, but it's so small it's hardly
  164021. * worth worrying about.
  164022. */
  164023. emit_dac(cinfo);
  164024. } else {
  164025. /* Emit Huffman tables.
  164026. * Note that emit_dht() suppresses any duplicate tables.
  164027. */
  164028. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164029. compptr = cinfo->cur_comp_info[i];
  164030. if (cinfo->progressive_mode) {
  164031. /* Progressive mode: only DC or only AC tables are used in one scan */
  164032. if (cinfo->Ss == 0) {
  164033. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164034. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164035. } else {
  164036. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164037. }
  164038. } else {
  164039. /* Sequential mode: need both DC and AC tables */
  164040. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164041. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164042. }
  164043. }
  164044. }
  164045. /* Emit DRI if required --- note that DRI value could change for each scan.
  164046. * We avoid wasting space with unnecessary DRIs, however.
  164047. */
  164048. if (cinfo->restart_interval != marker->last_restart_interval) {
  164049. emit_dri(cinfo);
  164050. marker->last_restart_interval = cinfo->restart_interval;
  164051. }
  164052. emit_sos(cinfo);
  164053. }
  164054. /*
  164055. * Write datastream trailer.
  164056. */
  164057. METHODDEF(void)
  164058. write_file_trailer (j_compress_ptr cinfo)
  164059. {
  164060. emit_marker(cinfo, M_EOI);
  164061. }
  164062. /*
  164063. * Write an abbreviated table-specification datastream.
  164064. * This consists of SOI, DQT and DHT tables, and EOI.
  164065. * Any table that is defined and not marked sent_table = TRUE will be
  164066. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164067. */
  164068. METHODDEF(void)
  164069. write_tables_only (j_compress_ptr cinfo)
  164070. {
  164071. int i;
  164072. emit_marker(cinfo, M_SOI);
  164073. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164074. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164075. (void) emit_dqt(cinfo, i);
  164076. }
  164077. if (! cinfo->arith_code) {
  164078. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164079. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164080. emit_dht(cinfo, i, FALSE);
  164081. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164082. emit_dht(cinfo, i, TRUE);
  164083. }
  164084. }
  164085. emit_marker(cinfo, M_EOI);
  164086. }
  164087. /*
  164088. * Initialize the marker writer module.
  164089. */
  164090. GLOBAL(void)
  164091. jinit_marker_writer (j_compress_ptr cinfo)
  164092. {
  164093. my_marker_ptr marker;
  164094. /* Create the subobject */
  164095. marker = (my_marker_ptr)
  164096. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164097. SIZEOF(my_marker_writer));
  164098. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164099. /* Initialize method pointers */
  164100. marker->pub.write_file_header = write_file_header;
  164101. marker->pub.write_frame_header = write_frame_header;
  164102. marker->pub.write_scan_header = write_scan_header;
  164103. marker->pub.write_file_trailer = write_file_trailer;
  164104. marker->pub.write_tables_only = write_tables_only;
  164105. marker->pub.write_marker_header = write_marker_header;
  164106. marker->pub.write_marker_byte = write_marker_byte;
  164107. /* Initialize private state */
  164108. marker->last_restart_interval = 0;
  164109. }
  164110. /*** End of inlined file: jcmarker.c ***/
  164111. /*** Start of inlined file: jcmaster.c ***/
  164112. #define JPEG_INTERNALS
  164113. /* Private state */
  164114. typedef enum {
  164115. main_pass, /* input data, also do first output step */
  164116. huff_opt_pass, /* Huffman code optimization pass */
  164117. output_pass /* data output pass */
  164118. } c_pass_type;
  164119. typedef struct {
  164120. struct jpeg_comp_master pub; /* public fields */
  164121. c_pass_type pass_type; /* the type of the current pass */
  164122. int pass_number; /* # of passes completed */
  164123. int total_passes; /* total # of passes needed */
  164124. int scan_number; /* current index in scan_info[] */
  164125. } my_comp_master;
  164126. typedef my_comp_master * my_master_ptr;
  164127. /*
  164128. * Support routines that do various essential calculations.
  164129. */
  164130. LOCAL(void)
  164131. initial_setup (j_compress_ptr cinfo)
  164132. /* Do computations that are needed before master selection phase */
  164133. {
  164134. int ci;
  164135. jpeg_component_info *compptr;
  164136. long samplesperrow;
  164137. JDIMENSION jd_samplesperrow;
  164138. /* Sanity check on image dimensions */
  164139. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164140. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164141. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164142. /* Make sure image isn't bigger than I can handle */
  164143. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164144. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164145. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164146. /* Width of an input scanline must be representable as JDIMENSION. */
  164147. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164148. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164149. if ((long) jd_samplesperrow != samplesperrow)
  164150. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164151. /* For now, precision must match compiled-in value... */
  164152. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164153. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164154. /* Check that number of components won't exceed internal array sizes */
  164155. if (cinfo->num_components > MAX_COMPONENTS)
  164156. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164157. MAX_COMPONENTS);
  164158. /* Compute maximum sampling factors; check factor validity */
  164159. cinfo->max_h_samp_factor = 1;
  164160. cinfo->max_v_samp_factor = 1;
  164161. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164162. ci++, compptr++) {
  164163. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164164. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164165. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164166. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164167. compptr->h_samp_factor);
  164168. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164169. compptr->v_samp_factor);
  164170. }
  164171. /* Compute dimensions of components */
  164172. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164173. ci++, compptr++) {
  164174. /* Fill in the correct component_index value; don't rely on application */
  164175. compptr->component_index = ci;
  164176. /* For compression, we never do DCT scaling. */
  164177. compptr->DCT_scaled_size = DCTSIZE;
  164178. /* Size in DCT blocks */
  164179. compptr->width_in_blocks = (JDIMENSION)
  164180. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164181. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164182. compptr->height_in_blocks = (JDIMENSION)
  164183. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164184. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164185. /* Size in samples */
  164186. compptr->downsampled_width = (JDIMENSION)
  164187. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164188. (long) cinfo->max_h_samp_factor);
  164189. compptr->downsampled_height = (JDIMENSION)
  164190. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164191. (long) cinfo->max_v_samp_factor);
  164192. /* Mark component needed (this flag isn't actually used for compression) */
  164193. compptr->component_needed = TRUE;
  164194. }
  164195. /* Compute number of fully interleaved MCU rows (number of times that
  164196. * main controller will call coefficient controller).
  164197. */
  164198. cinfo->total_iMCU_rows = (JDIMENSION)
  164199. jdiv_round_up((long) cinfo->image_height,
  164200. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164201. }
  164202. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164203. LOCAL(void)
  164204. validate_script (j_compress_ptr cinfo)
  164205. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164206. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164207. */
  164208. {
  164209. const jpeg_scan_info * scanptr;
  164210. int scanno, ncomps, ci, coefi, thisi;
  164211. int Ss, Se, Ah, Al;
  164212. boolean component_sent[MAX_COMPONENTS];
  164213. #ifdef C_PROGRESSIVE_SUPPORTED
  164214. int * last_bitpos_ptr;
  164215. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164216. /* -1 until that coefficient has been seen; then last Al for it */
  164217. #endif
  164218. if (cinfo->num_scans <= 0)
  164219. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164220. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164221. * for progressive JPEG, no scan can have this.
  164222. */
  164223. scanptr = cinfo->scan_info;
  164224. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164225. #ifdef C_PROGRESSIVE_SUPPORTED
  164226. cinfo->progressive_mode = TRUE;
  164227. last_bitpos_ptr = & last_bitpos[0][0];
  164228. for (ci = 0; ci < cinfo->num_components; ci++)
  164229. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164230. *last_bitpos_ptr++ = -1;
  164231. #else
  164232. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164233. #endif
  164234. } else {
  164235. cinfo->progressive_mode = FALSE;
  164236. for (ci = 0; ci < cinfo->num_components; ci++)
  164237. component_sent[ci] = FALSE;
  164238. }
  164239. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164240. /* Validate component indexes */
  164241. ncomps = scanptr->comps_in_scan;
  164242. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164243. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164244. for (ci = 0; ci < ncomps; ci++) {
  164245. thisi = scanptr->component_index[ci];
  164246. if (thisi < 0 || thisi >= cinfo->num_components)
  164247. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164248. /* Components must appear in SOF order within each scan */
  164249. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164250. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164251. }
  164252. /* Validate progression parameters */
  164253. Ss = scanptr->Ss;
  164254. Se = scanptr->Se;
  164255. Ah = scanptr->Ah;
  164256. Al = scanptr->Al;
  164257. if (cinfo->progressive_mode) {
  164258. #ifdef C_PROGRESSIVE_SUPPORTED
  164259. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164260. * seems wrong: the upper bound ought to depend on data precision.
  164261. * Perhaps they really meant 0..N+1 for N-bit precision.
  164262. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164263. * out-of-range reconstructed DC values during the first DC scan,
  164264. * which might cause problems for some decoders.
  164265. */
  164266. #if BITS_IN_JSAMPLE == 8
  164267. #define MAX_AH_AL 10
  164268. #else
  164269. #define MAX_AH_AL 13
  164270. #endif
  164271. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164272. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  164273. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164274. if (Ss == 0) {
  164275. if (Se != 0) /* DC and AC together not OK */
  164276. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164277. } else {
  164278. if (ncomps != 1) /* AC scans must be for only one component */
  164279. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164280. }
  164281. for (ci = 0; ci < ncomps; ci++) {
  164282. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  164283. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  164284. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164285. for (coefi = Ss; coefi <= Se; coefi++) {
  164286. if (last_bitpos_ptr[coefi] < 0) {
  164287. /* first scan of this coefficient */
  164288. if (Ah != 0)
  164289. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164290. } else {
  164291. /* not first scan */
  164292. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  164293. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164294. }
  164295. last_bitpos_ptr[coefi] = Al;
  164296. }
  164297. }
  164298. #endif
  164299. } else {
  164300. /* For sequential JPEG, all progression parameters must be these: */
  164301. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  164302. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164303. /* Make sure components are not sent twice */
  164304. for (ci = 0; ci < ncomps; ci++) {
  164305. thisi = scanptr->component_index[ci];
  164306. if (component_sent[thisi])
  164307. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164308. component_sent[thisi] = TRUE;
  164309. }
  164310. }
  164311. }
  164312. /* Now verify that everything got sent. */
  164313. if (cinfo->progressive_mode) {
  164314. #ifdef C_PROGRESSIVE_SUPPORTED
  164315. /* For progressive mode, we only check that at least some DC data
  164316. * got sent for each component; the spec does not require that all bits
  164317. * of all coefficients be transmitted. Would it be wiser to enforce
  164318. * transmission of all coefficient bits??
  164319. */
  164320. for (ci = 0; ci < cinfo->num_components; ci++) {
  164321. if (last_bitpos[ci][0] < 0)
  164322. ERREXIT(cinfo, JERR_MISSING_DATA);
  164323. }
  164324. #endif
  164325. } else {
  164326. for (ci = 0; ci < cinfo->num_components; ci++) {
  164327. if (! component_sent[ci])
  164328. ERREXIT(cinfo, JERR_MISSING_DATA);
  164329. }
  164330. }
  164331. }
  164332. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164333. LOCAL(void)
  164334. select_scan_parameters (j_compress_ptr cinfo)
  164335. /* Set up the scan parameters for the current scan */
  164336. {
  164337. int ci;
  164338. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164339. if (cinfo->scan_info != NULL) {
  164340. /* Prepare for current scan --- the script is already validated */
  164341. my_master_ptr master = (my_master_ptr) cinfo->master;
  164342. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164343. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164344. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164345. cinfo->cur_comp_info[ci] =
  164346. &cinfo->comp_info[scanptr->component_index[ci]];
  164347. }
  164348. cinfo->Ss = scanptr->Ss;
  164349. cinfo->Se = scanptr->Se;
  164350. cinfo->Ah = scanptr->Ah;
  164351. cinfo->Al = scanptr->Al;
  164352. }
  164353. else
  164354. #endif
  164355. {
  164356. /* Prepare for single sequential-JPEG scan containing all components */
  164357. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164358. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164359. MAX_COMPS_IN_SCAN);
  164360. cinfo->comps_in_scan = cinfo->num_components;
  164361. for (ci = 0; ci < cinfo->num_components; ci++) {
  164362. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164363. }
  164364. cinfo->Ss = 0;
  164365. cinfo->Se = DCTSIZE2-1;
  164366. cinfo->Ah = 0;
  164367. cinfo->Al = 0;
  164368. }
  164369. }
  164370. LOCAL(void)
  164371. per_scan_setup (j_compress_ptr cinfo)
  164372. /* Do computations that are needed before processing a JPEG scan */
  164373. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164374. {
  164375. int ci, mcublks, tmp;
  164376. jpeg_component_info *compptr;
  164377. if (cinfo->comps_in_scan == 1) {
  164378. /* Noninterleaved (single-component) scan */
  164379. compptr = cinfo->cur_comp_info[0];
  164380. /* Overall image size in MCUs */
  164381. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164382. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164383. /* For noninterleaved scan, always one block per MCU */
  164384. compptr->MCU_width = 1;
  164385. compptr->MCU_height = 1;
  164386. compptr->MCU_blocks = 1;
  164387. compptr->MCU_sample_width = DCTSIZE;
  164388. compptr->last_col_width = 1;
  164389. /* For noninterleaved scans, it is convenient to define last_row_height
  164390. * as the number of block rows present in the last iMCU row.
  164391. */
  164392. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164393. if (tmp == 0) tmp = compptr->v_samp_factor;
  164394. compptr->last_row_height = tmp;
  164395. /* Prepare array describing MCU composition */
  164396. cinfo->blocks_in_MCU = 1;
  164397. cinfo->MCU_membership[0] = 0;
  164398. } else {
  164399. /* Interleaved (multi-component) scan */
  164400. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164401. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164402. MAX_COMPS_IN_SCAN);
  164403. /* Overall image size in MCUs */
  164404. cinfo->MCUs_per_row = (JDIMENSION)
  164405. jdiv_round_up((long) cinfo->image_width,
  164406. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164407. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164408. jdiv_round_up((long) cinfo->image_height,
  164409. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164410. cinfo->blocks_in_MCU = 0;
  164411. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164412. compptr = cinfo->cur_comp_info[ci];
  164413. /* Sampling factors give # of blocks of component in each MCU */
  164414. compptr->MCU_width = compptr->h_samp_factor;
  164415. compptr->MCU_height = compptr->v_samp_factor;
  164416. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164417. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  164418. /* Figure number of non-dummy blocks in last MCU column & row */
  164419. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164420. if (tmp == 0) tmp = compptr->MCU_width;
  164421. compptr->last_col_width = tmp;
  164422. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164423. if (tmp == 0) tmp = compptr->MCU_height;
  164424. compptr->last_row_height = tmp;
  164425. /* Prepare array describing MCU composition */
  164426. mcublks = compptr->MCU_blocks;
  164427. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  164428. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164429. while (mcublks-- > 0) {
  164430. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  164431. }
  164432. }
  164433. }
  164434. /* Convert restart specified in rows to actual MCU count. */
  164435. /* Note that count must fit in 16 bits, so we provide limiting. */
  164436. if (cinfo->restart_in_rows > 0) {
  164437. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  164438. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  164439. }
  164440. }
  164441. /*
  164442. * Per-pass setup.
  164443. * This is called at the beginning of each pass. We determine which modules
  164444. * will be active during this pass and give them appropriate start_pass calls.
  164445. * We also set is_last_pass to indicate whether any more passes will be
  164446. * required.
  164447. */
  164448. METHODDEF(void)
  164449. prepare_for_pass (j_compress_ptr cinfo)
  164450. {
  164451. my_master_ptr master = (my_master_ptr) cinfo->master;
  164452. switch (master->pass_type) {
  164453. case main_pass:
  164454. /* Initial pass: will collect input data, and do either Huffman
  164455. * optimization or data output for the first scan.
  164456. */
  164457. select_scan_parameters(cinfo);
  164458. per_scan_setup(cinfo);
  164459. if (! cinfo->raw_data_in) {
  164460. (*cinfo->cconvert->start_pass) (cinfo);
  164461. (*cinfo->downsample->start_pass) (cinfo);
  164462. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  164463. }
  164464. (*cinfo->fdct->start_pass) (cinfo);
  164465. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  164466. (*cinfo->coef->start_pass) (cinfo,
  164467. (master->total_passes > 1 ?
  164468. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  164469. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  164470. if (cinfo->optimize_coding) {
  164471. /* No immediate data output; postpone writing frame/scan headers */
  164472. master->pub.call_pass_startup = FALSE;
  164473. } else {
  164474. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  164475. master->pub.call_pass_startup = TRUE;
  164476. }
  164477. break;
  164478. #ifdef ENTROPY_OPT_SUPPORTED
  164479. case huff_opt_pass:
  164480. /* Do Huffman optimization for a scan after the first one. */
  164481. select_scan_parameters(cinfo);
  164482. per_scan_setup(cinfo);
  164483. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  164484. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  164485. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164486. master->pub.call_pass_startup = FALSE;
  164487. break;
  164488. }
  164489. /* Special case: Huffman DC refinement scans need no Huffman table
  164490. * and therefore we can skip the optimization pass for them.
  164491. */
  164492. master->pass_type = output_pass;
  164493. master->pass_number++;
  164494. /*FALLTHROUGH*/
  164495. #endif
  164496. case output_pass:
  164497. /* Do a data-output pass. */
  164498. /* We need not repeat per-scan setup if prior optimization pass did it. */
  164499. if (! cinfo->optimize_coding) {
  164500. select_scan_parameters(cinfo);
  164501. per_scan_setup(cinfo);
  164502. }
  164503. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  164504. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164505. /* We emit frame/scan headers now */
  164506. if (master->scan_number == 0)
  164507. (*cinfo->marker->write_frame_header) (cinfo);
  164508. (*cinfo->marker->write_scan_header) (cinfo);
  164509. master->pub.call_pass_startup = FALSE;
  164510. break;
  164511. default:
  164512. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164513. }
  164514. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  164515. /* Set up progress monitor's pass info if present */
  164516. if (cinfo->progress != NULL) {
  164517. cinfo->progress->completed_passes = master->pass_number;
  164518. cinfo->progress->total_passes = master->total_passes;
  164519. }
  164520. }
  164521. /*
  164522. * Special start-of-pass hook.
  164523. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  164524. * In single-pass processing, we need this hook because we don't want to
  164525. * write frame/scan headers during jpeg_start_compress; we want to let the
  164526. * application write COM markers etc. between jpeg_start_compress and the
  164527. * jpeg_write_scanlines loop.
  164528. * In multi-pass processing, this routine is not used.
  164529. */
  164530. METHODDEF(void)
  164531. pass_startup (j_compress_ptr cinfo)
  164532. {
  164533. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  164534. (*cinfo->marker->write_frame_header) (cinfo);
  164535. (*cinfo->marker->write_scan_header) (cinfo);
  164536. }
  164537. /*
  164538. * Finish up at end of pass.
  164539. */
  164540. METHODDEF(void)
  164541. finish_pass_master (j_compress_ptr cinfo)
  164542. {
  164543. my_master_ptr master = (my_master_ptr) cinfo->master;
  164544. /* The entropy coder always needs an end-of-pass call,
  164545. * either to analyze statistics or to flush its output buffer.
  164546. */
  164547. (*cinfo->entropy->finish_pass) (cinfo);
  164548. /* Update state for next pass */
  164549. switch (master->pass_type) {
  164550. case main_pass:
  164551. /* next pass is either output of scan 0 (after optimization)
  164552. * or output of scan 1 (if no optimization).
  164553. */
  164554. master->pass_type = output_pass;
  164555. if (! cinfo->optimize_coding)
  164556. master->scan_number++;
  164557. break;
  164558. case huff_opt_pass:
  164559. /* next pass is always output of current scan */
  164560. master->pass_type = output_pass;
  164561. break;
  164562. case output_pass:
  164563. /* next pass is either optimization or output of next scan */
  164564. if (cinfo->optimize_coding)
  164565. master->pass_type = huff_opt_pass;
  164566. master->scan_number++;
  164567. break;
  164568. }
  164569. master->pass_number++;
  164570. }
  164571. /*
  164572. * Initialize master compression control.
  164573. */
  164574. GLOBAL(void)
  164575. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  164576. {
  164577. my_master_ptr master;
  164578. master = (my_master_ptr)
  164579. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164580. SIZEOF(my_comp_master));
  164581. cinfo->master = (struct jpeg_comp_master *) master;
  164582. master->pub.prepare_for_pass = prepare_for_pass;
  164583. master->pub.pass_startup = pass_startup;
  164584. master->pub.finish_pass = finish_pass_master;
  164585. master->pub.is_last_pass = FALSE;
  164586. /* Validate parameters, determine derived values */
  164587. initial_setup(cinfo);
  164588. if (cinfo->scan_info != NULL) {
  164589. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164590. validate_script(cinfo);
  164591. #else
  164592. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164593. #endif
  164594. } else {
  164595. cinfo->progressive_mode = FALSE;
  164596. cinfo->num_scans = 1;
  164597. }
  164598. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  164599. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  164600. /* Initialize my private state */
  164601. if (transcode_only) {
  164602. /* no main pass in transcoding */
  164603. if (cinfo->optimize_coding)
  164604. master->pass_type = huff_opt_pass;
  164605. else
  164606. master->pass_type = output_pass;
  164607. } else {
  164608. /* for normal compression, first pass is always this type: */
  164609. master->pass_type = main_pass;
  164610. }
  164611. master->scan_number = 0;
  164612. master->pass_number = 0;
  164613. if (cinfo->optimize_coding)
  164614. master->total_passes = cinfo->num_scans * 2;
  164615. else
  164616. master->total_passes = cinfo->num_scans;
  164617. }
  164618. /*** End of inlined file: jcmaster.c ***/
  164619. /*** Start of inlined file: jcomapi.c ***/
  164620. #define JPEG_INTERNALS
  164621. /*
  164622. * Abort processing of a JPEG compression or decompression operation,
  164623. * but don't destroy the object itself.
  164624. *
  164625. * For this, we merely clean up all the nonpermanent memory pools.
  164626. * Note that temp files (virtual arrays) are not allowed to belong to
  164627. * the permanent pool, so we will be able to close all temp files here.
  164628. * Closing a data source or destination, if necessary, is the application's
  164629. * responsibility.
  164630. */
  164631. GLOBAL(void)
  164632. jpeg_abort (j_common_ptr cinfo)
  164633. {
  164634. int pool;
  164635. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  164636. if (cinfo->mem == NULL)
  164637. return;
  164638. /* Releasing pools in reverse order might help avoid fragmentation
  164639. * with some (brain-damaged) malloc libraries.
  164640. */
  164641. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  164642. (*cinfo->mem->free_pool) (cinfo, pool);
  164643. }
  164644. /* Reset overall state for possible reuse of object */
  164645. if (cinfo->is_decompressor) {
  164646. cinfo->global_state = DSTATE_START;
  164647. /* Try to keep application from accessing now-deleted marker list.
  164648. * A bit kludgy to do it here, but this is the most central place.
  164649. */
  164650. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  164651. } else {
  164652. cinfo->global_state = CSTATE_START;
  164653. }
  164654. }
  164655. /*
  164656. * Destruction of a JPEG object.
  164657. *
  164658. * Everything gets deallocated except the master jpeg_compress_struct itself
  164659. * and the error manager struct. Both of these are supplied by the application
  164660. * and must be freed, if necessary, by the application. (Often they are on
  164661. * the stack and so don't need to be freed anyway.)
  164662. * Closing a data source or destination, if necessary, is the application's
  164663. * responsibility.
  164664. */
  164665. GLOBAL(void)
  164666. jpeg_destroy (j_common_ptr cinfo)
  164667. {
  164668. /* We need only tell the memory manager to release everything. */
  164669. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  164670. if (cinfo->mem != NULL)
  164671. (*cinfo->mem->self_destruct) (cinfo);
  164672. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  164673. cinfo->global_state = 0; /* mark it destroyed */
  164674. }
  164675. /*
  164676. * Convenience routines for allocating quantization and Huffman tables.
  164677. * (Would jutils.c be a more reasonable place to put these?)
  164678. */
  164679. GLOBAL(JQUANT_TBL *)
  164680. jpeg_alloc_quant_table (j_common_ptr cinfo)
  164681. {
  164682. JQUANT_TBL *tbl;
  164683. tbl = (JQUANT_TBL *)
  164684. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  164685. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164686. return tbl;
  164687. }
  164688. GLOBAL(JHUFF_TBL *)
  164689. jpeg_alloc_huff_table (j_common_ptr cinfo)
  164690. {
  164691. JHUFF_TBL *tbl;
  164692. tbl = (JHUFF_TBL *)
  164693. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  164694. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164695. return tbl;
  164696. }
  164697. /*** End of inlined file: jcomapi.c ***/
  164698. /*** Start of inlined file: jcparam.c ***/
  164699. #define JPEG_INTERNALS
  164700. /*
  164701. * Quantization table setup routines
  164702. */
  164703. GLOBAL(void)
  164704. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  164705. const unsigned int *basic_table,
  164706. int scale_factor, boolean force_baseline)
  164707. /* Define a quantization table equal to the basic_table times
  164708. * a scale factor (given as a percentage).
  164709. * If force_baseline is TRUE, the computed quantization table entries
  164710. * are limited to 1..255 for JPEG baseline compatibility.
  164711. */
  164712. {
  164713. JQUANT_TBL ** qtblptr;
  164714. int i;
  164715. long temp;
  164716. /* Safety check to ensure start_compress not called yet. */
  164717. if (cinfo->global_state != CSTATE_START)
  164718. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164719. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  164720. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  164721. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  164722. if (*qtblptr == NULL)
  164723. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  164724. for (i = 0; i < DCTSIZE2; i++) {
  164725. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  164726. /* limit the values to the valid range */
  164727. if (temp <= 0L) temp = 1L;
  164728. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  164729. if (force_baseline && temp > 255L)
  164730. temp = 255L; /* limit to baseline range if requested */
  164731. (*qtblptr)->quantval[i] = (UINT16) temp;
  164732. }
  164733. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  164734. (*qtblptr)->sent_table = FALSE;
  164735. }
  164736. GLOBAL(void)
  164737. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  164738. boolean force_baseline)
  164739. /* Set or change the 'quality' (quantization) setting, using default tables
  164740. * and a straight percentage-scaling quality scale. In most cases it's better
  164741. * to use jpeg_set_quality (below); this entry point is provided for
  164742. * applications that insist on a linear percentage scaling.
  164743. */
  164744. {
  164745. /* These are the sample quantization tables given in JPEG spec section K.1.
  164746. * The spec says that the values given produce "good" quality, and
  164747. * when divided by 2, "very good" quality.
  164748. */
  164749. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  164750. 16, 11, 10, 16, 24, 40, 51, 61,
  164751. 12, 12, 14, 19, 26, 58, 60, 55,
  164752. 14, 13, 16, 24, 40, 57, 69, 56,
  164753. 14, 17, 22, 29, 51, 87, 80, 62,
  164754. 18, 22, 37, 56, 68, 109, 103, 77,
  164755. 24, 35, 55, 64, 81, 104, 113, 92,
  164756. 49, 64, 78, 87, 103, 121, 120, 101,
  164757. 72, 92, 95, 98, 112, 100, 103, 99
  164758. };
  164759. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  164760. 17, 18, 24, 47, 99, 99, 99, 99,
  164761. 18, 21, 26, 66, 99, 99, 99, 99,
  164762. 24, 26, 56, 99, 99, 99, 99, 99,
  164763. 47, 66, 99, 99, 99, 99, 99, 99,
  164764. 99, 99, 99, 99, 99, 99, 99, 99,
  164765. 99, 99, 99, 99, 99, 99, 99, 99,
  164766. 99, 99, 99, 99, 99, 99, 99, 99,
  164767. 99, 99, 99, 99, 99, 99, 99, 99
  164768. };
  164769. /* Set up two quantization tables using the specified scaling */
  164770. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  164771. scale_factor, force_baseline);
  164772. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  164773. scale_factor, force_baseline);
  164774. }
  164775. GLOBAL(int)
  164776. jpeg_quality_scaling (int quality)
  164777. /* Convert a user-specified quality rating to a percentage scaling factor
  164778. * for an underlying quantization table, using our recommended scaling curve.
  164779. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  164780. */
  164781. {
  164782. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  164783. if (quality <= 0) quality = 1;
  164784. if (quality > 100) quality = 100;
  164785. /* The basic table is used as-is (scaling 100) for a quality of 50.
  164786. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  164787. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  164788. * to make all the table entries 1 (hence, minimum quantization loss).
  164789. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  164790. */
  164791. if (quality < 50)
  164792. quality = 5000 / quality;
  164793. else
  164794. quality = 200 - quality*2;
  164795. return quality;
  164796. }
  164797. GLOBAL(void)
  164798. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  164799. /* Set or change the 'quality' (quantization) setting, using default tables.
  164800. * This is the standard quality-adjusting entry point for typical user
  164801. * interfaces; only those who want detailed control over quantization tables
  164802. * would use the preceding three routines directly.
  164803. */
  164804. {
  164805. /* Convert user 0-100 rating to percentage scaling */
  164806. quality = jpeg_quality_scaling(quality);
  164807. /* Set up standard quality tables */
  164808. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  164809. }
  164810. /*
  164811. * Huffman table setup routines
  164812. */
  164813. LOCAL(void)
  164814. add_huff_table (j_compress_ptr cinfo,
  164815. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  164816. /* Define a Huffman table */
  164817. {
  164818. int nsymbols, len;
  164819. if (*htblptr == NULL)
  164820. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164821. /* Copy the number-of-symbols-of-each-code-length counts */
  164822. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  164823. /* Validate the counts. We do this here mainly so we can copy the right
  164824. * number of symbols from the val[] array, without risking marching off
  164825. * the end of memory. jchuff.c will do a more thorough test later.
  164826. */
  164827. nsymbols = 0;
  164828. for (len = 1; len <= 16; len++)
  164829. nsymbols += bits[len];
  164830. if (nsymbols < 1 || nsymbols > 256)
  164831. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164832. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  164833. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  164834. (*htblptr)->sent_table = FALSE;
  164835. }
  164836. LOCAL(void)
  164837. std_huff_tables (j_compress_ptr cinfo)
  164838. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  164839. /* IMPORTANT: these are only valid for 8-bit data precision! */
  164840. {
  164841. static const UINT8 bits_dc_luminance[17] =
  164842. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  164843. static const UINT8 val_dc_luminance[] =
  164844. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  164845. static const UINT8 bits_dc_chrominance[17] =
  164846. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  164847. static const UINT8 val_dc_chrominance[] =
  164848. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  164849. static const UINT8 bits_ac_luminance[17] =
  164850. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  164851. static const UINT8 val_ac_luminance[] =
  164852. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  164853. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  164854. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  164855. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  164856. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  164857. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  164858. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  164859. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  164860. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  164861. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  164862. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  164863. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  164864. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  164865. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  164866. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  164867. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  164868. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  164869. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  164870. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  164871. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  164872. 0xf9, 0xfa };
  164873. static const UINT8 bits_ac_chrominance[17] =
  164874. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  164875. static const UINT8 val_ac_chrominance[] =
  164876. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  164877. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  164878. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  164879. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  164880. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  164881. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  164882. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  164883. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  164884. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  164885. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  164886. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  164887. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  164888. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  164889. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  164890. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  164891. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  164892. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  164893. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  164894. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  164895. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  164896. 0xf9, 0xfa };
  164897. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  164898. bits_dc_luminance, val_dc_luminance);
  164899. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  164900. bits_ac_luminance, val_ac_luminance);
  164901. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  164902. bits_dc_chrominance, val_dc_chrominance);
  164903. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  164904. bits_ac_chrominance, val_ac_chrominance);
  164905. }
  164906. /*
  164907. * Default parameter setup for compression.
  164908. *
  164909. * Applications that don't choose to use this routine must do their
  164910. * own setup of all these parameters. Alternately, you can call this
  164911. * to establish defaults and then alter parameters selectively. This
  164912. * is the recommended approach since, if we add any new parameters,
  164913. * your code will still work (they'll be set to reasonable defaults).
  164914. */
  164915. GLOBAL(void)
  164916. jpeg_set_defaults (j_compress_ptr cinfo)
  164917. {
  164918. int i;
  164919. /* Safety check to ensure start_compress not called yet. */
  164920. if (cinfo->global_state != CSTATE_START)
  164921. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164922. /* Allocate comp_info array large enough for maximum component count.
  164923. * Array is made permanent in case application wants to compress
  164924. * multiple images at same param settings.
  164925. */
  164926. if (cinfo->comp_info == NULL)
  164927. cinfo->comp_info = (jpeg_component_info *)
  164928. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164929. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  164930. /* Initialize everything not dependent on the color space */
  164931. cinfo->data_precision = BITS_IN_JSAMPLE;
  164932. /* Set up two quantization tables using default quality of 75 */
  164933. jpeg_set_quality(cinfo, 75, TRUE);
  164934. /* Set up two Huffman tables */
  164935. std_huff_tables(cinfo);
  164936. /* Initialize default arithmetic coding conditioning */
  164937. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164938. cinfo->arith_dc_L[i] = 0;
  164939. cinfo->arith_dc_U[i] = 1;
  164940. cinfo->arith_ac_K[i] = 5;
  164941. }
  164942. /* Default is no multiple-scan output */
  164943. cinfo->scan_info = NULL;
  164944. cinfo->num_scans = 0;
  164945. /* Expect normal source image, not raw downsampled data */
  164946. cinfo->raw_data_in = FALSE;
  164947. /* Use Huffman coding, not arithmetic coding, by default */
  164948. cinfo->arith_code = FALSE;
  164949. /* By default, don't do extra passes to optimize entropy coding */
  164950. cinfo->optimize_coding = FALSE;
  164951. /* The standard Huffman tables are only valid for 8-bit data precision.
  164952. * If the precision is higher, force optimization on so that usable
  164953. * tables will be computed. This test can be removed if default tables
  164954. * are supplied that are valid for the desired precision.
  164955. */
  164956. if (cinfo->data_precision > 8)
  164957. cinfo->optimize_coding = TRUE;
  164958. /* By default, use the simpler non-cosited sampling alignment */
  164959. cinfo->CCIR601_sampling = FALSE;
  164960. /* No input smoothing */
  164961. cinfo->smoothing_factor = 0;
  164962. /* DCT algorithm preference */
  164963. cinfo->dct_method = JDCT_DEFAULT;
  164964. /* No restart markers */
  164965. cinfo->restart_interval = 0;
  164966. cinfo->restart_in_rows = 0;
  164967. /* Fill in default JFIF marker parameters. Note that whether the marker
  164968. * will actually be written is determined by jpeg_set_colorspace.
  164969. *
  164970. * By default, the library emits JFIF version code 1.01.
  164971. * An application that wants to emit JFIF 1.02 extension markers should set
  164972. * JFIF_minor_version to 2. We could probably get away with just defaulting
  164973. * to 1.02, but there may still be some decoders in use that will complain
  164974. * about that; saying 1.01 should minimize compatibility problems.
  164975. */
  164976. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  164977. cinfo->JFIF_minor_version = 1;
  164978. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  164979. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  164980. cinfo->Y_density = 1;
  164981. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  164982. jpeg_default_colorspace(cinfo);
  164983. }
  164984. /*
  164985. * Select an appropriate JPEG colorspace for in_color_space.
  164986. */
  164987. GLOBAL(void)
  164988. jpeg_default_colorspace (j_compress_ptr cinfo)
  164989. {
  164990. switch (cinfo->in_color_space) {
  164991. case JCS_GRAYSCALE:
  164992. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  164993. break;
  164994. case JCS_RGB:
  164995. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  164996. break;
  164997. case JCS_YCbCr:
  164998. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  164999. break;
  165000. case JCS_CMYK:
  165001. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165002. break;
  165003. case JCS_YCCK:
  165004. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165005. break;
  165006. case JCS_UNKNOWN:
  165007. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165008. break;
  165009. default:
  165010. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165011. }
  165012. }
  165013. /*
  165014. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165015. */
  165016. GLOBAL(void)
  165017. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165018. {
  165019. jpeg_component_info * compptr;
  165020. int ci;
  165021. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165022. (compptr = &cinfo->comp_info[index], \
  165023. compptr->component_id = (id), \
  165024. compptr->h_samp_factor = (hsamp), \
  165025. compptr->v_samp_factor = (vsamp), \
  165026. compptr->quant_tbl_no = (quant), \
  165027. compptr->dc_tbl_no = (dctbl), \
  165028. compptr->ac_tbl_no = (actbl) )
  165029. /* Safety check to ensure start_compress not called yet. */
  165030. if (cinfo->global_state != CSTATE_START)
  165031. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165032. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165033. * tables 1 for chrominance components.
  165034. */
  165035. cinfo->jpeg_color_space = colorspace;
  165036. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165037. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165038. switch (colorspace) {
  165039. case JCS_GRAYSCALE:
  165040. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165041. cinfo->num_components = 1;
  165042. /* JFIF specifies component ID 1 */
  165043. SET_COMP(0, 1, 1,1, 0, 0,0);
  165044. break;
  165045. case JCS_RGB:
  165046. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165047. cinfo->num_components = 3;
  165048. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165049. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165050. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165051. break;
  165052. case JCS_YCbCr:
  165053. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165054. cinfo->num_components = 3;
  165055. /* JFIF specifies component IDs 1,2,3 */
  165056. /* We default to 2x2 subsamples of chrominance */
  165057. SET_COMP(0, 1, 2,2, 0, 0,0);
  165058. SET_COMP(1, 2, 1,1, 1, 1,1);
  165059. SET_COMP(2, 3, 1,1, 1, 1,1);
  165060. break;
  165061. case JCS_CMYK:
  165062. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165063. cinfo->num_components = 4;
  165064. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165065. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165066. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165067. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165068. break;
  165069. case JCS_YCCK:
  165070. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165071. cinfo->num_components = 4;
  165072. SET_COMP(0, 1, 2,2, 0, 0,0);
  165073. SET_COMP(1, 2, 1,1, 1, 1,1);
  165074. SET_COMP(2, 3, 1,1, 1, 1,1);
  165075. SET_COMP(3, 4, 2,2, 0, 0,0);
  165076. break;
  165077. case JCS_UNKNOWN:
  165078. cinfo->num_components = cinfo->input_components;
  165079. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165080. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165081. MAX_COMPONENTS);
  165082. for (ci = 0; ci < cinfo->num_components; ci++) {
  165083. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165084. }
  165085. break;
  165086. default:
  165087. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165088. }
  165089. }
  165090. #ifdef C_PROGRESSIVE_SUPPORTED
  165091. LOCAL(jpeg_scan_info *)
  165092. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165093. int Ss, int Se, int Ah, int Al)
  165094. /* Support routine: generate one scan for specified component */
  165095. {
  165096. scanptr->comps_in_scan = 1;
  165097. scanptr->component_index[0] = ci;
  165098. scanptr->Ss = Ss;
  165099. scanptr->Se = Se;
  165100. scanptr->Ah = Ah;
  165101. scanptr->Al = Al;
  165102. scanptr++;
  165103. return scanptr;
  165104. }
  165105. LOCAL(jpeg_scan_info *)
  165106. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165107. int Ss, int Se, int Ah, int Al)
  165108. /* Support routine: generate one scan for each component */
  165109. {
  165110. int ci;
  165111. for (ci = 0; ci < ncomps; ci++) {
  165112. scanptr->comps_in_scan = 1;
  165113. scanptr->component_index[0] = ci;
  165114. scanptr->Ss = Ss;
  165115. scanptr->Se = Se;
  165116. scanptr->Ah = Ah;
  165117. scanptr->Al = Al;
  165118. scanptr++;
  165119. }
  165120. return scanptr;
  165121. }
  165122. LOCAL(jpeg_scan_info *)
  165123. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165124. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165125. {
  165126. int ci;
  165127. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165128. /* Single interleaved DC scan */
  165129. scanptr->comps_in_scan = ncomps;
  165130. for (ci = 0; ci < ncomps; ci++)
  165131. scanptr->component_index[ci] = ci;
  165132. scanptr->Ss = scanptr->Se = 0;
  165133. scanptr->Ah = Ah;
  165134. scanptr->Al = Al;
  165135. scanptr++;
  165136. } else {
  165137. /* Noninterleaved DC scan for each component */
  165138. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165139. }
  165140. return scanptr;
  165141. }
  165142. /*
  165143. * Create a recommended progressive-JPEG script.
  165144. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165145. */
  165146. GLOBAL(void)
  165147. jpeg_simple_progression (j_compress_ptr cinfo)
  165148. {
  165149. int ncomps = cinfo->num_components;
  165150. int nscans;
  165151. jpeg_scan_info * scanptr;
  165152. /* Safety check to ensure start_compress not called yet. */
  165153. if (cinfo->global_state != CSTATE_START)
  165154. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165155. /* Figure space needed for script. Calculation must match code below! */
  165156. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165157. /* Custom script for YCbCr color images. */
  165158. nscans = 10;
  165159. } else {
  165160. /* All-purpose script for other color spaces. */
  165161. if (ncomps > MAX_COMPS_IN_SCAN)
  165162. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165163. else
  165164. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165165. }
  165166. /* Allocate space for script.
  165167. * We need to put it in the permanent pool in case the application performs
  165168. * multiple compressions without changing the settings. To avoid a memory
  165169. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165170. * object, we try to re-use previously allocated space, and we allocate
  165171. * enough space to handle YCbCr even if initially asked for grayscale.
  165172. */
  165173. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165174. cinfo->script_space_size = MAX(nscans, 10);
  165175. cinfo->script_space = (jpeg_scan_info *)
  165176. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165177. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165178. }
  165179. scanptr = cinfo->script_space;
  165180. cinfo->scan_info = scanptr;
  165181. cinfo->num_scans = nscans;
  165182. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165183. /* Custom script for YCbCr color images. */
  165184. /* Initial DC scan */
  165185. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165186. /* Initial AC scan: get some luma data out in a hurry */
  165187. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165188. /* Chroma data is too small to be worth expending many scans on */
  165189. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165190. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165191. /* Complete spectral selection for luma AC */
  165192. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165193. /* Refine next bit of luma AC */
  165194. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165195. /* Finish DC successive approximation */
  165196. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165197. /* Finish AC successive approximation */
  165198. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165199. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165200. /* Luma bottom bit comes last since it's usually largest scan */
  165201. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165202. } else {
  165203. /* All-purpose script for other color spaces. */
  165204. /* Successive approximation first pass */
  165205. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165206. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165207. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165208. /* Successive approximation second pass */
  165209. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165210. /* Successive approximation final pass */
  165211. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165212. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165213. }
  165214. }
  165215. #endif /* C_PROGRESSIVE_SUPPORTED */
  165216. /*** End of inlined file: jcparam.c ***/
  165217. /*** Start of inlined file: jcphuff.c ***/
  165218. #define JPEG_INTERNALS
  165219. #ifdef C_PROGRESSIVE_SUPPORTED
  165220. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165221. typedef struct {
  165222. struct jpeg_entropy_encoder pub; /* public fields */
  165223. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165224. boolean gather_statistics;
  165225. /* Bit-level coding status.
  165226. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165227. */
  165228. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165229. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165230. INT32 put_buffer; /* current bit-accumulation buffer */
  165231. int put_bits; /* # of bits now in it */
  165232. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165233. /* Coding status for DC components */
  165234. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165235. /* Coding status for AC components */
  165236. int ac_tbl_no; /* the table number of the single component */
  165237. unsigned int EOBRUN; /* run length of EOBs */
  165238. unsigned int BE; /* # of buffered correction bits before MCU */
  165239. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165240. /* packing correction bits tightly would save some space but cost time... */
  165241. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165242. int next_restart_num; /* next restart number to write (0-7) */
  165243. /* Pointers to derived tables (these workspaces have image lifespan).
  165244. * Since any one scan codes only DC or only AC, we only need one set
  165245. * of tables, not one for DC and one for AC.
  165246. */
  165247. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165248. /* Statistics tables for optimization; again, one set is enough */
  165249. long * count_ptrs[NUM_HUFF_TBLS];
  165250. } phuff_entropy_encoder;
  165251. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165252. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165253. * buffer can hold. Larger sizes may slightly improve compression, but
  165254. * 1000 is already well into the realm of overkill.
  165255. * The minimum safe size is 64 bits.
  165256. */
  165257. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165258. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165259. * We assume that int right shift is unsigned if INT32 right shift is,
  165260. * which should be safe.
  165261. */
  165262. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165263. #define ISHIFT_TEMPS int ishift_temp;
  165264. #define IRIGHT_SHIFT(x,shft) \
  165265. ((ishift_temp = (x)) < 0 ? \
  165266. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165267. (ishift_temp >> (shft)))
  165268. #else
  165269. #define ISHIFT_TEMPS
  165270. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165271. #endif
  165272. /* Forward declarations */
  165273. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  165274. JBLOCKROW *MCU_data));
  165275. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  165276. JBLOCKROW *MCU_data));
  165277. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  165278. JBLOCKROW *MCU_data));
  165279. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  165280. JBLOCKROW *MCU_data));
  165281. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  165282. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  165283. /*
  165284. * Initialize for a Huffman-compressed scan using progressive JPEG.
  165285. */
  165286. METHODDEF(void)
  165287. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  165288. {
  165289. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165290. boolean is_DC_band;
  165291. int ci, tbl;
  165292. jpeg_component_info * compptr;
  165293. entropy->cinfo = cinfo;
  165294. entropy->gather_statistics = gather_statistics;
  165295. is_DC_band = (cinfo->Ss == 0);
  165296. /* We assume jcmaster.c already validated the scan parameters. */
  165297. /* Select execution routines */
  165298. if (cinfo->Ah == 0) {
  165299. if (is_DC_band)
  165300. entropy->pub.encode_mcu = encode_mcu_DC_first;
  165301. else
  165302. entropy->pub.encode_mcu = encode_mcu_AC_first;
  165303. } else {
  165304. if (is_DC_band)
  165305. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165306. else {
  165307. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165308. /* AC refinement needs a correction bit buffer */
  165309. if (entropy->bit_buffer == NULL)
  165310. entropy->bit_buffer = (char *)
  165311. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165312. MAX_CORR_BITS * SIZEOF(char));
  165313. }
  165314. }
  165315. if (gather_statistics)
  165316. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165317. else
  165318. entropy->pub.finish_pass = finish_pass_phuff;
  165319. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165320. * for AC coefficients.
  165321. */
  165322. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165323. compptr = cinfo->cur_comp_info[ci];
  165324. /* Initialize DC predictions to 0 */
  165325. entropy->last_dc_val[ci] = 0;
  165326. /* Get table index */
  165327. if (is_DC_band) {
  165328. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165329. continue;
  165330. tbl = compptr->dc_tbl_no;
  165331. } else {
  165332. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165333. }
  165334. if (gather_statistics) {
  165335. /* Check for invalid table index */
  165336. /* (make_c_derived_tbl does this in the other path) */
  165337. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165338. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165339. /* Allocate and zero the statistics tables */
  165340. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165341. if (entropy->count_ptrs[tbl] == NULL)
  165342. entropy->count_ptrs[tbl] = (long *)
  165343. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165344. 257 * SIZEOF(long));
  165345. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165346. } else {
  165347. /* Compute derived values for Huffman table */
  165348. /* We may do this more than once for a table, but it's not expensive */
  165349. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165350. & entropy->derived_tbls[tbl]);
  165351. }
  165352. }
  165353. /* Initialize AC stuff */
  165354. entropy->EOBRUN = 0;
  165355. entropy->BE = 0;
  165356. /* Initialize bit buffer to empty */
  165357. entropy->put_buffer = 0;
  165358. entropy->put_bits = 0;
  165359. /* Initialize restart stuff */
  165360. entropy->restarts_to_go = cinfo->restart_interval;
  165361. entropy->next_restart_num = 0;
  165362. }
  165363. /* Outputting bytes to the file.
  165364. * NB: these must be called only when actually outputting,
  165365. * that is, entropy->gather_statistics == FALSE.
  165366. */
  165367. /* Emit a byte */
  165368. #define emit_byte(entropy,val) \
  165369. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165370. if (--(entropy)->free_in_buffer == 0) \
  165371. dump_buffer_p(entropy); }
  165372. LOCAL(void)
  165373. dump_buffer_p (phuff_entropy_ptr entropy)
  165374. /* Empty the output buffer; we do not support suspension in this module. */
  165375. {
  165376. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165377. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165378. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165379. /* After a successful buffer dump, must reset buffer pointers */
  165380. entropy->next_output_byte = dest->next_output_byte;
  165381. entropy->free_in_buffer = dest->free_in_buffer;
  165382. }
  165383. /* Outputting bits to the file */
  165384. /* Only the right 24 bits of put_buffer are used; the valid bits are
  165385. * left-justified in this part. At most 16 bits can be passed to emit_bits
  165386. * in one call, and we never retain more than 7 bits in put_buffer
  165387. * between calls, so 24 bits are sufficient.
  165388. */
  165389. INLINE
  165390. LOCAL(void)
  165391. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  165392. /* Emit some bits, unless we are in gather mode */
  165393. {
  165394. /* This routine is heavily used, so it's worth coding tightly. */
  165395. register INT32 put_buffer = (INT32) code;
  165396. register int put_bits = entropy->put_bits;
  165397. /* if size is 0, caller used an invalid Huffman table entry */
  165398. if (size == 0)
  165399. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165400. if (entropy->gather_statistics)
  165401. return; /* do nothing if we're only getting stats */
  165402. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  165403. put_bits += size; /* new number of bits in buffer */
  165404. put_buffer <<= 24 - put_bits; /* align incoming bits */
  165405. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  165406. while (put_bits >= 8) {
  165407. int c = (int) ((put_buffer >> 16) & 0xFF);
  165408. emit_byte(entropy, c);
  165409. if (c == 0xFF) { /* need to stuff a zero byte? */
  165410. emit_byte(entropy, 0);
  165411. }
  165412. put_buffer <<= 8;
  165413. put_bits -= 8;
  165414. }
  165415. entropy->put_buffer = put_buffer; /* update variables */
  165416. entropy->put_bits = put_bits;
  165417. }
  165418. LOCAL(void)
  165419. flush_bits_p (phuff_entropy_ptr entropy)
  165420. {
  165421. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  165422. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  165423. entropy->put_bits = 0;
  165424. }
  165425. /*
  165426. * Emit (or just count) a Huffman symbol.
  165427. */
  165428. INLINE
  165429. LOCAL(void)
  165430. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  165431. {
  165432. if (entropy->gather_statistics)
  165433. entropy->count_ptrs[tbl_no][symbol]++;
  165434. else {
  165435. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  165436. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  165437. }
  165438. }
  165439. /*
  165440. * Emit bits from a correction bit buffer.
  165441. */
  165442. LOCAL(void)
  165443. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  165444. unsigned int nbits)
  165445. {
  165446. if (entropy->gather_statistics)
  165447. return; /* no real work */
  165448. while (nbits > 0) {
  165449. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  165450. bufstart++;
  165451. nbits--;
  165452. }
  165453. }
  165454. /*
  165455. * Emit any pending EOBRUN symbol.
  165456. */
  165457. LOCAL(void)
  165458. emit_eobrun (phuff_entropy_ptr entropy)
  165459. {
  165460. register int temp, nbits;
  165461. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  165462. temp = entropy->EOBRUN;
  165463. nbits = 0;
  165464. while ((temp >>= 1))
  165465. nbits++;
  165466. /* safety check: shouldn't happen given limited correction-bit buffer */
  165467. if (nbits > 14)
  165468. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165469. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  165470. if (nbits)
  165471. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  165472. entropy->EOBRUN = 0;
  165473. /* Emit any buffered correction bits */
  165474. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  165475. entropy->BE = 0;
  165476. }
  165477. }
  165478. /*
  165479. * Emit a restart marker & resynchronize predictions.
  165480. */
  165481. LOCAL(void)
  165482. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  165483. {
  165484. int ci;
  165485. emit_eobrun(entropy);
  165486. if (! entropy->gather_statistics) {
  165487. flush_bits_p(entropy);
  165488. emit_byte(entropy, 0xFF);
  165489. emit_byte(entropy, JPEG_RST0 + restart_num);
  165490. }
  165491. if (entropy->cinfo->Ss == 0) {
  165492. /* Re-initialize DC predictions to 0 */
  165493. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  165494. entropy->last_dc_val[ci] = 0;
  165495. } else {
  165496. /* Re-initialize all AC-related fields to 0 */
  165497. entropy->EOBRUN = 0;
  165498. entropy->BE = 0;
  165499. }
  165500. }
  165501. /*
  165502. * MCU encoding for DC initial scan (either spectral selection,
  165503. * or first pass of successive approximation).
  165504. */
  165505. METHODDEF(boolean)
  165506. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165507. {
  165508. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165509. register int temp, temp2;
  165510. register int nbits;
  165511. int blkn, ci;
  165512. int Al = cinfo->Al;
  165513. JBLOCKROW block;
  165514. jpeg_component_info * compptr;
  165515. ISHIFT_TEMPS
  165516. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165517. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165518. /* Emit restart marker if needed */
  165519. if (cinfo->restart_interval)
  165520. if (entropy->restarts_to_go == 0)
  165521. emit_restart_p(entropy, entropy->next_restart_num);
  165522. /* Encode the MCU data blocks */
  165523. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165524. block = MCU_data[blkn];
  165525. ci = cinfo->MCU_membership[blkn];
  165526. compptr = cinfo->cur_comp_info[ci];
  165527. /* Compute the DC value after the required point transform by Al.
  165528. * This is simply an arithmetic right shift.
  165529. */
  165530. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  165531. /* DC differences are figured on the point-transformed values. */
  165532. temp = temp2 - entropy->last_dc_val[ci];
  165533. entropy->last_dc_val[ci] = temp2;
  165534. /* Encode the DC coefficient difference per section G.1.2.1 */
  165535. temp2 = temp;
  165536. if (temp < 0) {
  165537. temp = -temp; /* temp is abs value of input */
  165538. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  165539. /* This code assumes we are on a two's complement machine */
  165540. temp2--;
  165541. }
  165542. /* Find the number of bits needed for the magnitude of the coefficient */
  165543. nbits = 0;
  165544. while (temp) {
  165545. nbits++;
  165546. temp >>= 1;
  165547. }
  165548. /* Check for out-of-range coefficient values.
  165549. * Since we're encoding a difference, the range limit is twice as much.
  165550. */
  165551. if (nbits > MAX_COEF_BITS+1)
  165552. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165553. /* Count/emit the Huffman-coded symbol for the number of bits */
  165554. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  165555. /* Emit that number of bits of the value, if positive, */
  165556. /* or the complement of its magnitude, if negative. */
  165557. if (nbits) /* emit_bits rejects calls with size 0 */
  165558. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165559. }
  165560. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165561. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165562. /* Update restart-interval state too */
  165563. if (cinfo->restart_interval) {
  165564. if (entropy->restarts_to_go == 0) {
  165565. entropy->restarts_to_go = cinfo->restart_interval;
  165566. entropy->next_restart_num++;
  165567. entropy->next_restart_num &= 7;
  165568. }
  165569. entropy->restarts_to_go--;
  165570. }
  165571. return TRUE;
  165572. }
  165573. /*
  165574. * MCU encoding for AC initial scan (either spectral selection,
  165575. * or first pass of successive approximation).
  165576. */
  165577. METHODDEF(boolean)
  165578. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165579. {
  165580. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165581. register int temp, temp2;
  165582. register int nbits;
  165583. register int r, k;
  165584. int Se = cinfo->Se;
  165585. int Al = cinfo->Al;
  165586. JBLOCKROW block;
  165587. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165588. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165589. /* Emit restart marker if needed */
  165590. if (cinfo->restart_interval)
  165591. if (entropy->restarts_to_go == 0)
  165592. emit_restart_p(entropy, entropy->next_restart_num);
  165593. /* Encode the MCU data block */
  165594. block = MCU_data[0];
  165595. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  165596. r = 0; /* r = run length of zeros */
  165597. for (k = cinfo->Ss; k <= Se; k++) {
  165598. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  165599. r++;
  165600. continue;
  165601. }
  165602. /* We must apply the point transform by Al. For AC coefficients this
  165603. * is an integer division with rounding towards 0. To do this portably
  165604. * in C, we shift after obtaining the absolute value; so the code is
  165605. * interwoven with finding the abs value (temp) and output bits (temp2).
  165606. */
  165607. if (temp < 0) {
  165608. temp = -temp; /* temp is abs value of input */
  165609. temp >>= Al; /* apply the point transform */
  165610. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  165611. temp2 = ~temp;
  165612. } else {
  165613. temp >>= Al; /* apply the point transform */
  165614. temp2 = temp;
  165615. }
  165616. /* Watch out for case that nonzero coef is zero after point transform */
  165617. if (temp == 0) {
  165618. r++;
  165619. continue;
  165620. }
  165621. /* Emit any pending EOBRUN */
  165622. if (entropy->EOBRUN > 0)
  165623. emit_eobrun(entropy);
  165624. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  165625. while (r > 15) {
  165626. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165627. r -= 16;
  165628. }
  165629. /* Find the number of bits needed for the magnitude of the coefficient */
  165630. nbits = 1; /* there must be at least one 1 bit */
  165631. while ((temp >>= 1))
  165632. nbits++;
  165633. /* Check for out-of-range coefficient values */
  165634. if (nbits > MAX_COEF_BITS)
  165635. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165636. /* Count/emit Huffman symbol for run length / number of bits */
  165637. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  165638. /* Emit that number of bits of the value, if positive, */
  165639. /* or the complement of its magnitude, if negative. */
  165640. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165641. r = 0; /* reset zero run length */
  165642. }
  165643. if (r > 0) { /* If there are trailing zeroes, */
  165644. entropy->EOBRUN++; /* count an EOB */
  165645. if (entropy->EOBRUN == 0x7FFF)
  165646. emit_eobrun(entropy); /* force it out to avoid overflow */
  165647. }
  165648. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165649. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165650. /* Update restart-interval state too */
  165651. if (cinfo->restart_interval) {
  165652. if (entropy->restarts_to_go == 0) {
  165653. entropy->restarts_to_go = cinfo->restart_interval;
  165654. entropy->next_restart_num++;
  165655. entropy->next_restart_num &= 7;
  165656. }
  165657. entropy->restarts_to_go--;
  165658. }
  165659. return TRUE;
  165660. }
  165661. /*
  165662. * MCU encoding for DC successive approximation refinement scan.
  165663. * Note: we assume such scans can be multi-component, although the spec
  165664. * is not very clear on the point.
  165665. */
  165666. METHODDEF(boolean)
  165667. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165668. {
  165669. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165670. register int temp;
  165671. int blkn;
  165672. int Al = cinfo->Al;
  165673. JBLOCKROW block;
  165674. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165675. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165676. /* Emit restart marker if needed */
  165677. if (cinfo->restart_interval)
  165678. if (entropy->restarts_to_go == 0)
  165679. emit_restart_p(entropy, entropy->next_restart_num);
  165680. /* Encode the MCU data blocks */
  165681. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165682. block = MCU_data[blkn];
  165683. /* We simply emit the Al'th bit of the DC coefficient value. */
  165684. temp = (*block)[0];
  165685. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  165686. }
  165687. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165688. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165689. /* Update restart-interval state too */
  165690. if (cinfo->restart_interval) {
  165691. if (entropy->restarts_to_go == 0) {
  165692. entropy->restarts_to_go = cinfo->restart_interval;
  165693. entropy->next_restart_num++;
  165694. entropy->next_restart_num &= 7;
  165695. }
  165696. entropy->restarts_to_go--;
  165697. }
  165698. return TRUE;
  165699. }
  165700. /*
  165701. * MCU encoding for AC successive approximation refinement scan.
  165702. */
  165703. METHODDEF(boolean)
  165704. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165705. {
  165706. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165707. register int temp;
  165708. register int r, k;
  165709. int EOB;
  165710. char *BR_buffer;
  165711. unsigned int BR;
  165712. int Se = cinfo->Se;
  165713. int Al = cinfo->Al;
  165714. JBLOCKROW block;
  165715. int absvalues[DCTSIZE2];
  165716. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165717. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165718. /* Emit restart marker if needed */
  165719. if (cinfo->restart_interval)
  165720. if (entropy->restarts_to_go == 0)
  165721. emit_restart_p(entropy, entropy->next_restart_num);
  165722. /* Encode the MCU data block */
  165723. block = MCU_data[0];
  165724. /* It is convenient to make a pre-pass to determine the transformed
  165725. * coefficients' absolute values and the EOB position.
  165726. */
  165727. EOB = 0;
  165728. for (k = cinfo->Ss; k <= Se; k++) {
  165729. temp = (*block)[jpeg_natural_order[k]];
  165730. /* We must apply the point transform by Al. For AC coefficients this
  165731. * is an integer division with rounding towards 0. To do this portably
  165732. * in C, we shift after obtaining the absolute value.
  165733. */
  165734. if (temp < 0)
  165735. temp = -temp; /* temp is abs value of input */
  165736. temp >>= Al; /* apply the point transform */
  165737. absvalues[k] = temp; /* save abs value for main pass */
  165738. if (temp == 1)
  165739. EOB = k; /* EOB = index of last newly-nonzero coef */
  165740. }
  165741. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  165742. r = 0; /* r = run length of zeros */
  165743. BR = 0; /* BR = count of buffered bits added now */
  165744. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  165745. for (k = cinfo->Ss; k <= Se; k++) {
  165746. if ((temp = absvalues[k]) == 0) {
  165747. r++;
  165748. continue;
  165749. }
  165750. /* Emit any required ZRLs, but not if they can be folded into EOB */
  165751. while (r > 15 && k <= EOB) {
  165752. /* emit any pending EOBRUN and the BE correction bits */
  165753. emit_eobrun(entropy);
  165754. /* Emit ZRL */
  165755. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165756. r -= 16;
  165757. /* Emit buffered correction bits that must be associated with ZRL */
  165758. emit_buffered_bits(entropy, BR_buffer, BR);
  165759. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  165760. BR = 0;
  165761. }
  165762. /* If the coef was previously nonzero, it only needs a correction bit.
  165763. * NOTE: a straight translation of the spec's figure G.7 would suggest
  165764. * that we also need to test r > 15. But if r > 15, we can only get here
  165765. * if k > EOB, which implies that this coefficient is not 1.
  165766. */
  165767. if (temp > 1) {
  165768. /* The correction bit is the next bit of the absolute value. */
  165769. BR_buffer[BR++] = (char) (temp & 1);
  165770. continue;
  165771. }
  165772. /* Emit any pending EOBRUN and the BE correction bits */
  165773. emit_eobrun(entropy);
  165774. /* Count/emit Huffman symbol for run length / number of bits */
  165775. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  165776. /* Emit output bit for newly-nonzero coef */
  165777. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  165778. emit_bits_p(entropy, (unsigned int) temp, 1);
  165779. /* Emit buffered correction bits that must be associated with this code */
  165780. emit_buffered_bits(entropy, BR_buffer, BR);
  165781. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  165782. BR = 0;
  165783. r = 0; /* reset zero run length */
  165784. }
  165785. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  165786. entropy->EOBRUN++; /* count an EOB */
  165787. entropy->BE += BR; /* concat my correction bits to older ones */
  165788. /* We force out the EOB if we risk either:
  165789. * 1. overflow of the EOB counter;
  165790. * 2. overflow of the correction bit buffer during the next MCU.
  165791. */
  165792. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  165793. emit_eobrun(entropy);
  165794. }
  165795. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165796. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165797. /* Update restart-interval state too */
  165798. if (cinfo->restart_interval) {
  165799. if (entropy->restarts_to_go == 0) {
  165800. entropy->restarts_to_go = cinfo->restart_interval;
  165801. entropy->next_restart_num++;
  165802. entropy->next_restart_num &= 7;
  165803. }
  165804. entropy->restarts_to_go--;
  165805. }
  165806. return TRUE;
  165807. }
  165808. /*
  165809. * Finish up at the end of a Huffman-compressed progressive scan.
  165810. */
  165811. METHODDEF(void)
  165812. finish_pass_phuff (j_compress_ptr cinfo)
  165813. {
  165814. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165815. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165816. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165817. /* Flush out any buffered data */
  165818. emit_eobrun(entropy);
  165819. flush_bits_p(entropy);
  165820. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165821. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165822. }
  165823. /*
  165824. * Finish up a statistics-gathering pass and create the new Huffman tables.
  165825. */
  165826. METHODDEF(void)
  165827. finish_pass_gather_phuff (j_compress_ptr cinfo)
  165828. {
  165829. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165830. boolean is_DC_band;
  165831. int ci, tbl;
  165832. jpeg_component_info * compptr;
  165833. JHUFF_TBL **htblptr;
  165834. boolean did[NUM_HUFF_TBLS];
  165835. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  165836. emit_eobrun(entropy);
  165837. is_DC_band = (cinfo->Ss == 0);
  165838. /* It's important not to apply jpeg_gen_optimal_table more than once
  165839. * per table, because it clobbers the input frequency counts!
  165840. */
  165841. MEMZERO(did, SIZEOF(did));
  165842. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165843. compptr = cinfo->cur_comp_info[ci];
  165844. if (is_DC_band) {
  165845. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165846. continue;
  165847. tbl = compptr->dc_tbl_no;
  165848. } else {
  165849. tbl = compptr->ac_tbl_no;
  165850. }
  165851. if (! did[tbl]) {
  165852. if (is_DC_band)
  165853. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  165854. else
  165855. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  165856. if (*htblptr == NULL)
  165857. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165858. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  165859. did[tbl] = TRUE;
  165860. }
  165861. }
  165862. }
  165863. /*
  165864. * Module initialization routine for progressive Huffman entropy encoding.
  165865. */
  165866. GLOBAL(void)
  165867. jinit_phuff_encoder (j_compress_ptr cinfo)
  165868. {
  165869. phuff_entropy_ptr entropy;
  165870. int i;
  165871. entropy = (phuff_entropy_ptr)
  165872. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165873. SIZEOF(phuff_entropy_encoder));
  165874. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  165875. entropy->pub.start_pass = start_pass_phuff;
  165876. /* Mark tables unallocated */
  165877. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  165878. entropy->derived_tbls[i] = NULL;
  165879. entropy->count_ptrs[i] = NULL;
  165880. }
  165881. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  165882. }
  165883. #endif /* C_PROGRESSIVE_SUPPORTED */
  165884. /*** End of inlined file: jcphuff.c ***/
  165885. /*** Start of inlined file: jcprepct.c ***/
  165886. #define JPEG_INTERNALS
  165887. /* At present, jcsample.c can request context rows only for smoothing.
  165888. * In the future, we might also need context rows for CCIR601 sampling
  165889. * or other more-complex downsampling procedures. The code to support
  165890. * context rows should be compiled only if needed.
  165891. */
  165892. #ifdef INPUT_SMOOTHING_SUPPORTED
  165893. #define CONTEXT_ROWS_SUPPORTED
  165894. #endif
  165895. /*
  165896. * For the simple (no-context-row) case, we just need to buffer one
  165897. * row group's worth of pixels for the downsampling step. At the bottom of
  165898. * the image, we pad to a full row group by replicating the last pixel row.
  165899. * The downsampler's last output row is then replicated if needed to pad
  165900. * out to a full iMCU row.
  165901. *
  165902. * When providing context rows, we must buffer three row groups' worth of
  165903. * pixels. Three row groups are physically allocated, but the row pointer
  165904. * arrays are made five row groups high, with the extra pointers above and
  165905. * below "wrapping around" to point to the last and first real row groups.
  165906. * This allows the downsampler to access the proper context rows.
  165907. * At the top and bottom of the image, we create dummy context rows by
  165908. * copying the first or last real pixel row. This copying could be avoided
  165909. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  165910. * trouble on the compression side.
  165911. */
  165912. /* Private buffer controller object */
  165913. typedef struct {
  165914. struct jpeg_c_prep_controller pub; /* public fields */
  165915. /* Downsampling input buffer. This buffer holds color-converted data
  165916. * until we have enough to do a downsample step.
  165917. */
  165918. JSAMPARRAY color_buf[MAX_COMPONENTS];
  165919. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  165920. int next_buf_row; /* index of next row to store in color_buf */
  165921. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  165922. int this_row_group; /* starting row index of group to process */
  165923. int next_buf_stop; /* downsample when we reach this index */
  165924. #endif
  165925. } my_prep_controller;
  165926. typedef my_prep_controller * my_prep_ptr;
  165927. /*
  165928. * Initialize for a processing pass.
  165929. */
  165930. METHODDEF(void)
  165931. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  165932. {
  165933. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165934. if (pass_mode != JBUF_PASS_THRU)
  165935. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165936. /* Initialize total-height counter for detecting bottom of image */
  165937. prep->rows_to_go = cinfo->image_height;
  165938. /* Mark the conversion buffer empty */
  165939. prep->next_buf_row = 0;
  165940. #ifdef CONTEXT_ROWS_SUPPORTED
  165941. /* Preset additional state variables for context mode.
  165942. * These aren't used in non-context mode, so we needn't test which mode.
  165943. */
  165944. prep->this_row_group = 0;
  165945. /* Set next_buf_stop to stop after two row groups have been read in. */
  165946. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  165947. #endif
  165948. }
  165949. /*
  165950. * Expand an image vertically from height input_rows to height output_rows,
  165951. * by duplicating the bottom row.
  165952. */
  165953. LOCAL(void)
  165954. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  165955. int input_rows, int output_rows)
  165956. {
  165957. register int row;
  165958. for (row = input_rows; row < output_rows; row++) {
  165959. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  165960. 1, num_cols);
  165961. }
  165962. }
  165963. /*
  165964. * Process some data in the simple no-context case.
  165965. *
  165966. * Preprocessor output data is counted in "row groups". A row group
  165967. * is defined to be v_samp_factor sample rows of each component.
  165968. * Downsampling will produce this much data from each max_v_samp_factor
  165969. * input rows.
  165970. */
  165971. METHODDEF(void)
  165972. pre_process_data (j_compress_ptr cinfo,
  165973. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  165974. JDIMENSION in_rows_avail,
  165975. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  165976. JDIMENSION out_row_groups_avail)
  165977. {
  165978. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165979. int numrows, ci;
  165980. JDIMENSION inrows;
  165981. jpeg_component_info * compptr;
  165982. while (*in_row_ctr < in_rows_avail &&
  165983. *out_row_group_ctr < out_row_groups_avail) {
  165984. /* Do color conversion to fill the conversion buffer. */
  165985. inrows = in_rows_avail - *in_row_ctr;
  165986. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  165987. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  165988. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  165989. prep->color_buf,
  165990. (JDIMENSION) prep->next_buf_row,
  165991. numrows);
  165992. *in_row_ctr += numrows;
  165993. prep->next_buf_row += numrows;
  165994. prep->rows_to_go -= numrows;
  165995. /* If at bottom of image, pad to fill the conversion buffer. */
  165996. if (prep->rows_to_go == 0 &&
  165997. prep->next_buf_row < cinfo->max_v_samp_factor) {
  165998. for (ci = 0; ci < cinfo->num_components; ci++) {
  165999. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166000. prep->next_buf_row, cinfo->max_v_samp_factor);
  166001. }
  166002. prep->next_buf_row = cinfo->max_v_samp_factor;
  166003. }
  166004. /* If we've filled the conversion buffer, empty it. */
  166005. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166006. (*cinfo->downsample->downsample) (cinfo,
  166007. prep->color_buf, (JDIMENSION) 0,
  166008. output_buf, *out_row_group_ctr);
  166009. prep->next_buf_row = 0;
  166010. (*out_row_group_ctr)++;
  166011. }
  166012. /* If at bottom of image, pad the output to a full iMCU height.
  166013. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166014. */
  166015. if (prep->rows_to_go == 0 &&
  166016. *out_row_group_ctr < out_row_groups_avail) {
  166017. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166018. ci++, compptr++) {
  166019. expand_bottom_edge(output_buf[ci],
  166020. compptr->width_in_blocks * DCTSIZE,
  166021. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166022. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166023. }
  166024. *out_row_group_ctr = out_row_groups_avail;
  166025. break; /* can exit outer loop without test */
  166026. }
  166027. }
  166028. }
  166029. #ifdef CONTEXT_ROWS_SUPPORTED
  166030. /*
  166031. * Process some data in the context case.
  166032. */
  166033. METHODDEF(void)
  166034. pre_process_context (j_compress_ptr cinfo,
  166035. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166036. JDIMENSION in_rows_avail,
  166037. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166038. JDIMENSION out_row_groups_avail)
  166039. {
  166040. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166041. int numrows, ci;
  166042. int buf_height = cinfo->max_v_samp_factor * 3;
  166043. JDIMENSION inrows;
  166044. while (*out_row_group_ctr < out_row_groups_avail) {
  166045. if (*in_row_ctr < in_rows_avail) {
  166046. /* Do color conversion to fill the conversion buffer. */
  166047. inrows = in_rows_avail - *in_row_ctr;
  166048. numrows = prep->next_buf_stop - prep->next_buf_row;
  166049. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166050. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166051. prep->color_buf,
  166052. (JDIMENSION) prep->next_buf_row,
  166053. numrows);
  166054. /* Pad at top of image, if first time through */
  166055. if (prep->rows_to_go == cinfo->image_height) {
  166056. for (ci = 0; ci < cinfo->num_components; ci++) {
  166057. int row;
  166058. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166059. jcopy_sample_rows(prep->color_buf[ci], 0,
  166060. prep->color_buf[ci], -row,
  166061. 1, cinfo->image_width);
  166062. }
  166063. }
  166064. }
  166065. *in_row_ctr += numrows;
  166066. prep->next_buf_row += numrows;
  166067. prep->rows_to_go -= numrows;
  166068. } else {
  166069. /* Return for more data, unless we are at the bottom of the image. */
  166070. if (prep->rows_to_go != 0)
  166071. break;
  166072. /* When at bottom of image, pad to fill the conversion buffer. */
  166073. if (prep->next_buf_row < prep->next_buf_stop) {
  166074. for (ci = 0; ci < cinfo->num_components; ci++) {
  166075. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166076. prep->next_buf_row, prep->next_buf_stop);
  166077. }
  166078. prep->next_buf_row = prep->next_buf_stop;
  166079. }
  166080. }
  166081. /* If we've gotten enough data, downsample a row group. */
  166082. if (prep->next_buf_row == prep->next_buf_stop) {
  166083. (*cinfo->downsample->downsample) (cinfo,
  166084. prep->color_buf,
  166085. (JDIMENSION) prep->this_row_group,
  166086. output_buf, *out_row_group_ctr);
  166087. (*out_row_group_ctr)++;
  166088. /* Advance pointers with wraparound as necessary. */
  166089. prep->this_row_group += cinfo->max_v_samp_factor;
  166090. if (prep->this_row_group >= buf_height)
  166091. prep->this_row_group = 0;
  166092. if (prep->next_buf_row >= buf_height)
  166093. prep->next_buf_row = 0;
  166094. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166095. }
  166096. }
  166097. }
  166098. /*
  166099. * Create the wrapped-around downsampling input buffer needed for context mode.
  166100. */
  166101. LOCAL(void)
  166102. create_context_buffer (j_compress_ptr cinfo)
  166103. {
  166104. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166105. int rgroup_height = cinfo->max_v_samp_factor;
  166106. int ci, i;
  166107. jpeg_component_info * compptr;
  166108. JSAMPARRAY true_buffer, fake_buffer;
  166109. /* Grab enough space for fake row pointers for all the components;
  166110. * we need five row groups' worth of pointers for each component.
  166111. */
  166112. fake_buffer = (JSAMPARRAY)
  166113. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166114. (cinfo->num_components * 5 * rgroup_height) *
  166115. SIZEOF(JSAMPROW));
  166116. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166117. ci++, compptr++) {
  166118. /* Allocate the actual buffer space (3 row groups) for this component.
  166119. * We make the buffer wide enough to allow the downsampler to edge-expand
  166120. * horizontally within the buffer, if it so chooses.
  166121. */
  166122. true_buffer = (*cinfo->mem->alloc_sarray)
  166123. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166124. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166125. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166126. (JDIMENSION) (3 * rgroup_height));
  166127. /* Copy true buffer row pointers into the middle of the fake row array */
  166128. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166129. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166130. /* Fill in the above and below wraparound pointers */
  166131. for (i = 0; i < rgroup_height; i++) {
  166132. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166133. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166134. }
  166135. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166136. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166137. }
  166138. }
  166139. #endif /* CONTEXT_ROWS_SUPPORTED */
  166140. /*
  166141. * Initialize preprocessing controller.
  166142. */
  166143. GLOBAL(void)
  166144. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166145. {
  166146. my_prep_ptr prep;
  166147. int ci;
  166148. jpeg_component_info * compptr;
  166149. if (need_full_buffer) /* safety check */
  166150. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166151. prep = (my_prep_ptr)
  166152. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166153. SIZEOF(my_prep_controller));
  166154. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166155. prep->pub.start_pass = start_pass_prep;
  166156. /* Allocate the color conversion buffer.
  166157. * We make the buffer wide enough to allow the downsampler to edge-expand
  166158. * horizontally within the buffer, if it so chooses.
  166159. */
  166160. if (cinfo->downsample->need_context_rows) {
  166161. /* Set up to provide context rows */
  166162. #ifdef CONTEXT_ROWS_SUPPORTED
  166163. prep->pub.pre_process_data = pre_process_context;
  166164. create_context_buffer(cinfo);
  166165. #else
  166166. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166167. #endif
  166168. } else {
  166169. /* No context, just make it tall enough for one row group */
  166170. prep->pub.pre_process_data = pre_process_data;
  166171. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166172. ci++, compptr++) {
  166173. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166174. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166175. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166176. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166177. (JDIMENSION) cinfo->max_v_samp_factor);
  166178. }
  166179. }
  166180. }
  166181. /*** End of inlined file: jcprepct.c ***/
  166182. /*** Start of inlined file: jcsample.c ***/
  166183. #define JPEG_INTERNALS
  166184. /* Pointer to routine to downsample a single component */
  166185. typedef JMETHOD(void, downsample1_ptr,
  166186. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166187. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166188. /* Private subobject */
  166189. typedef struct {
  166190. struct jpeg_downsampler pub; /* public fields */
  166191. /* Downsampling method pointers, one per component */
  166192. downsample1_ptr methods[MAX_COMPONENTS];
  166193. } my_downsampler;
  166194. typedef my_downsampler * my_downsample_ptr;
  166195. /*
  166196. * Initialize for a downsampling pass.
  166197. */
  166198. METHODDEF(void)
  166199. start_pass_downsample (j_compress_ptr)
  166200. {
  166201. /* no work for now */
  166202. }
  166203. /*
  166204. * Expand a component horizontally from width input_cols to width output_cols,
  166205. * by duplicating the rightmost samples.
  166206. */
  166207. LOCAL(void)
  166208. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166209. JDIMENSION input_cols, JDIMENSION output_cols)
  166210. {
  166211. register JSAMPROW ptr;
  166212. register JSAMPLE pixval;
  166213. register int count;
  166214. int row;
  166215. int numcols = (int) (output_cols - input_cols);
  166216. if (numcols > 0) {
  166217. for (row = 0; row < num_rows; row++) {
  166218. ptr = image_data[row] + input_cols;
  166219. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166220. for (count = numcols; count > 0; count--)
  166221. *ptr++ = pixval;
  166222. }
  166223. }
  166224. }
  166225. /*
  166226. * Do downsampling for a whole row group (all components).
  166227. *
  166228. * In this version we simply downsample each component independently.
  166229. */
  166230. METHODDEF(void)
  166231. sep_downsample (j_compress_ptr cinfo,
  166232. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166233. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166234. {
  166235. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166236. int ci;
  166237. jpeg_component_info * compptr;
  166238. JSAMPARRAY in_ptr, out_ptr;
  166239. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166240. ci++, compptr++) {
  166241. in_ptr = input_buf[ci] + in_row_index;
  166242. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166243. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166244. }
  166245. }
  166246. /*
  166247. * Downsample pixel values of a single component.
  166248. * One row group is processed per call.
  166249. * This version handles arbitrary integral sampling ratios, without smoothing.
  166250. * Note that this version is not actually used for customary sampling ratios.
  166251. */
  166252. METHODDEF(void)
  166253. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166254. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166255. {
  166256. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166257. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166258. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166259. JSAMPROW inptr, outptr;
  166260. INT32 outvalue;
  166261. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166262. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166263. numpix = h_expand * v_expand;
  166264. numpix2 = numpix/2;
  166265. /* Expand input data enough to let all the output samples be generated
  166266. * by the standard loop. Special-casing padded output would be more
  166267. * efficient.
  166268. */
  166269. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166270. cinfo->image_width, output_cols * h_expand);
  166271. inrow = 0;
  166272. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166273. outptr = output_data[outrow];
  166274. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  166275. outcol++, outcol_h += h_expand) {
  166276. outvalue = 0;
  166277. for (v = 0; v < v_expand; v++) {
  166278. inptr = input_data[inrow+v] + outcol_h;
  166279. for (h = 0; h < h_expand; h++) {
  166280. outvalue += (INT32) GETJSAMPLE(*inptr++);
  166281. }
  166282. }
  166283. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  166284. }
  166285. inrow += v_expand;
  166286. }
  166287. }
  166288. /*
  166289. * Downsample pixel values of a single component.
  166290. * This version handles the special case of a full-size component,
  166291. * without smoothing.
  166292. */
  166293. METHODDEF(void)
  166294. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166295. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166296. {
  166297. /* Copy the data */
  166298. jcopy_sample_rows(input_data, 0, output_data, 0,
  166299. cinfo->max_v_samp_factor, cinfo->image_width);
  166300. /* Edge-expand */
  166301. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  166302. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  166303. }
  166304. /*
  166305. * Downsample pixel values of a single component.
  166306. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166307. * without smoothing.
  166308. *
  166309. * A note about the "bias" calculations: when rounding fractional values to
  166310. * integer, we do not want to always round 0.5 up to the next integer.
  166311. * If we did that, we'd introduce a noticeable bias towards larger values.
  166312. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166313. * alternate pixel locations (a simple ordered dither pattern).
  166314. */
  166315. METHODDEF(void)
  166316. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166317. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166318. {
  166319. int outrow;
  166320. JDIMENSION outcol;
  166321. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166322. register JSAMPROW inptr, outptr;
  166323. register int bias;
  166324. /* Expand input data enough to let all the output samples be generated
  166325. * by the standard loop. Special-casing padded output would be more
  166326. * efficient.
  166327. */
  166328. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166329. cinfo->image_width, output_cols * 2);
  166330. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166331. outptr = output_data[outrow];
  166332. inptr = input_data[outrow];
  166333. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166334. for (outcol = 0; outcol < output_cols; outcol++) {
  166335. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166336. + bias) >> 1);
  166337. bias ^= 1; /* 0=>1, 1=>0 */
  166338. inptr += 2;
  166339. }
  166340. }
  166341. }
  166342. /*
  166343. * Downsample pixel values of a single component.
  166344. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166345. * without smoothing.
  166346. */
  166347. METHODDEF(void)
  166348. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166349. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166350. {
  166351. int inrow, outrow;
  166352. JDIMENSION outcol;
  166353. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166354. register JSAMPROW inptr0, inptr1, outptr;
  166355. register int bias;
  166356. /* Expand input data enough to let all the output samples be generated
  166357. * by the standard loop. Special-casing padded output would be more
  166358. * efficient.
  166359. */
  166360. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166361. cinfo->image_width, output_cols * 2);
  166362. inrow = 0;
  166363. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166364. outptr = output_data[outrow];
  166365. inptr0 = input_data[inrow];
  166366. inptr1 = input_data[inrow+1];
  166367. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166368. for (outcol = 0; outcol < output_cols; outcol++) {
  166369. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166370. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166371. + bias) >> 2);
  166372. bias ^= 3; /* 1=>2, 2=>1 */
  166373. inptr0 += 2; inptr1 += 2;
  166374. }
  166375. inrow += 2;
  166376. }
  166377. }
  166378. #ifdef INPUT_SMOOTHING_SUPPORTED
  166379. /*
  166380. * Downsample pixel values of a single component.
  166381. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166382. * with smoothing. One row of context is required.
  166383. */
  166384. METHODDEF(void)
  166385. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166386. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166387. {
  166388. int inrow, outrow;
  166389. JDIMENSION colctr;
  166390. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166391. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  166392. INT32 membersum, neighsum, memberscale, neighscale;
  166393. /* Expand input data enough to let all the output samples be generated
  166394. * by the standard loop. Special-casing padded output would be more
  166395. * efficient.
  166396. */
  166397. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166398. cinfo->image_width, output_cols * 2);
  166399. /* We don't bother to form the individual "smoothed" input pixel values;
  166400. * we can directly compute the output which is the average of the four
  166401. * smoothed values. Each of the four member pixels contributes a fraction
  166402. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  166403. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  166404. * output. The four corner-adjacent neighbor pixels contribute a fraction
  166405. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  166406. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  166407. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  166408. * factors are scaled by 2^16 = 65536.
  166409. * Also recall that SF = smoothing_factor / 1024.
  166410. */
  166411. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  166412. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  166413. inrow = 0;
  166414. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166415. outptr = output_data[outrow];
  166416. inptr0 = input_data[inrow];
  166417. inptr1 = input_data[inrow+1];
  166418. above_ptr = input_data[inrow-1];
  166419. below_ptr = input_data[inrow+2];
  166420. /* Special case for first column: pretend column -1 is same as column 0 */
  166421. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166422. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166423. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166424. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166425. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  166426. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  166427. neighsum += neighsum;
  166428. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  166429. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  166430. membersum = membersum * memberscale + neighsum * neighscale;
  166431. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166432. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166433. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166434. /* sum of pixels directly mapped to this output element */
  166435. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166436. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166437. /* sum of edge-neighbor pixels */
  166438. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166439. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166440. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  166441. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  166442. /* The edge-neighbors count twice as much as corner-neighbors */
  166443. neighsum += neighsum;
  166444. /* Add in the corner-neighbors */
  166445. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  166446. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  166447. /* form final output scaled up by 2^16 */
  166448. membersum = membersum * memberscale + neighsum * neighscale;
  166449. /* round, descale and output it */
  166450. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166451. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166452. }
  166453. /* Special case for last column */
  166454. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166455. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166456. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166457. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166458. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  166459. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  166460. neighsum += neighsum;
  166461. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  166462. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  166463. membersum = membersum * memberscale + neighsum * neighscale;
  166464. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166465. inrow += 2;
  166466. }
  166467. }
  166468. /*
  166469. * Downsample pixel values of a single component.
  166470. * This version handles the special case of a full-size component,
  166471. * with smoothing. One row of context is required.
  166472. */
  166473. METHODDEF(void)
  166474. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  166475. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166476. {
  166477. int outrow;
  166478. JDIMENSION colctr;
  166479. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166480. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  166481. INT32 membersum, neighsum, memberscale, neighscale;
  166482. int colsum, lastcolsum, nextcolsum;
  166483. /* Expand input data enough to let all the output samples be generated
  166484. * by the standard loop. Special-casing padded output would be more
  166485. * efficient.
  166486. */
  166487. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166488. cinfo->image_width, output_cols);
  166489. /* Each of the eight neighbor pixels contributes a fraction SF to the
  166490. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  166491. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  166492. * Also recall that SF = smoothing_factor / 1024.
  166493. */
  166494. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  166495. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  166496. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166497. outptr = output_data[outrow];
  166498. inptr = input_data[outrow];
  166499. above_ptr = input_data[outrow-1];
  166500. below_ptr = input_data[outrow+1];
  166501. /* Special case for first column */
  166502. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  166503. GETJSAMPLE(*inptr);
  166504. membersum = GETJSAMPLE(*inptr++);
  166505. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166506. GETJSAMPLE(*inptr);
  166507. neighsum = colsum + (colsum - membersum) + nextcolsum;
  166508. membersum = membersum * memberscale + neighsum * neighscale;
  166509. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166510. lastcolsum = colsum; colsum = nextcolsum;
  166511. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166512. membersum = GETJSAMPLE(*inptr++);
  166513. above_ptr++; below_ptr++;
  166514. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166515. GETJSAMPLE(*inptr);
  166516. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  166517. membersum = membersum * memberscale + neighsum * neighscale;
  166518. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166519. lastcolsum = colsum; colsum = nextcolsum;
  166520. }
  166521. /* Special case for last column */
  166522. membersum = GETJSAMPLE(*inptr);
  166523. neighsum = lastcolsum + (colsum - membersum) + colsum;
  166524. membersum = membersum * memberscale + neighsum * neighscale;
  166525. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166526. }
  166527. }
  166528. #endif /* INPUT_SMOOTHING_SUPPORTED */
  166529. /*
  166530. * Module initialization routine for downsampling.
  166531. * Note that we must select a routine for each component.
  166532. */
  166533. GLOBAL(void)
  166534. jinit_downsampler (j_compress_ptr cinfo)
  166535. {
  166536. my_downsample_ptr downsample;
  166537. int ci;
  166538. jpeg_component_info * compptr;
  166539. boolean smoothok = TRUE;
  166540. downsample = (my_downsample_ptr)
  166541. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166542. SIZEOF(my_downsampler));
  166543. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  166544. downsample->pub.start_pass = start_pass_downsample;
  166545. downsample->pub.downsample = sep_downsample;
  166546. downsample->pub.need_context_rows = FALSE;
  166547. if (cinfo->CCIR601_sampling)
  166548. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  166549. /* Verify we can handle the sampling factors, and set up method pointers */
  166550. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166551. ci++, compptr++) {
  166552. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  166553. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166554. #ifdef INPUT_SMOOTHING_SUPPORTED
  166555. if (cinfo->smoothing_factor) {
  166556. downsample->methods[ci] = fullsize_smooth_downsample;
  166557. downsample->pub.need_context_rows = TRUE;
  166558. } else
  166559. #endif
  166560. downsample->methods[ci] = fullsize_downsample;
  166561. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166562. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166563. smoothok = FALSE;
  166564. downsample->methods[ci] = h2v1_downsample;
  166565. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166566. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  166567. #ifdef INPUT_SMOOTHING_SUPPORTED
  166568. if (cinfo->smoothing_factor) {
  166569. downsample->methods[ci] = h2v2_smooth_downsample;
  166570. downsample->pub.need_context_rows = TRUE;
  166571. } else
  166572. #endif
  166573. downsample->methods[ci] = h2v2_downsample;
  166574. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  166575. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  166576. smoothok = FALSE;
  166577. downsample->methods[ci] = int_downsample;
  166578. } else
  166579. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  166580. }
  166581. #ifdef INPUT_SMOOTHING_SUPPORTED
  166582. if (cinfo->smoothing_factor && !smoothok)
  166583. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  166584. #endif
  166585. }
  166586. /*** End of inlined file: jcsample.c ***/
  166587. /*** Start of inlined file: jctrans.c ***/
  166588. #define JPEG_INTERNALS
  166589. /* Forward declarations */
  166590. LOCAL(void) transencode_master_selection
  166591. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166592. LOCAL(void) transencode_coef_controller
  166593. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166594. /*
  166595. * Compression initialization for writing raw-coefficient data.
  166596. * Before calling this, all parameters and a data destination must be set up.
  166597. * Call jpeg_finish_compress() to actually write the data.
  166598. *
  166599. * The number of passed virtual arrays must match cinfo->num_components.
  166600. * Note that the virtual arrays need not be filled or even realized at
  166601. * the time write_coefficients is called; indeed, if the virtual arrays
  166602. * were requested from this compression object's memory manager, they
  166603. * typically will be realized during this routine and filled afterwards.
  166604. */
  166605. GLOBAL(void)
  166606. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  166607. {
  166608. if (cinfo->global_state != CSTATE_START)
  166609. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166610. /* Mark all tables to be written */
  166611. jpeg_suppress_tables(cinfo, FALSE);
  166612. /* (Re)initialize error mgr and destination modules */
  166613. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  166614. (*cinfo->dest->init_destination) (cinfo);
  166615. /* Perform master selection of active modules */
  166616. transencode_master_selection(cinfo, coef_arrays);
  166617. /* Wait for jpeg_finish_compress() call */
  166618. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  166619. cinfo->global_state = CSTATE_WRCOEFS;
  166620. }
  166621. /*
  166622. * Initialize the compression object with default parameters,
  166623. * then copy from the source object all parameters needed for lossless
  166624. * transcoding. Parameters that can be varied without loss (such as
  166625. * scan script and Huffman optimization) are left in their default states.
  166626. */
  166627. GLOBAL(void)
  166628. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  166629. j_compress_ptr dstinfo)
  166630. {
  166631. JQUANT_TBL ** qtblptr;
  166632. jpeg_component_info *incomp, *outcomp;
  166633. JQUANT_TBL *c_quant, *slot_quant;
  166634. int tblno, ci, coefi;
  166635. /* Safety check to ensure start_compress not called yet. */
  166636. if (dstinfo->global_state != CSTATE_START)
  166637. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  166638. /* Copy fundamental image dimensions */
  166639. dstinfo->image_width = srcinfo->image_width;
  166640. dstinfo->image_height = srcinfo->image_height;
  166641. dstinfo->input_components = srcinfo->num_components;
  166642. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  166643. /* Initialize all parameters to default values */
  166644. jpeg_set_defaults(dstinfo);
  166645. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  166646. * Fix it to get the right header markers for the image colorspace.
  166647. */
  166648. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  166649. dstinfo->data_precision = srcinfo->data_precision;
  166650. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  166651. /* Copy the source's quantization tables. */
  166652. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  166653. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  166654. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  166655. if (*qtblptr == NULL)
  166656. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  166657. MEMCOPY((*qtblptr)->quantval,
  166658. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  166659. SIZEOF((*qtblptr)->quantval));
  166660. (*qtblptr)->sent_table = FALSE;
  166661. }
  166662. }
  166663. /* Copy the source's per-component info.
  166664. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  166665. */
  166666. dstinfo->num_components = srcinfo->num_components;
  166667. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  166668. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  166669. MAX_COMPONENTS);
  166670. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  166671. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  166672. outcomp->component_id = incomp->component_id;
  166673. outcomp->h_samp_factor = incomp->h_samp_factor;
  166674. outcomp->v_samp_factor = incomp->v_samp_factor;
  166675. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  166676. /* Make sure saved quantization table for component matches the qtable
  166677. * slot. If not, the input file re-used this qtable slot.
  166678. * IJG encoder currently cannot duplicate this.
  166679. */
  166680. tblno = outcomp->quant_tbl_no;
  166681. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  166682. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  166683. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  166684. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  166685. c_quant = incomp->quant_table;
  166686. if (c_quant != NULL) {
  166687. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  166688. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  166689. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  166690. }
  166691. }
  166692. /* Note: we do not copy the source's Huffman table assignments;
  166693. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  166694. */
  166695. }
  166696. /* Also copy JFIF version and resolution information, if available.
  166697. * Strictly speaking this isn't "critical" info, but it's nearly
  166698. * always appropriate to copy it if available. In particular,
  166699. * if the application chooses to copy JFIF 1.02 extension markers from
  166700. * the source file, we need to copy the version to make sure we don't
  166701. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  166702. * We will *not*, however, copy version info from mislabeled "2.01" files.
  166703. */
  166704. if (srcinfo->saw_JFIF_marker) {
  166705. if (srcinfo->JFIF_major_version == 1) {
  166706. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  166707. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  166708. }
  166709. dstinfo->density_unit = srcinfo->density_unit;
  166710. dstinfo->X_density = srcinfo->X_density;
  166711. dstinfo->Y_density = srcinfo->Y_density;
  166712. }
  166713. }
  166714. /*
  166715. * Master selection of compression modules for transcoding.
  166716. * This substitutes for jcinit.c's initialization of the full compressor.
  166717. */
  166718. LOCAL(void)
  166719. transencode_master_selection (j_compress_ptr cinfo,
  166720. jvirt_barray_ptr * coef_arrays)
  166721. {
  166722. /* Although we don't actually use input_components for transcoding,
  166723. * jcmaster.c's initial_setup will complain if input_components is 0.
  166724. */
  166725. cinfo->input_components = 1;
  166726. /* Initialize master control (includes parameter checking/processing) */
  166727. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  166728. /* Entropy encoding: either Huffman or arithmetic coding. */
  166729. if (cinfo->arith_code) {
  166730. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  166731. } else {
  166732. if (cinfo->progressive_mode) {
  166733. #ifdef C_PROGRESSIVE_SUPPORTED
  166734. jinit_phuff_encoder(cinfo);
  166735. #else
  166736. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166737. #endif
  166738. } else
  166739. jinit_huff_encoder(cinfo);
  166740. }
  166741. /* We need a special coefficient buffer controller. */
  166742. transencode_coef_controller(cinfo, coef_arrays);
  166743. jinit_marker_writer(cinfo);
  166744. /* We can now tell the memory manager to allocate virtual arrays. */
  166745. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  166746. /* Write the datastream header (SOI, JFIF) immediately.
  166747. * Frame and scan headers are postponed till later.
  166748. * This lets application insert special markers after the SOI.
  166749. */
  166750. (*cinfo->marker->write_file_header) (cinfo);
  166751. }
  166752. /*
  166753. * The rest of this file is a special implementation of the coefficient
  166754. * buffer controller. This is similar to jccoefct.c, but it handles only
  166755. * output from presupplied virtual arrays. Furthermore, we generate any
  166756. * dummy padding blocks on-the-fly rather than expecting them to be present
  166757. * in the arrays.
  166758. */
  166759. /* Private buffer controller object */
  166760. typedef struct {
  166761. struct jpeg_c_coef_controller pub; /* public fields */
  166762. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  166763. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  166764. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  166765. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  166766. /* Virtual block array for each component. */
  166767. jvirt_barray_ptr * whole_image;
  166768. /* Workspace for constructing dummy blocks at right/bottom edges. */
  166769. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  166770. } my_coef_controller2;
  166771. typedef my_coef_controller2 * my_coef_ptr2;
  166772. LOCAL(void)
  166773. start_iMCU_row2 (j_compress_ptr cinfo)
  166774. /* Reset within-iMCU-row counters for a new row */
  166775. {
  166776. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166777. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  166778. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  166779. * But at the bottom of the image, process only what's left.
  166780. */
  166781. if (cinfo->comps_in_scan > 1) {
  166782. coef->MCU_rows_per_iMCU_row = 1;
  166783. } else {
  166784. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  166785. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  166786. else
  166787. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  166788. }
  166789. coef->mcu_ctr = 0;
  166790. coef->MCU_vert_offset = 0;
  166791. }
  166792. /*
  166793. * Initialize for a processing pass.
  166794. */
  166795. METHODDEF(void)
  166796. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166797. {
  166798. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166799. if (pass_mode != JBUF_CRANK_DEST)
  166800. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166801. coef->iMCU_row_num = 0;
  166802. start_iMCU_row2(cinfo);
  166803. }
  166804. /*
  166805. * Process some data.
  166806. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  166807. * per call, ie, v_samp_factor block rows for each component in the scan.
  166808. * The data is obtained from the virtual arrays and fed to the entropy coder.
  166809. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  166810. *
  166811. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  166812. */
  166813. METHODDEF(boolean)
  166814. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  166815. {
  166816. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166817. JDIMENSION MCU_col_num; /* index of current MCU within row */
  166818. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  166819. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  166820. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  166821. JDIMENSION start_col;
  166822. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  166823. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  166824. JBLOCKROW buffer_ptr;
  166825. jpeg_component_info *compptr;
  166826. /* Align the virtual buffers for the components used in this scan. */
  166827. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166828. compptr = cinfo->cur_comp_info[ci];
  166829. buffer[ci] = (*cinfo->mem->access_virt_barray)
  166830. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  166831. coef->iMCU_row_num * compptr->v_samp_factor,
  166832. (JDIMENSION) compptr->v_samp_factor, FALSE);
  166833. }
  166834. /* Loop to process one whole iMCU row */
  166835. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  166836. yoffset++) {
  166837. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  166838. MCU_col_num++) {
  166839. /* Construct list of pointers to DCT blocks belonging to this MCU */
  166840. blkn = 0; /* index of current DCT block within MCU */
  166841. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166842. compptr = cinfo->cur_comp_info[ci];
  166843. start_col = MCU_col_num * compptr->MCU_width;
  166844. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  166845. : compptr->last_col_width;
  166846. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  166847. if (coef->iMCU_row_num < last_iMCU_row ||
  166848. yindex+yoffset < compptr->last_row_height) {
  166849. /* Fill in pointers to real blocks in this row */
  166850. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  166851. for (xindex = 0; xindex < blockcnt; xindex++)
  166852. MCU_buffer[blkn++] = buffer_ptr++;
  166853. } else {
  166854. /* At bottom of image, need a whole row of dummy blocks */
  166855. xindex = 0;
  166856. }
  166857. /* Fill in any dummy blocks needed in this row.
  166858. * Dummy blocks are filled in the same way as in jccoefct.c:
  166859. * all zeroes in the AC entries, DC entries equal to previous
  166860. * block's DC value. The init routine has already zeroed the
  166861. * AC entries, so we need only set the DC entries correctly.
  166862. */
  166863. for (; xindex < compptr->MCU_width; xindex++) {
  166864. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  166865. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  166866. blkn++;
  166867. }
  166868. }
  166869. }
  166870. /* Try to write the MCU. */
  166871. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  166872. /* Suspension forced; update state counters and exit */
  166873. coef->MCU_vert_offset = yoffset;
  166874. coef->mcu_ctr = MCU_col_num;
  166875. return FALSE;
  166876. }
  166877. }
  166878. /* Completed an MCU row, but perhaps not an iMCU row */
  166879. coef->mcu_ctr = 0;
  166880. }
  166881. /* Completed the iMCU row, advance counters for next one */
  166882. coef->iMCU_row_num++;
  166883. start_iMCU_row2(cinfo);
  166884. return TRUE;
  166885. }
  166886. /*
  166887. * Initialize coefficient buffer controller.
  166888. *
  166889. * Each passed coefficient array must be the right size for that
  166890. * coefficient: width_in_blocks wide and height_in_blocks high,
  166891. * with unitheight at least v_samp_factor.
  166892. */
  166893. LOCAL(void)
  166894. transencode_coef_controller (j_compress_ptr cinfo,
  166895. jvirt_barray_ptr * coef_arrays)
  166896. {
  166897. my_coef_ptr2 coef;
  166898. JBLOCKROW buffer;
  166899. int i;
  166900. coef = (my_coef_ptr2)
  166901. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166902. SIZEOF(my_coef_controller2));
  166903. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  166904. coef->pub.start_pass = start_pass_coef2;
  166905. coef->pub.compress_data = compress_output2;
  166906. /* Save pointer to virtual arrays */
  166907. coef->whole_image = coef_arrays;
  166908. /* Allocate and pre-zero space for dummy DCT blocks. */
  166909. buffer = (JBLOCKROW)
  166910. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166911. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  166912. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  166913. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  166914. coef->dummy_buffer[i] = buffer + i;
  166915. }
  166916. }
  166917. /*** End of inlined file: jctrans.c ***/
  166918. /*** Start of inlined file: jdapistd.c ***/
  166919. #define JPEG_INTERNALS
  166920. /* Forward declarations */
  166921. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  166922. /*
  166923. * Decompression initialization.
  166924. * jpeg_read_header must be completed before calling this.
  166925. *
  166926. * If a multipass operating mode was selected, this will do all but the
  166927. * last pass, and thus may take a great deal of time.
  166928. *
  166929. * Returns FALSE if suspended. The return value need be inspected only if
  166930. * a suspending data source is used.
  166931. */
  166932. GLOBAL(boolean)
  166933. jpeg_start_decompress (j_decompress_ptr cinfo)
  166934. {
  166935. if (cinfo->global_state == DSTATE_READY) {
  166936. /* First call: initialize master control, select active modules */
  166937. jinit_master_decompress(cinfo);
  166938. if (cinfo->buffered_image) {
  166939. /* No more work here; expecting jpeg_start_output next */
  166940. cinfo->global_state = DSTATE_BUFIMAGE;
  166941. return TRUE;
  166942. }
  166943. cinfo->global_state = DSTATE_PRELOAD;
  166944. }
  166945. if (cinfo->global_state == DSTATE_PRELOAD) {
  166946. /* If file has multiple scans, absorb them all into the coef buffer */
  166947. if (cinfo->inputctl->has_multiple_scans) {
  166948. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166949. for (;;) {
  166950. int retcode;
  166951. /* Call progress monitor hook if present */
  166952. if (cinfo->progress != NULL)
  166953. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166954. /* Absorb some more input */
  166955. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  166956. if (retcode == JPEG_SUSPENDED)
  166957. return FALSE;
  166958. if (retcode == JPEG_REACHED_EOI)
  166959. break;
  166960. /* Advance progress counter if appropriate */
  166961. if (cinfo->progress != NULL &&
  166962. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  166963. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  166964. /* jdmaster underestimated number of scans; ratchet up one scan */
  166965. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  166966. }
  166967. }
  166968. }
  166969. #else
  166970. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166971. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  166972. }
  166973. cinfo->output_scan_number = cinfo->input_scan_number;
  166974. } else if (cinfo->global_state != DSTATE_PRESCAN)
  166975. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166976. /* Perform any dummy output passes, and set up for the final pass */
  166977. return output_pass_setup(cinfo);
  166978. }
  166979. /*
  166980. * Set up for an output pass, and perform any dummy pass(es) needed.
  166981. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  166982. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  166983. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  166984. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  166985. */
  166986. LOCAL(boolean)
  166987. output_pass_setup (j_decompress_ptr cinfo)
  166988. {
  166989. if (cinfo->global_state != DSTATE_PRESCAN) {
  166990. /* First call: do pass setup */
  166991. (*cinfo->master->prepare_for_output_pass) (cinfo);
  166992. cinfo->output_scanline = 0;
  166993. cinfo->global_state = DSTATE_PRESCAN;
  166994. }
  166995. /* Loop over any required dummy passes */
  166996. while (cinfo->master->is_dummy_pass) {
  166997. #ifdef QUANT_2PASS_SUPPORTED
  166998. /* Crank through the dummy pass */
  166999. while (cinfo->output_scanline < cinfo->output_height) {
  167000. JDIMENSION last_scanline;
  167001. /* Call progress monitor hook if present */
  167002. if (cinfo->progress != NULL) {
  167003. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167004. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167005. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167006. }
  167007. /* Process some data */
  167008. last_scanline = cinfo->output_scanline;
  167009. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167010. &cinfo->output_scanline, (JDIMENSION) 0);
  167011. if (cinfo->output_scanline == last_scanline)
  167012. return FALSE; /* No progress made, must suspend */
  167013. }
  167014. /* Finish up dummy pass, and set up for another one */
  167015. (*cinfo->master->finish_output_pass) (cinfo);
  167016. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167017. cinfo->output_scanline = 0;
  167018. #else
  167019. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167020. #endif /* QUANT_2PASS_SUPPORTED */
  167021. }
  167022. /* Ready for application to drive output pass through
  167023. * jpeg_read_scanlines or jpeg_read_raw_data.
  167024. */
  167025. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167026. return TRUE;
  167027. }
  167028. /*
  167029. * Read some scanlines of data from the JPEG decompressor.
  167030. *
  167031. * The return value will be the number of lines actually read.
  167032. * This may be less than the number requested in several cases,
  167033. * including bottom of image, data source suspension, and operating
  167034. * modes that emit multiple scanlines at a time.
  167035. *
  167036. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167037. * this likely signals an application programmer error. However,
  167038. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167039. */
  167040. GLOBAL(JDIMENSION)
  167041. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167042. JDIMENSION max_lines)
  167043. {
  167044. JDIMENSION row_ctr;
  167045. if (cinfo->global_state != DSTATE_SCANNING)
  167046. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167047. if (cinfo->output_scanline >= cinfo->output_height) {
  167048. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167049. return 0;
  167050. }
  167051. /* Call progress monitor hook if present */
  167052. if (cinfo->progress != NULL) {
  167053. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167054. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167055. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167056. }
  167057. /* Process some data */
  167058. row_ctr = 0;
  167059. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167060. cinfo->output_scanline += row_ctr;
  167061. return row_ctr;
  167062. }
  167063. /*
  167064. * Alternate entry point to read raw data.
  167065. * Processes exactly one iMCU row per call, unless suspended.
  167066. */
  167067. GLOBAL(JDIMENSION)
  167068. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167069. JDIMENSION max_lines)
  167070. {
  167071. JDIMENSION lines_per_iMCU_row;
  167072. if (cinfo->global_state != DSTATE_RAW_OK)
  167073. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167074. if (cinfo->output_scanline >= cinfo->output_height) {
  167075. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167076. return 0;
  167077. }
  167078. /* Call progress monitor hook if present */
  167079. if (cinfo->progress != NULL) {
  167080. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167081. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167082. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167083. }
  167084. /* Verify that at least one iMCU row can be returned. */
  167085. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167086. if (max_lines < lines_per_iMCU_row)
  167087. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167088. /* Decompress directly into user's buffer. */
  167089. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167090. return 0; /* suspension forced, can do nothing more */
  167091. /* OK, we processed one iMCU row. */
  167092. cinfo->output_scanline += lines_per_iMCU_row;
  167093. return lines_per_iMCU_row;
  167094. }
  167095. /* Additional entry points for buffered-image mode. */
  167096. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167097. /*
  167098. * Initialize for an output pass in buffered-image mode.
  167099. */
  167100. GLOBAL(boolean)
  167101. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167102. {
  167103. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167104. cinfo->global_state != DSTATE_PRESCAN)
  167105. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167106. /* Limit scan number to valid range */
  167107. if (scan_number <= 0)
  167108. scan_number = 1;
  167109. if (cinfo->inputctl->eoi_reached &&
  167110. scan_number > cinfo->input_scan_number)
  167111. scan_number = cinfo->input_scan_number;
  167112. cinfo->output_scan_number = scan_number;
  167113. /* Perform any dummy output passes, and set up for the real pass */
  167114. return output_pass_setup(cinfo);
  167115. }
  167116. /*
  167117. * Finish up after an output pass in buffered-image mode.
  167118. *
  167119. * Returns FALSE if suspended. The return value need be inspected only if
  167120. * a suspending data source is used.
  167121. */
  167122. GLOBAL(boolean)
  167123. jpeg_finish_output (j_decompress_ptr cinfo)
  167124. {
  167125. if ((cinfo->global_state == DSTATE_SCANNING ||
  167126. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167127. /* Terminate this pass. */
  167128. /* We do not require the whole pass to have been completed. */
  167129. (*cinfo->master->finish_output_pass) (cinfo);
  167130. cinfo->global_state = DSTATE_BUFPOST;
  167131. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167132. /* BUFPOST = repeat call after a suspension, anything else is error */
  167133. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167134. }
  167135. /* Read markers looking for SOS or EOI */
  167136. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167137. ! cinfo->inputctl->eoi_reached) {
  167138. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167139. return FALSE; /* Suspend, come back later */
  167140. }
  167141. cinfo->global_state = DSTATE_BUFIMAGE;
  167142. return TRUE;
  167143. }
  167144. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167145. /*** End of inlined file: jdapistd.c ***/
  167146. /*** Start of inlined file: jdapimin.c ***/
  167147. #define JPEG_INTERNALS
  167148. /*
  167149. * Initialization of a JPEG decompression object.
  167150. * The error manager must already be set up (in case memory manager fails).
  167151. */
  167152. GLOBAL(void)
  167153. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167154. {
  167155. int i;
  167156. /* Guard against version mismatches between library and caller. */
  167157. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167158. if (version != JPEG_LIB_VERSION)
  167159. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167160. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167161. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167162. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167163. /* For debugging purposes, we zero the whole master structure.
  167164. * But the application has already set the err pointer, and may have set
  167165. * client_data, so we have to save and restore those fields.
  167166. * Note: if application hasn't set client_data, tools like Purify may
  167167. * complain here.
  167168. */
  167169. {
  167170. struct jpeg_error_mgr * err = cinfo->err;
  167171. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167172. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167173. cinfo->err = err;
  167174. cinfo->client_data = client_data;
  167175. }
  167176. cinfo->is_decompressor = TRUE;
  167177. /* Initialize a memory manager instance for this object */
  167178. jinit_memory_mgr((j_common_ptr) cinfo);
  167179. /* Zero out pointers to permanent structures. */
  167180. cinfo->progress = NULL;
  167181. cinfo->src = NULL;
  167182. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167183. cinfo->quant_tbl_ptrs[i] = NULL;
  167184. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167185. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167186. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167187. }
  167188. /* Initialize marker processor so application can override methods
  167189. * for COM, APPn markers before calling jpeg_read_header.
  167190. */
  167191. cinfo->marker_list = NULL;
  167192. jinit_marker_reader(cinfo);
  167193. /* And initialize the overall input controller. */
  167194. jinit_input_controller(cinfo);
  167195. /* OK, I'm ready */
  167196. cinfo->global_state = DSTATE_START;
  167197. }
  167198. /*
  167199. * Destruction of a JPEG decompression object
  167200. */
  167201. GLOBAL(void)
  167202. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167203. {
  167204. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167205. }
  167206. /*
  167207. * Abort processing of a JPEG decompression operation,
  167208. * but don't destroy the object itself.
  167209. */
  167210. GLOBAL(void)
  167211. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167212. {
  167213. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167214. }
  167215. /*
  167216. * Set default decompression parameters.
  167217. */
  167218. LOCAL(void)
  167219. default_decompress_parms (j_decompress_ptr cinfo)
  167220. {
  167221. /* Guess the input colorspace, and set output colorspace accordingly. */
  167222. /* (Wish JPEG committee had provided a real way to specify this...) */
  167223. /* Note application may override our guesses. */
  167224. switch (cinfo->num_components) {
  167225. case 1:
  167226. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167227. cinfo->out_color_space = JCS_GRAYSCALE;
  167228. break;
  167229. case 3:
  167230. if (cinfo->saw_JFIF_marker) {
  167231. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167232. } else if (cinfo->saw_Adobe_marker) {
  167233. switch (cinfo->Adobe_transform) {
  167234. case 0:
  167235. cinfo->jpeg_color_space = JCS_RGB;
  167236. break;
  167237. case 1:
  167238. cinfo->jpeg_color_space = JCS_YCbCr;
  167239. break;
  167240. default:
  167241. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167242. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167243. break;
  167244. }
  167245. } else {
  167246. /* Saw no special markers, try to guess from the component IDs */
  167247. int cid0 = cinfo->comp_info[0].component_id;
  167248. int cid1 = cinfo->comp_info[1].component_id;
  167249. int cid2 = cinfo->comp_info[2].component_id;
  167250. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167251. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167252. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167253. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167254. else {
  167255. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167256. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167257. }
  167258. }
  167259. /* Always guess RGB is proper output colorspace. */
  167260. cinfo->out_color_space = JCS_RGB;
  167261. break;
  167262. case 4:
  167263. if (cinfo->saw_Adobe_marker) {
  167264. switch (cinfo->Adobe_transform) {
  167265. case 0:
  167266. cinfo->jpeg_color_space = JCS_CMYK;
  167267. break;
  167268. case 2:
  167269. cinfo->jpeg_color_space = JCS_YCCK;
  167270. break;
  167271. default:
  167272. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167273. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  167274. break;
  167275. }
  167276. } else {
  167277. /* No special markers, assume straight CMYK. */
  167278. cinfo->jpeg_color_space = JCS_CMYK;
  167279. }
  167280. cinfo->out_color_space = JCS_CMYK;
  167281. break;
  167282. default:
  167283. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167284. cinfo->out_color_space = JCS_UNKNOWN;
  167285. break;
  167286. }
  167287. /* Set defaults for other decompression parameters. */
  167288. cinfo->scale_num = 1; /* 1:1 scaling */
  167289. cinfo->scale_denom = 1;
  167290. cinfo->output_gamma = 1.0;
  167291. cinfo->buffered_image = FALSE;
  167292. cinfo->raw_data_out = FALSE;
  167293. cinfo->dct_method = JDCT_DEFAULT;
  167294. cinfo->do_fancy_upsampling = TRUE;
  167295. cinfo->do_block_smoothing = TRUE;
  167296. cinfo->quantize_colors = FALSE;
  167297. /* We set these in case application only sets quantize_colors. */
  167298. cinfo->dither_mode = JDITHER_FS;
  167299. #ifdef QUANT_2PASS_SUPPORTED
  167300. cinfo->two_pass_quantize = TRUE;
  167301. #else
  167302. cinfo->two_pass_quantize = FALSE;
  167303. #endif
  167304. cinfo->desired_number_of_colors = 256;
  167305. cinfo->colormap = NULL;
  167306. /* Initialize for no mode change in buffered-image mode. */
  167307. cinfo->enable_1pass_quant = FALSE;
  167308. cinfo->enable_external_quant = FALSE;
  167309. cinfo->enable_2pass_quant = FALSE;
  167310. }
  167311. /*
  167312. * Decompression startup: read start of JPEG datastream to see what's there.
  167313. * Need only initialize JPEG object and supply a data source before calling.
  167314. *
  167315. * This routine will read as far as the first SOS marker (ie, actual start of
  167316. * compressed data), and will save all tables and parameters in the JPEG
  167317. * object. It will also initialize the decompression parameters to default
  167318. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167319. * adjust the decompression parameters and then call jpeg_start_decompress.
  167320. * (Or, if the application only wanted to determine the image parameters,
  167321. * the data need not be decompressed. In that case, call jpeg_abort or
  167322. * jpeg_destroy to release any temporary space.)
  167323. * If an abbreviated (tables only) datastream is presented, the routine will
  167324. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167325. * re-use the JPEG object to read the abbreviated image datastream(s).
  167326. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167327. * The JPEG_SUSPENDED return code only occurs if the data source module
  167328. * requests suspension of the decompressor. In this case the application
  167329. * should load more source data and then re-call jpeg_read_header to resume
  167330. * processing.
  167331. * If a non-suspending data source is used and require_image is TRUE, then the
  167332. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167333. *
  167334. * This routine is now just a front end to jpeg_consume_input, with some
  167335. * extra error checking.
  167336. */
  167337. GLOBAL(int)
  167338. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167339. {
  167340. int retcode;
  167341. if (cinfo->global_state != DSTATE_START &&
  167342. cinfo->global_state != DSTATE_INHEADER)
  167343. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167344. retcode = jpeg_consume_input(cinfo);
  167345. switch (retcode) {
  167346. case JPEG_REACHED_SOS:
  167347. retcode = JPEG_HEADER_OK;
  167348. break;
  167349. case JPEG_REACHED_EOI:
  167350. if (require_image) /* Complain if application wanted an image */
  167351. ERREXIT(cinfo, JERR_NO_IMAGE);
  167352. /* Reset to start state; it would be safer to require the application to
  167353. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167354. * A side effect is to free any temporary memory (there shouldn't be any).
  167355. */
  167356. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167357. retcode = JPEG_HEADER_TABLES_ONLY;
  167358. break;
  167359. case JPEG_SUSPENDED:
  167360. /* no work */
  167361. break;
  167362. }
  167363. return retcode;
  167364. }
  167365. /*
  167366. * Consume data in advance of what the decompressor requires.
  167367. * This can be called at any time once the decompressor object has
  167368. * been created and a data source has been set up.
  167369. *
  167370. * This routine is essentially a state machine that handles a couple
  167371. * of critical state-transition actions, namely initial setup and
  167372. * transition from header scanning to ready-for-start_decompress.
  167373. * All the actual input is done via the input controller's consume_input
  167374. * method.
  167375. */
  167376. GLOBAL(int)
  167377. jpeg_consume_input (j_decompress_ptr cinfo)
  167378. {
  167379. int retcode = JPEG_SUSPENDED;
  167380. /* NB: every possible DSTATE value should be listed in this switch */
  167381. switch (cinfo->global_state) {
  167382. case DSTATE_START:
  167383. /* Start-of-datastream actions: reset appropriate modules */
  167384. (*cinfo->inputctl->reset_input_controller) (cinfo);
  167385. /* Initialize application's data source module */
  167386. (*cinfo->src->init_source) (cinfo);
  167387. cinfo->global_state = DSTATE_INHEADER;
  167388. /*FALLTHROUGH*/
  167389. case DSTATE_INHEADER:
  167390. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167391. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  167392. /* Set up default parameters based on header data */
  167393. default_decompress_parms(cinfo);
  167394. /* Set global state: ready for start_decompress */
  167395. cinfo->global_state = DSTATE_READY;
  167396. }
  167397. break;
  167398. case DSTATE_READY:
  167399. /* Can't advance past first SOS until start_decompress is called */
  167400. retcode = JPEG_REACHED_SOS;
  167401. break;
  167402. case DSTATE_PRELOAD:
  167403. case DSTATE_PRESCAN:
  167404. case DSTATE_SCANNING:
  167405. case DSTATE_RAW_OK:
  167406. case DSTATE_BUFIMAGE:
  167407. case DSTATE_BUFPOST:
  167408. case DSTATE_STOPPING:
  167409. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167410. break;
  167411. default:
  167412. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167413. }
  167414. return retcode;
  167415. }
  167416. /*
  167417. * Have we finished reading the input file?
  167418. */
  167419. GLOBAL(boolean)
  167420. jpeg_input_complete (j_decompress_ptr cinfo)
  167421. {
  167422. /* Check for valid jpeg object */
  167423. if (cinfo->global_state < DSTATE_START ||
  167424. cinfo->global_state > DSTATE_STOPPING)
  167425. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167426. return cinfo->inputctl->eoi_reached;
  167427. }
  167428. /*
  167429. * Is there more than one scan?
  167430. */
  167431. GLOBAL(boolean)
  167432. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  167433. {
  167434. /* Only valid after jpeg_read_header completes */
  167435. if (cinfo->global_state < DSTATE_READY ||
  167436. cinfo->global_state > DSTATE_STOPPING)
  167437. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167438. return cinfo->inputctl->has_multiple_scans;
  167439. }
  167440. /*
  167441. * Finish JPEG decompression.
  167442. *
  167443. * This will normally just verify the file trailer and release temp storage.
  167444. *
  167445. * Returns FALSE if suspended. The return value need be inspected only if
  167446. * a suspending data source is used.
  167447. */
  167448. GLOBAL(boolean)
  167449. jpeg_finish_decompress (j_decompress_ptr cinfo)
  167450. {
  167451. if ((cinfo->global_state == DSTATE_SCANNING ||
  167452. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  167453. /* Terminate final pass of non-buffered mode */
  167454. if (cinfo->output_scanline < cinfo->output_height)
  167455. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  167456. (*cinfo->master->finish_output_pass) (cinfo);
  167457. cinfo->global_state = DSTATE_STOPPING;
  167458. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  167459. /* Finishing after a buffered-image operation */
  167460. cinfo->global_state = DSTATE_STOPPING;
  167461. } else if (cinfo->global_state != DSTATE_STOPPING) {
  167462. /* STOPPING = repeat call after a suspension, anything else is error */
  167463. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167464. }
  167465. /* Read until EOI */
  167466. while (! cinfo->inputctl->eoi_reached) {
  167467. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167468. return FALSE; /* Suspend, come back later */
  167469. }
  167470. /* Do final cleanup */
  167471. (*cinfo->src->term_source) (cinfo);
  167472. /* We can use jpeg_abort to release memory and reset global_state */
  167473. jpeg_abort((j_common_ptr) cinfo);
  167474. return TRUE;
  167475. }
  167476. /*** End of inlined file: jdapimin.c ***/
  167477. /*** Start of inlined file: jdatasrc.c ***/
  167478. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  167479. /*** Start of inlined file: jerror.h ***/
  167480. /*
  167481. * To define the enum list of message codes, include this file without
  167482. * defining macro JMESSAGE. To create a message string table, include it
  167483. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  167484. */
  167485. #ifndef JMESSAGE
  167486. #ifndef JERROR_H
  167487. /* First time through, define the enum list */
  167488. #define JMAKE_ENUM_LIST
  167489. #else
  167490. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  167491. #define JMESSAGE(code,string)
  167492. #endif /* JERROR_H */
  167493. #endif /* JMESSAGE */
  167494. #ifdef JMAKE_ENUM_LIST
  167495. typedef enum {
  167496. #define JMESSAGE(code,string) code ,
  167497. #endif /* JMAKE_ENUM_LIST */
  167498. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  167499. /* For maintenance convenience, list is alphabetical by message code name */
  167500. JMESSAGE(JERR_ARITH_NOTIMPL,
  167501. "Sorry, there are legal restrictions on arithmetic coding")
  167502. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  167503. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  167504. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  167505. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  167506. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  167507. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  167508. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  167509. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  167510. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  167511. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  167512. JMESSAGE(JERR_BAD_LIB_VERSION,
  167513. "Wrong JPEG library version: library is %d, caller expects %d")
  167514. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  167515. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  167516. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  167517. JMESSAGE(JERR_BAD_PROGRESSION,
  167518. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  167519. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  167520. "Invalid progressive parameters at scan script entry %d")
  167521. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  167522. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  167523. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  167524. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  167525. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  167526. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  167527. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  167528. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  167529. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  167530. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  167531. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  167532. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  167533. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  167534. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  167535. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  167536. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  167537. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  167538. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  167539. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  167540. JMESSAGE(JERR_FILE_READ, "Input file read error")
  167541. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  167542. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  167543. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  167544. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  167545. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  167546. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  167547. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  167548. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  167549. "Cannot transcode due to multiple use of quantization table %d")
  167550. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  167551. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  167552. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  167553. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  167554. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  167555. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  167556. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  167557. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  167558. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  167559. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  167560. JMESSAGE(JERR_QUANT_COMPONENTS,
  167561. "Cannot quantize more than %d color components")
  167562. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  167563. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  167564. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  167565. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  167566. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  167567. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  167568. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  167569. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  167570. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  167571. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  167572. JMESSAGE(JERR_TFILE_WRITE,
  167573. "Write failed on temporary file --- out of disk space?")
  167574. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  167575. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  167576. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  167577. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  167578. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  167579. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  167580. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  167581. JMESSAGE(JMSG_VERSION, JVERSION)
  167582. JMESSAGE(JTRC_16BIT_TABLES,
  167583. "Caution: quantization tables are too coarse for baseline JPEG")
  167584. JMESSAGE(JTRC_ADOBE,
  167585. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  167586. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  167587. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  167588. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  167589. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  167590. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  167591. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  167592. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  167593. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  167594. JMESSAGE(JTRC_EOI, "End Of Image")
  167595. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  167596. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  167597. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  167598. "Warning: thumbnail image size does not match data length %u")
  167599. JMESSAGE(JTRC_JFIF_EXTENSION,
  167600. "JFIF extension marker: type 0x%02x, length %u")
  167601. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  167602. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  167603. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  167604. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  167605. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  167606. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  167607. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  167608. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  167609. JMESSAGE(JTRC_RST, "RST%d")
  167610. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  167611. "Smoothing not supported with nonstandard sampling ratios")
  167612. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  167613. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  167614. JMESSAGE(JTRC_SOI, "Start of Image")
  167615. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  167616. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  167617. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  167618. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  167619. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  167620. JMESSAGE(JTRC_THUMB_JPEG,
  167621. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  167622. JMESSAGE(JTRC_THUMB_PALETTE,
  167623. "JFIF extension marker: palette thumbnail image, length %u")
  167624. JMESSAGE(JTRC_THUMB_RGB,
  167625. "JFIF extension marker: RGB thumbnail image, length %u")
  167626. JMESSAGE(JTRC_UNKNOWN_IDS,
  167627. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  167628. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  167629. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  167630. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  167631. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  167632. "Inconsistent progression sequence for component %d coefficient %d")
  167633. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  167634. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  167635. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  167636. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  167637. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  167638. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  167639. JMESSAGE(JWRN_MUST_RESYNC,
  167640. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  167641. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  167642. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  167643. #ifdef JMAKE_ENUM_LIST
  167644. JMSG_LASTMSGCODE
  167645. } J_MESSAGE_CODE;
  167646. #undef JMAKE_ENUM_LIST
  167647. #endif /* JMAKE_ENUM_LIST */
  167648. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  167649. #undef JMESSAGE
  167650. #ifndef JERROR_H
  167651. #define JERROR_H
  167652. /* Macros to simplify using the error and trace message stuff */
  167653. /* The first parameter is either type of cinfo pointer */
  167654. /* Fatal errors (print message and exit) */
  167655. #define ERREXIT(cinfo,code) \
  167656. ((cinfo)->err->msg_code = (code), \
  167657. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167658. #define ERREXIT1(cinfo,code,p1) \
  167659. ((cinfo)->err->msg_code = (code), \
  167660. (cinfo)->err->msg_parm.i[0] = (p1), \
  167661. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167662. #define ERREXIT2(cinfo,code,p1,p2) \
  167663. ((cinfo)->err->msg_code = (code), \
  167664. (cinfo)->err->msg_parm.i[0] = (p1), \
  167665. (cinfo)->err->msg_parm.i[1] = (p2), \
  167666. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167667. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  167668. ((cinfo)->err->msg_code = (code), \
  167669. (cinfo)->err->msg_parm.i[0] = (p1), \
  167670. (cinfo)->err->msg_parm.i[1] = (p2), \
  167671. (cinfo)->err->msg_parm.i[2] = (p3), \
  167672. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167673. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  167674. ((cinfo)->err->msg_code = (code), \
  167675. (cinfo)->err->msg_parm.i[0] = (p1), \
  167676. (cinfo)->err->msg_parm.i[1] = (p2), \
  167677. (cinfo)->err->msg_parm.i[2] = (p3), \
  167678. (cinfo)->err->msg_parm.i[3] = (p4), \
  167679. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167680. #define ERREXITS(cinfo,code,str) \
  167681. ((cinfo)->err->msg_code = (code), \
  167682. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167683. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167684. #define MAKESTMT(stuff) do { stuff } while (0)
  167685. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  167686. #define WARNMS(cinfo,code) \
  167687. ((cinfo)->err->msg_code = (code), \
  167688. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167689. #define WARNMS1(cinfo,code,p1) \
  167690. ((cinfo)->err->msg_code = (code), \
  167691. (cinfo)->err->msg_parm.i[0] = (p1), \
  167692. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167693. #define WARNMS2(cinfo,code,p1,p2) \
  167694. ((cinfo)->err->msg_code = (code), \
  167695. (cinfo)->err->msg_parm.i[0] = (p1), \
  167696. (cinfo)->err->msg_parm.i[1] = (p2), \
  167697. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167698. /* Informational/debugging messages */
  167699. #define TRACEMS(cinfo,lvl,code) \
  167700. ((cinfo)->err->msg_code = (code), \
  167701. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167702. #define TRACEMS1(cinfo,lvl,code,p1) \
  167703. ((cinfo)->err->msg_code = (code), \
  167704. (cinfo)->err->msg_parm.i[0] = (p1), \
  167705. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167706. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  167707. ((cinfo)->err->msg_code = (code), \
  167708. (cinfo)->err->msg_parm.i[0] = (p1), \
  167709. (cinfo)->err->msg_parm.i[1] = (p2), \
  167710. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167711. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  167712. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167713. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  167714. (cinfo)->err->msg_code = (code); \
  167715. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167716. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  167717. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167718. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167719. (cinfo)->err->msg_code = (code); \
  167720. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167721. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  167722. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167723. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167724. _mp[4] = (p5); \
  167725. (cinfo)->err->msg_code = (code); \
  167726. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167727. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  167728. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167729. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167730. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  167731. (cinfo)->err->msg_code = (code); \
  167732. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167733. #define TRACEMSS(cinfo,lvl,code,str) \
  167734. ((cinfo)->err->msg_code = (code), \
  167735. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167736. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167737. #endif /* JERROR_H */
  167738. /*** End of inlined file: jerror.h ***/
  167739. /* Expanded data source object for stdio input */
  167740. typedef struct {
  167741. struct jpeg_source_mgr pub; /* public fields */
  167742. FILE * infile; /* source stream */
  167743. JOCTET * buffer; /* start of buffer */
  167744. boolean start_of_file; /* have we gotten any data yet? */
  167745. } my_source_mgr;
  167746. typedef my_source_mgr * my_src_ptr;
  167747. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  167748. /*
  167749. * Initialize source --- called by jpeg_read_header
  167750. * before any data is actually read.
  167751. */
  167752. METHODDEF(void)
  167753. init_source (j_decompress_ptr cinfo)
  167754. {
  167755. my_src_ptr src = (my_src_ptr) cinfo->src;
  167756. /* We reset the empty-input-file flag for each image,
  167757. * but we don't clear the input buffer.
  167758. * This is correct behavior for reading a series of images from one source.
  167759. */
  167760. src->start_of_file = TRUE;
  167761. }
  167762. /*
  167763. * Fill the input buffer --- called whenever buffer is emptied.
  167764. *
  167765. * In typical applications, this should read fresh data into the buffer
  167766. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  167767. * reset the pointer & count to the start of the buffer, and return TRUE
  167768. * indicating that the buffer has been reloaded. It is not necessary to
  167769. * fill the buffer entirely, only to obtain at least one more byte.
  167770. *
  167771. * There is no such thing as an EOF return. If the end of the file has been
  167772. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  167773. * the buffer. In most cases, generating a warning message and inserting a
  167774. * fake EOI marker is the best course of action --- this will allow the
  167775. * decompressor to output however much of the image is there. However,
  167776. * the resulting error message is misleading if the real problem is an empty
  167777. * input file, so we handle that case specially.
  167778. *
  167779. * In applications that need to be able to suspend compression due to input
  167780. * not being available yet, a FALSE return indicates that no more data can be
  167781. * obtained right now, but more may be forthcoming later. In this situation,
  167782. * the decompressor will return to its caller (with an indication of the
  167783. * number of scanlines it has read, if any). The application should resume
  167784. * decompression after it has loaded more data into the input buffer. Note
  167785. * that there are substantial restrictions on the use of suspension --- see
  167786. * the documentation.
  167787. *
  167788. * When suspending, the decompressor will back up to a convenient restart point
  167789. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  167790. * indicate where the restart point will be if the current call returns FALSE.
  167791. * Data beyond this point must be rescanned after resumption, so move it to
  167792. * the front of the buffer rather than discarding it.
  167793. */
  167794. METHODDEF(boolean)
  167795. fill_input_buffer (j_decompress_ptr cinfo)
  167796. {
  167797. my_src_ptr src = (my_src_ptr) cinfo->src;
  167798. size_t nbytes;
  167799. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  167800. if (nbytes <= 0) {
  167801. if (src->start_of_file) /* Treat empty input file as fatal error */
  167802. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  167803. WARNMS(cinfo, JWRN_JPEG_EOF);
  167804. /* Insert a fake EOI marker */
  167805. src->buffer[0] = (JOCTET) 0xFF;
  167806. src->buffer[1] = (JOCTET) JPEG_EOI;
  167807. nbytes = 2;
  167808. }
  167809. src->pub.next_input_byte = src->buffer;
  167810. src->pub.bytes_in_buffer = nbytes;
  167811. src->start_of_file = FALSE;
  167812. return TRUE;
  167813. }
  167814. /*
  167815. * Skip data --- used to skip over a potentially large amount of
  167816. * uninteresting data (such as an APPn marker).
  167817. *
  167818. * Writers of suspendable-input applications must note that skip_input_data
  167819. * is not granted the right to give a suspension return. If the skip extends
  167820. * beyond the data currently in the buffer, the buffer can be marked empty so
  167821. * that the next read will cause a fill_input_buffer call that can suspend.
  167822. * Arranging for additional bytes to be discarded before reloading the input
  167823. * buffer is the application writer's problem.
  167824. */
  167825. METHODDEF(void)
  167826. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  167827. {
  167828. my_src_ptr src = (my_src_ptr) cinfo->src;
  167829. /* Just a dumb implementation for now. Could use fseek() except
  167830. * it doesn't work on pipes. Not clear that being smart is worth
  167831. * any trouble anyway --- large skips are infrequent.
  167832. */
  167833. if (num_bytes > 0) {
  167834. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  167835. num_bytes -= (long) src->pub.bytes_in_buffer;
  167836. (void) fill_input_buffer(cinfo);
  167837. /* note we assume that fill_input_buffer will never return FALSE,
  167838. * so suspension need not be handled.
  167839. */
  167840. }
  167841. src->pub.next_input_byte += (size_t) num_bytes;
  167842. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  167843. }
  167844. }
  167845. /*
  167846. * An additional method that can be provided by data source modules is the
  167847. * resync_to_restart method for error recovery in the presence of RST markers.
  167848. * For the moment, this source module just uses the default resync method
  167849. * provided by the JPEG library. That method assumes that no backtracking
  167850. * is possible.
  167851. */
  167852. /*
  167853. * Terminate source --- called by jpeg_finish_decompress
  167854. * after all data has been read. Often a no-op.
  167855. *
  167856. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  167857. * application must deal with any cleanup that should happen even
  167858. * for error exit.
  167859. */
  167860. METHODDEF(void)
  167861. term_source (j_decompress_ptr)
  167862. {
  167863. /* no work necessary here */
  167864. }
  167865. /*
  167866. * Prepare for input from a stdio stream.
  167867. * The caller must have already opened the stream, and is responsible
  167868. * for closing it after finishing decompression.
  167869. */
  167870. GLOBAL(void)
  167871. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  167872. {
  167873. my_src_ptr src;
  167874. /* The source object and input buffer are made permanent so that a series
  167875. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  167876. * only before the first one. (If we discarded the buffer at the end of
  167877. * one image, we'd likely lose the start of the next one.)
  167878. * This makes it unsafe to use this manager and a different source
  167879. * manager serially with the same JPEG object. Caveat programmer.
  167880. */
  167881. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  167882. cinfo->src = (struct jpeg_source_mgr *)
  167883. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167884. SIZEOF(my_source_mgr));
  167885. src = (my_src_ptr) cinfo->src;
  167886. src->buffer = (JOCTET *)
  167887. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167888. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  167889. }
  167890. src = (my_src_ptr) cinfo->src;
  167891. src->pub.init_source = init_source;
  167892. src->pub.fill_input_buffer = fill_input_buffer;
  167893. src->pub.skip_input_data = skip_input_data;
  167894. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  167895. src->pub.term_source = term_source;
  167896. src->infile = infile;
  167897. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  167898. src->pub.next_input_byte = NULL; /* until buffer loaded */
  167899. }
  167900. /*** End of inlined file: jdatasrc.c ***/
  167901. /*** Start of inlined file: jdcoefct.c ***/
  167902. #define JPEG_INTERNALS
  167903. /* Block smoothing is only applicable for progressive JPEG, so: */
  167904. #ifndef D_PROGRESSIVE_SUPPORTED
  167905. #undef BLOCK_SMOOTHING_SUPPORTED
  167906. #endif
  167907. /* Private buffer controller object */
  167908. typedef struct {
  167909. struct jpeg_d_coef_controller pub; /* public fields */
  167910. /* These variables keep track of the current location of the input side. */
  167911. /* cinfo->input_iMCU_row is also used for this. */
  167912. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  167913. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167914. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167915. /* The output side's location is represented by cinfo->output_iMCU_row. */
  167916. /* In single-pass modes, it's sufficient to buffer just one MCU.
  167917. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  167918. * and let the entropy decoder write into that workspace each time.
  167919. * (On 80x86, the workspace is FAR even though it's not really very big;
  167920. * this is to keep the module interfaces unchanged when a large coefficient
  167921. * buffer is necessary.)
  167922. * In multi-pass modes, this array points to the current MCU's blocks
  167923. * within the virtual arrays; it is used only by the input side.
  167924. */
  167925. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  167926. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167927. /* In multi-pass modes, we need a virtual block array for each component. */
  167928. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  167929. #endif
  167930. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167931. /* When doing block smoothing, we latch coefficient Al values here */
  167932. int * coef_bits_latch;
  167933. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  167934. #endif
  167935. } my_coef_controller3;
  167936. typedef my_coef_controller3 * my_coef_ptr3;
  167937. /* Forward declarations */
  167938. METHODDEF(int) decompress_onepass
  167939. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167940. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167941. METHODDEF(int) decompress_data
  167942. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167943. #endif
  167944. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167945. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  167946. METHODDEF(int) decompress_smooth_data
  167947. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167948. #endif
  167949. LOCAL(void)
  167950. start_iMCU_row3 (j_decompress_ptr cinfo)
  167951. /* Reset within-iMCU-row counters for a new row (input side) */
  167952. {
  167953. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167954. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167955. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167956. * But at the bottom of the image, process only what's left.
  167957. */
  167958. if (cinfo->comps_in_scan > 1) {
  167959. coef->MCU_rows_per_iMCU_row = 1;
  167960. } else {
  167961. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  167962. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167963. else
  167964. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167965. }
  167966. coef->MCU_ctr = 0;
  167967. coef->MCU_vert_offset = 0;
  167968. }
  167969. /*
  167970. * Initialize for an input processing pass.
  167971. */
  167972. METHODDEF(void)
  167973. start_input_pass (j_decompress_ptr cinfo)
  167974. {
  167975. cinfo->input_iMCU_row = 0;
  167976. start_iMCU_row3(cinfo);
  167977. }
  167978. /*
  167979. * Initialize for an output processing pass.
  167980. */
  167981. METHODDEF(void)
  167982. start_output_pass (j_decompress_ptr cinfo)
  167983. {
  167984. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167985. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167986. /* If multipass, check to see whether to use block smoothing on this pass */
  167987. if (coef->pub.coef_arrays != NULL) {
  167988. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  167989. coef->pub.decompress_data = decompress_smooth_data;
  167990. else
  167991. coef->pub.decompress_data = decompress_data;
  167992. }
  167993. #endif
  167994. cinfo->output_iMCU_row = 0;
  167995. }
  167996. /*
  167997. * Decompress and return some data in the single-pass case.
  167998. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  167999. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168000. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168001. *
  168002. * NB: output_buf contains a plane for each component in image,
  168003. * which we index according to the component's SOF position.
  168004. */
  168005. METHODDEF(int)
  168006. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168007. {
  168008. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168009. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168010. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168011. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168012. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168013. JSAMPARRAY output_ptr;
  168014. JDIMENSION start_col, output_col;
  168015. jpeg_component_info *compptr;
  168016. inverse_DCT_method_ptr inverse_DCT;
  168017. /* Loop to process as much as one whole iMCU row */
  168018. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168019. yoffset++) {
  168020. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168021. MCU_col_num++) {
  168022. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168023. jzero_far((void FAR *) coef->MCU_buffer[0],
  168024. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168025. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168026. /* Suspension forced; update state counters and exit */
  168027. coef->MCU_vert_offset = yoffset;
  168028. coef->MCU_ctr = MCU_col_num;
  168029. return JPEG_SUSPENDED;
  168030. }
  168031. /* Determine where data should go in output_buf and do the IDCT thing.
  168032. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168033. * incremented past them!). Note the inner loop relies on having
  168034. * allocated the MCU_buffer[] blocks sequentially.
  168035. */
  168036. blkn = 0; /* index of current DCT block within MCU */
  168037. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168038. compptr = cinfo->cur_comp_info[ci];
  168039. /* Don't bother to IDCT an uninteresting component. */
  168040. if (! compptr->component_needed) {
  168041. blkn += compptr->MCU_blocks;
  168042. continue;
  168043. }
  168044. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168045. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168046. : compptr->last_col_width;
  168047. output_ptr = output_buf[compptr->component_index] +
  168048. yoffset * compptr->DCT_scaled_size;
  168049. start_col = MCU_col_num * compptr->MCU_sample_width;
  168050. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168051. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168052. yoffset+yindex < compptr->last_row_height) {
  168053. output_col = start_col;
  168054. for (xindex = 0; xindex < useful_width; xindex++) {
  168055. (*inverse_DCT) (cinfo, compptr,
  168056. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168057. output_ptr, output_col);
  168058. output_col += compptr->DCT_scaled_size;
  168059. }
  168060. }
  168061. blkn += compptr->MCU_width;
  168062. output_ptr += compptr->DCT_scaled_size;
  168063. }
  168064. }
  168065. }
  168066. /* Completed an MCU row, but perhaps not an iMCU row */
  168067. coef->MCU_ctr = 0;
  168068. }
  168069. /* Completed the iMCU row, advance counters for next one */
  168070. cinfo->output_iMCU_row++;
  168071. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168072. start_iMCU_row3(cinfo);
  168073. return JPEG_ROW_COMPLETED;
  168074. }
  168075. /* Completed the scan */
  168076. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168077. return JPEG_SCAN_COMPLETED;
  168078. }
  168079. /*
  168080. * Dummy consume-input routine for single-pass operation.
  168081. */
  168082. METHODDEF(int)
  168083. dummy_consume_data (j_decompress_ptr)
  168084. {
  168085. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168086. }
  168087. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168088. /*
  168089. * Consume input data and store it in the full-image coefficient buffer.
  168090. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168091. * ie, v_samp_factor block rows for each component in the scan.
  168092. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168093. */
  168094. METHODDEF(int)
  168095. consume_data (j_decompress_ptr cinfo)
  168096. {
  168097. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168098. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168099. int blkn, ci, xindex, yindex, yoffset;
  168100. JDIMENSION start_col;
  168101. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168102. JBLOCKROW buffer_ptr;
  168103. jpeg_component_info *compptr;
  168104. /* Align the virtual buffers for the components used in this scan. */
  168105. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168106. compptr = cinfo->cur_comp_info[ci];
  168107. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168108. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168109. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168110. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168111. /* Note: entropy decoder expects buffer to be zeroed,
  168112. * but this is handled automatically by the memory manager
  168113. * because we requested a pre-zeroed array.
  168114. */
  168115. }
  168116. /* Loop to process one whole iMCU row */
  168117. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168118. yoffset++) {
  168119. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168120. MCU_col_num++) {
  168121. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168122. blkn = 0; /* index of current DCT block within MCU */
  168123. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168124. compptr = cinfo->cur_comp_info[ci];
  168125. start_col = MCU_col_num * compptr->MCU_width;
  168126. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168127. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168128. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168129. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168130. }
  168131. }
  168132. }
  168133. /* Try to fetch the MCU. */
  168134. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168135. /* Suspension forced; update state counters and exit */
  168136. coef->MCU_vert_offset = yoffset;
  168137. coef->MCU_ctr = MCU_col_num;
  168138. return JPEG_SUSPENDED;
  168139. }
  168140. }
  168141. /* Completed an MCU row, but perhaps not an iMCU row */
  168142. coef->MCU_ctr = 0;
  168143. }
  168144. /* Completed the iMCU row, advance counters for next one */
  168145. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168146. start_iMCU_row3(cinfo);
  168147. return JPEG_ROW_COMPLETED;
  168148. }
  168149. /* Completed the scan */
  168150. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168151. return JPEG_SCAN_COMPLETED;
  168152. }
  168153. /*
  168154. * Decompress and return some data in the multi-pass case.
  168155. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168156. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168157. *
  168158. * NB: output_buf contains a plane for each component in image.
  168159. */
  168160. METHODDEF(int)
  168161. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168162. {
  168163. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168164. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168165. JDIMENSION block_num;
  168166. int ci, block_row, block_rows;
  168167. JBLOCKARRAY buffer;
  168168. JBLOCKROW buffer_ptr;
  168169. JSAMPARRAY output_ptr;
  168170. JDIMENSION output_col;
  168171. jpeg_component_info *compptr;
  168172. inverse_DCT_method_ptr inverse_DCT;
  168173. /* Force some input to be done if we are getting ahead of the input. */
  168174. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168175. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168176. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168177. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168178. return JPEG_SUSPENDED;
  168179. }
  168180. /* OK, output from the virtual arrays. */
  168181. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168182. ci++, compptr++) {
  168183. /* Don't bother to IDCT an uninteresting component. */
  168184. if (! compptr->component_needed)
  168185. continue;
  168186. /* Align the virtual buffer for this component. */
  168187. buffer = (*cinfo->mem->access_virt_barray)
  168188. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168189. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168190. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168191. /* Count non-dummy DCT block rows in this iMCU row. */
  168192. if (cinfo->output_iMCU_row < last_iMCU_row)
  168193. block_rows = compptr->v_samp_factor;
  168194. else {
  168195. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168196. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168197. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168198. }
  168199. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168200. output_ptr = output_buf[ci];
  168201. /* Loop over all DCT blocks to be processed. */
  168202. for (block_row = 0; block_row < block_rows; block_row++) {
  168203. buffer_ptr = buffer[block_row];
  168204. output_col = 0;
  168205. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168206. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168207. output_ptr, output_col);
  168208. buffer_ptr++;
  168209. output_col += compptr->DCT_scaled_size;
  168210. }
  168211. output_ptr += compptr->DCT_scaled_size;
  168212. }
  168213. }
  168214. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168215. return JPEG_ROW_COMPLETED;
  168216. return JPEG_SCAN_COMPLETED;
  168217. }
  168218. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168219. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168220. /*
  168221. * This code applies interblock smoothing as described by section K.8
  168222. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168223. * the DC values of a DCT block and its 8 neighboring blocks.
  168224. * We apply smoothing only for progressive JPEG decoding, and only if
  168225. * the coefficients it can estimate are not yet known to full precision.
  168226. */
  168227. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168228. #define Q01_POS 1
  168229. #define Q10_POS 8
  168230. #define Q20_POS 16
  168231. #define Q11_POS 9
  168232. #define Q02_POS 2
  168233. /*
  168234. * Determine whether block smoothing is applicable and safe.
  168235. * We also latch the current states of the coef_bits[] entries for the
  168236. * AC coefficients; otherwise, if the input side of the decompressor
  168237. * advances into a new scan, we might think the coefficients are known
  168238. * more accurately than they really are.
  168239. */
  168240. LOCAL(boolean)
  168241. smoothing_ok (j_decompress_ptr cinfo)
  168242. {
  168243. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168244. boolean smoothing_useful = FALSE;
  168245. int ci, coefi;
  168246. jpeg_component_info *compptr;
  168247. JQUANT_TBL * qtable;
  168248. int * coef_bits;
  168249. int * coef_bits_latch;
  168250. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168251. return FALSE;
  168252. /* Allocate latch area if not already done */
  168253. if (coef->coef_bits_latch == NULL)
  168254. coef->coef_bits_latch = (int *)
  168255. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168256. cinfo->num_components *
  168257. (SAVED_COEFS * SIZEOF(int)));
  168258. coef_bits_latch = coef->coef_bits_latch;
  168259. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168260. ci++, compptr++) {
  168261. /* All components' quantization values must already be latched. */
  168262. if ((qtable = compptr->quant_table) == NULL)
  168263. return FALSE;
  168264. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168265. if (qtable->quantval[0] == 0 ||
  168266. qtable->quantval[Q01_POS] == 0 ||
  168267. qtable->quantval[Q10_POS] == 0 ||
  168268. qtable->quantval[Q20_POS] == 0 ||
  168269. qtable->quantval[Q11_POS] == 0 ||
  168270. qtable->quantval[Q02_POS] == 0)
  168271. return FALSE;
  168272. /* DC values must be at least partly known for all components. */
  168273. coef_bits = cinfo->coef_bits[ci];
  168274. if (coef_bits[0] < 0)
  168275. return FALSE;
  168276. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  168277. for (coefi = 1; coefi <= 5; coefi++) {
  168278. coef_bits_latch[coefi] = coef_bits[coefi];
  168279. if (coef_bits[coefi] != 0)
  168280. smoothing_useful = TRUE;
  168281. }
  168282. coef_bits_latch += SAVED_COEFS;
  168283. }
  168284. return smoothing_useful;
  168285. }
  168286. /*
  168287. * Variant of decompress_data for use when doing block smoothing.
  168288. */
  168289. METHODDEF(int)
  168290. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168291. {
  168292. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168293. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168294. JDIMENSION block_num, last_block_column;
  168295. int ci, block_row, block_rows, access_rows;
  168296. JBLOCKARRAY buffer;
  168297. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  168298. JSAMPARRAY output_ptr;
  168299. JDIMENSION output_col;
  168300. jpeg_component_info *compptr;
  168301. inverse_DCT_method_ptr inverse_DCT;
  168302. boolean first_row, last_row;
  168303. JBLOCK workspace;
  168304. int *coef_bits;
  168305. JQUANT_TBL *quanttbl;
  168306. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168307. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168308. int Al, pred;
  168309. /* Force some input to be done if we are getting ahead of the input. */
  168310. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168311. ! cinfo->inputctl->eoi_reached) {
  168312. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168313. /* If input is working on current scan, we ordinarily want it to
  168314. * have completed the current row. But if input scan is DC,
  168315. * we want it to keep one row ahead so that next block row's DC
  168316. * values are up to date.
  168317. */
  168318. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168319. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168320. break;
  168321. }
  168322. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168323. return JPEG_SUSPENDED;
  168324. }
  168325. /* OK, output from the virtual arrays. */
  168326. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168327. ci++, compptr++) {
  168328. /* Don't bother to IDCT an uninteresting component. */
  168329. if (! compptr->component_needed)
  168330. continue;
  168331. /* Count non-dummy DCT block rows in this iMCU row. */
  168332. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168333. block_rows = compptr->v_samp_factor;
  168334. access_rows = block_rows * 2; /* this and next iMCU row */
  168335. last_row = FALSE;
  168336. } else {
  168337. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168338. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168339. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168340. access_rows = block_rows; /* this iMCU row only */
  168341. last_row = TRUE;
  168342. }
  168343. /* Align the virtual buffer for this component. */
  168344. if (cinfo->output_iMCU_row > 0) {
  168345. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168346. buffer = (*cinfo->mem->access_virt_barray)
  168347. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168348. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168349. (JDIMENSION) access_rows, FALSE);
  168350. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168351. first_row = FALSE;
  168352. } else {
  168353. buffer = (*cinfo->mem->access_virt_barray)
  168354. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168355. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168356. first_row = TRUE;
  168357. }
  168358. /* Fetch component-dependent info */
  168359. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168360. quanttbl = compptr->quant_table;
  168361. Q00 = quanttbl->quantval[0];
  168362. Q01 = quanttbl->quantval[Q01_POS];
  168363. Q10 = quanttbl->quantval[Q10_POS];
  168364. Q20 = quanttbl->quantval[Q20_POS];
  168365. Q11 = quanttbl->quantval[Q11_POS];
  168366. Q02 = quanttbl->quantval[Q02_POS];
  168367. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168368. output_ptr = output_buf[ci];
  168369. /* Loop over all DCT blocks to be processed. */
  168370. for (block_row = 0; block_row < block_rows; block_row++) {
  168371. buffer_ptr = buffer[block_row];
  168372. if (first_row && block_row == 0)
  168373. prev_block_row = buffer_ptr;
  168374. else
  168375. prev_block_row = buffer[block_row-1];
  168376. if (last_row && block_row == block_rows-1)
  168377. next_block_row = buffer_ptr;
  168378. else
  168379. next_block_row = buffer[block_row+1];
  168380. /* We fetch the surrounding DC values using a sliding-register approach.
  168381. * Initialize all nine here so as to do the right thing on narrow pics.
  168382. */
  168383. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  168384. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  168385. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  168386. output_col = 0;
  168387. last_block_column = compptr->width_in_blocks - 1;
  168388. for (block_num = 0; block_num <= last_block_column; block_num++) {
  168389. /* Fetch current DCT block into workspace so we can modify it. */
  168390. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  168391. /* Update DC values */
  168392. if (block_num < last_block_column) {
  168393. DC3 = (int) prev_block_row[1][0];
  168394. DC6 = (int) buffer_ptr[1][0];
  168395. DC9 = (int) next_block_row[1][0];
  168396. }
  168397. /* Compute coefficient estimates per K.8.
  168398. * An estimate is applied only if coefficient is still zero,
  168399. * and is not known to be fully accurate.
  168400. */
  168401. /* AC01 */
  168402. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  168403. num = 36 * Q00 * (DC4 - DC6);
  168404. if (num >= 0) {
  168405. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  168406. if (Al > 0 && pred >= (1<<Al))
  168407. pred = (1<<Al)-1;
  168408. } else {
  168409. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  168410. if (Al > 0 && pred >= (1<<Al))
  168411. pred = (1<<Al)-1;
  168412. pred = -pred;
  168413. }
  168414. workspace[1] = (JCOEF) pred;
  168415. }
  168416. /* AC10 */
  168417. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  168418. num = 36 * Q00 * (DC2 - DC8);
  168419. if (num >= 0) {
  168420. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  168421. if (Al > 0 && pred >= (1<<Al))
  168422. pred = (1<<Al)-1;
  168423. } else {
  168424. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  168425. if (Al > 0 && pred >= (1<<Al))
  168426. pred = (1<<Al)-1;
  168427. pred = -pred;
  168428. }
  168429. workspace[8] = (JCOEF) pred;
  168430. }
  168431. /* AC20 */
  168432. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  168433. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  168434. if (num >= 0) {
  168435. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  168436. if (Al > 0 && pred >= (1<<Al))
  168437. pred = (1<<Al)-1;
  168438. } else {
  168439. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  168440. if (Al > 0 && pred >= (1<<Al))
  168441. pred = (1<<Al)-1;
  168442. pred = -pred;
  168443. }
  168444. workspace[16] = (JCOEF) pred;
  168445. }
  168446. /* AC11 */
  168447. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  168448. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  168449. if (num >= 0) {
  168450. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  168451. if (Al > 0 && pred >= (1<<Al))
  168452. pred = (1<<Al)-1;
  168453. } else {
  168454. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  168455. if (Al > 0 && pred >= (1<<Al))
  168456. pred = (1<<Al)-1;
  168457. pred = -pred;
  168458. }
  168459. workspace[9] = (JCOEF) pred;
  168460. }
  168461. /* AC02 */
  168462. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  168463. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  168464. if (num >= 0) {
  168465. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  168466. if (Al > 0 && pred >= (1<<Al))
  168467. pred = (1<<Al)-1;
  168468. } else {
  168469. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  168470. if (Al > 0 && pred >= (1<<Al))
  168471. pred = (1<<Al)-1;
  168472. pred = -pred;
  168473. }
  168474. workspace[2] = (JCOEF) pred;
  168475. }
  168476. /* OK, do the IDCT */
  168477. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  168478. output_ptr, output_col);
  168479. /* Advance for next column */
  168480. DC1 = DC2; DC2 = DC3;
  168481. DC4 = DC5; DC5 = DC6;
  168482. DC7 = DC8; DC8 = DC9;
  168483. buffer_ptr++, prev_block_row++, next_block_row++;
  168484. output_col += compptr->DCT_scaled_size;
  168485. }
  168486. output_ptr += compptr->DCT_scaled_size;
  168487. }
  168488. }
  168489. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168490. return JPEG_ROW_COMPLETED;
  168491. return JPEG_SCAN_COMPLETED;
  168492. }
  168493. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  168494. /*
  168495. * Initialize coefficient buffer controller.
  168496. */
  168497. GLOBAL(void)
  168498. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  168499. {
  168500. my_coef_ptr3 coef;
  168501. coef = (my_coef_ptr3)
  168502. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168503. SIZEOF(my_coef_controller3));
  168504. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  168505. coef->pub.start_input_pass = start_input_pass;
  168506. coef->pub.start_output_pass = start_output_pass;
  168507. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168508. coef->coef_bits_latch = NULL;
  168509. #endif
  168510. /* Create the coefficient buffer. */
  168511. if (need_full_buffer) {
  168512. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168513. /* Allocate a full-image virtual array for each component, */
  168514. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  168515. /* Note we ask for a pre-zeroed array. */
  168516. int ci, access_rows;
  168517. jpeg_component_info *compptr;
  168518. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168519. ci++, compptr++) {
  168520. access_rows = compptr->v_samp_factor;
  168521. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168522. /* If block smoothing could be used, need a bigger window */
  168523. if (cinfo->progressive_mode)
  168524. access_rows *= 3;
  168525. #endif
  168526. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  168527. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  168528. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  168529. (long) compptr->h_samp_factor),
  168530. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  168531. (long) compptr->v_samp_factor),
  168532. (JDIMENSION) access_rows);
  168533. }
  168534. coef->pub.consume_data = consume_data;
  168535. coef->pub.decompress_data = decompress_data;
  168536. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  168537. #else
  168538. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168539. #endif
  168540. } else {
  168541. /* We only need a single-MCU buffer. */
  168542. JBLOCKROW buffer;
  168543. int i;
  168544. buffer = (JBLOCKROW)
  168545. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168546. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  168547. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  168548. coef->MCU_buffer[i] = buffer + i;
  168549. }
  168550. coef->pub.consume_data = dummy_consume_data;
  168551. coef->pub.decompress_data = decompress_onepass;
  168552. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  168553. }
  168554. }
  168555. /*** End of inlined file: jdcoefct.c ***/
  168556. #undef FIX
  168557. /*** Start of inlined file: jdcolor.c ***/
  168558. #define JPEG_INTERNALS
  168559. /* Private subobject */
  168560. typedef struct {
  168561. struct jpeg_color_deconverter pub; /* public fields */
  168562. /* Private state for YCC->RGB conversion */
  168563. int * Cr_r_tab; /* => table for Cr to R conversion */
  168564. int * Cb_b_tab; /* => table for Cb to B conversion */
  168565. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  168566. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  168567. } my_color_deconverter2;
  168568. typedef my_color_deconverter2 * my_cconvert_ptr2;
  168569. /**************** YCbCr -> RGB conversion: most common case **************/
  168570. /*
  168571. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  168572. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  168573. * The conversion equations to be implemented are therefore
  168574. * R = Y + 1.40200 * Cr
  168575. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  168576. * B = Y + 1.77200 * Cb
  168577. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  168578. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  168579. *
  168580. * To avoid floating-point arithmetic, we represent the fractional constants
  168581. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  168582. * the products by 2^16, with appropriate rounding, to get the correct answer.
  168583. * Notice that Y, being an integral input, does not contribute any fraction
  168584. * so it need not participate in the rounding.
  168585. *
  168586. * For even more speed, we avoid doing any multiplications in the inner loop
  168587. * by precalculating the constants times Cb and Cr for all possible values.
  168588. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  168589. * for 12-bit samples it is still acceptable. It's not very reasonable for
  168590. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  168591. * colorspace anyway.
  168592. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  168593. * values for the G calculation are left scaled up, since we must add them
  168594. * together before rounding.
  168595. */
  168596. #define SCALEBITS 16 /* speediest right-shift on some machines */
  168597. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  168598. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  168599. /*
  168600. * Initialize tables for YCC->RGB colorspace conversion.
  168601. */
  168602. LOCAL(void)
  168603. build_ycc_rgb_table (j_decompress_ptr cinfo)
  168604. {
  168605. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168606. int i;
  168607. INT32 x;
  168608. SHIFT_TEMPS
  168609. cconvert->Cr_r_tab = (int *)
  168610. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168611. (MAXJSAMPLE+1) * SIZEOF(int));
  168612. cconvert->Cb_b_tab = (int *)
  168613. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168614. (MAXJSAMPLE+1) * SIZEOF(int));
  168615. cconvert->Cr_g_tab = (INT32 *)
  168616. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168617. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168618. cconvert->Cb_g_tab = (INT32 *)
  168619. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168620. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168621. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  168622. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  168623. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  168624. /* Cr=>R value is nearest int to 1.40200 * x */
  168625. cconvert->Cr_r_tab[i] = (int)
  168626. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  168627. /* Cb=>B value is nearest int to 1.77200 * x */
  168628. cconvert->Cb_b_tab[i] = (int)
  168629. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  168630. /* Cr=>G value is scaled-up -0.71414 * x */
  168631. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  168632. /* Cb=>G value is scaled-up -0.34414 * x */
  168633. /* We also add in ONE_HALF so that need not do it in inner loop */
  168634. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  168635. }
  168636. }
  168637. /*
  168638. * Convert some rows of samples to the output colorspace.
  168639. *
  168640. * Note that we change from noninterleaved, one-plane-per-component format
  168641. * to interleaved-pixel format. The output buffer is therefore three times
  168642. * as wide as the input buffer.
  168643. * A starting row offset is provided only for the input buffer. The caller
  168644. * can easily adjust the passed output_buf value to accommodate any row
  168645. * offset required on that side.
  168646. */
  168647. METHODDEF(void)
  168648. ycc_rgb_convert (j_decompress_ptr cinfo,
  168649. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168650. JSAMPARRAY output_buf, int num_rows)
  168651. {
  168652. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168653. register int y, cb, cr;
  168654. register JSAMPROW outptr;
  168655. register JSAMPROW inptr0, inptr1, inptr2;
  168656. register JDIMENSION col;
  168657. JDIMENSION num_cols = cinfo->output_width;
  168658. /* copy these pointers into registers if possible */
  168659. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168660. register int * Crrtab = cconvert->Cr_r_tab;
  168661. register int * Cbbtab = cconvert->Cb_b_tab;
  168662. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168663. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168664. SHIFT_TEMPS
  168665. while (--num_rows >= 0) {
  168666. inptr0 = input_buf[0][input_row];
  168667. inptr1 = input_buf[1][input_row];
  168668. inptr2 = input_buf[2][input_row];
  168669. input_row++;
  168670. outptr = *output_buf++;
  168671. for (col = 0; col < num_cols; col++) {
  168672. y = GETJSAMPLE(inptr0[col]);
  168673. cb = GETJSAMPLE(inptr1[col]);
  168674. cr = GETJSAMPLE(inptr2[col]);
  168675. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168676. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  168677. outptr[RGB_GREEN] = range_limit[y +
  168678. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168679. SCALEBITS))];
  168680. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  168681. outptr += RGB_PIXELSIZE;
  168682. }
  168683. }
  168684. }
  168685. /**************** Cases other than YCbCr -> RGB **************/
  168686. /*
  168687. * Color conversion for no colorspace change: just copy the data,
  168688. * converting from separate-planes to interleaved representation.
  168689. */
  168690. METHODDEF(void)
  168691. null_convert2 (j_decompress_ptr cinfo,
  168692. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168693. JSAMPARRAY output_buf, int num_rows)
  168694. {
  168695. register JSAMPROW inptr, outptr;
  168696. register JDIMENSION count;
  168697. register int num_components = cinfo->num_components;
  168698. JDIMENSION num_cols = cinfo->output_width;
  168699. int ci;
  168700. while (--num_rows >= 0) {
  168701. for (ci = 0; ci < num_components; ci++) {
  168702. inptr = input_buf[ci][input_row];
  168703. outptr = output_buf[0] + ci;
  168704. for (count = num_cols; count > 0; count--) {
  168705. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  168706. outptr += num_components;
  168707. }
  168708. }
  168709. input_row++;
  168710. output_buf++;
  168711. }
  168712. }
  168713. /*
  168714. * Color conversion for grayscale: just copy the data.
  168715. * This also works for YCbCr -> grayscale conversion, in which
  168716. * we just copy the Y (luminance) component and ignore chrominance.
  168717. */
  168718. METHODDEF(void)
  168719. grayscale_convert2 (j_decompress_ptr cinfo,
  168720. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168721. JSAMPARRAY output_buf, int num_rows)
  168722. {
  168723. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  168724. num_rows, cinfo->output_width);
  168725. }
  168726. /*
  168727. * Convert grayscale to RGB: just duplicate the graylevel three times.
  168728. * This is provided to support applications that don't want to cope
  168729. * with grayscale as a separate case.
  168730. */
  168731. METHODDEF(void)
  168732. gray_rgb_convert (j_decompress_ptr cinfo,
  168733. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168734. JSAMPARRAY output_buf, int num_rows)
  168735. {
  168736. register JSAMPROW inptr, outptr;
  168737. register JDIMENSION col;
  168738. JDIMENSION num_cols = cinfo->output_width;
  168739. while (--num_rows >= 0) {
  168740. inptr = input_buf[0][input_row++];
  168741. outptr = *output_buf++;
  168742. for (col = 0; col < num_cols; col++) {
  168743. /* We can dispense with GETJSAMPLE() here */
  168744. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  168745. outptr += RGB_PIXELSIZE;
  168746. }
  168747. }
  168748. }
  168749. /*
  168750. * Adobe-style YCCK->CMYK conversion.
  168751. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  168752. * conversion as above, while passing K (black) unchanged.
  168753. * We assume build_ycc_rgb_table has been called.
  168754. */
  168755. METHODDEF(void)
  168756. ycck_cmyk_convert (j_decompress_ptr cinfo,
  168757. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168758. JSAMPARRAY output_buf, int num_rows)
  168759. {
  168760. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168761. register int y, cb, cr;
  168762. register JSAMPROW outptr;
  168763. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  168764. register JDIMENSION col;
  168765. JDIMENSION num_cols = cinfo->output_width;
  168766. /* copy these pointers into registers if possible */
  168767. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168768. register int * Crrtab = cconvert->Cr_r_tab;
  168769. register int * Cbbtab = cconvert->Cb_b_tab;
  168770. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168771. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168772. SHIFT_TEMPS
  168773. while (--num_rows >= 0) {
  168774. inptr0 = input_buf[0][input_row];
  168775. inptr1 = input_buf[1][input_row];
  168776. inptr2 = input_buf[2][input_row];
  168777. inptr3 = input_buf[3][input_row];
  168778. input_row++;
  168779. outptr = *output_buf++;
  168780. for (col = 0; col < num_cols; col++) {
  168781. y = GETJSAMPLE(inptr0[col]);
  168782. cb = GETJSAMPLE(inptr1[col]);
  168783. cr = GETJSAMPLE(inptr2[col]);
  168784. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168785. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  168786. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  168787. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168788. SCALEBITS)))];
  168789. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  168790. /* K passes through unchanged */
  168791. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  168792. outptr += 4;
  168793. }
  168794. }
  168795. }
  168796. /*
  168797. * Empty method for start_pass.
  168798. */
  168799. METHODDEF(void)
  168800. start_pass_dcolor (j_decompress_ptr)
  168801. {
  168802. /* no work needed */
  168803. }
  168804. /*
  168805. * Module initialization routine for output colorspace conversion.
  168806. */
  168807. GLOBAL(void)
  168808. jinit_color_deconverter (j_decompress_ptr cinfo)
  168809. {
  168810. my_cconvert_ptr2 cconvert;
  168811. int ci;
  168812. cconvert = (my_cconvert_ptr2)
  168813. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168814. SIZEOF(my_color_deconverter2));
  168815. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  168816. cconvert->pub.start_pass = start_pass_dcolor;
  168817. /* Make sure num_components agrees with jpeg_color_space */
  168818. switch (cinfo->jpeg_color_space) {
  168819. case JCS_GRAYSCALE:
  168820. if (cinfo->num_components != 1)
  168821. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168822. break;
  168823. case JCS_RGB:
  168824. case JCS_YCbCr:
  168825. if (cinfo->num_components != 3)
  168826. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168827. break;
  168828. case JCS_CMYK:
  168829. case JCS_YCCK:
  168830. if (cinfo->num_components != 4)
  168831. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168832. break;
  168833. default: /* JCS_UNKNOWN can be anything */
  168834. if (cinfo->num_components < 1)
  168835. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168836. break;
  168837. }
  168838. /* Set out_color_components and conversion method based on requested space.
  168839. * Also clear the component_needed flags for any unused components,
  168840. * so that earlier pipeline stages can avoid useless computation.
  168841. */
  168842. switch (cinfo->out_color_space) {
  168843. case JCS_GRAYSCALE:
  168844. cinfo->out_color_components = 1;
  168845. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  168846. cinfo->jpeg_color_space == JCS_YCbCr) {
  168847. cconvert->pub.color_convert = grayscale_convert2;
  168848. /* For color->grayscale conversion, only the Y (0) component is needed */
  168849. for (ci = 1; ci < cinfo->num_components; ci++)
  168850. cinfo->comp_info[ci].component_needed = FALSE;
  168851. } else
  168852. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168853. break;
  168854. case JCS_RGB:
  168855. cinfo->out_color_components = RGB_PIXELSIZE;
  168856. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  168857. cconvert->pub.color_convert = ycc_rgb_convert;
  168858. build_ycc_rgb_table(cinfo);
  168859. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  168860. cconvert->pub.color_convert = gray_rgb_convert;
  168861. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  168862. cconvert->pub.color_convert = null_convert2;
  168863. } else
  168864. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168865. break;
  168866. case JCS_CMYK:
  168867. cinfo->out_color_components = 4;
  168868. if (cinfo->jpeg_color_space == JCS_YCCK) {
  168869. cconvert->pub.color_convert = ycck_cmyk_convert;
  168870. build_ycc_rgb_table(cinfo);
  168871. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  168872. cconvert->pub.color_convert = null_convert2;
  168873. } else
  168874. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168875. break;
  168876. default:
  168877. /* Permit null conversion to same output space */
  168878. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  168879. cinfo->out_color_components = cinfo->num_components;
  168880. cconvert->pub.color_convert = null_convert2;
  168881. } else /* unsupported non-null conversion */
  168882. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168883. break;
  168884. }
  168885. if (cinfo->quantize_colors)
  168886. cinfo->output_components = 1; /* single colormapped output component */
  168887. else
  168888. cinfo->output_components = cinfo->out_color_components;
  168889. }
  168890. /*** End of inlined file: jdcolor.c ***/
  168891. #undef FIX
  168892. /*** Start of inlined file: jddctmgr.c ***/
  168893. #define JPEG_INTERNALS
  168894. /*
  168895. * The decompressor input side (jdinput.c) saves away the appropriate
  168896. * quantization table for each component at the start of the first scan
  168897. * involving that component. (This is necessary in order to correctly
  168898. * decode files that reuse Q-table slots.)
  168899. * When we are ready to make an output pass, the saved Q-table is converted
  168900. * to a multiplier table that will actually be used by the IDCT routine.
  168901. * The multiplier table contents are IDCT-method-dependent. To support
  168902. * application changes in IDCT method between scans, we can remake the
  168903. * multiplier tables if necessary.
  168904. * In buffered-image mode, the first output pass may occur before any data
  168905. * has been seen for some components, and thus before their Q-tables have
  168906. * been saved away. To handle this case, multiplier tables are preset
  168907. * to zeroes; the result of the IDCT will be a neutral gray level.
  168908. */
  168909. /* Private subobject for this module */
  168910. typedef struct {
  168911. struct jpeg_inverse_dct pub; /* public fields */
  168912. /* This array contains the IDCT method code that each multiplier table
  168913. * is currently set up for, or -1 if it's not yet set up.
  168914. * The actual multiplier tables are pointed to by dct_table in the
  168915. * per-component comp_info structures.
  168916. */
  168917. int cur_method[MAX_COMPONENTS];
  168918. } my_idct_controller;
  168919. typedef my_idct_controller * my_idct_ptr;
  168920. /* Allocated multiplier tables: big enough for any supported variant */
  168921. typedef union {
  168922. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  168923. #ifdef DCT_IFAST_SUPPORTED
  168924. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  168925. #endif
  168926. #ifdef DCT_FLOAT_SUPPORTED
  168927. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  168928. #endif
  168929. } multiplier_table;
  168930. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  168931. * so be sure to compile that code if either ISLOW or SCALING is requested.
  168932. */
  168933. #ifdef DCT_ISLOW_SUPPORTED
  168934. #define PROVIDE_ISLOW_TABLES
  168935. #else
  168936. #ifdef IDCT_SCALING_SUPPORTED
  168937. #define PROVIDE_ISLOW_TABLES
  168938. #endif
  168939. #endif
  168940. /*
  168941. * Prepare for an output pass.
  168942. * Here we select the proper IDCT routine for each component and build
  168943. * a matching multiplier table.
  168944. */
  168945. METHODDEF(void)
  168946. start_pass (j_decompress_ptr cinfo)
  168947. {
  168948. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  168949. int ci, i;
  168950. jpeg_component_info *compptr;
  168951. int method = 0;
  168952. inverse_DCT_method_ptr method_ptr = NULL;
  168953. JQUANT_TBL * qtbl;
  168954. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168955. ci++, compptr++) {
  168956. /* Select the proper IDCT routine for this component's scaling */
  168957. switch (compptr->DCT_scaled_size) {
  168958. #ifdef IDCT_SCALING_SUPPORTED
  168959. case 1:
  168960. method_ptr = jpeg_idct_1x1;
  168961. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168962. break;
  168963. case 2:
  168964. method_ptr = jpeg_idct_2x2;
  168965. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168966. break;
  168967. case 4:
  168968. method_ptr = jpeg_idct_4x4;
  168969. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168970. break;
  168971. #endif
  168972. case DCTSIZE:
  168973. switch (cinfo->dct_method) {
  168974. #ifdef DCT_ISLOW_SUPPORTED
  168975. case JDCT_ISLOW:
  168976. method_ptr = jpeg_idct_islow;
  168977. method = JDCT_ISLOW;
  168978. break;
  168979. #endif
  168980. #ifdef DCT_IFAST_SUPPORTED
  168981. case JDCT_IFAST:
  168982. method_ptr = jpeg_idct_ifast;
  168983. method = JDCT_IFAST;
  168984. break;
  168985. #endif
  168986. #ifdef DCT_FLOAT_SUPPORTED
  168987. case JDCT_FLOAT:
  168988. method_ptr = jpeg_idct_float;
  168989. method = JDCT_FLOAT;
  168990. break;
  168991. #endif
  168992. default:
  168993. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168994. break;
  168995. }
  168996. break;
  168997. default:
  168998. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  168999. break;
  169000. }
  169001. idct->pub.inverse_DCT[ci] = method_ptr;
  169002. /* Create multiplier table from quant table.
  169003. * However, we can skip this if the component is uninteresting
  169004. * or if we already built the table. Also, if no quant table
  169005. * has yet been saved for the component, we leave the
  169006. * multiplier table all-zero; we'll be reading zeroes from the
  169007. * coefficient controller's buffer anyway.
  169008. */
  169009. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169010. continue;
  169011. qtbl = compptr->quant_table;
  169012. if (qtbl == NULL) /* happens if no data yet for component */
  169013. continue;
  169014. idct->cur_method[ci] = method;
  169015. switch (method) {
  169016. #ifdef PROVIDE_ISLOW_TABLES
  169017. case JDCT_ISLOW:
  169018. {
  169019. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169020. * coefficients, but are stored as ints to ensure access efficiency.
  169021. */
  169022. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169023. for (i = 0; i < DCTSIZE2; i++) {
  169024. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169025. }
  169026. }
  169027. break;
  169028. #endif
  169029. #ifdef DCT_IFAST_SUPPORTED
  169030. case JDCT_IFAST:
  169031. {
  169032. /* For AA&N IDCT method, multipliers are equal to quantization
  169033. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169034. * scalefactor[0] = 1
  169035. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169036. * For integer operation, the multiplier table is to be scaled by
  169037. * IFAST_SCALE_BITS.
  169038. */
  169039. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169040. #define CONST_BITS 14
  169041. static const INT16 aanscales[DCTSIZE2] = {
  169042. /* precomputed values scaled up by 14 bits */
  169043. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169044. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169045. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169046. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169047. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169048. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169049. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169050. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169051. };
  169052. SHIFT_TEMPS
  169053. for (i = 0; i < DCTSIZE2; i++) {
  169054. ifmtbl[i] = (IFAST_MULT_TYPE)
  169055. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169056. (INT32) aanscales[i]),
  169057. CONST_BITS-IFAST_SCALE_BITS);
  169058. }
  169059. }
  169060. break;
  169061. #endif
  169062. #ifdef DCT_FLOAT_SUPPORTED
  169063. case JDCT_FLOAT:
  169064. {
  169065. /* For float AA&N IDCT method, multipliers are equal to quantization
  169066. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169067. * scalefactor[0] = 1
  169068. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169069. */
  169070. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169071. int row, col;
  169072. static const double aanscalefactor[DCTSIZE] = {
  169073. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169074. 1.0, 0.785694958, 0.541196100, 0.275899379
  169075. };
  169076. i = 0;
  169077. for (row = 0; row < DCTSIZE; row++) {
  169078. for (col = 0; col < DCTSIZE; col++) {
  169079. fmtbl[i] = (FLOAT_MULT_TYPE)
  169080. ((double) qtbl->quantval[i] *
  169081. aanscalefactor[row] * aanscalefactor[col]);
  169082. i++;
  169083. }
  169084. }
  169085. }
  169086. break;
  169087. #endif
  169088. default:
  169089. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169090. break;
  169091. }
  169092. }
  169093. }
  169094. /*
  169095. * Initialize IDCT manager.
  169096. */
  169097. GLOBAL(void)
  169098. jinit_inverse_dct (j_decompress_ptr cinfo)
  169099. {
  169100. my_idct_ptr idct;
  169101. int ci;
  169102. jpeg_component_info *compptr;
  169103. idct = (my_idct_ptr)
  169104. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169105. SIZEOF(my_idct_controller));
  169106. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169107. idct->pub.start_pass = start_pass;
  169108. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169109. ci++, compptr++) {
  169110. /* Allocate and pre-zero a multiplier table for each component */
  169111. compptr->dct_table =
  169112. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169113. SIZEOF(multiplier_table));
  169114. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169115. /* Mark multiplier table not yet set up for any method */
  169116. idct->cur_method[ci] = -1;
  169117. }
  169118. }
  169119. /*** End of inlined file: jddctmgr.c ***/
  169120. #undef CONST_BITS
  169121. #undef ASSIGN_STATE
  169122. /*** Start of inlined file: jdhuff.c ***/
  169123. #define JPEG_INTERNALS
  169124. /*** Start of inlined file: jdhuff.h ***/
  169125. /* Short forms of external names for systems with brain-damaged linkers. */
  169126. #ifndef __jdhuff_h__
  169127. #define __jdhuff_h__
  169128. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169129. #define jpeg_make_d_derived_tbl jMkDDerived
  169130. #define jpeg_fill_bit_buffer jFilBitBuf
  169131. #define jpeg_huff_decode jHufDecode
  169132. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169133. /* Derived data constructed for each Huffman table */
  169134. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169135. typedef struct {
  169136. /* Basic tables: (element [0] of each array is unused) */
  169137. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169138. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169139. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169140. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169141. * the smallest code of length k; so given a code of length k, the
  169142. * corresponding symbol is huffval[code + valoffset[k]]
  169143. */
  169144. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169145. JHUFF_TBL *pub;
  169146. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169147. * the input data stream. If the next Huffman code is no more
  169148. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169149. * the corresponding symbol directly from these tables.
  169150. */
  169151. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169152. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169153. } d_derived_tbl;
  169154. /* Expand a Huffman table definition into the derived format */
  169155. EXTERN(void) jpeg_make_d_derived_tbl
  169156. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169157. d_derived_tbl ** pdtbl));
  169158. /*
  169159. * Fetching the next N bits from the input stream is a time-critical operation
  169160. * for the Huffman decoders. We implement it with a combination of inline
  169161. * macros and out-of-line subroutines. Note that N (the number of bits
  169162. * demanded at one time) never exceeds 15 for JPEG use.
  169163. *
  169164. * We read source bytes into get_buffer and dole out bits as needed.
  169165. * If get_buffer already contains enough bits, they are fetched in-line
  169166. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169167. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169168. * as full as possible (not just to the number of bits needed; this
  169169. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169170. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169171. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169172. * at least the requested number of bits --- dummy zeroes are inserted if
  169173. * necessary.
  169174. */
  169175. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169176. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169177. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169178. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169179. * appropriately should be a win. Unfortunately we can't define the size
  169180. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169181. * because not all machines measure sizeof in 8-bit bytes.
  169182. */
  169183. typedef struct { /* Bitreading state saved across MCUs */
  169184. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169185. int bits_left; /* # of unused bits in it */
  169186. } bitread_perm_state;
  169187. typedef struct { /* Bitreading working state within an MCU */
  169188. /* Current data source location */
  169189. /* We need a copy, rather than munging the original, in case of suspension */
  169190. const JOCTET * next_input_byte; /* => next byte to read from source */
  169191. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169192. /* Bit input buffer --- note these values are kept in register variables,
  169193. * not in this struct, inside the inner loops.
  169194. */
  169195. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169196. int bits_left; /* # of unused bits in it */
  169197. /* Pointer needed by jpeg_fill_bit_buffer. */
  169198. j_decompress_ptr cinfo; /* back link to decompress master record */
  169199. } bitread_working_state;
  169200. /* Macros to declare and load/save bitread local variables. */
  169201. #define BITREAD_STATE_VARS \
  169202. register bit_buf_type get_buffer; \
  169203. register int bits_left; \
  169204. bitread_working_state br_state
  169205. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169206. br_state.cinfo = cinfop; \
  169207. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169208. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169209. get_buffer = permstate.get_buffer; \
  169210. bits_left = permstate.bits_left;
  169211. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169212. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169213. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169214. permstate.get_buffer = get_buffer; \
  169215. permstate.bits_left = bits_left
  169216. /*
  169217. * These macros provide the in-line portion of bit fetching.
  169218. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169219. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169220. * The variables get_buffer and bits_left are assumed to be locals,
  169221. * but the state struct might not be (jpeg_huff_decode needs this).
  169222. * CHECK_BIT_BUFFER(state,n,action);
  169223. * Ensure there are N bits in get_buffer; if suspend, take action.
  169224. * val = GET_BITS(n);
  169225. * Fetch next N bits.
  169226. * val = PEEK_BITS(n);
  169227. * Fetch next N bits without removing them from the buffer.
  169228. * DROP_BITS(n);
  169229. * Discard next N bits.
  169230. * The value N should be a simple variable, not an expression, because it
  169231. * is evaluated multiple times.
  169232. */
  169233. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169234. { if (bits_left < (nbits)) { \
  169235. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169236. { action; } \
  169237. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169238. #define GET_BITS(nbits) \
  169239. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169240. #define PEEK_BITS(nbits) \
  169241. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169242. #define DROP_BITS(nbits) \
  169243. (bits_left -= (nbits))
  169244. /* Load up the bit buffer to a depth of at least nbits */
  169245. EXTERN(boolean) jpeg_fill_bit_buffer
  169246. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169247. register int bits_left, int nbits));
  169248. /*
  169249. * Code for extracting next Huffman-coded symbol from input bit stream.
  169250. * Again, this is time-critical and we make the main paths be macros.
  169251. *
  169252. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169253. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169254. * or fewer bits long. The few overlength codes are handled with a loop,
  169255. * which need not be inline code.
  169256. *
  169257. * Notes about the HUFF_DECODE macro:
  169258. * 1. Near the end of the data segment, we may fail to get enough bits
  169259. * for a lookahead. In that case, we do it the hard way.
  169260. * 2. If the lookahead table contains no entry, the next code must be
  169261. * more than HUFF_LOOKAHEAD bits long.
  169262. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169263. */
  169264. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169265. { register int nb, look; \
  169266. if (bits_left < HUFF_LOOKAHEAD) { \
  169267. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169268. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169269. if (bits_left < HUFF_LOOKAHEAD) { \
  169270. nb = 1; goto slowlabel; \
  169271. } \
  169272. } \
  169273. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  169274. if ((nb = htbl->look_nbits[look]) != 0) { \
  169275. DROP_BITS(nb); \
  169276. result = htbl->look_sym[look]; \
  169277. } else { \
  169278. nb = HUFF_LOOKAHEAD+1; \
  169279. slowlabel: \
  169280. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  169281. { failaction; } \
  169282. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169283. } \
  169284. }
  169285. /* Out-of-line case for Huffman code fetching */
  169286. EXTERN(int) jpeg_huff_decode
  169287. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169288. register int bits_left, d_derived_tbl * htbl, int min_bits));
  169289. #endif
  169290. /*** End of inlined file: jdhuff.h ***/
  169291. /* Declarations shared with jdphuff.c */
  169292. /*
  169293. * Expanded entropy decoder object for Huffman decoding.
  169294. *
  169295. * The savable_state subrecord contains fields that change within an MCU,
  169296. * but must not be updated permanently until we complete the MCU.
  169297. */
  169298. typedef struct {
  169299. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169300. } savable_state2;
  169301. /* This macro is to work around compilers with missing or broken
  169302. * structure assignment. You'll need to fix this code if you have
  169303. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169304. */
  169305. #ifndef NO_STRUCT_ASSIGN
  169306. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169307. #else
  169308. #if MAX_COMPS_IN_SCAN == 4
  169309. #define ASSIGN_STATE(dest,src) \
  169310. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169311. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169312. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169313. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169314. #endif
  169315. #endif
  169316. typedef struct {
  169317. struct jpeg_entropy_decoder pub; /* public fields */
  169318. /* These fields are loaded into local variables at start of each MCU.
  169319. * In case of suspension, we exit WITHOUT updating them.
  169320. */
  169321. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169322. savable_state2 saved; /* Other state at start of MCU */
  169323. /* These fields are NOT loaded into local working state. */
  169324. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169325. /* Pointers to derived tables (these workspaces have image lifespan) */
  169326. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169327. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169328. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169329. /* Pointers to derived tables to be used for each block within an MCU */
  169330. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169331. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169332. /* Whether we care about the DC and AC coefficient values for each block */
  169333. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169334. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169335. } huff_entropy_decoder2;
  169336. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169337. /*
  169338. * Initialize for a Huffman-compressed scan.
  169339. */
  169340. METHODDEF(void)
  169341. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169342. {
  169343. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169344. int ci, blkn, dctbl, actbl;
  169345. jpeg_component_info * compptr;
  169346. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169347. * This ought to be an error condition, but we make it a warning because
  169348. * there are some baseline files out there with all zeroes in these bytes.
  169349. */
  169350. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169351. cinfo->Ah != 0 || cinfo->Al != 0)
  169352. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169353. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169354. compptr = cinfo->cur_comp_info[ci];
  169355. dctbl = compptr->dc_tbl_no;
  169356. actbl = compptr->ac_tbl_no;
  169357. /* Compute derived values for Huffman tables */
  169358. /* We may do this more than once for a table, but it's not expensive */
  169359. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169360. & entropy->dc_derived_tbls[dctbl]);
  169361. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169362. & entropy->ac_derived_tbls[actbl]);
  169363. /* Initialize DC predictions to 0 */
  169364. entropy->saved.last_dc_val[ci] = 0;
  169365. }
  169366. /* Precalculate decoding info for each block in an MCU of this scan */
  169367. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169368. ci = cinfo->MCU_membership[blkn];
  169369. compptr = cinfo->cur_comp_info[ci];
  169370. /* Precalculate which table to use for each block */
  169371. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169372. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169373. /* Decide whether we really care about the coefficient values */
  169374. if (compptr->component_needed) {
  169375. entropy->dc_needed[blkn] = TRUE;
  169376. /* we don't need the ACs if producing a 1/8th-size image */
  169377. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169378. } else {
  169379. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169380. }
  169381. }
  169382. /* Initialize bitread state variables */
  169383. entropy->bitstate.bits_left = 0;
  169384. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169385. entropy->pub.insufficient_data = FALSE;
  169386. /* Initialize restart counter */
  169387. entropy->restarts_to_go = cinfo->restart_interval;
  169388. }
  169389. /*
  169390. * Compute the derived values for a Huffman table.
  169391. * This routine also performs some validation checks on the table.
  169392. *
  169393. * Note this is also used by jdphuff.c.
  169394. */
  169395. GLOBAL(void)
  169396. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  169397. d_derived_tbl ** pdtbl)
  169398. {
  169399. JHUFF_TBL *htbl;
  169400. d_derived_tbl *dtbl;
  169401. int p, i, l, si, numsymbols;
  169402. int lookbits, ctr;
  169403. char huffsize[257];
  169404. unsigned int huffcode[257];
  169405. unsigned int code;
  169406. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  169407. * paralleling the order of the symbols themselves in htbl->huffval[].
  169408. */
  169409. /* Find the input Huffman table */
  169410. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  169411. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169412. htbl =
  169413. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  169414. if (htbl == NULL)
  169415. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169416. /* Allocate a workspace if we haven't already done so. */
  169417. if (*pdtbl == NULL)
  169418. *pdtbl = (d_derived_tbl *)
  169419. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169420. SIZEOF(d_derived_tbl));
  169421. dtbl = *pdtbl;
  169422. dtbl->pub = htbl; /* fill in back link */
  169423. /* Figure C.1: make table of Huffman code length for each symbol */
  169424. p = 0;
  169425. for (l = 1; l <= 16; l++) {
  169426. i = (int) htbl->bits[l];
  169427. if (i < 0 || p + i > 256) /* protect against table overrun */
  169428. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169429. while (i--)
  169430. huffsize[p++] = (char) l;
  169431. }
  169432. huffsize[p] = 0;
  169433. numsymbols = p;
  169434. /* Figure C.2: generate the codes themselves */
  169435. /* We also validate that the counts represent a legal Huffman code tree. */
  169436. code = 0;
  169437. si = huffsize[0];
  169438. p = 0;
  169439. while (huffsize[p]) {
  169440. while (((int) huffsize[p]) == si) {
  169441. huffcode[p++] = code;
  169442. code++;
  169443. }
  169444. /* code is now 1 more than the last code used for codelength si; but
  169445. * it must still fit in si bits, since no code is allowed to be all ones.
  169446. */
  169447. if (((INT32) code) >= (((INT32) 1) << si))
  169448. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169449. code <<= 1;
  169450. si++;
  169451. }
  169452. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  169453. p = 0;
  169454. for (l = 1; l <= 16; l++) {
  169455. if (htbl->bits[l]) {
  169456. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  169457. * minus the minimum code of length l
  169458. */
  169459. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  169460. p += htbl->bits[l];
  169461. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  169462. } else {
  169463. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  169464. }
  169465. }
  169466. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  169467. /* Compute lookahead tables to speed up decoding.
  169468. * First we set all the table entries to 0, indicating "too long";
  169469. * then we iterate through the Huffman codes that are short enough and
  169470. * fill in all the entries that correspond to bit sequences starting
  169471. * with that code.
  169472. */
  169473. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  169474. p = 0;
  169475. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  169476. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  169477. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  169478. /* Generate left-justified code followed by all possible bit sequences */
  169479. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  169480. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  169481. dtbl->look_nbits[lookbits] = l;
  169482. dtbl->look_sym[lookbits] = htbl->huffval[p];
  169483. lookbits++;
  169484. }
  169485. }
  169486. }
  169487. /* Validate symbols as being reasonable.
  169488. * For AC tables, we make no check, but accept all byte values 0..255.
  169489. * For DC tables, we require the symbols to be in range 0..15.
  169490. * (Tighter bounds could be applied depending on the data depth and mode,
  169491. * but this is sufficient to ensure safe decoding.)
  169492. */
  169493. if (isDC) {
  169494. for (i = 0; i < numsymbols; i++) {
  169495. int sym = htbl->huffval[i];
  169496. if (sym < 0 || sym > 15)
  169497. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169498. }
  169499. }
  169500. }
  169501. /*
  169502. * Out-of-line code for bit fetching (shared with jdphuff.c).
  169503. * See jdhuff.h for info about usage.
  169504. * Note: current values of get_buffer and bits_left are passed as parameters,
  169505. * but are returned in the corresponding fields of the state struct.
  169506. *
  169507. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  169508. * of get_buffer to be used. (On machines with wider words, an even larger
  169509. * buffer could be used.) However, on some machines 32-bit shifts are
  169510. * quite slow and take time proportional to the number of places shifted.
  169511. * (This is true with most PC compilers, for instance.) In this case it may
  169512. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  169513. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  169514. */
  169515. #ifdef SLOW_SHIFT_32
  169516. #define MIN_GET_BITS 15 /* minimum allowable value */
  169517. #else
  169518. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  169519. #endif
  169520. GLOBAL(boolean)
  169521. jpeg_fill_bit_buffer (bitread_working_state * state,
  169522. register bit_buf_type get_buffer, register int bits_left,
  169523. int nbits)
  169524. /* Load up the bit buffer to a depth of at least nbits */
  169525. {
  169526. /* Copy heavily used state fields into locals (hopefully registers) */
  169527. register const JOCTET * next_input_byte = state->next_input_byte;
  169528. register size_t bytes_in_buffer = state->bytes_in_buffer;
  169529. j_decompress_ptr cinfo = state->cinfo;
  169530. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  169531. /* (It is assumed that no request will be for more than that many bits.) */
  169532. /* We fail to do so only if we hit a marker or are forced to suspend. */
  169533. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  169534. while (bits_left < MIN_GET_BITS) {
  169535. register int c;
  169536. /* Attempt to read a byte */
  169537. if (bytes_in_buffer == 0) {
  169538. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169539. return FALSE;
  169540. next_input_byte = cinfo->src->next_input_byte;
  169541. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169542. }
  169543. bytes_in_buffer--;
  169544. c = GETJOCTET(*next_input_byte++);
  169545. /* If it's 0xFF, check and discard stuffed zero byte */
  169546. if (c == 0xFF) {
  169547. /* Loop here to discard any padding FF's on terminating marker,
  169548. * so that we can save a valid unread_marker value. NOTE: we will
  169549. * accept multiple FF's followed by a 0 as meaning a single FF data
  169550. * byte. This data pattern is not valid according to the standard.
  169551. */
  169552. do {
  169553. if (bytes_in_buffer == 0) {
  169554. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169555. return FALSE;
  169556. next_input_byte = cinfo->src->next_input_byte;
  169557. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169558. }
  169559. bytes_in_buffer--;
  169560. c = GETJOCTET(*next_input_byte++);
  169561. } while (c == 0xFF);
  169562. if (c == 0) {
  169563. /* Found FF/00, which represents an FF data byte */
  169564. c = 0xFF;
  169565. } else {
  169566. /* Oops, it's actually a marker indicating end of compressed data.
  169567. * Save the marker code for later use.
  169568. * Fine point: it might appear that we should save the marker into
  169569. * bitread working state, not straight into permanent state. But
  169570. * once we have hit a marker, we cannot need to suspend within the
  169571. * current MCU, because we will read no more bytes from the data
  169572. * source. So it is OK to update permanent state right away.
  169573. */
  169574. cinfo->unread_marker = c;
  169575. /* See if we need to insert some fake zero bits. */
  169576. goto no_more_bytes;
  169577. }
  169578. }
  169579. /* OK, load c into get_buffer */
  169580. get_buffer = (get_buffer << 8) | c;
  169581. bits_left += 8;
  169582. } /* end while */
  169583. } else {
  169584. no_more_bytes:
  169585. /* We get here if we've read the marker that terminates the compressed
  169586. * data segment. There should be enough bits in the buffer register
  169587. * to satisfy the request; if so, no problem.
  169588. */
  169589. if (nbits > bits_left) {
  169590. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  169591. * the data stream, so that we can produce some kind of image.
  169592. * We use a nonvolatile flag to ensure that only one warning message
  169593. * appears per data segment.
  169594. */
  169595. if (! cinfo->entropy->insufficient_data) {
  169596. WARNMS(cinfo, JWRN_HIT_MARKER);
  169597. cinfo->entropy->insufficient_data = TRUE;
  169598. }
  169599. /* Fill the buffer with zero bits */
  169600. get_buffer <<= MIN_GET_BITS - bits_left;
  169601. bits_left = MIN_GET_BITS;
  169602. }
  169603. }
  169604. /* Unload the local registers */
  169605. state->next_input_byte = next_input_byte;
  169606. state->bytes_in_buffer = bytes_in_buffer;
  169607. state->get_buffer = get_buffer;
  169608. state->bits_left = bits_left;
  169609. return TRUE;
  169610. }
  169611. /*
  169612. * Out-of-line code for Huffman code decoding.
  169613. * See jdhuff.h for info about usage.
  169614. */
  169615. GLOBAL(int)
  169616. jpeg_huff_decode (bitread_working_state * state,
  169617. register bit_buf_type get_buffer, register int bits_left,
  169618. d_derived_tbl * htbl, int min_bits)
  169619. {
  169620. register int l = min_bits;
  169621. register INT32 code;
  169622. /* HUFF_DECODE has determined that the code is at least min_bits */
  169623. /* bits long, so fetch that many bits in one swoop. */
  169624. CHECK_BIT_BUFFER(*state, l, return -1);
  169625. code = GET_BITS(l);
  169626. /* Collect the rest of the Huffman code one bit at a time. */
  169627. /* This is per Figure F.16 in the JPEG spec. */
  169628. while (code > htbl->maxcode[l]) {
  169629. code <<= 1;
  169630. CHECK_BIT_BUFFER(*state, 1, return -1);
  169631. code |= GET_BITS(1);
  169632. l++;
  169633. }
  169634. /* Unload the local registers */
  169635. state->get_buffer = get_buffer;
  169636. state->bits_left = bits_left;
  169637. /* With garbage input we may reach the sentinel value l = 17. */
  169638. if (l > 16) {
  169639. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  169640. return 0; /* fake a zero as the safest result */
  169641. }
  169642. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  169643. }
  169644. /*
  169645. * Check for a restart marker & resynchronize decoder.
  169646. * Returns FALSE if must suspend.
  169647. */
  169648. LOCAL(boolean)
  169649. process_restart (j_decompress_ptr cinfo)
  169650. {
  169651. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169652. int ci;
  169653. /* Throw away any unused bits remaining in bit buffer; */
  169654. /* include any full bytes in next_marker's count of discarded bytes */
  169655. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  169656. entropy->bitstate.bits_left = 0;
  169657. /* Advance past the RSTn marker */
  169658. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  169659. return FALSE;
  169660. /* Re-initialize DC predictions to 0 */
  169661. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  169662. entropy->saved.last_dc_val[ci] = 0;
  169663. /* Reset restart counter */
  169664. entropy->restarts_to_go = cinfo->restart_interval;
  169665. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  169666. * against a marker. In that case we will end up treating the next data
  169667. * segment as empty, and we can avoid producing bogus output pixels by
  169668. * leaving the flag set.
  169669. */
  169670. if (cinfo->unread_marker == 0)
  169671. entropy->pub.insufficient_data = FALSE;
  169672. return TRUE;
  169673. }
  169674. /*
  169675. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  169676. * The coefficients are reordered from zigzag order into natural array order,
  169677. * but are not dequantized.
  169678. *
  169679. * The i'th block of the MCU is stored into the block pointed to by
  169680. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  169681. * (Wholesale zeroing is usually a little faster than retail...)
  169682. *
  169683. * Returns FALSE if data source requested suspension. In that case no
  169684. * changes have been made to permanent state. (Exception: some output
  169685. * coefficients may already have been assigned. This is harmless for
  169686. * this module, since we'll just re-assign them on the next call.)
  169687. */
  169688. METHODDEF(boolean)
  169689. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169690. {
  169691. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169692. int blkn;
  169693. BITREAD_STATE_VARS;
  169694. savable_state2 state;
  169695. /* Process restart marker if needed; may have to suspend */
  169696. if (cinfo->restart_interval) {
  169697. if (entropy->restarts_to_go == 0)
  169698. if (! process_restart(cinfo))
  169699. return FALSE;
  169700. }
  169701. /* If we've run out of data, just leave the MCU set to zeroes.
  169702. * This way, we return uniform gray for the remainder of the segment.
  169703. */
  169704. if (! entropy->pub.insufficient_data) {
  169705. /* Load up working state */
  169706. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169707. ASSIGN_STATE(state, entropy->saved);
  169708. /* Outer loop handles each block in the MCU */
  169709. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169710. JBLOCKROW block = MCU_data[blkn];
  169711. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  169712. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  169713. register int s, k, r;
  169714. /* Decode a single block's worth of coefficients */
  169715. /* Section F.2.2.1: decode the DC coefficient difference */
  169716. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  169717. if (s) {
  169718. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169719. r = GET_BITS(s);
  169720. s = HUFF_EXTEND(r, s);
  169721. }
  169722. if (entropy->dc_needed[blkn]) {
  169723. /* Convert DC difference to actual value, update last_dc_val */
  169724. int ci = cinfo->MCU_membership[blkn];
  169725. s += state.last_dc_val[ci];
  169726. state.last_dc_val[ci] = s;
  169727. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  169728. (*block)[0] = (JCOEF) s;
  169729. }
  169730. if (entropy->ac_needed[blkn]) {
  169731. /* Section F.2.2.2: decode the AC coefficients */
  169732. /* Since zeroes are skipped, output area must be cleared beforehand */
  169733. for (k = 1; k < DCTSIZE2; k++) {
  169734. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  169735. r = s >> 4;
  169736. s &= 15;
  169737. if (s) {
  169738. k += r;
  169739. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169740. r = GET_BITS(s);
  169741. s = HUFF_EXTEND(r, s);
  169742. /* Output coefficient in natural (dezigzagged) order.
  169743. * Note: the extra entries in jpeg_natural_order[] will save us
  169744. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  169745. */
  169746. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  169747. } else {
  169748. if (r != 15)
  169749. break;
  169750. k += 15;
  169751. }
  169752. }
  169753. } else {
  169754. /* Section F.2.2.2: decode the AC coefficients */
  169755. /* In this path we just discard the values */
  169756. for (k = 1; k < DCTSIZE2; k++) {
  169757. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  169758. r = s >> 4;
  169759. s &= 15;
  169760. if (s) {
  169761. k += r;
  169762. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169763. DROP_BITS(s);
  169764. } else {
  169765. if (r != 15)
  169766. break;
  169767. k += 15;
  169768. }
  169769. }
  169770. }
  169771. }
  169772. /* Completed MCU, so update state */
  169773. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169774. ASSIGN_STATE(entropy->saved, state);
  169775. }
  169776. /* Account for restart interval (no-op if not using restarts) */
  169777. entropy->restarts_to_go--;
  169778. return TRUE;
  169779. }
  169780. /*
  169781. * Module initialization routine for Huffman entropy decoding.
  169782. */
  169783. GLOBAL(void)
  169784. jinit_huff_decoder (j_decompress_ptr cinfo)
  169785. {
  169786. huff_entropy_ptr2 entropy;
  169787. int i;
  169788. entropy = (huff_entropy_ptr2)
  169789. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169790. SIZEOF(huff_entropy_decoder2));
  169791. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  169792. entropy->pub.start_pass = start_pass_huff_decoder;
  169793. entropy->pub.decode_mcu = decode_mcu;
  169794. /* Mark tables unallocated */
  169795. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  169796. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  169797. }
  169798. }
  169799. /*** End of inlined file: jdhuff.c ***/
  169800. /*** Start of inlined file: jdinput.c ***/
  169801. #define JPEG_INTERNALS
  169802. /* Private state */
  169803. typedef struct {
  169804. struct jpeg_input_controller pub; /* public fields */
  169805. boolean inheaders; /* TRUE until first SOS is reached */
  169806. } my_input_controller;
  169807. typedef my_input_controller * my_inputctl_ptr;
  169808. /* Forward declarations */
  169809. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  169810. /*
  169811. * Routines to calculate various quantities related to the size of the image.
  169812. */
  169813. LOCAL(void)
  169814. initial_setup2 (j_decompress_ptr cinfo)
  169815. /* Called once, when first SOS marker is reached */
  169816. {
  169817. int ci;
  169818. jpeg_component_info *compptr;
  169819. /* Make sure image isn't bigger than I can handle */
  169820. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  169821. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  169822. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  169823. /* For now, precision must match compiled-in value... */
  169824. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  169825. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  169826. /* Check that number of components won't exceed internal array sizes */
  169827. if (cinfo->num_components > MAX_COMPONENTS)
  169828. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  169829. MAX_COMPONENTS);
  169830. /* Compute maximum sampling factors; check factor validity */
  169831. cinfo->max_h_samp_factor = 1;
  169832. cinfo->max_v_samp_factor = 1;
  169833. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169834. ci++, compptr++) {
  169835. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  169836. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  169837. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  169838. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  169839. compptr->h_samp_factor);
  169840. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  169841. compptr->v_samp_factor);
  169842. }
  169843. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  169844. * In the full decompressor, this will be overridden by jdmaster.c;
  169845. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  169846. */
  169847. cinfo->min_DCT_scaled_size = DCTSIZE;
  169848. /* Compute dimensions of components */
  169849. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169850. ci++, compptr++) {
  169851. compptr->DCT_scaled_size = DCTSIZE;
  169852. /* Size in DCT blocks */
  169853. compptr->width_in_blocks = (JDIMENSION)
  169854. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  169855. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  169856. compptr->height_in_blocks = (JDIMENSION)
  169857. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  169858. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  169859. /* downsampled_width and downsampled_height will also be overridden by
  169860. * jdmaster.c if we are doing full decompression. The transcoder library
  169861. * doesn't use these values, but the calling application might.
  169862. */
  169863. /* Size in samples */
  169864. compptr->downsampled_width = (JDIMENSION)
  169865. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  169866. (long) cinfo->max_h_samp_factor);
  169867. compptr->downsampled_height = (JDIMENSION)
  169868. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  169869. (long) cinfo->max_v_samp_factor);
  169870. /* Mark component needed, until color conversion says otherwise */
  169871. compptr->component_needed = TRUE;
  169872. /* Mark no quantization table yet saved for component */
  169873. compptr->quant_table = NULL;
  169874. }
  169875. /* Compute number of fully interleaved MCU rows. */
  169876. cinfo->total_iMCU_rows = (JDIMENSION)
  169877. jdiv_round_up((long) cinfo->image_height,
  169878. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  169879. /* Decide whether file contains multiple scans */
  169880. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  169881. cinfo->inputctl->has_multiple_scans = TRUE;
  169882. else
  169883. cinfo->inputctl->has_multiple_scans = FALSE;
  169884. }
  169885. LOCAL(void)
  169886. per_scan_setup2 (j_decompress_ptr cinfo)
  169887. /* Do computations that are needed before processing a JPEG scan */
  169888. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  169889. {
  169890. int ci, mcublks, tmp;
  169891. jpeg_component_info *compptr;
  169892. if (cinfo->comps_in_scan == 1) {
  169893. /* Noninterleaved (single-component) scan */
  169894. compptr = cinfo->cur_comp_info[0];
  169895. /* Overall image size in MCUs */
  169896. cinfo->MCUs_per_row = compptr->width_in_blocks;
  169897. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  169898. /* For noninterleaved scan, always one block per MCU */
  169899. compptr->MCU_width = 1;
  169900. compptr->MCU_height = 1;
  169901. compptr->MCU_blocks = 1;
  169902. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  169903. compptr->last_col_width = 1;
  169904. /* For noninterleaved scans, it is convenient to define last_row_height
  169905. * as the number of block rows present in the last iMCU row.
  169906. */
  169907. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  169908. if (tmp == 0) tmp = compptr->v_samp_factor;
  169909. compptr->last_row_height = tmp;
  169910. /* Prepare array describing MCU composition */
  169911. cinfo->blocks_in_MCU = 1;
  169912. cinfo->MCU_membership[0] = 0;
  169913. } else {
  169914. /* Interleaved (multi-component) scan */
  169915. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  169916. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  169917. MAX_COMPS_IN_SCAN);
  169918. /* Overall image size in MCUs */
  169919. cinfo->MCUs_per_row = (JDIMENSION)
  169920. jdiv_round_up((long) cinfo->image_width,
  169921. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  169922. cinfo->MCU_rows_in_scan = (JDIMENSION)
  169923. jdiv_round_up((long) cinfo->image_height,
  169924. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  169925. cinfo->blocks_in_MCU = 0;
  169926. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169927. compptr = cinfo->cur_comp_info[ci];
  169928. /* Sampling factors give # of blocks of component in each MCU */
  169929. compptr->MCU_width = compptr->h_samp_factor;
  169930. compptr->MCU_height = compptr->v_samp_factor;
  169931. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  169932. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  169933. /* Figure number of non-dummy blocks in last MCU column & row */
  169934. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  169935. if (tmp == 0) tmp = compptr->MCU_width;
  169936. compptr->last_col_width = tmp;
  169937. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  169938. if (tmp == 0) tmp = compptr->MCU_height;
  169939. compptr->last_row_height = tmp;
  169940. /* Prepare array describing MCU composition */
  169941. mcublks = compptr->MCU_blocks;
  169942. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  169943. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  169944. while (mcublks-- > 0) {
  169945. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  169946. }
  169947. }
  169948. }
  169949. }
  169950. /*
  169951. * Save away a copy of the Q-table referenced by each component present
  169952. * in the current scan, unless already saved during a prior scan.
  169953. *
  169954. * In a multiple-scan JPEG file, the encoder could assign different components
  169955. * the same Q-table slot number, but change table definitions between scans
  169956. * so that each component uses a different Q-table. (The IJG encoder is not
  169957. * currently capable of doing this, but other encoders might.) Since we want
  169958. * to be able to dequantize all the components at the end of the file, this
  169959. * means that we have to save away the table actually used for each component.
  169960. * We do this by copying the table at the start of the first scan containing
  169961. * the component.
  169962. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  169963. * slot between scans of a component using that slot. If the encoder does so
  169964. * anyway, this decoder will simply use the Q-table values that were current
  169965. * at the start of the first scan for the component.
  169966. *
  169967. * The decompressor output side looks only at the saved quant tables,
  169968. * not at the current Q-table slots.
  169969. */
  169970. LOCAL(void)
  169971. latch_quant_tables (j_decompress_ptr cinfo)
  169972. {
  169973. int ci, qtblno;
  169974. jpeg_component_info *compptr;
  169975. JQUANT_TBL * qtbl;
  169976. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169977. compptr = cinfo->cur_comp_info[ci];
  169978. /* No work if we already saved Q-table for this component */
  169979. if (compptr->quant_table != NULL)
  169980. continue;
  169981. /* Make sure specified quantization table is present */
  169982. qtblno = compptr->quant_tbl_no;
  169983. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  169984. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  169985. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  169986. /* OK, save away the quantization table */
  169987. qtbl = (JQUANT_TBL *)
  169988. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169989. SIZEOF(JQUANT_TBL));
  169990. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  169991. compptr->quant_table = qtbl;
  169992. }
  169993. }
  169994. /*
  169995. * Initialize the input modules to read a scan of compressed data.
  169996. * The first call to this is done by jdmaster.c after initializing
  169997. * the entire decompressor (during jpeg_start_decompress).
  169998. * Subsequent calls come from consume_markers, below.
  169999. */
  170000. METHODDEF(void)
  170001. start_input_pass2 (j_decompress_ptr cinfo)
  170002. {
  170003. per_scan_setup2(cinfo);
  170004. latch_quant_tables(cinfo);
  170005. (*cinfo->entropy->start_pass) (cinfo);
  170006. (*cinfo->coef->start_input_pass) (cinfo);
  170007. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170008. }
  170009. /*
  170010. * Finish up after inputting a compressed-data scan.
  170011. * This is called by the coefficient controller after it's read all
  170012. * the expected data of the scan.
  170013. */
  170014. METHODDEF(void)
  170015. finish_input_pass (j_decompress_ptr cinfo)
  170016. {
  170017. cinfo->inputctl->consume_input = consume_markers;
  170018. }
  170019. /*
  170020. * Read JPEG markers before, between, or after compressed-data scans.
  170021. * Change state as necessary when a new scan is reached.
  170022. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170023. *
  170024. * The consume_input method pointer points either here or to the
  170025. * coefficient controller's consume_data routine, depending on whether
  170026. * we are reading a compressed data segment or inter-segment markers.
  170027. */
  170028. METHODDEF(int)
  170029. consume_markers (j_decompress_ptr cinfo)
  170030. {
  170031. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170032. int val;
  170033. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170034. return JPEG_REACHED_EOI;
  170035. val = (*cinfo->marker->read_markers) (cinfo);
  170036. switch (val) {
  170037. case JPEG_REACHED_SOS: /* Found SOS */
  170038. if (inputctl->inheaders) { /* 1st SOS */
  170039. initial_setup2(cinfo);
  170040. inputctl->inheaders = FALSE;
  170041. /* Note: start_input_pass must be called by jdmaster.c
  170042. * before any more input can be consumed. jdapimin.c is
  170043. * responsible for enforcing this sequencing.
  170044. */
  170045. } else { /* 2nd or later SOS marker */
  170046. if (! inputctl->pub.has_multiple_scans)
  170047. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170048. start_input_pass2(cinfo);
  170049. }
  170050. break;
  170051. case JPEG_REACHED_EOI: /* Found EOI */
  170052. inputctl->pub.eoi_reached = TRUE;
  170053. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170054. if (cinfo->marker->saw_SOF)
  170055. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170056. } else {
  170057. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170058. * if user set output_scan_number larger than number of scans.
  170059. */
  170060. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170061. cinfo->output_scan_number = cinfo->input_scan_number;
  170062. }
  170063. break;
  170064. case JPEG_SUSPENDED:
  170065. break;
  170066. }
  170067. return val;
  170068. }
  170069. /*
  170070. * Reset state to begin a fresh datastream.
  170071. */
  170072. METHODDEF(void)
  170073. reset_input_controller (j_decompress_ptr cinfo)
  170074. {
  170075. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170076. inputctl->pub.consume_input = consume_markers;
  170077. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170078. inputctl->pub.eoi_reached = FALSE;
  170079. inputctl->inheaders = TRUE;
  170080. /* Reset other modules */
  170081. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170082. (*cinfo->marker->reset_marker_reader) (cinfo);
  170083. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170084. cinfo->coef_bits = NULL;
  170085. }
  170086. /*
  170087. * Initialize the input controller module.
  170088. * This is called only once, when the decompression object is created.
  170089. */
  170090. GLOBAL(void)
  170091. jinit_input_controller (j_decompress_ptr cinfo)
  170092. {
  170093. my_inputctl_ptr inputctl;
  170094. /* Create subobject in permanent pool */
  170095. inputctl = (my_inputctl_ptr)
  170096. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170097. SIZEOF(my_input_controller));
  170098. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170099. /* Initialize method pointers */
  170100. inputctl->pub.consume_input = consume_markers;
  170101. inputctl->pub.reset_input_controller = reset_input_controller;
  170102. inputctl->pub.start_input_pass = start_input_pass2;
  170103. inputctl->pub.finish_input_pass = finish_input_pass;
  170104. /* Initialize state: can't use reset_input_controller since we don't
  170105. * want to try to reset other modules yet.
  170106. */
  170107. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170108. inputctl->pub.eoi_reached = FALSE;
  170109. inputctl->inheaders = TRUE;
  170110. }
  170111. /*** End of inlined file: jdinput.c ***/
  170112. /*** Start of inlined file: jdmainct.c ***/
  170113. #define JPEG_INTERNALS
  170114. /*
  170115. * In the current system design, the main buffer need never be a full-image
  170116. * buffer; any full-height buffers will be found inside the coefficient or
  170117. * postprocessing controllers. Nonetheless, the main controller is not
  170118. * trivial. Its responsibility is to provide context rows for upsampling/
  170119. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170120. *
  170121. * Postprocessor input data is counted in "row groups". A row group
  170122. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170123. * sample rows of each component. (We require DCT_scaled_size values to be
  170124. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170125. * values will likely be powers of two, so we actually have the stronger
  170126. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170127. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170128. * row group (times any additional scale factor that the upsampler is
  170129. * applying).
  170130. *
  170131. * The coefficient controller will deliver data to us one iMCU row at a time;
  170132. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170133. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170134. * to one row of MCUs when the image is fully interleaved.) Note that the
  170135. * number of sample rows varies across components, but the number of row
  170136. * groups does not. Some garbage sample rows may be included in the last iMCU
  170137. * row at the bottom of the image.
  170138. *
  170139. * Depending on the vertical scaling algorithm used, the upsampler may need
  170140. * access to the sample row(s) above and below its current input row group.
  170141. * The upsampler is required to set need_context_rows TRUE at global selection
  170142. * time if so. When need_context_rows is FALSE, this controller can simply
  170143. * obtain one iMCU row at a time from the coefficient controller and dole it
  170144. * out as row groups to the postprocessor.
  170145. *
  170146. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170147. * passed to postprocessing contains at least one row group's worth of samples
  170148. * above and below the row group(s) being processed. Note that the context
  170149. * rows "above" the first passed row group appear at negative row offsets in
  170150. * the passed buffer. At the top and bottom of the image, the required
  170151. * context rows are manufactured by duplicating the first or last real sample
  170152. * row; this avoids having special cases in the upsampling inner loops.
  170153. *
  170154. * The amount of context is fixed at one row group just because that's a
  170155. * convenient number for this controller to work with. The existing
  170156. * upsamplers really only need one sample row of context. An upsampler
  170157. * supporting arbitrary output rescaling might wish for more than one row
  170158. * group of context when shrinking the image; tough, we don't handle that.
  170159. * (This is justified by the assumption that downsizing will be handled mostly
  170160. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170161. * the upsample step needn't be much less than one.)
  170162. *
  170163. * To provide the desired context, we have to retain the last two row groups
  170164. * of one iMCU row while reading in the next iMCU row. (The last row group
  170165. * can't be processed until we have another row group for its below-context,
  170166. * and so we have to save the next-to-last group too for its above-context.)
  170167. * We could do this most simply by copying data around in our buffer, but
  170168. * that'd be very slow. We can avoid copying any data by creating a rather
  170169. * strange pointer structure. Here's how it works. We allocate a workspace
  170170. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170171. * of row groups per iMCU row). We create two sets of redundant pointers to
  170172. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170173. * pointer lists look like this:
  170174. * M+1 M-1
  170175. * master pointer --> 0 master pointer --> 0
  170176. * 1 1
  170177. * ... ...
  170178. * M-3 M-3
  170179. * M-2 M
  170180. * M-1 M+1
  170181. * M M-2
  170182. * M+1 M-1
  170183. * 0 0
  170184. * We read alternate iMCU rows using each master pointer; thus the last two
  170185. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170186. * The pointer lists are set up so that the required context rows appear to
  170187. * be adjacent to the proper places when we pass the pointer lists to the
  170188. * upsampler.
  170189. *
  170190. * The above pictures describe the normal state of the pointer lists.
  170191. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170192. * the first or last sample row as necessary (this is cheaper than copying
  170193. * sample rows around).
  170194. *
  170195. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170196. * situation each iMCU row provides only one row group so the buffering logic
  170197. * must be different (eg, we must read two iMCU rows before we can emit the
  170198. * first row group). For now, we simply do not support providing context
  170199. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170200. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170201. * want it quick and dirty, so a context-free upsampler is sufficient.
  170202. */
  170203. /* Private buffer controller object */
  170204. typedef struct {
  170205. struct jpeg_d_main_controller pub; /* public fields */
  170206. /* Pointer to allocated workspace (M or M+2 row groups). */
  170207. JSAMPARRAY buffer[MAX_COMPONENTS];
  170208. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170209. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170210. /* Remaining fields are only used in the context case. */
  170211. /* These are the master pointers to the funny-order pointer lists. */
  170212. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170213. int whichptr; /* indicates which pointer set is now in use */
  170214. int context_state; /* process_data state machine status */
  170215. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170216. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170217. } my_main_controller4;
  170218. typedef my_main_controller4 * my_main_ptr4;
  170219. /* context_state values: */
  170220. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170221. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170222. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170223. /* Forward declarations */
  170224. METHODDEF(void) process_data_simple_main2
  170225. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170226. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170227. METHODDEF(void) process_data_context_main
  170228. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170229. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170230. #ifdef QUANT_2PASS_SUPPORTED
  170231. METHODDEF(void) process_data_crank_post
  170232. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170233. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170234. #endif
  170235. LOCAL(void)
  170236. alloc_funny_pointers (j_decompress_ptr cinfo)
  170237. /* Allocate space for the funny pointer lists.
  170238. * This is done only once, not once per pass.
  170239. */
  170240. {
  170241. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170242. int ci, rgroup;
  170243. int M = cinfo->min_DCT_scaled_size;
  170244. jpeg_component_info *compptr;
  170245. JSAMPARRAY xbuf;
  170246. /* Get top-level space for component array pointers.
  170247. * We alloc both arrays with one call to save a few cycles.
  170248. */
  170249. main_->xbuffer[0] = (JSAMPIMAGE)
  170250. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170251. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170252. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170253. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170254. ci++, compptr++) {
  170255. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170256. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170257. /* Get space for pointer lists --- M+4 row groups in each list.
  170258. * We alloc both pointer lists with one call to save a few cycles.
  170259. */
  170260. xbuf = (JSAMPARRAY)
  170261. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170262. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170263. xbuf += rgroup; /* want one row group at negative offsets */
  170264. main_->xbuffer[0][ci] = xbuf;
  170265. xbuf += rgroup * (M + 4);
  170266. main_->xbuffer[1][ci] = xbuf;
  170267. }
  170268. }
  170269. LOCAL(void)
  170270. make_funny_pointers (j_decompress_ptr cinfo)
  170271. /* Create the funny pointer lists discussed in the comments above.
  170272. * The actual workspace is already allocated (in main->buffer),
  170273. * and the space for the pointer lists is allocated too.
  170274. * This routine just fills in the curiously ordered lists.
  170275. * This will be repeated at the beginning of each pass.
  170276. */
  170277. {
  170278. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170279. int ci, i, rgroup;
  170280. int M = cinfo->min_DCT_scaled_size;
  170281. jpeg_component_info *compptr;
  170282. JSAMPARRAY buf, xbuf0, xbuf1;
  170283. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170284. ci++, compptr++) {
  170285. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170286. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170287. xbuf0 = main_->xbuffer[0][ci];
  170288. xbuf1 = main_->xbuffer[1][ci];
  170289. /* First copy the workspace pointers as-is */
  170290. buf = main_->buffer[ci];
  170291. for (i = 0; i < rgroup * (M + 2); i++) {
  170292. xbuf0[i] = xbuf1[i] = buf[i];
  170293. }
  170294. /* In the second list, put the last four row groups in swapped order */
  170295. for (i = 0; i < rgroup * 2; i++) {
  170296. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  170297. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  170298. }
  170299. /* The wraparound pointers at top and bottom will be filled later
  170300. * (see set_wraparound_pointers, below). Initially we want the "above"
  170301. * pointers to duplicate the first actual data line. This only needs
  170302. * to happen in xbuffer[0].
  170303. */
  170304. for (i = 0; i < rgroup; i++) {
  170305. xbuf0[i - rgroup] = xbuf0[0];
  170306. }
  170307. }
  170308. }
  170309. LOCAL(void)
  170310. set_wraparound_pointers (j_decompress_ptr cinfo)
  170311. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170312. * This changes the pointer list state from top-of-image to the normal state.
  170313. */
  170314. {
  170315. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170316. int ci, i, rgroup;
  170317. int M = cinfo->min_DCT_scaled_size;
  170318. jpeg_component_info *compptr;
  170319. JSAMPARRAY xbuf0, xbuf1;
  170320. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170321. ci++, compptr++) {
  170322. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170323. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170324. xbuf0 = main_->xbuffer[0][ci];
  170325. xbuf1 = main_->xbuffer[1][ci];
  170326. for (i = 0; i < rgroup; i++) {
  170327. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170328. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170329. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170330. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170331. }
  170332. }
  170333. }
  170334. LOCAL(void)
  170335. set_bottom_pointers (j_decompress_ptr cinfo)
  170336. /* Change the pointer lists to duplicate the last sample row at the bottom
  170337. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170338. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170339. */
  170340. {
  170341. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170342. int ci, i, rgroup, iMCUheight, rows_left;
  170343. jpeg_component_info *compptr;
  170344. JSAMPARRAY xbuf;
  170345. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170346. ci++, compptr++) {
  170347. /* Count sample rows in one iMCU row and in one row group */
  170348. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170349. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170350. /* Count nondummy sample rows remaining for this component */
  170351. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170352. if (rows_left == 0) rows_left = iMCUheight;
  170353. /* Count nondummy row groups. Should get same answer for each component,
  170354. * so we need only do it once.
  170355. */
  170356. if (ci == 0) {
  170357. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170358. }
  170359. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170360. * last partial rowgroup and ensures at least one full rowgroup of context.
  170361. */
  170362. xbuf = main_->xbuffer[main_->whichptr][ci];
  170363. for (i = 0; i < rgroup * 2; i++) {
  170364. xbuf[rows_left + i] = xbuf[rows_left-1];
  170365. }
  170366. }
  170367. }
  170368. /*
  170369. * Initialize for a processing pass.
  170370. */
  170371. METHODDEF(void)
  170372. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170373. {
  170374. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170375. switch (pass_mode) {
  170376. case JBUF_PASS_THRU:
  170377. if (cinfo->upsample->need_context_rows) {
  170378. main_->pub.process_data = process_data_context_main;
  170379. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170380. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170381. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170382. main_->iMCU_row_ctr = 0;
  170383. } else {
  170384. /* Simple case with no context needed */
  170385. main_->pub.process_data = process_data_simple_main2;
  170386. }
  170387. main_->buffer_full = FALSE; /* Mark buffer empty */
  170388. main_->rowgroup_ctr = 0;
  170389. break;
  170390. #ifdef QUANT_2PASS_SUPPORTED
  170391. case JBUF_CRANK_DEST:
  170392. /* For last pass of 2-pass quantization, just crank the postprocessor */
  170393. main_->pub.process_data = process_data_crank_post;
  170394. break;
  170395. #endif
  170396. default:
  170397. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170398. break;
  170399. }
  170400. }
  170401. /*
  170402. * Process some data.
  170403. * This handles the simple case where no context is required.
  170404. */
  170405. METHODDEF(void)
  170406. process_data_simple_main2 (j_decompress_ptr cinfo,
  170407. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170408. JDIMENSION out_rows_avail)
  170409. {
  170410. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170411. JDIMENSION rowgroups_avail;
  170412. /* Read input data if we haven't filled the main buffer yet */
  170413. if (! main_->buffer_full) {
  170414. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  170415. return; /* suspension forced, can do nothing more */
  170416. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170417. }
  170418. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  170419. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  170420. /* Note: at the bottom of the image, we may pass extra garbage row groups
  170421. * to the postprocessor. The postprocessor has to check for bottom
  170422. * of image anyway (at row resolution), so no point in us doing it too.
  170423. */
  170424. /* Feed the postprocessor */
  170425. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  170426. &main_->rowgroup_ctr, rowgroups_avail,
  170427. output_buf, out_row_ctr, out_rows_avail);
  170428. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  170429. if (main_->rowgroup_ctr >= rowgroups_avail) {
  170430. main_->buffer_full = FALSE;
  170431. main_->rowgroup_ctr = 0;
  170432. }
  170433. }
  170434. /*
  170435. * Process some data.
  170436. * This handles the case where context rows must be provided.
  170437. */
  170438. METHODDEF(void)
  170439. process_data_context_main (j_decompress_ptr cinfo,
  170440. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170441. JDIMENSION out_rows_avail)
  170442. {
  170443. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170444. /* Read input data if we haven't filled the main buffer yet */
  170445. if (! main_->buffer_full) {
  170446. if (! (*cinfo->coef->decompress_data) (cinfo,
  170447. main_->xbuffer[main_->whichptr]))
  170448. return; /* suspension forced, can do nothing more */
  170449. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170450. main_->iMCU_row_ctr++; /* count rows received */
  170451. }
  170452. /* Postprocessor typically will not swallow all the input data it is handed
  170453. * in one call (due to filling the output buffer first). Must be prepared
  170454. * to exit and restart. This switch lets us keep track of how far we got.
  170455. * Note that each case falls through to the next on successful completion.
  170456. */
  170457. switch (main_->context_state) {
  170458. case CTX_POSTPONED_ROW:
  170459. /* Call postprocessor using previously set pointers for postponed row */
  170460. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170461. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170462. output_buf, out_row_ctr, out_rows_avail);
  170463. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170464. return; /* Need to suspend */
  170465. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170466. if (*out_row_ctr >= out_rows_avail)
  170467. return; /* Postprocessor exactly filled output buf */
  170468. /*FALLTHROUGH*/
  170469. case CTX_PREPARE_FOR_IMCU:
  170470. /* Prepare to process first M-1 row groups of this iMCU row */
  170471. main_->rowgroup_ctr = 0;
  170472. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  170473. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  170474. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  170475. */
  170476. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  170477. set_bottom_pointers(cinfo);
  170478. main_->context_state = CTX_PROCESS_IMCU;
  170479. /*FALLTHROUGH*/
  170480. case CTX_PROCESS_IMCU:
  170481. /* Call postprocessor using previously set pointers */
  170482. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170483. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170484. output_buf, out_row_ctr, out_rows_avail);
  170485. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170486. return; /* Need to suspend */
  170487. /* After the first iMCU, change wraparound pointers to normal state */
  170488. if (main_->iMCU_row_ctr == 1)
  170489. set_wraparound_pointers(cinfo);
  170490. /* Prepare to load new iMCU row using other xbuffer list */
  170491. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  170492. main_->buffer_full = FALSE;
  170493. /* Still need to process last row group of this iMCU row, */
  170494. /* which is saved at index M+1 of the other xbuffer */
  170495. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  170496. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  170497. main_->context_state = CTX_POSTPONED_ROW;
  170498. }
  170499. }
  170500. /*
  170501. * Process some data.
  170502. * Final pass of two-pass quantization: just call the postprocessor.
  170503. * Source data will be the postprocessor controller's internal buffer.
  170504. */
  170505. #ifdef QUANT_2PASS_SUPPORTED
  170506. METHODDEF(void)
  170507. process_data_crank_post (j_decompress_ptr cinfo,
  170508. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170509. JDIMENSION out_rows_avail)
  170510. {
  170511. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  170512. (JDIMENSION *) NULL, (JDIMENSION) 0,
  170513. output_buf, out_row_ctr, out_rows_avail);
  170514. }
  170515. #endif /* QUANT_2PASS_SUPPORTED */
  170516. /*
  170517. * Initialize main buffer controller.
  170518. */
  170519. GLOBAL(void)
  170520. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  170521. {
  170522. my_main_ptr4 main_;
  170523. int ci, rgroup, ngroups;
  170524. jpeg_component_info *compptr;
  170525. main_ = (my_main_ptr4)
  170526. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170527. SIZEOF(my_main_controller4));
  170528. cinfo->main = (struct jpeg_d_main_controller *) main_;
  170529. main_->pub.start_pass = start_pass_main2;
  170530. if (need_full_buffer) /* shouldn't happen */
  170531. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170532. /* Allocate the workspace.
  170533. * ngroups is the number of row groups we need.
  170534. */
  170535. if (cinfo->upsample->need_context_rows) {
  170536. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  170537. ERREXIT(cinfo, JERR_NOTIMPL);
  170538. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  170539. ngroups = cinfo->min_DCT_scaled_size + 2;
  170540. } else {
  170541. ngroups = cinfo->min_DCT_scaled_size;
  170542. }
  170543. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170544. ci++, compptr++) {
  170545. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170546. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170547. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  170548. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170549. compptr->width_in_blocks * compptr->DCT_scaled_size,
  170550. (JDIMENSION) (rgroup * ngroups));
  170551. }
  170552. }
  170553. /*** End of inlined file: jdmainct.c ***/
  170554. /*** Start of inlined file: jdmarker.c ***/
  170555. #define JPEG_INTERNALS
  170556. /* Private state */
  170557. typedef struct {
  170558. struct jpeg_marker_reader pub; /* public fields */
  170559. /* Application-overridable marker processing methods */
  170560. jpeg_marker_parser_method process_COM;
  170561. jpeg_marker_parser_method process_APPn[16];
  170562. /* Limit on marker data length to save for each marker type */
  170563. unsigned int length_limit_COM;
  170564. unsigned int length_limit_APPn[16];
  170565. /* Status of COM/APPn marker saving */
  170566. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  170567. unsigned int bytes_read; /* data bytes read so far in marker */
  170568. /* Note: cur_marker is not linked into marker_list until it's all read. */
  170569. } my_marker_reader;
  170570. typedef my_marker_reader * my_marker_ptr2;
  170571. /*
  170572. * Macros for fetching data from the data source module.
  170573. *
  170574. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  170575. * the current restart point; we update them only when we have reached a
  170576. * suitable place to restart if a suspension occurs.
  170577. */
  170578. /* Declare and initialize local copies of input pointer/count */
  170579. #define INPUT_VARS(cinfo) \
  170580. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  170581. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  170582. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  170583. /* Unload the local copies --- do this only at a restart boundary */
  170584. #define INPUT_SYNC(cinfo) \
  170585. ( datasrc->next_input_byte = next_input_byte, \
  170586. datasrc->bytes_in_buffer = bytes_in_buffer )
  170587. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  170588. #define INPUT_RELOAD(cinfo) \
  170589. ( next_input_byte = datasrc->next_input_byte, \
  170590. bytes_in_buffer = datasrc->bytes_in_buffer )
  170591. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  170592. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  170593. * but we must reload the local copies after a successful fill.
  170594. */
  170595. #define MAKE_BYTE_AVAIL(cinfo,action) \
  170596. if (bytes_in_buffer == 0) { \
  170597. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  170598. { action; } \
  170599. INPUT_RELOAD(cinfo); \
  170600. }
  170601. /* Read a byte into variable V.
  170602. * If must suspend, take the specified action (typically "return FALSE").
  170603. */
  170604. #define INPUT_BYTE(cinfo,V,action) \
  170605. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170606. bytes_in_buffer--; \
  170607. V = GETJOCTET(*next_input_byte++); )
  170608. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  170609. * V should be declared unsigned int or perhaps INT32.
  170610. */
  170611. #define INPUT_2BYTES(cinfo,V,action) \
  170612. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170613. bytes_in_buffer--; \
  170614. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  170615. MAKE_BYTE_AVAIL(cinfo,action); \
  170616. bytes_in_buffer--; \
  170617. V += GETJOCTET(*next_input_byte++); )
  170618. /*
  170619. * Routines to process JPEG markers.
  170620. *
  170621. * Entry condition: JPEG marker itself has been read and its code saved
  170622. * in cinfo->unread_marker; input restart point is just after the marker.
  170623. *
  170624. * Exit: if return TRUE, have read and processed any parameters, and have
  170625. * updated the restart point to point after the parameters.
  170626. * If return FALSE, was forced to suspend before reaching end of
  170627. * marker parameters; restart point has not been moved. Same routine
  170628. * will be called again after application supplies more input data.
  170629. *
  170630. * This approach to suspension assumes that all of a marker's parameters
  170631. * can fit into a single input bufferload. This should hold for "normal"
  170632. * markers. Some COM/APPn markers might have large parameter segments
  170633. * that might not fit. If we are simply dropping such a marker, we use
  170634. * skip_input_data to get past it, and thereby put the problem on the
  170635. * source manager's shoulders. If we are saving the marker's contents
  170636. * into memory, we use a slightly different convention: when forced to
  170637. * suspend, the marker processor updates the restart point to the end of
  170638. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  170639. * On resumption, cinfo->unread_marker still contains the marker code,
  170640. * but the data source will point to the next chunk of marker data.
  170641. * The marker processor must retain internal state to deal with this.
  170642. *
  170643. * Note that we don't bother to avoid duplicate trace messages if a
  170644. * suspension occurs within marker parameters. Other side effects
  170645. * require more care.
  170646. */
  170647. LOCAL(boolean)
  170648. get_soi (j_decompress_ptr cinfo)
  170649. /* Process an SOI marker */
  170650. {
  170651. int i;
  170652. TRACEMS(cinfo, 1, JTRC_SOI);
  170653. if (cinfo->marker->saw_SOI)
  170654. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  170655. /* Reset all parameters that are defined to be reset by SOI */
  170656. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  170657. cinfo->arith_dc_L[i] = 0;
  170658. cinfo->arith_dc_U[i] = 1;
  170659. cinfo->arith_ac_K[i] = 5;
  170660. }
  170661. cinfo->restart_interval = 0;
  170662. /* Set initial assumptions for colorspace etc */
  170663. cinfo->jpeg_color_space = JCS_UNKNOWN;
  170664. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  170665. cinfo->saw_JFIF_marker = FALSE;
  170666. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  170667. cinfo->JFIF_minor_version = 1;
  170668. cinfo->density_unit = 0;
  170669. cinfo->X_density = 1;
  170670. cinfo->Y_density = 1;
  170671. cinfo->saw_Adobe_marker = FALSE;
  170672. cinfo->Adobe_transform = 0;
  170673. cinfo->marker->saw_SOI = TRUE;
  170674. return TRUE;
  170675. }
  170676. LOCAL(boolean)
  170677. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  170678. /* Process a SOFn marker */
  170679. {
  170680. INT32 length;
  170681. int c, ci;
  170682. jpeg_component_info * compptr;
  170683. INPUT_VARS(cinfo);
  170684. cinfo->progressive_mode = is_prog;
  170685. cinfo->arith_code = is_arith;
  170686. INPUT_2BYTES(cinfo, length, return FALSE);
  170687. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  170688. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  170689. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  170690. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  170691. length -= 8;
  170692. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  170693. (int) cinfo->image_width, (int) cinfo->image_height,
  170694. cinfo->num_components);
  170695. if (cinfo->marker->saw_SOF)
  170696. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  170697. /* We don't support files in which the image height is initially specified */
  170698. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  170699. /* might as well have a general sanity check. */
  170700. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  170701. || cinfo->num_components <= 0)
  170702. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  170703. if (length != (cinfo->num_components * 3))
  170704. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170705. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  170706. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  170707. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170708. cinfo->num_components * SIZEOF(jpeg_component_info));
  170709. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170710. ci++, compptr++) {
  170711. compptr->component_index = ci;
  170712. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  170713. INPUT_BYTE(cinfo, c, return FALSE);
  170714. compptr->h_samp_factor = (c >> 4) & 15;
  170715. compptr->v_samp_factor = (c ) & 15;
  170716. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  170717. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  170718. compptr->component_id, compptr->h_samp_factor,
  170719. compptr->v_samp_factor, compptr->quant_tbl_no);
  170720. }
  170721. cinfo->marker->saw_SOF = TRUE;
  170722. INPUT_SYNC(cinfo);
  170723. return TRUE;
  170724. }
  170725. LOCAL(boolean)
  170726. get_sos (j_decompress_ptr cinfo)
  170727. /* Process a SOS marker */
  170728. {
  170729. INT32 length;
  170730. int i, ci, n, c, cc;
  170731. jpeg_component_info * compptr;
  170732. INPUT_VARS(cinfo);
  170733. if (! cinfo->marker->saw_SOF)
  170734. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  170735. INPUT_2BYTES(cinfo, length, return FALSE);
  170736. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  170737. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  170738. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  170739. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170740. cinfo->comps_in_scan = n;
  170741. /* Collect the component-spec parameters */
  170742. for (i = 0; i < n; i++) {
  170743. INPUT_BYTE(cinfo, cc, return FALSE);
  170744. INPUT_BYTE(cinfo, c, return FALSE);
  170745. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170746. ci++, compptr++) {
  170747. if (cc == compptr->component_id)
  170748. goto id_found;
  170749. }
  170750. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  170751. id_found:
  170752. cinfo->cur_comp_info[i] = compptr;
  170753. compptr->dc_tbl_no = (c >> 4) & 15;
  170754. compptr->ac_tbl_no = (c ) & 15;
  170755. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  170756. compptr->dc_tbl_no, compptr->ac_tbl_no);
  170757. }
  170758. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  170759. INPUT_BYTE(cinfo, c, return FALSE);
  170760. cinfo->Ss = c;
  170761. INPUT_BYTE(cinfo, c, return FALSE);
  170762. cinfo->Se = c;
  170763. INPUT_BYTE(cinfo, c, return FALSE);
  170764. cinfo->Ah = (c >> 4) & 15;
  170765. cinfo->Al = (c ) & 15;
  170766. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  170767. cinfo->Ah, cinfo->Al);
  170768. /* Prepare to scan data & restart markers */
  170769. cinfo->marker->next_restart_num = 0;
  170770. /* Count another SOS marker */
  170771. cinfo->input_scan_number++;
  170772. INPUT_SYNC(cinfo);
  170773. return TRUE;
  170774. }
  170775. #ifdef D_ARITH_CODING_SUPPORTED
  170776. LOCAL(boolean)
  170777. get_dac (j_decompress_ptr cinfo)
  170778. /* Process a DAC marker */
  170779. {
  170780. INT32 length;
  170781. int index, val;
  170782. INPUT_VARS(cinfo);
  170783. INPUT_2BYTES(cinfo, length, return FALSE);
  170784. length -= 2;
  170785. while (length > 0) {
  170786. INPUT_BYTE(cinfo, index, return FALSE);
  170787. INPUT_BYTE(cinfo, val, return FALSE);
  170788. length -= 2;
  170789. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  170790. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  170791. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  170792. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  170793. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  170794. } else { /* define DC table */
  170795. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  170796. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  170797. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  170798. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  170799. }
  170800. }
  170801. if (length != 0)
  170802. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170803. INPUT_SYNC(cinfo);
  170804. return TRUE;
  170805. }
  170806. #else /* ! D_ARITH_CODING_SUPPORTED */
  170807. #define get_dac(cinfo) skip_variable(cinfo)
  170808. #endif /* D_ARITH_CODING_SUPPORTED */
  170809. LOCAL(boolean)
  170810. get_dht (j_decompress_ptr cinfo)
  170811. /* Process a DHT marker */
  170812. {
  170813. INT32 length;
  170814. UINT8 bits[17];
  170815. UINT8 huffval[256];
  170816. int i, index, count;
  170817. JHUFF_TBL **htblptr;
  170818. INPUT_VARS(cinfo);
  170819. INPUT_2BYTES(cinfo, length, return FALSE);
  170820. length -= 2;
  170821. while (length > 16) {
  170822. INPUT_BYTE(cinfo, index, return FALSE);
  170823. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  170824. bits[0] = 0;
  170825. count = 0;
  170826. for (i = 1; i <= 16; i++) {
  170827. INPUT_BYTE(cinfo, bits[i], return FALSE);
  170828. count += bits[i];
  170829. }
  170830. length -= 1 + 16;
  170831. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  170832. bits[1], bits[2], bits[3], bits[4],
  170833. bits[5], bits[6], bits[7], bits[8]);
  170834. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  170835. bits[9], bits[10], bits[11], bits[12],
  170836. bits[13], bits[14], bits[15], bits[16]);
  170837. /* Here we just do minimal validation of the counts to avoid walking
  170838. * off the end of our table space. jdhuff.c will check more carefully.
  170839. */
  170840. if (count > 256 || ((INT32) count) > length)
  170841. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170842. for (i = 0; i < count; i++)
  170843. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  170844. length -= count;
  170845. if (index & 0x10) { /* AC table definition */
  170846. index -= 0x10;
  170847. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  170848. } else { /* DC table definition */
  170849. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  170850. }
  170851. if (index < 0 || index >= NUM_HUFF_TBLS)
  170852. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  170853. if (*htblptr == NULL)
  170854. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  170855. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  170856. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  170857. }
  170858. if (length != 0)
  170859. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170860. INPUT_SYNC(cinfo);
  170861. return TRUE;
  170862. }
  170863. LOCAL(boolean)
  170864. get_dqt (j_decompress_ptr cinfo)
  170865. /* Process a DQT marker */
  170866. {
  170867. INT32 length;
  170868. int n, i, prec;
  170869. unsigned int tmp;
  170870. JQUANT_TBL *quant_ptr;
  170871. INPUT_VARS(cinfo);
  170872. INPUT_2BYTES(cinfo, length, return FALSE);
  170873. length -= 2;
  170874. while (length > 0) {
  170875. INPUT_BYTE(cinfo, n, return FALSE);
  170876. prec = n >> 4;
  170877. n &= 0x0F;
  170878. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  170879. if (n >= NUM_QUANT_TBLS)
  170880. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  170881. if (cinfo->quant_tbl_ptrs[n] == NULL)
  170882. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  170883. quant_ptr = cinfo->quant_tbl_ptrs[n];
  170884. for (i = 0; i < DCTSIZE2; i++) {
  170885. if (prec)
  170886. INPUT_2BYTES(cinfo, tmp, return FALSE);
  170887. else
  170888. INPUT_BYTE(cinfo, tmp, return FALSE);
  170889. /* We convert the zigzag-order table to natural array order. */
  170890. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  170891. }
  170892. if (cinfo->err->trace_level >= 2) {
  170893. for (i = 0; i < DCTSIZE2; i += 8) {
  170894. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  170895. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  170896. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  170897. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  170898. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  170899. }
  170900. }
  170901. length -= DCTSIZE2+1;
  170902. if (prec) length -= DCTSIZE2;
  170903. }
  170904. if (length != 0)
  170905. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170906. INPUT_SYNC(cinfo);
  170907. return TRUE;
  170908. }
  170909. LOCAL(boolean)
  170910. get_dri (j_decompress_ptr cinfo)
  170911. /* Process a DRI marker */
  170912. {
  170913. INT32 length;
  170914. unsigned int tmp;
  170915. INPUT_VARS(cinfo);
  170916. INPUT_2BYTES(cinfo, length, return FALSE);
  170917. if (length != 4)
  170918. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170919. INPUT_2BYTES(cinfo, tmp, return FALSE);
  170920. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  170921. cinfo->restart_interval = tmp;
  170922. INPUT_SYNC(cinfo);
  170923. return TRUE;
  170924. }
  170925. /*
  170926. * Routines for processing APPn and COM markers.
  170927. * These are either saved in memory or discarded, per application request.
  170928. * APP0 and APP14 are specially checked to see if they are
  170929. * JFIF and Adobe markers, respectively.
  170930. */
  170931. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  170932. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  170933. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  170934. LOCAL(void)
  170935. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  170936. unsigned int datalen, INT32 remaining)
  170937. /* Examine first few bytes from an APP0.
  170938. * Take appropriate action if it is a JFIF marker.
  170939. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  170940. */
  170941. {
  170942. INT32 totallen = (INT32) datalen + remaining;
  170943. if (datalen >= APP0_DATA_LEN &&
  170944. GETJOCTET(data[0]) == 0x4A &&
  170945. GETJOCTET(data[1]) == 0x46 &&
  170946. GETJOCTET(data[2]) == 0x49 &&
  170947. GETJOCTET(data[3]) == 0x46 &&
  170948. GETJOCTET(data[4]) == 0) {
  170949. /* Found JFIF APP0 marker: save info */
  170950. cinfo->saw_JFIF_marker = TRUE;
  170951. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  170952. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  170953. cinfo->density_unit = GETJOCTET(data[7]);
  170954. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  170955. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  170956. /* Check version.
  170957. * Major version must be 1, anything else signals an incompatible change.
  170958. * (We used to treat this as an error, but now it's a nonfatal warning,
  170959. * because some bozo at Hijaak couldn't read the spec.)
  170960. * Minor version should be 0..2, but process anyway if newer.
  170961. */
  170962. if (cinfo->JFIF_major_version != 1)
  170963. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  170964. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  170965. /* Generate trace messages */
  170966. TRACEMS5(cinfo, 1, JTRC_JFIF,
  170967. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  170968. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  170969. /* Validate thumbnail dimensions and issue appropriate messages */
  170970. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  170971. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  170972. GETJOCTET(data[12]), GETJOCTET(data[13]));
  170973. totallen -= APP0_DATA_LEN;
  170974. if (totallen !=
  170975. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  170976. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  170977. } else if (datalen >= 6 &&
  170978. GETJOCTET(data[0]) == 0x4A &&
  170979. GETJOCTET(data[1]) == 0x46 &&
  170980. GETJOCTET(data[2]) == 0x58 &&
  170981. GETJOCTET(data[3]) == 0x58 &&
  170982. GETJOCTET(data[4]) == 0) {
  170983. /* Found JFIF "JFXX" extension APP0 marker */
  170984. /* The library doesn't actually do anything with these,
  170985. * but we try to produce a helpful trace message.
  170986. */
  170987. switch (GETJOCTET(data[5])) {
  170988. case 0x10:
  170989. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  170990. break;
  170991. case 0x11:
  170992. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  170993. break;
  170994. case 0x13:
  170995. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  170996. break;
  170997. default:
  170998. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  170999. GETJOCTET(data[5]), (int) totallen);
  171000. break;
  171001. }
  171002. } else {
  171003. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171004. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171005. }
  171006. }
  171007. LOCAL(void)
  171008. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171009. unsigned int datalen, INT32 remaining)
  171010. /* Examine first few bytes from an APP14.
  171011. * Take appropriate action if it is an Adobe marker.
  171012. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171013. */
  171014. {
  171015. unsigned int version, flags0, flags1, transform;
  171016. if (datalen >= APP14_DATA_LEN &&
  171017. GETJOCTET(data[0]) == 0x41 &&
  171018. GETJOCTET(data[1]) == 0x64 &&
  171019. GETJOCTET(data[2]) == 0x6F &&
  171020. GETJOCTET(data[3]) == 0x62 &&
  171021. GETJOCTET(data[4]) == 0x65) {
  171022. /* Found Adobe APP14 marker */
  171023. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171024. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171025. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171026. transform = GETJOCTET(data[11]);
  171027. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171028. cinfo->saw_Adobe_marker = TRUE;
  171029. cinfo->Adobe_transform = (UINT8) transform;
  171030. } else {
  171031. /* Start of APP14 does not match "Adobe", or too short */
  171032. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171033. }
  171034. }
  171035. METHODDEF(boolean)
  171036. get_interesting_appn (j_decompress_ptr cinfo)
  171037. /* Process an APP0 or APP14 marker without saving it */
  171038. {
  171039. INT32 length;
  171040. JOCTET b[APPN_DATA_LEN];
  171041. unsigned int i, numtoread;
  171042. INPUT_VARS(cinfo);
  171043. INPUT_2BYTES(cinfo, length, return FALSE);
  171044. length -= 2;
  171045. /* get the interesting part of the marker data */
  171046. if (length >= APPN_DATA_LEN)
  171047. numtoread = APPN_DATA_LEN;
  171048. else if (length > 0)
  171049. numtoread = (unsigned int) length;
  171050. else
  171051. numtoread = 0;
  171052. for (i = 0; i < numtoread; i++)
  171053. INPUT_BYTE(cinfo, b[i], return FALSE);
  171054. length -= numtoread;
  171055. /* process it */
  171056. switch (cinfo->unread_marker) {
  171057. case M_APP0:
  171058. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171059. break;
  171060. case M_APP14:
  171061. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171062. break;
  171063. default:
  171064. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171065. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171066. break;
  171067. }
  171068. /* skip any remaining data -- could be lots */
  171069. INPUT_SYNC(cinfo);
  171070. if (length > 0)
  171071. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171072. return TRUE;
  171073. }
  171074. #ifdef SAVE_MARKERS_SUPPORTED
  171075. METHODDEF(boolean)
  171076. save_marker (j_decompress_ptr cinfo)
  171077. /* Save an APPn or COM marker into the marker list */
  171078. {
  171079. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171080. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171081. unsigned int bytes_read, data_length;
  171082. JOCTET FAR * data;
  171083. INT32 length = 0;
  171084. INPUT_VARS(cinfo);
  171085. if (cur_marker == NULL) {
  171086. /* begin reading a marker */
  171087. INPUT_2BYTES(cinfo, length, return FALSE);
  171088. length -= 2;
  171089. if (length >= 0) { /* watch out for bogus length word */
  171090. /* figure out how much we want to save */
  171091. unsigned int limit;
  171092. if (cinfo->unread_marker == (int) M_COM)
  171093. limit = marker->length_limit_COM;
  171094. else
  171095. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171096. if ((unsigned int) length < limit)
  171097. limit = (unsigned int) length;
  171098. /* allocate and initialize the marker item */
  171099. cur_marker = (jpeg_saved_marker_ptr)
  171100. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171101. SIZEOF(struct jpeg_marker_struct) + limit);
  171102. cur_marker->next = NULL;
  171103. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171104. cur_marker->original_length = (unsigned int) length;
  171105. cur_marker->data_length = limit;
  171106. /* data area is just beyond the jpeg_marker_struct */
  171107. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171108. marker->cur_marker = cur_marker;
  171109. marker->bytes_read = 0;
  171110. bytes_read = 0;
  171111. data_length = limit;
  171112. } else {
  171113. /* deal with bogus length word */
  171114. bytes_read = data_length = 0;
  171115. data = NULL;
  171116. }
  171117. } else {
  171118. /* resume reading a marker */
  171119. bytes_read = marker->bytes_read;
  171120. data_length = cur_marker->data_length;
  171121. data = cur_marker->data + bytes_read;
  171122. }
  171123. while (bytes_read < data_length) {
  171124. INPUT_SYNC(cinfo); /* move the restart point to here */
  171125. marker->bytes_read = bytes_read;
  171126. /* If there's not at least one byte in buffer, suspend */
  171127. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171128. /* Copy bytes with reasonable rapidity */
  171129. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171130. *data++ = *next_input_byte++;
  171131. bytes_in_buffer--;
  171132. bytes_read++;
  171133. }
  171134. }
  171135. /* Done reading what we want to read */
  171136. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171137. /* Add new marker to end of list */
  171138. if (cinfo->marker_list == NULL) {
  171139. cinfo->marker_list = cur_marker;
  171140. } else {
  171141. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171142. while (prev->next != NULL)
  171143. prev = prev->next;
  171144. prev->next = cur_marker;
  171145. }
  171146. /* Reset pointer & calc remaining data length */
  171147. data = cur_marker->data;
  171148. length = cur_marker->original_length - data_length;
  171149. }
  171150. /* Reset to initial state for next marker */
  171151. marker->cur_marker = NULL;
  171152. /* Process the marker if interesting; else just make a generic trace msg */
  171153. switch (cinfo->unread_marker) {
  171154. case M_APP0:
  171155. examine_app0(cinfo, data, data_length, length);
  171156. break;
  171157. case M_APP14:
  171158. examine_app14(cinfo, data, data_length, length);
  171159. break;
  171160. default:
  171161. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171162. (int) (data_length + length));
  171163. break;
  171164. }
  171165. /* skip any remaining data -- could be lots */
  171166. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171167. if (length > 0)
  171168. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171169. return TRUE;
  171170. }
  171171. #endif /* SAVE_MARKERS_SUPPORTED */
  171172. METHODDEF(boolean)
  171173. skip_variable (j_decompress_ptr cinfo)
  171174. /* Skip over an unknown or uninteresting variable-length marker */
  171175. {
  171176. INT32 length;
  171177. INPUT_VARS(cinfo);
  171178. INPUT_2BYTES(cinfo, length, return FALSE);
  171179. length -= 2;
  171180. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171181. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171182. if (length > 0)
  171183. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171184. return TRUE;
  171185. }
  171186. /*
  171187. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171188. * Returns FALSE if had to suspend before reaching a marker;
  171189. * in that case cinfo->unread_marker is unchanged.
  171190. *
  171191. * Note that the result might not be a valid marker code,
  171192. * but it will never be 0 or FF.
  171193. */
  171194. LOCAL(boolean)
  171195. next_marker (j_decompress_ptr cinfo)
  171196. {
  171197. int c;
  171198. INPUT_VARS(cinfo);
  171199. for (;;) {
  171200. INPUT_BYTE(cinfo, c, return FALSE);
  171201. /* Skip any non-FF bytes.
  171202. * This may look a bit inefficient, but it will not occur in a valid file.
  171203. * We sync after each discarded byte so that a suspending data source
  171204. * can discard the byte from its buffer.
  171205. */
  171206. while (c != 0xFF) {
  171207. cinfo->marker->discarded_bytes++;
  171208. INPUT_SYNC(cinfo);
  171209. INPUT_BYTE(cinfo, c, return FALSE);
  171210. }
  171211. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171212. * pad bytes, so don't count them in discarded_bytes. We assume there
  171213. * will not be so many consecutive FF bytes as to overflow a suspending
  171214. * data source's input buffer.
  171215. */
  171216. do {
  171217. INPUT_BYTE(cinfo, c, return FALSE);
  171218. } while (c == 0xFF);
  171219. if (c != 0)
  171220. break; /* found a valid marker, exit loop */
  171221. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171222. * Discard it and loop back to try again.
  171223. */
  171224. cinfo->marker->discarded_bytes += 2;
  171225. INPUT_SYNC(cinfo);
  171226. }
  171227. if (cinfo->marker->discarded_bytes != 0) {
  171228. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171229. cinfo->marker->discarded_bytes = 0;
  171230. }
  171231. cinfo->unread_marker = c;
  171232. INPUT_SYNC(cinfo);
  171233. return TRUE;
  171234. }
  171235. LOCAL(boolean)
  171236. first_marker (j_decompress_ptr cinfo)
  171237. /* Like next_marker, but used to obtain the initial SOI marker. */
  171238. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171239. * we might well scan an entire input file before realizing it ain't JPEG.
  171240. * If an application wants to process non-JFIF files, it must seek to the
  171241. * SOI before calling the JPEG library.
  171242. */
  171243. {
  171244. int c, c2;
  171245. INPUT_VARS(cinfo);
  171246. INPUT_BYTE(cinfo, c, return FALSE);
  171247. INPUT_BYTE(cinfo, c2, return FALSE);
  171248. if (c != 0xFF || c2 != (int) M_SOI)
  171249. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171250. cinfo->unread_marker = c2;
  171251. INPUT_SYNC(cinfo);
  171252. return TRUE;
  171253. }
  171254. /*
  171255. * Read markers until SOS or EOI.
  171256. *
  171257. * Returns same codes as are defined for jpeg_consume_input:
  171258. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171259. */
  171260. METHODDEF(int)
  171261. read_markers (j_decompress_ptr cinfo)
  171262. {
  171263. /* Outer loop repeats once for each marker. */
  171264. for (;;) {
  171265. /* Collect the marker proper, unless we already did. */
  171266. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171267. if (cinfo->unread_marker == 0) {
  171268. if (! cinfo->marker->saw_SOI) {
  171269. if (! first_marker(cinfo))
  171270. return JPEG_SUSPENDED;
  171271. } else {
  171272. if (! next_marker(cinfo))
  171273. return JPEG_SUSPENDED;
  171274. }
  171275. }
  171276. /* At this point cinfo->unread_marker contains the marker code and the
  171277. * input point is just past the marker proper, but before any parameters.
  171278. * A suspension will cause us to return with this state still true.
  171279. */
  171280. switch (cinfo->unread_marker) {
  171281. case M_SOI:
  171282. if (! get_soi(cinfo))
  171283. return JPEG_SUSPENDED;
  171284. break;
  171285. case M_SOF0: /* Baseline */
  171286. case M_SOF1: /* Extended sequential, Huffman */
  171287. if (! get_sof(cinfo, FALSE, FALSE))
  171288. return JPEG_SUSPENDED;
  171289. break;
  171290. case M_SOF2: /* Progressive, Huffman */
  171291. if (! get_sof(cinfo, TRUE, FALSE))
  171292. return JPEG_SUSPENDED;
  171293. break;
  171294. case M_SOF9: /* Extended sequential, arithmetic */
  171295. if (! get_sof(cinfo, FALSE, TRUE))
  171296. return JPEG_SUSPENDED;
  171297. break;
  171298. case M_SOF10: /* Progressive, arithmetic */
  171299. if (! get_sof(cinfo, TRUE, TRUE))
  171300. return JPEG_SUSPENDED;
  171301. break;
  171302. /* Currently unsupported SOFn types */
  171303. case M_SOF3: /* Lossless, Huffman */
  171304. case M_SOF5: /* Differential sequential, Huffman */
  171305. case M_SOF6: /* Differential progressive, Huffman */
  171306. case M_SOF7: /* Differential lossless, Huffman */
  171307. case M_JPG: /* Reserved for JPEG extensions */
  171308. case M_SOF11: /* Lossless, arithmetic */
  171309. case M_SOF13: /* Differential sequential, arithmetic */
  171310. case M_SOF14: /* Differential progressive, arithmetic */
  171311. case M_SOF15: /* Differential lossless, arithmetic */
  171312. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171313. break;
  171314. case M_SOS:
  171315. if (! get_sos(cinfo))
  171316. return JPEG_SUSPENDED;
  171317. cinfo->unread_marker = 0; /* processed the marker */
  171318. return JPEG_REACHED_SOS;
  171319. case M_EOI:
  171320. TRACEMS(cinfo, 1, JTRC_EOI);
  171321. cinfo->unread_marker = 0; /* processed the marker */
  171322. return JPEG_REACHED_EOI;
  171323. case M_DAC:
  171324. if (! get_dac(cinfo))
  171325. return JPEG_SUSPENDED;
  171326. break;
  171327. case M_DHT:
  171328. if (! get_dht(cinfo))
  171329. return JPEG_SUSPENDED;
  171330. break;
  171331. case M_DQT:
  171332. if (! get_dqt(cinfo))
  171333. return JPEG_SUSPENDED;
  171334. break;
  171335. case M_DRI:
  171336. if (! get_dri(cinfo))
  171337. return JPEG_SUSPENDED;
  171338. break;
  171339. case M_APP0:
  171340. case M_APP1:
  171341. case M_APP2:
  171342. case M_APP3:
  171343. case M_APP4:
  171344. case M_APP5:
  171345. case M_APP6:
  171346. case M_APP7:
  171347. case M_APP8:
  171348. case M_APP9:
  171349. case M_APP10:
  171350. case M_APP11:
  171351. case M_APP12:
  171352. case M_APP13:
  171353. case M_APP14:
  171354. case M_APP15:
  171355. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171356. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171357. return JPEG_SUSPENDED;
  171358. break;
  171359. case M_COM:
  171360. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171361. return JPEG_SUSPENDED;
  171362. break;
  171363. case M_RST0: /* these are all parameterless */
  171364. case M_RST1:
  171365. case M_RST2:
  171366. case M_RST3:
  171367. case M_RST4:
  171368. case M_RST5:
  171369. case M_RST6:
  171370. case M_RST7:
  171371. case M_TEM:
  171372. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171373. break;
  171374. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171375. if (! skip_variable(cinfo))
  171376. return JPEG_SUSPENDED;
  171377. break;
  171378. default: /* must be DHP, EXP, JPGn, or RESn */
  171379. /* For now, we treat the reserved markers as fatal errors since they are
  171380. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171381. * Once the JPEG 3 version-number marker is well defined, this code
  171382. * ought to change!
  171383. */
  171384. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171385. break;
  171386. }
  171387. /* Successfully processed marker, so reset state variable */
  171388. cinfo->unread_marker = 0;
  171389. } /* end loop */
  171390. }
  171391. /*
  171392. * Read a restart marker, which is expected to appear next in the datastream;
  171393. * if the marker is not there, take appropriate recovery action.
  171394. * Returns FALSE if suspension is required.
  171395. *
  171396. * This is called by the entropy decoder after it has read an appropriate
  171397. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  171398. * has already read a marker from the data source. Under normal conditions
  171399. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  171400. * it holds a marker which the decoder will be unable to read past.
  171401. */
  171402. METHODDEF(boolean)
  171403. read_restart_marker (j_decompress_ptr cinfo)
  171404. {
  171405. /* Obtain a marker unless we already did. */
  171406. /* Note that next_marker will complain if it skips any data. */
  171407. if (cinfo->unread_marker == 0) {
  171408. if (! next_marker(cinfo))
  171409. return FALSE;
  171410. }
  171411. if (cinfo->unread_marker ==
  171412. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  171413. /* Normal case --- swallow the marker and let entropy decoder continue */
  171414. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  171415. cinfo->unread_marker = 0;
  171416. } else {
  171417. /* Uh-oh, the restart markers have been messed up. */
  171418. /* Let the data source manager determine how to resync. */
  171419. if (! (*cinfo->src->resync_to_restart) (cinfo,
  171420. cinfo->marker->next_restart_num))
  171421. return FALSE;
  171422. }
  171423. /* Update next-restart state */
  171424. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  171425. return TRUE;
  171426. }
  171427. /*
  171428. * This is the default resync_to_restart method for data source managers
  171429. * to use if they don't have any better approach. Some data source managers
  171430. * may be able to back up, or may have additional knowledge about the data
  171431. * which permits a more intelligent recovery strategy; such managers would
  171432. * presumably supply their own resync method.
  171433. *
  171434. * read_restart_marker calls resync_to_restart if it finds a marker other than
  171435. * the restart marker it was expecting. (This code is *not* used unless
  171436. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  171437. * the marker code actually found (might be anything, except 0 or FF).
  171438. * The desired restart marker number (0..7) is passed as a parameter.
  171439. * This routine is supposed to apply whatever error recovery strategy seems
  171440. * appropriate in order to position the input stream to the next data segment.
  171441. * Note that cinfo->unread_marker is treated as a marker appearing before
  171442. * the current data-source input point; usually it should be reset to zero
  171443. * before returning.
  171444. * Returns FALSE if suspension is required.
  171445. *
  171446. * This implementation is substantially constrained by wanting to treat the
  171447. * input as a data stream; this means we can't back up. Therefore, we have
  171448. * only the following actions to work with:
  171449. * 1. Simply discard the marker and let the entropy decoder resume at next
  171450. * byte of file.
  171451. * 2. Read forward until we find another marker, discarding intervening
  171452. * data. (In theory we could look ahead within the current bufferload,
  171453. * without having to discard data if we don't find the desired marker.
  171454. * This idea is not implemented here, in part because it makes behavior
  171455. * dependent on buffer size and chance buffer-boundary positions.)
  171456. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  171457. * This will cause the entropy decoder to process an empty data segment,
  171458. * inserting dummy zeroes, and then we will reprocess the marker.
  171459. *
  171460. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  171461. * appropriate if the found marker is a future restart marker (indicating
  171462. * that we have missed the desired restart marker, probably because it got
  171463. * corrupted).
  171464. * We apply #2 or #3 if the found marker is a restart marker no more than
  171465. * two counts behind or ahead of the expected one. We also apply #2 if the
  171466. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  171467. * If the found marker is a restart marker more than 2 counts away, we do #1
  171468. * (too much risk that the marker is erroneous; with luck we will be able to
  171469. * resync at some future point).
  171470. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  171471. * overrunning the end of a scan. An implementation limited to single-scan
  171472. * files might find it better to apply #2 for markers other than EOI, since
  171473. * any other marker would have to be bogus data in that case.
  171474. */
  171475. GLOBAL(boolean)
  171476. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  171477. {
  171478. int marker = cinfo->unread_marker;
  171479. int action = 1;
  171480. /* Always put up a warning. */
  171481. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  171482. /* Outer loop handles repeated decision after scanning forward. */
  171483. for (;;) {
  171484. if (marker < (int) M_SOF0)
  171485. action = 2; /* invalid marker */
  171486. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  171487. action = 3; /* valid non-restart marker */
  171488. else {
  171489. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  171490. marker == ((int) M_RST0 + ((desired+2) & 7)))
  171491. action = 3; /* one of the next two expected restarts */
  171492. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  171493. marker == ((int) M_RST0 + ((desired-2) & 7)))
  171494. action = 2; /* a prior restart, so advance */
  171495. else
  171496. action = 1; /* desired restart or too far away */
  171497. }
  171498. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  171499. switch (action) {
  171500. case 1:
  171501. /* Discard marker and let entropy decoder resume processing. */
  171502. cinfo->unread_marker = 0;
  171503. return TRUE;
  171504. case 2:
  171505. /* Scan to the next marker, and repeat the decision loop. */
  171506. if (! next_marker(cinfo))
  171507. return FALSE;
  171508. marker = cinfo->unread_marker;
  171509. break;
  171510. case 3:
  171511. /* Return without advancing past this marker. */
  171512. /* Entropy decoder will be forced to process an empty segment. */
  171513. return TRUE;
  171514. }
  171515. } /* end loop */
  171516. }
  171517. /*
  171518. * Reset marker processing state to begin a fresh datastream.
  171519. */
  171520. METHODDEF(void)
  171521. reset_marker_reader (j_decompress_ptr cinfo)
  171522. {
  171523. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171524. cinfo->comp_info = NULL; /* until allocated by get_sof */
  171525. cinfo->input_scan_number = 0; /* no SOS seen yet */
  171526. cinfo->unread_marker = 0; /* no pending marker */
  171527. marker->pub.saw_SOI = FALSE; /* set internal state too */
  171528. marker->pub.saw_SOF = FALSE;
  171529. marker->pub.discarded_bytes = 0;
  171530. marker->cur_marker = NULL;
  171531. }
  171532. /*
  171533. * Initialize the marker reader module.
  171534. * This is called only once, when the decompression object is created.
  171535. */
  171536. GLOBAL(void)
  171537. jinit_marker_reader (j_decompress_ptr cinfo)
  171538. {
  171539. my_marker_ptr2 marker;
  171540. int i;
  171541. /* Create subobject in permanent pool */
  171542. marker = (my_marker_ptr2)
  171543. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  171544. SIZEOF(my_marker_reader));
  171545. cinfo->marker = (struct jpeg_marker_reader *) marker;
  171546. /* Initialize public method pointers */
  171547. marker->pub.reset_marker_reader = reset_marker_reader;
  171548. marker->pub.read_markers = read_markers;
  171549. marker->pub.read_restart_marker = read_restart_marker;
  171550. /* Initialize COM/APPn processing.
  171551. * By default, we examine and then discard APP0 and APP14,
  171552. * but simply discard COM and all other APPn.
  171553. */
  171554. marker->process_COM = skip_variable;
  171555. marker->length_limit_COM = 0;
  171556. for (i = 0; i < 16; i++) {
  171557. marker->process_APPn[i] = skip_variable;
  171558. marker->length_limit_APPn[i] = 0;
  171559. }
  171560. marker->process_APPn[0] = get_interesting_appn;
  171561. marker->process_APPn[14] = get_interesting_appn;
  171562. /* Reset marker processing state */
  171563. reset_marker_reader(cinfo);
  171564. }
  171565. /*
  171566. * Control saving of COM and APPn markers into marker_list.
  171567. */
  171568. #ifdef SAVE_MARKERS_SUPPORTED
  171569. GLOBAL(void)
  171570. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  171571. unsigned int length_limit)
  171572. {
  171573. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171574. long maxlength;
  171575. jpeg_marker_parser_method processor;
  171576. /* Length limit mustn't be larger than what we can allocate
  171577. * (should only be a concern in a 16-bit environment).
  171578. */
  171579. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  171580. if (((long) length_limit) > maxlength)
  171581. length_limit = (unsigned int) maxlength;
  171582. /* Choose processor routine to use.
  171583. * APP0/APP14 have special requirements.
  171584. */
  171585. if (length_limit) {
  171586. processor = save_marker;
  171587. /* If saving APP0/APP14, save at least enough for our internal use. */
  171588. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  171589. length_limit = APP0_DATA_LEN;
  171590. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  171591. length_limit = APP14_DATA_LEN;
  171592. } else {
  171593. processor = skip_variable;
  171594. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  171595. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  171596. processor = get_interesting_appn;
  171597. }
  171598. if (marker_code == (int) M_COM) {
  171599. marker->process_COM = processor;
  171600. marker->length_limit_COM = length_limit;
  171601. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  171602. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  171603. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  171604. } else
  171605. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171606. }
  171607. #endif /* SAVE_MARKERS_SUPPORTED */
  171608. /*
  171609. * Install a special processing method for COM or APPn markers.
  171610. */
  171611. GLOBAL(void)
  171612. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  171613. jpeg_marker_parser_method routine)
  171614. {
  171615. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171616. if (marker_code == (int) M_COM)
  171617. marker->process_COM = routine;
  171618. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  171619. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  171620. else
  171621. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171622. }
  171623. /*** End of inlined file: jdmarker.c ***/
  171624. /*** Start of inlined file: jdmaster.c ***/
  171625. #define JPEG_INTERNALS
  171626. /* Private state */
  171627. typedef struct {
  171628. struct jpeg_decomp_master pub; /* public fields */
  171629. int pass_number; /* # of passes completed */
  171630. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  171631. /* Saved references to initialized quantizer modules,
  171632. * in case we need to switch modes.
  171633. */
  171634. struct jpeg_color_quantizer * quantizer_1pass;
  171635. struct jpeg_color_quantizer * quantizer_2pass;
  171636. } my_decomp_master;
  171637. typedef my_decomp_master * my_master_ptr6;
  171638. /*
  171639. * Determine whether merged upsample/color conversion should be used.
  171640. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  171641. */
  171642. LOCAL(boolean)
  171643. use_merged_upsample (j_decompress_ptr cinfo)
  171644. {
  171645. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171646. /* Merging is the equivalent of plain box-filter upsampling */
  171647. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  171648. return FALSE;
  171649. /* jdmerge.c only supports YCC=>RGB color conversion */
  171650. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  171651. cinfo->out_color_space != JCS_RGB ||
  171652. cinfo->out_color_components != RGB_PIXELSIZE)
  171653. return FALSE;
  171654. /* and it only handles 2h1v or 2h2v sampling ratios */
  171655. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  171656. cinfo->comp_info[1].h_samp_factor != 1 ||
  171657. cinfo->comp_info[2].h_samp_factor != 1 ||
  171658. cinfo->comp_info[0].v_samp_factor > 2 ||
  171659. cinfo->comp_info[1].v_samp_factor != 1 ||
  171660. cinfo->comp_info[2].v_samp_factor != 1)
  171661. return FALSE;
  171662. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  171663. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171664. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171665. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  171666. return FALSE;
  171667. /* ??? also need to test for upsample-time rescaling, when & if supported */
  171668. return TRUE; /* by golly, it'll work... */
  171669. #else
  171670. return FALSE;
  171671. #endif
  171672. }
  171673. /*
  171674. * Compute output image dimensions and related values.
  171675. * NOTE: this is exported for possible use by application.
  171676. * Hence it mustn't do anything that can't be done twice.
  171677. * Also note that it may be called before the master module is initialized!
  171678. */
  171679. GLOBAL(void)
  171680. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  171681. /* Do computations that are needed before master selection phase */
  171682. {
  171683. #ifdef IDCT_SCALING_SUPPORTED
  171684. int ci;
  171685. jpeg_component_info *compptr;
  171686. #endif
  171687. /* Prevent application from calling me at wrong times */
  171688. if (cinfo->global_state != DSTATE_READY)
  171689. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  171690. #ifdef IDCT_SCALING_SUPPORTED
  171691. /* Compute actual output image dimensions and DCT scaling choices. */
  171692. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  171693. /* Provide 1/8 scaling */
  171694. cinfo->output_width = (JDIMENSION)
  171695. jdiv_round_up((long) cinfo->image_width, 8L);
  171696. cinfo->output_height = (JDIMENSION)
  171697. jdiv_round_up((long) cinfo->image_height, 8L);
  171698. cinfo->min_DCT_scaled_size = 1;
  171699. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  171700. /* Provide 1/4 scaling */
  171701. cinfo->output_width = (JDIMENSION)
  171702. jdiv_round_up((long) cinfo->image_width, 4L);
  171703. cinfo->output_height = (JDIMENSION)
  171704. jdiv_round_up((long) cinfo->image_height, 4L);
  171705. cinfo->min_DCT_scaled_size = 2;
  171706. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  171707. /* Provide 1/2 scaling */
  171708. cinfo->output_width = (JDIMENSION)
  171709. jdiv_round_up((long) cinfo->image_width, 2L);
  171710. cinfo->output_height = (JDIMENSION)
  171711. jdiv_round_up((long) cinfo->image_height, 2L);
  171712. cinfo->min_DCT_scaled_size = 4;
  171713. } else {
  171714. /* Provide 1/1 scaling */
  171715. cinfo->output_width = cinfo->image_width;
  171716. cinfo->output_height = cinfo->image_height;
  171717. cinfo->min_DCT_scaled_size = DCTSIZE;
  171718. }
  171719. /* In selecting the actual DCT scaling for each component, we try to
  171720. * scale up the chroma components via IDCT scaling rather than upsampling.
  171721. * This saves time if the upsampler gets to use 1:1 scaling.
  171722. * Note this code assumes that the supported DCT scalings are powers of 2.
  171723. */
  171724. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171725. ci++, compptr++) {
  171726. int ssize = cinfo->min_DCT_scaled_size;
  171727. while (ssize < DCTSIZE &&
  171728. (compptr->h_samp_factor * ssize * 2 <=
  171729. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  171730. (compptr->v_samp_factor * ssize * 2 <=
  171731. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  171732. ssize = ssize * 2;
  171733. }
  171734. compptr->DCT_scaled_size = ssize;
  171735. }
  171736. /* Recompute downsampled dimensions of components;
  171737. * application needs to know these if using raw downsampled data.
  171738. */
  171739. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171740. ci++, compptr++) {
  171741. /* Size in samples, after IDCT scaling */
  171742. compptr->downsampled_width = (JDIMENSION)
  171743. jdiv_round_up((long) cinfo->image_width *
  171744. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  171745. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  171746. compptr->downsampled_height = (JDIMENSION)
  171747. jdiv_round_up((long) cinfo->image_height *
  171748. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  171749. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  171750. }
  171751. #else /* !IDCT_SCALING_SUPPORTED */
  171752. /* Hardwire it to "no scaling" */
  171753. cinfo->output_width = cinfo->image_width;
  171754. cinfo->output_height = cinfo->image_height;
  171755. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  171756. * and has computed unscaled downsampled_width and downsampled_height.
  171757. */
  171758. #endif /* IDCT_SCALING_SUPPORTED */
  171759. /* Report number of components in selected colorspace. */
  171760. /* Probably this should be in the color conversion module... */
  171761. switch (cinfo->out_color_space) {
  171762. case JCS_GRAYSCALE:
  171763. cinfo->out_color_components = 1;
  171764. break;
  171765. case JCS_RGB:
  171766. #if RGB_PIXELSIZE != 3
  171767. cinfo->out_color_components = RGB_PIXELSIZE;
  171768. break;
  171769. #endif /* else share code with YCbCr */
  171770. case JCS_YCbCr:
  171771. cinfo->out_color_components = 3;
  171772. break;
  171773. case JCS_CMYK:
  171774. case JCS_YCCK:
  171775. cinfo->out_color_components = 4;
  171776. break;
  171777. default: /* else must be same colorspace as in file */
  171778. cinfo->out_color_components = cinfo->num_components;
  171779. break;
  171780. }
  171781. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  171782. cinfo->out_color_components);
  171783. /* See if upsampler will want to emit more than one row at a time */
  171784. if (use_merged_upsample(cinfo))
  171785. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  171786. else
  171787. cinfo->rec_outbuf_height = 1;
  171788. }
  171789. /*
  171790. * Several decompression processes need to range-limit values to the range
  171791. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  171792. * due to noise introduced by quantization, roundoff error, etc. These
  171793. * processes are inner loops and need to be as fast as possible. On most
  171794. * machines, particularly CPUs with pipelines or instruction prefetch,
  171795. * a (subscript-check-less) C table lookup
  171796. * x = sample_range_limit[x];
  171797. * is faster than explicit tests
  171798. * if (x < 0) x = 0;
  171799. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  171800. * These processes all use a common table prepared by the routine below.
  171801. *
  171802. * For most steps we can mathematically guarantee that the initial value
  171803. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  171804. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  171805. * limiting step (just after the IDCT), a wildly out-of-range value is
  171806. * possible if the input data is corrupt. To avoid any chance of indexing
  171807. * off the end of memory and getting a bad-pointer trap, we perform the
  171808. * post-IDCT limiting thus:
  171809. * x = range_limit[x & MASK];
  171810. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  171811. * samples. Under normal circumstances this is more than enough range and
  171812. * a correct output will be generated; with bogus input data the mask will
  171813. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  171814. * For the post-IDCT step, we want to convert the data from signed to unsigned
  171815. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  171816. * So the post-IDCT limiting table ends up looking like this:
  171817. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  171818. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  171819. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  171820. * 0,1,...,CENTERJSAMPLE-1
  171821. * Negative inputs select values from the upper half of the table after
  171822. * masking.
  171823. *
  171824. * We can save some space by overlapping the start of the post-IDCT table
  171825. * with the simpler range limiting table. The post-IDCT table begins at
  171826. * sample_range_limit + CENTERJSAMPLE.
  171827. *
  171828. * Note that the table is allocated in near data space on PCs; it's small
  171829. * enough and used often enough to justify this.
  171830. */
  171831. LOCAL(void)
  171832. prepare_range_limit_table (j_decompress_ptr cinfo)
  171833. /* Allocate and fill in the sample_range_limit table */
  171834. {
  171835. JSAMPLE * table;
  171836. int i;
  171837. table = (JSAMPLE *)
  171838. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171839. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  171840. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  171841. cinfo->sample_range_limit = table;
  171842. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  171843. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  171844. /* Main part of "simple" table: limit[x] = x */
  171845. for (i = 0; i <= MAXJSAMPLE; i++)
  171846. table[i] = (JSAMPLE) i;
  171847. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  171848. /* End of simple table, rest of first half of post-IDCT table */
  171849. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  171850. table[i] = MAXJSAMPLE;
  171851. /* Second half of post-IDCT table */
  171852. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  171853. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  171854. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  171855. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  171856. }
  171857. /*
  171858. * Master selection of decompression modules.
  171859. * This is done once at jpeg_start_decompress time. We determine
  171860. * which modules will be used and give them appropriate initialization calls.
  171861. * We also initialize the decompressor input side to begin consuming data.
  171862. *
  171863. * Since jpeg_read_header has finished, we know what is in the SOF
  171864. * and (first) SOS markers. We also have all the application parameter
  171865. * settings.
  171866. */
  171867. LOCAL(void)
  171868. master_selection (j_decompress_ptr cinfo)
  171869. {
  171870. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171871. boolean use_c_buffer;
  171872. long samplesperrow;
  171873. JDIMENSION jd_samplesperrow;
  171874. /* Initialize dimensions and other stuff */
  171875. jpeg_calc_output_dimensions(cinfo);
  171876. prepare_range_limit_table(cinfo);
  171877. /* Width of an output scanline must be representable as JDIMENSION. */
  171878. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  171879. jd_samplesperrow = (JDIMENSION) samplesperrow;
  171880. if ((long) jd_samplesperrow != samplesperrow)
  171881. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  171882. /* Initialize my private state */
  171883. master->pass_number = 0;
  171884. master->using_merged_upsample = use_merged_upsample(cinfo);
  171885. /* Color quantizer selection */
  171886. master->quantizer_1pass = NULL;
  171887. master->quantizer_2pass = NULL;
  171888. /* No mode changes if not using buffered-image mode. */
  171889. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  171890. cinfo->enable_1pass_quant = FALSE;
  171891. cinfo->enable_external_quant = FALSE;
  171892. cinfo->enable_2pass_quant = FALSE;
  171893. }
  171894. if (cinfo->quantize_colors) {
  171895. if (cinfo->raw_data_out)
  171896. ERREXIT(cinfo, JERR_NOTIMPL);
  171897. /* 2-pass quantizer only works in 3-component color space. */
  171898. if (cinfo->out_color_components != 3) {
  171899. cinfo->enable_1pass_quant = TRUE;
  171900. cinfo->enable_external_quant = FALSE;
  171901. cinfo->enable_2pass_quant = FALSE;
  171902. cinfo->colormap = NULL;
  171903. } else if (cinfo->colormap != NULL) {
  171904. cinfo->enable_external_quant = TRUE;
  171905. } else if (cinfo->two_pass_quantize) {
  171906. cinfo->enable_2pass_quant = TRUE;
  171907. } else {
  171908. cinfo->enable_1pass_quant = TRUE;
  171909. }
  171910. if (cinfo->enable_1pass_quant) {
  171911. #ifdef QUANT_1PASS_SUPPORTED
  171912. jinit_1pass_quantizer(cinfo);
  171913. master->quantizer_1pass = cinfo->cquantize;
  171914. #else
  171915. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171916. #endif
  171917. }
  171918. /* We use the 2-pass code to map to external colormaps. */
  171919. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  171920. #ifdef QUANT_2PASS_SUPPORTED
  171921. jinit_2pass_quantizer(cinfo);
  171922. master->quantizer_2pass = cinfo->cquantize;
  171923. #else
  171924. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171925. #endif
  171926. }
  171927. /* If both quantizers are initialized, the 2-pass one is left active;
  171928. * this is necessary for starting with quantization to an external map.
  171929. */
  171930. }
  171931. /* Post-processing: in particular, color conversion first */
  171932. if (! cinfo->raw_data_out) {
  171933. if (master->using_merged_upsample) {
  171934. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171935. jinit_merged_upsampler(cinfo); /* does color conversion too */
  171936. #else
  171937. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171938. #endif
  171939. } else {
  171940. jinit_color_deconverter(cinfo);
  171941. jinit_upsampler(cinfo);
  171942. }
  171943. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  171944. }
  171945. /* Inverse DCT */
  171946. jinit_inverse_dct(cinfo);
  171947. /* Entropy decoding: either Huffman or arithmetic coding. */
  171948. if (cinfo->arith_code) {
  171949. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  171950. } else {
  171951. if (cinfo->progressive_mode) {
  171952. #ifdef D_PROGRESSIVE_SUPPORTED
  171953. jinit_phuff_decoder(cinfo);
  171954. #else
  171955. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171956. #endif
  171957. } else
  171958. jinit_huff_decoder(cinfo);
  171959. }
  171960. /* Initialize principal buffer controllers. */
  171961. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  171962. jinit_d_coef_controller(cinfo, use_c_buffer);
  171963. if (! cinfo->raw_data_out)
  171964. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  171965. /* We can now tell the memory manager to allocate virtual arrays. */
  171966. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  171967. /* Initialize input side of decompressor to consume first scan. */
  171968. (*cinfo->inputctl->start_input_pass) (cinfo);
  171969. #ifdef D_MULTISCAN_FILES_SUPPORTED
  171970. /* If jpeg_start_decompress will read the whole file, initialize
  171971. * progress monitoring appropriately. The input step is counted
  171972. * as one pass.
  171973. */
  171974. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  171975. cinfo->inputctl->has_multiple_scans) {
  171976. int nscans;
  171977. /* Estimate number of scans to set pass_limit. */
  171978. if (cinfo->progressive_mode) {
  171979. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  171980. nscans = 2 + 3 * cinfo->num_components;
  171981. } else {
  171982. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  171983. nscans = cinfo->num_components;
  171984. }
  171985. cinfo->progress->pass_counter = 0L;
  171986. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  171987. cinfo->progress->completed_passes = 0;
  171988. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  171989. /* Count the input pass as done */
  171990. master->pass_number++;
  171991. }
  171992. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  171993. }
  171994. /*
  171995. * Per-pass setup.
  171996. * This is called at the beginning of each output pass. We determine which
  171997. * modules will be active during this pass and give them appropriate
  171998. * start_pass calls. We also set is_dummy_pass to indicate whether this
  171999. * is a "real" output pass or a dummy pass for color quantization.
  172000. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172001. */
  172002. METHODDEF(void)
  172003. prepare_for_output_pass (j_decompress_ptr cinfo)
  172004. {
  172005. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172006. if (master->pub.is_dummy_pass) {
  172007. #ifdef QUANT_2PASS_SUPPORTED
  172008. /* Final pass of 2-pass quantization */
  172009. master->pub.is_dummy_pass = FALSE;
  172010. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172011. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172012. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172013. #else
  172014. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172015. #endif /* QUANT_2PASS_SUPPORTED */
  172016. } else {
  172017. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172018. /* Select new quantization method */
  172019. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172020. cinfo->cquantize = master->quantizer_2pass;
  172021. master->pub.is_dummy_pass = TRUE;
  172022. } else if (cinfo->enable_1pass_quant) {
  172023. cinfo->cquantize = master->quantizer_1pass;
  172024. } else {
  172025. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172026. }
  172027. }
  172028. (*cinfo->idct->start_pass) (cinfo);
  172029. (*cinfo->coef->start_output_pass) (cinfo);
  172030. if (! cinfo->raw_data_out) {
  172031. if (! master->using_merged_upsample)
  172032. (*cinfo->cconvert->start_pass) (cinfo);
  172033. (*cinfo->upsample->start_pass) (cinfo);
  172034. if (cinfo->quantize_colors)
  172035. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172036. (*cinfo->post->start_pass) (cinfo,
  172037. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172038. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172039. }
  172040. }
  172041. /* Set up progress monitor's pass info if present */
  172042. if (cinfo->progress != NULL) {
  172043. cinfo->progress->completed_passes = master->pass_number;
  172044. cinfo->progress->total_passes = master->pass_number +
  172045. (master->pub.is_dummy_pass ? 2 : 1);
  172046. /* In buffered-image mode, we assume one more output pass if EOI not
  172047. * yet reached, but no more passes if EOI has been reached.
  172048. */
  172049. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172050. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172051. }
  172052. }
  172053. }
  172054. /*
  172055. * Finish up at end of an output pass.
  172056. */
  172057. METHODDEF(void)
  172058. finish_output_pass (j_decompress_ptr cinfo)
  172059. {
  172060. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172061. if (cinfo->quantize_colors)
  172062. (*cinfo->cquantize->finish_pass) (cinfo);
  172063. master->pass_number++;
  172064. }
  172065. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172066. /*
  172067. * Switch to a new external colormap between output passes.
  172068. */
  172069. GLOBAL(void)
  172070. jpeg_new_colormap (j_decompress_ptr cinfo)
  172071. {
  172072. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172073. /* Prevent application from calling me at wrong times */
  172074. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172075. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172076. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172077. cinfo->colormap != NULL) {
  172078. /* Select 2-pass quantizer for external colormap use */
  172079. cinfo->cquantize = master->quantizer_2pass;
  172080. /* Notify quantizer of colormap change */
  172081. (*cinfo->cquantize->new_color_map) (cinfo);
  172082. master->pub.is_dummy_pass = FALSE; /* just in case */
  172083. } else
  172084. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172085. }
  172086. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172087. /*
  172088. * Initialize master decompression control and select active modules.
  172089. * This is performed at the start of jpeg_start_decompress.
  172090. */
  172091. GLOBAL(void)
  172092. jinit_master_decompress (j_decompress_ptr cinfo)
  172093. {
  172094. my_master_ptr6 master;
  172095. master = (my_master_ptr6)
  172096. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172097. SIZEOF(my_decomp_master));
  172098. cinfo->master = (struct jpeg_decomp_master *) master;
  172099. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172100. master->pub.finish_output_pass = finish_output_pass;
  172101. master->pub.is_dummy_pass = FALSE;
  172102. master_selection(cinfo);
  172103. }
  172104. /*** End of inlined file: jdmaster.c ***/
  172105. #undef FIX
  172106. /*** Start of inlined file: jdmerge.c ***/
  172107. #define JPEG_INTERNALS
  172108. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172109. /* Private subobject */
  172110. typedef struct {
  172111. struct jpeg_upsampler pub; /* public fields */
  172112. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172113. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172114. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172115. JSAMPARRAY output_buf));
  172116. /* Private state for YCC->RGB conversion */
  172117. int * Cr_r_tab; /* => table for Cr to R conversion */
  172118. int * Cb_b_tab; /* => table for Cb to B conversion */
  172119. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172120. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172121. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172122. * We need a "spare" row buffer to hold the second output row if the
  172123. * application provides just a one-row buffer; we also use the spare
  172124. * to discard the dummy last row if the image height is odd.
  172125. */
  172126. JSAMPROW spare_row;
  172127. boolean spare_full; /* T if spare buffer is occupied */
  172128. JDIMENSION out_row_width; /* samples per output row */
  172129. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172130. } my_upsampler;
  172131. typedef my_upsampler * my_upsample_ptr;
  172132. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172133. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172134. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172135. /*
  172136. * Initialize tables for YCC->RGB colorspace conversion.
  172137. * This is taken directly from jdcolor.c; see that file for more info.
  172138. */
  172139. LOCAL(void)
  172140. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172141. {
  172142. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172143. int i;
  172144. INT32 x;
  172145. SHIFT_TEMPS
  172146. upsample->Cr_r_tab = (int *)
  172147. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172148. (MAXJSAMPLE+1) * SIZEOF(int));
  172149. upsample->Cb_b_tab = (int *)
  172150. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172151. (MAXJSAMPLE+1) * SIZEOF(int));
  172152. upsample->Cr_g_tab = (INT32 *)
  172153. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172154. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172155. upsample->Cb_g_tab = (INT32 *)
  172156. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172157. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172158. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172159. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172160. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172161. /* Cr=>R value is nearest int to 1.40200 * x */
  172162. upsample->Cr_r_tab[i] = (int)
  172163. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172164. /* Cb=>B value is nearest int to 1.77200 * x */
  172165. upsample->Cb_b_tab[i] = (int)
  172166. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172167. /* Cr=>G value is scaled-up -0.71414 * x */
  172168. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172169. /* Cb=>G value is scaled-up -0.34414 * x */
  172170. /* We also add in ONE_HALF so that need not do it in inner loop */
  172171. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172172. }
  172173. }
  172174. /*
  172175. * Initialize for an upsampling pass.
  172176. */
  172177. METHODDEF(void)
  172178. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172179. {
  172180. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172181. /* Mark the spare buffer empty */
  172182. upsample->spare_full = FALSE;
  172183. /* Initialize total-height counter for detecting bottom of image */
  172184. upsample->rows_to_go = cinfo->output_height;
  172185. }
  172186. /*
  172187. * Control routine to do upsampling (and color conversion).
  172188. *
  172189. * The control routine just handles the row buffering considerations.
  172190. */
  172191. METHODDEF(void)
  172192. merged_2v_upsample (j_decompress_ptr cinfo,
  172193. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172194. JDIMENSION,
  172195. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172196. JDIMENSION out_rows_avail)
  172197. /* 2:1 vertical sampling case: may need a spare row. */
  172198. {
  172199. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172200. JSAMPROW work_ptrs[2];
  172201. JDIMENSION num_rows; /* number of rows returned to caller */
  172202. if (upsample->spare_full) {
  172203. /* If we have a spare row saved from a previous cycle, just return it. */
  172204. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172205. 1, upsample->out_row_width);
  172206. num_rows = 1;
  172207. upsample->spare_full = FALSE;
  172208. } else {
  172209. /* Figure number of rows to return to caller. */
  172210. num_rows = 2;
  172211. /* Not more than the distance to the end of the image. */
  172212. if (num_rows > upsample->rows_to_go)
  172213. num_rows = upsample->rows_to_go;
  172214. /* And not more than what the client can accept: */
  172215. out_rows_avail -= *out_row_ctr;
  172216. if (num_rows > out_rows_avail)
  172217. num_rows = out_rows_avail;
  172218. /* Create output pointer array for upsampler. */
  172219. work_ptrs[0] = output_buf[*out_row_ctr];
  172220. if (num_rows > 1) {
  172221. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172222. } else {
  172223. work_ptrs[1] = upsample->spare_row;
  172224. upsample->spare_full = TRUE;
  172225. }
  172226. /* Now do the upsampling. */
  172227. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172228. }
  172229. /* Adjust counts */
  172230. *out_row_ctr += num_rows;
  172231. upsample->rows_to_go -= num_rows;
  172232. /* When the buffer is emptied, declare this input row group consumed */
  172233. if (! upsample->spare_full)
  172234. (*in_row_group_ctr)++;
  172235. }
  172236. METHODDEF(void)
  172237. merged_1v_upsample (j_decompress_ptr cinfo,
  172238. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172239. JDIMENSION,
  172240. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172241. JDIMENSION)
  172242. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172243. {
  172244. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172245. /* Just do the upsampling. */
  172246. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172247. output_buf + *out_row_ctr);
  172248. /* Adjust counts */
  172249. (*out_row_ctr)++;
  172250. (*in_row_group_ctr)++;
  172251. }
  172252. /*
  172253. * These are the routines invoked by the control routines to do
  172254. * the actual upsampling/conversion. One row group is processed per call.
  172255. *
  172256. * Note: since we may be writing directly into application-supplied buffers,
  172257. * we have to be honest about the output width; we can't assume the buffer
  172258. * has been rounded up to an even width.
  172259. */
  172260. /*
  172261. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172262. */
  172263. METHODDEF(void)
  172264. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172265. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172266. JSAMPARRAY output_buf)
  172267. {
  172268. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172269. register int y, cred, cgreen, cblue;
  172270. int cb, cr;
  172271. register JSAMPROW outptr;
  172272. JSAMPROW inptr0, inptr1, inptr2;
  172273. JDIMENSION col;
  172274. /* copy these pointers into registers if possible */
  172275. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172276. int * Crrtab = upsample->Cr_r_tab;
  172277. int * Cbbtab = upsample->Cb_b_tab;
  172278. INT32 * Crgtab = upsample->Cr_g_tab;
  172279. INT32 * Cbgtab = upsample->Cb_g_tab;
  172280. SHIFT_TEMPS
  172281. inptr0 = input_buf[0][in_row_group_ctr];
  172282. inptr1 = input_buf[1][in_row_group_ctr];
  172283. inptr2 = input_buf[2][in_row_group_ctr];
  172284. outptr = output_buf[0];
  172285. /* Loop for each pair of output pixels */
  172286. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172287. /* Do the chroma part of the calculation */
  172288. cb = GETJSAMPLE(*inptr1++);
  172289. cr = GETJSAMPLE(*inptr2++);
  172290. cred = Crrtab[cr];
  172291. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172292. cblue = Cbbtab[cb];
  172293. /* Fetch 2 Y values and emit 2 pixels */
  172294. y = GETJSAMPLE(*inptr0++);
  172295. outptr[RGB_RED] = range_limit[y + cred];
  172296. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172297. outptr[RGB_BLUE] = range_limit[y + cblue];
  172298. outptr += RGB_PIXELSIZE;
  172299. y = GETJSAMPLE(*inptr0++);
  172300. outptr[RGB_RED] = range_limit[y + cred];
  172301. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172302. outptr[RGB_BLUE] = range_limit[y + cblue];
  172303. outptr += RGB_PIXELSIZE;
  172304. }
  172305. /* If image width is odd, do the last output column separately */
  172306. if (cinfo->output_width & 1) {
  172307. cb = GETJSAMPLE(*inptr1);
  172308. cr = GETJSAMPLE(*inptr2);
  172309. cred = Crrtab[cr];
  172310. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172311. cblue = Cbbtab[cb];
  172312. y = GETJSAMPLE(*inptr0);
  172313. outptr[RGB_RED] = range_limit[y + cred];
  172314. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172315. outptr[RGB_BLUE] = range_limit[y + cblue];
  172316. }
  172317. }
  172318. /*
  172319. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172320. */
  172321. METHODDEF(void)
  172322. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172323. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172324. JSAMPARRAY output_buf)
  172325. {
  172326. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172327. register int y, cred, cgreen, cblue;
  172328. int cb, cr;
  172329. register JSAMPROW outptr0, outptr1;
  172330. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172331. JDIMENSION col;
  172332. /* copy these pointers into registers if possible */
  172333. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172334. int * Crrtab = upsample->Cr_r_tab;
  172335. int * Cbbtab = upsample->Cb_b_tab;
  172336. INT32 * Crgtab = upsample->Cr_g_tab;
  172337. INT32 * Cbgtab = upsample->Cb_g_tab;
  172338. SHIFT_TEMPS
  172339. inptr00 = input_buf[0][in_row_group_ctr*2];
  172340. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172341. inptr1 = input_buf[1][in_row_group_ctr];
  172342. inptr2 = input_buf[2][in_row_group_ctr];
  172343. outptr0 = output_buf[0];
  172344. outptr1 = output_buf[1];
  172345. /* Loop for each group of output pixels */
  172346. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172347. /* Do the chroma part of the calculation */
  172348. cb = GETJSAMPLE(*inptr1++);
  172349. cr = GETJSAMPLE(*inptr2++);
  172350. cred = Crrtab[cr];
  172351. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172352. cblue = Cbbtab[cb];
  172353. /* Fetch 4 Y values and emit 4 pixels */
  172354. y = GETJSAMPLE(*inptr00++);
  172355. outptr0[RGB_RED] = range_limit[y + cred];
  172356. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172357. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172358. outptr0 += RGB_PIXELSIZE;
  172359. y = GETJSAMPLE(*inptr00++);
  172360. outptr0[RGB_RED] = range_limit[y + cred];
  172361. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172362. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172363. outptr0 += RGB_PIXELSIZE;
  172364. y = GETJSAMPLE(*inptr01++);
  172365. outptr1[RGB_RED] = range_limit[y + cred];
  172366. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172367. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172368. outptr1 += RGB_PIXELSIZE;
  172369. y = GETJSAMPLE(*inptr01++);
  172370. outptr1[RGB_RED] = range_limit[y + cred];
  172371. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172372. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172373. outptr1 += RGB_PIXELSIZE;
  172374. }
  172375. /* If image width is odd, do the last output column separately */
  172376. if (cinfo->output_width & 1) {
  172377. cb = GETJSAMPLE(*inptr1);
  172378. cr = GETJSAMPLE(*inptr2);
  172379. cred = Crrtab[cr];
  172380. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172381. cblue = Cbbtab[cb];
  172382. y = GETJSAMPLE(*inptr00);
  172383. outptr0[RGB_RED] = range_limit[y + cred];
  172384. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172385. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172386. y = GETJSAMPLE(*inptr01);
  172387. outptr1[RGB_RED] = range_limit[y + cred];
  172388. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172389. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172390. }
  172391. }
  172392. /*
  172393. * Module initialization routine for merged upsampling/color conversion.
  172394. *
  172395. * NB: this is called under the conditions determined by use_merged_upsample()
  172396. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  172397. * of this module; no safety checks are made here.
  172398. */
  172399. GLOBAL(void)
  172400. jinit_merged_upsampler (j_decompress_ptr cinfo)
  172401. {
  172402. my_upsample_ptr upsample;
  172403. upsample = (my_upsample_ptr)
  172404. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172405. SIZEOF(my_upsampler));
  172406. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  172407. upsample->pub.start_pass = start_pass_merged_upsample;
  172408. upsample->pub.need_context_rows = FALSE;
  172409. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  172410. if (cinfo->max_v_samp_factor == 2) {
  172411. upsample->pub.upsample = merged_2v_upsample;
  172412. upsample->upmethod = h2v2_merged_upsample;
  172413. /* Allocate a spare row buffer */
  172414. upsample->spare_row = (JSAMPROW)
  172415. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172416. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  172417. } else {
  172418. upsample->pub.upsample = merged_1v_upsample;
  172419. upsample->upmethod = h2v1_merged_upsample;
  172420. /* No spare row needed */
  172421. upsample->spare_row = NULL;
  172422. }
  172423. build_ycc_rgb_table2(cinfo);
  172424. }
  172425. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  172426. /*** End of inlined file: jdmerge.c ***/
  172427. #undef ASSIGN_STATE
  172428. /*** Start of inlined file: jdphuff.c ***/
  172429. #define JPEG_INTERNALS
  172430. #ifdef D_PROGRESSIVE_SUPPORTED
  172431. /*
  172432. * Expanded entropy decoder object for progressive Huffman decoding.
  172433. *
  172434. * The savable_state subrecord contains fields that change within an MCU,
  172435. * but must not be updated permanently until we complete the MCU.
  172436. */
  172437. typedef struct {
  172438. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  172439. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  172440. } savable_state3;
  172441. /* This macro is to work around compilers with missing or broken
  172442. * structure assignment. You'll need to fix this code if you have
  172443. * such a compiler and you change MAX_COMPS_IN_SCAN.
  172444. */
  172445. #ifndef NO_STRUCT_ASSIGN
  172446. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  172447. #else
  172448. #if MAX_COMPS_IN_SCAN == 4
  172449. #define ASSIGN_STATE(dest,src) \
  172450. ((dest).EOBRUN = (src).EOBRUN, \
  172451. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  172452. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  172453. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  172454. (dest).last_dc_val[3] = (src).last_dc_val[3])
  172455. #endif
  172456. #endif
  172457. typedef struct {
  172458. struct jpeg_entropy_decoder pub; /* public fields */
  172459. /* These fields are loaded into local variables at start of each MCU.
  172460. * In case of suspension, we exit WITHOUT updating them.
  172461. */
  172462. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  172463. savable_state3 saved; /* Other state at start of MCU */
  172464. /* These fields are NOT loaded into local working state. */
  172465. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  172466. /* Pointers to derived tables (these workspaces have image lifespan) */
  172467. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  172468. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  172469. } phuff_entropy_decoder;
  172470. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  172471. /* Forward declarations */
  172472. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  172473. JBLOCKROW *MCU_data));
  172474. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  172475. JBLOCKROW *MCU_data));
  172476. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  172477. JBLOCKROW *MCU_data));
  172478. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  172479. JBLOCKROW *MCU_data));
  172480. /*
  172481. * Initialize for a Huffman-compressed scan.
  172482. */
  172483. METHODDEF(void)
  172484. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  172485. {
  172486. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172487. boolean is_DC_band, bad;
  172488. int ci, coefi, tbl;
  172489. int *coef_bit_ptr;
  172490. jpeg_component_info * compptr;
  172491. is_DC_band = (cinfo->Ss == 0);
  172492. /* Validate scan parameters */
  172493. bad = FALSE;
  172494. if (is_DC_band) {
  172495. if (cinfo->Se != 0)
  172496. bad = TRUE;
  172497. } else {
  172498. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  172499. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  172500. bad = TRUE;
  172501. /* AC scans may have only one component */
  172502. if (cinfo->comps_in_scan != 1)
  172503. bad = TRUE;
  172504. }
  172505. if (cinfo->Ah != 0) {
  172506. /* Successive approximation refinement scan: must have Al = Ah-1. */
  172507. if (cinfo->Al != cinfo->Ah-1)
  172508. bad = TRUE;
  172509. }
  172510. if (cinfo->Al > 13) /* need not check for < 0 */
  172511. bad = TRUE;
  172512. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  172513. * but the spec doesn't say so, and we try to be liberal about what we
  172514. * accept. Note: large Al values could result in out-of-range DC
  172515. * coefficients during early scans, leading to bizarre displays due to
  172516. * overflows in the IDCT math. But we won't crash.
  172517. */
  172518. if (bad)
  172519. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  172520. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  172521. /* Update progression status, and verify that scan order is legal.
  172522. * Note that inter-scan inconsistencies are treated as warnings
  172523. * not fatal errors ... not clear if this is right way to behave.
  172524. */
  172525. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172526. int cindex = cinfo->cur_comp_info[ci]->component_index;
  172527. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  172528. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  172529. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  172530. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  172531. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  172532. if (cinfo->Ah != expected)
  172533. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  172534. coef_bit_ptr[coefi] = cinfo->Al;
  172535. }
  172536. }
  172537. /* Select MCU decoding routine */
  172538. if (cinfo->Ah == 0) {
  172539. if (is_DC_band)
  172540. entropy->pub.decode_mcu = decode_mcu_DC_first;
  172541. else
  172542. entropy->pub.decode_mcu = decode_mcu_AC_first;
  172543. } else {
  172544. if (is_DC_band)
  172545. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  172546. else
  172547. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  172548. }
  172549. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172550. compptr = cinfo->cur_comp_info[ci];
  172551. /* Make sure requested tables are present, and compute derived tables.
  172552. * We may build same derived table more than once, but it's not expensive.
  172553. */
  172554. if (is_DC_band) {
  172555. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  172556. tbl = compptr->dc_tbl_no;
  172557. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  172558. & entropy->derived_tbls[tbl]);
  172559. }
  172560. } else {
  172561. tbl = compptr->ac_tbl_no;
  172562. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  172563. & entropy->derived_tbls[tbl]);
  172564. /* remember the single active table */
  172565. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  172566. }
  172567. /* Initialize DC predictions to 0 */
  172568. entropy->saved.last_dc_val[ci] = 0;
  172569. }
  172570. /* Initialize bitread state variables */
  172571. entropy->bitstate.bits_left = 0;
  172572. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  172573. entropy->pub.insufficient_data = FALSE;
  172574. /* Initialize private state variables */
  172575. entropy->saved.EOBRUN = 0;
  172576. /* Initialize restart counter */
  172577. entropy->restarts_to_go = cinfo->restart_interval;
  172578. }
  172579. /*
  172580. * Check for a restart marker & resynchronize decoder.
  172581. * Returns FALSE if must suspend.
  172582. */
  172583. LOCAL(boolean)
  172584. process_restartp (j_decompress_ptr cinfo)
  172585. {
  172586. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172587. int ci;
  172588. /* Throw away any unused bits remaining in bit buffer; */
  172589. /* include any full bytes in next_marker's count of discarded bytes */
  172590. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  172591. entropy->bitstate.bits_left = 0;
  172592. /* Advance past the RSTn marker */
  172593. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  172594. return FALSE;
  172595. /* Re-initialize DC predictions to 0 */
  172596. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  172597. entropy->saved.last_dc_val[ci] = 0;
  172598. /* Re-init EOB run count, too */
  172599. entropy->saved.EOBRUN = 0;
  172600. /* Reset restart counter */
  172601. entropy->restarts_to_go = cinfo->restart_interval;
  172602. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  172603. * against a marker. In that case we will end up treating the next data
  172604. * segment as empty, and we can avoid producing bogus output pixels by
  172605. * leaving the flag set.
  172606. */
  172607. if (cinfo->unread_marker == 0)
  172608. entropy->pub.insufficient_data = FALSE;
  172609. return TRUE;
  172610. }
  172611. /*
  172612. * Huffman MCU decoding.
  172613. * Each of these routines decodes and returns one MCU's worth of
  172614. * Huffman-compressed coefficients.
  172615. * The coefficients are reordered from zigzag order into natural array order,
  172616. * but are not dequantized.
  172617. *
  172618. * The i'th block of the MCU is stored into the block pointed to by
  172619. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  172620. *
  172621. * We return FALSE if data source requested suspension. In that case no
  172622. * changes have been made to permanent state. (Exception: some output
  172623. * coefficients may already have been assigned. This is harmless for
  172624. * spectral selection, since we'll just re-assign them on the next call.
  172625. * Successive approximation AC refinement has to be more careful, however.)
  172626. */
  172627. /*
  172628. * MCU decoding for DC initial scan (either spectral selection,
  172629. * or first pass of successive approximation).
  172630. */
  172631. METHODDEF(boolean)
  172632. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172633. {
  172634. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172635. int Al = cinfo->Al;
  172636. register int s, r;
  172637. int blkn, ci;
  172638. JBLOCKROW block;
  172639. BITREAD_STATE_VARS;
  172640. savable_state3 state;
  172641. d_derived_tbl * tbl;
  172642. jpeg_component_info * compptr;
  172643. /* Process restart marker if needed; may have to suspend */
  172644. if (cinfo->restart_interval) {
  172645. if (entropy->restarts_to_go == 0)
  172646. if (! process_restartp(cinfo))
  172647. return FALSE;
  172648. }
  172649. /* If we've run out of data, just leave the MCU set to zeroes.
  172650. * This way, we return uniform gray for the remainder of the segment.
  172651. */
  172652. if (! entropy->pub.insufficient_data) {
  172653. /* Load up working state */
  172654. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172655. ASSIGN_STATE(state, entropy->saved);
  172656. /* Outer loop handles each block in the MCU */
  172657. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172658. block = MCU_data[blkn];
  172659. ci = cinfo->MCU_membership[blkn];
  172660. compptr = cinfo->cur_comp_info[ci];
  172661. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  172662. /* Decode a single block's worth of coefficients */
  172663. /* Section F.2.2.1: decode the DC coefficient difference */
  172664. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  172665. if (s) {
  172666. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172667. r = GET_BITS(s);
  172668. s = HUFF_EXTEND(r, s);
  172669. }
  172670. /* Convert DC difference to actual value, update last_dc_val */
  172671. s += state.last_dc_val[ci];
  172672. state.last_dc_val[ci] = s;
  172673. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  172674. (*block)[0] = (JCOEF) (s << Al);
  172675. }
  172676. /* Completed MCU, so update state */
  172677. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172678. ASSIGN_STATE(entropy->saved, state);
  172679. }
  172680. /* Account for restart interval (no-op if not using restarts) */
  172681. entropy->restarts_to_go--;
  172682. return TRUE;
  172683. }
  172684. /*
  172685. * MCU decoding for AC initial scan (either spectral selection,
  172686. * or first pass of successive approximation).
  172687. */
  172688. METHODDEF(boolean)
  172689. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172690. {
  172691. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172692. int Se = cinfo->Se;
  172693. int Al = cinfo->Al;
  172694. register int s, k, r;
  172695. unsigned int EOBRUN;
  172696. JBLOCKROW block;
  172697. BITREAD_STATE_VARS;
  172698. d_derived_tbl * tbl;
  172699. /* Process restart marker if needed; may have to suspend */
  172700. if (cinfo->restart_interval) {
  172701. if (entropy->restarts_to_go == 0)
  172702. if (! process_restartp(cinfo))
  172703. return FALSE;
  172704. }
  172705. /* If we've run out of data, just leave the MCU set to zeroes.
  172706. * This way, we return uniform gray for the remainder of the segment.
  172707. */
  172708. if (! entropy->pub.insufficient_data) {
  172709. /* Load up working state.
  172710. * We can avoid loading/saving bitread state if in an EOB run.
  172711. */
  172712. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  172713. /* There is always only one block per MCU */
  172714. if (EOBRUN > 0) /* if it's a band of zeroes... */
  172715. EOBRUN--; /* ...process it now (we do nothing) */
  172716. else {
  172717. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172718. block = MCU_data[0];
  172719. tbl = entropy->ac_derived_tbl;
  172720. for (k = cinfo->Ss; k <= Se; k++) {
  172721. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  172722. r = s >> 4;
  172723. s &= 15;
  172724. if (s) {
  172725. k += r;
  172726. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172727. r = GET_BITS(s);
  172728. s = HUFF_EXTEND(r, s);
  172729. /* Scale and output coefficient in natural (dezigzagged) order */
  172730. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  172731. } else {
  172732. if (r == 15) { /* ZRL */
  172733. k += 15; /* skip 15 zeroes in band */
  172734. } else { /* EOBr, run length is 2^r + appended bits */
  172735. EOBRUN = 1 << r;
  172736. if (r) { /* EOBr, r > 0 */
  172737. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  172738. r = GET_BITS(r);
  172739. EOBRUN += r;
  172740. }
  172741. EOBRUN--; /* this band is processed at this moment */
  172742. break; /* force end-of-band */
  172743. }
  172744. }
  172745. }
  172746. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172747. }
  172748. /* Completed MCU, so update state */
  172749. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  172750. }
  172751. /* Account for restart interval (no-op if not using restarts) */
  172752. entropy->restarts_to_go--;
  172753. return TRUE;
  172754. }
  172755. /*
  172756. * MCU decoding for DC successive approximation refinement scan.
  172757. * Note: we assume such scans can be multi-component, although the spec
  172758. * is not very clear on the point.
  172759. */
  172760. METHODDEF(boolean)
  172761. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172762. {
  172763. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172764. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  172765. int blkn;
  172766. JBLOCKROW block;
  172767. BITREAD_STATE_VARS;
  172768. /* Process restart marker if needed; may have to suspend */
  172769. if (cinfo->restart_interval) {
  172770. if (entropy->restarts_to_go == 0)
  172771. if (! process_restartp(cinfo))
  172772. return FALSE;
  172773. }
  172774. /* Not worth the cycles to check insufficient_data here,
  172775. * since we will not change the data anyway if we read zeroes.
  172776. */
  172777. /* Load up working state */
  172778. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172779. /* Outer loop handles each block in the MCU */
  172780. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172781. block = MCU_data[blkn];
  172782. /* Encoded data is simply the next bit of the two's-complement DC value */
  172783. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  172784. if (GET_BITS(1))
  172785. (*block)[0] |= p1;
  172786. /* Note: since we use |=, repeating the assignment later is safe */
  172787. }
  172788. /* Completed MCU, so update state */
  172789. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172790. /* Account for restart interval (no-op if not using restarts) */
  172791. entropy->restarts_to_go--;
  172792. return TRUE;
  172793. }
  172794. /*
  172795. * MCU decoding for AC successive approximation refinement scan.
  172796. */
  172797. METHODDEF(boolean)
  172798. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172799. {
  172800. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172801. int Se = cinfo->Se;
  172802. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  172803. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  172804. register int s, k, r;
  172805. unsigned int EOBRUN;
  172806. JBLOCKROW block;
  172807. JCOEFPTR thiscoef;
  172808. BITREAD_STATE_VARS;
  172809. d_derived_tbl * tbl;
  172810. int num_newnz;
  172811. int newnz_pos[DCTSIZE2];
  172812. /* Process restart marker if needed; may have to suspend */
  172813. if (cinfo->restart_interval) {
  172814. if (entropy->restarts_to_go == 0)
  172815. if (! process_restartp(cinfo))
  172816. return FALSE;
  172817. }
  172818. /* If we've run out of data, don't modify the MCU.
  172819. */
  172820. if (! entropy->pub.insufficient_data) {
  172821. /* Load up working state */
  172822. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172823. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  172824. /* There is always only one block per MCU */
  172825. block = MCU_data[0];
  172826. tbl = entropy->ac_derived_tbl;
  172827. /* If we are forced to suspend, we must undo the assignments to any newly
  172828. * nonzero coefficients in the block, because otherwise we'd get confused
  172829. * next time about which coefficients were already nonzero.
  172830. * But we need not undo addition of bits to already-nonzero coefficients;
  172831. * instead, we can test the current bit to see if we already did it.
  172832. */
  172833. num_newnz = 0;
  172834. /* initialize coefficient loop counter to start of band */
  172835. k = cinfo->Ss;
  172836. if (EOBRUN == 0) {
  172837. for (; k <= Se; k++) {
  172838. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  172839. r = s >> 4;
  172840. s &= 15;
  172841. if (s) {
  172842. if (s != 1) /* size of new coef should always be 1 */
  172843. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  172844. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172845. if (GET_BITS(1))
  172846. s = p1; /* newly nonzero coef is positive */
  172847. else
  172848. s = m1; /* newly nonzero coef is negative */
  172849. } else {
  172850. if (r != 15) {
  172851. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  172852. if (r) {
  172853. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  172854. r = GET_BITS(r);
  172855. EOBRUN += r;
  172856. }
  172857. break; /* rest of block is handled by EOB logic */
  172858. }
  172859. /* note s = 0 for processing ZRL */
  172860. }
  172861. /* Advance over already-nonzero coefs and r still-zero coefs,
  172862. * appending correction bits to the nonzeroes. A correction bit is 1
  172863. * if the absolute value of the coefficient must be increased.
  172864. */
  172865. do {
  172866. thiscoef = *block + jpeg_natural_order[k];
  172867. if (*thiscoef != 0) {
  172868. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172869. if (GET_BITS(1)) {
  172870. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  172871. if (*thiscoef >= 0)
  172872. *thiscoef += p1;
  172873. else
  172874. *thiscoef += m1;
  172875. }
  172876. }
  172877. } else {
  172878. if (--r < 0)
  172879. break; /* reached target zero coefficient */
  172880. }
  172881. k++;
  172882. } while (k <= Se);
  172883. if (s) {
  172884. int pos = jpeg_natural_order[k];
  172885. /* Output newly nonzero coefficient */
  172886. (*block)[pos] = (JCOEF) s;
  172887. /* Remember its position in case we have to suspend */
  172888. newnz_pos[num_newnz++] = pos;
  172889. }
  172890. }
  172891. }
  172892. if (EOBRUN > 0) {
  172893. /* Scan any remaining coefficient positions after the end-of-band
  172894. * (the last newly nonzero coefficient, if any). Append a correction
  172895. * bit to each already-nonzero coefficient. A correction bit is 1
  172896. * if the absolute value of the coefficient must be increased.
  172897. */
  172898. for (; k <= Se; k++) {
  172899. thiscoef = *block + jpeg_natural_order[k];
  172900. if (*thiscoef != 0) {
  172901. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172902. if (GET_BITS(1)) {
  172903. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  172904. if (*thiscoef >= 0)
  172905. *thiscoef += p1;
  172906. else
  172907. *thiscoef += m1;
  172908. }
  172909. }
  172910. }
  172911. }
  172912. /* Count one block completed in EOB run */
  172913. EOBRUN--;
  172914. }
  172915. /* Completed MCU, so update state */
  172916. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172917. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  172918. }
  172919. /* Account for restart interval (no-op if not using restarts) */
  172920. entropy->restarts_to_go--;
  172921. return TRUE;
  172922. undoit:
  172923. /* Re-zero any output coefficients that we made newly nonzero */
  172924. while (num_newnz > 0)
  172925. (*block)[newnz_pos[--num_newnz]] = 0;
  172926. return FALSE;
  172927. }
  172928. /*
  172929. * Module initialization routine for progressive Huffman entropy decoding.
  172930. */
  172931. GLOBAL(void)
  172932. jinit_phuff_decoder (j_decompress_ptr cinfo)
  172933. {
  172934. phuff_entropy_ptr2 entropy;
  172935. int *coef_bit_ptr;
  172936. int ci, i;
  172937. entropy = (phuff_entropy_ptr2)
  172938. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172939. SIZEOF(phuff_entropy_decoder));
  172940. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  172941. entropy->pub.start_pass = start_pass_phuff_decoder;
  172942. /* Mark derived tables unallocated */
  172943. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  172944. entropy->derived_tbls[i] = NULL;
  172945. }
  172946. /* Create progression status table */
  172947. cinfo->coef_bits = (int (*)[DCTSIZE2])
  172948. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172949. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  172950. coef_bit_ptr = & cinfo->coef_bits[0][0];
  172951. for (ci = 0; ci < cinfo->num_components; ci++)
  172952. for (i = 0; i < DCTSIZE2; i++)
  172953. *coef_bit_ptr++ = -1;
  172954. }
  172955. #endif /* D_PROGRESSIVE_SUPPORTED */
  172956. /*** End of inlined file: jdphuff.c ***/
  172957. /*** Start of inlined file: jdpostct.c ***/
  172958. #define JPEG_INTERNALS
  172959. /* Private buffer controller object */
  172960. typedef struct {
  172961. struct jpeg_d_post_controller pub; /* public fields */
  172962. /* Color quantization source buffer: this holds output data from
  172963. * the upsample/color conversion step to be passed to the quantizer.
  172964. * For two-pass color quantization, we need a full-image buffer;
  172965. * for one-pass operation, a strip buffer is sufficient.
  172966. */
  172967. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  172968. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  172969. JDIMENSION strip_height; /* buffer size in rows */
  172970. /* for two-pass mode only: */
  172971. JDIMENSION starting_row; /* row # of first row in current strip */
  172972. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  172973. } my_post_controller;
  172974. typedef my_post_controller * my_post_ptr;
  172975. /* Forward declarations */
  172976. METHODDEF(void) post_process_1pass
  172977. JPP((j_decompress_ptr cinfo,
  172978. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172979. JDIMENSION in_row_groups_avail,
  172980. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172981. JDIMENSION out_rows_avail));
  172982. #ifdef QUANT_2PASS_SUPPORTED
  172983. METHODDEF(void) post_process_prepass
  172984. JPP((j_decompress_ptr cinfo,
  172985. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172986. JDIMENSION in_row_groups_avail,
  172987. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172988. JDIMENSION out_rows_avail));
  172989. METHODDEF(void) post_process_2pass
  172990. JPP((j_decompress_ptr cinfo,
  172991. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172992. JDIMENSION in_row_groups_avail,
  172993. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172994. JDIMENSION out_rows_avail));
  172995. #endif
  172996. /*
  172997. * Initialize for a processing pass.
  172998. */
  172999. METHODDEF(void)
  173000. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173001. {
  173002. my_post_ptr post = (my_post_ptr) cinfo->post;
  173003. switch (pass_mode) {
  173004. case JBUF_PASS_THRU:
  173005. if (cinfo->quantize_colors) {
  173006. /* Single-pass processing with color quantization. */
  173007. post->pub.post_process_data = post_process_1pass;
  173008. /* We could be doing buffered-image output before starting a 2-pass
  173009. * color quantization; in that case, jinit_d_post_controller did not
  173010. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173011. */
  173012. if (post->buffer == NULL) {
  173013. post->buffer = (*cinfo->mem->access_virt_sarray)
  173014. ((j_common_ptr) cinfo, post->whole_image,
  173015. (JDIMENSION) 0, post->strip_height, TRUE);
  173016. }
  173017. } else {
  173018. /* For single-pass processing without color quantization,
  173019. * I have no work to do; just call the upsampler directly.
  173020. */
  173021. post->pub.post_process_data = cinfo->upsample->upsample;
  173022. }
  173023. break;
  173024. #ifdef QUANT_2PASS_SUPPORTED
  173025. case JBUF_SAVE_AND_PASS:
  173026. /* First pass of 2-pass quantization */
  173027. if (post->whole_image == NULL)
  173028. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173029. post->pub.post_process_data = post_process_prepass;
  173030. break;
  173031. case JBUF_CRANK_DEST:
  173032. /* Second pass of 2-pass quantization */
  173033. if (post->whole_image == NULL)
  173034. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173035. post->pub.post_process_data = post_process_2pass;
  173036. break;
  173037. #endif /* QUANT_2PASS_SUPPORTED */
  173038. default:
  173039. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173040. break;
  173041. }
  173042. post->starting_row = post->next_row = 0;
  173043. }
  173044. /*
  173045. * Process some data in the one-pass (strip buffer) case.
  173046. * This is used for color precision reduction as well as one-pass quantization.
  173047. */
  173048. METHODDEF(void)
  173049. post_process_1pass (j_decompress_ptr cinfo,
  173050. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173051. JDIMENSION in_row_groups_avail,
  173052. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173053. JDIMENSION out_rows_avail)
  173054. {
  173055. my_post_ptr post = (my_post_ptr) cinfo->post;
  173056. JDIMENSION num_rows, max_rows;
  173057. /* Fill the buffer, but not more than what we can dump out in one go. */
  173058. /* Note we rely on the upsampler to detect bottom of image. */
  173059. max_rows = out_rows_avail - *out_row_ctr;
  173060. if (max_rows > post->strip_height)
  173061. max_rows = post->strip_height;
  173062. num_rows = 0;
  173063. (*cinfo->upsample->upsample) (cinfo,
  173064. input_buf, in_row_group_ctr, in_row_groups_avail,
  173065. post->buffer, &num_rows, max_rows);
  173066. /* Quantize and emit data. */
  173067. (*cinfo->cquantize->color_quantize) (cinfo,
  173068. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173069. *out_row_ctr += num_rows;
  173070. }
  173071. #ifdef QUANT_2PASS_SUPPORTED
  173072. /*
  173073. * Process some data in the first pass of 2-pass quantization.
  173074. */
  173075. METHODDEF(void)
  173076. post_process_prepass (j_decompress_ptr cinfo,
  173077. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173078. JDIMENSION in_row_groups_avail,
  173079. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173080. JDIMENSION)
  173081. {
  173082. my_post_ptr post = (my_post_ptr) cinfo->post;
  173083. JDIMENSION old_next_row, num_rows;
  173084. /* Reposition virtual buffer if at start of strip. */
  173085. if (post->next_row == 0) {
  173086. post->buffer = (*cinfo->mem->access_virt_sarray)
  173087. ((j_common_ptr) cinfo, post->whole_image,
  173088. post->starting_row, post->strip_height, TRUE);
  173089. }
  173090. /* Upsample some data (up to a strip height's worth). */
  173091. old_next_row = post->next_row;
  173092. (*cinfo->upsample->upsample) (cinfo,
  173093. input_buf, in_row_group_ctr, in_row_groups_avail,
  173094. post->buffer, &post->next_row, post->strip_height);
  173095. /* Allow quantizer to scan new data. No data is emitted, */
  173096. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173097. if (post->next_row > old_next_row) {
  173098. num_rows = post->next_row - old_next_row;
  173099. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173100. (JSAMPARRAY) NULL, (int) num_rows);
  173101. *out_row_ctr += num_rows;
  173102. }
  173103. /* Advance if we filled the strip. */
  173104. if (post->next_row >= post->strip_height) {
  173105. post->starting_row += post->strip_height;
  173106. post->next_row = 0;
  173107. }
  173108. }
  173109. /*
  173110. * Process some data in the second pass of 2-pass quantization.
  173111. */
  173112. METHODDEF(void)
  173113. post_process_2pass (j_decompress_ptr cinfo,
  173114. JSAMPIMAGE, JDIMENSION *,
  173115. JDIMENSION,
  173116. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173117. JDIMENSION out_rows_avail)
  173118. {
  173119. my_post_ptr post = (my_post_ptr) cinfo->post;
  173120. JDIMENSION num_rows, max_rows;
  173121. /* Reposition virtual buffer if at start of strip. */
  173122. if (post->next_row == 0) {
  173123. post->buffer = (*cinfo->mem->access_virt_sarray)
  173124. ((j_common_ptr) cinfo, post->whole_image,
  173125. post->starting_row, post->strip_height, FALSE);
  173126. }
  173127. /* Determine number of rows to emit. */
  173128. num_rows = post->strip_height - post->next_row; /* available in strip */
  173129. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173130. if (num_rows > max_rows)
  173131. num_rows = max_rows;
  173132. /* We have to check bottom of image here, can't depend on upsampler. */
  173133. max_rows = cinfo->output_height - post->starting_row;
  173134. if (num_rows > max_rows)
  173135. num_rows = max_rows;
  173136. /* Quantize and emit data. */
  173137. (*cinfo->cquantize->color_quantize) (cinfo,
  173138. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173139. (int) num_rows);
  173140. *out_row_ctr += num_rows;
  173141. /* Advance if we filled the strip. */
  173142. post->next_row += num_rows;
  173143. if (post->next_row >= post->strip_height) {
  173144. post->starting_row += post->strip_height;
  173145. post->next_row = 0;
  173146. }
  173147. }
  173148. #endif /* QUANT_2PASS_SUPPORTED */
  173149. /*
  173150. * Initialize postprocessing controller.
  173151. */
  173152. GLOBAL(void)
  173153. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173154. {
  173155. my_post_ptr post;
  173156. post = (my_post_ptr)
  173157. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173158. SIZEOF(my_post_controller));
  173159. cinfo->post = (struct jpeg_d_post_controller *) post;
  173160. post->pub.start_pass = start_pass_dpost;
  173161. post->whole_image = NULL; /* flag for no virtual arrays */
  173162. post->buffer = NULL; /* flag for no strip buffer */
  173163. /* Create the quantization buffer, if needed */
  173164. if (cinfo->quantize_colors) {
  173165. /* The buffer strip height is max_v_samp_factor, which is typically
  173166. * an efficient number of rows for upsampling to return.
  173167. * (In the presence of output rescaling, we might want to be smarter?)
  173168. */
  173169. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173170. if (need_full_buffer) {
  173171. /* Two-pass color quantization: need full-image storage. */
  173172. /* We round up the number of rows to a multiple of the strip height. */
  173173. #ifdef QUANT_2PASS_SUPPORTED
  173174. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173175. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173176. cinfo->output_width * cinfo->out_color_components,
  173177. (JDIMENSION) jround_up((long) cinfo->output_height,
  173178. (long) post->strip_height),
  173179. post->strip_height);
  173180. #else
  173181. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173182. #endif /* QUANT_2PASS_SUPPORTED */
  173183. } else {
  173184. /* One-pass color quantization: just make a strip buffer. */
  173185. post->buffer = (*cinfo->mem->alloc_sarray)
  173186. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173187. cinfo->output_width * cinfo->out_color_components,
  173188. post->strip_height);
  173189. }
  173190. }
  173191. }
  173192. /*** End of inlined file: jdpostct.c ***/
  173193. #undef FIX
  173194. /*** Start of inlined file: jdsample.c ***/
  173195. #define JPEG_INTERNALS
  173196. /* Pointer to routine to upsample a single component */
  173197. typedef JMETHOD(void, upsample1_ptr,
  173198. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173199. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173200. /* Private subobject */
  173201. typedef struct {
  173202. struct jpeg_upsampler pub; /* public fields */
  173203. /* Color conversion buffer. When using separate upsampling and color
  173204. * conversion steps, this buffer holds one upsampled row group until it
  173205. * has been color converted and output.
  173206. * Note: we do not allocate any storage for component(s) which are full-size,
  173207. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173208. * simply set to point to the input data array, thereby avoiding copying.
  173209. */
  173210. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173211. /* Per-component upsampling method pointers */
  173212. upsample1_ptr methods[MAX_COMPONENTS];
  173213. int next_row_out; /* counts rows emitted from color_buf */
  173214. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173215. /* Height of an input row group for each component. */
  173216. int rowgroup_height[MAX_COMPONENTS];
  173217. /* These arrays save pixel expansion factors so that int_expand need not
  173218. * recompute them each time. They are unused for other upsampling methods.
  173219. */
  173220. UINT8 h_expand[MAX_COMPONENTS];
  173221. UINT8 v_expand[MAX_COMPONENTS];
  173222. } my_upsampler2;
  173223. typedef my_upsampler2 * my_upsample_ptr2;
  173224. /*
  173225. * Initialize for an upsampling pass.
  173226. */
  173227. METHODDEF(void)
  173228. start_pass_upsample (j_decompress_ptr cinfo)
  173229. {
  173230. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173231. /* Mark the conversion buffer empty */
  173232. upsample->next_row_out = cinfo->max_v_samp_factor;
  173233. /* Initialize total-height counter for detecting bottom of image */
  173234. upsample->rows_to_go = cinfo->output_height;
  173235. }
  173236. /*
  173237. * Control routine to do upsampling (and color conversion).
  173238. *
  173239. * In this version we upsample each component independently.
  173240. * We upsample one row group into the conversion buffer, then apply
  173241. * color conversion a row at a time.
  173242. */
  173243. METHODDEF(void)
  173244. sep_upsample (j_decompress_ptr cinfo,
  173245. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173246. JDIMENSION,
  173247. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173248. JDIMENSION out_rows_avail)
  173249. {
  173250. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173251. int ci;
  173252. jpeg_component_info * compptr;
  173253. JDIMENSION num_rows;
  173254. /* Fill the conversion buffer, if it's empty */
  173255. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173256. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173257. ci++, compptr++) {
  173258. /* Invoke per-component upsample method. Notice we pass a POINTER
  173259. * to color_buf[ci], so that fullsize_upsample can change it.
  173260. */
  173261. (*upsample->methods[ci]) (cinfo, compptr,
  173262. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173263. upsample->color_buf + ci);
  173264. }
  173265. upsample->next_row_out = 0;
  173266. }
  173267. /* Color-convert and emit rows */
  173268. /* How many we have in the buffer: */
  173269. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173270. /* Not more than the distance to the end of the image. Need this test
  173271. * in case the image height is not a multiple of max_v_samp_factor:
  173272. */
  173273. if (num_rows > upsample->rows_to_go)
  173274. num_rows = upsample->rows_to_go;
  173275. /* And not more than what the client can accept: */
  173276. out_rows_avail -= *out_row_ctr;
  173277. if (num_rows > out_rows_avail)
  173278. num_rows = out_rows_avail;
  173279. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  173280. (JDIMENSION) upsample->next_row_out,
  173281. output_buf + *out_row_ctr,
  173282. (int) num_rows);
  173283. /* Adjust counts */
  173284. *out_row_ctr += num_rows;
  173285. upsample->rows_to_go -= num_rows;
  173286. upsample->next_row_out += num_rows;
  173287. /* When the buffer is emptied, declare this input row group consumed */
  173288. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  173289. (*in_row_group_ctr)++;
  173290. }
  173291. /*
  173292. * These are the routines invoked by sep_upsample to upsample pixel values
  173293. * of a single component. One row group is processed per call.
  173294. */
  173295. /*
  173296. * For full-size components, we just make color_buf[ci] point at the
  173297. * input buffer, and thus avoid copying any data. Note that this is
  173298. * safe only because sep_upsample doesn't declare the input row group
  173299. * "consumed" until we are done color converting and emitting it.
  173300. */
  173301. METHODDEF(void)
  173302. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  173303. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173304. {
  173305. *output_data_ptr = input_data;
  173306. }
  173307. /*
  173308. * This is a no-op version used for "uninteresting" components.
  173309. * These components will not be referenced by color conversion.
  173310. */
  173311. METHODDEF(void)
  173312. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173313. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173314. {
  173315. *output_data_ptr = NULL; /* safety check */
  173316. }
  173317. /*
  173318. * This version handles any integral sampling ratios.
  173319. * This is not used for typical JPEG files, so it need not be fast.
  173320. * Nor, for that matter, is it particularly accurate: the algorithm is
  173321. * simple replication of the input pixel onto the corresponding output
  173322. * pixels. The hi-falutin sampling literature refers to this as a
  173323. * "box filter". A box filter tends to introduce visible artifacts,
  173324. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173325. * you would be well advised to improve this code.
  173326. */
  173327. METHODDEF(void)
  173328. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173329. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173330. {
  173331. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173332. JSAMPARRAY output_data = *output_data_ptr;
  173333. register JSAMPROW inptr, outptr;
  173334. register JSAMPLE invalue;
  173335. register int h;
  173336. JSAMPROW outend;
  173337. int h_expand, v_expand;
  173338. int inrow, outrow;
  173339. h_expand = upsample->h_expand[compptr->component_index];
  173340. v_expand = upsample->v_expand[compptr->component_index];
  173341. inrow = outrow = 0;
  173342. while (outrow < cinfo->max_v_samp_factor) {
  173343. /* Generate one output row with proper horizontal expansion */
  173344. inptr = input_data[inrow];
  173345. outptr = output_data[outrow];
  173346. outend = outptr + cinfo->output_width;
  173347. while (outptr < outend) {
  173348. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173349. for (h = h_expand; h > 0; h--) {
  173350. *outptr++ = invalue;
  173351. }
  173352. }
  173353. /* Generate any additional output rows by duplicating the first one */
  173354. if (v_expand > 1) {
  173355. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173356. v_expand-1, cinfo->output_width);
  173357. }
  173358. inrow++;
  173359. outrow += v_expand;
  173360. }
  173361. }
  173362. /*
  173363. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173364. * It's still a box filter.
  173365. */
  173366. METHODDEF(void)
  173367. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173368. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173369. {
  173370. JSAMPARRAY output_data = *output_data_ptr;
  173371. register JSAMPROW inptr, outptr;
  173372. register JSAMPLE invalue;
  173373. JSAMPROW outend;
  173374. int inrow;
  173375. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173376. inptr = input_data[inrow];
  173377. outptr = output_data[inrow];
  173378. outend = outptr + cinfo->output_width;
  173379. while (outptr < outend) {
  173380. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173381. *outptr++ = invalue;
  173382. *outptr++ = invalue;
  173383. }
  173384. }
  173385. }
  173386. /*
  173387. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  173388. * It's still a box filter.
  173389. */
  173390. METHODDEF(void)
  173391. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173392. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173393. {
  173394. JSAMPARRAY output_data = *output_data_ptr;
  173395. register JSAMPROW inptr, outptr;
  173396. register JSAMPLE invalue;
  173397. JSAMPROW outend;
  173398. int inrow, outrow;
  173399. inrow = outrow = 0;
  173400. while (outrow < cinfo->max_v_samp_factor) {
  173401. inptr = input_data[inrow];
  173402. outptr = output_data[outrow];
  173403. outend = outptr + cinfo->output_width;
  173404. while (outptr < outend) {
  173405. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173406. *outptr++ = invalue;
  173407. *outptr++ = invalue;
  173408. }
  173409. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173410. 1, cinfo->output_width);
  173411. inrow++;
  173412. outrow += 2;
  173413. }
  173414. }
  173415. /*
  173416. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  173417. *
  173418. * The upsampling algorithm is linear interpolation between pixel centers,
  173419. * also known as a "triangle filter". This is a good compromise between
  173420. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  173421. * of the way between input pixel centers.
  173422. *
  173423. * A note about the "bias" calculations: when rounding fractional values to
  173424. * integer, we do not want to always round 0.5 up to the next integer.
  173425. * If we did that, we'd introduce a noticeable bias towards larger values.
  173426. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  173427. * alternate pixel locations (a simple ordered dither pattern).
  173428. */
  173429. METHODDEF(void)
  173430. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173431. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173432. {
  173433. JSAMPARRAY output_data = *output_data_ptr;
  173434. register JSAMPROW inptr, outptr;
  173435. register int invalue;
  173436. register JDIMENSION colctr;
  173437. int inrow;
  173438. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173439. inptr = input_data[inrow];
  173440. outptr = output_data[inrow];
  173441. /* Special case for first column */
  173442. invalue = GETJSAMPLE(*inptr++);
  173443. *outptr++ = (JSAMPLE) invalue;
  173444. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  173445. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173446. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  173447. invalue = GETJSAMPLE(*inptr++) * 3;
  173448. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  173449. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  173450. }
  173451. /* Special case for last column */
  173452. invalue = GETJSAMPLE(*inptr);
  173453. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  173454. *outptr++ = (JSAMPLE) invalue;
  173455. }
  173456. }
  173457. /*
  173458. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  173459. * Again a triangle filter; see comments for h2v1 case, above.
  173460. *
  173461. * It is OK for us to reference the adjacent input rows because we demanded
  173462. * context from the main buffer controller (see initialization code).
  173463. */
  173464. METHODDEF(void)
  173465. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173466. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173467. {
  173468. JSAMPARRAY output_data = *output_data_ptr;
  173469. register JSAMPROW inptr0, inptr1, outptr;
  173470. #if BITS_IN_JSAMPLE == 8
  173471. register int thiscolsum, lastcolsum, nextcolsum;
  173472. #else
  173473. register INT32 thiscolsum, lastcolsum, nextcolsum;
  173474. #endif
  173475. register JDIMENSION colctr;
  173476. int inrow, outrow, v;
  173477. inrow = outrow = 0;
  173478. while (outrow < cinfo->max_v_samp_factor) {
  173479. for (v = 0; v < 2; v++) {
  173480. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  173481. inptr0 = input_data[inrow];
  173482. if (v == 0) /* next nearest is row above */
  173483. inptr1 = input_data[inrow-1];
  173484. else /* next nearest is row below */
  173485. inptr1 = input_data[inrow+1];
  173486. outptr = output_data[outrow++];
  173487. /* Special case for first column */
  173488. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173489. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173490. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  173491. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173492. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173493. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173494. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  173495. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  173496. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173497. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173498. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173499. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173500. }
  173501. /* Special case for last column */
  173502. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173503. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  173504. }
  173505. inrow++;
  173506. }
  173507. }
  173508. /*
  173509. * Module initialization routine for upsampling.
  173510. */
  173511. GLOBAL(void)
  173512. jinit_upsampler (j_decompress_ptr cinfo)
  173513. {
  173514. my_upsample_ptr2 upsample;
  173515. int ci;
  173516. jpeg_component_info * compptr;
  173517. boolean need_buffer, do_fancy;
  173518. int h_in_group, v_in_group, h_out_group, v_out_group;
  173519. upsample = (my_upsample_ptr2)
  173520. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173521. SIZEOF(my_upsampler2));
  173522. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173523. upsample->pub.start_pass = start_pass_upsample;
  173524. upsample->pub.upsample = sep_upsample;
  173525. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  173526. if (cinfo->CCIR601_sampling) /* this isn't supported */
  173527. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  173528. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  173529. * so don't ask for it.
  173530. */
  173531. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  173532. /* Verify we can handle the sampling factors, select per-component methods,
  173533. * and create storage as needed.
  173534. */
  173535. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173536. ci++, compptr++) {
  173537. /* Compute size of an "input group" after IDCT scaling. This many samples
  173538. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  173539. */
  173540. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  173541. cinfo->min_DCT_scaled_size;
  173542. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  173543. cinfo->min_DCT_scaled_size;
  173544. h_out_group = cinfo->max_h_samp_factor;
  173545. v_out_group = cinfo->max_v_samp_factor;
  173546. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  173547. need_buffer = TRUE;
  173548. if (! compptr->component_needed) {
  173549. /* Don't bother to upsample an uninteresting component. */
  173550. upsample->methods[ci] = noop_upsample;
  173551. need_buffer = FALSE;
  173552. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  173553. /* Fullsize components can be processed without any work. */
  173554. upsample->methods[ci] = fullsize_upsample;
  173555. need_buffer = FALSE;
  173556. } else if (h_in_group * 2 == h_out_group &&
  173557. v_in_group == v_out_group) {
  173558. /* Special cases for 2h1v upsampling */
  173559. if (do_fancy && compptr->downsampled_width > 2)
  173560. upsample->methods[ci] = h2v1_fancy_upsample;
  173561. else
  173562. upsample->methods[ci] = h2v1_upsample;
  173563. } else if (h_in_group * 2 == h_out_group &&
  173564. v_in_group * 2 == v_out_group) {
  173565. /* Special cases for 2h2v upsampling */
  173566. if (do_fancy && compptr->downsampled_width > 2) {
  173567. upsample->methods[ci] = h2v2_fancy_upsample;
  173568. upsample->pub.need_context_rows = TRUE;
  173569. } else
  173570. upsample->methods[ci] = h2v2_upsample;
  173571. } else if ((h_out_group % h_in_group) == 0 &&
  173572. (v_out_group % v_in_group) == 0) {
  173573. /* Generic integral-factors upsampling method */
  173574. upsample->methods[ci] = int_upsample;
  173575. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  173576. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  173577. } else
  173578. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  173579. if (need_buffer) {
  173580. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  173581. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173582. (JDIMENSION) jround_up((long) cinfo->output_width,
  173583. (long) cinfo->max_h_samp_factor),
  173584. (JDIMENSION) cinfo->max_v_samp_factor);
  173585. }
  173586. }
  173587. }
  173588. /*** End of inlined file: jdsample.c ***/
  173589. /*** Start of inlined file: jdtrans.c ***/
  173590. #define JPEG_INTERNALS
  173591. /* Forward declarations */
  173592. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  173593. /*
  173594. * Read the coefficient arrays from a JPEG file.
  173595. * jpeg_read_header must be completed before calling this.
  173596. *
  173597. * The entire image is read into a set of virtual coefficient-block arrays,
  173598. * one per component. The return value is a pointer to the array of
  173599. * virtual-array descriptors. These can be manipulated directly via the
  173600. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  173601. * To release the memory occupied by the virtual arrays, call
  173602. * jpeg_finish_decompress() when done with the data.
  173603. *
  173604. * An alternative usage is to simply obtain access to the coefficient arrays
  173605. * during a buffered-image-mode decompression operation. This is allowed
  173606. * after any jpeg_finish_output() call. The arrays can be accessed until
  173607. * jpeg_finish_decompress() is called. (Note that any call to the library
  173608. * may reposition the arrays, so don't rely on access_virt_barray() results
  173609. * to stay valid across library calls.)
  173610. *
  173611. * Returns NULL if suspended. This case need be checked only if
  173612. * a suspending data source is used.
  173613. */
  173614. GLOBAL(jvirt_barray_ptr *)
  173615. jpeg_read_coefficients (j_decompress_ptr cinfo)
  173616. {
  173617. if (cinfo->global_state == DSTATE_READY) {
  173618. /* First call: initialize active modules */
  173619. transdecode_master_selection(cinfo);
  173620. cinfo->global_state = DSTATE_RDCOEFS;
  173621. }
  173622. if (cinfo->global_state == DSTATE_RDCOEFS) {
  173623. /* Absorb whole file into the coef buffer */
  173624. for (;;) {
  173625. int retcode;
  173626. /* Call progress monitor hook if present */
  173627. if (cinfo->progress != NULL)
  173628. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  173629. /* Absorb some more input */
  173630. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  173631. if (retcode == JPEG_SUSPENDED)
  173632. return NULL;
  173633. if (retcode == JPEG_REACHED_EOI)
  173634. break;
  173635. /* Advance progress counter if appropriate */
  173636. if (cinfo->progress != NULL &&
  173637. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  173638. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  173639. /* startup underestimated number of scans; ratchet up one scan */
  173640. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  173641. }
  173642. }
  173643. }
  173644. /* Set state so that jpeg_finish_decompress does the right thing */
  173645. cinfo->global_state = DSTATE_STOPPING;
  173646. }
  173647. /* At this point we should be in state DSTATE_STOPPING if being used
  173648. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  173649. * to the coefficients during a full buffered-image-mode decompression.
  173650. */
  173651. if ((cinfo->global_state == DSTATE_STOPPING ||
  173652. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  173653. return cinfo->coef->coef_arrays;
  173654. }
  173655. /* Oops, improper usage */
  173656. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  173657. return NULL; /* keep compiler happy */
  173658. }
  173659. /*
  173660. * Master selection of decompression modules for transcoding.
  173661. * This substitutes for jdmaster.c's initialization of the full decompressor.
  173662. */
  173663. LOCAL(void)
  173664. transdecode_master_selection (j_decompress_ptr cinfo)
  173665. {
  173666. /* This is effectively a buffered-image operation. */
  173667. cinfo->buffered_image = TRUE;
  173668. /* Entropy decoding: either Huffman or arithmetic coding. */
  173669. if (cinfo->arith_code) {
  173670. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  173671. } else {
  173672. if (cinfo->progressive_mode) {
  173673. #ifdef D_PROGRESSIVE_SUPPORTED
  173674. jinit_phuff_decoder(cinfo);
  173675. #else
  173676. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173677. #endif
  173678. } else
  173679. jinit_huff_decoder(cinfo);
  173680. }
  173681. /* Always get a full-image coefficient buffer. */
  173682. jinit_d_coef_controller(cinfo, TRUE);
  173683. /* We can now tell the memory manager to allocate virtual arrays. */
  173684. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  173685. /* Initialize input side of decompressor to consume first scan. */
  173686. (*cinfo->inputctl->start_input_pass) (cinfo);
  173687. /* Initialize progress monitoring. */
  173688. if (cinfo->progress != NULL) {
  173689. int nscans;
  173690. /* Estimate number of scans to set pass_limit. */
  173691. if (cinfo->progressive_mode) {
  173692. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  173693. nscans = 2 + 3 * cinfo->num_components;
  173694. } else if (cinfo->inputctl->has_multiple_scans) {
  173695. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  173696. nscans = cinfo->num_components;
  173697. } else {
  173698. nscans = 1;
  173699. }
  173700. cinfo->progress->pass_counter = 0L;
  173701. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  173702. cinfo->progress->completed_passes = 0;
  173703. cinfo->progress->total_passes = 1;
  173704. }
  173705. }
  173706. /*** End of inlined file: jdtrans.c ***/
  173707. /*** Start of inlined file: jfdctflt.c ***/
  173708. #define JPEG_INTERNALS
  173709. #ifdef DCT_FLOAT_SUPPORTED
  173710. /*
  173711. * This module is specialized to the case DCTSIZE = 8.
  173712. */
  173713. #if DCTSIZE != 8
  173714. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173715. #endif
  173716. /*
  173717. * Perform the forward DCT on one block of samples.
  173718. */
  173719. GLOBAL(void)
  173720. jpeg_fdct_float (FAST_FLOAT * data)
  173721. {
  173722. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173723. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  173724. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  173725. FAST_FLOAT *dataptr;
  173726. int ctr;
  173727. /* Pass 1: process rows. */
  173728. dataptr = data;
  173729. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173730. tmp0 = dataptr[0] + dataptr[7];
  173731. tmp7 = dataptr[0] - dataptr[7];
  173732. tmp1 = dataptr[1] + dataptr[6];
  173733. tmp6 = dataptr[1] - dataptr[6];
  173734. tmp2 = dataptr[2] + dataptr[5];
  173735. tmp5 = dataptr[2] - dataptr[5];
  173736. tmp3 = dataptr[3] + dataptr[4];
  173737. tmp4 = dataptr[3] - dataptr[4];
  173738. /* Even part */
  173739. tmp10 = tmp0 + tmp3; /* phase 2 */
  173740. tmp13 = tmp0 - tmp3;
  173741. tmp11 = tmp1 + tmp2;
  173742. tmp12 = tmp1 - tmp2;
  173743. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  173744. dataptr[4] = tmp10 - tmp11;
  173745. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  173746. dataptr[2] = tmp13 + z1; /* phase 5 */
  173747. dataptr[6] = tmp13 - z1;
  173748. /* Odd part */
  173749. tmp10 = tmp4 + tmp5; /* phase 2 */
  173750. tmp11 = tmp5 + tmp6;
  173751. tmp12 = tmp6 + tmp7;
  173752. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173753. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  173754. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  173755. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  173756. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  173757. z11 = tmp7 + z3; /* phase 5 */
  173758. z13 = tmp7 - z3;
  173759. dataptr[5] = z13 + z2; /* phase 6 */
  173760. dataptr[3] = z13 - z2;
  173761. dataptr[1] = z11 + z4;
  173762. dataptr[7] = z11 - z4;
  173763. dataptr += DCTSIZE; /* advance pointer to next row */
  173764. }
  173765. /* Pass 2: process columns. */
  173766. dataptr = data;
  173767. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173768. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173769. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173770. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173771. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173772. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173773. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173774. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173775. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173776. /* Even part */
  173777. tmp10 = tmp0 + tmp3; /* phase 2 */
  173778. tmp13 = tmp0 - tmp3;
  173779. tmp11 = tmp1 + tmp2;
  173780. tmp12 = tmp1 - tmp2;
  173781. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  173782. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  173783. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  173784. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  173785. dataptr[DCTSIZE*6] = tmp13 - z1;
  173786. /* Odd part */
  173787. tmp10 = tmp4 + tmp5; /* phase 2 */
  173788. tmp11 = tmp5 + tmp6;
  173789. tmp12 = tmp6 + tmp7;
  173790. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173791. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  173792. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  173793. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  173794. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  173795. z11 = tmp7 + z3; /* phase 5 */
  173796. z13 = tmp7 - z3;
  173797. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  173798. dataptr[DCTSIZE*3] = z13 - z2;
  173799. dataptr[DCTSIZE*1] = z11 + z4;
  173800. dataptr[DCTSIZE*7] = z11 - z4;
  173801. dataptr++; /* advance pointer to next column */
  173802. }
  173803. }
  173804. #endif /* DCT_FLOAT_SUPPORTED */
  173805. /*** End of inlined file: jfdctflt.c ***/
  173806. /*** Start of inlined file: jfdctint.c ***/
  173807. #define JPEG_INTERNALS
  173808. #ifdef DCT_ISLOW_SUPPORTED
  173809. /*
  173810. * This module is specialized to the case DCTSIZE = 8.
  173811. */
  173812. #if DCTSIZE != 8
  173813. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173814. #endif
  173815. /*
  173816. * The poop on this scaling stuff is as follows:
  173817. *
  173818. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  173819. * larger than the true DCT outputs. The final outputs are therefore
  173820. * a factor of N larger than desired; since N=8 this can be cured by
  173821. * a simple right shift at the end of the algorithm. The advantage of
  173822. * this arrangement is that we save two multiplications per 1-D DCT,
  173823. * because the y0 and y4 outputs need not be divided by sqrt(N).
  173824. * In the IJG code, this factor of 8 is removed by the quantization step
  173825. * (in jcdctmgr.c), NOT in this module.
  173826. *
  173827. * We have to do addition and subtraction of the integer inputs, which
  173828. * is no problem, and multiplication by fractional constants, which is
  173829. * a problem to do in integer arithmetic. We multiply all the constants
  173830. * by CONST_SCALE and convert them to integer constants (thus retaining
  173831. * CONST_BITS bits of precision in the constants). After doing a
  173832. * multiplication we have to divide the product by CONST_SCALE, with proper
  173833. * rounding, to produce the correct output. This division can be done
  173834. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  173835. * as long as possible so that partial sums can be added together with
  173836. * full fractional precision.
  173837. *
  173838. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  173839. * they are represented to better-than-integral precision. These outputs
  173840. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  173841. * with the recommended scaling. (For 12-bit sample data, the intermediate
  173842. * array is INT32 anyway.)
  173843. *
  173844. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  173845. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  173846. * shows that the values given below are the most effective.
  173847. */
  173848. #if BITS_IN_JSAMPLE == 8
  173849. #define CONST_BITS 13
  173850. #define PASS1_BITS 2
  173851. #else
  173852. #define CONST_BITS 13
  173853. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  173854. #endif
  173855. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  173856. * causing a lot of useless floating-point operations at run time.
  173857. * To get around this we use the following pre-calculated constants.
  173858. * If you change CONST_BITS you may want to add appropriate values.
  173859. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  173860. */
  173861. #if CONST_BITS == 13
  173862. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  173863. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  173864. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  173865. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  173866. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  173867. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  173868. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  173869. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  173870. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  173871. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  173872. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  173873. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  173874. #else
  173875. #define FIX_0_298631336 FIX(0.298631336)
  173876. #define FIX_0_390180644 FIX(0.390180644)
  173877. #define FIX_0_541196100 FIX(0.541196100)
  173878. #define FIX_0_765366865 FIX(0.765366865)
  173879. #define FIX_0_899976223 FIX(0.899976223)
  173880. #define FIX_1_175875602 FIX(1.175875602)
  173881. #define FIX_1_501321110 FIX(1.501321110)
  173882. #define FIX_1_847759065 FIX(1.847759065)
  173883. #define FIX_1_961570560 FIX(1.961570560)
  173884. #define FIX_2_053119869 FIX(2.053119869)
  173885. #define FIX_2_562915447 FIX(2.562915447)
  173886. #define FIX_3_072711026 FIX(3.072711026)
  173887. #endif
  173888. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  173889. * For 8-bit samples with the recommended scaling, all the variable
  173890. * and constant values involved are no more than 16 bits wide, so a
  173891. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  173892. * For 12-bit samples, a full 32-bit multiplication will be needed.
  173893. */
  173894. #if BITS_IN_JSAMPLE == 8
  173895. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  173896. #else
  173897. #define MULTIPLY(var,const) ((var) * (const))
  173898. #endif
  173899. /*
  173900. * Perform the forward DCT on one block of samples.
  173901. */
  173902. GLOBAL(void)
  173903. jpeg_fdct_islow (DCTELEM * data)
  173904. {
  173905. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173906. INT32 tmp10, tmp11, tmp12, tmp13;
  173907. INT32 z1, z2, z3, z4, z5;
  173908. DCTELEM *dataptr;
  173909. int ctr;
  173910. SHIFT_TEMPS
  173911. /* Pass 1: process rows. */
  173912. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  173913. /* furthermore, we scale the results by 2**PASS1_BITS. */
  173914. dataptr = data;
  173915. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173916. tmp0 = dataptr[0] + dataptr[7];
  173917. tmp7 = dataptr[0] - dataptr[7];
  173918. tmp1 = dataptr[1] + dataptr[6];
  173919. tmp6 = dataptr[1] - dataptr[6];
  173920. tmp2 = dataptr[2] + dataptr[5];
  173921. tmp5 = dataptr[2] - dataptr[5];
  173922. tmp3 = dataptr[3] + dataptr[4];
  173923. tmp4 = dataptr[3] - dataptr[4];
  173924. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  173925. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  173926. */
  173927. tmp10 = tmp0 + tmp3;
  173928. tmp13 = tmp0 - tmp3;
  173929. tmp11 = tmp1 + tmp2;
  173930. tmp12 = tmp1 - tmp2;
  173931. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  173932. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  173933. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  173934. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  173935. CONST_BITS-PASS1_BITS);
  173936. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  173937. CONST_BITS-PASS1_BITS);
  173938. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  173939. * cK represents cos(K*pi/16).
  173940. * i0..i3 in the paper are tmp4..tmp7 here.
  173941. */
  173942. z1 = tmp4 + tmp7;
  173943. z2 = tmp5 + tmp6;
  173944. z3 = tmp4 + tmp6;
  173945. z4 = tmp5 + tmp7;
  173946. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  173947. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  173948. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  173949. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  173950. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  173951. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  173952. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  173953. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  173954. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  173955. z3 += z5;
  173956. z4 += z5;
  173957. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  173958. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  173959. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  173960. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  173961. dataptr += DCTSIZE; /* advance pointer to next row */
  173962. }
  173963. /* Pass 2: process columns.
  173964. * We remove the PASS1_BITS scaling, but leave the results scaled up
  173965. * by an overall factor of 8.
  173966. */
  173967. dataptr = data;
  173968. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173969. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173970. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173971. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173972. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173973. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173974. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173975. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173976. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173977. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  173978. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  173979. */
  173980. tmp10 = tmp0 + tmp3;
  173981. tmp13 = tmp0 - tmp3;
  173982. tmp11 = tmp1 + tmp2;
  173983. tmp12 = tmp1 - tmp2;
  173984. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  173985. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  173986. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  173987. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  173988. CONST_BITS+PASS1_BITS);
  173989. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  173990. CONST_BITS+PASS1_BITS);
  173991. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  173992. * cK represents cos(K*pi/16).
  173993. * i0..i3 in the paper are tmp4..tmp7 here.
  173994. */
  173995. z1 = tmp4 + tmp7;
  173996. z2 = tmp5 + tmp6;
  173997. z3 = tmp4 + tmp6;
  173998. z4 = tmp5 + tmp7;
  173999. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174000. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174001. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174002. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174003. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174004. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174005. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174006. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174007. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174008. z3 += z5;
  174009. z4 += z5;
  174010. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174011. CONST_BITS+PASS1_BITS);
  174012. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174013. CONST_BITS+PASS1_BITS);
  174014. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174015. CONST_BITS+PASS1_BITS);
  174016. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174017. CONST_BITS+PASS1_BITS);
  174018. dataptr++; /* advance pointer to next column */
  174019. }
  174020. }
  174021. #endif /* DCT_ISLOW_SUPPORTED */
  174022. /*** End of inlined file: jfdctint.c ***/
  174023. #undef CONST_BITS
  174024. #undef MULTIPLY
  174025. #undef FIX_0_541196100
  174026. /*** Start of inlined file: jfdctfst.c ***/
  174027. #define JPEG_INTERNALS
  174028. #ifdef DCT_IFAST_SUPPORTED
  174029. /*
  174030. * This module is specialized to the case DCTSIZE = 8.
  174031. */
  174032. #if DCTSIZE != 8
  174033. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174034. #endif
  174035. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174036. * see jfdctint.c for more details. However, we choose to descale
  174037. * (right shift) multiplication products as soon as they are formed,
  174038. * rather than carrying additional fractional bits into subsequent additions.
  174039. * This compromises accuracy slightly, but it lets us save a few shifts.
  174040. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174041. * everywhere except in the multiplications proper; this saves a good deal
  174042. * of work on 16-bit-int machines.
  174043. *
  174044. * Again to save a few shifts, the intermediate results between pass 1 and
  174045. * pass 2 are not upscaled, but are represented only to integral precision.
  174046. *
  174047. * A final compromise is to represent the multiplicative constants to only
  174048. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174049. * machines, and may also reduce the cost of multiplication (since there
  174050. * are fewer one-bits in the constants).
  174051. */
  174052. #define CONST_BITS 8
  174053. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174054. * causing a lot of useless floating-point operations at run time.
  174055. * To get around this we use the following pre-calculated constants.
  174056. * If you change CONST_BITS you may want to add appropriate values.
  174057. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174058. */
  174059. #if CONST_BITS == 8
  174060. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174061. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174062. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174063. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174064. #else
  174065. #define FIX_0_382683433 FIX(0.382683433)
  174066. #define FIX_0_541196100 FIX(0.541196100)
  174067. #define FIX_0_707106781 FIX(0.707106781)
  174068. #define FIX_1_306562965 FIX(1.306562965)
  174069. #endif
  174070. /* We can gain a little more speed, with a further compromise in accuracy,
  174071. * by omitting the addition in a descaling shift. This yields an incorrectly
  174072. * rounded result half the time...
  174073. */
  174074. #ifndef USE_ACCURATE_ROUNDING
  174075. #undef DESCALE
  174076. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174077. #endif
  174078. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174079. * descale to yield a DCTELEM result.
  174080. */
  174081. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174082. /*
  174083. * Perform the forward DCT on one block of samples.
  174084. */
  174085. GLOBAL(void)
  174086. jpeg_fdct_ifast (DCTELEM * data)
  174087. {
  174088. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174089. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174090. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174091. DCTELEM *dataptr;
  174092. int ctr;
  174093. SHIFT_TEMPS
  174094. /* Pass 1: process rows. */
  174095. dataptr = data;
  174096. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174097. tmp0 = dataptr[0] + dataptr[7];
  174098. tmp7 = dataptr[0] - dataptr[7];
  174099. tmp1 = dataptr[1] + dataptr[6];
  174100. tmp6 = dataptr[1] - dataptr[6];
  174101. tmp2 = dataptr[2] + dataptr[5];
  174102. tmp5 = dataptr[2] - dataptr[5];
  174103. tmp3 = dataptr[3] + dataptr[4];
  174104. tmp4 = dataptr[3] - dataptr[4];
  174105. /* Even part */
  174106. tmp10 = tmp0 + tmp3; /* phase 2 */
  174107. tmp13 = tmp0 - tmp3;
  174108. tmp11 = tmp1 + tmp2;
  174109. tmp12 = tmp1 - tmp2;
  174110. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174111. dataptr[4] = tmp10 - tmp11;
  174112. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174113. dataptr[2] = tmp13 + z1; /* phase 5 */
  174114. dataptr[6] = tmp13 - z1;
  174115. /* Odd part */
  174116. tmp10 = tmp4 + tmp5; /* phase 2 */
  174117. tmp11 = tmp5 + tmp6;
  174118. tmp12 = tmp6 + tmp7;
  174119. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174120. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174121. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174122. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174123. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174124. z11 = tmp7 + z3; /* phase 5 */
  174125. z13 = tmp7 - z3;
  174126. dataptr[5] = z13 + z2; /* phase 6 */
  174127. dataptr[3] = z13 - z2;
  174128. dataptr[1] = z11 + z4;
  174129. dataptr[7] = z11 - z4;
  174130. dataptr += DCTSIZE; /* advance pointer to next row */
  174131. }
  174132. /* Pass 2: process columns. */
  174133. dataptr = data;
  174134. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174135. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174136. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174137. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174138. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174139. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174140. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174141. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174142. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174143. /* Even part */
  174144. tmp10 = tmp0 + tmp3; /* phase 2 */
  174145. tmp13 = tmp0 - tmp3;
  174146. tmp11 = tmp1 + tmp2;
  174147. tmp12 = tmp1 - tmp2;
  174148. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174149. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174150. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174151. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174152. dataptr[DCTSIZE*6] = tmp13 - z1;
  174153. /* Odd part */
  174154. tmp10 = tmp4 + tmp5; /* phase 2 */
  174155. tmp11 = tmp5 + tmp6;
  174156. tmp12 = tmp6 + tmp7;
  174157. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174158. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174159. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174160. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174161. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174162. z11 = tmp7 + z3; /* phase 5 */
  174163. z13 = tmp7 - z3;
  174164. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174165. dataptr[DCTSIZE*3] = z13 - z2;
  174166. dataptr[DCTSIZE*1] = z11 + z4;
  174167. dataptr[DCTSIZE*7] = z11 - z4;
  174168. dataptr++; /* advance pointer to next column */
  174169. }
  174170. }
  174171. #endif /* DCT_IFAST_SUPPORTED */
  174172. /*** End of inlined file: jfdctfst.c ***/
  174173. #undef FIX_0_541196100
  174174. /*** Start of inlined file: jidctflt.c ***/
  174175. #define JPEG_INTERNALS
  174176. #ifdef DCT_FLOAT_SUPPORTED
  174177. /*
  174178. * This module is specialized to the case DCTSIZE = 8.
  174179. */
  174180. #if DCTSIZE != 8
  174181. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174182. #endif
  174183. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174184. * entry; produce a float result.
  174185. */
  174186. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174187. /*
  174188. * Perform dequantization and inverse DCT on one block of coefficients.
  174189. */
  174190. GLOBAL(void)
  174191. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174192. JCOEFPTR coef_block,
  174193. JSAMPARRAY output_buf, JDIMENSION output_col)
  174194. {
  174195. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174196. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174197. FAST_FLOAT z5, z10, z11, z12, z13;
  174198. JCOEFPTR inptr;
  174199. FLOAT_MULT_TYPE * quantptr;
  174200. FAST_FLOAT * wsptr;
  174201. JSAMPROW outptr;
  174202. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174203. int ctr;
  174204. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174205. SHIFT_TEMPS
  174206. /* Pass 1: process columns from input, store into work array. */
  174207. inptr = coef_block;
  174208. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174209. wsptr = workspace;
  174210. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174211. /* Due to quantization, we will usually find that many of the input
  174212. * coefficients are zero, especially the AC terms. We can exploit this
  174213. * by short-circuiting the IDCT calculation for any column in which all
  174214. * the AC terms are zero. In that case each output is equal to the
  174215. * DC coefficient (with scale factor as needed).
  174216. * With typical images and quantization tables, half or more of the
  174217. * column DCT calculations can be simplified this way.
  174218. */
  174219. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174220. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174221. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174222. inptr[DCTSIZE*7] == 0) {
  174223. /* AC terms all zero */
  174224. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174225. wsptr[DCTSIZE*0] = dcval;
  174226. wsptr[DCTSIZE*1] = dcval;
  174227. wsptr[DCTSIZE*2] = dcval;
  174228. wsptr[DCTSIZE*3] = dcval;
  174229. wsptr[DCTSIZE*4] = dcval;
  174230. wsptr[DCTSIZE*5] = dcval;
  174231. wsptr[DCTSIZE*6] = dcval;
  174232. wsptr[DCTSIZE*7] = dcval;
  174233. inptr++; /* advance pointers to next column */
  174234. quantptr++;
  174235. wsptr++;
  174236. continue;
  174237. }
  174238. /* Even part */
  174239. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174240. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174241. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174242. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174243. tmp10 = tmp0 + tmp2; /* phase 3 */
  174244. tmp11 = tmp0 - tmp2;
  174245. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174246. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174247. tmp0 = tmp10 + tmp13; /* phase 2 */
  174248. tmp3 = tmp10 - tmp13;
  174249. tmp1 = tmp11 + tmp12;
  174250. tmp2 = tmp11 - tmp12;
  174251. /* Odd part */
  174252. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174253. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174254. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174255. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174256. z13 = tmp6 + tmp5; /* phase 6 */
  174257. z10 = tmp6 - tmp5;
  174258. z11 = tmp4 + tmp7;
  174259. z12 = tmp4 - tmp7;
  174260. tmp7 = z11 + z13; /* phase 5 */
  174261. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174262. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174263. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174264. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174265. tmp6 = tmp12 - tmp7; /* phase 2 */
  174266. tmp5 = tmp11 - tmp6;
  174267. tmp4 = tmp10 + tmp5;
  174268. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174269. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174270. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174271. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174272. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  174273. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  174274. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  174275. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  174276. inptr++; /* advance pointers to next column */
  174277. quantptr++;
  174278. wsptr++;
  174279. }
  174280. /* Pass 2: process rows from work array, store into output array. */
  174281. /* Note that we must descale the results by a factor of 8 == 2**3. */
  174282. wsptr = workspace;
  174283. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174284. outptr = output_buf[ctr] + output_col;
  174285. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174286. * However, the column calculation has created many nonzero AC terms, so
  174287. * the simplification applies less often (typically 5% to 10% of the time).
  174288. * And testing floats for zero is relatively expensive, so we don't bother.
  174289. */
  174290. /* Even part */
  174291. tmp10 = wsptr[0] + wsptr[4];
  174292. tmp11 = wsptr[0] - wsptr[4];
  174293. tmp13 = wsptr[2] + wsptr[6];
  174294. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  174295. tmp0 = tmp10 + tmp13;
  174296. tmp3 = tmp10 - tmp13;
  174297. tmp1 = tmp11 + tmp12;
  174298. tmp2 = tmp11 - tmp12;
  174299. /* Odd part */
  174300. z13 = wsptr[5] + wsptr[3];
  174301. z10 = wsptr[5] - wsptr[3];
  174302. z11 = wsptr[1] + wsptr[7];
  174303. z12 = wsptr[1] - wsptr[7];
  174304. tmp7 = z11 + z13;
  174305. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174306. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174307. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174308. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174309. tmp6 = tmp12 - tmp7;
  174310. tmp5 = tmp11 - tmp6;
  174311. tmp4 = tmp10 + tmp5;
  174312. /* Final output stage: scale down by a factor of 8 and range-limit */
  174313. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174314. & RANGE_MASK];
  174315. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174316. & RANGE_MASK];
  174317. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174318. & RANGE_MASK];
  174319. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174320. & RANGE_MASK];
  174321. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174322. & RANGE_MASK];
  174323. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174324. & RANGE_MASK];
  174325. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174326. & RANGE_MASK];
  174327. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174328. & RANGE_MASK];
  174329. wsptr += DCTSIZE; /* advance pointer to next row */
  174330. }
  174331. }
  174332. #endif /* DCT_FLOAT_SUPPORTED */
  174333. /*** End of inlined file: jidctflt.c ***/
  174334. #undef CONST_BITS
  174335. #undef FIX_1_847759065
  174336. #undef MULTIPLY
  174337. #undef DEQUANTIZE
  174338. #undef DESCALE
  174339. /*** Start of inlined file: jidctfst.c ***/
  174340. #define JPEG_INTERNALS
  174341. #ifdef DCT_IFAST_SUPPORTED
  174342. /*
  174343. * This module is specialized to the case DCTSIZE = 8.
  174344. */
  174345. #if DCTSIZE != 8
  174346. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174347. #endif
  174348. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174349. * see jidctint.c for more details. However, we choose to descale
  174350. * (right shift) multiplication products as soon as they are formed,
  174351. * rather than carrying additional fractional bits into subsequent additions.
  174352. * This compromises accuracy slightly, but it lets us save a few shifts.
  174353. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174354. * everywhere except in the multiplications proper; this saves a good deal
  174355. * of work on 16-bit-int machines.
  174356. *
  174357. * The dequantized coefficients are not integers because the AA&N scaling
  174358. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174359. * so that the first and second IDCT rounds have the same input scaling.
  174360. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174361. * avoid a descaling shift; this compromises accuracy rather drastically
  174362. * for small quantization table entries, but it saves a lot of shifts.
  174363. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174364. * so we use a much larger scaling factor to preserve accuracy.
  174365. *
  174366. * A final compromise is to represent the multiplicative constants to only
  174367. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174368. * machines, and may also reduce the cost of multiplication (since there
  174369. * are fewer one-bits in the constants).
  174370. */
  174371. #if BITS_IN_JSAMPLE == 8
  174372. #define CONST_BITS 8
  174373. #define PASS1_BITS 2
  174374. #else
  174375. #define CONST_BITS 8
  174376. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174377. #endif
  174378. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174379. * causing a lot of useless floating-point operations at run time.
  174380. * To get around this we use the following pre-calculated constants.
  174381. * If you change CONST_BITS you may want to add appropriate values.
  174382. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174383. */
  174384. #if CONST_BITS == 8
  174385. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  174386. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  174387. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  174388. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  174389. #else
  174390. #define FIX_1_082392200 FIX(1.082392200)
  174391. #define FIX_1_414213562 FIX(1.414213562)
  174392. #define FIX_1_847759065 FIX(1.847759065)
  174393. #define FIX_2_613125930 FIX(2.613125930)
  174394. #endif
  174395. /* We can gain a little more speed, with a further compromise in accuracy,
  174396. * by omitting the addition in a descaling shift. This yields an incorrectly
  174397. * rounded result half the time...
  174398. */
  174399. #ifndef USE_ACCURATE_ROUNDING
  174400. #undef DESCALE
  174401. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174402. #endif
  174403. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174404. * descale to yield a DCTELEM result.
  174405. */
  174406. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174407. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174408. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  174409. * multiplication will do. For 12-bit data, the multiplier table is
  174410. * declared INT32, so a 32-bit multiply will be used.
  174411. */
  174412. #if BITS_IN_JSAMPLE == 8
  174413. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  174414. #else
  174415. #define DEQUANTIZE(coef,quantval) \
  174416. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  174417. #endif
  174418. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  174419. * We assume that int right shift is unsigned if INT32 right shift is.
  174420. */
  174421. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  174422. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  174423. #if BITS_IN_JSAMPLE == 8
  174424. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  174425. #else
  174426. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  174427. #endif
  174428. #define IRIGHT_SHIFT(x,shft) \
  174429. ((ishift_temp = (x)) < 0 ? \
  174430. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  174431. (ishift_temp >> (shft)))
  174432. #else
  174433. #define ISHIFT_TEMPS
  174434. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  174435. #endif
  174436. #ifdef USE_ACCURATE_ROUNDING
  174437. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  174438. #else
  174439. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  174440. #endif
  174441. /*
  174442. * Perform dequantization and inverse DCT on one block of coefficients.
  174443. */
  174444. GLOBAL(void)
  174445. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174446. JCOEFPTR coef_block,
  174447. JSAMPARRAY output_buf, JDIMENSION output_col)
  174448. {
  174449. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174450. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174451. DCTELEM z5, z10, z11, z12, z13;
  174452. JCOEFPTR inptr;
  174453. IFAST_MULT_TYPE * quantptr;
  174454. int * wsptr;
  174455. JSAMPROW outptr;
  174456. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174457. int ctr;
  174458. int workspace[DCTSIZE2]; /* buffers data between passes */
  174459. SHIFT_TEMPS /* for DESCALE */
  174460. ISHIFT_TEMPS /* for IDESCALE */
  174461. /* Pass 1: process columns from input, store into work array. */
  174462. inptr = coef_block;
  174463. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  174464. wsptr = workspace;
  174465. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174466. /* Due to quantization, we will usually find that many of the input
  174467. * coefficients are zero, especially the AC terms. We can exploit this
  174468. * by short-circuiting the IDCT calculation for any column in which all
  174469. * the AC terms are zero. In that case each output is equal to the
  174470. * DC coefficient (with scale factor as needed).
  174471. * With typical images and quantization tables, half or more of the
  174472. * column DCT calculations can be simplified this way.
  174473. */
  174474. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174475. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174476. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174477. inptr[DCTSIZE*7] == 0) {
  174478. /* AC terms all zero */
  174479. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174480. wsptr[DCTSIZE*0] = dcval;
  174481. wsptr[DCTSIZE*1] = dcval;
  174482. wsptr[DCTSIZE*2] = dcval;
  174483. wsptr[DCTSIZE*3] = dcval;
  174484. wsptr[DCTSIZE*4] = dcval;
  174485. wsptr[DCTSIZE*5] = dcval;
  174486. wsptr[DCTSIZE*6] = dcval;
  174487. wsptr[DCTSIZE*7] = dcval;
  174488. inptr++; /* advance pointers to next column */
  174489. quantptr++;
  174490. wsptr++;
  174491. continue;
  174492. }
  174493. /* Even part */
  174494. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174495. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174496. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174497. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174498. tmp10 = tmp0 + tmp2; /* phase 3 */
  174499. tmp11 = tmp0 - tmp2;
  174500. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174501. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  174502. tmp0 = tmp10 + tmp13; /* phase 2 */
  174503. tmp3 = tmp10 - tmp13;
  174504. tmp1 = tmp11 + tmp12;
  174505. tmp2 = tmp11 - tmp12;
  174506. /* Odd part */
  174507. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174508. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174509. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174510. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174511. z13 = tmp6 + tmp5; /* phase 6 */
  174512. z10 = tmp6 - tmp5;
  174513. z11 = tmp4 + tmp7;
  174514. z12 = tmp4 - tmp7;
  174515. tmp7 = z11 + z13; /* phase 5 */
  174516. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174517. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174518. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174519. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174520. tmp6 = tmp12 - tmp7; /* phase 2 */
  174521. tmp5 = tmp11 - tmp6;
  174522. tmp4 = tmp10 + tmp5;
  174523. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  174524. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  174525. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  174526. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  174527. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  174528. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  174529. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  174530. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  174531. inptr++; /* advance pointers to next column */
  174532. quantptr++;
  174533. wsptr++;
  174534. }
  174535. /* Pass 2: process rows from work array, store into output array. */
  174536. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174537. /* and also undo the PASS1_BITS scaling. */
  174538. wsptr = workspace;
  174539. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174540. outptr = output_buf[ctr] + output_col;
  174541. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174542. * However, the column calculation has created many nonzero AC terms, so
  174543. * the simplification applies less often (typically 5% to 10% of the time).
  174544. * On machines with very fast multiplication, it's possible that the
  174545. * test takes more time than it's worth. In that case this section
  174546. * may be commented out.
  174547. */
  174548. #ifndef NO_ZERO_ROW_TEST
  174549. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174550. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174551. /* AC terms all zero */
  174552. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  174553. & RANGE_MASK];
  174554. outptr[0] = dcval;
  174555. outptr[1] = dcval;
  174556. outptr[2] = dcval;
  174557. outptr[3] = dcval;
  174558. outptr[4] = dcval;
  174559. outptr[5] = dcval;
  174560. outptr[6] = dcval;
  174561. outptr[7] = dcval;
  174562. wsptr += DCTSIZE; /* advance pointer to next row */
  174563. continue;
  174564. }
  174565. #endif
  174566. /* Even part */
  174567. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  174568. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  174569. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  174570. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  174571. - tmp13;
  174572. tmp0 = tmp10 + tmp13;
  174573. tmp3 = tmp10 - tmp13;
  174574. tmp1 = tmp11 + tmp12;
  174575. tmp2 = tmp11 - tmp12;
  174576. /* Odd part */
  174577. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  174578. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  174579. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  174580. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  174581. tmp7 = z11 + z13; /* phase 5 */
  174582. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174583. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174584. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174585. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174586. tmp6 = tmp12 - tmp7; /* phase 2 */
  174587. tmp5 = tmp11 - tmp6;
  174588. tmp4 = tmp10 + tmp5;
  174589. /* Final output stage: scale down by a factor of 8 and range-limit */
  174590. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  174591. & RANGE_MASK];
  174592. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  174593. & RANGE_MASK];
  174594. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  174595. & RANGE_MASK];
  174596. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  174597. & RANGE_MASK];
  174598. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  174599. & RANGE_MASK];
  174600. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  174601. & RANGE_MASK];
  174602. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  174603. & RANGE_MASK];
  174604. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  174605. & RANGE_MASK];
  174606. wsptr += DCTSIZE; /* advance pointer to next row */
  174607. }
  174608. }
  174609. #endif /* DCT_IFAST_SUPPORTED */
  174610. /*** End of inlined file: jidctfst.c ***/
  174611. #undef CONST_BITS
  174612. #undef FIX_1_847759065
  174613. #undef MULTIPLY
  174614. #undef DEQUANTIZE
  174615. /*** Start of inlined file: jidctint.c ***/
  174616. #define JPEG_INTERNALS
  174617. #ifdef DCT_ISLOW_SUPPORTED
  174618. /*
  174619. * This module is specialized to the case DCTSIZE = 8.
  174620. */
  174621. #if DCTSIZE != 8
  174622. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174623. #endif
  174624. /*
  174625. * The poop on this scaling stuff is as follows:
  174626. *
  174627. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  174628. * larger than the true IDCT outputs. The final outputs are therefore
  174629. * a factor of N larger than desired; since N=8 this can be cured by
  174630. * a simple right shift at the end of the algorithm. The advantage of
  174631. * this arrangement is that we save two multiplications per 1-D IDCT,
  174632. * because the y0 and y4 inputs need not be divided by sqrt(N).
  174633. *
  174634. * We have to do addition and subtraction of the integer inputs, which
  174635. * is no problem, and multiplication by fractional constants, which is
  174636. * a problem to do in integer arithmetic. We multiply all the constants
  174637. * by CONST_SCALE and convert them to integer constants (thus retaining
  174638. * CONST_BITS bits of precision in the constants). After doing a
  174639. * multiplication we have to divide the product by CONST_SCALE, with proper
  174640. * rounding, to produce the correct output. This division can be done
  174641. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174642. * as long as possible so that partial sums can be added together with
  174643. * full fractional precision.
  174644. *
  174645. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174646. * they are represented to better-than-integral precision. These outputs
  174647. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174648. * with the recommended scaling. (To scale up 12-bit sample data further, an
  174649. * intermediate INT32 array would be needed.)
  174650. *
  174651. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174652. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174653. * shows that the values given below are the most effective.
  174654. */
  174655. #if BITS_IN_JSAMPLE == 8
  174656. #define CONST_BITS 13
  174657. #define PASS1_BITS 2
  174658. #else
  174659. #define CONST_BITS 13
  174660. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174661. #endif
  174662. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174663. * causing a lot of useless floating-point operations at run time.
  174664. * To get around this we use the following pre-calculated constants.
  174665. * If you change CONST_BITS you may want to add appropriate values.
  174666. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174667. */
  174668. #if CONST_BITS == 13
  174669. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174670. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174671. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174672. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174673. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174674. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174675. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174676. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174677. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174678. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174679. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174680. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174681. #else
  174682. #define FIX_0_298631336 FIX(0.298631336)
  174683. #define FIX_0_390180644 FIX(0.390180644)
  174684. #define FIX_0_541196100 FIX(0.541196100)
  174685. #define FIX_0_765366865 FIX(0.765366865)
  174686. #define FIX_0_899976223 FIX(0.899976223)
  174687. #define FIX_1_175875602 FIX(1.175875602)
  174688. #define FIX_1_501321110 FIX(1.501321110)
  174689. #define FIX_1_847759065 FIX(1.847759065)
  174690. #define FIX_1_961570560 FIX(1.961570560)
  174691. #define FIX_2_053119869 FIX(2.053119869)
  174692. #define FIX_2_562915447 FIX(2.562915447)
  174693. #define FIX_3_072711026 FIX(3.072711026)
  174694. #endif
  174695. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174696. * For 8-bit samples with the recommended scaling, all the variable
  174697. * and constant values involved are no more than 16 bits wide, so a
  174698. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174699. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174700. */
  174701. #if BITS_IN_JSAMPLE == 8
  174702. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174703. #else
  174704. #define MULTIPLY(var,const) ((var) * (const))
  174705. #endif
  174706. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174707. * entry; produce an int result. In this module, both inputs and result
  174708. * are 16 bits or less, so either int or short multiply will work.
  174709. */
  174710. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  174711. /*
  174712. * Perform dequantization and inverse DCT on one block of coefficients.
  174713. */
  174714. GLOBAL(void)
  174715. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174716. JCOEFPTR coef_block,
  174717. JSAMPARRAY output_buf, JDIMENSION output_col)
  174718. {
  174719. INT32 tmp0, tmp1, tmp2, tmp3;
  174720. INT32 tmp10, tmp11, tmp12, tmp13;
  174721. INT32 z1, z2, z3, z4, z5;
  174722. JCOEFPTR inptr;
  174723. ISLOW_MULT_TYPE * quantptr;
  174724. int * wsptr;
  174725. JSAMPROW outptr;
  174726. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174727. int ctr;
  174728. int workspace[DCTSIZE2]; /* buffers data between passes */
  174729. SHIFT_TEMPS
  174730. /* Pass 1: process columns from input, store into work array. */
  174731. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  174732. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174733. inptr = coef_block;
  174734. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174735. wsptr = workspace;
  174736. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174737. /* Due to quantization, we will usually find that many of the input
  174738. * coefficients are zero, especially the AC terms. We can exploit this
  174739. * by short-circuiting the IDCT calculation for any column in which all
  174740. * the AC terms are zero. In that case each output is equal to the
  174741. * DC coefficient (with scale factor as needed).
  174742. * With typical images and quantization tables, half or more of the
  174743. * column DCT calculations can be simplified this way.
  174744. */
  174745. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174746. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174747. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174748. inptr[DCTSIZE*7] == 0) {
  174749. /* AC terms all zero */
  174750. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  174751. wsptr[DCTSIZE*0] = dcval;
  174752. wsptr[DCTSIZE*1] = dcval;
  174753. wsptr[DCTSIZE*2] = dcval;
  174754. wsptr[DCTSIZE*3] = dcval;
  174755. wsptr[DCTSIZE*4] = dcval;
  174756. wsptr[DCTSIZE*5] = dcval;
  174757. wsptr[DCTSIZE*6] = dcval;
  174758. wsptr[DCTSIZE*7] = dcval;
  174759. inptr++; /* advance pointers to next column */
  174760. quantptr++;
  174761. wsptr++;
  174762. continue;
  174763. }
  174764. /* Even part: reverse the even part of the forward DCT. */
  174765. /* The rotator is sqrt(2)*c(-6). */
  174766. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174767. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174768. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  174769. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  174770. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  174771. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174772. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174773. tmp0 = (z2 + z3) << CONST_BITS;
  174774. tmp1 = (z2 - z3) << CONST_BITS;
  174775. tmp10 = tmp0 + tmp3;
  174776. tmp13 = tmp0 - tmp3;
  174777. tmp11 = tmp1 + tmp2;
  174778. tmp12 = tmp1 - tmp2;
  174779. /* Odd part per figure 8; the matrix is unitary and hence its
  174780. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  174781. */
  174782. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174783. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174784. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174785. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174786. z1 = tmp0 + tmp3;
  174787. z2 = tmp1 + tmp2;
  174788. z3 = tmp0 + tmp2;
  174789. z4 = tmp1 + tmp3;
  174790. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174791. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174792. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174793. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174794. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174795. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174796. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174797. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174798. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174799. z3 += z5;
  174800. z4 += z5;
  174801. tmp0 += z1 + z3;
  174802. tmp1 += z2 + z4;
  174803. tmp2 += z2 + z3;
  174804. tmp3 += z1 + z4;
  174805. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  174806. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  174807. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  174808. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  174809. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  174810. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  174811. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  174812. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  174813. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  174814. inptr++; /* advance pointers to next column */
  174815. quantptr++;
  174816. wsptr++;
  174817. }
  174818. /* Pass 2: process rows from work array, store into output array. */
  174819. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174820. /* and also undo the PASS1_BITS scaling. */
  174821. wsptr = workspace;
  174822. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174823. outptr = output_buf[ctr] + output_col;
  174824. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174825. * However, the column calculation has created many nonzero AC terms, so
  174826. * the simplification applies less often (typically 5% to 10% of the time).
  174827. * On machines with very fast multiplication, it's possible that the
  174828. * test takes more time than it's worth. In that case this section
  174829. * may be commented out.
  174830. */
  174831. #ifndef NO_ZERO_ROW_TEST
  174832. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174833. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174834. /* AC terms all zero */
  174835. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  174836. & RANGE_MASK];
  174837. outptr[0] = dcval;
  174838. outptr[1] = dcval;
  174839. outptr[2] = dcval;
  174840. outptr[3] = dcval;
  174841. outptr[4] = dcval;
  174842. outptr[5] = dcval;
  174843. outptr[6] = dcval;
  174844. outptr[7] = dcval;
  174845. wsptr += DCTSIZE; /* advance pointer to next row */
  174846. continue;
  174847. }
  174848. #endif
  174849. /* Even part: reverse the even part of the forward DCT. */
  174850. /* The rotator is sqrt(2)*c(-6). */
  174851. z2 = (INT32) wsptr[2];
  174852. z3 = (INT32) wsptr[6];
  174853. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  174854. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  174855. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  174856. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  174857. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  174858. tmp10 = tmp0 + tmp3;
  174859. tmp13 = tmp0 - tmp3;
  174860. tmp11 = tmp1 + tmp2;
  174861. tmp12 = tmp1 - tmp2;
  174862. /* Odd part per figure 8; the matrix is unitary and hence its
  174863. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  174864. */
  174865. tmp0 = (INT32) wsptr[7];
  174866. tmp1 = (INT32) wsptr[5];
  174867. tmp2 = (INT32) wsptr[3];
  174868. tmp3 = (INT32) wsptr[1];
  174869. z1 = tmp0 + tmp3;
  174870. z2 = tmp1 + tmp2;
  174871. z3 = tmp0 + tmp2;
  174872. z4 = tmp1 + tmp3;
  174873. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174874. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174875. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174876. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174877. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174878. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174879. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174880. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174881. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174882. z3 += z5;
  174883. z4 += z5;
  174884. tmp0 += z1 + z3;
  174885. tmp1 += z2 + z4;
  174886. tmp2 += z2 + z3;
  174887. tmp3 += z1 + z4;
  174888. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  174889. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  174890. CONST_BITS+PASS1_BITS+3)
  174891. & RANGE_MASK];
  174892. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  174893. CONST_BITS+PASS1_BITS+3)
  174894. & RANGE_MASK];
  174895. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  174896. CONST_BITS+PASS1_BITS+3)
  174897. & RANGE_MASK];
  174898. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  174899. CONST_BITS+PASS1_BITS+3)
  174900. & RANGE_MASK];
  174901. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  174902. CONST_BITS+PASS1_BITS+3)
  174903. & RANGE_MASK];
  174904. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  174905. CONST_BITS+PASS1_BITS+3)
  174906. & RANGE_MASK];
  174907. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  174908. CONST_BITS+PASS1_BITS+3)
  174909. & RANGE_MASK];
  174910. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  174911. CONST_BITS+PASS1_BITS+3)
  174912. & RANGE_MASK];
  174913. wsptr += DCTSIZE; /* advance pointer to next row */
  174914. }
  174915. }
  174916. #endif /* DCT_ISLOW_SUPPORTED */
  174917. /*** End of inlined file: jidctint.c ***/
  174918. /*** Start of inlined file: jidctred.c ***/
  174919. #define JPEG_INTERNALS
  174920. #ifdef IDCT_SCALING_SUPPORTED
  174921. /*
  174922. * This module is specialized to the case DCTSIZE = 8.
  174923. */
  174924. #if DCTSIZE != 8
  174925. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174926. #endif
  174927. /* Scaling is the same as in jidctint.c. */
  174928. #if BITS_IN_JSAMPLE == 8
  174929. #define CONST_BITS 13
  174930. #define PASS1_BITS 2
  174931. #else
  174932. #define CONST_BITS 13
  174933. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174934. #endif
  174935. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174936. * causing a lot of useless floating-point operations at run time.
  174937. * To get around this we use the following pre-calculated constants.
  174938. * If you change CONST_BITS you may want to add appropriate values.
  174939. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174940. */
  174941. #if CONST_BITS == 13
  174942. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  174943. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  174944. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  174945. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  174946. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174947. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  174948. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174949. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  174950. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  174951. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  174952. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174953. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  174954. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174955. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  174956. #else
  174957. #define FIX_0_211164243 FIX(0.211164243)
  174958. #define FIX_0_509795579 FIX(0.509795579)
  174959. #define FIX_0_601344887 FIX(0.601344887)
  174960. #define FIX_0_720959822 FIX(0.720959822)
  174961. #define FIX_0_765366865 FIX(0.765366865)
  174962. #define FIX_0_850430095 FIX(0.850430095)
  174963. #define FIX_0_899976223 FIX(0.899976223)
  174964. #define FIX_1_061594337 FIX(1.061594337)
  174965. #define FIX_1_272758580 FIX(1.272758580)
  174966. #define FIX_1_451774981 FIX(1.451774981)
  174967. #define FIX_1_847759065 FIX(1.847759065)
  174968. #define FIX_2_172734803 FIX(2.172734803)
  174969. #define FIX_2_562915447 FIX(2.562915447)
  174970. #define FIX_3_624509785 FIX(3.624509785)
  174971. #endif
  174972. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174973. * For 8-bit samples with the recommended scaling, all the variable
  174974. * and constant values involved are no more than 16 bits wide, so a
  174975. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174976. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174977. */
  174978. #if BITS_IN_JSAMPLE == 8
  174979. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174980. #else
  174981. #define MULTIPLY(var,const) ((var) * (const))
  174982. #endif
  174983. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174984. * entry; produce an int result. In this module, both inputs and result
  174985. * are 16 bits or less, so either int or short multiply will work.
  174986. */
  174987. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  174988. /*
  174989. * Perform dequantization and inverse DCT on one block of coefficients,
  174990. * producing a reduced-size 4x4 output block.
  174991. */
  174992. GLOBAL(void)
  174993. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174994. JCOEFPTR coef_block,
  174995. JSAMPARRAY output_buf, JDIMENSION output_col)
  174996. {
  174997. INT32 tmp0, tmp2, tmp10, tmp12;
  174998. INT32 z1, z2, z3, z4;
  174999. JCOEFPTR inptr;
  175000. ISLOW_MULT_TYPE * quantptr;
  175001. int * wsptr;
  175002. JSAMPROW outptr;
  175003. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175004. int ctr;
  175005. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175006. SHIFT_TEMPS
  175007. /* Pass 1: process columns from input, store into work array. */
  175008. inptr = coef_block;
  175009. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175010. wsptr = workspace;
  175011. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175012. /* Don't bother to process column 4, because second pass won't use it */
  175013. if (ctr == DCTSIZE-4)
  175014. continue;
  175015. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175016. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175017. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175018. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175019. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175020. wsptr[DCTSIZE*0] = dcval;
  175021. wsptr[DCTSIZE*1] = dcval;
  175022. wsptr[DCTSIZE*2] = dcval;
  175023. wsptr[DCTSIZE*3] = dcval;
  175024. continue;
  175025. }
  175026. /* Even part */
  175027. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175028. tmp0 <<= (CONST_BITS+1);
  175029. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175030. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175031. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175032. tmp10 = tmp0 + tmp2;
  175033. tmp12 = tmp0 - tmp2;
  175034. /* Odd part */
  175035. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175036. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175037. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175038. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175039. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175040. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175041. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175042. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175043. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175044. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175045. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175046. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175047. /* Final output stage */
  175048. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175049. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175050. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175051. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175052. }
  175053. /* Pass 2: process 4 rows from work array, store into output array. */
  175054. wsptr = workspace;
  175055. for (ctr = 0; ctr < 4; ctr++) {
  175056. outptr = output_buf[ctr] + output_col;
  175057. /* It's not clear whether a zero row test is worthwhile here ... */
  175058. #ifndef NO_ZERO_ROW_TEST
  175059. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175060. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175061. /* AC terms all zero */
  175062. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175063. & RANGE_MASK];
  175064. outptr[0] = dcval;
  175065. outptr[1] = dcval;
  175066. outptr[2] = dcval;
  175067. outptr[3] = dcval;
  175068. wsptr += DCTSIZE; /* advance pointer to next row */
  175069. continue;
  175070. }
  175071. #endif
  175072. /* Even part */
  175073. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175074. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175075. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175076. tmp10 = tmp0 + tmp2;
  175077. tmp12 = tmp0 - tmp2;
  175078. /* Odd part */
  175079. z1 = (INT32) wsptr[7];
  175080. z2 = (INT32) wsptr[5];
  175081. z3 = (INT32) wsptr[3];
  175082. z4 = (INT32) wsptr[1];
  175083. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175084. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175085. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175086. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175087. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175088. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175089. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175090. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175091. /* Final output stage */
  175092. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175093. CONST_BITS+PASS1_BITS+3+1)
  175094. & RANGE_MASK];
  175095. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175096. CONST_BITS+PASS1_BITS+3+1)
  175097. & RANGE_MASK];
  175098. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175099. CONST_BITS+PASS1_BITS+3+1)
  175100. & RANGE_MASK];
  175101. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175102. CONST_BITS+PASS1_BITS+3+1)
  175103. & RANGE_MASK];
  175104. wsptr += DCTSIZE; /* advance pointer to next row */
  175105. }
  175106. }
  175107. /*
  175108. * Perform dequantization and inverse DCT on one block of coefficients,
  175109. * producing a reduced-size 2x2 output block.
  175110. */
  175111. GLOBAL(void)
  175112. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175113. JCOEFPTR coef_block,
  175114. JSAMPARRAY output_buf, JDIMENSION output_col)
  175115. {
  175116. INT32 tmp0, tmp10, z1;
  175117. JCOEFPTR inptr;
  175118. ISLOW_MULT_TYPE * quantptr;
  175119. int * wsptr;
  175120. JSAMPROW outptr;
  175121. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175122. int ctr;
  175123. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175124. SHIFT_TEMPS
  175125. /* Pass 1: process columns from input, store into work array. */
  175126. inptr = coef_block;
  175127. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175128. wsptr = workspace;
  175129. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175130. /* Don't bother to process columns 2,4,6 */
  175131. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175132. continue;
  175133. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175134. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175135. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175136. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175137. wsptr[DCTSIZE*0] = dcval;
  175138. wsptr[DCTSIZE*1] = dcval;
  175139. continue;
  175140. }
  175141. /* Even part */
  175142. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175143. tmp10 = z1 << (CONST_BITS+2);
  175144. /* Odd part */
  175145. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175146. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175147. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175148. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175149. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175150. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175151. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175152. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175153. /* Final output stage */
  175154. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175155. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175156. }
  175157. /* Pass 2: process 2 rows from work array, store into output array. */
  175158. wsptr = workspace;
  175159. for (ctr = 0; ctr < 2; ctr++) {
  175160. outptr = output_buf[ctr] + output_col;
  175161. /* It's not clear whether a zero row test is worthwhile here ... */
  175162. #ifndef NO_ZERO_ROW_TEST
  175163. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175164. /* AC terms all zero */
  175165. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175166. & RANGE_MASK];
  175167. outptr[0] = dcval;
  175168. outptr[1] = dcval;
  175169. wsptr += DCTSIZE; /* advance pointer to next row */
  175170. continue;
  175171. }
  175172. #endif
  175173. /* Even part */
  175174. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175175. /* Odd part */
  175176. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175177. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175178. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175179. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175180. /* Final output stage */
  175181. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175182. CONST_BITS+PASS1_BITS+3+2)
  175183. & RANGE_MASK];
  175184. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175185. CONST_BITS+PASS1_BITS+3+2)
  175186. & RANGE_MASK];
  175187. wsptr += DCTSIZE; /* advance pointer to next row */
  175188. }
  175189. }
  175190. /*
  175191. * Perform dequantization and inverse DCT on one block of coefficients,
  175192. * producing a reduced-size 1x1 output block.
  175193. */
  175194. GLOBAL(void)
  175195. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175196. JCOEFPTR coef_block,
  175197. JSAMPARRAY output_buf, JDIMENSION output_col)
  175198. {
  175199. int dcval;
  175200. ISLOW_MULT_TYPE * quantptr;
  175201. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175202. SHIFT_TEMPS
  175203. /* We hardly need an inverse DCT routine for this: just take the
  175204. * average pixel value, which is one-eighth of the DC coefficient.
  175205. */
  175206. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175207. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175208. dcval = (int) DESCALE((INT32) dcval, 3);
  175209. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175210. }
  175211. #endif /* IDCT_SCALING_SUPPORTED */
  175212. /*** End of inlined file: jidctred.c ***/
  175213. /*** Start of inlined file: jmemmgr.c ***/
  175214. #define JPEG_INTERNALS
  175215. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175216. /*** Start of inlined file: jmemsys.h ***/
  175217. #ifndef __jmemsys_h__
  175218. #define __jmemsys_h__
  175219. /* Short forms of external names for systems with brain-damaged linkers. */
  175220. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175221. #define jpeg_get_small jGetSmall
  175222. #define jpeg_free_small jFreeSmall
  175223. #define jpeg_get_large jGetLarge
  175224. #define jpeg_free_large jFreeLarge
  175225. #define jpeg_mem_available jMemAvail
  175226. #define jpeg_open_backing_store jOpenBackStore
  175227. #define jpeg_mem_init jMemInit
  175228. #define jpeg_mem_term jMemTerm
  175229. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175230. /*
  175231. * These two functions are used to allocate and release small chunks of
  175232. * memory. (Typically the total amount requested through jpeg_get_small is
  175233. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175234. * Behavior should be the same as for the standard library functions malloc
  175235. * and free; in particular, jpeg_get_small must return NULL on failure.
  175236. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175237. * size of the object being freed, just in case it's needed.
  175238. * On an 80x86 machine using small-data memory model, these manage near heap.
  175239. */
  175240. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175241. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175242. size_t sizeofobject));
  175243. /*
  175244. * These two functions are used to allocate and release large chunks of
  175245. * memory (up to the total free space designated by jpeg_mem_available).
  175246. * The interface is the same as above, except that on an 80x86 machine,
  175247. * far pointers are used. On most other machines these are identical to
  175248. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175249. * in case a different allocation strategy is desirable for large chunks.
  175250. */
  175251. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175252. size_t sizeofobject));
  175253. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175254. size_t sizeofobject));
  175255. /*
  175256. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175257. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175258. * matter, but that case should never come into play). This macro is needed
  175259. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175260. * On those machines, we expect that jconfig.h will provide a proper value.
  175261. * On machines with 32-bit flat address spaces, any large constant may be used.
  175262. *
  175263. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175264. * size_t and will be a multiple of sizeof(align_type).
  175265. */
  175266. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175267. #define MAX_ALLOC_CHUNK 1000000000L
  175268. #endif
  175269. /*
  175270. * This routine computes the total space still available for allocation by
  175271. * jpeg_get_large. If more space than this is needed, backing store will be
  175272. * used. NOTE: any memory already allocated must not be counted.
  175273. *
  175274. * There is a minimum space requirement, corresponding to the minimum
  175275. * feasible buffer sizes; jmemmgr.c will request that much space even if
  175276. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  175277. * all working storage in memory, is also passed in case it is useful.
  175278. * Finally, the total space already allocated is passed. If no better
  175279. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  175280. * is often a suitable calculation.
  175281. *
  175282. * It is OK for jpeg_mem_available to underestimate the space available
  175283. * (that'll just lead to more backing-store access than is really necessary).
  175284. * However, an overestimate will lead to failure. Hence it's wise to subtract
  175285. * a slop factor from the true available space. 5% should be enough.
  175286. *
  175287. * On machines with lots of virtual memory, any large constant may be returned.
  175288. * Conversely, zero may be returned to always use the minimum amount of memory.
  175289. */
  175290. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  175291. long min_bytes_needed,
  175292. long max_bytes_needed,
  175293. long already_allocated));
  175294. /*
  175295. * This structure holds whatever state is needed to access a single
  175296. * backing-store object. The read/write/close method pointers are called
  175297. * by jmemmgr.c to manipulate the backing-store object; all other fields
  175298. * are private to the system-dependent backing store routines.
  175299. */
  175300. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  175301. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  175302. typedef unsigned short XMSH; /* type of extended-memory handles */
  175303. typedef unsigned short EMSH; /* type of expanded-memory handles */
  175304. typedef union {
  175305. short file_handle; /* DOS file handle if it's a temp file */
  175306. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175307. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175308. } handle_union;
  175309. #endif /* USE_MSDOS_MEMMGR */
  175310. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175311. #include <Files.h>
  175312. #endif /* USE_MAC_MEMMGR */
  175313. //typedef struct backing_store_struct * backing_store_ptr;
  175314. typedef struct backing_store_struct {
  175315. /* Methods for reading/writing/closing this backing-store object */
  175316. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175317. struct backing_store_struct *info,
  175318. void FAR * buffer_address,
  175319. long file_offset, long byte_count));
  175320. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175321. struct backing_store_struct *info,
  175322. void FAR * buffer_address,
  175323. long file_offset, long byte_count));
  175324. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175325. struct backing_store_struct *info));
  175326. /* Private fields for system-dependent backing-store management */
  175327. #ifdef USE_MSDOS_MEMMGR
  175328. /* For the MS-DOS manager (jmemdos.c), we need: */
  175329. handle_union handle; /* reference to backing-store storage object */
  175330. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175331. #else
  175332. #ifdef USE_MAC_MEMMGR
  175333. /* For the Mac manager (jmemmac.c), we need: */
  175334. short temp_file; /* file reference number to temp file */
  175335. FSSpec tempSpec; /* the FSSpec for the temp file */
  175336. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175337. #else
  175338. /* For a typical implementation with temp files, we need: */
  175339. FILE * temp_file; /* stdio reference to temp file */
  175340. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175341. #endif
  175342. #endif
  175343. } backing_store_info;
  175344. /*
  175345. * Initial opening of a backing-store object. This must fill in the
  175346. * read/write/close pointers in the object. The read/write routines
  175347. * may take an error exit if the specified maximum file size is exceeded.
  175348. * (If jpeg_mem_available always returns a large value, this routine can
  175349. * just take an error exit.)
  175350. */
  175351. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175352. struct backing_store_struct *info,
  175353. long total_bytes_needed));
  175354. /*
  175355. * These routines take care of any system-dependent initialization and
  175356. * cleanup required. jpeg_mem_init will be called before anything is
  175357. * allocated (and, therefore, nothing in cinfo is of use except the error
  175358. * manager pointer). It should return a suitable default value for
  175359. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175360. * application. (Note that max_memory_to_use is only important if
  175361. * jpeg_mem_available chooses to consult it ... no one else will.)
  175362. * jpeg_mem_term may assume that all requested memory has been freed and that
  175363. * all opened backing-store objects have been closed.
  175364. */
  175365. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175366. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175367. #endif
  175368. /*** End of inlined file: jmemsys.h ***/
  175369. /* import the system-dependent declarations */
  175370. #ifndef NO_GETENV
  175371. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175372. extern char * getenv JPP((const char * name));
  175373. #endif
  175374. #endif
  175375. /*
  175376. * Some important notes:
  175377. * The allocation routines provided here must never return NULL.
  175378. * They should exit to error_exit if unsuccessful.
  175379. *
  175380. * It's not a good idea to try to merge the sarray and barray routines,
  175381. * even though they are textually almost the same, because samples are
  175382. * usually stored as bytes while coefficients are shorts or ints. Thus,
  175383. * in machines where byte pointers have a different representation from
  175384. * word pointers, the resulting machine code could not be the same.
  175385. */
  175386. /*
  175387. * Many machines require storage alignment: longs must start on 4-byte
  175388. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  175389. * always returns pointers that are multiples of the worst-case alignment
  175390. * requirement, and we had better do so too.
  175391. * There isn't any really portable way to determine the worst-case alignment
  175392. * requirement. This module assumes that the alignment requirement is
  175393. * multiples of sizeof(ALIGN_TYPE).
  175394. * By default, we define ALIGN_TYPE as double. This is necessary on some
  175395. * workstations (where doubles really do need 8-byte alignment) and will work
  175396. * fine on nearly everything. If your machine has lesser alignment needs,
  175397. * you can save a few bytes by making ALIGN_TYPE smaller.
  175398. * The only place I know of where this will NOT work is certain Macintosh
  175399. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  175400. * Doing 10-byte alignment is counterproductive because longwords won't be
  175401. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  175402. * such a compiler.
  175403. */
  175404. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  175405. #define ALIGN_TYPE double
  175406. #endif
  175407. /*
  175408. * We allocate objects from "pools", where each pool is gotten with a single
  175409. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  175410. * overhead within a pool, except for alignment padding. Each pool has a
  175411. * header with a link to the next pool of the same class.
  175412. * Small and large pool headers are identical except that the latter's
  175413. * link pointer must be FAR on 80x86 machines.
  175414. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  175415. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  175416. * of the alignment requirement of ALIGN_TYPE.
  175417. */
  175418. typedef union small_pool_struct * small_pool_ptr;
  175419. typedef union small_pool_struct {
  175420. struct {
  175421. small_pool_ptr next; /* next in list of pools */
  175422. size_t bytes_used; /* how many bytes already used within pool */
  175423. size_t bytes_left; /* bytes still available in this pool */
  175424. } hdr;
  175425. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175426. } small_pool_hdr;
  175427. typedef union large_pool_struct FAR * large_pool_ptr;
  175428. typedef union large_pool_struct {
  175429. struct {
  175430. large_pool_ptr next; /* next in list of pools */
  175431. size_t bytes_used; /* how many bytes already used within pool */
  175432. size_t bytes_left; /* bytes still available in this pool */
  175433. } hdr;
  175434. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175435. } large_pool_hdr;
  175436. /*
  175437. * Here is the full definition of a memory manager object.
  175438. */
  175439. typedef struct {
  175440. struct jpeg_memory_mgr pub; /* public fields */
  175441. /* Each pool identifier (lifetime class) names a linked list of pools. */
  175442. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  175443. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  175444. /* Since we only have one lifetime class of virtual arrays, only one
  175445. * linked list is necessary (for each datatype). Note that the virtual
  175446. * array control blocks being linked together are actually stored somewhere
  175447. * in the small-pool list.
  175448. */
  175449. jvirt_sarray_ptr virt_sarray_list;
  175450. jvirt_barray_ptr virt_barray_list;
  175451. /* This counts total space obtained from jpeg_get_small/large */
  175452. long total_space_allocated;
  175453. /* alloc_sarray and alloc_barray set this value for use by virtual
  175454. * array routines.
  175455. */
  175456. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  175457. } my_memory_mgr;
  175458. typedef my_memory_mgr * my_mem_ptr;
  175459. /*
  175460. * The control blocks for virtual arrays.
  175461. * Note that these blocks are allocated in the "small" pool area.
  175462. * System-dependent info for the associated backing store (if any) is hidden
  175463. * inside the backing_store_info struct.
  175464. */
  175465. struct jvirt_sarray_control {
  175466. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  175467. JDIMENSION rows_in_array; /* total virtual array height */
  175468. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  175469. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  175470. JDIMENSION rows_in_mem; /* height of memory buffer */
  175471. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175472. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175473. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175474. boolean pre_zero; /* pre-zero mode requested? */
  175475. boolean dirty; /* do current buffer contents need written? */
  175476. boolean b_s_open; /* is backing-store data valid? */
  175477. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  175478. backing_store_info b_s_info; /* System-dependent control info */
  175479. };
  175480. struct jvirt_barray_control {
  175481. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  175482. JDIMENSION rows_in_array; /* total virtual array height */
  175483. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  175484. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  175485. JDIMENSION rows_in_mem; /* height of memory buffer */
  175486. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175487. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175488. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175489. boolean pre_zero; /* pre-zero mode requested? */
  175490. boolean dirty; /* do current buffer contents need written? */
  175491. boolean b_s_open; /* is backing-store data valid? */
  175492. jvirt_barray_ptr next; /* link to next virtual barray control block */
  175493. backing_store_info b_s_info; /* System-dependent control info */
  175494. };
  175495. #ifdef MEM_STATS /* optional extra stuff for statistics */
  175496. LOCAL(void)
  175497. print_mem_stats (j_common_ptr cinfo, int pool_id)
  175498. {
  175499. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175500. small_pool_ptr shdr_ptr;
  175501. large_pool_ptr lhdr_ptr;
  175502. /* Since this is only a debugging stub, we can cheat a little by using
  175503. * fprintf directly rather than going through the trace message code.
  175504. * This is helpful because message parm array can't handle longs.
  175505. */
  175506. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  175507. pool_id, mem->total_space_allocated);
  175508. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  175509. lhdr_ptr = lhdr_ptr->hdr.next) {
  175510. fprintf(stderr, " Large chunk used %ld\n",
  175511. (long) lhdr_ptr->hdr.bytes_used);
  175512. }
  175513. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  175514. shdr_ptr = shdr_ptr->hdr.next) {
  175515. fprintf(stderr, " Small chunk used %ld free %ld\n",
  175516. (long) shdr_ptr->hdr.bytes_used,
  175517. (long) shdr_ptr->hdr.bytes_left);
  175518. }
  175519. }
  175520. #endif /* MEM_STATS */
  175521. LOCAL(void)
  175522. out_of_memory (j_common_ptr cinfo, int which)
  175523. /* Report an out-of-memory error and stop execution */
  175524. /* If we compiled MEM_STATS support, report alloc requests before dying */
  175525. {
  175526. #ifdef MEM_STATS
  175527. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  175528. #endif
  175529. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  175530. }
  175531. /*
  175532. * Allocation of "small" objects.
  175533. *
  175534. * For these, we use pooled storage. When a new pool must be created,
  175535. * we try to get enough space for the current request plus a "slop" factor,
  175536. * where the slop will be the amount of leftover space in the new pool.
  175537. * The speed vs. space tradeoff is largely determined by the slop values.
  175538. * A different slop value is provided for each pool class (lifetime),
  175539. * and we also distinguish the first pool of a class from later ones.
  175540. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  175541. * machines, but may be too small if longs are 64 bits or more.
  175542. */
  175543. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  175544. {
  175545. 1600, /* first PERMANENT pool */
  175546. 16000 /* first IMAGE pool */
  175547. };
  175548. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  175549. {
  175550. 0, /* additional PERMANENT pools */
  175551. 5000 /* additional IMAGE pools */
  175552. };
  175553. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  175554. METHODDEF(void *)
  175555. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175556. /* Allocate a "small" object */
  175557. {
  175558. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175559. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  175560. char * data_ptr;
  175561. size_t odd_bytes, min_request, slop;
  175562. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175563. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  175564. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  175565. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175566. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175567. if (odd_bytes > 0)
  175568. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175569. /* See if space is available in any existing pool */
  175570. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175571. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175572. prev_hdr_ptr = NULL;
  175573. hdr_ptr = mem->small_list[pool_id];
  175574. while (hdr_ptr != NULL) {
  175575. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  175576. break; /* found pool with enough space */
  175577. prev_hdr_ptr = hdr_ptr;
  175578. hdr_ptr = hdr_ptr->hdr.next;
  175579. }
  175580. /* Time to make a new pool? */
  175581. if (hdr_ptr == NULL) {
  175582. /* min_request is what we need now, slop is what will be leftover */
  175583. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  175584. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175585. slop = first_pool_slop[pool_id];
  175586. else
  175587. slop = extra_pool_slop[pool_id];
  175588. /* Don't ask for more than MAX_ALLOC_CHUNK */
  175589. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  175590. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  175591. /* Try to get space, if fail reduce slop and try again */
  175592. for (;;) {
  175593. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  175594. if (hdr_ptr != NULL)
  175595. break;
  175596. slop /= 2;
  175597. if (slop < MIN_SLOP) /* give up when it gets real small */
  175598. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  175599. }
  175600. mem->total_space_allocated += min_request + slop;
  175601. /* Success, initialize the new pool header and add to end of list */
  175602. hdr_ptr->hdr.next = NULL;
  175603. hdr_ptr->hdr.bytes_used = 0;
  175604. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  175605. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175606. mem->small_list[pool_id] = hdr_ptr;
  175607. else
  175608. prev_hdr_ptr->hdr.next = hdr_ptr;
  175609. }
  175610. /* OK, allocate the object from the current pool */
  175611. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  175612. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  175613. hdr_ptr->hdr.bytes_used += sizeofobject;
  175614. hdr_ptr->hdr.bytes_left -= sizeofobject;
  175615. return (void *) data_ptr;
  175616. }
  175617. /*
  175618. * Allocation of "large" objects.
  175619. *
  175620. * The external semantics of these are the same as "small" objects,
  175621. * except that FAR pointers are used on 80x86. However the pool
  175622. * management heuristics are quite different. We assume that each
  175623. * request is large enough that it may as well be passed directly to
  175624. * jpeg_get_large; the pool management just links everything together
  175625. * so that we can free it all on demand.
  175626. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  175627. * structures. The routines that create these structures (see below)
  175628. * deliberately bunch rows together to ensure a large request size.
  175629. */
  175630. METHODDEF(void FAR *)
  175631. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175632. /* Allocate a "large" object */
  175633. {
  175634. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175635. large_pool_ptr hdr_ptr;
  175636. size_t odd_bytes;
  175637. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175638. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  175639. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  175640. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175641. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175642. if (odd_bytes > 0)
  175643. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175644. /* Always make a new pool */
  175645. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175646. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175647. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  175648. SIZEOF(large_pool_hdr));
  175649. if (hdr_ptr == NULL)
  175650. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  175651. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  175652. /* Success, initialize the new pool header and add to list */
  175653. hdr_ptr->hdr.next = mem->large_list[pool_id];
  175654. /* We maintain space counts in each pool header for statistical purposes,
  175655. * even though they are not needed for allocation.
  175656. */
  175657. hdr_ptr->hdr.bytes_used = sizeofobject;
  175658. hdr_ptr->hdr.bytes_left = 0;
  175659. mem->large_list[pool_id] = hdr_ptr;
  175660. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  175661. }
  175662. /*
  175663. * Creation of 2-D sample arrays.
  175664. * The pointers are in near heap, the samples themselves in FAR heap.
  175665. *
  175666. * To minimize allocation overhead and to allow I/O of large contiguous
  175667. * blocks, we allocate the sample rows in groups of as many rows as possible
  175668. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  175669. * NB: the virtual array control routines, later in this file, know about
  175670. * this chunking of rows. The rowsperchunk value is left in the mem manager
  175671. * object so that it can be saved away if this sarray is the workspace for
  175672. * a virtual array.
  175673. */
  175674. METHODDEF(JSAMPARRAY)
  175675. alloc_sarray (j_common_ptr cinfo, int pool_id,
  175676. JDIMENSION samplesperrow, JDIMENSION numrows)
  175677. /* Allocate a 2-D sample array */
  175678. {
  175679. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175680. JSAMPARRAY result;
  175681. JSAMPROW workspace;
  175682. JDIMENSION rowsperchunk, currow, i;
  175683. long ltemp;
  175684. /* Calculate max # of rows allowed in one allocation chunk */
  175685. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175686. ((long) samplesperrow * SIZEOF(JSAMPLE));
  175687. if (ltemp <= 0)
  175688. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175689. if (ltemp < (long) numrows)
  175690. rowsperchunk = (JDIMENSION) ltemp;
  175691. else
  175692. rowsperchunk = numrows;
  175693. mem->last_rowsperchunk = rowsperchunk;
  175694. /* Get space for row pointers (small object) */
  175695. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  175696. (size_t) (numrows * SIZEOF(JSAMPROW)));
  175697. /* Get the rows themselves (large objects) */
  175698. currow = 0;
  175699. while (currow < numrows) {
  175700. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175701. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  175702. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  175703. * SIZEOF(JSAMPLE)));
  175704. for (i = rowsperchunk; i > 0; i--) {
  175705. result[currow++] = workspace;
  175706. workspace += samplesperrow;
  175707. }
  175708. }
  175709. return result;
  175710. }
  175711. /*
  175712. * Creation of 2-D coefficient-block arrays.
  175713. * This is essentially the same as the code for sample arrays, above.
  175714. */
  175715. METHODDEF(JBLOCKARRAY)
  175716. alloc_barray (j_common_ptr cinfo, int pool_id,
  175717. JDIMENSION blocksperrow, JDIMENSION numrows)
  175718. /* Allocate a 2-D coefficient-block array */
  175719. {
  175720. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175721. JBLOCKARRAY result;
  175722. JBLOCKROW workspace;
  175723. JDIMENSION rowsperchunk, currow, i;
  175724. long ltemp;
  175725. /* Calculate max # of rows allowed in one allocation chunk */
  175726. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175727. ((long) blocksperrow * SIZEOF(JBLOCK));
  175728. if (ltemp <= 0)
  175729. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175730. if (ltemp < (long) numrows)
  175731. rowsperchunk = (JDIMENSION) ltemp;
  175732. else
  175733. rowsperchunk = numrows;
  175734. mem->last_rowsperchunk = rowsperchunk;
  175735. /* Get space for row pointers (small object) */
  175736. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  175737. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  175738. /* Get the rows themselves (large objects) */
  175739. currow = 0;
  175740. while (currow < numrows) {
  175741. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175742. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  175743. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  175744. * SIZEOF(JBLOCK)));
  175745. for (i = rowsperchunk; i > 0; i--) {
  175746. result[currow++] = workspace;
  175747. workspace += blocksperrow;
  175748. }
  175749. }
  175750. return result;
  175751. }
  175752. /*
  175753. * About virtual array management:
  175754. *
  175755. * The above "normal" array routines are only used to allocate strip buffers
  175756. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  175757. * are handled as "virtual" arrays. The array is still accessed a strip at a
  175758. * time, but the memory manager must save the whole array for repeated
  175759. * accesses. The intended implementation is that there is a strip buffer in
  175760. * memory (as high as is possible given the desired memory limit), plus a
  175761. * backing file that holds the rest of the array.
  175762. *
  175763. * The request_virt_array routines are told the total size of the image and
  175764. * the maximum number of rows that will be accessed at once. The in-memory
  175765. * buffer must be at least as large as the maxaccess value.
  175766. *
  175767. * The request routines create control blocks but not the in-memory buffers.
  175768. * That is postponed until realize_virt_arrays is called. At that time the
  175769. * total amount of space needed is known (approximately, anyway), so free
  175770. * memory can be divided up fairly.
  175771. *
  175772. * The access_virt_array routines are responsible for making a specific strip
  175773. * area accessible (after reading or writing the backing file, if necessary).
  175774. * Note that the access routines are told whether the caller intends to modify
  175775. * the accessed strip; during a read-only pass this saves having to rewrite
  175776. * data to disk. The access routines are also responsible for pre-zeroing
  175777. * any newly accessed rows, if pre-zeroing was requested.
  175778. *
  175779. * In current usage, the access requests are usually for nonoverlapping
  175780. * strips; that is, successive access start_row numbers differ by exactly
  175781. * num_rows = maxaccess. This means we can get good performance with simple
  175782. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  175783. * of the access height; then there will never be accesses across bufferload
  175784. * boundaries. The code will still work with overlapping access requests,
  175785. * but it doesn't handle bufferload overlaps very efficiently.
  175786. */
  175787. METHODDEF(jvirt_sarray_ptr)
  175788. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  175789. JDIMENSION samplesperrow, JDIMENSION numrows,
  175790. JDIMENSION maxaccess)
  175791. /* Request a virtual 2-D sample array */
  175792. {
  175793. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175794. jvirt_sarray_ptr result;
  175795. /* Only IMAGE-lifetime virtual arrays are currently supported */
  175796. if (pool_id != JPOOL_IMAGE)
  175797. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175798. /* get control block */
  175799. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  175800. SIZEOF(struct jvirt_sarray_control));
  175801. result->mem_buffer = NULL; /* marks array not yet realized */
  175802. result->rows_in_array = numrows;
  175803. result->samplesperrow = samplesperrow;
  175804. result->maxaccess = maxaccess;
  175805. result->pre_zero = pre_zero;
  175806. result->b_s_open = FALSE; /* no associated backing-store object */
  175807. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  175808. mem->virt_sarray_list = result;
  175809. return result;
  175810. }
  175811. METHODDEF(jvirt_barray_ptr)
  175812. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  175813. JDIMENSION blocksperrow, JDIMENSION numrows,
  175814. JDIMENSION maxaccess)
  175815. /* Request a virtual 2-D coefficient-block array */
  175816. {
  175817. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175818. jvirt_barray_ptr result;
  175819. /* Only IMAGE-lifetime virtual arrays are currently supported */
  175820. if (pool_id != JPOOL_IMAGE)
  175821. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175822. /* get control block */
  175823. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  175824. SIZEOF(struct jvirt_barray_control));
  175825. result->mem_buffer = NULL; /* marks array not yet realized */
  175826. result->rows_in_array = numrows;
  175827. result->blocksperrow = blocksperrow;
  175828. result->maxaccess = maxaccess;
  175829. result->pre_zero = pre_zero;
  175830. result->b_s_open = FALSE; /* no associated backing-store object */
  175831. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  175832. mem->virt_barray_list = result;
  175833. return result;
  175834. }
  175835. METHODDEF(void)
  175836. realize_virt_arrays (j_common_ptr cinfo)
  175837. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  175838. {
  175839. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175840. long space_per_minheight, maximum_space, avail_mem;
  175841. long minheights, max_minheights;
  175842. jvirt_sarray_ptr sptr;
  175843. jvirt_barray_ptr bptr;
  175844. /* Compute the minimum space needed (maxaccess rows in each buffer)
  175845. * and the maximum space needed (full image height in each buffer).
  175846. * These may be of use to the system-dependent jpeg_mem_available routine.
  175847. */
  175848. space_per_minheight = 0;
  175849. maximum_space = 0;
  175850. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175851. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  175852. space_per_minheight += (long) sptr->maxaccess *
  175853. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  175854. maximum_space += (long) sptr->rows_in_array *
  175855. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  175856. }
  175857. }
  175858. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  175859. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  175860. space_per_minheight += (long) bptr->maxaccess *
  175861. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  175862. maximum_space += (long) bptr->rows_in_array *
  175863. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  175864. }
  175865. }
  175866. if (space_per_minheight <= 0)
  175867. return; /* no unrealized arrays, no work */
  175868. /* Determine amount of memory to actually use; this is system-dependent. */
  175869. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  175870. mem->total_space_allocated);
  175871. /* If the maximum space needed is available, make all the buffers full
  175872. * height; otherwise parcel it out with the same number of minheights
  175873. * in each buffer.
  175874. */
  175875. if (avail_mem >= maximum_space)
  175876. max_minheights = 1000000000L;
  175877. else {
  175878. max_minheights = avail_mem / space_per_minheight;
  175879. /* If there doesn't seem to be enough space, try to get the minimum
  175880. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  175881. */
  175882. if (max_minheights <= 0)
  175883. max_minheights = 1;
  175884. }
  175885. /* Allocate the in-memory buffers and initialize backing store as needed. */
  175886. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175887. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  175888. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  175889. if (minheights <= max_minheights) {
  175890. /* This buffer fits in memory */
  175891. sptr->rows_in_mem = sptr->rows_in_array;
  175892. } else {
  175893. /* It doesn't fit in memory, create backing store. */
  175894. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  175895. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  175896. (long) sptr->rows_in_array *
  175897. (long) sptr->samplesperrow *
  175898. (long) SIZEOF(JSAMPLE));
  175899. sptr->b_s_open = TRUE;
  175900. }
  175901. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  175902. sptr->samplesperrow, sptr->rows_in_mem);
  175903. sptr->rowsperchunk = mem->last_rowsperchunk;
  175904. sptr->cur_start_row = 0;
  175905. sptr->first_undef_row = 0;
  175906. sptr->dirty = FALSE;
  175907. }
  175908. }
  175909. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  175910. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  175911. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  175912. if (minheights <= max_minheights) {
  175913. /* This buffer fits in memory */
  175914. bptr->rows_in_mem = bptr->rows_in_array;
  175915. } else {
  175916. /* It doesn't fit in memory, create backing store. */
  175917. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  175918. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  175919. (long) bptr->rows_in_array *
  175920. (long) bptr->blocksperrow *
  175921. (long) SIZEOF(JBLOCK));
  175922. bptr->b_s_open = TRUE;
  175923. }
  175924. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  175925. bptr->blocksperrow, bptr->rows_in_mem);
  175926. bptr->rowsperchunk = mem->last_rowsperchunk;
  175927. bptr->cur_start_row = 0;
  175928. bptr->first_undef_row = 0;
  175929. bptr->dirty = FALSE;
  175930. }
  175931. }
  175932. }
  175933. LOCAL(void)
  175934. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  175935. /* Do backing store read or write of a virtual sample array */
  175936. {
  175937. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  175938. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  175939. file_offset = ptr->cur_start_row * bytesperrow;
  175940. /* Loop to read or write each allocation chunk in mem_buffer */
  175941. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  175942. /* One chunk, but check for short chunk at end of buffer */
  175943. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  175944. /* Transfer no more than is currently defined */
  175945. thisrow = (long) ptr->cur_start_row + i;
  175946. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  175947. /* Transfer no more than fits in file */
  175948. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  175949. if (rows <= 0) /* this chunk might be past end of file! */
  175950. break;
  175951. byte_count = rows * bytesperrow;
  175952. if (writing)
  175953. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  175954. (void FAR *) ptr->mem_buffer[i],
  175955. file_offset, byte_count);
  175956. else
  175957. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  175958. (void FAR *) ptr->mem_buffer[i],
  175959. file_offset, byte_count);
  175960. file_offset += byte_count;
  175961. }
  175962. }
  175963. LOCAL(void)
  175964. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  175965. /* Do backing store read or write of a virtual coefficient-block array */
  175966. {
  175967. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  175968. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  175969. file_offset = ptr->cur_start_row * bytesperrow;
  175970. /* Loop to read or write each allocation chunk in mem_buffer */
  175971. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  175972. /* One chunk, but check for short chunk at end of buffer */
  175973. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  175974. /* Transfer no more than is currently defined */
  175975. thisrow = (long) ptr->cur_start_row + i;
  175976. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  175977. /* Transfer no more than fits in file */
  175978. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  175979. if (rows <= 0) /* this chunk might be past end of file! */
  175980. break;
  175981. byte_count = rows * bytesperrow;
  175982. if (writing)
  175983. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  175984. (void FAR *) ptr->mem_buffer[i],
  175985. file_offset, byte_count);
  175986. else
  175987. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  175988. (void FAR *) ptr->mem_buffer[i],
  175989. file_offset, byte_count);
  175990. file_offset += byte_count;
  175991. }
  175992. }
  175993. METHODDEF(JSAMPARRAY)
  175994. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  175995. JDIMENSION start_row, JDIMENSION num_rows,
  175996. boolean writable)
  175997. /* Access the part of a virtual sample array starting at start_row */
  175998. /* and extending for num_rows rows. writable is true if */
  175999. /* caller intends to modify the accessed area. */
  176000. {
  176001. JDIMENSION end_row = start_row + num_rows;
  176002. JDIMENSION undef_row;
  176003. /* debugging check */
  176004. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176005. ptr->mem_buffer == NULL)
  176006. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176007. /* Make the desired part of the virtual array accessible */
  176008. if (start_row < ptr->cur_start_row ||
  176009. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176010. if (! ptr->b_s_open)
  176011. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176012. /* Flush old buffer contents if necessary */
  176013. if (ptr->dirty) {
  176014. do_sarray_io(cinfo, ptr, TRUE);
  176015. ptr->dirty = FALSE;
  176016. }
  176017. /* Decide what part of virtual array to access.
  176018. * Algorithm: if target address > current window, assume forward scan,
  176019. * load starting at target address. If target address < current window,
  176020. * assume backward scan, load so that target area is top of window.
  176021. * Note that when switching from forward write to forward read, will have
  176022. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176023. */
  176024. if (start_row > ptr->cur_start_row) {
  176025. ptr->cur_start_row = start_row;
  176026. } else {
  176027. /* use long arithmetic here to avoid overflow & unsigned problems */
  176028. long ltemp;
  176029. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176030. if (ltemp < 0)
  176031. ltemp = 0; /* don't fall off front end of file */
  176032. ptr->cur_start_row = (JDIMENSION) ltemp;
  176033. }
  176034. /* Read in the selected part of the array.
  176035. * During the initial write pass, we will do no actual read
  176036. * because the selected part is all undefined.
  176037. */
  176038. do_sarray_io(cinfo, ptr, FALSE);
  176039. }
  176040. /* Ensure the accessed part of the array is defined; prezero if needed.
  176041. * To improve locality of access, we only prezero the part of the array
  176042. * that the caller is about to access, not the entire in-memory array.
  176043. */
  176044. if (ptr->first_undef_row < end_row) {
  176045. if (ptr->first_undef_row < start_row) {
  176046. if (writable) /* writer skipped over a section of array */
  176047. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176048. undef_row = start_row; /* but reader is allowed to read ahead */
  176049. } else {
  176050. undef_row = ptr->first_undef_row;
  176051. }
  176052. if (writable)
  176053. ptr->first_undef_row = end_row;
  176054. if (ptr->pre_zero) {
  176055. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176056. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176057. end_row -= ptr->cur_start_row;
  176058. while (undef_row < end_row) {
  176059. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176060. undef_row++;
  176061. }
  176062. } else {
  176063. if (! writable) /* reader looking at undefined data */
  176064. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176065. }
  176066. }
  176067. /* Flag the buffer dirty if caller will write in it */
  176068. if (writable)
  176069. ptr->dirty = TRUE;
  176070. /* Return address of proper part of the buffer */
  176071. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176072. }
  176073. METHODDEF(JBLOCKARRAY)
  176074. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176075. JDIMENSION start_row, JDIMENSION num_rows,
  176076. boolean writable)
  176077. /* Access the part of a virtual block array starting at start_row */
  176078. /* and extending for num_rows rows. writable is true if */
  176079. /* caller intends to modify the accessed area. */
  176080. {
  176081. JDIMENSION end_row = start_row + num_rows;
  176082. JDIMENSION undef_row;
  176083. /* debugging check */
  176084. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176085. ptr->mem_buffer == NULL)
  176086. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176087. /* Make the desired part of the virtual array accessible */
  176088. if (start_row < ptr->cur_start_row ||
  176089. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176090. if (! ptr->b_s_open)
  176091. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176092. /* Flush old buffer contents if necessary */
  176093. if (ptr->dirty) {
  176094. do_barray_io(cinfo, ptr, TRUE);
  176095. ptr->dirty = FALSE;
  176096. }
  176097. /* Decide what part of virtual array to access.
  176098. * Algorithm: if target address > current window, assume forward scan,
  176099. * load starting at target address. If target address < current window,
  176100. * assume backward scan, load so that target area is top of window.
  176101. * Note that when switching from forward write to forward read, will have
  176102. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176103. */
  176104. if (start_row > ptr->cur_start_row) {
  176105. ptr->cur_start_row = start_row;
  176106. } else {
  176107. /* use long arithmetic here to avoid overflow & unsigned problems */
  176108. long ltemp;
  176109. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176110. if (ltemp < 0)
  176111. ltemp = 0; /* don't fall off front end of file */
  176112. ptr->cur_start_row = (JDIMENSION) ltemp;
  176113. }
  176114. /* Read in the selected part of the array.
  176115. * During the initial write pass, we will do no actual read
  176116. * because the selected part is all undefined.
  176117. */
  176118. do_barray_io(cinfo, ptr, FALSE);
  176119. }
  176120. /* Ensure the accessed part of the array is defined; prezero if needed.
  176121. * To improve locality of access, we only prezero the part of the array
  176122. * that the caller is about to access, not the entire in-memory array.
  176123. */
  176124. if (ptr->first_undef_row < end_row) {
  176125. if (ptr->first_undef_row < start_row) {
  176126. if (writable) /* writer skipped over a section of array */
  176127. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176128. undef_row = start_row; /* but reader is allowed to read ahead */
  176129. } else {
  176130. undef_row = ptr->first_undef_row;
  176131. }
  176132. if (writable)
  176133. ptr->first_undef_row = end_row;
  176134. if (ptr->pre_zero) {
  176135. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176136. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176137. end_row -= ptr->cur_start_row;
  176138. while (undef_row < end_row) {
  176139. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176140. undef_row++;
  176141. }
  176142. } else {
  176143. if (! writable) /* reader looking at undefined data */
  176144. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176145. }
  176146. }
  176147. /* Flag the buffer dirty if caller will write in it */
  176148. if (writable)
  176149. ptr->dirty = TRUE;
  176150. /* Return address of proper part of the buffer */
  176151. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176152. }
  176153. /*
  176154. * Release all objects belonging to a specified pool.
  176155. */
  176156. METHODDEF(void)
  176157. free_pool (j_common_ptr cinfo, int pool_id)
  176158. {
  176159. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176160. small_pool_ptr shdr_ptr;
  176161. large_pool_ptr lhdr_ptr;
  176162. size_t space_freed;
  176163. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176164. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176165. #ifdef MEM_STATS
  176166. if (cinfo->err->trace_level > 1)
  176167. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176168. #endif
  176169. /* If freeing IMAGE pool, close any virtual arrays first */
  176170. if (pool_id == JPOOL_IMAGE) {
  176171. jvirt_sarray_ptr sptr;
  176172. jvirt_barray_ptr bptr;
  176173. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176174. if (sptr->b_s_open) { /* there may be no backing store */
  176175. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176176. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176177. }
  176178. }
  176179. mem->virt_sarray_list = NULL;
  176180. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176181. if (bptr->b_s_open) { /* there may be no backing store */
  176182. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176183. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176184. }
  176185. }
  176186. mem->virt_barray_list = NULL;
  176187. }
  176188. /* Release large objects */
  176189. lhdr_ptr = mem->large_list[pool_id];
  176190. mem->large_list[pool_id] = NULL;
  176191. while (lhdr_ptr != NULL) {
  176192. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176193. space_freed = lhdr_ptr->hdr.bytes_used +
  176194. lhdr_ptr->hdr.bytes_left +
  176195. SIZEOF(large_pool_hdr);
  176196. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176197. mem->total_space_allocated -= space_freed;
  176198. lhdr_ptr = next_lhdr_ptr;
  176199. }
  176200. /* Release small objects */
  176201. shdr_ptr = mem->small_list[pool_id];
  176202. mem->small_list[pool_id] = NULL;
  176203. while (shdr_ptr != NULL) {
  176204. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176205. space_freed = shdr_ptr->hdr.bytes_used +
  176206. shdr_ptr->hdr.bytes_left +
  176207. SIZEOF(small_pool_hdr);
  176208. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176209. mem->total_space_allocated -= space_freed;
  176210. shdr_ptr = next_shdr_ptr;
  176211. }
  176212. }
  176213. /*
  176214. * Close up shop entirely.
  176215. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176216. */
  176217. METHODDEF(void)
  176218. self_destruct (j_common_ptr cinfo)
  176219. {
  176220. int pool;
  176221. /* Close all backing store, release all memory.
  176222. * Releasing pools in reverse order might help avoid fragmentation
  176223. * with some (brain-damaged) malloc libraries.
  176224. */
  176225. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176226. free_pool(cinfo, pool);
  176227. }
  176228. /* Release the memory manager control block too. */
  176229. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176230. cinfo->mem = NULL; /* ensures I will be called only once */
  176231. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176232. }
  176233. /*
  176234. * Memory manager initialization.
  176235. * When this is called, only the error manager pointer is valid in cinfo!
  176236. */
  176237. GLOBAL(void)
  176238. jinit_memory_mgr (j_common_ptr cinfo)
  176239. {
  176240. my_mem_ptr mem;
  176241. long max_to_use;
  176242. int pool;
  176243. size_t test_mac;
  176244. cinfo->mem = NULL; /* for safety if init fails */
  176245. /* Check for configuration errors.
  176246. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176247. * doesn't reflect any real hardware alignment requirement.
  176248. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176249. * in common if and only if X is a power of 2, ie has only one one-bit.
  176250. * Some compilers may give an "unreachable code" warning here; ignore it.
  176251. */
  176252. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176253. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176254. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176255. * a multiple of SIZEOF(ALIGN_TYPE).
  176256. * Again, an "unreachable code" warning may be ignored here.
  176257. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176258. */
  176259. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176260. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176261. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176262. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176263. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176264. /* Attempt to allocate memory manager's control block */
  176265. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176266. if (mem == NULL) {
  176267. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176268. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176269. }
  176270. /* OK, fill in the method pointers */
  176271. mem->pub.alloc_small = alloc_small;
  176272. mem->pub.alloc_large = alloc_large;
  176273. mem->pub.alloc_sarray = alloc_sarray;
  176274. mem->pub.alloc_barray = alloc_barray;
  176275. mem->pub.request_virt_sarray = request_virt_sarray;
  176276. mem->pub.request_virt_barray = request_virt_barray;
  176277. mem->pub.realize_virt_arrays = realize_virt_arrays;
  176278. mem->pub.access_virt_sarray = access_virt_sarray;
  176279. mem->pub.access_virt_barray = access_virt_barray;
  176280. mem->pub.free_pool = free_pool;
  176281. mem->pub.self_destruct = self_destruct;
  176282. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  176283. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  176284. /* Initialize working state */
  176285. mem->pub.max_memory_to_use = max_to_use;
  176286. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176287. mem->small_list[pool] = NULL;
  176288. mem->large_list[pool] = NULL;
  176289. }
  176290. mem->virt_sarray_list = NULL;
  176291. mem->virt_barray_list = NULL;
  176292. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  176293. /* Declare ourselves open for business */
  176294. cinfo->mem = & mem->pub;
  176295. /* Check for an environment variable JPEGMEM; if found, override the
  176296. * default max_memory setting from jpeg_mem_init. Note that the
  176297. * surrounding application may again override this value.
  176298. * If your system doesn't support getenv(), define NO_GETENV to disable
  176299. * this feature.
  176300. */
  176301. #ifndef NO_GETENV
  176302. { char * memenv;
  176303. if ((memenv = getenv("JPEGMEM")) != NULL) {
  176304. char ch = 'x';
  176305. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176306. if (ch == 'm' || ch == 'M')
  176307. max_to_use *= 1000L;
  176308. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176309. }
  176310. }
  176311. }
  176312. #endif
  176313. }
  176314. /*** End of inlined file: jmemmgr.c ***/
  176315. /*** Start of inlined file: jmemnobs.c ***/
  176316. #define JPEG_INTERNALS
  176317. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176318. extern void * malloc JPP((size_t size));
  176319. extern void free JPP((void *ptr));
  176320. #endif
  176321. /*
  176322. * Memory allocation and freeing are controlled by the regular library
  176323. * routines malloc() and free().
  176324. */
  176325. GLOBAL(void *)
  176326. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176327. {
  176328. return (void *) malloc(sizeofobject);
  176329. }
  176330. GLOBAL(void)
  176331. jpeg_free_small (j_common_ptr , void * object, size_t)
  176332. {
  176333. free(object);
  176334. }
  176335. /*
  176336. * "Large" objects are treated the same as "small" ones.
  176337. * NB: although we include FAR keywords in the routine declarations,
  176338. * this file won't actually work in 80x86 small/medium model; at least,
  176339. * you probably won't be able to process useful-size images in only 64KB.
  176340. */
  176341. GLOBAL(void FAR *)
  176342. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176343. {
  176344. return (void FAR *) malloc(sizeofobject);
  176345. }
  176346. GLOBAL(void)
  176347. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176348. {
  176349. free(object);
  176350. }
  176351. /*
  176352. * This routine computes the total memory space available for allocation.
  176353. * Here we always say, "we got all you want bud!"
  176354. */
  176355. GLOBAL(long)
  176356. jpeg_mem_available (j_common_ptr, long,
  176357. long max_bytes_needed, long)
  176358. {
  176359. return max_bytes_needed;
  176360. }
  176361. /*
  176362. * Backing store (temporary file) management.
  176363. * Since jpeg_mem_available always promised the moon,
  176364. * this should never be called and we can just error out.
  176365. */
  176366. GLOBAL(void)
  176367. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176368. long )
  176369. {
  176370. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176371. }
  176372. /*
  176373. * These routines take care of any system-dependent initialization and
  176374. * cleanup required. Here, there isn't any.
  176375. */
  176376. GLOBAL(long)
  176377. jpeg_mem_init (j_common_ptr)
  176378. {
  176379. return 0; /* just set max_memory_to_use to 0 */
  176380. }
  176381. GLOBAL(void)
  176382. jpeg_mem_term (j_common_ptr)
  176383. {
  176384. /* no work */
  176385. }
  176386. /*** End of inlined file: jmemnobs.c ***/
  176387. /*** Start of inlined file: jquant1.c ***/
  176388. #define JPEG_INTERNALS
  176389. #ifdef QUANT_1PASS_SUPPORTED
  176390. /*
  176391. * The main purpose of 1-pass quantization is to provide a fast, if not very
  176392. * high quality, colormapped output capability. A 2-pass quantizer usually
  176393. * gives better visual quality; however, for quantized grayscale output this
  176394. * quantizer is perfectly adequate. Dithering is highly recommended with this
  176395. * quantizer, though you can turn it off if you really want to.
  176396. *
  176397. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  176398. * image. We use a map consisting of all combinations of Ncolors[i] color
  176399. * values for the i'th component. The Ncolors[] values are chosen so that
  176400. * their product, the total number of colors, is no more than that requested.
  176401. * (In most cases, the product will be somewhat less.)
  176402. *
  176403. * Since the colormap is orthogonal, the representative value for each color
  176404. * component can be determined without considering the other components;
  176405. * then these indexes can be combined into a colormap index by a standard
  176406. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  176407. * can be precalculated and stored in the lookup table colorindex[].
  176408. * colorindex[i][j] maps pixel value j in component i to the nearest
  176409. * representative value (grid plane) for that component; this index is
  176410. * multiplied by the array stride for component i, so that the
  176411. * index of the colormap entry closest to a given pixel value is just
  176412. * sum( colorindex[component-number][pixel-component-value] )
  176413. * Aside from being fast, this scheme allows for variable spacing between
  176414. * representative values with no additional lookup cost.
  176415. *
  176416. * If gamma correction has been applied in color conversion, it might be wise
  176417. * to adjust the color grid spacing so that the representative colors are
  176418. * equidistant in linear space. At this writing, gamma correction is not
  176419. * implemented by jdcolor, so nothing is done here.
  176420. */
  176421. /* Declarations for ordered dithering.
  176422. *
  176423. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  176424. * dithering is described in many references, for instance Dale Schumacher's
  176425. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  176426. * In place of Schumacher's comparisons against a "threshold" value, we add a
  176427. * "dither" value to the input pixel and then round the result to the nearest
  176428. * output value. The dither value is equivalent to (0.5 - threshold) times
  176429. * the distance between output values. For ordered dithering, we assume that
  176430. * the output colors are equally spaced; if not, results will probably be
  176431. * worse, since the dither may be too much or too little at a given point.
  176432. *
  176433. * The normal calculation would be to form pixel value + dither, range-limit
  176434. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  176435. * We can skip the separate range-limiting step by extending the colorindex
  176436. * table in both directions.
  176437. */
  176438. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  176439. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  176440. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  176441. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  176442. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  176443. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  176444. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  176445. /* Bayer's order-4 dither array. Generated by the code given in
  176446. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  176447. * The values in this array must range from 0 to ODITHER_CELLS-1.
  176448. */
  176449. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  176450. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  176451. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  176452. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  176453. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  176454. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  176455. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  176456. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  176457. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  176458. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  176459. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  176460. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  176461. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  176462. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  176463. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  176464. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  176465. };
  176466. /* Declarations for Floyd-Steinberg dithering.
  176467. *
  176468. * Errors are accumulated into the array fserrors[], at a resolution of
  176469. * 1/16th of a pixel count. The error at a given pixel is propagated
  176470. * to its not-yet-processed neighbors using the standard F-S fractions,
  176471. * ... (here) 7/16
  176472. * 3/16 5/16 1/16
  176473. * We work left-to-right on even rows, right-to-left on odd rows.
  176474. *
  176475. * We can get away with a single array (holding one row's worth of errors)
  176476. * by using it to store the current row's errors at pixel columns not yet
  176477. * processed, but the next row's errors at columns already processed. We
  176478. * need only a few extra variables to hold the errors immediately around the
  176479. * current column. (If we are lucky, those variables are in registers, but
  176480. * even if not, they're probably cheaper to access than array elements are.)
  176481. *
  176482. * The fserrors[] array is indexed [component#][position].
  176483. * We provide (#columns + 2) entries per component; the extra entry at each
  176484. * end saves us from special-casing the first and last pixels.
  176485. *
  176486. * Note: on a wide image, we might not have enough room in a PC's near data
  176487. * segment to hold the error array; so it is allocated with alloc_large.
  176488. */
  176489. #if BITS_IN_JSAMPLE == 8
  176490. typedef INT16 FSERROR; /* 16 bits should be enough */
  176491. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  176492. #else
  176493. typedef INT32 FSERROR; /* may need more than 16 bits */
  176494. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  176495. #endif
  176496. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  176497. /* Private subobject */
  176498. #define MAX_Q_COMPS 4 /* max components I can handle */
  176499. typedef struct {
  176500. struct jpeg_color_quantizer pub; /* public fields */
  176501. /* Initially allocated colormap is saved here */
  176502. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  176503. int sv_actual; /* number of entries in use */
  176504. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  176505. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  176506. * premultiplied as described above. Since colormap indexes must fit into
  176507. * JSAMPLEs, the entries of this array will too.
  176508. */
  176509. boolean is_padded; /* is the colorindex padded for odither? */
  176510. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  176511. /* Variables for ordered dithering */
  176512. int row_index; /* cur row's vertical index in dither matrix */
  176513. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  176514. /* Variables for Floyd-Steinberg dithering */
  176515. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  176516. boolean on_odd_row; /* flag to remember which row we are on */
  176517. } my_cquantizer;
  176518. typedef my_cquantizer * my_cquantize_ptr;
  176519. /*
  176520. * Policy-making subroutines for create_colormap and create_colorindex.
  176521. * These routines determine the colormap to be used. The rest of the module
  176522. * only assumes that the colormap is orthogonal.
  176523. *
  176524. * * select_ncolors decides how to divvy up the available colors
  176525. * among the components.
  176526. * * output_value defines the set of representative values for a component.
  176527. * * largest_input_value defines the mapping from input values to
  176528. * representative values for a component.
  176529. * Note that the latter two routines may impose different policies for
  176530. * different components, though this is not currently done.
  176531. */
  176532. LOCAL(int)
  176533. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  176534. /* Determine allocation of desired colors to components, */
  176535. /* and fill in Ncolors[] array to indicate choice. */
  176536. /* Return value is total number of colors (product of Ncolors[] values). */
  176537. {
  176538. int nc = cinfo->out_color_components; /* number of color components */
  176539. int max_colors = cinfo->desired_number_of_colors;
  176540. int total_colors, iroot, i, j;
  176541. boolean changed;
  176542. long temp;
  176543. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  176544. /* We can allocate at least the nc'th root of max_colors per component. */
  176545. /* Compute floor(nc'th root of max_colors). */
  176546. iroot = 1;
  176547. do {
  176548. iroot++;
  176549. temp = iroot; /* set temp = iroot ** nc */
  176550. for (i = 1; i < nc; i++)
  176551. temp *= iroot;
  176552. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  176553. iroot--; /* now iroot = floor(root) */
  176554. /* Must have at least 2 color values per component */
  176555. if (iroot < 2)
  176556. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  176557. /* Initialize to iroot color values for each component */
  176558. total_colors = 1;
  176559. for (i = 0; i < nc; i++) {
  176560. Ncolors[i] = iroot;
  176561. total_colors *= iroot;
  176562. }
  176563. /* We may be able to increment the count for one or more components without
  176564. * exceeding max_colors, though we know not all can be incremented.
  176565. * Sometimes, the first component can be incremented more than once!
  176566. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  176567. * In RGB colorspace, try to increment G first, then R, then B.
  176568. */
  176569. do {
  176570. changed = FALSE;
  176571. for (i = 0; i < nc; i++) {
  176572. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  176573. /* calculate new total_colors if Ncolors[j] is incremented */
  176574. temp = total_colors / Ncolors[j];
  176575. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  176576. if (temp > (long) max_colors)
  176577. break; /* won't fit, done with this pass */
  176578. Ncolors[j]++; /* OK, apply the increment */
  176579. total_colors = (int) temp;
  176580. changed = TRUE;
  176581. }
  176582. } while (changed);
  176583. return total_colors;
  176584. }
  176585. LOCAL(int)
  176586. output_value (j_decompress_ptr, int, int j, int maxj)
  176587. /* Return j'th output value, where j will range from 0 to maxj */
  176588. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  176589. {
  176590. /* We always provide values 0 and MAXJSAMPLE for each component;
  176591. * any additional values are equally spaced between these limits.
  176592. * (Forcing the upper and lower values to the limits ensures that
  176593. * dithering can't produce a color outside the selected gamut.)
  176594. */
  176595. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  176596. }
  176597. LOCAL(int)
  176598. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  176599. /* Return largest input value that should map to j'th output value */
  176600. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  176601. {
  176602. /* Breakpoints are halfway between values returned by output_value */
  176603. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  176604. }
  176605. /*
  176606. * Create the colormap.
  176607. */
  176608. LOCAL(void)
  176609. create_colormap (j_decompress_ptr cinfo)
  176610. {
  176611. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176612. JSAMPARRAY colormap; /* Created colormap */
  176613. int total_colors; /* Number of distinct output colors */
  176614. int i,j,k, nci, blksize, blkdist, ptr, val;
  176615. /* Select number of colors for each component */
  176616. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  176617. /* Report selected color counts */
  176618. if (cinfo->out_color_components == 3)
  176619. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  176620. total_colors, cquantize->Ncolors[0],
  176621. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  176622. else
  176623. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  176624. /* Allocate and fill in the colormap. */
  176625. /* The colors are ordered in the map in standard row-major order, */
  176626. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  176627. colormap = (*cinfo->mem->alloc_sarray)
  176628. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176629. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  176630. /* blksize is number of adjacent repeated entries for a component */
  176631. /* blkdist is distance between groups of identical entries for a component */
  176632. blkdist = total_colors;
  176633. for (i = 0; i < cinfo->out_color_components; i++) {
  176634. /* fill in colormap entries for i'th color component */
  176635. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176636. blksize = blkdist / nci;
  176637. for (j = 0; j < nci; j++) {
  176638. /* Compute j'th output value (out of nci) for component */
  176639. val = output_value(cinfo, i, j, nci-1);
  176640. /* Fill in all colormap entries that have this value of this component */
  176641. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  176642. /* fill in blksize entries beginning at ptr */
  176643. for (k = 0; k < blksize; k++)
  176644. colormap[i][ptr+k] = (JSAMPLE) val;
  176645. }
  176646. }
  176647. blkdist = blksize; /* blksize of this color is blkdist of next */
  176648. }
  176649. /* Save the colormap in private storage,
  176650. * where it will survive color quantization mode changes.
  176651. */
  176652. cquantize->sv_colormap = colormap;
  176653. cquantize->sv_actual = total_colors;
  176654. }
  176655. /*
  176656. * Create the color index table.
  176657. */
  176658. LOCAL(void)
  176659. create_colorindex (j_decompress_ptr cinfo)
  176660. {
  176661. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176662. JSAMPROW indexptr;
  176663. int i,j,k, nci, blksize, val, pad;
  176664. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  176665. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  176666. * This is not necessary in the other dithering modes. However, we
  176667. * flag whether it was done in case user changes dithering mode.
  176668. */
  176669. if (cinfo->dither_mode == JDITHER_ORDERED) {
  176670. pad = MAXJSAMPLE*2;
  176671. cquantize->is_padded = TRUE;
  176672. } else {
  176673. pad = 0;
  176674. cquantize->is_padded = FALSE;
  176675. }
  176676. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  176677. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176678. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  176679. (JDIMENSION) cinfo->out_color_components);
  176680. /* blksize is number of adjacent repeated entries for a component */
  176681. blksize = cquantize->sv_actual;
  176682. for (i = 0; i < cinfo->out_color_components; i++) {
  176683. /* fill in colorindex entries for i'th color component */
  176684. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176685. blksize = blksize / nci;
  176686. /* adjust colorindex pointers to provide padding at negative indexes. */
  176687. if (pad)
  176688. cquantize->colorindex[i] += MAXJSAMPLE;
  176689. /* in loop, val = index of current output value, */
  176690. /* and k = largest j that maps to current val */
  176691. indexptr = cquantize->colorindex[i];
  176692. val = 0;
  176693. k = largest_input_value(cinfo, i, 0, nci-1);
  176694. for (j = 0; j <= MAXJSAMPLE; j++) {
  176695. while (j > k) /* advance val if past boundary */
  176696. k = largest_input_value(cinfo, i, ++val, nci-1);
  176697. /* premultiply so that no multiplication needed in main processing */
  176698. indexptr[j] = (JSAMPLE) (val * blksize);
  176699. }
  176700. /* Pad at both ends if necessary */
  176701. if (pad)
  176702. for (j = 1; j <= MAXJSAMPLE; j++) {
  176703. indexptr[-j] = indexptr[0];
  176704. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  176705. }
  176706. }
  176707. }
  176708. /*
  176709. * Create an ordered-dither array for a component having ncolors
  176710. * distinct output values.
  176711. */
  176712. LOCAL(ODITHER_MATRIX_PTR)
  176713. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  176714. {
  176715. ODITHER_MATRIX_PTR odither;
  176716. int j,k;
  176717. INT32 num,den;
  176718. odither = (ODITHER_MATRIX_PTR)
  176719. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176720. SIZEOF(ODITHER_MATRIX));
  176721. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  176722. * Hence the dither value for the matrix cell with fill order f
  176723. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  176724. * On 16-bit-int machine, be careful to avoid overflow.
  176725. */
  176726. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  176727. for (j = 0; j < ODITHER_SIZE; j++) {
  176728. for (k = 0; k < ODITHER_SIZE; k++) {
  176729. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  176730. * MAXJSAMPLE;
  176731. /* Ensure round towards zero despite C's lack of consistency
  176732. * about rounding negative values in integer division...
  176733. */
  176734. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  176735. }
  176736. }
  176737. return odither;
  176738. }
  176739. /*
  176740. * Create the ordered-dither tables.
  176741. * Components having the same number of representative colors may
  176742. * share a dither table.
  176743. */
  176744. LOCAL(void)
  176745. create_odither_tables (j_decompress_ptr cinfo)
  176746. {
  176747. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176748. ODITHER_MATRIX_PTR odither;
  176749. int i, j, nci;
  176750. for (i = 0; i < cinfo->out_color_components; i++) {
  176751. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176752. odither = NULL; /* search for matching prior component */
  176753. for (j = 0; j < i; j++) {
  176754. if (nci == cquantize->Ncolors[j]) {
  176755. odither = cquantize->odither[j];
  176756. break;
  176757. }
  176758. }
  176759. if (odither == NULL) /* need a new table? */
  176760. odither = make_odither_array(cinfo, nci);
  176761. cquantize->odither[i] = odither;
  176762. }
  176763. }
  176764. /*
  176765. * Map some rows of pixels to the output colormapped representation.
  176766. */
  176767. METHODDEF(void)
  176768. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176769. JSAMPARRAY output_buf, int num_rows)
  176770. /* General case, no dithering */
  176771. {
  176772. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176773. JSAMPARRAY colorindex = cquantize->colorindex;
  176774. register int pixcode, ci;
  176775. register JSAMPROW ptrin, ptrout;
  176776. int row;
  176777. JDIMENSION col;
  176778. JDIMENSION width = cinfo->output_width;
  176779. register int nc = cinfo->out_color_components;
  176780. for (row = 0; row < num_rows; row++) {
  176781. ptrin = input_buf[row];
  176782. ptrout = output_buf[row];
  176783. for (col = width; col > 0; col--) {
  176784. pixcode = 0;
  176785. for (ci = 0; ci < nc; ci++) {
  176786. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  176787. }
  176788. *ptrout++ = (JSAMPLE) pixcode;
  176789. }
  176790. }
  176791. }
  176792. METHODDEF(void)
  176793. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176794. JSAMPARRAY output_buf, int num_rows)
  176795. /* Fast path for out_color_components==3, no dithering */
  176796. {
  176797. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176798. register int pixcode;
  176799. register JSAMPROW ptrin, ptrout;
  176800. JSAMPROW colorindex0 = cquantize->colorindex[0];
  176801. JSAMPROW colorindex1 = cquantize->colorindex[1];
  176802. JSAMPROW colorindex2 = cquantize->colorindex[2];
  176803. int row;
  176804. JDIMENSION col;
  176805. JDIMENSION width = cinfo->output_width;
  176806. for (row = 0; row < num_rows; row++) {
  176807. ptrin = input_buf[row];
  176808. ptrout = output_buf[row];
  176809. for (col = width; col > 0; col--) {
  176810. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  176811. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  176812. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  176813. *ptrout++ = (JSAMPLE) pixcode;
  176814. }
  176815. }
  176816. }
  176817. METHODDEF(void)
  176818. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176819. JSAMPARRAY output_buf, int num_rows)
  176820. /* General case, with ordered dithering */
  176821. {
  176822. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176823. register JSAMPROW input_ptr;
  176824. register JSAMPROW output_ptr;
  176825. JSAMPROW colorindex_ci;
  176826. int * dither; /* points to active row of dither matrix */
  176827. int row_index, col_index; /* current indexes into dither matrix */
  176828. int nc = cinfo->out_color_components;
  176829. int ci;
  176830. int row;
  176831. JDIMENSION col;
  176832. JDIMENSION width = cinfo->output_width;
  176833. for (row = 0; row < num_rows; row++) {
  176834. /* Initialize output values to 0 so can process components separately */
  176835. jzero_far((void FAR *) output_buf[row],
  176836. (size_t) (width * SIZEOF(JSAMPLE)));
  176837. row_index = cquantize->row_index;
  176838. for (ci = 0; ci < nc; ci++) {
  176839. input_ptr = input_buf[row] + ci;
  176840. output_ptr = output_buf[row];
  176841. colorindex_ci = cquantize->colorindex[ci];
  176842. dither = cquantize->odither[ci][row_index];
  176843. col_index = 0;
  176844. for (col = width; col > 0; col--) {
  176845. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  176846. * select output value, accumulate into output code for this pixel.
  176847. * Range-limiting need not be done explicitly, as we have extended
  176848. * the colorindex table to produce the right answers for out-of-range
  176849. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  176850. * required amount of padding.
  176851. */
  176852. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  176853. input_ptr += nc;
  176854. output_ptr++;
  176855. col_index = (col_index + 1) & ODITHER_MASK;
  176856. }
  176857. }
  176858. /* Advance row index for next row */
  176859. row_index = (row_index + 1) & ODITHER_MASK;
  176860. cquantize->row_index = row_index;
  176861. }
  176862. }
  176863. METHODDEF(void)
  176864. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176865. JSAMPARRAY output_buf, int num_rows)
  176866. /* Fast path for out_color_components==3, with ordered dithering */
  176867. {
  176868. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176869. register int pixcode;
  176870. register JSAMPROW input_ptr;
  176871. register JSAMPROW output_ptr;
  176872. JSAMPROW colorindex0 = cquantize->colorindex[0];
  176873. JSAMPROW colorindex1 = cquantize->colorindex[1];
  176874. JSAMPROW colorindex2 = cquantize->colorindex[2];
  176875. int * dither0; /* points to active row of dither matrix */
  176876. int * dither1;
  176877. int * dither2;
  176878. int row_index, col_index; /* current indexes into dither matrix */
  176879. int row;
  176880. JDIMENSION col;
  176881. JDIMENSION width = cinfo->output_width;
  176882. for (row = 0; row < num_rows; row++) {
  176883. row_index = cquantize->row_index;
  176884. input_ptr = input_buf[row];
  176885. output_ptr = output_buf[row];
  176886. dither0 = cquantize->odither[0][row_index];
  176887. dither1 = cquantize->odither[1][row_index];
  176888. dither2 = cquantize->odither[2][row_index];
  176889. col_index = 0;
  176890. for (col = width; col > 0; col--) {
  176891. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  176892. dither0[col_index]]);
  176893. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  176894. dither1[col_index]]);
  176895. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  176896. dither2[col_index]]);
  176897. *output_ptr++ = (JSAMPLE) pixcode;
  176898. col_index = (col_index + 1) & ODITHER_MASK;
  176899. }
  176900. row_index = (row_index + 1) & ODITHER_MASK;
  176901. cquantize->row_index = row_index;
  176902. }
  176903. }
  176904. METHODDEF(void)
  176905. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176906. JSAMPARRAY output_buf, int num_rows)
  176907. /* General case, with Floyd-Steinberg dithering */
  176908. {
  176909. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176910. register LOCFSERROR cur; /* current error or pixel value */
  176911. LOCFSERROR belowerr; /* error for pixel below cur */
  176912. LOCFSERROR bpreverr; /* error for below/prev col */
  176913. LOCFSERROR bnexterr; /* error for below/next col */
  176914. LOCFSERROR delta;
  176915. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  176916. register JSAMPROW input_ptr;
  176917. register JSAMPROW output_ptr;
  176918. JSAMPROW colorindex_ci;
  176919. JSAMPROW colormap_ci;
  176920. int pixcode;
  176921. int nc = cinfo->out_color_components;
  176922. int dir; /* 1 for left-to-right, -1 for right-to-left */
  176923. int dirnc; /* dir * nc */
  176924. int ci;
  176925. int row;
  176926. JDIMENSION col;
  176927. JDIMENSION width = cinfo->output_width;
  176928. JSAMPLE *range_limit = cinfo->sample_range_limit;
  176929. SHIFT_TEMPS
  176930. for (row = 0; row < num_rows; row++) {
  176931. /* Initialize output values to 0 so can process components separately */
  176932. jzero_far((void FAR *) output_buf[row],
  176933. (size_t) (width * SIZEOF(JSAMPLE)));
  176934. for (ci = 0; ci < nc; ci++) {
  176935. input_ptr = input_buf[row] + ci;
  176936. output_ptr = output_buf[row];
  176937. if (cquantize->on_odd_row) {
  176938. /* work right to left in this row */
  176939. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  176940. output_ptr += width-1;
  176941. dir = -1;
  176942. dirnc = -nc;
  176943. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  176944. } else {
  176945. /* work left to right in this row */
  176946. dir = 1;
  176947. dirnc = nc;
  176948. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  176949. }
  176950. colorindex_ci = cquantize->colorindex[ci];
  176951. colormap_ci = cquantize->sv_colormap[ci];
  176952. /* Preset error values: no error propagated to first pixel from left */
  176953. cur = 0;
  176954. /* and no error propagated to row below yet */
  176955. belowerr = bpreverr = 0;
  176956. for (col = width; col > 0; col--) {
  176957. /* cur holds the error propagated from the previous pixel on the
  176958. * current line. Add the error propagated from the previous line
  176959. * to form the complete error correction term for this pixel, and
  176960. * round the error term (which is expressed * 16) to an integer.
  176961. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  176962. * for either sign of the error value.
  176963. * Note: errorptr points to *previous* column's array entry.
  176964. */
  176965. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  176966. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  176967. * The maximum error is +- MAXJSAMPLE; this sets the required size
  176968. * of the range_limit array.
  176969. */
  176970. cur += GETJSAMPLE(*input_ptr);
  176971. cur = GETJSAMPLE(range_limit[cur]);
  176972. /* Select output value, accumulate into output code for this pixel */
  176973. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  176974. *output_ptr += (JSAMPLE) pixcode;
  176975. /* Compute actual representation error at this pixel */
  176976. /* Note: we can do this even though we don't have the final */
  176977. /* pixel code, because the colormap is orthogonal. */
  176978. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  176979. /* Compute error fractions to be propagated to adjacent pixels.
  176980. * Add these into the running sums, and simultaneously shift the
  176981. * next-line error sums left by 1 column.
  176982. */
  176983. bnexterr = cur;
  176984. delta = cur * 2;
  176985. cur += delta; /* form error * 3 */
  176986. errorptr[0] = (FSERROR) (bpreverr + cur);
  176987. cur += delta; /* form error * 5 */
  176988. bpreverr = belowerr + cur;
  176989. belowerr = bnexterr;
  176990. cur += delta; /* form error * 7 */
  176991. /* At this point cur contains the 7/16 error value to be propagated
  176992. * to the next pixel on the current line, and all the errors for the
  176993. * next line have been shifted over. We are therefore ready to move on.
  176994. */
  176995. input_ptr += dirnc; /* advance input ptr to next column */
  176996. output_ptr += dir; /* advance output ptr to next column */
  176997. errorptr += dir; /* advance errorptr to current column */
  176998. }
  176999. /* Post-loop cleanup: we must unload the final error value into the
  177000. * final fserrors[] entry. Note we need not unload belowerr because
  177001. * it is for the dummy column before or after the actual array.
  177002. */
  177003. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177004. }
  177005. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177006. }
  177007. }
  177008. /*
  177009. * Allocate workspace for Floyd-Steinberg errors.
  177010. */
  177011. LOCAL(void)
  177012. alloc_fs_workspace (j_decompress_ptr cinfo)
  177013. {
  177014. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177015. size_t arraysize;
  177016. int i;
  177017. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177018. for (i = 0; i < cinfo->out_color_components; i++) {
  177019. cquantize->fserrors[i] = (FSERRPTR)
  177020. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177021. }
  177022. }
  177023. /*
  177024. * Initialize for one-pass color quantization.
  177025. */
  177026. METHODDEF(void)
  177027. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177028. {
  177029. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177030. size_t arraysize;
  177031. int i;
  177032. /* Install my colormap. */
  177033. cinfo->colormap = cquantize->sv_colormap;
  177034. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177035. /* Initialize for desired dithering mode. */
  177036. switch (cinfo->dither_mode) {
  177037. case JDITHER_NONE:
  177038. if (cinfo->out_color_components == 3)
  177039. cquantize->pub.color_quantize = color_quantize3;
  177040. else
  177041. cquantize->pub.color_quantize = color_quantize;
  177042. break;
  177043. case JDITHER_ORDERED:
  177044. if (cinfo->out_color_components == 3)
  177045. cquantize->pub.color_quantize = quantize3_ord_dither;
  177046. else
  177047. cquantize->pub.color_quantize = quantize_ord_dither;
  177048. cquantize->row_index = 0; /* initialize state for ordered dither */
  177049. /* If user changed to ordered dither from another mode,
  177050. * we must recreate the color index table with padding.
  177051. * This will cost extra space, but probably isn't very likely.
  177052. */
  177053. if (! cquantize->is_padded)
  177054. create_colorindex(cinfo);
  177055. /* Create ordered-dither tables if we didn't already. */
  177056. if (cquantize->odither[0] == NULL)
  177057. create_odither_tables(cinfo);
  177058. break;
  177059. case JDITHER_FS:
  177060. cquantize->pub.color_quantize = quantize_fs_dither;
  177061. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177062. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177063. if (cquantize->fserrors[0] == NULL)
  177064. alloc_fs_workspace(cinfo);
  177065. /* Initialize the propagated errors to zero. */
  177066. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177067. for (i = 0; i < cinfo->out_color_components; i++)
  177068. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177069. break;
  177070. default:
  177071. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177072. break;
  177073. }
  177074. }
  177075. /*
  177076. * Finish up at the end of the pass.
  177077. */
  177078. METHODDEF(void)
  177079. finish_pass_1_quant (j_decompress_ptr)
  177080. {
  177081. /* no work in 1-pass case */
  177082. }
  177083. /*
  177084. * Switch to a new external colormap between output passes.
  177085. * Shouldn't get to this module!
  177086. */
  177087. METHODDEF(void)
  177088. new_color_map_1_quant (j_decompress_ptr cinfo)
  177089. {
  177090. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177091. }
  177092. /*
  177093. * Module initialization routine for 1-pass color quantization.
  177094. */
  177095. GLOBAL(void)
  177096. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177097. {
  177098. my_cquantize_ptr cquantize;
  177099. cquantize = (my_cquantize_ptr)
  177100. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177101. SIZEOF(my_cquantizer));
  177102. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177103. cquantize->pub.start_pass = start_pass_1_quant;
  177104. cquantize->pub.finish_pass = finish_pass_1_quant;
  177105. cquantize->pub.new_color_map = new_color_map_1_quant;
  177106. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177107. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177108. /* Make sure my internal arrays won't overflow */
  177109. if (cinfo->out_color_components > MAX_Q_COMPS)
  177110. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177111. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177112. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177113. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177114. /* Create the colormap and color index table. */
  177115. create_colormap(cinfo);
  177116. create_colorindex(cinfo);
  177117. /* Allocate Floyd-Steinberg workspace now if requested.
  177118. * We do this now since it is FAR storage and may affect the memory
  177119. * manager's space calculations. If the user changes to FS dither
  177120. * mode in a later pass, we will allocate the space then, and will
  177121. * possibly overrun the max_memory_to_use setting.
  177122. */
  177123. if (cinfo->dither_mode == JDITHER_FS)
  177124. alloc_fs_workspace(cinfo);
  177125. }
  177126. #endif /* QUANT_1PASS_SUPPORTED */
  177127. /*** End of inlined file: jquant1.c ***/
  177128. /*** Start of inlined file: jquant2.c ***/
  177129. #define JPEG_INTERNALS
  177130. #ifdef QUANT_2PASS_SUPPORTED
  177131. /*
  177132. * This module implements the well-known Heckbert paradigm for color
  177133. * quantization. Most of the ideas used here can be traced back to
  177134. * Heckbert's seminal paper
  177135. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177136. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177137. *
  177138. * In the first pass over the image, we accumulate a histogram showing the
  177139. * usage count of each possible color. To keep the histogram to a reasonable
  177140. * size, we reduce the precision of the input; typical practice is to retain
  177141. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177142. * in the same histogram cell.
  177143. *
  177144. * Next, the color-selection step begins with a box representing the whole
  177145. * color space, and repeatedly splits the "largest" remaining box until we
  177146. * have as many boxes as desired colors. Then the mean color in each
  177147. * remaining box becomes one of the possible output colors.
  177148. *
  177149. * The second pass over the image maps each input pixel to the closest output
  177150. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177151. * This mapping is logically trivial, but making it go fast enough requires
  177152. * considerable care.
  177153. *
  177154. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177155. * the "largest" box and deciding where to cut it. The particular policies
  177156. * used here have proved out well in experimental comparisons, but better ones
  177157. * may yet be found.
  177158. *
  177159. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177160. * space, processing the raw upsampled data without a color conversion step.
  177161. * This allowed the color conversion math to be done only once per colormap
  177162. * entry, not once per pixel. However, that optimization precluded other
  177163. * useful optimizations (such as merging color conversion with upsampling)
  177164. * and it also interfered with desired capabilities such as quantizing to an
  177165. * externally-supplied colormap. We have therefore abandoned that approach.
  177166. * The present code works in the post-conversion color space, typically RGB.
  177167. *
  177168. * To improve the visual quality of the results, we actually work in scaled
  177169. * RGB space, giving G distances more weight than R, and R in turn more than
  177170. * B. To do everything in integer math, we must use integer scale factors.
  177171. * The 2/3/1 scale factors used here correspond loosely to the relative
  177172. * weights of the colors in the NTSC grayscale equation.
  177173. * If you want to use this code to quantize a non-RGB color space, you'll
  177174. * probably need to change these scale factors.
  177175. */
  177176. #define R_SCALE 2 /* scale R distances by this much */
  177177. #define G_SCALE 3 /* scale G distances by this much */
  177178. #define B_SCALE 1 /* and B by this much */
  177179. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177180. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177181. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177182. * you'll get compile errors until you extend this logic. In that case
  177183. * you'll probably want to tweak the histogram sizes too.
  177184. */
  177185. #if RGB_RED == 0
  177186. #define C0_SCALE R_SCALE
  177187. #endif
  177188. #if RGB_BLUE == 0
  177189. #define C0_SCALE B_SCALE
  177190. #endif
  177191. #if RGB_GREEN == 1
  177192. #define C1_SCALE G_SCALE
  177193. #endif
  177194. #if RGB_RED == 2
  177195. #define C2_SCALE R_SCALE
  177196. #endif
  177197. #if RGB_BLUE == 2
  177198. #define C2_SCALE B_SCALE
  177199. #endif
  177200. /*
  177201. * First we have the histogram data structure and routines for creating it.
  177202. *
  177203. * The number of bits of precision can be adjusted by changing these symbols.
  177204. * We recommend keeping 6 bits for G and 5 each for R and B.
  177205. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177206. * better results; if you are short of memory, 5 bits all around will save
  177207. * some space but degrade the results.
  177208. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177209. * (preferably unsigned long) for each cell. In practice this is overkill;
  177210. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177211. * and clamping those that do overflow to the maximum value will give close-
  177212. * enough results. This reduces the recommended histogram size from 256Kb
  177213. * to 128Kb, which is a useful savings on PC-class machines.
  177214. * (In the second pass the histogram space is re-used for pixel mapping data;
  177215. * in that capacity, each cell must be able to store zero to the number of
  177216. * desired colors. 16 bits/cell is plenty for that too.)
  177217. * Since the JPEG code is intended to run in small memory model on 80x86
  177218. * machines, we can't just allocate the histogram in one chunk. Instead
  177219. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177220. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177221. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177222. * on 80x86 machines, the pointer row is in near memory but the actual
  177223. * arrays are in far memory (same arrangement as we use for image arrays).
  177224. */
  177225. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177226. /* These will do the right thing for either R,G,B or B,G,R color order,
  177227. * but you may not like the results for other color orders.
  177228. */
  177229. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177230. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177231. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177232. /* Number of elements along histogram axes. */
  177233. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177234. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177235. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177236. /* These are the amounts to shift an input value to get a histogram index. */
  177237. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177238. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177239. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177240. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177241. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177242. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177243. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177244. typedef hist2d * hist3d; /* type for top-level pointer */
  177245. /* Declarations for Floyd-Steinberg dithering.
  177246. *
  177247. * Errors are accumulated into the array fserrors[], at a resolution of
  177248. * 1/16th of a pixel count. The error at a given pixel is propagated
  177249. * to its not-yet-processed neighbors using the standard F-S fractions,
  177250. * ... (here) 7/16
  177251. * 3/16 5/16 1/16
  177252. * We work left-to-right on even rows, right-to-left on odd rows.
  177253. *
  177254. * We can get away with a single array (holding one row's worth of errors)
  177255. * by using it to store the current row's errors at pixel columns not yet
  177256. * processed, but the next row's errors at columns already processed. We
  177257. * need only a few extra variables to hold the errors immediately around the
  177258. * current column. (If we are lucky, those variables are in registers, but
  177259. * even if not, they're probably cheaper to access than array elements are.)
  177260. *
  177261. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177262. * each end saves us from special-casing the first and last pixels.
  177263. * Each entry is three values long, one value for each color component.
  177264. *
  177265. * Note: on a wide image, we might not have enough room in a PC's near data
  177266. * segment to hold the error array; so it is allocated with alloc_large.
  177267. */
  177268. #if BITS_IN_JSAMPLE == 8
  177269. typedef INT16 FSERROR; /* 16 bits should be enough */
  177270. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177271. #else
  177272. typedef INT32 FSERROR; /* may need more than 16 bits */
  177273. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177274. #endif
  177275. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177276. /* Private subobject */
  177277. typedef struct {
  177278. struct jpeg_color_quantizer pub; /* public fields */
  177279. /* Space for the eventually created colormap is stashed here */
  177280. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  177281. int desired; /* desired # of colors = size of colormap */
  177282. /* Variables for accumulating image statistics */
  177283. hist3d histogram; /* pointer to the histogram */
  177284. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  177285. /* Variables for Floyd-Steinberg dithering */
  177286. FSERRPTR fserrors; /* accumulated errors */
  177287. boolean on_odd_row; /* flag to remember which row we are on */
  177288. int * error_limiter; /* table for clamping the applied error */
  177289. } my_cquantizer2;
  177290. typedef my_cquantizer2 * my_cquantize_ptr2;
  177291. /*
  177292. * Prescan some rows of pixels.
  177293. * In this module the prescan simply updates the histogram, which has been
  177294. * initialized to zeroes by start_pass.
  177295. * An output_buf parameter is required by the method signature, but no data
  177296. * is actually output (in fact the buffer controller is probably passing a
  177297. * NULL pointer).
  177298. */
  177299. METHODDEF(void)
  177300. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177301. JSAMPARRAY, int num_rows)
  177302. {
  177303. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177304. register JSAMPROW ptr;
  177305. register histptr histp;
  177306. register hist3d histogram = cquantize->histogram;
  177307. int row;
  177308. JDIMENSION col;
  177309. JDIMENSION width = cinfo->output_width;
  177310. for (row = 0; row < num_rows; row++) {
  177311. ptr = input_buf[row];
  177312. for (col = width; col > 0; col--) {
  177313. /* get pixel value and index into the histogram */
  177314. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177315. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177316. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177317. /* increment, check for overflow and undo increment if so. */
  177318. if (++(*histp) <= 0)
  177319. (*histp)--;
  177320. ptr += 3;
  177321. }
  177322. }
  177323. }
  177324. /*
  177325. * Next we have the really interesting routines: selection of a colormap
  177326. * given the completed histogram.
  177327. * These routines work with a list of "boxes", each representing a rectangular
  177328. * subset of the input color space (to histogram precision).
  177329. */
  177330. typedef struct {
  177331. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177332. int c0min, c0max;
  177333. int c1min, c1max;
  177334. int c2min, c2max;
  177335. /* The volume (actually 2-norm) of the box */
  177336. INT32 volume;
  177337. /* The number of nonzero histogram cells within this box */
  177338. long colorcount;
  177339. } box;
  177340. typedef box * boxptr;
  177341. LOCAL(boxptr)
  177342. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177343. /* Find the splittable box with the largest color population */
  177344. /* Returns NULL if no splittable boxes remain */
  177345. {
  177346. register boxptr boxp;
  177347. register int i;
  177348. register long maxc = 0;
  177349. boxptr which = NULL;
  177350. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177351. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177352. which = boxp;
  177353. maxc = boxp->colorcount;
  177354. }
  177355. }
  177356. return which;
  177357. }
  177358. LOCAL(boxptr)
  177359. find_biggest_volume (boxptr boxlist, int numboxes)
  177360. /* Find the splittable box with the largest (scaled) volume */
  177361. /* Returns NULL if no splittable boxes remain */
  177362. {
  177363. register boxptr boxp;
  177364. register int i;
  177365. register INT32 maxv = 0;
  177366. boxptr which = NULL;
  177367. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177368. if (boxp->volume > maxv) {
  177369. which = boxp;
  177370. maxv = boxp->volume;
  177371. }
  177372. }
  177373. return which;
  177374. }
  177375. LOCAL(void)
  177376. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177377. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177378. /* and recompute its volume and population */
  177379. {
  177380. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177381. hist3d histogram = cquantize->histogram;
  177382. histptr histp;
  177383. int c0,c1,c2;
  177384. int c0min,c0max,c1min,c1max,c2min,c2max;
  177385. INT32 dist0,dist1,dist2;
  177386. long ccount;
  177387. c0min = boxp->c0min; c0max = boxp->c0max;
  177388. c1min = boxp->c1min; c1max = boxp->c1max;
  177389. c2min = boxp->c2min; c2max = boxp->c2max;
  177390. if (c0max > c0min)
  177391. for (c0 = c0min; c0 <= c0max; c0++)
  177392. for (c1 = c1min; c1 <= c1max; c1++) {
  177393. histp = & histogram[c0][c1][c2min];
  177394. for (c2 = c2min; c2 <= c2max; c2++)
  177395. if (*histp++ != 0) {
  177396. boxp->c0min = c0min = c0;
  177397. goto have_c0min;
  177398. }
  177399. }
  177400. have_c0min:
  177401. if (c0max > c0min)
  177402. for (c0 = c0max; c0 >= c0min; c0--)
  177403. for (c1 = c1min; c1 <= c1max; c1++) {
  177404. histp = & histogram[c0][c1][c2min];
  177405. for (c2 = c2min; c2 <= c2max; c2++)
  177406. if (*histp++ != 0) {
  177407. boxp->c0max = c0max = c0;
  177408. goto have_c0max;
  177409. }
  177410. }
  177411. have_c0max:
  177412. if (c1max > c1min)
  177413. for (c1 = c1min; c1 <= c1max; c1++)
  177414. for (c0 = c0min; c0 <= c0max; c0++) {
  177415. histp = & histogram[c0][c1][c2min];
  177416. for (c2 = c2min; c2 <= c2max; c2++)
  177417. if (*histp++ != 0) {
  177418. boxp->c1min = c1min = c1;
  177419. goto have_c1min;
  177420. }
  177421. }
  177422. have_c1min:
  177423. if (c1max > c1min)
  177424. for (c1 = c1max; c1 >= c1min; c1--)
  177425. for (c0 = c0min; c0 <= c0max; c0++) {
  177426. histp = & histogram[c0][c1][c2min];
  177427. for (c2 = c2min; c2 <= c2max; c2++)
  177428. if (*histp++ != 0) {
  177429. boxp->c1max = c1max = c1;
  177430. goto have_c1max;
  177431. }
  177432. }
  177433. have_c1max:
  177434. if (c2max > c2min)
  177435. for (c2 = c2min; c2 <= c2max; c2++)
  177436. for (c0 = c0min; c0 <= c0max; c0++) {
  177437. histp = & histogram[c0][c1min][c2];
  177438. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177439. if (*histp != 0) {
  177440. boxp->c2min = c2min = c2;
  177441. goto have_c2min;
  177442. }
  177443. }
  177444. have_c2min:
  177445. if (c2max > c2min)
  177446. for (c2 = c2max; c2 >= c2min; c2--)
  177447. for (c0 = c0min; c0 <= c0max; c0++) {
  177448. histp = & histogram[c0][c1min][c2];
  177449. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177450. if (*histp != 0) {
  177451. boxp->c2max = c2max = c2;
  177452. goto have_c2max;
  177453. }
  177454. }
  177455. have_c2max:
  177456. /* Update box volume.
  177457. * We use 2-norm rather than real volume here; this biases the method
  177458. * against making long narrow boxes, and it has the side benefit that
  177459. * a box is splittable iff norm > 0.
  177460. * Since the differences are expressed in histogram-cell units,
  177461. * we have to shift back to JSAMPLE units to get consistent distances;
  177462. * after which, we scale according to the selected distance scale factors.
  177463. */
  177464. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  177465. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  177466. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  177467. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  177468. /* Now scan remaining volume of box and compute population */
  177469. ccount = 0;
  177470. for (c0 = c0min; c0 <= c0max; c0++)
  177471. for (c1 = c1min; c1 <= c1max; c1++) {
  177472. histp = & histogram[c0][c1][c2min];
  177473. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  177474. if (*histp != 0) {
  177475. ccount++;
  177476. }
  177477. }
  177478. boxp->colorcount = ccount;
  177479. }
  177480. LOCAL(int)
  177481. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  177482. int desired_colors)
  177483. /* Repeatedly select and split the largest box until we have enough boxes */
  177484. {
  177485. int n,lb;
  177486. int c0,c1,c2,cmax;
  177487. register boxptr b1,b2;
  177488. while (numboxes < desired_colors) {
  177489. /* Select box to split.
  177490. * Current algorithm: by population for first half, then by volume.
  177491. */
  177492. if (numboxes*2 <= desired_colors) {
  177493. b1 = find_biggest_color_pop(boxlist, numboxes);
  177494. } else {
  177495. b1 = find_biggest_volume(boxlist, numboxes);
  177496. }
  177497. if (b1 == NULL) /* no splittable boxes left! */
  177498. break;
  177499. b2 = &boxlist[numboxes]; /* where new box will go */
  177500. /* Copy the color bounds to the new box. */
  177501. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  177502. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  177503. /* Choose which axis to split the box on.
  177504. * Current algorithm: longest scaled axis.
  177505. * See notes in update_box about scaling distances.
  177506. */
  177507. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  177508. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  177509. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  177510. /* We want to break any ties in favor of green, then red, blue last.
  177511. * This code does the right thing for R,G,B or B,G,R color orders only.
  177512. */
  177513. #if RGB_RED == 0
  177514. cmax = c1; n = 1;
  177515. if (c0 > cmax) { cmax = c0; n = 0; }
  177516. if (c2 > cmax) { n = 2; }
  177517. #else
  177518. cmax = c1; n = 1;
  177519. if (c2 > cmax) { cmax = c2; n = 2; }
  177520. if (c0 > cmax) { n = 0; }
  177521. #endif
  177522. /* Choose split point along selected axis, and update box bounds.
  177523. * Current algorithm: split at halfway point.
  177524. * (Since the box has been shrunk to minimum volume,
  177525. * any split will produce two nonempty subboxes.)
  177526. * Note that lb value is max for lower box, so must be < old max.
  177527. */
  177528. switch (n) {
  177529. case 0:
  177530. lb = (b1->c0max + b1->c0min) / 2;
  177531. b1->c0max = lb;
  177532. b2->c0min = lb+1;
  177533. break;
  177534. case 1:
  177535. lb = (b1->c1max + b1->c1min) / 2;
  177536. b1->c1max = lb;
  177537. b2->c1min = lb+1;
  177538. break;
  177539. case 2:
  177540. lb = (b1->c2max + b1->c2min) / 2;
  177541. b1->c2max = lb;
  177542. b2->c2min = lb+1;
  177543. break;
  177544. }
  177545. /* Update stats for boxes */
  177546. update_box(cinfo, b1);
  177547. update_box(cinfo, b2);
  177548. numboxes++;
  177549. }
  177550. return numboxes;
  177551. }
  177552. LOCAL(void)
  177553. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  177554. /* Compute representative color for a box, put it in colormap[icolor] */
  177555. {
  177556. /* Current algorithm: mean weighted by pixels (not colors) */
  177557. /* Note it is important to get the rounding correct! */
  177558. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177559. hist3d histogram = cquantize->histogram;
  177560. histptr histp;
  177561. int c0,c1,c2;
  177562. int c0min,c0max,c1min,c1max,c2min,c2max;
  177563. long count;
  177564. long total = 0;
  177565. long c0total = 0;
  177566. long c1total = 0;
  177567. long c2total = 0;
  177568. c0min = boxp->c0min; c0max = boxp->c0max;
  177569. c1min = boxp->c1min; c1max = boxp->c1max;
  177570. c2min = boxp->c2min; c2max = boxp->c2max;
  177571. for (c0 = c0min; c0 <= c0max; c0++)
  177572. for (c1 = c1min; c1 <= c1max; c1++) {
  177573. histp = & histogram[c0][c1][c2min];
  177574. for (c2 = c2min; c2 <= c2max; c2++) {
  177575. if ((count = *histp++) != 0) {
  177576. total += count;
  177577. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  177578. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  177579. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  177580. }
  177581. }
  177582. }
  177583. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  177584. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  177585. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  177586. }
  177587. LOCAL(void)
  177588. select_colors (j_decompress_ptr cinfo, int desired_colors)
  177589. /* Master routine for color selection */
  177590. {
  177591. boxptr boxlist;
  177592. int numboxes;
  177593. int i;
  177594. /* Allocate workspace for box list */
  177595. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  177596. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  177597. /* Initialize one box containing whole space */
  177598. numboxes = 1;
  177599. boxlist[0].c0min = 0;
  177600. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  177601. boxlist[0].c1min = 0;
  177602. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  177603. boxlist[0].c2min = 0;
  177604. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  177605. /* Shrink it to actually-used volume and set its statistics */
  177606. update_box(cinfo, & boxlist[0]);
  177607. /* Perform median-cut to produce final box list */
  177608. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  177609. /* Compute the representative color for each box, fill colormap */
  177610. for (i = 0; i < numboxes; i++)
  177611. compute_color(cinfo, & boxlist[i], i);
  177612. cinfo->actual_number_of_colors = numboxes;
  177613. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  177614. }
  177615. /*
  177616. * These routines are concerned with the time-critical task of mapping input
  177617. * colors to the nearest color in the selected colormap.
  177618. *
  177619. * We re-use the histogram space as an "inverse color map", essentially a
  177620. * cache for the results of nearest-color searches. All colors within a
  177621. * histogram cell will be mapped to the same colormap entry, namely the one
  177622. * closest to the cell's center. This may not be quite the closest entry to
  177623. * the actual input color, but it's almost as good. A zero in the cache
  177624. * indicates we haven't found the nearest color for that cell yet; the array
  177625. * is cleared to zeroes before starting the mapping pass. When we find the
  177626. * nearest color for a cell, its colormap index plus one is recorded in the
  177627. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  177628. * when they need to use an unfilled entry in the cache.
  177629. *
  177630. * Our method of efficiently finding nearest colors is based on the "locally
  177631. * sorted search" idea described by Heckbert and on the incremental distance
  177632. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  177633. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  177634. * the distances from a given colormap entry to each cell of the histogram can
  177635. * be computed quickly using an incremental method: the differences between
  177636. * distances to adjacent cells themselves differ by a constant. This allows a
  177637. * fairly fast implementation of the "brute force" approach of computing the
  177638. * distance from every colormap entry to every histogram cell. Unfortunately,
  177639. * it needs a work array to hold the best-distance-so-far for each histogram
  177640. * cell (because the inner loop has to be over cells, not colormap entries).
  177641. * The work array elements have to be INT32s, so the work array would need
  177642. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  177643. *
  177644. * To get around these problems, we apply Thomas' method to compute the
  177645. * nearest colors for only the cells within a small subbox of the histogram.
  177646. * The work array need be only as big as the subbox, so the memory usage
  177647. * problem is solved. Furthermore, we need not fill subboxes that are never
  177648. * referenced in pass2; many images use only part of the color gamut, so a
  177649. * fair amount of work is saved. An additional advantage of this
  177650. * approach is that we can apply Heckbert's locality criterion to quickly
  177651. * eliminate colormap entries that are far away from the subbox; typically
  177652. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  177653. * and we need not compute their distances to individual cells in the subbox.
  177654. * The speed of this approach is heavily influenced by the subbox size: too
  177655. * small means too much overhead, too big loses because Heckbert's criterion
  177656. * can't eliminate as many colormap entries. Empirically the best subbox
  177657. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  177658. *
  177659. * Thomas' article also describes a refined method which is asymptotically
  177660. * faster than the brute-force method, but it is also far more complex and
  177661. * cannot efficiently be applied to small subboxes. It is therefore not
  177662. * useful for programs intended to be portable to DOS machines. On machines
  177663. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  177664. * refined method might be faster than the present code --- but then again,
  177665. * it might not be any faster, and it's certainly more complicated.
  177666. */
  177667. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  177668. #define BOX_C0_LOG (HIST_C0_BITS-3)
  177669. #define BOX_C1_LOG (HIST_C1_BITS-3)
  177670. #define BOX_C2_LOG (HIST_C2_BITS-3)
  177671. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  177672. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  177673. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  177674. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  177675. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  177676. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  177677. /*
  177678. * The next three routines implement inverse colormap filling. They could
  177679. * all be folded into one big routine, but splitting them up this way saves
  177680. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  177681. * and may allow some compilers to produce better code by registerizing more
  177682. * inner-loop variables.
  177683. */
  177684. LOCAL(int)
  177685. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177686. JSAMPLE colorlist[])
  177687. /* Locate the colormap entries close enough to an update box to be candidates
  177688. * for the nearest entry to some cell(s) in the update box. The update box
  177689. * is specified by the center coordinates of its first cell. The number of
  177690. * candidate colormap entries is returned, and their colormap indexes are
  177691. * placed in colorlist[].
  177692. * This routine uses Heckbert's "locally sorted search" criterion to select
  177693. * the colors that need further consideration.
  177694. */
  177695. {
  177696. int numcolors = cinfo->actual_number_of_colors;
  177697. int maxc0, maxc1, maxc2;
  177698. int centerc0, centerc1, centerc2;
  177699. int i, x, ncolors;
  177700. INT32 minmaxdist, min_dist, max_dist, tdist;
  177701. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  177702. /* Compute true coordinates of update box's upper corner and center.
  177703. * Actually we compute the coordinates of the center of the upper-corner
  177704. * histogram cell, which are the upper bounds of the volume we care about.
  177705. * Note that since ">>" rounds down, the "center" values may be closer to
  177706. * min than to max; hence comparisons to them must be "<=", not "<".
  177707. */
  177708. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  177709. centerc0 = (minc0 + maxc0) >> 1;
  177710. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  177711. centerc1 = (minc1 + maxc1) >> 1;
  177712. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  177713. centerc2 = (minc2 + maxc2) >> 1;
  177714. /* For each color in colormap, find:
  177715. * 1. its minimum squared-distance to any point in the update box
  177716. * (zero if color is within update box);
  177717. * 2. its maximum squared-distance to any point in the update box.
  177718. * Both of these can be found by considering only the corners of the box.
  177719. * We save the minimum distance for each color in mindist[];
  177720. * only the smallest maximum distance is of interest.
  177721. */
  177722. minmaxdist = 0x7FFFFFFFL;
  177723. for (i = 0; i < numcolors; i++) {
  177724. /* We compute the squared-c0-distance term, then add in the other two. */
  177725. x = GETJSAMPLE(cinfo->colormap[0][i]);
  177726. if (x < minc0) {
  177727. tdist = (x - minc0) * C0_SCALE;
  177728. min_dist = tdist*tdist;
  177729. tdist = (x - maxc0) * C0_SCALE;
  177730. max_dist = tdist*tdist;
  177731. } else if (x > maxc0) {
  177732. tdist = (x - maxc0) * C0_SCALE;
  177733. min_dist = tdist*tdist;
  177734. tdist = (x - minc0) * C0_SCALE;
  177735. max_dist = tdist*tdist;
  177736. } else {
  177737. /* within cell range so no contribution to min_dist */
  177738. min_dist = 0;
  177739. if (x <= centerc0) {
  177740. tdist = (x - maxc0) * C0_SCALE;
  177741. max_dist = tdist*tdist;
  177742. } else {
  177743. tdist = (x - minc0) * C0_SCALE;
  177744. max_dist = tdist*tdist;
  177745. }
  177746. }
  177747. x = GETJSAMPLE(cinfo->colormap[1][i]);
  177748. if (x < minc1) {
  177749. tdist = (x - minc1) * C1_SCALE;
  177750. min_dist += tdist*tdist;
  177751. tdist = (x - maxc1) * C1_SCALE;
  177752. max_dist += tdist*tdist;
  177753. } else if (x > maxc1) {
  177754. tdist = (x - maxc1) * C1_SCALE;
  177755. min_dist += tdist*tdist;
  177756. tdist = (x - minc1) * C1_SCALE;
  177757. max_dist += tdist*tdist;
  177758. } else {
  177759. /* within cell range so no contribution to min_dist */
  177760. if (x <= centerc1) {
  177761. tdist = (x - maxc1) * C1_SCALE;
  177762. max_dist += tdist*tdist;
  177763. } else {
  177764. tdist = (x - minc1) * C1_SCALE;
  177765. max_dist += tdist*tdist;
  177766. }
  177767. }
  177768. x = GETJSAMPLE(cinfo->colormap[2][i]);
  177769. if (x < minc2) {
  177770. tdist = (x - minc2) * C2_SCALE;
  177771. min_dist += tdist*tdist;
  177772. tdist = (x - maxc2) * C2_SCALE;
  177773. max_dist += tdist*tdist;
  177774. } else if (x > maxc2) {
  177775. tdist = (x - maxc2) * C2_SCALE;
  177776. min_dist += tdist*tdist;
  177777. tdist = (x - minc2) * C2_SCALE;
  177778. max_dist += tdist*tdist;
  177779. } else {
  177780. /* within cell range so no contribution to min_dist */
  177781. if (x <= centerc2) {
  177782. tdist = (x - maxc2) * C2_SCALE;
  177783. max_dist += tdist*tdist;
  177784. } else {
  177785. tdist = (x - minc2) * C2_SCALE;
  177786. max_dist += tdist*tdist;
  177787. }
  177788. }
  177789. mindist[i] = min_dist; /* save away the results */
  177790. if (max_dist < minmaxdist)
  177791. minmaxdist = max_dist;
  177792. }
  177793. /* Now we know that no cell in the update box is more than minmaxdist
  177794. * away from some colormap entry. Therefore, only colors that are
  177795. * within minmaxdist of some part of the box need be considered.
  177796. */
  177797. ncolors = 0;
  177798. for (i = 0; i < numcolors; i++) {
  177799. if (mindist[i] <= minmaxdist)
  177800. colorlist[ncolors++] = (JSAMPLE) i;
  177801. }
  177802. return ncolors;
  177803. }
  177804. LOCAL(void)
  177805. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177806. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  177807. /* Find the closest colormap entry for each cell in the update box,
  177808. * given the list of candidate colors prepared by find_nearby_colors.
  177809. * Return the indexes of the closest entries in the bestcolor[] array.
  177810. * This routine uses Thomas' incremental distance calculation method to
  177811. * find the distance from a colormap entry to successive cells in the box.
  177812. */
  177813. {
  177814. int ic0, ic1, ic2;
  177815. int i, icolor;
  177816. register INT32 * bptr; /* pointer into bestdist[] array */
  177817. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  177818. INT32 dist0, dist1; /* initial distance values */
  177819. register INT32 dist2; /* current distance in inner loop */
  177820. INT32 xx0, xx1; /* distance increments */
  177821. register INT32 xx2;
  177822. INT32 inc0, inc1, inc2; /* initial values for increments */
  177823. /* This array holds the distance to the nearest-so-far color for each cell */
  177824. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  177825. /* Initialize best-distance for each cell of the update box */
  177826. bptr = bestdist;
  177827. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  177828. *bptr++ = 0x7FFFFFFFL;
  177829. /* For each color selected by find_nearby_colors,
  177830. * compute its distance to the center of each cell in the box.
  177831. * If that's less than best-so-far, update best distance and color number.
  177832. */
  177833. /* Nominal steps between cell centers ("x" in Thomas article) */
  177834. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  177835. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  177836. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  177837. for (i = 0; i < numcolors; i++) {
  177838. icolor = GETJSAMPLE(colorlist[i]);
  177839. /* Compute (square of) distance from minc0/c1/c2 to this color */
  177840. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  177841. dist0 = inc0*inc0;
  177842. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  177843. dist0 += inc1*inc1;
  177844. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  177845. dist0 += inc2*inc2;
  177846. /* Form the initial difference increments */
  177847. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  177848. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  177849. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  177850. /* Now loop over all cells in box, updating distance per Thomas method */
  177851. bptr = bestdist;
  177852. cptr = bestcolor;
  177853. xx0 = inc0;
  177854. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  177855. dist1 = dist0;
  177856. xx1 = inc1;
  177857. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  177858. dist2 = dist1;
  177859. xx2 = inc2;
  177860. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  177861. if (dist2 < *bptr) {
  177862. *bptr = dist2;
  177863. *cptr = (JSAMPLE) icolor;
  177864. }
  177865. dist2 += xx2;
  177866. xx2 += 2 * STEP_C2 * STEP_C2;
  177867. bptr++;
  177868. cptr++;
  177869. }
  177870. dist1 += xx1;
  177871. xx1 += 2 * STEP_C1 * STEP_C1;
  177872. }
  177873. dist0 += xx0;
  177874. xx0 += 2 * STEP_C0 * STEP_C0;
  177875. }
  177876. }
  177877. }
  177878. LOCAL(void)
  177879. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  177880. /* Fill the inverse-colormap entries in the update box that contains */
  177881. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  177882. /* we can fill as many others as we wish.) */
  177883. {
  177884. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177885. hist3d histogram = cquantize->histogram;
  177886. int minc0, minc1, minc2; /* lower left corner of update box */
  177887. int ic0, ic1, ic2;
  177888. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  177889. register histptr cachep; /* pointer into main cache array */
  177890. /* This array lists the candidate colormap indexes. */
  177891. JSAMPLE colorlist[MAXNUMCOLORS];
  177892. int numcolors; /* number of candidate colors */
  177893. /* This array holds the actually closest colormap index for each cell. */
  177894. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  177895. /* Convert cell coordinates to update box ID */
  177896. c0 >>= BOX_C0_LOG;
  177897. c1 >>= BOX_C1_LOG;
  177898. c2 >>= BOX_C2_LOG;
  177899. /* Compute true coordinates of update box's origin corner.
  177900. * Actually we compute the coordinates of the center of the corner
  177901. * histogram cell, which are the lower bounds of the volume we care about.
  177902. */
  177903. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  177904. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  177905. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  177906. /* Determine which colormap entries are close enough to be candidates
  177907. * for the nearest entry to some cell in the update box.
  177908. */
  177909. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  177910. /* Determine the actually nearest colors. */
  177911. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  177912. bestcolor);
  177913. /* Save the best color numbers (plus 1) in the main cache array */
  177914. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  177915. c1 <<= BOX_C1_LOG;
  177916. c2 <<= BOX_C2_LOG;
  177917. cptr = bestcolor;
  177918. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  177919. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  177920. cachep = & histogram[c0+ic0][c1+ic1][c2];
  177921. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  177922. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  177923. }
  177924. }
  177925. }
  177926. }
  177927. /*
  177928. * Map some rows of pixels to the output colormapped representation.
  177929. */
  177930. METHODDEF(void)
  177931. pass2_no_dither (j_decompress_ptr cinfo,
  177932. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  177933. /* This version performs no dithering */
  177934. {
  177935. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177936. hist3d histogram = cquantize->histogram;
  177937. register JSAMPROW inptr, outptr;
  177938. register histptr cachep;
  177939. register int c0, c1, c2;
  177940. int row;
  177941. JDIMENSION col;
  177942. JDIMENSION width = cinfo->output_width;
  177943. for (row = 0; row < num_rows; row++) {
  177944. inptr = input_buf[row];
  177945. outptr = output_buf[row];
  177946. for (col = width; col > 0; col--) {
  177947. /* get pixel value and index into the cache */
  177948. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  177949. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  177950. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  177951. cachep = & histogram[c0][c1][c2];
  177952. /* If we have not seen this color before, find nearest colormap entry */
  177953. /* and update the cache */
  177954. if (*cachep == 0)
  177955. fill_inverse_cmap(cinfo, c0,c1,c2);
  177956. /* Now emit the colormap index for this cell */
  177957. *outptr++ = (JSAMPLE) (*cachep - 1);
  177958. }
  177959. }
  177960. }
  177961. METHODDEF(void)
  177962. pass2_fs_dither (j_decompress_ptr cinfo,
  177963. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  177964. /* This version performs Floyd-Steinberg dithering */
  177965. {
  177966. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177967. hist3d histogram = cquantize->histogram;
  177968. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  177969. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  177970. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  177971. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177972. JSAMPROW inptr; /* => current input pixel */
  177973. JSAMPROW outptr; /* => current output pixel */
  177974. histptr cachep;
  177975. int dir; /* +1 or -1 depending on direction */
  177976. int dir3; /* 3*dir, for advancing inptr & errorptr */
  177977. int row;
  177978. JDIMENSION col;
  177979. JDIMENSION width = cinfo->output_width;
  177980. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177981. int *error_limit = cquantize->error_limiter;
  177982. JSAMPROW colormap0 = cinfo->colormap[0];
  177983. JSAMPROW colormap1 = cinfo->colormap[1];
  177984. JSAMPROW colormap2 = cinfo->colormap[2];
  177985. SHIFT_TEMPS
  177986. for (row = 0; row < num_rows; row++) {
  177987. inptr = input_buf[row];
  177988. outptr = output_buf[row];
  177989. if (cquantize->on_odd_row) {
  177990. /* work right to left in this row */
  177991. inptr += (width-1) * 3; /* so point to rightmost pixel */
  177992. outptr += width-1;
  177993. dir = -1;
  177994. dir3 = -3;
  177995. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  177996. cquantize->on_odd_row = FALSE; /* flip for next time */
  177997. } else {
  177998. /* work left to right in this row */
  177999. dir = 1;
  178000. dir3 = 3;
  178001. errorptr = cquantize->fserrors; /* => entry before first real column */
  178002. cquantize->on_odd_row = TRUE; /* flip for next time */
  178003. }
  178004. /* Preset error values: no error propagated to first pixel from left */
  178005. cur0 = cur1 = cur2 = 0;
  178006. /* and no error propagated to row below yet */
  178007. belowerr0 = belowerr1 = belowerr2 = 0;
  178008. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178009. for (col = width; col > 0; col--) {
  178010. /* curN holds the error propagated from the previous pixel on the
  178011. * current line. Add the error propagated from the previous line
  178012. * to form the complete error correction term for this pixel, and
  178013. * round the error term (which is expressed * 16) to an integer.
  178014. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178015. * for either sign of the error value.
  178016. * Note: errorptr points to *previous* column's array entry.
  178017. */
  178018. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178019. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178020. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178021. /* Limit the error using transfer function set by init_error_limit.
  178022. * See comments with init_error_limit for rationale.
  178023. */
  178024. cur0 = error_limit[cur0];
  178025. cur1 = error_limit[cur1];
  178026. cur2 = error_limit[cur2];
  178027. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178028. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178029. * this sets the required size of the range_limit array.
  178030. */
  178031. cur0 += GETJSAMPLE(inptr[0]);
  178032. cur1 += GETJSAMPLE(inptr[1]);
  178033. cur2 += GETJSAMPLE(inptr[2]);
  178034. cur0 = GETJSAMPLE(range_limit[cur0]);
  178035. cur1 = GETJSAMPLE(range_limit[cur1]);
  178036. cur2 = GETJSAMPLE(range_limit[cur2]);
  178037. /* Index into the cache with adjusted pixel value */
  178038. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178039. /* If we have not seen this color before, find nearest colormap */
  178040. /* entry and update the cache */
  178041. if (*cachep == 0)
  178042. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178043. /* Now emit the colormap index for this cell */
  178044. { register int pixcode = *cachep - 1;
  178045. *outptr = (JSAMPLE) pixcode;
  178046. /* Compute representation error for this pixel */
  178047. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178048. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178049. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178050. }
  178051. /* Compute error fractions to be propagated to adjacent pixels.
  178052. * Add these into the running sums, and simultaneously shift the
  178053. * next-line error sums left by 1 column.
  178054. */
  178055. { register LOCFSERROR bnexterr, delta;
  178056. bnexterr = cur0; /* Process component 0 */
  178057. delta = cur0 * 2;
  178058. cur0 += delta; /* form error * 3 */
  178059. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178060. cur0 += delta; /* form error * 5 */
  178061. bpreverr0 = belowerr0 + cur0;
  178062. belowerr0 = bnexterr;
  178063. cur0 += delta; /* form error * 7 */
  178064. bnexterr = cur1; /* Process component 1 */
  178065. delta = cur1 * 2;
  178066. cur1 += delta; /* form error * 3 */
  178067. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178068. cur1 += delta; /* form error * 5 */
  178069. bpreverr1 = belowerr1 + cur1;
  178070. belowerr1 = bnexterr;
  178071. cur1 += delta; /* form error * 7 */
  178072. bnexterr = cur2; /* Process component 2 */
  178073. delta = cur2 * 2;
  178074. cur2 += delta; /* form error * 3 */
  178075. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178076. cur2 += delta; /* form error * 5 */
  178077. bpreverr2 = belowerr2 + cur2;
  178078. belowerr2 = bnexterr;
  178079. cur2 += delta; /* form error * 7 */
  178080. }
  178081. /* At this point curN contains the 7/16 error value to be propagated
  178082. * to the next pixel on the current line, and all the errors for the
  178083. * next line have been shifted over. We are therefore ready to move on.
  178084. */
  178085. inptr += dir3; /* Advance pixel pointers to next column */
  178086. outptr += dir;
  178087. errorptr += dir3; /* advance errorptr to current column */
  178088. }
  178089. /* Post-loop cleanup: we must unload the final error values into the
  178090. * final fserrors[] entry. Note we need not unload belowerrN because
  178091. * it is for the dummy column before or after the actual array.
  178092. */
  178093. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178094. errorptr[1] = (FSERROR) bpreverr1;
  178095. errorptr[2] = (FSERROR) bpreverr2;
  178096. }
  178097. }
  178098. /*
  178099. * Initialize the error-limiting transfer function (lookup table).
  178100. * The raw F-S error computation can potentially compute error values of up to
  178101. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178102. * much less, otherwise obviously wrong pixels will be created. (Typical
  178103. * effects include weird fringes at color-area boundaries, isolated bright
  178104. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178105. * is to ensure that the "corners" of the color cube are allocated as output
  178106. * colors; then repeated errors in the same direction cannot cause cascading
  178107. * error buildup. However, that only prevents the error from getting
  178108. * completely out of hand; Aaron Giles reports that error limiting improves
  178109. * the results even with corner colors allocated.
  178110. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178111. * well, but the smoother transfer function used below is even better. Thanks
  178112. * to Aaron Giles for this idea.
  178113. */
  178114. LOCAL(void)
  178115. init_error_limit (j_decompress_ptr cinfo)
  178116. /* Allocate and fill in the error_limiter table */
  178117. {
  178118. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178119. int * table;
  178120. int in, out;
  178121. table = (int *) (*cinfo->mem->alloc_small)
  178122. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178123. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178124. cquantize->error_limiter = table;
  178125. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178126. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178127. out = 0;
  178128. for (in = 0; in < STEPSIZE; in++, out++) {
  178129. table[in] = out; table[-in] = -out;
  178130. }
  178131. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178132. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178133. table[in] = out; table[-in] = -out;
  178134. }
  178135. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178136. for (; in <= MAXJSAMPLE; in++) {
  178137. table[in] = out; table[-in] = -out;
  178138. }
  178139. #undef STEPSIZE
  178140. }
  178141. /*
  178142. * Finish up at the end of each pass.
  178143. */
  178144. METHODDEF(void)
  178145. finish_pass1 (j_decompress_ptr cinfo)
  178146. {
  178147. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178148. /* Select the representative colors and fill in cinfo->colormap */
  178149. cinfo->colormap = cquantize->sv_colormap;
  178150. select_colors(cinfo, cquantize->desired);
  178151. /* Force next pass to zero the color index table */
  178152. cquantize->needs_zeroed = TRUE;
  178153. }
  178154. METHODDEF(void)
  178155. finish_pass2 (j_decompress_ptr)
  178156. {
  178157. /* no work */
  178158. }
  178159. /*
  178160. * Initialize for each processing pass.
  178161. */
  178162. METHODDEF(void)
  178163. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178164. {
  178165. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178166. hist3d histogram = cquantize->histogram;
  178167. int i;
  178168. /* Only F-S dithering or no dithering is supported. */
  178169. /* If user asks for ordered dither, give him F-S. */
  178170. if (cinfo->dither_mode != JDITHER_NONE)
  178171. cinfo->dither_mode = JDITHER_FS;
  178172. if (is_pre_scan) {
  178173. /* Set up method pointers */
  178174. cquantize->pub.color_quantize = prescan_quantize;
  178175. cquantize->pub.finish_pass = finish_pass1;
  178176. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178177. } else {
  178178. /* Set up method pointers */
  178179. if (cinfo->dither_mode == JDITHER_FS)
  178180. cquantize->pub.color_quantize = pass2_fs_dither;
  178181. else
  178182. cquantize->pub.color_quantize = pass2_no_dither;
  178183. cquantize->pub.finish_pass = finish_pass2;
  178184. /* Make sure color count is acceptable */
  178185. i = cinfo->actual_number_of_colors;
  178186. if (i < 1)
  178187. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178188. if (i > MAXNUMCOLORS)
  178189. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178190. if (cinfo->dither_mode == JDITHER_FS) {
  178191. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178192. (3 * SIZEOF(FSERROR)));
  178193. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178194. if (cquantize->fserrors == NULL)
  178195. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178196. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178197. /* Initialize the propagated errors to zero. */
  178198. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178199. /* Make the error-limit table if we didn't already. */
  178200. if (cquantize->error_limiter == NULL)
  178201. init_error_limit(cinfo);
  178202. cquantize->on_odd_row = FALSE;
  178203. }
  178204. }
  178205. /* Zero the histogram or inverse color map, if necessary */
  178206. if (cquantize->needs_zeroed) {
  178207. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178208. jzero_far((void FAR *) histogram[i],
  178209. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178210. }
  178211. cquantize->needs_zeroed = FALSE;
  178212. }
  178213. }
  178214. /*
  178215. * Switch to a new external colormap between output passes.
  178216. */
  178217. METHODDEF(void)
  178218. new_color_map_2_quant (j_decompress_ptr cinfo)
  178219. {
  178220. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178221. /* Reset the inverse color map */
  178222. cquantize->needs_zeroed = TRUE;
  178223. }
  178224. /*
  178225. * Module initialization routine for 2-pass color quantization.
  178226. */
  178227. GLOBAL(void)
  178228. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178229. {
  178230. my_cquantize_ptr2 cquantize;
  178231. int i;
  178232. cquantize = (my_cquantize_ptr2)
  178233. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178234. SIZEOF(my_cquantizer2));
  178235. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178236. cquantize->pub.start_pass = start_pass_2_quant;
  178237. cquantize->pub.new_color_map = new_color_map_2_quant;
  178238. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178239. cquantize->error_limiter = NULL;
  178240. /* Make sure jdmaster didn't give me a case I can't handle */
  178241. if (cinfo->out_color_components != 3)
  178242. ERREXIT(cinfo, JERR_NOTIMPL);
  178243. /* Allocate the histogram/inverse colormap storage */
  178244. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178245. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178246. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178247. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178248. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178249. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178250. }
  178251. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178252. /* Allocate storage for the completed colormap, if required.
  178253. * We do this now since it is FAR storage and may affect
  178254. * the memory manager's space calculations.
  178255. */
  178256. if (cinfo->enable_2pass_quant) {
  178257. /* Make sure color count is acceptable */
  178258. int desired = cinfo->desired_number_of_colors;
  178259. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178260. if (desired < 8)
  178261. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178262. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178263. if (desired > MAXNUMCOLORS)
  178264. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178265. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178266. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178267. cquantize->desired = desired;
  178268. } else
  178269. cquantize->sv_colormap = NULL;
  178270. /* Only F-S dithering or no dithering is supported. */
  178271. /* If user asks for ordered dither, give him F-S. */
  178272. if (cinfo->dither_mode != JDITHER_NONE)
  178273. cinfo->dither_mode = JDITHER_FS;
  178274. /* Allocate Floyd-Steinberg workspace if necessary.
  178275. * This isn't really needed until pass 2, but again it is FAR storage.
  178276. * Although we will cope with a later change in dither_mode,
  178277. * we do not promise to honor max_memory_to_use if dither_mode changes.
  178278. */
  178279. if (cinfo->dither_mode == JDITHER_FS) {
  178280. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178281. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178282. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  178283. /* Might as well create the error-limiting table too. */
  178284. init_error_limit(cinfo);
  178285. }
  178286. }
  178287. #endif /* QUANT_2PASS_SUPPORTED */
  178288. /*** End of inlined file: jquant2.c ***/
  178289. /*** Start of inlined file: jutils.c ***/
  178290. #define JPEG_INTERNALS
  178291. /*
  178292. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  178293. * of a DCT block read in natural order (left to right, top to bottom).
  178294. */
  178295. #if 0 /* This table is not actually needed in v6a */
  178296. const int jpeg_zigzag_order[DCTSIZE2] = {
  178297. 0, 1, 5, 6, 14, 15, 27, 28,
  178298. 2, 4, 7, 13, 16, 26, 29, 42,
  178299. 3, 8, 12, 17, 25, 30, 41, 43,
  178300. 9, 11, 18, 24, 31, 40, 44, 53,
  178301. 10, 19, 23, 32, 39, 45, 52, 54,
  178302. 20, 22, 33, 38, 46, 51, 55, 60,
  178303. 21, 34, 37, 47, 50, 56, 59, 61,
  178304. 35, 36, 48, 49, 57, 58, 62, 63
  178305. };
  178306. #endif
  178307. /*
  178308. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178309. * of zigzag order.
  178310. *
  178311. * When reading corrupted data, the Huffman decoders could attempt
  178312. * to reference an entry beyond the end of this array (if the decoded
  178313. * zero run length reaches past the end of the block). To prevent
  178314. * wild stores without adding an inner-loop test, we put some extra
  178315. * "63"s after the real entries. This will cause the extra coefficient
  178316. * to be stored in location 63 of the block, not somewhere random.
  178317. * The worst case would be a run-length of 15, which means we need 16
  178318. * fake entries.
  178319. */
  178320. const int jpeg_natural_order[DCTSIZE2+16] = {
  178321. 0, 1, 8, 16, 9, 2, 3, 10,
  178322. 17, 24, 32, 25, 18, 11, 4, 5,
  178323. 12, 19, 26, 33, 40, 48, 41, 34,
  178324. 27, 20, 13, 6, 7, 14, 21, 28,
  178325. 35, 42, 49, 56, 57, 50, 43, 36,
  178326. 29, 22, 15, 23, 30, 37, 44, 51,
  178327. 58, 59, 52, 45, 38, 31, 39, 46,
  178328. 53, 60, 61, 54, 47, 55, 62, 63,
  178329. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178330. 63, 63, 63, 63, 63, 63, 63, 63
  178331. };
  178332. /*
  178333. * Arithmetic utilities
  178334. */
  178335. GLOBAL(long)
  178336. jdiv_round_up (long a, long b)
  178337. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178338. /* Assumes a >= 0, b > 0 */
  178339. {
  178340. return (a + b - 1L) / b;
  178341. }
  178342. GLOBAL(long)
  178343. jround_up (long a, long b)
  178344. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178345. /* Assumes a >= 0, b > 0 */
  178346. {
  178347. a += b - 1L;
  178348. return a - (a % b);
  178349. }
  178350. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178351. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178352. * are FAR and we're assuming a small-pointer memory model. However, some
  178353. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178354. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178355. * Otherwise, the routines below do it the hard way. (The performance cost
  178356. * is not all that great, because these routines aren't very heavily used.)
  178357. */
  178358. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178359. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178360. #define FMEMZERO(target,size) MEMZERO(target,size)
  178361. #else /* 80x86 case, define if we can */
  178362. #ifdef USE_FMEM
  178363. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178364. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178365. #endif
  178366. #endif
  178367. GLOBAL(void)
  178368. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178369. JSAMPARRAY output_array, int dest_row,
  178370. int num_rows, JDIMENSION num_cols)
  178371. /* Copy some rows of samples from one place to another.
  178372. * num_rows rows are copied from input_array[source_row++]
  178373. * to output_array[dest_row++]; these areas may overlap for duplication.
  178374. * The source and destination arrays must be at least as wide as num_cols.
  178375. */
  178376. {
  178377. register JSAMPROW inptr, outptr;
  178378. #ifdef FMEMCOPY
  178379. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178380. #else
  178381. register JDIMENSION count;
  178382. #endif
  178383. register int row;
  178384. input_array += source_row;
  178385. output_array += dest_row;
  178386. for (row = num_rows; row > 0; row--) {
  178387. inptr = *input_array++;
  178388. outptr = *output_array++;
  178389. #ifdef FMEMCOPY
  178390. FMEMCOPY(outptr, inptr, count);
  178391. #else
  178392. for (count = num_cols; count > 0; count--)
  178393. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  178394. #endif
  178395. }
  178396. }
  178397. GLOBAL(void)
  178398. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  178399. JDIMENSION num_blocks)
  178400. /* Copy a row of coefficient blocks from one place to another. */
  178401. {
  178402. #ifdef FMEMCOPY
  178403. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  178404. #else
  178405. register JCOEFPTR inptr, outptr;
  178406. register long count;
  178407. inptr = (JCOEFPTR) input_row;
  178408. outptr = (JCOEFPTR) output_row;
  178409. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  178410. *outptr++ = *inptr++;
  178411. }
  178412. #endif
  178413. }
  178414. GLOBAL(void)
  178415. jzero_far (void FAR * target, size_t bytestozero)
  178416. /* Zero out a chunk of FAR memory. */
  178417. /* This might be sample-array data, block-array data, or alloc_large data. */
  178418. {
  178419. #ifdef FMEMZERO
  178420. FMEMZERO(target, bytestozero);
  178421. #else
  178422. register char FAR * ptr = (char FAR *) target;
  178423. register size_t count;
  178424. for (count = bytestozero; count > 0; count--) {
  178425. *ptr++ = 0;
  178426. }
  178427. #endif
  178428. }
  178429. /*** End of inlined file: jutils.c ***/
  178430. /*** Start of inlined file: transupp.c ***/
  178431. /* Although this file really shouldn't have access to the library internals,
  178432. * it's helpful to let it call jround_up() and jcopy_block_row().
  178433. */
  178434. #define JPEG_INTERNALS
  178435. /*** Start of inlined file: transupp.h ***/
  178436. /* If you happen not to want the image transform support, disable it here */
  178437. #ifndef TRANSFORMS_SUPPORTED
  178438. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  178439. #endif
  178440. /* Short forms of external names for systems with brain-damaged linkers. */
  178441. #ifdef NEED_SHORT_EXTERNAL_NAMES
  178442. #define jtransform_request_workspace jTrRequest
  178443. #define jtransform_adjust_parameters jTrAdjust
  178444. #define jtransform_execute_transformation jTrExec
  178445. #define jcopy_markers_setup jCMrkSetup
  178446. #define jcopy_markers_execute jCMrkExec
  178447. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  178448. /*
  178449. * Codes for supported types of image transformations.
  178450. */
  178451. typedef enum {
  178452. JXFORM_NONE, /* no transformation */
  178453. JXFORM_FLIP_H, /* horizontal flip */
  178454. JXFORM_FLIP_V, /* vertical flip */
  178455. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  178456. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  178457. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  178458. JXFORM_ROT_180, /* 180-degree rotation */
  178459. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  178460. } JXFORM_CODE;
  178461. /*
  178462. * Although rotating and flipping data expressed as DCT coefficients is not
  178463. * hard, there is an asymmetry in the JPEG format specification for images
  178464. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  178465. * image edges are padded out to the next iMCU boundary with junk data; but
  178466. * no padding is possible at the top and left edges. If we were to flip
  178467. * the whole image including the pad data, then pad garbage would become
  178468. * visible at the top and/or left, and real pixels would disappear into the
  178469. * pad margins --- perhaps permanently, since encoders & decoders may not
  178470. * bother to preserve DCT blocks that appear to be completely outside the
  178471. * nominal image area. So, we have to exclude any partial iMCUs from the
  178472. * basic transformation.
  178473. *
  178474. * Transpose is the only transformation that can handle partial iMCUs at the
  178475. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  178476. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  178477. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  178478. * The other transforms are defined as combinations of these basic transforms
  178479. * and process edge blocks in a way that preserves the equivalence.
  178480. *
  178481. * The "trim" option causes untransformable partial iMCUs to be dropped;
  178482. * this is not strictly lossless, but it usually gives the best-looking
  178483. * result for odd-size images. Note that when this option is active,
  178484. * the expected mathematical equivalences between the transforms may not hold.
  178485. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  178486. * followed by -rot 180 -trim trims both edges.)
  178487. *
  178488. * We also offer a "force to grayscale" option, which simply discards the
  178489. * chrominance channels of a YCbCr image. This is lossless in the sense that
  178490. * the luminance channel is preserved exactly. It's not the same kind of
  178491. * thing as the rotate/flip transformations, but it's convenient to handle it
  178492. * as part of this package, mainly because the transformation routines have to
  178493. * be aware of the option to know how many components to work on.
  178494. */
  178495. typedef struct {
  178496. /* Options: set by caller */
  178497. JXFORM_CODE transform; /* image transform operator */
  178498. boolean trim; /* if TRUE, trim partial MCUs as needed */
  178499. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  178500. /* Internal workspace: caller should not touch these */
  178501. int num_components; /* # of components in workspace */
  178502. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  178503. } jpeg_transform_info;
  178504. #if TRANSFORMS_SUPPORTED
  178505. /* Request any required workspace */
  178506. EXTERN(void) jtransform_request_workspace
  178507. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  178508. /* Adjust output image parameters */
  178509. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  178510. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178511. jvirt_barray_ptr *src_coef_arrays,
  178512. jpeg_transform_info *info));
  178513. /* Execute the actual transformation, if any */
  178514. EXTERN(void) jtransform_execute_transformation
  178515. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178516. jvirt_barray_ptr *src_coef_arrays,
  178517. jpeg_transform_info *info));
  178518. #endif /* TRANSFORMS_SUPPORTED */
  178519. /*
  178520. * Support for copying optional markers from source to destination file.
  178521. */
  178522. typedef enum {
  178523. JCOPYOPT_NONE, /* copy no optional markers */
  178524. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  178525. JCOPYOPT_ALL /* copy all optional markers */
  178526. } JCOPY_OPTION;
  178527. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  178528. /* Setup decompression object to save desired markers in memory */
  178529. EXTERN(void) jcopy_markers_setup
  178530. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  178531. /* Copy markers saved in the given source object to the destination object */
  178532. EXTERN(void) jcopy_markers_execute
  178533. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178534. JCOPY_OPTION option));
  178535. /*** End of inlined file: transupp.h ***/
  178536. /* My own external interface */
  178537. #if TRANSFORMS_SUPPORTED
  178538. /*
  178539. * Lossless image transformation routines. These routines work on DCT
  178540. * coefficient arrays and thus do not require any lossy decompression
  178541. * or recompression of the image.
  178542. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  178543. *
  178544. * Horizontal flipping is done in-place, using a single top-to-bottom
  178545. * pass through the virtual source array. It will thus be much the
  178546. * fastest option for images larger than main memory.
  178547. *
  178548. * The other routines require a set of destination virtual arrays, so they
  178549. * need twice as much memory as jpegtran normally does. The destination
  178550. * arrays are always written in normal scan order (top to bottom) because
  178551. * the virtual array manager expects this. The source arrays will be scanned
  178552. * in the corresponding order, which means multiple passes through the source
  178553. * arrays for most of the transforms. That could result in much thrashing
  178554. * if the image is larger than main memory.
  178555. *
  178556. * Some notes about the operating environment of the individual transform
  178557. * routines:
  178558. * 1. Both the source and destination virtual arrays are allocated from the
  178559. * source JPEG object, and therefore should be manipulated by calling the
  178560. * source's memory manager.
  178561. * 2. The destination's component count should be used. It may be smaller
  178562. * than the source's when forcing to grayscale.
  178563. * 3. Likewise the destination's sampling factors should be used. When
  178564. * forcing to grayscale the destination's sampling factors will be all 1,
  178565. * and we may as well take that as the effective iMCU size.
  178566. * 4. When "trim" is in effect, the destination's dimensions will be the
  178567. * trimmed values but the source's will be untrimmed.
  178568. * 5. All the routines assume that the source and destination buffers are
  178569. * padded out to a full iMCU boundary. This is true, although for the
  178570. * source buffer it is an undocumented property of jdcoefct.c.
  178571. * Notes 2,3,4 boil down to this: generally we should use the destination's
  178572. * dimensions and ignore the source's.
  178573. */
  178574. LOCAL(void)
  178575. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178576. jvirt_barray_ptr *src_coef_arrays)
  178577. /* Horizontal flip; done in-place, so no separate dest array is required */
  178578. {
  178579. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  178580. int ci, k, offset_y;
  178581. JBLOCKARRAY buffer;
  178582. JCOEFPTR ptr1, ptr2;
  178583. JCOEF temp1, temp2;
  178584. jpeg_component_info *compptr;
  178585. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  178586. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  178587. * mirroring by changing the signs of odd-numbered columns.
  178588. * Partial iMCUs at the right edge are left untouched.
  178589. */
  178590. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178591. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178592. compptr = dstinfo->comp_info + ci;
  178593. comp_width = MCU_cols * compptr->h_samp_factor;
  178594. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  178595. blk_y += compptr->v_samp_factor) {
  178596. buffer = (*srcinfo->mem->access_virt_barray)
  178597. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  178598. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178599. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178600. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  178601. ptr1 = buffer[offset_y][blk_x];
  178602. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  178603. /* this unrolled loop doesn't need to know which row it's on... */
  178604. for (k = 0; k < DCTSIZE2; k += 2) {
  178605. temp1 = *ptr1; /* swap even column */
  178606. temp2 = *ptr2;
  178607. *ptr1++ = temp2;
  178608. *ptr2++ = temp1;
  178609. temp1 = *ptr1; /* swap odd column with sign change */
  178610. temp2 = *ptr2;
  178611. *ptr1++ = -temp2;
  178612. *ptr2++ = -temp1;
  178613. }
  178614. }
  178615. }
  178616. }
  178617. }
  178618. }
  178619. LOCAL(void)
  178620. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178621. jvirt_barray_ptr *src_coef_arrays,
  178622. jvirt_barray_ptr *dst_coef_arrays)
  178623. /* Vertical flip */
  178624. {
  178625. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178626. int ci, i, j, offset_y;
  178627. JBLOCKARRAY src_buffer, dst_buffer;
  178628. JBLOCKROW src_row_ptr, dst_row_ptr;
  178629. JCOEFPTR src_ptr, dst_ptr;
  178630. jpeg_component_info *compptr;
  178631. /* We output into a separate array because we can't touch different
  178632. * rows of the source virtual array simultaneously. Otherwise, this
  178633. * is a pretty straightforward analog of horizontal flip.
  178634. * Within a DCT block, vertical mirroring is done by changing the signs
  178635. * of odd-numbered rows.
  178636. * Partial iMCUs at the bottom edge are copied verbatim.
  178637. */
  178638. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178639. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178640. compptr = dstinfo->comp_info + ci;
  178641. comp_height = MCU_rows * compptr->v_samp_factor;
  178642. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178643. dst_blk_y += compptr->v_samp_factor) {
  178644. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178645. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178646. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178647. if (dst_blk_y < comp_height) {
  178648. /* Row is within the mirrorable area. */
  178649. src_buffer = (*srcinfo->mem->access_virt_barray)
  178650. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  178651. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  178652. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178653. } else {
  178654. /* Bottom-edge blocks will be copied verbatim. */
  178655. src_buffer = (*srcinfo->mem->access_virt_barray)
  178656. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  178657. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178658. }
  178659. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178660. if (dst_blk_y < comp_height) {
  178661. /* Row is within the mirrorable area. */
  178662. dst_row_ptr = dst_buffer[offset_y];
  178663. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  178664. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178665. dst_blk_x++) {
  178666. dst_ptr = dst_row_ptr[dst_blk_x];
  178667. src_ptr = src_row_ptr[dst_blk_x];
  178668. for (i = 0; i < DCTSIZE; i += 2) {
  178669. /* copy even row */
  178670. for (j = 0; j < DCTSIZE; j++)
  178671. *dst_ptr++ = *src_ptr++;
  178672. /* copy odd row with sign change */
  178673. for (j = 0; j < DCTSIZE; j++)
  178674. *dst_ptr++ = - *src_ptr++;
  178675. }
  178676. }
  178677. } else {
  178678. /* Just copy row verbatim. */
  178679. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  178680. compptr->width_in_blocks);
  178681. }
  178682. }
  178683. }
  178684. }
  178685. }
  178686. LOCAL(void)
  178687. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178688. jvirt_barray_ptr *src_coef_arrays,
  178689. jvirt_barray_ptr *dst_coef_arrays)
  178690. /* Transpose source into destination */
  178691. {
  178692. JDIMENSION dst_blk_x, dst_blk_y;
  178693. int ci, i, j, offset_x, offset_y;
  178694. JBLOCKARRAY src_buffer, dst_buffer;
  178695. JCOEFPTR src_ptr, dst_ptr;
  178696. jpeg_component_info *compptr;
  178697. /* Transposing pixels within a block just requires transposing the
  178698. * DCT coefficients.
  178699. * Partial iMCUs at the edges require no special treatment; we simply
  178700. * process all the available DCT blocks for every component.
  178701. */
  178702. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178703. compptr = dstinfo->comp_info + ci;
  178704. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178705. dst_blk_y += compptr->v_samp_factor) {
  178706. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178707. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178708. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178709. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178710. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178711. dst_blk_x += compptr->h_samp_factor) {
  178712. src_buffer = (*srcinfo->mem->access_virt_barray)
  178713. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178714. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178715. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178716. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178717. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178718. for (i = 0; i < DCTSIZE; i++)
  178719. for (j = 0; j < DCTSIZE; j++)
  178720. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178721. }
  178722. }
  178723. }
  178724. }
  178725. }
  178726. }
  178727. LOCAL(void)
  178728. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178729. jvirt_barray_ptr *src_coef_arrays,
  178730. jvirt_barray_ptr *dst_coef_arrays)
  178731. /* 90 degree rotation is equivalent to
  178732. * 1. Transposing the image;
  178733. * 2. Horizontal mirroring.
  178734. * These two steps are merged into a single processing routine.
  178735. */
  178736. {
  178737. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  178738. int ci, i, j, offset_x, offset_y;
  178739. JBLOCKARRAY src_buffer, dst_buffer;
  178740. JCOEFPTR src_ptr, dst_ptr;
  178741. jpeg_component_info *compptr;
  178742. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178743. * at the (output) right edge properly. They just get transposed and
  178744. * not mirrored.
  178745. */
  178746. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178747. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178748. compptr = dstinfo->comp_info + ci;
  178749. comp_width = MCU_cols * compptr->h_samp_factor;
  178750. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178751. dst_blk_y += compptr->v_samp_factor) {
  178752. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178753. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178754. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178755. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178756. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178757. dst_blk_x += compptr->h_samp_factor) {
  178758. src_buffer = (*srcinfo->mem->access_virt_barray)
  178759. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178760. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178761. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178762. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178763. if (dst_blk_x < comp_width) {
  178764. /* Block is within the mirrorable area. */
  178765. dst_ptr = dst_buffer[offset_y]
  178766. [comp_width - dst_blk_x - offset_x - 1];
  178767. for (i = 0; i < DCTSIZE; i++) {
  178768. for (j = 0; j < DCTSIZE; j++)
  178769. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178770. i++;
  178771. for (j = 0; j < DCTSIZE; j++)
  178772. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178773. }
  178774. } else {
  178775. /* Edge blocks are transposed but not mirrored. */
  178776. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178777. for (i = 0; i < DCTSIZE; i++)
  178778. for (j = 0; j < DCTSIZE; j++)
  178779. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178780. }
  178781. }
  178782. }
  178783. }
  178784. }
  178785. }
  178786. }
  178787. LOCAL(void)
  178788. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178789. jvirt_barray_ptr *src_coef_arrays,
  178790. jvirt_barray_ptr *dst_coef_arrays)
  178791. /* 270 degree rotation is equivalent to
  178792. * 1. Horizontal mirroring;
  178793. * 2. Transposing the image.
  178794. * These two steps are merged into a single processing routine.
  178795. */
  178796. {
  178797. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178798. int ci, i, j, offset_x, offset_y;
  178799. JBLOCKARRAY src_buffer, dst_buffer;
  178800. JCOEFPTR src_ptr, dst_ptr;
  178801. jpeg_component_info *compptr;
  178802. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178803. * at the (output) bottom edge properly. They just get transposed and
  178804. * not mirrored.
  178805. */
  178806. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178807. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178808. compptr = dstinfo->comp_info + ci;
  178809. comp_height = MCU_rows * compptr->v_samp_factor;
  178810. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178811. dst_blk_y += compptr->v_samp_factor) {
  178812. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178813. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178814. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178815. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178816. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178817. dst_blk_x += compptr->h_samp_factor) {
  178818. src_buffer = (*srcinfo->mem->access_virt_barray)
  178819. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178820. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178821. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178822. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178823. if (dst_blk_y < comp_height) {
  178824. /* Block is within the mirrorable area. */
  178825. src_ptr = src_buffer[offset_x]
  178826. [comp_height - dst_blk_y - offset_y - 1];
  178827. for (i = 0; i < DCTSIZE; i++) {
  178828. for (j = 0; j < DCTSIZE; j++) {
  178829. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178830. j++;
  178831. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178832. }
  178833. }
  178834. } else {
  178835. /* Edge blocks are transposed but not mirrored. */
  178836. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178837. for (i = 0; i < DCTSIZE; i++)
  178838. for (j = 0; j < DCTSIZE; j++)
  178839. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178840. }
  178841. }
  178842. }
  178843. }
  178844. }
  178845. }
  178846. }
  178847. LOCAL(void)
  178848. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178849. jvirt_barray_ptr *src_coef_arrays,
  178850. jvirt_barray_ptr *dst_coef_arrays)
  178851. /* 180 degree rotation is equivalent to
  178852. * 1. Vertical mirroring;
  178853. * 2. Horizontal mirroring.
  178854. * These two steps are merged into a single processing routine.
  178855. */
  178856. {
  178857. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  178858. int ci, i, j, offset_y;
  178859. JBLOCKARRAY src_buffer, dst_buffer;
  178860. JBLOCKROW src_row_ptr, dst_row_ptr;
  178861. JCOEFPTR src_ptr, dst_ptr;
  178862. jpeg_component_info *compptr;
  178863. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178864. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178865. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178866. compptr = dstinfo->comp_info + ci;
  178867. comp_width = MCU_cols * compptr->h_samp_factor;
  178868. comp_height = MCU_rows * compptr->v_samp_factor;
  178869. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178870. dst_blk_y += compptr->v_samp_factor) {
  178871. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178872. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178873. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178874. if (dst_blk_y < comp_height) {
  178875. /* Row is within the vertically mirrorable area. */
  178876. src_buffer = (*srcinfo->mem->access_virt_barray)
  178877. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  178878. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  178879. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178880. } else {
  178881. /* Bottom-edge rows are only mirrored horizontally. */
  178882. src_buffer = (*srcinfo->mem->access_virt_barray)
  178883. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  178884. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178885. }
  178886. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178887. if (dst_blk_y < comp_height) {
  178888. /* Row is within the mirrorable area. */
  178889. dst_row_ptr = dst_buffer[offset_y];
  178890. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  178891. /* Process the blocks that can be mirrored both ways. */
  178892. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  178893. dst_ptr = dst_row_ptr[dst_blk_x];
  178894. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  178895. for (i = 0; i < DCTSIZE; i += 2) {
  178896. /* For even row, negate every odd column. */
  178897. for (j = 0; j < DCTSIZE; j += 2) {
  178898. *dst_ptr++ = *src_ptr++;
  178899. *dst_ptr++ = - *src_ptr++;
  178900. }
  178901. /* For odd row, negate every even column. */
  178902. for (j = 0; j < DCTSIZE; j += 2) {
  178903. *dst_ptr++ = - *src_ptr++;
  178904. *dst_ptr++ = *src_ptr++;
  178905. }
  178906. }
  178907. }
  178908. /* Any remaining right-edge blocks are only mirrored vertically. */
  178909. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  178910. dst_ptr = dst_row_ptr[dst_blk_x];
  178911. src_ptr = src_row_ptr[dst_blk_x];
  178912. for (i = 0; i < DCTSIZE; i += 2) {
  178913. for (j = 0; j < DCTSIZE; j++)
  178914. *dst_ptr++ = *src_ptr++;
  178915. for (j = 0; j < DCTSIZE; j++)
  178916. *dst_ptr++ = - *src_ptr++;
  178917. }
  178918. }
  178919. } else {
  178920. /* Remaining rows are just mirrored horizontally. */
  178921. dst_row_ptr = dst_buffer[offset_y];
  178922. src_row_ptr = src_buffer[offset_y];
  178923. /* Process the blocks that can be mirrored. */
  178924. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  178925. dst_ptr = dst_row_ptr[dst_blk_x];
  178926. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  178927. for (i = 0; i < DCTSIZE2; i += 2) {
  178928. *dst_ptr++ = *src_ptr++;
  178929. *dst_ptr++ = - *src_ptr++;
  178930. }
  178931. }
  178932. /* Any remaining right-edge blocks are only copied. */
  178933. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  178934. dst_ptr = dst_row_ptr[dst_blk_x];
  178935. src_ptr = src_row_ptr[dst_blk_x];
  178936. for (i = 0; i < DCTSIZE2; i++)
  178937. *dst_ptr++ = *src_ptr++;
  178938. }
  178939. }
  178940. }
  178941. }
  178942. }
  178943. }
  178944. LOCAL(void)
  178945. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178946. jvirt_barray_ptr *src_coef_arrays,
  178947. jvirt_barray_ptr *dst_coef_arrays)
  178948. /* Transverse transpose is equivalent to
  178949. * 1. 180 degree rotation;
  178950. * 2. Transposition;
  178951. * or
  178952. * 1. Horizontal mirroring;
  178953. * 2. Transposition;
  178954. * 3. Horizontal mirroring.
  178955. * These steps are merged into a single processing routine.
  178956. */
  178957. {
  178958. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  178959. int ci, i, j, offset_x, offset_y;
  178960. JBLOCKARRAY src_buffer, dst_buffer;
  178961. JCOEFPTR src_ptr, dst_ptr;
  178962. jpeg_component_info *compptr;
  178963. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178964. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178965. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178966. compptr = dstinfo->comp_info + ci;
  178967. comp_width = MCU_cols * compptr->h_samp_factor;
  178968. comp_height = MCU_rows * compptr->v_samp_factor;
  178969. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178970. dst_blk_y += compptr->v_samp_factor) {
  178971. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178972. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178973. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178974. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178975. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178976. dst_blk_x += compptr->h_samp_factor) {
  178977. src_buffer = (*srcinfo->mem->access_virt_barray)
  178978. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178979. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178980. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178981. if (dst_blk_y < comp_height) {
  178982. src_ptr = src_buffer[offset_x]
  178983. [comp_height - dst_blk_y - offset_y - 1];
  178984. if (dst_blk_x < comp_width) {
  178985. /* Block is within the mirrorable area. */
  178986. dst_ptr = dst_buffer[offset_y]
  178987. [comp_width - dst_blk_x - offset_x - 1];
  178988. for (i = 0; i < DCTSIZE; i++) {
  178989. for (j = 0; j < DCTSIZE; j++) {
  178990. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178991. j++;
  178992. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178993. }
  178994. i++;
  178995. for (j = 0; j < DCTSIZE; j++) {
  178996. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178997. j++;
  178998. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178999. }
  179000. }
  179001. } else {
  179002. /* Right-edge blocks are mirrored in y only */
  179003. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179004. for (i = 0; i < DCTSIZE; i++) {
  179005. for (j = 0; j < DCTSIZE; j++) {
  179006. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179007. j++;
  179008. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179009. }
  179010. }
  179011. }
  179012. } else {
  179013. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179014. if (dst_blk_x < comp_width) {
  179015. /* Bottom-edge blocks are mirrored in x only */
  179016. dst_ptr = dst_buffer[offset_y]
  179017. [comp_width - dst_blk_x - offset_x - 1];
  179018. for (i = 0; i < DCTSIZE; i++) {
  179019. for (j = 0; j < DCTSIZE; j++)
  179020. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179021. i++;
  179022. for (j = 0; j < DCTSIZE; j++)
  179023. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179024. }
  179025. } else {
  179026. /* At lower right corner, just transpose, no mirroring */
  179027. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179028. for (i = 0; i < DCTSIZE; i++)
  179029. for (j = 0; j < DCTSIZE; j++)
  179030. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179031. }
  179032. }
  179033. }
  179034. }
  179035. }
  179036. }
  179037. }
  179038. }
  179039. /* Request any required workspace.
  179040. *
  179041. * We allocate the workspace virtual arrays from the source decompression
  179042. * object, so that all the arrays (both the original data and the workspace)
  179043. * will be taken into account while making memory management decisions.
  179044. * Hence, this routine must be called after jpeg_read_header (which reads
  179045. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179046. * the source's virtual arrays).
  179047. */
  179048. GLOBAL(void)
  179049. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179050. jpeg_transform_info *info)
  179051. {
  179052. jvirt_barray_ptr *coef_arrays = NULL;
  179053. jpeg_component_info *compptr;
  179054. int ci;
  179055. if (info->force_grayscale &&
  179056. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179057. srcinfo->num_components == 3) {
  179058. /* We'll only process the first component */
  179059. info->num_components = 1;
  179060. } else {
  179061. /* Process all the components */
  179062. info->num_components = srcinfo->num_components;
  179063. }
  179064. switch (info->transform) {
  179065. case JXFORM_NONE:
  179066. case JXFORM_FLIP_H:
  179067. /* Don't need a workspace array */
  179068. break;
  179069. case JXFORM_FLIP_V:
  179070. case JXFORM_ROT_180:
  179071. /* Need workspace arrays having same dimensions as source image.
  179072. * Note that we allocate arrays padded out to the next iMCU boundary,
  179073. * so that transform routines need not worry about missing edge blocks.
  179074. */
  179075. coef_arrays = (jvirt_barray_ptr *)
  179076. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179077. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179078. for (ci = 0; ci < info->num_components; ci++) {
  179079. compptr = srcinfo->comp_info + ci;
  179080. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179081. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179082. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179083. (long) compptr->h_samp_factor),
  179084. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179085. (long) compptr->v_samp_factor),
  179086. (JDIMENSION) compptr->v_samp_factor);
  179087. }
  179088. break;
  179089. case JXFORM_TRANSPOSE:
  179090. case JXFORM_TRANSVERSE:
  179091. case JXFORM_ROT_90:
  179092. case JXFORM_ROT_270:
  179093. /* Need workspace arrays having transposed dimensions.
  179094. * Note that we allocate arrays padded out to the next iMCU boundary,
  179095. * so that transform routines need not worry about missing edge blocks.
  179096. */
  179097. coef_arrays = (jvirt_barray_ptr *)
  179098. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179099. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179100. for (ci = 0; ci < info->num_components; ci++) {
  179101. compptr = srcinfo->comp_info + ci;
  179102. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179103. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179104. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179105. (long) compptr->v_samp_factor),
  179106. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179107. (long) compptr->h_samp_factor),
  179108. (JDIMENSION) compptr->h_samp_factor);
  179109. }
  179110. break;
  179111. }
  179112. info->workspace_coef_arrays = coef_arrays;
  179113. }
  179114. /* Transpose destination image parameters */
  179115. LOCAL(void)
  179116. transpose_critical_parameters (j_compress_ptr dstinfo)
  179117. {
  179118. int tblno, i, j, ci, itemp;
  179119. jpeg_component_info *compptr;
  179120. JQUANT_TBL *qtblptr;
  179121. JDIMENSION dtemp;
  179122. UINT16 qtemp;
  179123. /* Transpose basic image dimensions */
  179124. dtemp = dstinfo->image_width;
  179125. dstinfo->image_width = dstinfo->image_height;
  179126. dstinfo->image_height = dtemp;
  179127. /* Transpose sampling factors */
  179128. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179129. compptr = dstinfo->comp_info + ci;
  179130. itemp = compptr->h_samp_factor;
  179131. compptr->h_samp_factor = compptr->v_samp_factor;
  179132. compptr->v_samp_factor = itemp;
  179133. }
  179134. /* Transpose quantization tables */
  179135. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179136. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179137. if (qtblptr != NULL) {
  179138. for (i = 0; i < DCTSIZE; i++) {
  179139. for (j = 0; j < i; j++) {
  179140. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179141. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179142. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179143. }
  179144. }
  179145. }
  179146. }
  179147. }
  179148. /* Trim off any partial iMCUs on the indicated destination edge */
  179149. LOCAL(void)
  179150. trim_right_edge (j_compress_ptr dstinfo)
  179151. {
  179152. int ci, max_h_samp_factor;
  179153. JDIMENSION MCU_cols;
  179154. /* We have to compute max_h_samp_factor ourselves,
  179155. * because it hasn't been set yet in the destination
  179156. * (and we don't want to use the source's value).
  179157. */
  179158. max_h_samp_factor = 1;
  179159. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179160. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179161. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179162. }
  179163. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179164. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179165. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179166. }
  179167. LOCAL(void)
  179168. trim_bottom_edge (j_compress_ptr dstinfo)
  179169. {
  179170. int ci, max_v_samp_factor;
  179171. JDIMENSION MCU_rows;
  179172. /* We have to compute max_v_samp_factor ourselves,
  179173. * because it hasn't been set yet in the destination
  179174. * (and we don't want to use the source's value).
  179175. */
  179176. max_v_samp_factor = 1;
  179177. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179178. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179179. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179180. }
  179181. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179182. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179183. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179184. }
  179185. /* Adjust output image parameters as needed.
  179186. *
  179187. * This must be called after jpeg_copy_critical_parameters()
  179188. * and before jpeg_write_coefficients().
  179189. *
  179190. * The return value is the set of virtual coefficient arrays to be written
  179191. * (either the ones allocated by jtransform_request_workspace, or the
  179192. * original source data arrays). The caller will need to pass this value
  179193. * to jpeg_write_coefficients().
  179194. */
  179195. GLOBAL(jvirt_barray_ptr *)
  179196. jtransform_adjust_parameters (j_decompress_ptr,
  179197. j_compress_ptr dstinfo,
  179198. jvirt_barray_ptr *src_coef_arrays,
  179199. jpeg_transform_info *info)
  179200. {
  179201. /* If force-to-grayscale is requested, adjust destination parameters */
  179202. if (info->force_grayscale) {
  179203. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179204. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179205. * will get set to 1, which typically won't match the source.
  179206. * In fact we do this even if the source is already grayscale; that
  179207. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179208. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179209. */
  179210. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179211. dstinfo->num_components == 3) ||
  179212. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179213. dstinfo->num_components == 1)) {
  179214. /* We have to preserve the source's quantization table number. */
  179215. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179216. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179217. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179218. } else {
  179219. /* Sorry, can't do it */
  179220. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179221. }
  179222. }
  179223. /* Correct the destination's image dimensions etc if necessary */
  179224. switch (info->transform) {
  179225. case JXFORM_NONE:
  179226. /* Nothing to do */
  179227. break;
  179228. case JXFORM_FLIP_H:
  179229. if (info->trim)
  179230. trim_right_edge(dstinfo);
  179231. break;
  179232. case JXFORM_FLIP_V:
  179233. if (info->trim)
  179234. trim_bottom_edge(dstinfo);
  179235. break;
  179236. case JXFORM_TRANSPOSE:
  179237. transpose_critical_parameters(dstinfo);
  179238. /* transpose does NOT have to trim anything */
  179239. break;
  179240. case JXFORM_TRANSVERSE:
  179241. transpose_critical_parameters(dstinfo);
  179242. if (info->trim) {
  179243. trim_right_edge(dstinfo);
  179244. trim_bottom_edge(dstinfo);
  179245. }
  179246. break;
  179247. case JXFORM_ROT_90:
  179248. transpose_critical_parameters(dstinfo);
  179249. if (info->trim)
  179250. trim_right_edge(dstinfo);
  179251. break;
  179252. case JXFORM_ROT_180:
  179253. if (info->trim) {
  179254. trim_right_edge(dstinfo);
  179255. trim_bottom_edge(dstinfo);
  179256. }
  179257. break;
  179258. case JXFORM_ROT_270:
  179259. transpose_critical_parameters(dstinfo);
  179260. if (info->trim)
  179261. trim_bottom_edge(dstinfo);
  179262. break;
  179263. }
  179264. /* Return the appropriate output data set */
  179265. if (info->workspace_coef_arrays != NULL)
  179266. return info->workspace_coef_arrays;
  179267. return src_coef_arrays;
  179268. }
  179269. /* Execute the actual transformation, if any.
  179270. *
  179271. * This must be called *after* jpeg_write_coefficients, because it depends
  179272. * on jpeg_write_coefficients to have computed subsidiary values such as
  179273. * the per-component width and height fields in the destination object.
  179274. *
  179275. * Note that some transformations will modify the source data arrays!
  179276. */
  179277. GLOBAL(void)
  179278. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  179279. j_compress_ptr dstinfo,
  179280. jvirt_barray_ptr *src_coef_arrays,
  179281. jpeg_transform_info *info)
  179282. {
  179283. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  179284. switch (info->transform) {
  179285. case JXFORM_NONE:
  179286. break;
  179287. case JXFORM_FLIP_H:
  179288. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  179289. break;
  179290. case JXFORM_FLIP_V:
  179291. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179292. break;
  179293. case JXFORM_TRANSPOSE:
  179294. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179295. break;
  179296. case JXFORM_TRANSVERSE:
  179297. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179298. break;
  179299. case JXFORM_ROT_90:
  179300. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179301. break;
  179302. case JXFORM_ROT_180:
  179303. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179304. break;
  179305. case JXFORM_ROT_270:
  179306. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179307. break;
  179308. }
  179309. }
  179310. #endif /* TRANSFORMS_SUPPORTED */
  179311. /* Setup decompression object to save desired markers in memory.
  179312. * This must be called before jpeg_read_header() to have the desired effect.
  179313. */
  179314. GLOBAL(void)
  179315. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179316. {
  179317. #ifdef SAVE_MARKERS_SUPPORTED
  179318. int m;
  179319. /* Save comments except under NONE option */
  179320. if (option != JCOPYOPT_NONE) {
  179321. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179322. }
  179323. /* Save all types of APPn markers iff ALL option */
  179324. if (option == JCOPYOPT_ALL) {
  179325. for (m = 0; m < 16; m++)
  179326. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179327. }
  179328. #endif /* SAVE_MARKERS_SUPPORTED */
  179329. }
  179330. /* Copy markers saved in the given source object to the destination object.
  179331. * This should be called just after jpeg_start_compress() or
  179332. * jpeg_write_coefficients().
  179333. * Note that those routines will have written the SOI, and also the
  179334. * JFIF APP0 or Adobe APP14 markers if selected.
  179335. */
  179336. GLOBAL(void)
  179337. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179338. JCOPY_OPTION)
  179339. {
  179340. jpeg_saved_marker_ptr marker;
  179341. /* In the current implementation, we don't actually need to examine the
  179342. * option flag here; we just copy everything that got saved.
  179343. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179344. * if the encoder library already wrote one.
  179345. */
  179346. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179347. if (dstinfo->write_JFIF_header &&
  179348. marker->marker == JPEG_APP0 &&
  179349. marker->data_length >= 5 &&
  179350. GETJOCTET(marker->data[0]) == 0x4A &&
  179351. GETJOCTET(marker->data[1]) == 0x46 &&
  179352. GETJOCTET(marker->data[2]) == 0x49 &&
  179353. GETJOCTET(marker->data[3]) == 0x46 &&
  179354. GETJOCTET(marker->data[4]) == 0)
  179355. continue; /* reject duplicate JFIF */
  179356. if (dstinfo->write_Adobe_marker &&
  179357. marker->marker == JPEG_APP0+14 &&
  179358. marker->data_length >= 5 &&
  179359. GETJOCTET(marker->data[0]) == 0x41 &&
  179360. GETJOCTET(marker->data[1]) == 0x64 &&
  179361. GETJOCTET(marker->data[2]) == 0x6F &&
  179362. GETJOCTET(marker->data[3]) == 0x62 &&
  179363. GETJOCTET(marker->data[4]) == 0x65)
  179364. continue; /* reject duplicate Adobe */
  179365. #ifdef NEED_FAR_POINTERS
  179366. /* We could use jpeg_write_marker if the data weren't FAR... */
  179367. {
  179368. unsigned int i;
  179369. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179370. for (i = 0; i < marker->data_length; i++)
  179371. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179372. }
  179373. #else
  179374. jpeg_write_marker(dstinfo, marker->marker,
  179375. marker->data, marker->data_length);
  179376. #endif
  179377. }
  179378. }
  179379. /*** End of inlined file: transupp.c ***/
  179380. }
  179381. #else
  179382. #define JPEG_INTERNALS
  179383. #undef FAR
  179384. #include <jpeglib.h>
  179385. #endif
  179386. }
  179387. #undef max
  179388. #undef min
  179389. #if JUCE_MSVC
  179390. #pragma warning (pop)
  179391. #endif
  179392. BEGIN_JUCE_NAMESPACE
  179393. namespace JPEGHelpers
  179394. {
  179395. using namespace jpeglibNamespace;
  179396. #if ! JUCE_MSVC
  179397. using jpeglibNamespace::boolean;
  179398. #endif
  179399. struct JPEGDecodingFailure {};
  179400. static void fatalErrorHandler (j_common_ptr)
  179401. {
  179402. throw JPEGDecodingFailure();
  179403. }
  179404. static void silentErrorCallback1 (j_common_ptr) {}
  179405. static void silentErrorCallback2 (j_common_ptr, int) {}
  179406. static void silentErrorCallback3 (j_common_ptr, char*) {}
  179407. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  179408. {
  179409. zerostruct (err);
  179410. err.error_exit = fatalErrorHandler;
  179411. err.emit_message = silentErrorCallback2;
  179412. err.output_message = silentErrorCallback1;
  179413. err.format_message = silentErrorCallback3;
  179414. err.reset_error_mgr = silentErrorCallback1;
  179415. }
  179416. static void dummyCallback1 (j_decompress_ptr)
  179417. {
  179418. }
  179419. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  179420. {
  179421. decompStruct->src->next_input_byte += num;
  179422. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  179423. decompStruct->src->bytes_in_buffer -= num;
  179424. }
  179425. static boolean jpegFill (j_decompress_ptr)
  179426. {
  179427. return 0;
  179428. }
  179429. static const int jpegBufferSize = 512;
  179430. struct JuceJpegDest : public jpeg_destination_mgr
  179431. {
  179432. OutputStream* output;
  179433. char* buffer;
  179434. };
  179435. static void jpegWriteInit (j_compress_ptr)
  179436. {
  179437. }
  179438. static void jpegWriteTerminate (j_compress_ptr cinfo)
  179439. {
  179440. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179441. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  179442. dest->output->write (dest->buffer, (int) numToWrite);
  179443. }
  179444. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  179445. {
  179446. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179447. const int numToWrite = jpegBufferSize;
  179448. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  179449. dest->free_in_buffer = jpegBufferSize;
  179450. return dest->output->write (dest->buffer, numToWrite);
  179451. }
  179452. }
  179453. JPEGImageFormat::JPEGImageFormat()
  179454. : quality (-1.0f)
  179455. {
  179456. }
  179457. JPEGImageFormat::~JPEGImageFormat() {}
  179458. void JPEGImageFormat::setQuality (const float newQuality)
  179459. {
  179460. quality = newQuality;
  179461. }
  179462. const String JPEGImageFormat::getFormatName()
  179463. {
  179464. return "JPEG";
  179465. }
  179466. bool JPEGImageFormat::canUnderstand (InputStream& in)
  179467. {
  179468. const int bytesNeeded = 10;
  179469. uint8 header [bytesNeeded];
  179470. if (in.read (header, bytesNeeded) == bytesNeeded)
  179471. {
  179472. return header[0] == 0xff
  179473. && header[1] == 0xd8
  179474. && header[2] == 0xff
  179475. && (header[3] == 0xe0 || header[3] == 0xe1);
  179476. }
  179477. return false;
  179478. }
  179479. const Image JPEGImageFormat::decodeImage (InputStream& in)
  179480. {
  179481. using namespace jpeglibNamespace;
  179482. using namespace JPEGHelpers;
  179483. MemoryOutputStream mb;
  179484. mb.writeFromInputStream (in, -1);
  179485. Image image;
  179486. if (mb.getDataSize() > 16)
  179487. {
  179488. struct jpeg_decompress_struct jpegDecompStruct;
  179489. struct jpeg_error_mgr jerr;
  179490. setupSilentErrorHandler (jerr);
  179491. jpegDecompStruct.err = &jerr;
  179492. jpeg_create_decompress (&jpegDecompStruct);
  179493. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  179494. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  179495. jpegDecompStruct.src->init_source = dummyCallback1;
  179496. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  179497. jpegDecompStruct.src->skip_input_data = jpegSkip;
  179498. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  179499. jpegDecompStruct.src->term_source = dummyCallback1;
  179500. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  179501. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  179502. try
  179503. {
  179504. jpeg_read_header (&jpegDecompStruct, TRUE);
  179505. jpeg_calc_output_dimensions (&jpegDecompStruct);
  179506. const int width = jpegDecompStruct.output_width;
  179507. const int height = jpegDecompStruct.output_height;
  179508. jpegDecompStruct.out_color_space = JCS_RGB;
  179509. JSAMPARRAY buffer
  179510. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  179511. JPOOL_IMAGE,
  179512. width * 3, 1);
  179513. if (jpeg_start_decompress (&jpegDecompStruct))
  179514. {
  179515. image = Image (Image::RGB, width, height, false);
  179516. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  179517. const Image::BitmapData destData (image, true);
  179518. for (int y = 0; y < height; ++y)
  179519. {
  179520. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  179521. const uint8* src = *buffer;
  179522. uint8* dest = destData.getLinePointer (y);
  179523. if (hasAlphaChan)
  179524. {
  179525. for (int i = width; --i >= 0;)
  179526. {
  179527. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179528. ((PixelARGB*) dest)->premultiply();
  179529. dest += destData.pixelStride;
  179530. src += 3;
  179531. }
  179532. }
  179533. else
  179534. {
  179535. for (int i = width; --i >= 0;)
  179536. {
  179537. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179538. dest += destData.pixelStride;
  179539. src += 3;
  179540. }
  179541. }
  179542. }
  179543. jpeg_finish_decompress (&jpegDecompStruct);
  179544. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  179545. }
  179546. jpeg_destroy_decompress (&jpegDecompStruct);
  179547. }
  179548. catch (...)
  179549. {}
  179550. }
  179551. return image;
  179552. }
  179553. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  179554. {
  179555. using namespace jpeglibNamespace;
  179556. using namespace JPEGHelpers;
  179557. if (image.hasAlphaChannel())
  179558. {
  179559. // this method could fill the background in white and still save the image..
  179560. jassertfalse;
  179561. return true;
  179562. }
  179563. struct jpeg_compress_struct jpegCompStruct;
  179564. struct jpeg_error_mgr jerr;
  179565. setupSilentErrorHandler (jerr);
  179566. jpegCompStruct.err = &jerr;
  179567. jpeg_create_compress (&jpegCompStruct);
  179568. JuceJpegDest dest;
  179569. jpegCompStruct.dest = &dest;
  179570. dest.output = &out;
  179571. HeapBlock <char> tempBuffer (jpegBufferSize);
  179572. dest.buffer = tempBuffer;
  179573. dest.next_output_byte = (JOCTET*) dest.buffer;
  179574. dest.free_in_buffer = jpegBufferSize;
  179575. dest.init_destination = jpegWriteInit;
  179576. dest.empty_output_buffer = jpegWriteFlush;
  179577. dest.term_destination = jpegWriteTerminate;
  179578. jpegCompStruct.image_width = image.getWidth();
  179579. jpegCompStruct.image_height = image.getHeight();
  179580. jpegCompStruct.input_components = 3;
  179581. jpegCompStruct.in_color_space = JCS_RGB;
  179582. jpegCompStruct.write_JFIF_header = 1;
  179583. jpegCompStruct.X_density = 72;
  179584. jpegCompStruct.Y_density = 72;
  179585. jpeg_set_defaults (&jpegCompStruct);
  179586. jpegCompStruct.dct_method = JDCT_FLOAT;
  179587. jpegCompStruct.optimize_coding = 1;
  179588. //jpegCompStruct.smoothing_factor = 10;
  179589. if (quality < 0.0f)
  179590. quality = 0.85f;
  179591. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  179592. jpeg_start_compress (&jpegCompStruct, TRUE);
  179593. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  179594. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  179595. JPOOL_IMAGE, strideBytes, 1);
  179596. const Image::BitmapData srcData (image, false);
  179597. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  179598. {
  179599. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  179600. uint8* dst = *buffer;
  179601. for (int i = jpegCompStruct.image_width; --i >= 0;)
  179602. {
  179603. *dst++ = ((const PixelRGB*) src)->getRed();
  179604. *dst++ = ((const PixelRGB*) src)->getGreen();
  179605. *dst++ = ((const PixelRGB*) src)->getBlue();
  179606. src += srcData.pixelStride;
  179607. }
  179608. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  179609. }
  179610. jpeg_finish_compress (&jpegCompStruct);
  179611. jpeg_destroy_compress (&jpegCompStruct);
  179612. out.flush();
  179613. return true;
  179614. }
  179615. END_JUCE_NAMESPACE
  179616. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  179617. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  179618. #if JUCE_MSVC
  179619. #pragma warning (push)
  179620. #pragma warning (disable: 4390 4611)
  179621. #endif
  179622. namespace zlibNamespace
  179623. {
  179624. #if JUCE_INCLUDE_ZLIB_CODE
  179625. #undef OS_CODE
  179626. #undef fdopen
  179627. #undef OS_CODE
  179628. #else
  179629. #include <zlib.h>
  179630. #endif
  179631. }
  179632. namespace pnglibNamespace
  179633. {
  179634. using namespace zlibNamespace;
  179635. #if JUCE_INCLUDE_PNGLIB_CODE
  179636. #if _MSC_VER != 1310
  179637. using ::calloc; // (causes conflict in VS.NET 2003)
  179638. using ::malloc;
  179639. using ::free;
  179640. #endif
  179641. extern "C"
  179642. {
  179643. using ::abs;
  179644. #define PNG_INTERNAL
  179645. #define NO_DUMMY_DECL
  179646. #define PNG_SETJMP_NOT_SUPPORTED
  179647. /*** Start of inlined file: png.h ***/
  179648. /* png.h - header file for PNG reference library
  179649. *
  179650. * libpng version 1.2.21 - October 4, 2007
  179651. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179652. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179653. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179654. *
  179655. * Authors and maintainers:
  179656. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  179657. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  179658. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  179659. * See also "Contributing Authors", below.
  179660. *
  179661. * Note about libpng version numbers:
  179662. *
  179663. * Due to various miscommunications, unforeseen code incompatibilities
  179664. * and occasional factors outside the authors' control, version numbering
  179665. * on the library has not always been consistent and straightforward.
  179666. * The following table summarizes matters since version 0.89c, which was
  179667. * the first widely used release:
  179668. *
  179669. * source png.h png.h shared-lib
  179670. * version string int version
  179671. * ------- ------ ----- ----------
  179672. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  179673. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  179674. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  179675. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  179676. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  179677. * 0.97c 0.97 97 2.0.97
  179678. * 0.98 0.98 98 2.0.98
  179679. * 0.99 0.99 98 2.0.99
  179680. * 0.99a-m 0.99 99 2.0.99
  179681. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  179682. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  179683. * 1.0.1 png.h string is 10001 2.1.0
  179684. * 1.0.1a-e identical to the 10002 from here on, the shared library
  179685. * 1.0.2 source version) 10002 is 2.V where V is the source code
  179686. * 1.0.2a-b 10003 version, except as noted.
  179687. * 1.0.3 10003
  179688. * 1.0.3a-d 10004
  179689. * 1.0.4 10004
  179690. * 1.0.4a-f 10005
  179691. * 1.0.5 (+ 2 patches) 10005
  179692. * 1.0.5a-d 10006
  179693. * 1.0.5e-r 10100 (not source compatible)
  179694. * 1.0.5s-v 10006 (not binary compatible)
  179695. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  179696. * 1.0.6d-f 10007 (still binary incompatible)
  179697. * 1.0.6g 10007
  179698. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  179699. * 1.0.6i 10007 10.6i
  179700. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  179701. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  179702. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  179703. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  179704. * 1.0.7 1 10007 (still compatible)
  179705. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  179706. * 1.0.8rc1 1 10008 2.1.0.8rc1
  179707. * 1.0.8 1 10008 2.1.0.8
  179708. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  179709. * 1.0.9rc1 1 10009 2.1.0.9rc1
  179710. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  179711. * 1.0.9rc2 1 10009 2.1.0.9rc2
  179712. * 1.0.9 1 10009 2.1.0.9
  179713. * 1.0.10beta1 1 10010 2.1.0.10beta1
  179714. * 1.0.10rc1 1 10010 2.1.0.10rc1
  179715. * 1.0.10 1 10010 2.1.0.10
  179716. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  179717. * 1.0.11rc1 1 10011 2.1.0.11rc1
  179718. * 1.0.11 1 10011 2.1.0.11
  179719. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  179720. * 1.0.12rc1 2 10012 2.1.0.12rc1
  179721. * 1.0.12 2 10012 2.1.0.12
  179722. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  179723. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  179724. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  179725. * 1.2.0rc1 3 10200 3.1.2.0rc1
  179726. * 1.2.0 3 10200 3.1.2.0
  179727. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  179728. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  179729. * 1.2.1 3 10201 3.1.2.1
  179730. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  179731. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  179732. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  179733. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  179734. * 1.0.13 10 10013 10.so.0.1.0.13
  179735. * 1.2.2 12 10202 12.so.0.1.2.2
  179736. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  179737. * 1.2.3 12 10203 12.so.0.1.2.3
  179738. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  179739. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  179740. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  179741. * 1.0.14 10 10014 10.so.0.1.0.14
  179742. * 1.2.4 13 10204 12.so.0.1.2.4
  179743. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  179744. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  179745. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  179746. * 1.0.15 10 10015 10.so.0.1.0.15
  179747. * 1.2.5 13 10205 12.so.0.1.2.5
  179748. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  179749. * 1.0.16 10 10016 10.so.0.1.0.16
  179750. * 1.2.6 13 10206 12.so.0.1.2.6
  179751. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  179752. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  179753. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  179754. * 1.0.17 10 10017 10.so.0.1.0.17
  179755. * 1.2.7 13 10207 12.so.0.1.2.7
  179756. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  179757. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  179758. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  179759. * 1.0.18 10 10018 10.so.0.1.0.18
  179760. * 1.2.8 13 10208 12.so.0.1.2.8
  179761. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  179762. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  179763. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  179764. * 1.2.9 13 10209 12.so.0.9[.0]
  179765. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  179766. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  179767. * 1.2.10 13 10210 12.so.0.10[.0]
  179768. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  179769. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  179770. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  179771. * 1.0.19 10 10019 10.so.0.19[.0]
  179772. * 1.2.11 13 10211 12.so.0.11[.0]
  179773. * 1.0.20 10 10020 10.so.0.20[.0]
  179774. * 1.2.12 13 10212 12.so.0.12[.0]
  179775. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  179776. * 1.0.21 10 10021 10.so.0.21[.0]
  179777. * 1.2.13 13 10213 12.so.0.13[.0]
  179778. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  179779. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  179780. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  179781. * 1.0.22 10 10022 10.so.0.22[.0]
  179782. * 1.2.14 13 10214 12.so.0.14[.0]
  179783. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  179784. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  179785. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  179786. * 1.0.23 10 10023 10.so.0.23[.0]
  179787. * 1.2.15 13 10215 12.so.0.15[.0]
  179788. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  179789. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  179790. * 1.0.24 10 10024 10.so.0.24[.0]
  179791. * 1.2.16 13 10216 12.so.0.16[.0]
  179792. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  179793. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  179794. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  179795. * 1.0.25 10 10025 10.so.0.25[.0]
  179796. * 1.2.17 13 10217 12.so.0.17[.0]
  179797. * 1.0.26 10 10026 10.so.0.26[.0]
  179798. * 1.2.18 13 10218 12.so.0.18[.0]
  179799. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  179800. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  179801. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  179802. * 1.0.27 10 10027 10.so.0.27[.0]
  179803. * 1.2.19 13 10219 12.so.0.19[.0]
  179804. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  179805. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  179806. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  179807. * 1.0.28 10 10028 10.so.0.28[.0]
  179808. * 1.2.20 13 10220 12.so.0.20[.0]
  179809. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  179810. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  179811. * 1.0.29 10 10029 10.so.0.29[.0]
  179812. * 1.2.21 13 10221 12.so.0.21[.0]
  179813. *
  179814. * Henceforth the source version will match the shared-library major
  179815. * and minor numbers; the shared-library major version number will be
  179816. * used for changes in backward compatibility, as it is intended. The
  179817. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  179818. * for applications, is an unsigned integer of the form xyyzz corresponding
  179819. * to the source version x.y.z (leading zeros in y and z). Beta versions
  179820. * were given the previous public release number plus a letter, until
  179821. * version 1.0.6j; from then on they were given the upcoming public
  179822. * release number plus "betaNN" or "rcN".
  179823. *
  179824. * Binary incompatibility exists only when applications make direct access
  179825. * to the info_ptr or png_ptr members through png.h, and the compiled
  179826. * application is loaded with a different version of the library.
  179827. *
  179828. * DLLNUM will change each time there are forward or backward changes
  179829. * in binary compatibility (e.g., when a new feature is added).
  179830. *
  179831. * See libpng.txt or libpng.3 for more information. The PNG specification
  179832. * is available as a W3C Recommendation and as an ISO Specification,
  179833. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  179834. */
  179835. /*
  179836. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  179837. *
  179838. * If you modify libpng you may insert additional notices immediately following
  179839. * this sentence.
  179840. *
  179841. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  179842. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  179843. * distributed according to the same disclaimer and license as libpng-1.2.5
  179844. * with the following individual added to the list of Contributing Authors:
  179845. *
  179846. * Cosmin Truta
  179847. *
  179848. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  179849. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  179850. * distributed according to the same disclaimer and license as libpng-1.0.6
  179851. * with the following individuals added to the list of Contributing Authors:
  179852. *
  179853. * Simon-Pierre Cadieux
  179854. * Eric S. Raymond
  179855. * Gilles Vollant
  179856. *
  179857. * and with the following additions to the disclaimer:
  179858. *
  179859. * There is no warranty against interference with your enjoyment of the
  179860. * library or against infringement. There is no warranty that our
  179861. * efforts or the library will fulfill any of your particular purposes
  179862. * or needs. This library is provided with all faults, and the entire
  179863. * risk of satisfactory quality, performance, accuracy, and effort is with
  179864. * the user.
  179865. *
  179866. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  179867. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  179868. * distributed according to the same disclaimer and license as libpng-0.96,
  179869. * with the following individuals added to the list of Contributing Authors:
  179870. *
  179871. * Tom Lane
  179872. * Glenn Randers-Pehrson
  179873. * Willem van Schaik
  179874. *
  179875. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  179876. * Copyright (c) 1996, 1997 Andreas Dilger
  179877. * Distributed according to the same disclaimer and license as libpng-0.88,
  179878. * with the following individuals added to the list of Contributing Authors:
  179879. *
  179880. * John Bowler
  179881. * Kevin Bracey
  179882. * Sam Bushell
  179883. * Magnus Holmgren
  179884. * Greg Roelofs
  179885. * Tom Tanner
  179886. *
  179887. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  179888. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  179889. *
  179890. * For the purposes of this copyright and license, "Contributing Authors"
  179891. * is defined as the following set of individuals:
  179892. *
  179893. * Andreas Dilger
  179894. * Dave Martindale
  179895. * Guy Eric Schalnat
  179896. * Paul Schmidt
  179897. * Tim Wegner
  179898. *
  179899. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  179900. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  179901. * including, without limitation, the warranties of merchantability and of
  179902. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  179903. * assume no liability for direct, indirect, incidental, special, exemplary,
  179904. * or consequential damages, which may result from the use of the PNG
  179905. * Reference Library, even if advised of the possibility of such damage.
  179906. *
  179907. * Permission is hereby granted to use, copy, modify, and distribute this
  179908. * source code, or portions hereof, for any purpose, without fee, subject
  179909. * to the following restrictions:
  179910. *
  179911. * 1. The origin of this source code must not be misrepresented.
  179912. *
  179913. * 2. Altered versions must be plainly marked as such and
  179914. * must not be misrepresented as being the original source.
  179915. *
  179916. * 3. This Copyright notice may not be removed or altered from
  179917. * any source or altered source distribution.
  179918. *
  179919. * The Contributing Authors and Group 42, Inc. specifically permit, without
  179920. * fee, and encourage the use of this source code as a component to
  179921. * supporting the PNG file format in commercial products. If you use this
  179922. * source code in a product, acknowledgment is not required but would be
  179923. * appreciated.
  179924. */
  179925. /*
  179926. * A "png_get_copyright" function is available, for convenient use in "about"
  179927. * boxes and the like:
  179928. *
  179929. * printf("%s",png_get_copyright(NULL));
  179930. *
  179931. * Also, the PNG logo (in PNG format, of course) is supplied in the
  179932. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  179933. */
  179934. /*
  179935. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  179936. * certification mark of the Open Source Initiative.
  179937. */
  179938. /*
  179939. * The contributing authors would like to thank all those who helped
  179940. * with testing, bug fixes, and patience. This wouldn't have been
  179941. * possible without all of you.
  179942. *
  179943. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  179944. */
  179945. /*
  179946. * Y2K compliance in libpng:
  179947. * =========================
  179948. *
  179949. * October 4, 2007
  179950. *
  179951. * Since the PNG Development group is an ad-hoc body, we can't make
  179952. * an official declaration.
  179953. *
  179954. * This is your unofficial assurance that libpng from version 0.71 and
  179955. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  179956. * versions were also Y2K compliant.
  179957. *
  179958. * Libpng only has three year fields. One is a 2-byte unsigned integer
  179959. * that will hold years up to 65535. The other two hold the date in text
  179960. * format, and will hold years up to 9999.
  179961. *
  179962. * The integer is
  179963. * "png_uint_16 year" in png_time_struct.
  179964. *
  179965. * The strings are
  179966. * "png_charp time_buffer" in png_struct and
  179967. * "near_time_buffer", which is a local character string in png.c.
  179968. *
  179969. * There are seven time-related functions:
  179970. * png.c: png_convert_to_rfc_1123() in png.c
  179971. * (formerly png_convert_to_rfc_1152() in error)
  179972. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  179973. * png_convert_from_time_t() in pngwrite.c
  179974. * png_get_tIME() in pngget.c
  179975. * png_handle_tIME() in pngrutil.c, called in pngread.c
  179976. * png_set_tIME() in pngset.c
  179977. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  179978. *
  179979. * All handle dates properly in a Y2K environment. The
  179980. * png_convert_from_time_t() function calls gmtime() to convert from system
  179981. * clock time, which returns (year - 1900), which we properly convert to
  179982. * the full 4-digit year. There is a possibility that applications using
  179983. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  179984. * function, or that they are incorrectly passing only a 2-digit year
  179985. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  179986. * but this is not under our control. The libpng documentation has always
  179987. * stated that it works with 4-digit years, and the APIs have been
  179988. * documented as such.
  179989. *
  179990. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  179991. * integer to hold the year, and can hold years as large as 65535.
  179992. *
  179993. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  179994. * no date-related code.
  179995. *
  179996. * Glenn Randers-Pehrson
  179997. * libpng maintainer
  179998. * PNG Development Group
  179999. */
  180000. #ifndef PNG_H
  180001. #define PNG_H
  180002. /* This is not the place to learn how to use libpng. The file libpng.txt
  180003. * describes how to use libpng, and the file example.c summarizes it
  180004. * with some code on which to build. This file is useful for looking
  180005. * at the actual function definitions and structure components.
  180006. */
  180007. /* Version information for png.h - this should match the version in png.c */
  180008. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180009. #define PNG_HEADER_VERSION_STRING \
  180010. " libpng version 1.2.21 - October 4, 2007\n"
  180011. #define PNG_LIBPNG_VER_SONUM 0
  180012. #define PNG_LIBPNG_VER_DLLNUM 13
  180013. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180014. #define PNG_LIBPNG_VER_MAJOR 1
  180015. #define PNG_LIBPNG_VER_MINOR 2
  180016. #define PNG_LIBPNG_VER_RELEASE 21
  180017. /* This should match the numeric part of the final component of
  180018. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180019. #define PNG_LIBPNG_VER_BUILD 0
  180020. /* Release Status */
  180021. #define PNG_LIBPNG_BUILD_ALPHA 1
  180022. #define PNG_LIBPNG_BUILD_BETA 2
  180023. #define PNG_LIBPNG_BUILD_RC 3
  180024. #define PNG_LIBPNG_BUILD_STABLE 4
  180025. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180026. /* Release-Specific Flags */
  180027. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180028. PNG_LIBPNG_BUILD_STABLE only */
  180029. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180030. PNG_LIBPNG_BUILD_SPECIAL */
  180031. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180032. PNG_LIBPNG_BUILD_PRIVATE */
  180033. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180034. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180035. * We must not include leading zeros.
  180036. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180037. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180038. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180039. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180040. #ifndef PNG_VERSION_INFO_ONLY
  180041. /* include the compression library's header */
  180042. #endif
  180043. /* include all user configurable info, including optional assembler routines */
  180044. /*** Start of inlined file: pngconf.h ***/
  180045. /* pngconf.h - machine configurable file for libpng
  180046. *
  180047. * libpng version 1.2.21 - October 4, 2007
  180048. * For conditions of distribution and use, see copyright notice in png.h
  180049. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180050. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180051. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180052. */
  180053. /* Any machine specific code is near the front of this file, so if you
  180054. * are configuring libpng for a machine, you may want to read the section
  180055. * starting here down to where it starts to typedef png_color, png_text,
  180056. * and png_info.
  180057. */
  180058. #ifndef PNGCONF_H
  180059. #define PNGCONF_H
  180060. #define PNG_1_2_X
  180061. // These are some Juce config settings that should remove any unnecessary code bloat..
  180062. #define PNG_NO_STDIO 1
  180063. #define PNG_DEBUG 0
  180064. #define PNG_NO_WARNINGS 1
  180065. #define PNG_NO_ERROR_TEXT 1
  180066. #define PNG_NO_ERROR_NUMBERS 1
  180067. #define PNG_NO_USER_MEM 1
  180068. #define PNG_NO_READ_iCCP 1
  180069. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180070. #define PNG_NO_READ_USER_CHUNKS 1
  180071. #define PNG_NO_READ_iTXt 1
  180072. #define PNG_NO_READ_sCAL 1
  180073. #define PNG_NO_READ_sPLT 1
  180074. #define png_error(a, b) png_err(a)
  180075. #define png_warning(a, b)
  180076. #define png_chunk_error(a, b) png_err(a)
  180077. #define png_chunk_warning(a, b)
  180078. /*
  180079. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180080. * includes the resource compiler for Windows DLL configurations.
  180081. */
  180082. #ifdef PNG_USER_CONFIG
  180083. # ifndef PNG_USER_PRIVATEBUILD
  180084. # define PNG_USER_PRIVATEBUILD
  180085. # endif
  180086. #include "pngusr.h"
  180087. #endif
  180088. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180089. #ifdef PNG_CONFIGURE_LIBPNG
  180090. #ifdef HAVE_CONFIG_H
  180091. #include "config.h"
  180092. #endif
  180093. #endif
  180094. /*
  180095. * Added at libpng-1.2.8
  180096. *
  180097. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180098. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180099. * the DLL was built>
  180100. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180101. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180102. * distinguish your DLL from those of the official release. These
  180103. * correspond to the trailing letters that come after the version
  180104. * number and must match your private DLL name>
  180105. * e.g. // private DLL "libpng13gx.dll"
  180106. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180107. *
  180108. * The following macros are also at your disposal if you want to complete the
  180109. * DLL VERSIONINFO structure.
  180110. * - PNG_USER_VERSIONINFO_COMMENTS
  180111. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180112. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180113. */
  180114. #ifdef __STDC__
  180115. #ifdef SPECIALBUILD
  180116. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180117. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180118. #endif
  180119. #ifdef PRIVATEBUILD
  180120. # pragma message("PRIVATEBUILD is deprecated.\
  180121. Use PNG_USER_PRIVATEBUILD instead.")
  180122. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180123. #endif
  180124. #endif /* __STDC__ */
  180125. #ifndef PNG_VERSION_INFO_ONLY
  180126. /* End of material added to libpng-1.2.8 */
  180127. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180128. Restored at libpng-1.2.21 */
  180129. # define PNG_WARN_UNINITIALIZED_ROW 1
  180130. /* End of material added at libpng-1.2.19/1.2.21 */
  180131. /* This is the size of the compression buffer, and thus the size of
  180132. * an IDAT chunk. Make this whatever size you feel is best for your
  180133. * machine. One of these will be allocated per png_struct. When this
  180134. * is full, it writes the data to the disk, and does some other
  180135. * calculations. Making this an extremely small size will slow
  180136. * the library down, but you may want to experiment to determine
  180137. * where it becomes significant, if you are concerned with memory
  180138. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180139. * this describes the size of the buffer available to read the data in.
  180140. * Unless this gets smaller than the size of a row (compressed),
  180141. * it should not make much difference how big this is.
  180142. */
  180143. #ifndef PNG_ZBUF_SIZE
  180144. # define PNG_ZBUF_SIZE 8192
  180145. #endif
  180146. /* Enable if you want a write-only libpng */
  180147. #ifndef PNG_NO_READ_SUPPORTED
  180148. # define PNG_READ_SUPPORTED
  180149. #endif
  180150. /* Enable if you want a read-only libpng */
  180151. #ifndef PNG_NO_WRITE_SUPPORTED
  180152. # define PNG_WRITE_SUPPORTED
  180153. #endif
  180154. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180155. support PNGs that are embedded in MNG datastreams */
  180156. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180157. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180158. # define PNG_MNG_FEATURES_SUPPORTED
  180159. # endif
  180160. #endif
  180161. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180162. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180163. # define PNG_FLOATING_POINT_SUPPORTED
  180164. # endif
  180165. #endif
  180166. /* If you are running on a machine where you cannot allocate more
  180167. * than 64K of memory at once, uncomment this. While libpng will not
  180168. * normally need that much memory in a chunk (unless you load up a very
  180169. * large file), zlib needs to know how big of a chunk it can use, and
  180170. * libpng thus makes sure to check any memory allocation to verify it
  180171. * will fit into memory.
  180172. #define PNG_MAX_MALLOC_64K
  180173. */
  180174. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180175. # define PNG_MAX_MALLOC_64K
  180176. #endif
  180177. /* Special munging to support doing things the 'cygwin' way:
  180178. * 'Normal' png-on-win32 defines/defaults:
  180179. * PNG_BUILD_DLL -- building dll
  180180. * PNG_USE_DLL -- building an application, linking to dll
  180181. * (no define) -- building static library, or building an
  180182. * application and linking to the static lib
  180183. * 'Cygwin' defines/defaults:
  180184. * PNG_BUILD_DLL -- (ignored) building the dll
  180185. * (no define) -- (ignored) building an application, linking to the dll
  180186. * PNG_STATIC -- (ignored) building the static lib, or building an
  180187. * application that links to the static lib.
  180188. * ALL_STATIC -- (ignored) building various static libs, or building an
  180189. * application that links to the static libs.
  180190. * Thus,
  180191. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180192. * this bit of #ifdefs will define the 'correct' config variables based on
  180193. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180194. * unnecessary.
  180195. *
  180196. * Also, the precedence order is:
  180197. * ALL_STATIC (since we can't #undef something outside our namespace)
  180198. * PNG_BUILD_DLL
  180199. * PNG_STATIC
  180200. * (nothing) == PNG_USE_DLL
  180201. *
  180202. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180203. * of auto-import in binutils, we no longer need to worry about
  180204. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180205. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180206. * to __declspec() stuff. However, we DO need to worry about
  180207. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180208. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180209. */
  180210. #if defined(__CYGWIN__)
  180211. # if defined(ALL_STATIC)
  180212. # if defined(PNG_BUILD_DLL)
  180213. # undef PNG_BUILD_DLL
  180214. # endif
  180215. # if defined(PNG_USE_DLL)
  180216. # undef PNG_USE_DLL
  180217. # endif
  180218. # if defined(PNG_DLL)
  180219. # undef PNG_DLL
  180220. # endif
  180221. # if !defined(PNG_STATIC)
  180222. # define PNG_STATIC
  180223. # endif
  180224. # else
  180225. # if defined (PNG_BUILD_DLL)
  180226. # if defined(PNG_STATIC)
  180227. # undef PNG_STATIC
  180228. # endif
  180229. # if defined(PNG_USE_DLL)
  180230. # undef PNG_USE_DLL
  180231. # endif
  180232. # if !defined(PNG_DLL)
  180233. # define PNG_DLL
  180234. # endif
  180235. # else
  180236. # if defined(PNG_STATIC)
  180237. # if defined(PNG_USE_DLL)
  180238. # undef PNG_USE_DLL
  180239. # endif
  180240. # if defined(PNG_DLL)
  180241. # undef PNG_DLL
  180242. # endif
  180243. # else
  180244. # if !defined(PNG_USE_DLL)
  180245. # define PNG_USE_DLL
  180246. # endif
  180247. # if !defined(PNG_DLL)
  180248. # define PNG_DLL
  180249. # endif
  180250. # endif
  180251. # endif
  180252. # endif
  180253. #endif
  180254. /* This protects us against compilers that run on a windowing system
  180255. * and thus don't have or would rather us not use the stdio types:
  180256. * stdin, stdout, and stderr. The only one currently used is stderr
  180257. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180258. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180259. * will also prevent these, plus will prevent the entire set of stdio
  180260. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180261. * unless (PNG_DEBUG > 0) has been #defined.
  180262. *
  180263. * #define PNG_NO_CONSOLE_IO
  180264. * #define PNG_NO_STDIO
  180265. */
  180266. #if defined(_WIN32_WCE)
  180267. # include <windows.h>
  180268. /* Console I/O functions are not supported on WindowsCE */
  180269. # define PNG_NO_CONSOLE_IO
  180270. # ifdef PNG_DEBUG
  180271. # undef PNG_DEBUG
  180272. # endif
  180273. #endif
  180274. #ifdef PNG_BUILD_DLL
  180275. # ifndef PNG_CONSOLE_IO_SUPPORTED
  180276. # ifndef PNG_NO_CONSOLE_IO
  180277. # define PNG_NO_CONSOLE_IO
  180278. # endif
  180279. # endif
  180280. #endif
  180281. # ifdef PNG_NO_STDIO
  180282. # ifndef PNG_NO_CONSOLE_IO
  180283. # define PNG_NO_CONSOLE_IO
  180284. # endif
  180285. # ifdef PNG_DEBUG
  180286. # if (PNG_DEBUG > 0)
  180287. # include <stdio.h>
  180288. # endif
  180289. # endif
  180290. # else
  180291. # if !defined(_WIN32_WCE)
  180292. /* "stdio.h" functions are not supported on WindowsCE */
  180293. # include <stdio.h>
  180294. # endif
  180295. # endif
  180296. /* This macro protects us against machines that don't have function
  180297. * prototypes (ie K&R style headers). If your compiler does not handle
  180298. * function prototypes, define this macro and use the included ansi2knr.
  180299. * I've always been able to use _NO_PROTO as the indicator, but you may
  180300. * need to drag the empty declaration out in front of here, or change the
  180301. * ifdef to suit your own needs.
  180302. */
  180303. #ifndef PNGARG
  180304. #ifdef OF /* zlib prototype munger */
  180305. # define PNGARG(arglist) OF(arglist)
  180306. #else
  180307. #ifdef _NO_PROTO
  180308. # define PNGARG(arglist) ()
  180309. # ifndef PNG_TYPECAST_NULL
  180310. # define PNG_TYPECAST_NULL
  180311. # endif
  180312. #else
  180313. # define PNGARG(arglist) arglist
  180314. #endif /* _NO_PROTO */
  180315. #endif /* OF */
  180316. #endif /* PNGARG */
  180317. /* Try to determine if we are compiling on a Mac. Note that testing for
  180318. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180319. * on non-Mac platforms.
  180320. */
  180321. #ifndef MACOS
  180322. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180323. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180324. # define MACOS
  180325. # endif
  180326. #endif
  180327. /* enough people need this for various reasons to include it here */
  180328. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180329. # include <sys/types.h>
  180330. #endif
  180331. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180332. # define PNG_SETJMP_SUPPORTED
  180333. #endif
  180334. #ifdef PNG_SETJMP_SUPPORTED
  180335. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180336. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180337. */
  180338. # ifdef __linux__
  180339. # ifdef _BSD_SOURCE
  180340. # define PNG_SAVE_BSD_SOURCE
  180341. # undef _BSD_SOURCE
  180342. # endif
  180343. # ifdef _SETJMP_H
  180344. /* If you encounter a compiler error here, see the explanation
  180345. * near the end of INSTALL.
  180346. */
  180347. __png.h__ already includes setjmp.h;
  180348. __dont__ include it again.;
  180349. # endif
  180350. # endif /* __linux__ */
  180351. /* include setjmp.h for error handling */
  180352. # include <setjmp.h>
  180353. # ifdef __linux__
  180354. # ifdef PNG_SAVE_BSD_SOURCE
  180355. # define _BSD_SOURCE
  180356. # undef PNG_SAVE_BSD_SOURCE
  180357. # endif
  180358. # endif /* __linux__ */
  180359. #endif /* PNG_SETJMP_SUPPORTED */
  180360. #ifdef BSD
  180361. #if ! JUCE_MAC
  180362. # include <strings.h>
  180363. #endif
  180364. #else
  180365. # include <string.h>
  180366. #endif
  180367. /* Other defines for things like memory and the like can go here. */
  180368. #ifdef PNG_INTERNAL
  180369. #include <stdlib.h>
  180370. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180371. * aren't usually used outside the library (as far as I know), so it is
  180372. * debatable if they should be exported at all. In the future, when it is
  180373. * possible to have run-time registry of chunk-handling functions, some of
  180374. * these will be made available again.
  180375. #define PNG_EXTERN extern
  180376. */
  180377. #define PNG_EXTERN
  180378. /* Other defines specific to compilers can go here. Try to keep
  180379. * them inside an appropriate ifdef/endif pair for portability.
  180380. */
  180381. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  180382. # if defined(MACOS)
  180383. /* We need to check that <math.h> hasn't already been included earlier
  180384. * as it seems it doesn't agree with <fp.h>, yet we should really use
  180385. * <fp.h> if possible.
  180386. */
  180387. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  180388. # include <fp.h>
  180389. # endif
  180390. # else
  180391. # include <math.h>
  180392. # endif
  180393. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  180394. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  180395. * MATH=68881
  180396. */
  180397. # include <m68881.h>
  180398. # endif
  180399. #endif
  180400. /* Codewarrior on NT has linking problems without this. */
  180401. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  180402. # define PNG_ALWAYS_EXTERN
  180403. #endif
  180404. /* This provides the non-ANSI (far) memory allocation routines. */
  180405. #if defined(__TURBOC__) && defined(__MSDOS__)
  180406. # include <mem.h>
  180407. # include <alloc.h>
  180408. #endif
  180409. /* I have no idea why is this necessary... */
  180410. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  180411. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  180412. # include <malloc.h>
  180413. #endif
  180414. /* This controls how fine the dithering gets. As this allocates
  180415. * a largish chunk of memory (32K), those who are not as concerned
  180416. * with dithering quality can decrease some or all of these.
  180417. */
  180418. #ifndef PNG_DITHER_RED_BITS
  180419. # define PNG_DITHER_RED_BITS 5
  180420. #endif
  180421. #ifndef PNG_DITHER_GREEN_BITS
  180422. # define PNG_DITHER_GREEN_BITS 5
  180423. #endif
  180424. #ifndef PNG_DITHER_BLUE_BITS
  180425. # define PNG_DITHER_BLUE_BITS 5
  180426. #endif
  180427. /* This controls how fine the gamma correction becomes when you
  180428. * are only interested in 8 bits anyway. Increasing this value
  180429. * results in more memory being used, and more pow() functions
  180430. * being called to fill in the gamma tables. Don't set this value
  180431. * less then 8, and even that may not work (I haven't tested it).
  180432. */
  180433. #ifndef PNG_MAX_GAMMA_8
  180434. # define PNG_MAX_GAMMA_8 11
  180435. #endif
  180436. /* This controls how much a difference in gamma we can tolerate before
  180437. * we actually start doing gamma conversion.
  180438. */
  180439. #ifndef PNG_GAMMA_THRESHOLD
  180440. # define PNG_GAMMA_THRESHOLD 0.05
  180441. #endif
  180442. #endif /* PNG_INTERNAL */
  180443. /* The following uses const char * instead of char * for error
  180444. * and warning message functions, so some compilers won't complain.
  180445. * If you do not want to use const, define PNG_NO_CONST here.
  180446. */
  180447. #ifndef PNG_NO_CONST
  180448. # define PNG_CONST const
  180449. #else
  180450. # define PNG_CONST
  180451. #endif
  180452. /* The following defines give you the ability to remove code from the
  180453. * library that you will not be using. I wish I could figure out how to
  180454. * automate this, but I can't do that without making it seriously hard
  180455. * on the users. So if you are not using an ability, change the #define
  180456. * to and #undef, and that part of the library will not be compiled. If
  180457. * your linker can't find a function, you may want to make sure the
  180458. * ability is defined here. Some of these depend upon some others being
  180459. * defined. I haven't figured out all the interactions here, so you may
  180460. * have to experiment awhile to get everything to compile. If you are
  180461. * creating or using a shared library, you probably shouldn't touch this,
  180462. * as it will affect the size of the structures, and this will cause bad
  180463. * things to happen if the library and/or application ever change.
  180464. */
  180465. /* Any features you will not be using can be undef'ed here */
  180466. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  180467. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  180468. * on the compile line, then pick and choose which ones to define without
  180469. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  180470. * if you only want to have a png-compliant reader/writer but don't need
  180471. * any of the extra transformations. This saves about 80 kbytes in a
  180472. * typical installation of the library. (PNG_NO_* form added in version
  180473. * 1.0.1c, for consistency)
  180474. */
  180475. /* The size of the png_text structure changed in libpng-1.0.6 when
  180476. * iTXt support was added. iTXt support was turned off by default through
  180477. * libpng-1.2.x, to support old apps that malloc the png_text structure
  180478. * instead of calling png_set_text() and letting libpng malloc it. It
  180479. * was turned on by default in libpng-1.3.0.
  180480. */
  180481. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180482. # ifndef PNG_NO_iTXt_SUPPORTED
  180483. # define PNG_NO_iTXt_SUPPORTED
  180484. # endif
  180485. # ifndef PNG_NO_READ_iTXt
  180486. # define PNG_NO_READ_iTXt
  180487. # endif
  180488. # ifndef PNG_NO_WRITE_iTXt
  180489. # define PNG_NO_WRITE_iTXt
  180490. # endif
  180491. #endif
  180492. #if !defined(PNG_NO_iTXt_SUPPORTED)
  180493. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  180494. # define PNG_READ_iTXt
  180495. # endif
  180496. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  180497. # define PNG_WRITE_iTXt
  180498. # endif
  180499. #endif
  180500. /* The following support, added after version 1.0.0, can be turned off here en
  180501. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  180502. * with old applications that require the length of png_struct and png_info
  180503. * to remain unchanged.
  180504. */
  180505. #ifdef PNG_LEGACY_SUPPORTED
  180506. # define PNG_NO_FREE_ME
  180507. # define PNG_NO_READ_UNKNOWN_CHUNKS
  180508. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  180509. # define PNG_NO_READ_USER_CHUNKS
  180510. # define PNG_NO_READ_iCCP
  180511. # define PNG_NO_WRITE_iCCP
  180512. # define PNG_NO_READ_iTXt
  180513. # define PNG_NO_WRITE_iTXt
  180514. # define PNG_NO_READ_sCAL
  180515. # define PNG_NO_WRITE_sCAL
  180516. # define PNG_NO_READ_sPLT
  180517. # define PNG_NO_WRITE_sPLT
  180518. # define PNG_NO_INFO_IMAGE
  180519. # define PNG_NO_READ_RGB_TO_GRAY
  180520. # define PNG_NO_READ_USER_TRANSFORM
  180521. # define PNG_NO_WRITE_USER_TRANSFORM
  180522. # define PNG_NO_USER_MEM
  180523. # define PNG_NO_READ_EMPTY_PLTE
  180524. # define PNG_NO_MNG_FEATURES
  180525. # define PNG_NO_FIXED_POINT_SUPPORTED
  180526. #endif
  180527. /* Ignore attempt to turn off both floating and fixed point support */
  180528. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  180529. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  180530. # define PNG_FIXED_POINT_SUPPORTED
  180531. #endif
  180532. #ifndef PNG_NO_FREE_ME
  180533. # define PNG_FREE_ME_SUPPORTED
  180534. #endif
  180535. #if defined(PNG_READ_SUPPORTED)
  180536. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  180537. !defined(PNG_NO_READ_TRANSFORMS)
  180538. # define PNG_READ_TRANSFORMS_SUPPORTED
  180539. #endif
  180540. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  180541. # ifndef PNG_NO_READ_EXPAND
  180542. # define PNG_READ_EXPAND_SUPPORTED
  180543. # endif
  180544. # ifndef PNG_NO_READ_SHIFT
  180545. # define PNG_READ_SHIFT_SUPPORTED
  180546. # endif
  180547. # ifndef PNG_NO_READ_PACK
  180548. # define PNG_READ_PACK_SUPPORTED
  180549. # endif
  180550. # ifndef PNG_NO_READ_BGR
  180551. # define PNG_READ_BGR_SUPPORTED
  180552. # endif
  180553. # ifndef PNG_NO_READ_SWAP
  180554. # define PNG_READ_SWAP_SUPPORTED
  180555. # endif
  180556. # ifndef PNG_NO_READ_PACKSWAP
  180557. # define PNG_READ_PACKSWAP_SUPPORTED
  180558. # endif
  180559. # ifndef PNG_NO_READ_INVERT
  180560. # define PNG_READ_INVERT_SUPPORTED
  180561. # endif
  180562. # ifndef PNG_NO_READ_DITHER
  180563. # define PNG_READ_DITHER_SUPPORTED
  180564. # endif
  180565. # ifndef PNG_NO_READ_BACKGROUND
  180566. # define PNG_READ_BACKGROUND_SUPPORTED
  180567. # endif
  180568. # ifndef PNG_NO_READ_16_TO_8
  180569. # define PNG_READ_16_TO_8_SUPPORTED
  180570. # endif
  180571. # ifndef PNG_NO_READ_FILLER
  180572. # define PNG_READ_FILLER_SUPPORTED
  180573. # endif
  180574. # ifndef PNG_NO_READ_GAMMA
  180575. # define PNG_READ_GAMMA_SUPPORTED
  180576. # endif
  180577. # ifndef PNG_NO_READ_GRAY_TO_RGB
  180578. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  180579. # endif
  180580. # ifndef PNG_NO_READ_SWAP_ALPHA
  180581. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  180582. # endif
  180583. # ifndef PNG_NO_READ_INVERT_ALPHA
  180584. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  180585. # endif
  180586. # ifndef PNG_NO_READ_STRIP_ALPHA
  180587. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  180588. # endif
  180589. # ifndef PNG_NO_READ_USER_TRANSFORM
  180590. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  180591. # endif
  180592. # ifndef PNG_NO_READ_RGB_TO_GRAY
  180593. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  180594. # endif
  180595. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  180596. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  180597. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  180598. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  180599. #endif /* about interlacing capability! You'll */
  180600. /* still have interlacing unless you change the following line: */
  180601. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  180602. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  180603. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  180604. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  180605. # endif
  180606. #endif
  180607. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180608. /* Deprecated, will be removed from version 2.0.0.
  180609. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  180610. #ifndef PNG_NO_READ_EMPTY_PLTE
  180611. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  180612. #endif
  180613. #endif
  180614. #endif /* PNG_READ_SUPPORTED */
  180615. #if defined(PNG_WRITE_SUPPORTED)
  180616. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  180617. !defined(PNG_NO_WRITE_TRANSFORMS)
  180618. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  180619. #endif
  180620. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  180621. # ifndef PNG_NO_WRITE_SHIFT
  180622. # define PNG_WRITE_SHIFT_SUPPORTED
  180623. # endif
  180624. # ifndef PNG_NO_WRITE_PACK
  180625. # define PNG_WRITE_PACK_SUPPORTED
  180626. # endif
  180627. # ifndef PNG_NO_WRITE_BGR
  180628. # define PNG_WRITE_BGR_SUPPORTED
  180629. # endif
  180630. # ifndef PNG_NO_WRITE_SWAP
  180631. # define PNG_WRITE_SWAP_SUPPORTED
  180632. # endif
  180633. # ifndef PNG_NO_WRITE_PACKSWAP
  180634. # define PNG_WRITE_PACKSWAP_SUPPORTED
  180635. # endif
  180636. # ifndef PNG_NO_WRITE_INVERT
  180637. # define PNG_WRITE_INVERT_SUPPORTED
  180638. # endif
  180639. # ifndef PNG_NO_WRITE_FILLER
  180640. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  180641. # endif
  180642. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  180643. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  180644. # endif
  180645. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  180646. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  180647. # endif
  180648. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  180649. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  180650. # endif
  180651. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  180652. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  180653. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  180654. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  180655. encoders, but can cause trouble
  180656. if left undefined */
  180657. #endif
  180658. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  180659. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  180660. defined(PNG_FLOATING_POINT_SUPPORTED)
  180661. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  180662. #endif
  180663. #ifndef PNG_NO_WRITE_FLUSH
  180664. # define PNG_WRITE_FLUSH_SUPPORTED
  180665. #endif
  180666. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180667. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  180668. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  180669. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  180670. #endif
  180671. #endif
  180672. #endif /* PNG_WRITE_SUPPORTED */
  180673. #ifndef PNG_1_0_X
  180674. # ifndef PNG_NO_ERROR_NUMBERS
  180675. # define PNG_ERROR_NUMBERS_SUPPORTED
  180676. # endif
  180677. #endif /* PNG_1_0_X */
  180678. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  180679. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  180680. # ifndef PNG_NO_USER_TRANSFORM_PTR
  180681. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  180682. # endif
  180683. #endif
  180684. #ifndef PNG_NO_STDIO
  180685. # define PNG_TIME_RFC1123_SUPPORTED
  180686. #endif
  180687. /* This adds extra functions in pngget.c for accessing data from the
  180688. * info pointer (added in version 0.99)
  180689. * png_get_image_width()
  180690. * png_get_image_height()
  180691. * png_get_bit_depth()
  180692. * png_get_color_type()
  180693. * png_get_compression_type()
  180694. * png_get_filter_type()
  180695. * png_get_interlace_type()
  180696. * png_get_pixel_aspect_ratio()
  180697. * png_get_pixels_per_meter()
  180698. * png_get_x_offset_pixels()
  180699. * png_get_y_offset_pixels()
  180700. * png_get_x_offset_microns()
  180701. * png_get_y_offset_microns()
  180702. */
  180703. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  180704. # define PNG_EASY_ACCESS_SUPPORTED
  180705. #endif
  180706. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  180707. * and removed from version 1.2.20. The following will be removed
  180708. * from libpng-1.4.0
  180709. */
  180710. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  180711. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  180712. # define PNG_OPTIMIZED_CODE_SUPPORTED
  180713. # endif
  180714. #endif
  180715. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  180716. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  180717. # define PNG_ASSEMBLER_CODE_SUPPORTED
  180718. # endif
  180719. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  180720. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  180721. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180722. # define PNG_NO_MMX_CODE
  180723. # endif
  180724. # endif
  180725. # if defined(__APPLE__)
  180726. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180727. # define PNG_NO_MMX_CODE
  180728. # endif
  180729. # endif
  180730. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  180731. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180732. # define PNG_NO_MMX_CODE
  180733. # endif
  180734. # endif
  180735. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180736. # define PNG_MMX_CODE_SUPPORTED
  180737. # endif
  180738. #endif
  180739. /* end of obsolete code to be removed from libpng-1.4.0 */
  180740. #if !defined(PNG_1_0_X)
  180741. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  180742. # define PNG_USER_MEM_SUPPORTED
  180743. #endif
  180744. #endif /* PNG_1_0_X */
  180745. /* Added at libpng-1.2.6 */
  180746. #if !defined(PNG_1_0_X)
  180747. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  180748. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  180749. # define PNG_SET_USER_LIMITS_SUPPORTED
  180750. #endif
  180751. #endif
  180752. #endif /* PNG_1_0_X */
  180753. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  180754. * how large, set these limits to 0x7fffffffL
  180755. */
  180756. #ifndef PNG_USER_WIDTH_MAX
  180757. # define PNG_USER_WIDTH_MAX 1000000L
  180758. #endif
  180759. #ifndef PNG_USER_HEIGHT_MAX
  180760. # define PNG_USER_HEIGHT_MAX 1000000L
  180761. #endif
  180762. /* These are currently experimental features, define them if you want */
  180763. /* very little testing */
  180764. /*
  180765. #ifdef PNG_READ_SUPPORTED
  180766. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  180767. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  180768. # endif
  180769. #endif
  180770. */
  180771. /* This is only for PowerPC big-endian and 680x0 systems */
  180772. /* some testing */
  180773. /*
  180774. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  180775. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  180776. #endif
  180777. */
  180778. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  180779. /*
  180780. #define PNG_NO_POINTER_INDEXING
  180781. */
  180782. /* These functions are turned off by default, as they will be phased out. */
  180783. /*
  180784. #define PNG_USELESS_TESTS_SUPPORTED
  180785. #define PNG_CORRECT_PALETTE_SUPPORTED
  180786. */
  180787. /* Any chunks you are not interested in, you can undef here. The
  180788. * ones that allocate memory may be expecially important (hIST,
  180789. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  180790. * a bit smaller.
  180791. */
  180792. #if defined(PNG_READ_SUPPORTED) && \
  180793. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  180794. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  180795. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  180796. #endif
  180797. #if defined(PNG_WRITE_SUPPORTED) && \
  180798. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  180799. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  180800. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  180801. #endif
  180802. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  180803. #ifdef PNG_NO_READ_TEXT
  180804. # define PNG_NO_READ_iTXt
  180805. # define PNG_NO_READ_tEXt
  180806. # define PNG_NO_READ_zTXt
  180807. #endif
  180808. #ifndef PNG_NO_READ_bKGD
  180809. # define PNG_READ_bKGD_SUPPORTED
  180810. # define PNG_bKGD_SUPPORTED
  180811. #endif
  180812. #ifndef PNG_NO_READ_cHRM
  180813. # define PNG_READ_cHRM_SUPPORTED
  180814. # define PNG_cHRM_SUPPORTED
  180815. #endif
  180816. #ifndef PNG_NO_READ_gAMA
  180817. # define PNG_READ_gAMA_SUPPORTED
  180818. # define PNG_gAMA_SUPPORTED
  180819. #endif
  180820. #ifndef PNG_NO_READ_hIST
  180821. # define PNG_READ_hIST_SUPPORTED
  180822. # define PNG_hIST_SUPPORTED
  180823. #endif
  180824. #ifndef PNG_NO_READ_iCCP
  180825. # define PNG_READ_iCCP_SUPPORTED
  180826. # define PNG_iCCP_SUPPORTED
  180827. #endif
  180828. #ifndef PNG_NO_READ_iTXt
  180829. # ifndef PNG_READ_iTXt_SUPPORTED
  180830. # define PNG_READ_iTXt_SUPPORTED
  180831. # endif
  180832. # ifndef PNG_iTXt_SUPPORTED
  180833. # define PNG_iTXt_SUPPORTED
  180834. # endif
  180835. #endif
  180836. #ifndef PNG_NO_READ_oFFs
  180837. # define PNG_READ_oFFs_SUPPORTED
  180838. # define PNG_oFFs_SUPPORTED
  180839. #endif
  180840. #ifndef PNG_NO_READ_pCAL
  180841. # define PNG_READ_pCAL_SUPPORTED
  180842. # define PNG_pCAL_SUPPORTED
  180843. #endif
  180844. #ifndef PNG_NO_READ_sCAL
  180845. # define PNG_READ_sCAL_SUPPORTED
  180846. # define PNG_sCAL_SUPPORTED
  180847. #endif
  180848. #ifndef PNG_NO_READ_pHYs
  180849. # define PNG_READ_pHYs_SUPPORTED
  180850. # define PNG_pHYs_SUPPORTED
  180851. #endif
  180852. #ifndef PNG_NO_READ_sBIT
  180853. # define PNG_READ_sBIT_SUPPORTED
  180854. # define PNG_sBIT_SUPPORTED
  180855. #endif
  180856. #ifndef PNG_NO_READ_sPLT
  180857. # define PNG_READ_sPLT_SUPPORTED
  180858. # define PNG_sPLT_SUPPORTED
  180859. #endif
  180860. #ifndef PNG_NO_READ_sRGB
  180861. # define PNG_READ_sRGB_SUPPORTED
  180862. # define PNG_sRGB_SUPPORTED
  180863. #endif
  180864. #ifndef PNG_NO_READ_tEXt
  180865. # define PNG_READ_tEXt_SUPPORTED
  180866. # define PNG_tEXt_SUPPORTED
  180867. #endif
  180868. #ifndef PNG_NO_READ_tIME
  180869. # define PNG_READ_tIME_SUPPORTED
  180870. # define PNG_tIME_SUPPORTED
  180871. #endif
  180872. #ifndef PNG_NO_READ_tRNS
  180873. # define PNG_READ_tRNS_SUPPORTED
  180874. # define PNG_tRNS_SUPPORTED
  180875. #endif
  180876. #ifndef PNG_NO_READ_zTXt
  180877. # define PNG_READ_zTXt_SUPPORTED
  180878. # define PNG_zTXt_SUPPORTED
  180879. #endif
  180880. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  180881. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  180882. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  180883. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  180884. # endif
  180885. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  180886. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180887. # endif
  180888. #endif
  180889. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  180890. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  180891. # define PNG_READ_USER_CHUNKS_SUPPORTED
  180892. # define PNG_USER_CHUNKS_SUPPORTED
  180893. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  180894. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  180895. # endif
  180896. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  180897. # undef PNG_NO_HANDLE_AS_UNKNOWN
  180898. # endif
  180899. #endif
  180900. #ifndef PNG_NO_READ_OPT_PLTE
  180901. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  180902. #endif /* optional PLTE chunk in RGB and RGBA images */
  180903. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  180904. defined(PNG_READ_zTXt_SUPPORTED)
  180905. # define PNG_READ_TEXT_SUPPORTED
  180906. # define PNG_TEXT_SUPPORTED
  180907. #endif
  180908. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  180909. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  180910. #ifdef PNG_NO_WRITE_TEXT
  180911. # define PNG_NO_WRITE_iTXt
  180912. # define PNG_NO_WRITE_tEXt
  180913. # define PNG_NO_WRITE_zTXt
  180914. #endif
  180915. #ifndef PNG_NO_WRITE_bKGD
  180916. # define PNG_WRITE_bKGD_SUPPORTED
  180917. # ifndef PNG_bKGD_SUPPORTED
  180918. # define PNG_bKGD_SUPPORTED
  180919. # endif
  180920. #endif
  180921. #ifndef PNG_NO_WRITE_cHRM
  180922. # define PNG_WRITE_cHRM_SUPPORTED
  180923. # ifndef PNG_cHRM_SUPPORTED
  180924. # define PNG_cHRM_SUPPORTED
  180925. # endif
  180926. #endif
  180927. #ifndef PNG_NO_WRITE_gAMA
  180928. # define PNG_WRITE_gAMA_SUPPORTED
  180929. # ifndef PNG_gAMA_SUPPORTED
  180930. # define PNG_gAMA_SUPPORTED
  180931. # endif
  180932. #endif
  180933. #ifndef PNG_NO_WRITE_hIST
  180934. # define PNG_WRITE_hIST_SUPPORTED
  180935. # ifndef PNG_hIST_SUPPORTED
  180936. # define PNG_hIST_SUPPORTED
  180937. # endif
  180938. #endif
  180939. #ifndef PNG_NO_WRITE_iCCP
  180940. # define PNG_WRITE_iCCP_SUPPORTED
  180941. # ifndef PNG_iCCP_SUPPORTED
  180942. # define PNG_iCCP_SUPPORTED
  180943. # endif
  180944. #endif
  180945. #ifndef PNG_NO_WRITE_iTXt
  180946. # ifndef PNG_WRITE_iTXt_SUPPORTED
  180947. # define PNG_WRITE_iTXt_SUPPORTED
  180948. # endif
  180949. # ifndef PNG_iTXt_SUPPORTED
  180950. # define PNG_iTXt_SUPPORTED
  180951. # endif
  180952. #endif
  180953. #ifndef PNG_NO_WRITE_oFFs
  180954. # define PNG_WRITE_oFFs_SUPPORTED
  180955. # ifndef PNG_oFFs_SUPPORTED
  180956. # define PNG_oFFs_SUPPORTED
  180957. # endif
  180958. #endif
  180959. #ifndef PNG_NO_WRITE_pCAL
  180960. # define PNG_WRITE_pCAL_SUPPORTED
  180961. # ifndef PNG_pCAL_SUPPORTED
  180962. # define PNG_pCAL_SUPPORTED
  180963. # endif
  180964. #endif
  180965. #ifndef PNG_NO_WRITE_sCAL
  180966. # define PNG_WRITE_sCAL_SUPPORTED
  180967. # ifndef PNG_sCAL_SUPPORTED
  180968. # define PNG_sCAL_SUPPORTED
  180969. # endif
  180970. #endif
  180971. #ifndef PNG_NO_WRITE_pHYs
  180972. # define PNG_WRITE_pHYs_SUPPORTED
  180973. # ifndef PNG_pHYs_SUPPORTED
  180974. # define PNG_pHYs_SUPPORTED
  180975. # endif
  180976. #endif
  180977. #ifndef PNG_NO_WRITE_sBIT
  180978. # define PNG_WRITE_sBIT_SUPPORTED
  180979. # ifndef PNG_sBIT_SUPPORTED
  180980. # define PNG_sBIT_SUPPORTED
  180981. # endif
  180982. #endif
  180983. #ifndef PNG_NO_WRITE_sPLT
  180984. # define PNG_WRITE_sPLT_SUPPORTED
  180985. # ifndef PNG_sPLT_SUPPORTED
  180986. # define PNG_sPLT_SUPPORTED
  180987. # endif
  180988. #endif
  180989. #ifndef PNG_NO_WRITE_sRGB
  180990. # define PNG_WRITE_sRGB_SUPPORTED
  180991. # ifndef PNG_sRGB_SUPPORTED
  180992. # define PNG_sRGB_SUPPORTED
  180993. # endif
  180994. #endif
  180995. #ifndef PNG_NO_WRITE_tEXt
  180996. # define PNG_WRITE_tEXt_SUPPORTED
  180997. # ifndef PNG_tEXt_SUPPORTED
  180998. # define PNG_tEXt_SUPPORTED
  180999. # endif
  181000. #endif
  181001. #ifndef PNG_NO_WRITE_tIME
  181002. # define PNG_WRITE_tIME_SUPPORTED
  181003. # ifndef PNG_tIME_SUPPORTED
  181004. # define PNG_tIME_SUPPORTED
  181005. # endif
  181006. #endif
  181007. #ifndef PNG_NO_WRITE_tRNS
  181008. # define PNG_WRITE_tRNS_SUPPORTED
  181009. # ifndef PNG_tRNS_SUPPORTED
  181010. # define PNG_tRNS_SUPPORTED
  181011. # endif
  181012. #endif
  181013. #ifndef PNG_NO_WRITE_zTXt
  181014. # define PNG_WRITE_zTXt_SUPPORTED
  181015. # ifndef PNG_zTXt_SUPPORTED
  181016. # define PNG_zTXt_SUPPORTED
  181017. # endif
  181018. #endif
  181019. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181020. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181021. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181022. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181023. # endif
  181024. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181025. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181026. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181027. # endif
  181028. # endif
  181029. #endif
  181030. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181031. defined(PNG_WRITE_zTXt_SUPPORTED)
  181032. # define PNG_WRITE_TEXT_SUPPORTED
  181033. # ifndef PNG_TEXT_SUPPORTED
  181034. # define PNG_TEXT_SUPPORTED
  181035. # endif
  181036. #endif
  181037. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181038. /* Turn this off to disable png_read_png() and
  181039. * png_write_png() and leave the row_pointers member
  181040. * out of the info structure.
  181041. */
  181042. #ifndef PNG_NO_INFO_IMAGE
  181043. # define PNG_INFO_IMAGE_SUPPORTED
  181044. #endif
  181045. /* need the time information for reading tIME chunks */
  181046. #if defined(PNG_tIME_SUPPORTED)
  181047. # if !defined(_WIN32_WCE)
  181048. /* "time.h" functions are not supported on WindowsCE */
  181049. # include <time.h>
  181050. # endif
  181051. #endif
  181052. /* Some typedefs to get us started. These should be safe on most of the
  181053. * common platforms. The typedefs should be at least as large as the
  181054. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181055. * don't have to be exactly that size. Some compilers dislike passing
  181056. * unsigned shorts as function parameters, so you may be better off using
  181057. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181058. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181059. */
  181060. typedef unsigned long png_uint_32;
  181061. typedef long png_int_32;
  181062. typedef unsigned short png_uint_16;
  181063. typedef short png_int_16;
  181064. typedef unsigned char png_byte;
  181065. /* This is usually size_t. It is typedef'ed just in case you need it to
  181066. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181067. #ifdef PNG_SIZE_T
  181068. typedef PNG_SIZE_T png_size_t;
  181069. # define png_sizeof(x) png_convert_size(sizeof (x))
  181070. #else
  181071. typedef size_t png_size_t;
  181072. # define png_sizeof(x) sizeof (x)
  181073. #endif
  181074. /* The following is needed for medium model support. It cannot be in the
  181075. * PNG_INTERNAL section. Needs modification for other compilers besides
  181076. * MSC. Model independent support declares all arrays and pointers to be
  181077. * large using the far keyword. The zlib version used must also support
  181078. * model independent data. As of version zlib 1.0.4, the necessary changes
  181079. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181080. * changes that are needed. (Tim Wegner)
  181081. */
  181082. /* Separate compiler dependencies (problem here is that zlib.h always
  181083. defines FAR. (SJT) */
  181084. #ifdef __BORLANDC__
  181085. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181086. # define LDATA 1
  181087. # else
  181088. # define LDATA 0
  181089. # endif
  181090. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181091. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181092. # define PNG_MAX_MALLOC_64K
  181093. # if (LDATA != 1)
  181094. # ifndef FAR
  181095. # define FAR __far
  181096. # endif
  181097. # define USE_FAR_KEYWORD
  181098. # endif /* LDATA != 1 */
  181099. /* Possibly useful for moving data out of default segment.
  181100. * Uncomment it if you want. Could also define FARDATA as
  181101. * const if your compiler supports it. (SJT)
  181102. # define FARDATA FAR
  181103. */
  181104. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181105. #endif /* __BORLANDC__ */
  181106. /* Suggest testing for specific compiler first before testing for
  181107. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181108. * making reliance oncertain keywords suspect. (SJT)
  181109. */
  181110. /* MSC Medium model */
  181111. #if defined(FAR)
  181112. # if defined(M_I86MM)
  181113. # define USE_FAR_KEYWORD
  181114. # define FARDATA FAR
  181115. # include <dos.h>
  181116. # endif
  181117. #endif
  181118. /* SJT: default case */
  181119. #ifndef FAR
  181120. # define FAR
  181121. #endif
  181122. /* At this point FAR is always defined */
  181123. #ifndef FARDATA
  181124. # define FARDATA
  181125. #endif
  181126. /* Typedef for floating-point numbers that are converted
  181127. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181128. typedef png_int_32 png_fixed_point;
  181129. /* Add typedefs for pointers */
  181130. typedef void FAR * png_voidp;
  181131. typedef png_byte FAR * png_bytep;
  181132. typedef png_uint_32 FAR * png_uint_32p;
  181133. typedef png_int_32 FAR * png_int_32p;
  181134. typedef png_uint_16 FAR * png_uint_16p;
  181135. typedef png_int_16 FAR * png_int_16p;
  181136. typedef PNG_CONST char FAR * png_const_charp;
  181137. typedef char FAR * png_charp;
  181138. typedef png_fixed_point FAR * png_fixed_point_p;
  181139. #ifndef PNG_NO_STDIO
  181140. #if defined(_WIN32_WCE)
  181141. typedef HANDLE png_FILE_p;
  181142. #else
  181143. typedef FILE * png_FILE_p;
  181144. #endif
  181145. #endif
  181146. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181147. typedef double FAR * png_doublep;
  181148. #endif
  181149. /* Pointers to pointers; i.e. arrays */
  181150. typedef png_byte FAR * FAR * png_bytepp;
  181151. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181152. typedef png_int_32 FAR * FAR * png_int_32pp;
  181153. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181154. typedef png_int_16 FAR * FAR * png_int_16pp;
  181155. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181156. typedef char FAR * FAR * png_charpp;
  181157. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181158. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181159. typedef double FAR * FAR * png_doublepp;
  181160. #endif
  181161. /* Pointers to pointers to pointers; i.e., pointer to array */
  181162. typedef char FAR * FAR * FAR * png_charppp;
  181163. #if 0
  181164. /* SPC - Is this stuff deprecated? */
  181165. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181166. /* libpng typedefs for types in zlib. If zlib changes
  181167. * or another compression library is used, then change these.
  181168. * Eliminates need to change all the source files.
  181169. */
  181170. typedef charf * png_zcharp;
  181171. typedef charf * FAR * png_zcharpp;
  181172. typedef z_stream FAR * png_zstreamp;
  181173. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181174. /*
  181175. * Define PNG_BUILD_DLL if the module being built is a Windows
  181176. * LIBPNG DLL.
  181177. *
  181178. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181179. * It is equivalent to Microsoft predefined macro _DLL that is
  181180. * automatically defined when you compile using the share
  181181. * version of the CRT (C Run-Time library)
  181182. *
  181183. * The cygwin mods make this behavior a little different:
  181184. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181185. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181186. * -or- if you are building an application that you want to link to the
  181187. * static library.
  181188. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181189. * the other flags is defined.
  181190. */
  181191. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181192. # define PNG_DLL
  181193. #endif
  181194. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181195. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181196. * command-line override
  181197. */
  181198. #if defined(__CYGWIN__)
  181199. # if !defined(PNG_STATIC)
  181200. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181201. # undef PNG_USE_GLOBAL_ARRAYS
  181202. # endif
  181203. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181204. # define PNG_USE_LOCAL_ARRAYS
  181205. # endif
  181206. # else
  181207. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181208. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181209. # undef PNG_USE_GLOBAL_ARRAYS
  181210. # endif
  181211. # endif
  181212. # endif
  181213. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181214. # define PNG_USE_LOCAL_ARRAYS
  181215. # endif
  181216. #endif
  181217. /* Do not use global arrays (helps with building DLL's)
  181218. * They are no longer used in libpng itself, since version 1.0.5c,
  181219. * but might be required for some pre-1.0.5c applications.
  181220. */
  181221. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181222. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181223. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181224. # define PNG_USE_LOCAL_ARRAYS
  181225. # else
  181226. # define PNG_USE_GLOBAL_ARRAYS
  181227. # endif
  181228. #endif
  181229. #if defined(__CYGWIN__)
  181230. # undef PNGAPI
  181231. # define PNGAPI __cdecl
  181232. # undef PNG_IMPEXP
  181233. # define PNG_IMPEXP
  181234. #endif
  181235. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181236. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181237. * Don't ignore those warnings; you must also reset the default calling
  181238. * convention in your compiler to match your PNGAPI, and you must build
  181239. * zlib and your applications the same way you build libpng.
  181240. */
  181241. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181242. # ifndef PNG_NO_MODULEDEF
  181243. # define PNG_NO_MODULEDEF
  181244. # endif
  181245. #endif
  181246. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181247. # define PNG_IMPEXP
  181248. #endif
  181249. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181250. (( defined(_Windows) || defined(_WINDOWS) || \
  181251. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181252. # ifndef PNGAPI
  181253. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181254. # define PNGAPI __cdecl
  181255. # else
  181256. # define PNGAPI _cdecl
  181257. # endif
  181258. # endif
  181259. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181260. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181261. # define PNG_IMPEXP
  181262. # endif
  181263. # if !defined(PNG_IMPEXP)
  181264. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181265. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  181266. /* Borland/Microsoft */
  181267. # if defined(_MSC_VER) || defined(__BORLANDC__)
  181268. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  181269. # define PNG_EXPORT PNG_EXPORT_TYPE1
  181270. # else
  181271. # define PNG_EXPORT PNG_EXPORT_TYPE2
  181272. # if defined(PNG_BUILD_DLL)
  181273. # define PNG_IMPEXP __export
  181274. # else
  181275. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  181276. VC++ */
  181277. # endif /* Exists in Borland C++ for
  181278. C++ classes (== huge) */
  181279. # endif
  181280. # endif
  181281. # if !defined(PNG_IMPEXP)
  181282. # if defined(PNG_BUILD_DLL)
  181283. # define PNG_IMPEXP __declspec(dllexport)
  181284. # else
  181285. # define PNG_IMPEXP __declspec(dllimport)
  181286. # endif
  181287. # endif
  181288. # endif /* PNG_IMPEXP */
  181289. #else /* !(DLL || non-cygwin WINDOWS) */
  181290. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  181291. # ifndef PNGAPI
  181292. # define PNGAPI _System
  181293. # endif
  181294. # else
  181295. # if 0 /* ... other platforms, with other meanings */
  181296. # endif
  181297. # endif
  181298. #endif
  181299. #ifndef PNGAPI
  181300. # define PNGAPI
  181301. #endif
  181302. #ifndef PNG_IMPEXP
  181303. # define PNG_IMPEXP
  181304. #endif
  181305. #ifdef PNG_BUILDSYMS
  181306. # ifndef PNG_EXPORT
  181307. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181308. # endif
  181309. # ifdef PNG_USE_GLOBAL_ARRAYS
  181310. # ifndef PNG_EXPORT_VAR
  181311. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181312. # endif
  181313. # endif
  181314. #endif
  181315. #ifndef PNG_EXPORT
  181316. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181317. #endif
  181318. #ifdef PNG_USE_GLOBAL_ARRAYS
  181319. # ifndef PNG_EXPORT_VAR
  181320. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181321. # endif
  181322. #endif
  181323. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181324. * functions that are passed far data must be model independent.
  181325. */
  181326. #ifndef PNG_ABORT
  181327. # define PNG_ABORT() abort()
  181328. #endif
  181329. #ifdef PNG_SETJMP_SUPPORTED
  181330. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181331. #else
  181332. # define png_jmpbuf(png_ptr) \
  181333. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181334. #endif
  181335. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181336. /* use this to make far-to-near assignments */
  181337. # define CHECK 1
  181338. # define NOCHECK 0
  181339. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181340. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181341. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181342. # define png_strcpy _fstrcpy
  181343. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181344. # define png_strlen _fstrlen
  181345. # define png_memcmp _fmemcmp /* SJT: added */
  181346. # define png_memcpy _fmemcpy
  181347. # define png_memset _fmemset
  181348. #else /* use the usual functions */
  181349. # define CVT_PTR(ptr) (ptr)
  181350. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181351. # ifndef PNG_NO_SNPRINTF
  181352. # ifdef _MSC_VER
  181353. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181354. # define png_snprintf2 _snprintf
  181355. # define png_snprintf6 _snprintf
  181356. # else
  181357. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181358. # define png_snprintf2 snprintf
  181359. # define png_snprintf6 snprintf
  181360. # endif
  181361. # else
  181362. /* You don't have or don't want to use snprintf(). Caution: Using
  181363. * sprintf instead of snprintf exposes your application to accidental
  181364. * or malevolent buffer overflows. If you don't have snprintf()
  181365. * as a general rule you should provide one (you can get one from
  181366. * Portable OpenSSH). */
  181367. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181368. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181369. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181370. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181371. # endif
  181372. # define png_strcpy strcpy
  181373. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181374. # define png_strlen strlen
  181375. # define png_memcmp memcmp /* SJT: added */
  181376. # define png_memcpy memcpy
  181377. # define png_memset memset
  181378. #endif
  181379. /* End of memory model independent support */
  181380. /* Just a little check that someone hasn't tried to define something
  181381. * contradictory.
  181382. */
  181383. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  181384. # undef PNG_ZBUF_SIZE
  181385. # define PNG_ZBUF_SIZE 65536L
  181386. #endif
  181387. /* Added at libpng-1.2.8 */
  181388. #endif /* PNG_VERSION_INFO_ONLY */
  181389. #endif /* PNGCONF_H */
  181390. /*** End of inlined file: pngconf.h ***/
  181391. #ifdef _MSC_VER
  181392. #pragma warning (disable: 4996 4100)
  181393. #endif
  181394. /*
  181395. * Added at libpng-1.2.8 */
  181396. /* Ref MSDN: Private as priority over Special
  181397. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  181398. * procedures. If this value is given, the StringFileInfo block must
  181399. * contain a PrivateBuild string.
  181400. *
  181401. * VS_FF_SPECIALBUILD File *was* built by the original company using
  181402. * standard release procedures but is a variation of the standard
  181403. * file of the same version number. If this value is given, the
  181404. * StringFileInfo block must contain a SpecialBuild string.
  181405. */
  181406. #if defined(PNG_USER_PRIVATEBUILD)
  181407. # define PNG_LIBPNG_BUILD_TYPE \
  181408. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  181409. #else
  181410. # if defined(PNG_LIBPNG_SPECIALBUILD)
  181411. # define PNG_LIBPNG_BUILD_TYPE \
  181412. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  181413. # else
  181414. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  181415. # endif
  181416. #endif
  181417. #ifndef PNG_VERSION_INFO_ONLY
  181418. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  181419. #ifdef __cplusplus
  181420. extern "C" {
  181421. #endif /* __cplusplus */
  181422. /* This file is arranged in several sections. The first section contains
  181423. * structure and type definitions. The second section contains the external
  181424. * library functions, while the third has the internal library functions,
  181425. * which applications aren't expected to use directly.
  181426. */
  181427. #ifndef PNG_NO_TYPECAST_NULL
  181428. #define int_p_NULL (int *)NULL
  181429. #define png_bytep_NULL (png_bytep)NULL
  181430. #define png_bytepp_NULL (png_bytepp)NULL
  181431. #define png_doublep_NULL (png_doublep)NULL
  181432. #define png_error_ptr_NULL (png_error_ptr)NULL
  181433. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  181434. #define png_free_ptr_NULL (png_free_ptr)NULL
  181435. #define png_infopp_NULL (png_infopp)NULL
  181436. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  181437. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  181438. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  181439. #define png_structp_NULL (png_structp)NULL
  181440. #define png_uint_16p_NULL (png_uint_16p)NULL
  181441. #define png_voidp_NULL (png_voidp)NULL
  181442. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  181443. #else
  181444. #define int_p_NULL NULL
  181445. #define png_bytep_NULL NULL
  181446. #define png_bytepp_NULL NULL
  181447. #define png_doublep_NULL NULL
  181448. #define png_error_ptr_NULL NULL
  181449. #define png_flush_ptr_NULL NULL
  181450. #define png_free_ptr_NULL NULL
  181451. #define png_infopp_NULL NULL
  181452. #define png_malloc_ptr_NULL NULL
  181453. #define png_read_status_ptr_NULL NULL
  181454. #define png_rw_ptr_NULL NULL
  181455. #define png_structp_NULL NULL
  181456. #define png_uint_16p_NULL NULL
  181457. #define png_voidp_NULL NULL
  181458. #define png_write_status_ptr_NULL NULL
  181459. #endif
  181460. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  181461. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  181462. /* Version information for C files, stored in png.c. This had better match
  181463. * the version above.
  181464. */
  181465. #ifdef PNG_USE_GLOBAL_ARRAYS
  181466. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  181467. /* need room for 99.99.99beta99z */
  181468. #else
  181469. #define png_libpng_ver png_get_header_ver(NULL)
  181470. #endif
  181471. #ifdef PNG_USE_GLOBAL_ARRAYS
  181472. /* This was removed in version 1.0.5c */
  181473. /* Structures to facilitate easy interlacing. See png.c for more details */
  181474. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  181475. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  181476. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  181477. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  181478. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  181479. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  181480. /* This isn't currently used. If you need it, see png.c for more details.
  181481. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  181482. */
  181483. #endif
  181484. #endif /* PNG_NO_EXTERN */
  181485. /* Three color definitions. The order of the red, green, and blue, (and the
  181486. * exact size) is not important, although the size of the fields need to
  181487. * be png_byte or png_uint_16 (as defined below).
  181488. */
  181489. typedef struct png_color_struct
  181490. {
  181491. png_byte red;
  181492. png_byte green;
  181493. png_byte blue;
  181494. } png_color;
  181495. typedef png_color FAR * png_colorp;
  181496. typedef png_color FAR * FAR * png_colorpp;
  181497. typedef struct png_color_16_struct
  181498. {
  181499. png_byte index; /* used for palette files */
  181500. png_uint_16 red; /* for use in red green blue files */
  181501. png_uint_16 green;
  181502. png_uint_16 blue;
  181503. png_uint_16 gray; /* for use in grayscale files */
  181504. } png_color_16;
  181505. typedef png_color_16 FAR * png_color_16p;
  181506. typedef png_color_16 FAR * FAR * png_color_16pp;
  181507. typedef struct png_color_8_struct
  181508. {
  181509. png_byte red; /* for use in red green blue files */
  181510. png_byte green;
  181511. png_byte blue;
  181512. png_byte gray; /* for use in grayscale files */
  181513. png_byte alpha; /* for alpha channel files */
  181514. } png_color_8;
  181515. typedef png_color_8 FAR * png_color_8p;
  181516. typedef png_color_8 FAR * FAR * png_color_8pp;
  181517. /*
  181518. * The following two structures are used for the in-core representation
  181519. * of sPLT chunks.
  181520. */
  181521. typedef struct png_sPLT_entry_struct
  181522. {
  181523. png_uint_16 red;
  181524. png_uint_16 green;
  181525. png_uint_16 blue;
  181526. png_uint_16 alpha;
  181527. png_uint_16 frequency;
  181528. } png_sPLT_entry;
  181529. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  181530. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  181531. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  181532. * occupy the LSB of their respective members, and the MSB of each member
  181533. * is zero-filled. The frequency member always occupies the full 16 bits.
  181534. */
  181535. typedef struct png_sPLT_struct
  181536. {
  181537. png_charp name; /* palette name */
  181538. png_byte depth; /* depth of palette samples */
  181539. png_sPLT_entryp entries; /* palette entries */
  181540. png_int_32 nentries; /* number of palette entries */
  181541. } png_sPLT_t;
  181542. typedef png_sPLT_t FAR * png_sPLT_tp;
  181543. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  181544. #ifdef PNG_TEXT_SUPPORTED
  181545. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  181546. * and whether that contents is compressed or not. The "key" field
  181547. * points to a regular zero-terminated C string. The "text", "lang", and
  181548. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  181549. * However, the * structure returned by png_get_text() will always contain
  181550. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  181551. * so they can be safely used in printf() and other string-handling functions.
  181552. */
  181553. typedef struct png_text_struct
  181554. {
  181555. int compression; /* compression value:
  181556. -1: tEXt, none
  181557. 0: zTXt, deflate
  181558. 1: iTXt, none
  181559. 2: iTXt, deflate */
  181560. png_charp key; /* keyword, 1-79 character description of "text" */
  181561. png_charp text; /* comment, may be an empty string (ie "")
  181562. or a NULL pointer */
  181563. png_size_t text_length; /* length of the text string */
  181564. #ifdef PNG_iTXt_SUPPORTED
  181565. png_size_t itxt_length; /* length of the itxt string */
  181566. png_charp lang; /* language code, 0-79 characters
  181567. or a NULL pointer */
  181568. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  181569. chars or a NULL pointer */
  181570. #endif
  181571. } png_text;
  181572. typedef png_text FAR * png_textp;
  181573. typedef png_text FAR * FAR * png_textpp;
  181574. #endif
  181575. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  181576. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  181577. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  181578. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  181579. #define PNG_TEXT_COMPRESSION_NONE -1
  181580. #define PNG_TEXT_COMPRESSION_zTXt 0
  181581. #define PNG_ITXT_COMPRESSION_NONE 1
  181582. #define PNG_ITXT_COMPRESSION_zTXt 2
  181583. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  181584. /* png_time is a way to hold the time in an machine independent way.
  181585. * Two conversions are provided, both from time_t and struct tm. There
  181586. * is no portable way to convert to either of these structures, as far
  181587. * as I know. If you know of a portable way, send it to me. As a side
  181588. * note - PNG has always been Year 2000 compliant!
  181589. */
  181590. typedef struct png_time_struct
  181591. {
  181592. png_uint_16 year; /* full year, as in, 1995 */
  181593. png_byte month; /* month of year, 1 - 12 */
  181594. png_byte day; /* day of month, 1 - 31 */
  181595. png_byte hour; /* hour of day, 0 - 23 */
  181596. png_byte minute; /* minute of hour, 0 - 59 */
  181597. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  181598. } png_time;
  181599. typedef png_time FAR * png_timep;
  181600. typedef png_time FAR * FAR * png_timepp;
  181601. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181602. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  181603. * no specific support. The idea is that we can use this to queue
  181604. * up private chunks for output even though the library doesn't actually
  181605. * know about their semantics.
  181606. */
  181607. typedef struct png_unknown_chunk_t
  181608. {
  181609. png_byte name[5];
  181610. png_byte *data;
  181611. png_size_t size;
  181612. /* libpng-using applications should NOT directly modify this byte. */
  181613. png_byte location; /* mode of operation at read time */
  181614. }
  181615. png_unknown_chunk;
  181616. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  181617. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  181618. #endif
  181619. /* png_info is a structure that holds the information in a PNG file so
  181620. * that the application can find out the characteristics of the image.
  181621. * If you are reading the file, this structure will tell you what is
  181622. * in the PNG file. If you are writing the file, fill in the information
  181623. * you want to put into the PNG file, then call png_write_info().
  181624. * The names chosen should be very close to the PNG specification, so
  181625. * consult that document for information about the meaning of each field.
  181626. *
  181627. * With libpng < 0.95, it was only possible to directly set and read the
  181628. * the values in the png_info_struct, which meant that the contents and
  181629. * order of the values had to remain fixed. With libpng 0.95 and later,
  181630. * however, there are now functions that abstract the contents of
  181631. * png_info_struct from the application, so this makes it easier to use
  181632. * libpng with dynamic libraries, and even makes it possible to use
  181633. * libraries that don't have all of the libpng ancillary chunk-handing
  181634. * functionality.
  181635. *
  181636. * In any case, the order of the parameters in png_info_struct should NOT
  181637. * be changed for as long as possible to keep compatibility with applications
  181638. * that use the old direct-access method with png_info_struct.
  181639. *
  181640. * The following members may have allocated storage attached that should be
  181641. * cleaned up before the structure is discarded: palette, trans, text,
  181642. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  181643. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  181644. * are automatically freed when the info structure is deallocated, if they were
  181645. * allocated internally by libpng. This behavior can be changed by means
  181646. * of the png_data_freer() function.
  181647. *
  181648. * More allocation details: all the chunk-reading functions that
  181649. * change these members go through the corresponding png_set_*
  181650. * functions. A function to clear these members is available: see
  181651. * png_free_data(). The png_set_* functions do not depend on being
  181652. * able to point info structure members to any of the storage they are
  181653. * passed (they make their own copies), EXCEPT that the png_set_text
  181654. * functions use the same storage passed to them in the text_ptr or
  181655. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  181656. * functions do not make their own copies.
  181657. */
  181658. typedef struct png_info_struct
  181659. {
  181660. /* the following are necessary for every PNG file */
  181661. png_uint_32 width; /* width of image in pixels (from IHDR) */
  181662. png_uint_32 height; /* height of image in pixels (from IHDR) */
  181663. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  181664. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  181665. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  181666. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  181667. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  181668. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  181669. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  181670. /* The following three should have been named *_method not *_type */
  181671. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  181672. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  181673. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  181674. /* The following is informational only on read, and not used on writes. */
  181675. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  181676. png_byte pixel_depth; /* number of bits per pixel */
  181677. png_byte spare_byte; /* to align the data, and for future use */
  181678. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  181679. /* The rest of the data is optional. If you are reading, check the
  181680. * valid field to see if the information in these are valid. If you
  181681. * are writing, set the valid field to those chunks you want written,
  181682. * and initialize the appropriate fields below.
  181683. */
  181684. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  181685. /* The gAMA chunk describes the gamma characteristics of the system
  181686. * on which the image was created, normally in the range [1.0, 2.5].
  181687. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  181688. */
  181689. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  181690. #endif
  181691. #if defined(PNG_sRGB_SUPPORTED)
  181692. /* GR-P, 0.96a */
  181693. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  181694. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  181695. #endif
  181696. #if defined(PNG_TEXT_SUPPORTED)
  181697. /* The tEXt, and zTXt chunks contain human-readable textual data in
  181698. * uncompressed, compressed, and optionally compressed forms, respectively.
  181699. * The data in "text" is an array of pointers to uncompressed,
  181700. * null-terminated C strings. Each chunk has a keyword that describes the
  181701. * textual data contained in that chunk. Keywords are not required to be
  181702. * unique, and the text string may be empty. Any number of text chunks may
  181703. * be in an image.
  181704. */
  181705. int num_text; /* number of comments read/to write */
  181706. int max_text; /* current size of text array */
  181707. png_textp text; /* array of comments read/to write */
  181708. #endif /* PNG_TEXT_SUPPORTED */
  181709. #if defined(PNG_tIME_SUPPORTED)
  181710. /* The tIME chunk holds the last time the displayed image data was
  181711. * modified. See the png_time struct for the contents of this struct.
  181712. */
  181713. png_time mod_time;
  181714. #endif
  181715. #if defined(PNG_sBIT_SUPPORTED)
  181716. /* The sBIT chunk specifies the number of significant high-order bits
  181717. * in the pixel data. Values are in the range [1, bit_depth], and are
  181718. * only specified for the channels in the pixel data. The contents of
  181719. * the low-order bits is not specified. Data is valid if
  181720. * (valid & PNG_INFO_sBIT) is non-zero.
  181721. */
  181722. png_color_8 sig_bit; /* significant bits in color channels */
  181723. #endif
  181724. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  181725. defined(PNG_READ_BACKGROUND_SUPPORTED)
  181726. /* The tRNS chunk supplies transparency data for paletted images and
  181727. * other image types that don't need a full alpha channel. There are
  181728. * "num_trans" transparency values for a paletted image, stored in the
  181729. * same order as the palette colors, starting from index 0. Values
  181730. * for the data are in the range [0, 255], ranging from fully transparent
  181731. * to fully opaque, respectively. For non-paletted images, there is a
  181732. * single color specified that should be treated as fully transparent.
  181733. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  181734. */
  181735. png_bytep trans; /* transparent values for paletted image */
  181736. png_color_16 trans_values; /* transparent color for non-palette image */
  181737. #endif
  181738. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181739. /* The bKGD chunk gives the suggested image background color if the
  181740. * display program does not have its own background color and the image
  181741. * is needs to composited onto a background before display. The colors
  181742. * in "background" are normally in the same color space/depth as the
  181743. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  181744. */
  181745. png_color_16 background;
  181746. #endif
  181747. #if defined(PNG_oFFs_SUPPORTED)
  181748. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  181749. * and downwards from the top-left corner of the display, page, or other
  181750. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  181751. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  181752. */
  181753. png_int_32 x_offset; /* x offset on page */
  181754. png_int_32 y_offset; /* y offset on page */
  181755. png_byte offset_unit_type; /* offset units type */
  181756. #endif
  181757. #if defined(PNG_pHYs_SUPPORTED)
  181758. /* The pHYs chunk gives the physical pixel density of the image for
  181759. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  181760. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  181761. */
  181762. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  181763. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  181764. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  181765. #endif
  181766. #if defined(PNG_hIST_SUPPORTED)
  181767. /* The hIST chunk contains the relative frequency or importance of the
  181768. * various palette entries, so that a viewer can intelligently select a
  181769. * reduced-color palette, if required. Data is an array of "num_palette"
  181770. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  181771. * is non-zero.
  181772. */
  181773. png_uint_16p hist;
  181774. #endif
  181775. #ifdef PNG_cHRM_SUPPORTED
  181776. /* The cHRM chunk describes the CIE color characteristics of the monitor
  181777. * on which the PNG was created. This data allows the viewer to do gamut
  181778. * mapping of the input image to ensure that the viewer sees the same
  181779. * colors in the image as the creator. Values are in the range
  181780. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  181781. */
  181782. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181783. float x_white;
  181784. float y_white;
  181785. float x_red;
  181786. float y_red;
  181787. float x_green;
  181788. float y_green;
  181789. float x_blue;
  181790. float y_blue;
  181791. #endif
  181792. #endif
  181793. #if defined(PNG_pCAL_SUPPORTED)
  181794. /* The pCAL chunk describes a transformation between the stored pixel
  181795. * values and original physical data values used to create the image.
  181796. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  181797. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  181798. * (possibly non-linear) transformation function given by "pcal_type"
  181799. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  181800. * defines below, and the PNG-Group's PNG extensions document for a
  181801. * complete description of the transformations and how they should be
  181802. * implemented, and for a description of the ASCII parameter strings.
  181803. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  181804. */
  181805. png_charp pcal_purpose; /* pCAL chunk description string */
  181806. png_int_32 pcal_X0; /* minimum value */
  181807. png_int_32 pcal_X1; /* maximum value */
  181808. png_charp pcal_units; /* Latin-1 string giving physical units */
  181809. png_charpp pcal_params; /* ASCII strings containing parameter values */
  181810. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  181811. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  181812. #endif
  181813. /* New members added in libpng-1.0.6 */
  181814. #ifdef PNG_FREE_ME_SUPPORTED
  181815. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  181816. #endif
  181817. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181818. /* storage for unknown chunks that the library doesn't recognize. */
  181819. png_unknown_chunkp unknown_chunks;
  181820. png_size_t unknown_chunks_num;
  181821. #endif
  181822. #if defined(PNG_iCCP_SUPPORTED)
  181823. /* iCCP chunk data. */
  181824. png_charp iccp_name; /* profile name */
  181825. png_charp iccp_profile; /* International Color Consortium profile data */
  181826. /* Note to maintainer: should be png_bytep */
  181827. png_uint_32 iccp_proflen; /* ICC profile data length */
  181828. png_byte iccp_compression; /* Always zero */
  181829. #endif
  181830. #if defined(PNG_sPLT_SUPPORTED)
  181831. /* data on sPLT chunks (there may be more than one). */
  181832. png_sPLT_tp splt_palettes;
  181833. png_uint_32 splt_palettes_num;
  181834. #endif
  181835. #if defined(PNG_sCAL_SUPPORTED)
  181836. /* The sCAL chunk describes the actual physical dimensions of the
  181837. * subject matter of the graphic. The chunk contains a unit specification
  181838. * a byte value, and two ASCII strings representing floating-point
  181839. * values. The values are width and height corresponsing to one pixel
  181840. * in the image. This external representation is converted to double
  181841. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  181842. */
  181843. png_byte scal_unit; /* unit of physical scale */
  181844. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181845. double scal_pixel_width; /* width of one pixel */
  181846. double scal_pixel_height; /* height of one pixel */
  181847. #endif
  181848. #ifdef PNG_FIXED_POINT_SUPPORTED
  181849. png_charp scal_s_width; /* string containing height */
  181850. png_charp scal_s_height; /* string containing width */
  181851. #endif
  181852. #endif
  181853. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  181854. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  181855. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  181856. png_bytepp row_pointers; /* the image bits */
  181857. #endif
  181858. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  181859. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  181860. #endif
  181861. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  181862. png_fixed_point int_x_white;
  181863. png_fixed_point int_y_white;
  181864. png_fixed_point int_x_red;
  181865. png_fixed_point int_y_red;
  181866. png_fixed_point int_x_green;
  181867. png_fixed_point int_y_green;
  181868. png_fixed_point int_x_blue;
  181869. png_fixed_point int_y_blue;
  181870. #endif
  181871. } png_info;
  181872. typedef png_info FAR * png_infop;
  181873. typedef png_info FAR * FAR * png_infopp;
  181874. /* Maximum positive integer used in PNG is (2^31)-1 */
  181875. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  181876. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  181877. #define PNG_SIZE_MAX ((png_size_t)(-1))
  181878. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181879. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  181880. #define PNG_MAX_UINT PNG_UINT_31_MAX
  181881. #endif
  181882. /* These describe the color_type field in png_info. */
  181883. /* color type masks */
  181884. #define PNG_COLOR_MASK_PALETTE 1
  181885. #define PNG_COLOR_MASK_COLOR 2
  181886. #define PNG_COLOR_MASK_ALPHA 4
  181887. /* color types. Note that not all combinations are legal */
  181888. #define PNG_COLOR_TYPE_GRAY 0
  181889. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  181890. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  181891. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  181892. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  181893. /* aliases */
  181894. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  181895. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  181896. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  181897. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  181898. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  181899. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  181900. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  181901. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  181902. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  181903. /* These are for the interlacing type. These values should NOT be changed. */
  181904. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  181905. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  181906. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  181907. /* These are for the oFFs chunk. These values should NOT be changed. */
  181908. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  181909. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  181910. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  181911. /* These are for the pCAL chunk. These values should NOT be changed. */
  181912. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  181913. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  181914. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  181915. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  181916. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  181917. /* These are for the sCAL chunk. These values should NOT be changed. */
  181918. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  181919. #define PNG_SCALE_METER 1 /* meters per pixel */
  181920. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  181921. #define PNG_SCALE_LAST 3 /* Not a valid value */
  181922. /* These are for the pHYs chunk. These values should NOT be changed. */
  181923. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  181924. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  181925. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  181926. /* These are for the sRGB chunk. These values should NOT be changed. */
  181927. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  181928. #define PNG_sRGB_INTENT_RELATIVE 1
  181929. #define PNG_sRGB_INTENT_SATURATION 2
  181930. #define PNG_sRGB_INTENT_ABSOLUTE 3
  181931. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  181932. /* This is for text chunks */
  181933. #define PNG_KEYWORD_MAX_LENGTH 79
  181934. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  181935. #define PNG_MAX_PALETTE_LENGTH 256
  181936. /* These determine if an ancillary chunk's data has been successfully read
  181937. * from the PNG header, or if the application has filled in the corresponding
  181938. * data in the info_struct to be written into the output file. The values
  181939. * of the PNG_INFO_<chunk> defines should NOT be changed.
  181940. */
  181941. #define PNG_INFO_gAMA 0x0001
  181942. #define PNG_INFO_sBIT 0x0002
  181943. #define PNG_INFO_cHRM 0x0004
  181944. #define PNG_INFO_PLTE 0x0008
  181945. #define PNG_INFO_tRNS 0x0010
  181946. #define PNG_INFO_bKGD 0x0020
  181947. #define PNG_INFO_hIST 0x0040
  181948. #define PNG_INFO_pHYs 0x0080
  181949. #define PNG_INFO_oFFs 0x0100
  181950. #define PNG_INFO_tIME 0x0200
  181951. #define PNG_INFO_pCAL 0x0400
  181952. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  181953. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  181954. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  181955. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  181956. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  181957. /* This is used for the transformation routines, as some of them
  181958. * change these values for the row. It also should enable using
  181959. * the routines for other purposes.
  181960. */
  181961. typedef struct png_row_info_struct
  181962. {
  181963. png_uint_32 width; /* width of row */
  181964. png_uint_32 rowbytes; /* number of bytes in row */
  181965. png_byte color_type; /* color type of row */
  181966. png_byte bit_depth; /* bit depth of row */
  181967. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  181968. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  181969. } png_row_info;
  181970. typedef png_row_info FAR * png_row_infop;
  181971. typedef png_row_info FAR * FAR * png_row_infopp;
  181972. /* These are the function types for the I/O functions and for the functions
  181973. * that allow the user to override the default I/O functions with his or her
  181974. * own. The png_error_ptr type should match that of user-supplied warning
  181975. * and error functions, while the png_rw_ptr type should match that of the
  181976. * user read/write data functions.
  181977. */
  181978. typedef struct png_struct_def png_struct;
  181979. typedef png_struct FAR * png_structp;
  181980. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  181981. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  181982. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  181983. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  181984. int));
  181985. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  181986. int));
  181987. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181988. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  181989. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  181990. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  181991. png_uint_32, int));
  181992. #endif
  181993. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181994. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  181995. defined(PNG_LEGACY_SUPPORTED)
  181996. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  181997. png_row_infop, png_bytep));
  181998. #endif
  181999. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182000. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182001. #endif
  182002. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182003. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182004. #endif
  182005. /* Transform masks for the high-level interface */
  182006. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182007. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182008. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182009. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182010. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182011. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182012. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182013. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182014. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182015. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182016. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182017. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182018. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182019. /* Flags for MNG supported features */
  182020. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182021. #define PNG_FLAG_MNG_FILTER_64 0x04
  182022. #define PNG_ALL_MNG_FEATURES 0x05
  182023. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182024. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182025. /* The structure that holds the information to read and write PNG files.
  182026. * The only people who need to care about what is inside of this are the
  182027. * people who will be modifying the library for their own special needs.
  182028. * It should NOT be accessed directly by an application, except to store
  182029. * the jmp_buf.
  182030. */
  182031. struct png_struct_def
  182032. {
  182033. #ifdef PNG_SETJMP_SUPPORTED
  182034. jmp_buf jmpbuf; /* used in png_error */
  182035. #endif
  182036. png_error_ptr error_fn; /* function for printing errors and aborting */
  182037. png_error_ptr warning_fn; /* function for printing warnings */
  182038. png_voidp error_ptr; /* user supplied struct for error functions */
  182039. png_rw_ptr write_data_fn; /* function for writing output data */
  182040. png_rw_ptr read_data_fn; /* function for reading input data */
  182041. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182042. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182043. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182044. #endif
  182045. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182046. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182047. #endif
  182048. /* These were added in libpng-1.0.2 */
  182049. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182050. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182051. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182052. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182053. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182054. png_byte user_transform_channels; /* channels in user transformed pixels */
  182055. #endif
  182056. #endif
  182057. png_uint_32 mode; /* tells us where we are in the PNG file */
  182058. png_uint_32 flags; /* flags indicating various things to libpng */
  182059. png_uint_32 transformations; /* which transformations to perform */
  182060. z_stream zstream; /* pointer to decompression structure (below) */
  182061. png_bytep zbuf; /* buffer for zlib */
  182062. png_size_t zbuf_size; /* size of zbuf */
  182063. int zlib_level; /* holds zlib compression level */
  182064. int zlib_method; /* holds zlib compression method */
  182065. int zlib_window_bits; /* holds zlib compression window bits */
  182066. int zlib_mem_level; /* holds zlib compression memory level */
  182067. int zlib_strategy; /* holds zlib compression strategy */
  182068. png_uint_32 width; /* width of image in pixels */
  182069. png_uint_32 height; /* height of image in pixels */
  182070. png_uint_32 num_rows; /* number of rows in current pass */
  182071. png_uint_32 usr_width; /* width of row at start of write */
  182072. png_uint_32 rowbytes; /* size of row in bytes */
  182073. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182074. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182075. png_uint_32 row_number; /* current row in interlace pass */
  182076. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182077. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182078. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182079. png_bytep up_row; /* buffer to save "up" row when filtering */
  182080. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182081. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182082. png_row_info row_info; /* used for transformation routines */
  182083. png_uint_32 idat_size; /* current IDAT size for read */
  182084. png_uint_32 crc; /* current chunk CRC value */
  182085. png_colorp palette; /* palette from the input file */
  182086. png_uint_16 num_palette; /* number of color entries in palette */
  182087. png_uint_16 num_trans; /* number of transparency values */
  182088. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182089. png_byte compression; /* file compression type (always 0) */
  182090. png_byte filter; /* file filter type (always 0) */
  182091. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182092. png_byte pass; /* current interlace pass (0 - 6) */
  182093. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182094. png_byte color_type; /* color type of file */
  182095. png_byte bit_depth; /* bit depth of file */
  182096. png_byte usr_bit_depth; /* bit depth of users row */
  182097. png_byte pixel_depth; /* number of bits per pixel */
  182098. png_byte channels; /* number of channels in file */
  182099. png_byte usr_channels; /* channels at start of write */
  182100. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182101. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182102. #ifdef PNG_LEGACY_SUPPORTED
  182103. png_byte filler; /* filler byte for pixel expansion */
  182104. #else
  182105. png_uint_16 filler; /* filler bytes for pixel expansion */
  182106. #endif
  182107. #endif
  182108. #if defined(PNG_bKGD_SUPPORTED)
  182109. png_byte background_gamma_type;
  182110. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182111. float background_gamma;
  182112. # endif
  182113. png_color_16 background; /* background color in screen gamma space */
  182114. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182115. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182116. #endif
  182117. #endif /* PNG_bKGD_SUPPORTED */
  182118. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182119. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182120. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182121. png_uint_32 flush_rows; /* number of rows written since last flush */
  182122. #endif
  182123. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182124. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182125. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182126. float gamma; /* file gamma value */
  182127. float screen_gamma; /* screen gamma value (display_exponent) */
  182128. #endif
  182129. #endif
  182130. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182131. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182132. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182133. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182134. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182135. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182136. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182137. #endif
  182138. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182139. png_color_8 sig_bit; /* significant bits in each available channel */
  182140. #endif
  182141. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182142. png_color_8 shift; /* shift for significant bit tranformation */
  182143. #endif
  182144. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182145. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182146. png_bytep trans; /* transparency values for paletted files */
  182147. png_color_16 trans_values; /* transparency values for non-paletted files */
  182148. #endif
  182149. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182150. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182151. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182152. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182153. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182154. png_progressive_end_ptr end_fn; /* called after image is complete */
  182155. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182156. png_bytep save_buffer; /* buffer for previously read data */
  182157. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182158. png_bytep current_buffer; /* buffer for recently used data */
  182159. png_uint_32 push_length; /* size of current input chunk */
  182160. png_uint_32 skip_length; /* bytes to skip in input data */
  182161. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182162. png_size_t save_buffer_max; /* total size of save_buffer */
  182163. png_size_t buffer_size; /* total amount of available input data */
  182164. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182165. int process_mode; /* what push library is currently doing */
  182166. int cur_palette; /* current push library palette index */
  182167. # if defined(PNG_TEXT_SUPPORTED)
  182168. png_size_t current_text_size; /* current size of text input data */
  182169. png_size_t current_text_left; /* how much text left to read in input */
  182170. png_charp current_text; /* current text chunk buffer */
  182171. png_charp current_text_ptr; /* current location in current_text */
  182172. # endif /* PNG_TEXT_SUPPORTED */
  182173. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182174. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182175. /* for the Borland special 64K segment handler */
  182176. png_bytepp offset_table_ptr;
  182177. png_bytep offset_table;
  182178. png_uint_16 offset_table_number;
  182179. png_uint_16 offset_table_count;
  182180. png_uint_16 offset_table_count_free;
  182181. #endif
  182182. #if defined(PNG_READ_DITHER_SUPPORTED)
  182183. png_bytep palette_lookup; /* lookup table for dithering */
  182184. png_bytep dither_index; /* index translation for palette files */
  182185. #endif
  182186. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182187. png_uint_16p hist; /* histogram */
  182188. #endif
  182189. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182190. png_byte heuristic_method; /* heuristic for row filter selection */
  182191. png_byte num_prev_filters; /* number of weights for previous rows */
  182192. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182193. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182194. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182195. png_uint_16p filter_costs; /* relative filter calculation cost */
  182196. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182197. #endif
  182198. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182199. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182200. #endif
  182201. /* New members added in libpng-1.0.6 */
  182202. #ifdef PNG_FREE_ME_SUPPORTED
  182203. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182204. #endif
  182205. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182206. png_voidp user_chunk_ptr;
  182207. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182208. #endif
  182209. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182210. int num_chunk_list;
  182211. png_bytep chunk_list;
  182212. #endif
  182213. /* New members added in libpng-1.0.3 */
  182214. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182215. png_byte rgb_to_gray_status;
  182216. /* These were changed from png_byte in libpng-1.0.6 */
  182217. png_uint_16 rgb_to_gray_red_coeff;
  182218. png_uint_16 rgb_to_gray_green_coeff;
  182219. png_uint_16 rgb_to_gray_blue_coeff;
  182220. #endif
  182221. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182222. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182223. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182224. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182225. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182226. #ifdef PNG_1_0_X
  182227. png_byte mng_features_permitted;
  182228. #else
  182229. png_uint_32 mng_features_permitted;
  182230. #endif /* PNG_1_0_X */
  182231. #endif
  182232. /* New member added in libpng-1.0.7 */
  182233. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182234. png_fixed_point int_gamma;
  182235. #endif
  182236. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182237. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182238. png_byte filter_type;
  182239. #endif
  182240. #if defined(PNG_1_0_X)
  182241. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182242. png_uint_32 row_buf_size;
  182243. #endif
  182244. /* New members added in libpng-1.2.0 */
  182245. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182246. # if !defined(PNG_1_0_X)
  182247. # if defined(PNG_MMX_CODE_SUPPORTED)
  182248. png_byte mmx_bitdepth_threshold;
  182249. png_uint_32 mmx_rowbytes_threshold;
  182250. # endif
  182251. png_uint_32 asm_flags;
  182252. # endif
  182253. #endif
  182254. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182255. #ifdef PNG_USER_MEM_SUPPORTED
  182256. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182257. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182258. png_free_ptr free_fn; /* function for freeing memory */
  182259. #endif
  182260. /* New member added in libpng-1.0.13 and 1.2.0 */
  182261. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182262. #if defined(PNG_READ_DITHER_SUPPORTED)
  182263. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182264. png_bytep dither_sort; /* working sort array */
  182265. png_bytep index_to_palette; /* where the original index currently is */
  182266. /* in the palette */
  182267. png_bytep palette_to_index; /* which original index points to this */
  182268. /* palette color */
  182269. #endif
  182270. /* New members added in libpng-1.0.16 and 1.2.6 */
  182271. png_byte compression_type;
  182272. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182273. png_uint_32 user_width_max;
  182274. png_uint_32 user_height_max;
  182275. #endif
  182276. /* New member added in libpng-1.0.25 and 1.2.17 */
  182277. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182278. /* storage for unknown chunk that the library doesn't recognize. */
  182279. png_unknown_chunk unknown_chunk;
  182280. #endif
  182281. };
  182282. /* This triggers a compiler error in png.c, if png.c and png.h
  182283. * do not agree upon the version number.
  182284. */
  182285. typedef png_structp version_1_2_21;
  182286. typedef png_struct FAR * FAR * png_structpp;
  182287. /* Here are the function definitions most commonly used. This is not
  182288. * the place to find out how to use libpng. See libpng.txt for the
  182289. * full explanation, see example.c for the summary. This just provides
  182290. * a simple one line description of the use of each function.
  182291. */
  182292. /* Returns the version number of the library */
  182293. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  182294. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  182295. * Handling more than 8 bytes from the beginning of the file is an error.
  182296. */
  182297. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  182298. int num_bytes));
  182299. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  182300. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  182301. * signature, and non-zero otherwise. Having num_to_check == 0 or
  182302. * start > 7 will always fail (ie return non-zero).
  182303. */
  182304. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182305. png_size_t num_to_check));
  182306. /* Simple signature checking function. This is the same as calling
  182307. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182308. */
  182309. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182310. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182311. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182312. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182313. png_error_ptr error_fn, png_error_ptr warn_fn));
  182314. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182315. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182316. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182317. png_error_ptr error_fn, png_error_ptr warn_fn));
  182318. #ifdef PNG_WRITE_SUPPORTED
  182319. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182320. PNGARG((png_structp png_ptr));
  182321. #endif
  182322. #ifdef PNG_WRITE_SUPPORTED
  182323. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182324. PNGARG((png_structp png_ptr, png_uint_32 size));
  182325. #endif
  182326. /* Reset the compression stream */
  182327. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182328. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182329. #ifdef PNG_USER_MEM_SUPPORTED
  182330. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182331. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182332. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182333. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182334. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182335. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182336. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182337. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182338. #endif
  182339. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182340. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182341. png_bytep chunk_name, png_bytep data, png_size_t length));
  182342. /* Write the start of a PNG chunk - length and chunk name. */
  182343. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182344. png_bytep chunk_name, png_uint_32 length));
  182345. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182346. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182347. png_bytep data, png_size_t length));
  182348. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182349. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182350. /* Allocate and initialize the info structure */
  182351. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182352. PNGARG((png_structp png_ptr));
  182353. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182354. /* Initialize the info structure (old interface - DEPRECATED) */
  182355. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182356. #undef png_info_init
  182357. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182358. png_sizeof(png_info));
  182359. #endif
  182360. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182361. png_size_t png_info_struct_size));
  182362. /* Writes all the PNG information before the image. */
  182363. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182364. png_infop info_ptr));
  182365. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182366. png_infop info_ptr));
  182367. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182368. /* read the information before the actual image data. */
  182369. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182370. png_infop info_ptr));
  182371. #endif
  182372. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182373. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182374. PNGARG((png_structp png_ptr, png_timep ptime));
  182375. #endif
  182376. #if !defined(_WIN32_WCE)
  182377. /* "time.h" functions are not supported on WindowsCE */
  182378. #if defined(PNG_WRITE_tIME_SUPPORTED)
  182379. /* convert from a struct tm to png_time */
  182380. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  182381. struct tm FAR * ttime));
  182382. /* convert from time_t to png_time. Uses gmtime() */
  182383. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  182384. time_t ttime));
  182385. #endif /* PNG_WRITE_tIME_SUPPORTED */
  182386. #endif /* _WIN32_WCE */
  182387. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182388. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  182389. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  182390. #if !defined(PNG_1_0_X)
  182391. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  182392. png_ptr));
  182393. #endif
  182394. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  182395. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  182396. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182397. /* Deprecated */
  182398. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  182399. #endif
  182400. #endif
  182401. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  182402. /* Use blue, green, red order for pixels. */
  182403. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  182404. #endif
  182405. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  182406. /* Expand the grayscale to 24-bit RGB if necessary. */
  182407. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  182408. #endif
  182409. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182410. /* Reduce RGB to grayscale. */
  182411. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182412. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  182413. int error_action, double red, double green ));
  182414. #endif
  182415. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  182416. int error_action, png_fixed_point red, png_fixed_point green ));
  182417. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  182418. png_ptr));
  182419. #endif
  182420. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  182421. png_colorp palette));
  182422. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182423. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  182424. #endif
  182425. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  182426. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  182427. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  182428. #endif
  182429. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  182430. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  182431. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  182432. #endif
  182433. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182434. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  182435. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  182436. png_uint_32 filler, int flags));
  182437. /* The values of the PNG_FILLER_ defines should NOT be changed */
  182438. #define PNG_FILLER_BEFORE 0
  182439. #define PNG_FILLER_AFTER 1
  182440. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  182441. #if !defined(PNG_1_0_X)
  182442. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  182443. png_uint_32 filler, int flags));
  182444. #endif
  182445. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  182446. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  182447. /* Swap bytes in 16-bit depth files. */
  182448. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  182449. #endif
  182450. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  182451. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  182452. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  182453. #endif
  182454. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  182455. /* Swap packing order of pixels in bytes. */
  182456. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  182457. #endif
  182458. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182459. /* Converts files to legal bit depths. */
  182460. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  182461. png_color_8p true_bits));
  182462. #endif
  182463. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  182464. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  182465. /* Have the code handle the interlacing. Returns the number of passes. */
  182466. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  182467. #endif
  182468. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  182469. /* Invert monochrome files */
  182470. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  182471. #endif
  182472. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182473. /* Handle alpha and tRNS by replacing with a background color. */
  182474. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182475. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  182476. png_color_16p background_color, int background_gamma_code,
  182477. int need_expand, double background_gamma));
  182478. #endif
  182479. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  182480. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  182481. #define PNG_BACKGROUND_GAMMA_FILE 2
  182482. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  182483. #endif
  182484. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  182485. /* strip the second byte of information from a 16-bit depth file. */
  182486. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  182487. #endif
  182488. #if defined(PNG_READ_DITHER_SUPPORTED)
  182489. /* Turn on dithering, and reduce the palette to the number of colors available. */
  182490. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  182491. png_colorp palette, int num_palette, int maximum_colors,
  182492. png_uint_16p histogram, int full_dither));
  182493. #endif
  182494. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182495. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  182496. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182497. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  182498. double screen_gamma, double default_file_gamma));
  182499. #endif
  182500. #endif
  182501. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182502. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182503. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182504. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  182505. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  182506. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  182507. int empty_plte_permitted));
  182508. #endif
  182509. #endif
  182510. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182511. /* Set how many lines between output flushes - 0 for no flushing */
  182512. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  182513. /* Flush the current PNG output buffer */
  182514. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  182515. #endif
  182516. /* optional update palette with requested transformations */
  182517. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  182518. /* optional call to update the users info structure */
  182519. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  182520. png_infop info_ptr));
  182521. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182522. /* read one or more rows of image data. */
  182523. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  182524. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  182525. #endif
  182526. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182527. /* read a row of data. */
  182528. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  182529. png_bytep row,
  182530. png_bytep display_row));
  182531. #endif
  182532. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182533. /* read the whole image into memory at once. */
  182534. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  182535. png_bytepp image));
  182536. #endif
  182537. /* write a row of image data */
  182538. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  182539. png_bytep row));
  182540. /* write a few rows of image data */
  182541. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  182542. png_bytepp row, png_uint_32 num_rows));
  182543. /* write the image data */
  182544. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  182545. png_bytepp image));
  182546. /* writes the end of the PNG file. */
  182547. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  182548. png_infop info_ptr));
  182549. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182550. /* read the end of the PNG file. */
  182551. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  182552. png_infop info_ptr));
  182553. #endif
  182554. /* free any memory associated with the png_info_struct */
  182555. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  182556. png_infopp info_ptr_ptr));
  182557. /* free any memory associated with the png_struct and the png_info_structs */
  182558. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  182559. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  182560. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  182561. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  182562. png_infop end_info_ptr));
  182563. /* free any memory associated with the png_struct and the png_info_structs */
  182564. extern PNG_EXPORT(void,png_destroy_write_struct)
  182565. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  182566. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  182567. extern void png_write_destroy PNGARG((png_structp png_ptr));
  182568. /* set the libpng method of handling chunk CRC errors */
  182569. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  182570. int crit_action, int ancil_action));
  182571. /* Values for png_set_crc_action() to say how to handle CRC errors in
  182572. * ancillary and critical chunks, and whether to use the data contained
  182573. * therein. Note that it is impossible to "discard" data in a critical
  182574. * chunk. For versions prior to 0.90, the action was always error/quit,
  182575. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  182576. * chunks is warn/discard. These values should NOT be changed.
  182577. *
  182578. * value action:critical action:ancillary
  182579. */
  182580. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  182581. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  182582. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  182583. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  182584. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  182585. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  182586. /* These functions give the user control over the scan-line filtering in
  182587. * libpng and the compression methods used by zlib. These functions are
  182588. * mainly useful for testing, as the defaults should work with most users.
  182589. * Those users who are tight on memory or want faster performance at the
  182590. * expense of compression can modify them. See the compression library
  182591. * header file (zlib.h) for an explination of the compression functions.
  182592. */
  182593. /* set the filtering method(s) used by libpng. Currently, the only valid
  182594. * value for "method" is 0.
  182595. */
  182596. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  182597. int filters));
  182598. /* Flags for png_set_filter() to say which filters to use. The flags
  182599. * are chosen so that they don't conflict with real filter types
  182600. * below, in case they are supplied instead of the #defined constants.
  182601. * These values should NOT be changed.
  182602. */
  182603. #define PNG_NO_FILTERS 0x00
  182604. #define PNG_FILTER_NONE 0x08
  182605. #define PNG_FILTER_SUB 0x10
  182606. #define PNG_FILTER_UP 0x20
  182607. #define PNG_FILTER_AVG 0x40
  182608. #define PNG_FILTER_PAETH 0x80
  182609. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  182610. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  182611. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  182612. * These defines should NOT be changed.
  182613. */
  182614. #define PNG_FILTER_VALUE_NONE 0
  182615. #define PNG_FILTER_VALUE_SUB 1
  182616. #define PNG_FILTER_VALUE_UP 2
  182617. #define PNG_FILTER_VALUE_AVG 3
  182618. #define PNG_FILTER_VALUE_PAETH 4
  182619. #define PNG_FILTER_VALUE_LAST 5
  182620. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  182621. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  182622. * defines, either the default (minimum-sum-of-absolute-differences), or
  182623. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  182624. *
  182625. * Weights are factors >= 1.0, indicating how important it is to keep the
  182626. * filter type consistent between rows. Larger numbers mean the current
  182627. * filter is that many times as likely to be the same as the "num_weights"
  182628. * previous filters. This is cumulative for each previous row with a weight.
  182629. * There needs to be "num_weights" values in "filter_weights", or it can be
  182630. * NULL if the weights aren't being specified. Weights have no influence on
  182631. * the selection of the first row filter. Well chosen weights can (in theory)
  182632. * improve the compression for a given image.
  182633. *
  182634. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  182635. * filter type. Higher costs indicate more decoding expense, and are
  182636. * therefore less likely to be selected over a filter with lower computational
  182637. * costs. There needs to be a value in "filter_costs" for each valid filter
  182638. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  182639. * setting the costs. Costs try to improve the speed of decompression without
  182640. * unduly increasing the compressed image size.
  182641. *
  182642. * A negative weight or cost indicates the default value is to be used, and
  182643. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  182644. * The default values for both weights and costs are currently 1.0, but may
  182645. * change if good general weighting/cost heuristics can be found. If both
  182646. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  182647. * to the UNWEIGHTED method, but with added encoding time/computation.
  182648. */
  182649. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182650. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  182651. int heuristic_method, int num_weights, png_doublep filter_weights,
  182652. png_doublep filter_costs));
  182653. #endif
  182654. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  182655. /* Heuristic used for row filter selection. These defines should NOT be
  182656. * changed.
  182657. */
  182658. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  182659. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  182660. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  182661. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  182662. /* Set the library compression level. Currently, valid values range from
  182663. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  182664. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  182665. * shown that zlib compression levels 3-6 usually perform as well as level 9
  182666. * for PNG images, and do considerably fewer caclulations. In the future,
  182667. * these values may not correspond directly to the zlib compression levels.
  182668. */
  182669. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  182670. int level));
  182671. extern PNG_EXPORT(void,png_set_compression_mem_level)
  182672. PNGARG((png_structp png_ptr, int mem_level));
  182673. extern PNG_EXPORT(void,png_set_compression_strategy)
  182674. PNGARG((png_structp png_ptr, int strategy));
  182675. extern PNG_EXPORT(void,png_set_compression_window_bits)
  182676. PNGARG((png_structp png_ptr, int window_bits));
  182677. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  182678. int method));
  182679. /* These next functions are called for input/output, memory, and error
  182680. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  182681. * and call standard C I/O routines such as fread(), fwrite(), and
  182682. * fprintf(). These functions can be made to use other I/O routines
  182683. * at run time for those applications that need to handle I/O in a
  182684. * different manner by calling png_set_???_fn(). See libpng.txt for
  182685. * more information.
  182686. */
  182687. #if !defined(PNG_NO_STDIO)
  182688. /* Initialize the input/output for the PNG file to the default functions. */
  182689. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  182690. #endif
  182691. /* Replace the (error and abort), and warning functions with user
  182692. * supplied functions. If no messages are to be printed you must still
  182693. * write and use replacement functions. The replacement error_fn should
  182694. * still do a longjmp to the last setjmp location if you are using this
  182695. * method of error handling. If error_fn or warning_fn is NULL, the
  182696. * default function will be used.
  182697. */
  182698. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  182699. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  182700. /* Return the user pointer associated with the error functions */
  182701. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  182702. /* Replace the default data output functions with a user supplied one(s).
  182703. * If buffered output is not used, then output_flush_fn can be set to NULL.
  182704. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  182705. * output_flush_fn will be ignored (and thus can be NULL).
  182706. */
  182707. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  182708. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  182709. /* Replace the default data input function with a user supplied one. */
  182710. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  182711. png_voidp io_ptr, png_rw_ptr read_data_fn));
  182712. /* Return the user pointer associated with the I/O functions */
  182713. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  182714. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  182715. png_read_status_ptr read_row_fn));
  182716. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  182717. png_write_status_ptr write_row_fn));
  182718. #ifdef PNG_USER_MEM_SUPPORTED
  182719. /* Replace the default memory allocation functions with user supplied one(s). */
  182720. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  182721. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182722. /* Return the user pointer associated with the memory functions */
  182723. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  182724. #endif
  182725. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182726. defined(PNG_LEGACY_SUPPORTED)
  182727. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  182728. png_ptr, png_user_transform_ptr read_user_transform_fn));
  182729. #endif
  182730. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182731. defined(PNG_LEGACY_SUPPORTED)
  182732. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  182733. png_ptr, png_user_transform_ptr write_user_transform_fn));
  182734. #endif
  182735. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182736. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182737. defined(PNG_LEGACY_SUPPORTED)
  182738. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  182739. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  182740. int user_transform_channels));
  182741. /* Return the user pointer associated with the user transform functions */
  182742. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  182743. PNGARG((png_structp png_ptr));
  182744. #endif
  182745. #ifdef PNG_USER_CHUNKS_SUPPORTED
  182746. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  182747. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  182748. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  182749. png_ptr));
  182750. #endif
  182751. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182752. /* Sets the function callbacks for the push reader, and a pointer to a
  182753. * user-defined structure available to the callback functions.
  182754. */
  182755. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  182756. png_voidp progressive_ptr,
  182757. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  182758. png_progressive_end_ptr end_fn));
  182759. /* returns the user pointer associated with the push read functions */
  182760. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  182761. PNGARG((png_structp png_ptr));
  182762. /* function to be called when data becomes available */
  182763. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  182764. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  182765. /* function that combines rows. Not very much different than the
  182766. * png_combine_row() call. Is this even used?????
  182767. */
  182768. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  182769. png_bytep old_row, png_bytep new_row));
  182770. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182771. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  182772. png_uint_32 size));
  182773. #if defined(PNG_1_0_X)
  182774. # define png_malloc_warn png_malloc
  182775. #else
  182776. /* Added at libpng version 1.2.4 */
  182777. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  182778. png_uint_32 size));
  182779. #endif
  182780. /* frees a pointer allocated by png_malloc() */
  182781. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  182782. #if defined(PNG_1_0_X)
  182783. /* Function to allocate memory for zlib. */
  182784. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  182785. uInt size));
  182786. /* Function to free memory for zlib */
  182787. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  182788. #endif
  182789. /* Free data that was allocated internally */
  182790. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  182791. png_infop info_ptr, png_uint_32 free_me, int num));
  182792. #ifdef PNG_FREE_ME_SUPPORTED
  182793. /* Reassign responsibility for freeing existing data, whether allocated
  182794. * by libpng or by the application */
  182795. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  182796. png_infop info_ptr, int freer, png_uint_32 mask));
  182797. #endif
  182798. /* assignments for png_data_freer */
  182799. #define PNG_DESTROY_WILL_FREE_DATA 1
  182800. #define PNG_SET_WILL_FREE_DATA 1
  182801. #define PNG_USER_WILL_FREE_DATA 2
  182802. /* Flags for png_ptr->free_me and info_ptr->free_me */
  182803. #define PNG_FREE_HIST 0x0008
  182804. #define PNG_FREE_ICCP 0x0010
  182805. #define PNG_FREE_SPLT 0x0020
  182806. #define PNG_FREE_ROWS 0x0040
  182807. #define PNG_FREE_PCAL 0x0080
  182808. #define PNG_FREE_SCAL 0x0100
  182809. #define PNG_FREE_UNKN 0x0200
  182810. #define PNG_FREE_LIST 0x0400
  182811. #define PNG_FREE_PLTE 0x1000
  182812. #define PNG_FREE_TRNS 0x2000
  182813. #define PNG_FREE_TEXT 0x4000
  182814. #define PNG_FREE_ALL 0x7fff
  182815. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  182816. #ifdef PNG_USER_MEM_SUPPORTED
  182817. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  182818. png_uint_32 size));
  182819. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  182820. png_voidp ptr));
  182821. #endif
  182822. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  182823. png_voidp s1, png_voidp s2, png_uint_32 size));
  182824. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  182825. png_voidp s1, int value, png_uint_32 size));
  182826. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  182827. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  182828. int check));
  182829. #endif /* USE_FAR_KEYWORD */
  182830. #ifndef PNG_NO_ERROR_TEXT
  182831. /* Fatal error in PNG image of libpng - can't continue */
  182832. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  182833. png_const_charp error_message));
  182834. /* The same, but the chunk name is prepended to the error string. */
  182835. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  182836. png_const_charp error_message));
  182837. #else
  182838. /* Fatal error in PNG image of libpng - can't continue */
  182839. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  182840. #endif
  182841. #ifndef PNG_NO_WARNINGS
  182842. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  182843. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  182844. png_const_charp warning_message));
  182845. #ifdef PNG_READ_SUPPORTED
  182846. /* Non-fatal error in libpng, chunk name is prepended to message. */
  182847. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  182848. png_const_charp warning_message));
  182849. #endif /* PNG_READ_SUPPORTED */
  182850. #endif /* PNG_NO_WARNINGS */
  182851. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  182852. * Similarly, the png_get_<chunk> calls are used to read values from the
  182853. * png_info_struct, either storing the parameters in the passed variables, or
  182854. * setting pointers into the png_info_struct where the data is stored. The
  182855. * png_get_<chunk> functions return a non-zero value if the data was available
  182856. * in info_ptr, or return zero and do not change any of the parameters if the
  182857. * data was not available.
  182858. *
  182859. * These functions should be used instead of directly accessing png_info
  182860. * to avoid problems with future changes in the size and internal layout of
  182861. * png_info_struct.
  182862. */
  182863. /* Returns "flag" if chunk data is valid in info_ptr. */
  182864. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  182865. png_infop info_ptr, png_uint_32 flag));
  182866. /* Returns number of bytes needed to hold a transformed row. */
  182867. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  182868. png_infop info_ptr));
  182869. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182870. /* Returns row_pointers, which is an array of pointers to scanlines that was
  182871. returned from png_read_png(). */
  182872. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  182873. png_infop info_ptr));
  182874. /* Set row_pointers, which is an array of pointers to scanlines for use
  182875. by png_write_png(). */
  182876. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  182877. png_infop info_ptr, png_bytepp row_pointers));
  182878. #endif
  182879. /* Returns number of color channels in image. */
  182880. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  182881. png_infop info_ptr));
  182882. #ifdef PNG_EASY_ACCESS_SUPPORTED
  182883. /* Returns image width in pixels. */
  182884. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  182885. png_ptr, png_infop info_ptr));
  182886. /* Returns image height in pixels. */
  182887. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  182888. png_ptr, png_infop info_ptr));
  182889. /* Returns image bit_depth. */
  182890. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  182891. png_ptr, png_infop info_ptr));
  182892. /* Returns image color_type. */
  182893. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  182894. png_ptr, png_infop info_ptr));
  182895. /* Returns image filter_type. */
  182896. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  182897. png_ptr, png_infop info_ptr));
  182898. /* Returns image interlace_type. */
  182899. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  182900. png_ptr, png_infop info_ptr));
  182901. /* Returns image compression_type. */
  182902. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  182903. png_ptr, png_infop info_ptr));
  182904. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  182905. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  182906. png_ptr, png_infop info_ptr));
  182907. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  182908. png_ptr, png_infop info_ptr));
  182909. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  182910. png_ptr, png_infop info_ptr));
  182911. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  182912. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182913. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  182914. png_ptr, png_infop info_ptr));
  182915. #endif
  182916. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  182917. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  182918. png_ptr, png_infop info_ptr));
  182919. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  182920. png_ptr, png_infop info_ptr));
  182921. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  182922. png_ptr, png_infop info_ptr));
  182923. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  182924. png_ptr, png_infop info_ptr));
  182925. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  182926. /* Returns pointer to signature string read from PNG header */
  182927. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  182928. png_infop info_ptr));
  182929. #if defined(PNG_bKGD_SUPPORTED)
  182930. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  182931. png_infop info_ptr, png_color_16p *background));
  182932. #endif
  182933. #if defined(PNG_bKGD_SUPPORTED)
  182934. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  182935. png_infop info_ptr, png_color_16p background));
  182936. #endif
  182937. #if defined(PNG_cHRM_SUPPORTED)
  182938. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182939. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  182940. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  182941. double *red_y, double *green_x, double *green_y, double *blue_x,
  182942. double *blue_y));
  182943. #endif
  182944. #ifdef PNG_FIXED_POINT_SUPPORTED
  182945. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  182946. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  182947. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  182948. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  182949. *int_blue_x, png_fixed_point *int_blue_y));
  182950. #endif
  182951. #endif
  182952. #if defined(PNG_cHRM_SUPPORTED)
  182953. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182954. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  182955. png_infop info_ptr, double white_x, double white_y, double red_x,
  182956. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  182957. #endif
  182958. #ifdef PNG_FIXED_POINT_SUPPORTED
  182959. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  182960. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  182961. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  182962. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  182963. png_fixed_point int_blue_y));
  182964. #endif
  182965. #endif
  182966. #if defined(PNG_gAMA_SUPPORTED)
  182967. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182968. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  182969. png_infop info_ptr, double *file_gamma));
  182970. #endif
  182971. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  182972. png_infop info_ptr, png_fixed_point *int_file_gamma));
  182973. #endif
  182974. #if defined(PNG_gAMA_SUPPORTED)
  182975. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182976. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  182977. png_infop info_ptr, double file_gamma));
  182978. #endif
  182979. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  182980. png_infop info_ptr, png_fixed_point int_file_gamma));
  182981. #endif
  182982. #if defined(PNG_hIST_SUPPORTED)
  182983. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  182984. png_infop info_ptr, png_uint_16p *hist));
  182985. #endif
  182986. #if defined(PNG_hIST_SUPPORTED)
  182987. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  182988. png_infop info_ptr, png_uint_16p hist));
  182989. #endif
  182990. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  182991. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  182992. int *bit_depth, int *color_type, int *interlace_method,
  182993. int *compression_method, int *filter_method));
  182994. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  182995. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  182996. int color_type, int interlace_method, int compression_method,
  182997. int filter_method));
  182998. #if defined(PNG_oFFs_SUPPORTED)
  182999. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183000. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183001. int *unit_type));
  183002. #endif
  183003. #if defined(PNG_oFFs_SUPPORTED)
  183004. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183005. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183006. int unit_type));
  183007. #endif
  183008. #if defined(PNG_pCAL_SUPPORTED)
  183009. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183010. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183011. int *type, int *nparams, png_charp *units, png_charpp *params));
  183012. #endif
  183013. #if defined(PNG_pCAL_SUPPORTED)
  183014. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183015. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183016. int type, int nparams, png_charp units, png_charpp params));
  183017. #endif
  183018. #if defined(PNG_pHYs_SUPPORTED)
  183019. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183020. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183021. #endif
  183022. #if defined(PNG_pHYs_SUPPORTED)
  183023. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183024. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183025. #endif
  183026. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183027. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183028. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183029. png_infop info_ptr, png_colorp palette, int num_palette));
  183030. #if defined(PNG_sBIT_SUPPORTED)
  183031. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183032. png_infop info_ptr, png_color_8p *sig_bit));
  183033. #endif
  183034. #if defined(PNG_sBIT_SUPPORTED)
  183035. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183036. png_infop info_ptr, png_color_8p sig_bit));
  183037. #endif
  183038. #if defined(PNG_sRGB_SUPPORTED)
  183039. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183040. png_infop info_ptr, int *intent));
  183041. #endif
  183042. #if defined(PNG_sRGB_SUPPORTED)
  183043. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183044. png_infop info_ptr, int intent));
  183045. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183046. png_infop info_ptr, int intent));
  183047. #endif
  183048. #if defined(PNG_iCCP_SUPPORTED)
  183049. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183050. png_infop info_ptr, png_charpp name, int *compression_type,
  183051. png_charpp profile, png_uint_32 *proflen));
  183052. /* Note to maintainer: profile should be png_bytepp */
  183053. #endif
  183054. #if defined(PNG_iCCP_SUPPORTED)
  183055. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183056. png_infop info_ptr, png_charp name, int compression_type,
  183057. png_charp profile, png_uint_32 proflen));
  183058. /* Note to maintainer: profile should be png_bytep */
  183059. #endif
  183060. #if defined(PNG_sPLT_SUPPORTED)
  183061. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183062. png_infop info_ptr, png_sPLT_tpp entries));
  183063. #endif
  183064. #if defined(PNG_sPLT_SUPPORTED)
  183065. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183066. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183067. #endif
  183068. #if defined(PNG_TEXT_SUPPORTED)
  183069. /* png_get_text also returns the number of text chunks in *num_text */
  183070. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183071. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183072. #endif
  183073. /*
  183074. * Note while png_set_text() will accept a structure whose text,
  183075. * language, and translated keywords are NULL pointers, the structure
  183076. * returned by png_get_text will always contain regular
  183077. * zero-terminated C strings. They might be empty strings but
  183078. * they will never be NULL pointers.
  183079. */
  183080. #if defined(PNG_TEXT_SUPPORTED)
  183081. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183082. png_infop info_ptr, png_textp text_ptr, int num_text));
  183083. #endif
  183084. #if defined(PNG_tIME_SUPPORTED)
  183085. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183086. png_infop info_ptr, png_timep *mod_time));
  183087. #endif
  183088. #if defined(PNG_tIME_SUPPORTED)
  183089. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183090. png_infop info_ptr, png_timep mod_time));
  183091. #endif
  183092. #if defined(PNG_tRNS_SUPPORTED)
  183093. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183094. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183095. png_color_16p *trans_values));
  183096. #endif
  183097. #if defined(PNG_tRNS_SUPPORTED)
  183098. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183099. png_infop info_ptr, png_bytep trans, int num_trans,
  183100. png_color_16p trans_values));
  183101. #endif
  183102. #if defined(PNG_tRNS_SUPPORTED)
  183103. #endif
  183104. #if defined(PNG_sCAL_SUPPORTED)
  183105. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183106. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183107. png_infop info_ptr, int *unit, double *width, double *height));
  183108. #else
  183109. #ifdef PNG_FIXED_POINT_SUPPORTED
  183110. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183111. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183112. #endif
  183113. #endif
  183114. #endif /* PNG_sCAL_SUPPORTED */
  183115. #if defined(PNG_sCAL_SUPPORTED)
  183116. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183117. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183118. png_infop info_ptr, int unit, double width, double height));
  183119. #else
  183120. #ifdef PNG_FIXED_POINT_SUPPORTED
  183121. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183122. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183123. #endif
  183124. #endif
  183125. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183126. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183127. /* provide a list of chunks and how they are to be handled, if the built-in
  183128. handling or default unknown chunk handling is not desired. Any chunks not
  183129. listed will be handled in the default manner. The IHDR and IEND chunks
  183130. must not be listed.
  183131. keep = 0: follow default behaviour
  183132. = 1: do not keep
  183133. = 2: keep only if safe-to-copy
  183134. = 3: keep even if unsafe-to-copy
  183135. */
  183136. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183137. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183138. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183139. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183140. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183141. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183142. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183143. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183144. #endif
  183145. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183146. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183147. chunk_name));
  183148. #endif
  183149. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183150. If you need to turn it off for a chunk that your application has freed,
  183151. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183152. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183153. png_infop info_ptr, int mask));
  183154. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183155. /* The "params" pointer is currently not used and is for future expansion. */
  183156. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183157. png_infop info_ptr,
  183158. int transforms,
  183159. png_voidp params));
  183160. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183161. png_infop info_ptr,
  183162. int transforms,
  183163. png_voidp params));
  183164. #endif
  183165. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183166. * numbers for PNG_DEBUG mean more debugging information. This has
  183167. * only been added since version 0.95 so it is not implemented throughout
  183168. * libpng yet, but more support will be added as needed.
  183169. */
  183170. #ifdef PNG_DEBUG
  183171. #if (PNG_DEBUG > 0)
  183172. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183173. #include <crtdbg.h>
  183174. #if (PNG_DEBUG > 1)
  183175. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183176. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183177. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183178. #endif
  183179. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183180. #ifndef PNG_DEBUG_FILE
  183181. #define PNG_DEBUG_FILE stderr
  183182. #endif /* PNG_DEBUG_FILE */
  183183. #if (PNG_DEBUG > 1)
  183184. #define png_debug(l,m) \
  183185. { \
  183186. int num_tabs=l; \
  183187. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183188. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183189. }
  183190. #define png_debug1(l,m,p1) \
  183191. { \
  183192. int num_tabs=l; \
  183193. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183194. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183195. }
  183196. #define png_debug2(l,m,p1,p2) \
  183197. { \
  183198. int num_tabs=l; \
  183199. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183200. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183201. }
  183202. #endif /* (PNG_DEBUG > 1) */
  183203. #endif /* _MSC_VER */
  183204. #endif /* (PNG_DEBUG > 0) */
  183205. #endif /* PNG_DEBUG */
  183206. #ifndef png_debug
  183207. #define png_debug(l, m)
  183208. #endif
  183209. #ifndef png_debug1
  183210. #define png_debug1(l, m, p1)
  183211. #endif
  183212. #ifndef png_debug2
  183213. #define png_debug2(l, m, p1, p2)
  183214. #endif
  183215. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183216. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183217. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183218. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183219. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183220. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183221. png_ptr, png_uint_32 mng_features_permitted));
  183222. #endif
  183223. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183224. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183225. #define PNG_HANDLE_CHUNK_NEVER 1
  183226. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183227. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183228. /* Added to version 1.2.0 */
  183229. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183230. #if defined(PNG_MMX_CODE_SUPPORTED)
  183231. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183232. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183233. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183234. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183235. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183236. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183237. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183238. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183239. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183240. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183241. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183242. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183243. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183244. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183245. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183246. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183247. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183248. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183249. | PNG_MMX_READ_FLAGS \
  183250. | PNG_MMX_WRITE_FLAGS )
  183251. #define PNG_SELECT_READ 1
  183252. #define PNG_SELECT_WRITE 2
  183253. #endif /* PNG_MMX_CODE_SUPPORTED */
  183254. #if !defined(PNG_1_0_X)
  183255. /* pngget.c */
  183256. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183257. PNGARG((int flag_select, int *compilerID));
  183258. /* pngget.c */
  183259. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183260. PNGARG((int flag_select));
  183261. /* pngget.c */
  183262. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183263. PNGARG((png_structp png_ptr));
  183264. /* pngget.c */
  183265. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  183266. PNGARG((png_structp png_ptr));
  183267. /* pngget.c */
  183268. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  183269. PNGARG((png_structp png_ptr));
  183270. /* pngset.c */
  183271. extern PNG_EXPORT(void,png_set_asm_flags)
  183272. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  183273. /* pngset.c */
  183274. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  183275. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  183276. png_uint_32 mmx_rowbytes_threshold));
  183277. #endif /* PNG_1_0_X */
  183278. #if !defined(PNG_1_0_X)
  183279. /* png.c, pnggccrd.c, or pngvcrd.c */
  183280. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  183281. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  183282. /* Strip the prepended error numbers ("#nnn ") from error and warning
  183283. * messages before passing them to the error or warning handler. */
  183284. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183285. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  183286. png_ptr, png_uint_32 strip_mode));
  183287. #endif
  183288. #endif /* PNG_1_0_X */
  183289. /* Added at libpng-1.2.6 */
  183290. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183291. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  183292. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  183293. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  183294. png_ptr));
  183295. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  183296. png_ptr));
  183297. #endif
  183298. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  183299. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  183300. /* With these routines we avoid an integer divide, which will be slower on
  183301. * most machines. However, it does take more operations than the corresponding
  183302. * divide method, so it may be slower on a few RISC systems. There are two
  183303. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  183304. *
  183305. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183306. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183307. * standard method.
  183308. *
  183309. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183310. */
  183311. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183312. # define png_composite(composite, fg, alpha, bg) \
  183313. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183314. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183315. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183316. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183317. # define png_composite_16(composite, fg, alpha, bg) \
  183318. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183319. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183320. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183321. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183322. #else /* standard method using integer division */
  183323. # define png_composite(composite, fg, alpha, bg) \
  183324. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183325. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183326. (png_uint_16)127) / 255)
  183327. # define png_composite_16(composite, fg, alpha, bg) \
  183328. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183329. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183330. (png_uint_32)32767) / (png_uint_32)65535L)
  183331. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183332. /* Inline macros to do direct reads of bytes from the input buffer. These
  183333. * require that you are using an architecture that uses PNG byte ordering
  183334. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183335. * in big-endian mode and 680x0 are the only ones that will support this.
  183336. * The x86 line of processors definitely do not. The png_get_int_32()
  183337. * routine also assumes we are using two's complement format for negative
  183338. * values, which is almost certainly true.
  183339. */
  183340. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183341. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183342. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183343. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183344. #else
  183345. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183346. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183347. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183348. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183349. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183350. PNGARG((png_structp png_ptr, png_bytep buf));
  183351. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183352. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183353. */
  183354. extern PNG_EXPORT(void,png_save_uint_32)
  183355. PNGARG((png_bytep buf, png_uint_32 i));
  183356. extern PNG_EXPORT(void,png_save_int_32)
  183357. PNGARG((png_bytep buf, png_int_32 i));
  183358. /* Place a 16-bit number into a buffer in PNG byte order.
  183359. * The parameter is declared unsigned int, not png_uint_16,
  183360. * just to avoid potential problems on pre-ANSI C compilers.
  183361. */
  183362. extern PNG_EXPORT(void,png_save_uint_16)
  183363. PNGARG((png_bytep buf, unsigned int i));
  183364. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183365. /* ************************************************************************* */
  183366. /* These next functions are used internally in the code. They generally
  183367. * shouldn't be used unless you are writing code to add or replace some
  183368. * functionality in libpng. More information about most functions can
  183369. * be found in the files where the functions are located.
  183370. */
  183371. /* Various modes of operation, that are visible to applications because
  183372. * they are used for unknown chunk location.
  183373. */
  183374. #define PNG_HAVE_IHDR 0x01
  183375. #define PNG_HAVE_PLTE 0x02
  183376. #define PNG_HAVE_IDAT 0x04
  183377. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183378. #define PNG_HAVE_IEND 0x10
  183379. #if defined(PNG_INTERNAL)
  183380. /* More modes of operation. Note that after an init, mode is set to
  183381. * zero automatically when the structure is created.
  183382. */
  183383. #define PNG_HAVE_gAMA 0x20
  183384. #define PNG_HAVE_cHRM 0x40
  183385. #define PNG_HAVE_sRGB 0x80
  183386. #define PNG_HAVE_CHUNK_HEADER 0x100
  183387. #define PNG_WROTE_tIME 0x200
  183388. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  183389. #define PNG_BACKGROUND_IS_GRAY 0x800
  183390. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  183391. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  183392. /* flags for the transformations the PNG library does on the image data */
  183393. #define PNG_BGR 0x0001
  183394. #define PNG_INTERLACE 0x0002
  183395. #define PNG_PACK 0x0004
  183396. #define PNG_SHIFT 0x0008
  183397. #define PNG_SWAP_BYTES 0x0010
  183398. #define PNG_INVERT_MONO 0x0020
  183399. #define PNG_DITHER 0x0040
  183400. #define PNG_BACKGROUND 0x0080
  183401. #define PNG_BACKGROUND_EXPAND 0x0100
  183402. /* 0x0200 unused */
  183403. #define PNG_16_TO_8 0x0400
  183404. #define PNG_RGBA 0x0800
  183405. #define PNG_EXPAND 0x1000
  183406. #define PNG_GAMMA 0x2000
  183407. #define PNG_GRAY_TO_RGB 0x4000
  183408. #define PNG_FILLER 0x8000L
  183409. #define PNG_PACKSWAP 0x10000L
  183410. #define PNG_SWAP_ALPHA 0x20000L
  183411. #define PNG_STRIP_ALPHA 0x40000L
  183412. #define PNG_INVERT_ALPHA 0x80000L
  183413. #define PNG_USER_TRANSFORM 0x100000L
  183414. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  183415. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  183416. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  183417. /* 0x800000L Unused */
  183418. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  183419. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  183420. /* 0x4000000L unused */
  183421. /* 0x8000000L unused */
  183422. /* 0x10000000L unused */
  183423. /* 0x20000000L unused */
  183424. /* 0x40000000L unused */
  183425. /* flags for png_create_struct */
  183426. #define PNG_STRUCT_PNG 0x0001
  183427. #define PNG_STRUCT_INFO 0x0002
  183428. /* Scaling factor for filter heuristic weighting calculations */
  183429. #define PNG_WEIGHT_SHIFT 8
  183430. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  183431. #define PNG_COST_SHIFT 3
  183432. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  183433. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  183434. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  183435. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  183436. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  183437. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  183438. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  183439. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  183440. #define PNG_FLAG_ROW_INIT 0x0040
  183441. #define PNG_FLAG_FILLER_AFTER 0x0080
  183442. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  183443. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  183444. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  183445. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  183446. #define PNG_FLAG_FREE_PLTE 0x1000
  183447. #define PNG_FLAG_FREE_TRNS 0x2000
  183448. #define PNG_FLAG_FREE_HIST 0x4000
  183449. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  183450. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  183451. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  183452. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  183453. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  183454. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  183455. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  183456. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  183457. /* 0x800000L unused */
  183458. /* 0x1000000L unused */
  183459. /* 0x2000000L unused */
  183460. /* 0x4000000L unused */
  183461. /* 0x8000000L unused */
  183462. /* 0x10000000L unused */
  183463. /* 0x20000000L unused */
  183464. /* 0x40000000L unused */
  183465. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  183466. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  183467. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  183468. PNG_FLAG_CRC_CRITICAL_IGNORE)
  183469. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  183470. PNG_FLAG_CRC_CRITICAL_MASK)
  183471. /* save typing and make code easier to understand */
  183472. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  183473. abs((int)((c1).green) - (int)((c2).green)) + \
  183474. abs((int)((c1).blue) - (int)((c2).blue)))
  183475. /* Added to libpng-1.2.6 JB */
  183476. #define PNG_ROWBYTES(pixel_bits, width) \
  183477. ((pixel_bits) >= 8 ? \
  183478. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  183479. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  183480. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  183481. ideal-delta..ideal+delta. Each argument is evaluated twice.
  183482. "ideal" and "delta" should be constants, normally simple
  183483. integers, "value" a variable. Added to libpng-1.2.6 JB */
  183484. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  183485. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  183486. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  183487. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  183488. /* place to hold the signature string for a PNG file. */
  183489. #ifdef PNG_USE_GLOBAL_ARRAYS
  183490. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  183491. #else
  183492. #endif
  183493. #endif /* PNG_NO_EXTERN */
  183494. /* Constant strings for known chunk types. If you need to add a chunk,
  183495. * define the name here, and add an invocation of the macro in png.c and
  183496. * wherever it's needed.
  183497. */
  183498. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  183499. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  183500. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  183501. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  183502. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  183503. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  183504. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  183505. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  183506. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  183507. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  183508. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  183509. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  183510. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  183511. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  183512. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  183513. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  183514. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  183515. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  183516. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  183517. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  183518. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  183519. #ifdef PNG_USE_GLOBAL_ARRAYS
  183520. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  183521. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  183522. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  183523. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  183524. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  183525. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  183526. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  183527. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  183528. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  183529. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  183530. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  183531. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  183532. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  183533. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  183534. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  183535. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  183536. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  183537. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  183538. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  183539. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  183540. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  183541. #endif /* PNG_USE_GLOBAL_ARRAYS */
  183542. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183543. /* Initialize png_ptr struct for reading, and allocate any other memory.
  183544. * (old interface - DEPRECATED - use png_create_read_struct instead).
  183545. */
  183546. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  183547. #undef png_read_init
  183548. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  183549. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183550. #endif
  183551. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  183552. png_const_charp user_png_ver, png_size_t png_struct_size));
  183553. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183554. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  183555. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183556. png_info_size));
  183557. #endif
  183558. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183559. /* Initialize png_ptr struct for writing, and allocate any other memory.
  183560. * (old interface - DEPRECATED - use png_create_write_struct instead).
  183561. */
  183562. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  183563. #undef png_write_init
  183564. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  183565. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183566. #endif
  183567. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  183568. png_const_charp user_png_ver, png_size_t png_struct_size));
  183569. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  183570. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183571. png_info_size));
  183572. /* Allocate memory for an internal libpng struct */
  183573. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  183574. /* Free memory from internal libpng struct */
  183575. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  183576. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  183577. malloc_fn, png_voidp mem_ptr));
  183578. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  183579. png_free_ptr free_fn, png_voidp mem_ptr));
  183580. /* Free any memory that info_ptr points to and reset struct. */
  183581. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  183582. png_infop info_ptr));
  183583. #ifndef PNG_1_0_X
  183584. /* Function to allocate memory for zlib. */
  183585. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  183586. /* Function to free memory for zlib */
  183587. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  183588. #ifdef PNG_SIZE_T
  183589. /* Function to convert a sizeof an item to png_sizeof item */
  183590. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  183591. #endif
  183592. /* Next four functions are used internally as callbacks. PNGAPI is required
  183593. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  183594. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  183595. png_bytep data, png_size_t length));
  183596. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183597. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  183598. png_bytep buffer, png_size_t length));
  183599. #endif
  183600. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  183601. png_bytep data, png_size_t length));
  183602. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183603. #if !defined(PNG_NO_STDIO)
  183604. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  183605. #endif
  183606. #endif
  183607. #else /* PNG_1_0_X */
  183608. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183609. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  183610. png_bytep buffer, png_size_t length));
  183611. #endif
  183612. #endif /* PNG_1_0_X */
  183613. /* Reset the CRC variable */
  183614. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  183615. /* Write the "data" buffer to whatever output you are using. */
  183616. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  183617. png_size_t length));
  183618. /* Read data from whatever input you are using into the "data" buffer */
  183619. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  183620. png_size_t length));
  183621. /* Read bytes into buf, and update png_ptr->crc */
  183622. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  183623. png_size_t length));
  183624. /* Decompress data in a chunk that uses compression */
  183625. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  183626. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  183627. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  183628. int comp_type, png_charp chunkdata, png_size_t chunklength,
  183629. png_size_t prefix_length, png_size_t *data_length));
  183630. #endif
  183631. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  183632. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  183633. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  183634. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  183635. /* Calculate the CRC over a section of data. Note that we are only
  183636. * passing a maximum of 64K on systems that have this as a memory limit,
  183637. * since this is the maximum buffer size we can specify.
  183638. */
  183639. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  183640. png_size_t length));
  183641. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183642. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  183643. #endif
  183644. /* simple function to write the signature */
  183645. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  183646. /* write various chunks */
  183647. /* Write the IHDR chunk, and update the png_struct with the necessary
  183648. * information.
  183649. */
  183650. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  183651. png_uint_32 height,
  183652. int bit_depth, int color_type, int compression_method, int filter_method,
  183653. int interlace_method));
  183654. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  183655. png_uint_32 num_pal));
  183656. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  183657. png_size_t length));
  183658. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  183659. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  183660. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183661. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  183662. #endif
  183663. #ifdef PNG_FIXED_POINT_SUPPORTED
  183664. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  183665. file_gamma));
  183666. #endif
  183667. #endif
  183668. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  183669. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  183670. int color_type));
  183671. #endif
  183672. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  183673. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183674. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  183675. double white_x, double white_y,
  183676. double red_x, double red_y, double green_x, double green_y,
  183677. double blue_x, double blue_y));
  183678. #endif
  183679. #ifdef PNG_FIXED_POINT_SUPPORTED
  183680. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  183681. png_fixed_point int_white_x, png_fixed_point int_white_y,
  183682. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183683. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183684. png_fixed_point int_blue_y));
  183685. #endif
  183686. #endif
  183687. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  183688. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  183689. int intent));
  183690. #endif
  183691. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  183692. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  183693. png_charp name, int compression_type,
  183694. png_charp profile, int proflen));
  183695. /* Note to maintainer: profile should be png_bytep */
  183696. #endif
  183697. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  183698. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  183699. png_sPLT_tp palette));
  183700. #endif
  183701. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  183702. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  183703. png_color_16p values, int number, int color_type));
  183704. #endif
  183705. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  183706. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  183707. png_color_16p values, int color_type));
  183708. #endif
  183709. #if defined(PNG_WRITE_hIST_SUPPORTED)
  183710. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  183711. int num_hist));
  183712. #endif
  183713. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  183714. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  183715. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  183716. png_charp key, png_charpp new_key));
  183717. #endif
  183718. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  183719. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  183720. png_charp text, png_size_t text_len));
  183721. #endif
  183722. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  183723. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  183724. png_charp text, png_size_t text_len, int compression));
  183725. #endif
  183726. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  183727. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  183728. int compression, png_charp key, png_charp lang, png_charp lang_key,
  183729. png_charp text));
  183730. #endif
  183731. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  183732. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  183733. png_infop info_ptr, png_textp text_ptr, int num_text));
  183734. #endif
  183735. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  183736. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  183737. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  183738. #endif
  183739. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  183740. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  183741. png_int_32 X0, png_int_32 X1, int type, int nparams,
  183742. png_charp units, png_charpp params));
  183743. #endif
  183744. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  183745. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  183746. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  183747. int unit_type));
  183748. #endif
  183749. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183750. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  183751. png_timep mod_time));
  183752. #endif
  183753. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  183754. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  183755. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  183756. int unit, double width, double height));
  183757. #else
  183758. #ifdef PNG_FIXED_POINT_SUPPORTED
  183759. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  183760. int unit, png_charp width, png_charp height));
  183761. #endif
  183762. #endif
  183763. #endif
  183764. /* Called when finished processing a row of data */
  183765. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  183766. /* Internal use only. Called before first row of data */
  183767. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  183768. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183769. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  183770. #endif
  183771. /* combine a row of data, dealing with alpha, etc. if requested */
  183772. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  183773. int mask));
  183774. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183775. /* expand an interlaced row */
  183776. /* OLD pre-1.0.9 interface:
  183777. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  183778. png_bytep row, int pass, png_uint_32 transformations));
  183779. */
  183780. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  183781. #endif
  183782. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  183783. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183784. /* grab pixels out of a row for an interlaced pass */
  183785. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  183786. png_bytep row, int pass));
  183787. #endif
  183788. /* unfilter a row */
  183789. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  183790. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  183791. /* Choose the best filter to use and filter the row data */
  183792. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  183793. png_row_infop row_info));
  183794. /* Write out the filtered row. */
  183795. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  183796. png_bytep filtered_row));
  183797. /* finish a row while reading, dealing with interlacing passes, etc. */
  183798. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  183799. /* initialize the row buffers, etc. */
  183800. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  183801. /* optional call to update the users info structure */
  183802. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  183803. png_infop info_ptr));
  183804. /* these are the functions that do the transformations */
  183805. #if defined(PNG_READ_FILLER_SUPPORTED)
  183806. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  183807. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  183808. #endif
  183809. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  183810. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  183811. png_bytep row));
  183812. #endif
  183813. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183814. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  183815. png_bytep row));
  183816. #endif
  183817. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  183818. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  183819. png_bytep row));
  183820. #endif
  183821. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183822. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  183823. png_bytep row));
  183824. #endif
  183825. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  183826. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183827. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  183828. png_bytep row, png_uint_32 flags));
  183829. #endif
  183830. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183831. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  183832. #endif
  183833. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183834. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  183835. #endif
  183836. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183837. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  183838. row_info, png_bytep row));
  183839. #endif
  183840. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183841. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  183842. png_bytep row));
  183843. #endif
  183844. #if defined(PNG_READ_PACK_SUPPORTED)
  183845. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  183846. #endif
  183847. #if defined(PNG_READ_SHIFT_SUPPORTED)
  183848. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  183849. png_color_8p sig_bits));
  183850. #endif
  183851. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183852. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  183853. #endif
  183854. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183855. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  183856. #endif
  183857. #if defined(PNG_READ_DITHER_SUPPORTED)
  183858. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  183859. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  183860. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  183861. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  183862. png_colorp palette, int num_palette));
  183863. # endif
  183864. #endif
  183865. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  183866. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  183867. #endif
  183868. #if defined(PNG_WRITE_PACK_SUPPORTED)
  183869. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  183870. png_bytep row, png_uint_32 bit_depth));
  183871. #endif
  183872. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  183873. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  183874. png_color_8p bit_depth));
  183875. #endif
  183876. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183877. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183878. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  183879. png_color_16p trans_values, png_color_16p background,
  183880. png_color_16p background_1,
  183881. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  183882. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  183883. png_uint_16pp gamma_16_to_1, int gamma_shift));
  183884. #else
  183885. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  183886. png_color_16p trans_values, png_color_16p background));
  183887. #endif
  183888. #endif
  183889. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183890. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  183891. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  183892. int gamma_shift));
  183893. #endif
  183894. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183895. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  183896. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  183897. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  183898. png_bytep row, png_color_16p trans_value));
  183899. #endif
  183900. /* The following decodes the appropriate chunks, and does error correction,
  183901. * then calls the appropriate callback for the chunk if it is valid.
  183902. */
  183903. /* decode the IHDR chunk */
  183904. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  183905. png_uint_32 length));
  183906. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  183907. png_uint_32 length));
  183908. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  183909. png_uint_32 length));
  183910. #if defined(PNG_READ_bKGD_SUPPORTED)
  183911. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  183912. png_uint_32 length));
  183913. #endif
  183914. #if defined(PNG_READ_cHRM_SUPPORTED)
  183915. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  183916. png_uint_32 length));
  183917. #endif
  183918. #if defined(PNG_READ_gAMA_SUPPORTED)
  183919. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  183920. png_uint_32 length));
  183921. #endif
  183922. #if defined(PNG_READ_hIST_SUPPORTED)
  183923. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  183924. png_uint_32 length));
  183925. #endif
  183926. #if defined(PNG_READ_iCCP_SUPPORTED)
  183927. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  183928. png_uint_32 length));
  183929. #endif /* PNG_READ_iCCP_SUPPORTED */
  183930. #if defined(PNG_READ_iTXt_SUPPORTED)
  183931. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183932. png_uint_32 length));
  183933. #endif
  183934. #if defined(PNG_READ_oFFs_SUPPORTED)
  183935. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  183936. png_uint_32 length));
  183937. #endif
  183938. #if defined(PNG_READ_pCAL_SUPPORTED)
  183939. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  183940. png_uint_32 length));
  183941. #endif
  183942. #if defined(PNG_READ_pHYs_SUPPORTED)
  183943. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  183944. png_uint_32 length));
  183945. #endif
  183946. #if defined(PNG_READ_sBIT_SUPPORTED)
  183947. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  183948. png_uint_32 length));
  183949. #endif
  183950. #if defined(PNG_READ_sCAL_SUPPORTED)
  183951. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  183952. png_uint_32 length));
  183953. #endif
  183954. #if defined(PNG_READ_sPLT_SUPPORTED)
  183955. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  183956. png_uint_32 length));
  183957. #endif /* PNG_READ_sPLT_SUPPORTED */
  183958. #if defined(PNG_READ_sRGB_SUPPORTED)
  183959. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  183960. png_uint_32 length));
  183961. #endif
  183962. #if defined(PNG_READ_tEXt_SUPPORTED)
  183963. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183964. png_uint_32 length));
  183965. #endif
  183966. #if defined(PNG_READ_tIME_SUPPORTED)
  183967. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  183968. png_uint_32 length));
  183969. #endif
  183970. #if defined(PNG_READ_tRNS_SUPPORTED)
  183971. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  183972. png_uint_32 length));
  183973. #endif
  183974. #if defined(PNG_READ_zTXt_SUPPORTED)
  183975. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183976. png_uint_32 length));
  183977. #endif
  183978. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  183979. png_infop info_ptr, png_uint_32 length));
  183980. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  183981. png_bytep chunk_name));
  183982. /* handle the transformations for reading and writing */
  183983. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  183984. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  183985. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  183986. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183987. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  183988. png_infop info_ptr));
  183989. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  183990. png_infop info_ptr));
  183991. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  183992. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  183993. png_uint_32 length));
  183994. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  183995. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  183996. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  183997. png_bytep buffer, png_size_t buffer_length));
  183998. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  183999. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184000. png_bytep buffer, png_size_t buffer_length));
  184001. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184002. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184003. png_infop info_ptr, png_uint_32 length));
  184004. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184005. png_infop info_ptr));
  184006. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184007. png_infop info_ptr));
  184008. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184009. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184010. png_infop info_ptr));
  184011. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184012. png_infop info_ptr));
  184013. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184014. #if defined(PNG_READ_tEXt_SUPPORTED)
  184015. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184016. png_infop info_ptr, png_uint_32 length));
  184017. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184018. png_infop info_ptr));
  184019. #endif
  184020. #if defined(PNG_READ_zTXt_SUPPORTED)
  184021. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184022. png_infop info_ptr, png_uint_32 length));
  184023. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184024. png_infop info_ptr));
  184025. #endif
  184026. #if defined(PNG_READ_iTXt_SUPPORTED)
  184027. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184028. png_infop info_ptr, png_uint_32 length));
  184029. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184030. png_infop info_ptr));
  184031. #endif
  184032. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184033. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184034. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184035. png_bytep row));
  184036. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184037. png_bytep row));
  184038. #endif
  184039. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184040. #if defined(PNG_MMX_CODE_SUPPORTED)
  184041. /* png.c */ /* PRIVATE */
  184042. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184043. #endif
  184044. #endif
  184045. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184046. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184047. png_infop info_ptr));
  184048. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184049. png_infop info_ptr));
  184050. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184051. png_infop info_ptr));
  184052. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184053. png_infop info_ptr));
  184054. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184055. png_infop info_ptr));
  184056. #if defined(PNG_pHYs_SUPPORTED)
  184057. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184058. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184059. #endif /* PNG_pHYs_SUPPORTED */
  184060. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184061. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184062. #endif /* PNG_INTERNAL */
  184063. #ifdef __cplusplus
  184064. }
  184065. #endif
  184066. #endif /* PNG_VERSION_INFO_ONLY */
  184067. /* do not put anything past this line */
  184068. #endif /* PNG_H */
  184069. /*** End of inlined file: png.h ***/
  184070. #define PNG_NO_EXTERN
  184071. /*** Start of inlined file: png.c ***/
  184072. /* png.c - location for general purpose libpng functions
  184073. *
  184074. * Last changed in libpng 1.2.21 [October 4, 2007]
  184075. * For conditions of distribution and use, see copyright notice in png.h
  184076. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184077. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184078. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184079. */
  184080. #define PNG_INTERNAL
  184081. #define PNG_NO_EXTERN
  184082. /* Generate a compiler error if there is an old png.h in the search path. */
  184083. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184084. /* Version information for C files. This had better match the version
  184085. * string defined in png.h. */
  184086. #ifdef PNG_USE_GLOBAL_ARRAYS
  184087. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184088. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184089. #ifdef PNG_READ_SUPPORTED
  184090. /* png_sig was changed to a function in version 1.0.5c */
  184091. /* Place to hold the signature string for a PNG file. */
  184092. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184093. #endif /* PNG_READ_SUPPORTED */
  184094. /* Invoke global declarations for constant strings for known chunk types */
  184095. PNG_IHDR;
  184096. PNG_IDAT;
  184097. PNG_IEND;
  184098. PNG_PLTE;
  184099. PNG_bKGD;
  184100. PNG_cHRM;
  184101. PNG_gAMA;
  184102. PNG_hIST;
  184103. PNG_iCCP;
  184104. PNG_iTXt;
  184105. PNG_oFFs;
  184106. PNG_pCAL;
  184107. PNG_sCAL;
  184108. PNG_pHYs;
  184109. PNG_sBIT;
  184110. PNG_sPLT;
  184111. PNG_sRGB;
  184112. PNG_tEXt;
  184113. PNG_tIME;
  184114. PNG_tRNS;
  184115. PNG_zTXt;
  184116. #ifdef PNG_READ_SUPPORTED
  184117. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184118. /* start of interlace block */
  184119. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184120. /* offset to next interlace block */
  184121. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184122. /* start of interlace block in the y direction */
  184123. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184124. /* offset to next interlace block in the y direction */
  184125. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184126. /* Height of interlace block. This is not currently used - if you need
  184127. * it, uncomment it here and in png.h
  184128. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184129. */
  184130. /* Mask to determine which pixels are valid in a pass */
  184131. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184132. /* Mask to determine which pixels to overwrite while displaying */
  184133. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184134. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184135. #endif /* PNG_READ_SUPPORTED */
  184136. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184137. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184138. * of the PNG file signature. If the PNG data is embedded into another
  184139. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184140. * or write any of the magic bytes before it starts on the IHDR.
  184141. */
  184142. #ifdef PNG_READ_SUPPORTED
  184143. void PNGAPI
  184144. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184145. {
  184146. if(png_ptr == NULL) return;
  184147. png_debug(1, "in png_set_sig_bytes\n");
  184148. if (num_bytes > 8)
  184149. png_error(png_ptr, "Too many bytes for PNG signature.");
  184150. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184151. }
  184152. /* Checks whether the supplied bytes match the PNG signature. We allow
  184153. * checking less than the full 8-byte signature so that those apps that
  184154. * already read the first few bytes of a file to determine the file type
  184155. * can simply check the remaining bytes for extra assurance. Returns
  184156. * an integer less than, equal to, or greater than zero if sig is found,
  184157. * respectively, to be less than, to match, or be greater than the correct
  184158. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184159. */
  184160. int PNGAPI
  184161. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184162. {
  184163. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184164. if (num_to_check > 8)
  184165. num_to_check = 8;
  184166. else if (num_to_check < 1)
  184167. return (-1);
  184168. if (start > 7)
  184169. return (-1);
  184170. if (start + num_to_check > 8)
  184171. num_to_check = 8 - start;
  184172. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184173. }
  184174. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184175. /* (Obsolete) function to check signature bytes. It does not allow one
  184176. * to check a partial signature. This function might be removed in the
  184177. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184178. */
  184179. int PNGAPI
  184180. png_check_sig(png_bytep sig, int num)
  184181. {
  184182. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184183. }
  184184. #endif
  184185. #endif /* PNG_READ_SUPPORTED */
  184186. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184187. /* Function to allocate memory for zlib and clear it to 0. */
  184188. #ifdef PNG_1_0_X
  184189. voidpf PNGAPI
  184190. #else
  184191. voidpf /* private */
  184192. #endif
  184193. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184194. {
  184195. png_voidp ptr;
  184196. png_structp p=(png_structp)png_ptr;
  184197. png_uint_32 save_flags=p->flags;
  184198. png_uint_32 num_bytes;
  184199. if(png_ptr == NULL) return (NULL);
  184200. if (items > PNG_UINT_32_MAX/size)
  184201. {
  184202. png_warning (p, "Potential overflow in png_zalloc()");
  184203. return (NULL);
  184204. }
  184205. num_bytes = (png_uint_32)items * size;
  184206. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184207. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184208. p->flags=save_flags;
  184209. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184210. if (ptr == NULL)
  184211. return ((voidpf)ptr);
  184212. if (num_bytes > (png_uint_32)0x8000L)
  184213. {
  184214. png_memset(ptr, 0, (png_size_t)0x8000L);
  184215. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184216. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184217. }
  184218. else
  184219. {
  184220. png_memset(ptr, 0, (png_size_t)num_bytes);
  184221. }
  184222. #endif
  184223. return ((voidpf)ptr);
  184224. }
  184225. /* function to free memory for zlib */
  184226. #ifdef PNG_1_0_X
  184227. void PNGAPI
  184228. #else
  184229. void /* private */
  184230. #endif
  184231. png_zfree(voidpf png_ptr, voidpf ptr)
  184232. {
  184233. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184234. }
  184235. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184236. * in case CRC is > 32 bits to leave the top bits 0.
  184237. */
  184238. void /* PRIVATE */
  184239. png_reset_crc(png_structp png_ptr)
  184240. {
  184241. png_ptr->crc = crc32(0, Z_NULL, 0);
  184242. }
  184243. /* Calculate the CRC over a section of data. We can only pass as
  184244. * much data to this routine as the largest single buffer size. We
  184245. * also check that this data will actually be used before going to the
  184246. * trouble of calculating it.
  184247. */
  184248. void /* PRIVATE */
  184249. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184250. {
  184251. int need_crc = 1;
  184252. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184253. {
  184254. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184255. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184256. need_crc = 0;
  184257. }
  184258. else /* critical */
  184259. {
  184260. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184261. need_crc = 0;
  184262. }
  184263. if (need_crc)
  184264. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  184265. }
  184266. /* Allocate the memory for an info_struct for the application. We don't
  184267. * really need the png_ptr, but it could potentially be useful in the
  184268. * future. This should be used in favour of malloc(png_sizeof(png_info))
  184269. * and png_info_init() so that applications that want to use a shared
  184270. * libpng don't have to be recompiled if png_info changes size.
  184271. */
  184272. png_infop PNGAPI
  184273. png_create_info_struct(png_structp png_ptr)
  184274. {
  184275. png_infop info_ptr;
  184276. png_debug(1, "in png_create_info_struct\n");
  184277. if(png_ptr == NULL) return (NULL);
  184278. #ifdef PNG_USER_MEM_SUPPORTED
  184279. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  184280. png_ptr->malloc_fn, png_ptr->mem_ptr);
  184281. #else
  184282. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184283. #endif
  184284. if (info_ptr != NULL)
  184285. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184286. return (info_ptr);
  184287. }
  184288. /* This function frees the memory associated with a single info struct.
  184289. * Normally, one would use either png_destroy_read_struct() or
  184290. * png_destroy_write_struct() to free an info struct, but this may be
  184291. * useful for some applications.
  184292. */
  184293. void PNGAPI
  184294. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  184295. {
  184296. png_infop info_ptr = NULL;
  184297. if(png_ptr == NULL) return;
  184298. png_debug(1, "in png_destroy_info_struct\n");
  184299. if (info_ptr_ptr != NULL)
  184300. info_ptr = *info_ptr_ptr;
  184301. if (info_ptr != NULL)
  184302. {
  184303. png_info_destroy(png_ptr, info_ptr);
  184304. #ifdef PNG_USER_MEM_SUPPORTED
  184305. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184306. png_ptr->mem_ptr);
  184307. #else
  184308. png_destroy_struct((png_voidp)info_ptr);
  184309. #endif
  184310. *info_ptr_ptr = NULL;
  184311. }
  184312. }
  184313. /* Initialize the info structure. This is now an internal function (0.89)
  184314. * and applications using it are urged to use png_create_info_struct()
  184315. * instead.
  184316. */
  184317. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184318. #undef png_info_init
  184319. void PNGAPI
  184320. png_info_init(png_infop info_ptr)
  184321. {
  184322. /* We only come here via pre-1.0.12-compiled applications */
  184323. png_info_init_3(&info_ptr, 0);
  184324. }
  184325. #endif
  184326. void PNGAPI
  184327. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184328. {
  184329. png_infop info_ptr = *ptr_ptr;
  184330. if(info_ptr == NULL) return;
  184331. png_debug(1, "in png_info_init_3\n");
  184332. if(png_sizeof(png_info) > png_info_struct_size)
  184333. {
  184334. png_destroy_struct(info_ptr);
  184335. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184336. *ptr_ptr = info_ptr;
  184337. }
  184338. /* set everything to 0 */
  184339. png_memset(info_ptr, 0, png_sizeof (png_info));
  184340. }
  184341. #ifdef PNG_FREE_ME_SUPPORTED
  184342. void PNGAPI
  184343. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184344. int freer, png_uint_32 mask)
  184345. {
  184346. png_debug(1, "in png_data_freer\n");
  184347. if (png_ptr == NULL || info_ptr == NULL)
  184348. return;
  184349. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184350. info_ptr->free_me |= mask;
  184351. else if(freer == PNG_USER_WILL_FREE_DATA)
  184352. info_ptr->free_me &= ~mask;
  184353. else
  184354. png_warning(png_ptr,
  184355. "Unknown freer parameter in png_data_freer.");
  184356. }
  184357. #endif
  184358. void PNGAPI
  184359. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184360. int num)
  184361. {
  184362. png_debug(1, "in png_free_data\n");
  184363. if (png_ptr == NULL || info_ptr == NULL)
  184364. return;
  184365. #if defined(PNG_TEXT_SUPPORTED)
  184366. /* free text item num or (if num == -1) all text items */
  184367. #ifdef PNG_FREE_ME_SUPPORTED
  184368. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184369. #else
  184370. if (mask & PNG_FREE_TEXT)
  184371. #endif
  184372. {
  184373. if (num != -1)
  184374. {
  184375. if (info_ptr->text && info_ptr->text[num].key)
  184376. {
  184377. png_free(png_ptr, info_ptr->text[num].key);
  184378. info_ptr->text[num].key = NULL;
  184379. }
  184380. }
  184381. else
  184382. {
  184383. int i;
  184384. for (i = 0; i < info_ptr->num_text; i++)
  184385. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  184386. png_free(png_ptr, info_ptr->text);
  184387. info_ptr->text = NULL;
  184388. info_ptr->num_text=0;
  184389. }
  184390. }
  184391. #endif
  184392. #if defined(PNG_tRNS_SUPPORTED)
  184393. /* free any tRNS entry */
  184394. #ifdef PNG_FREE_ME_SUPPORTED
  184395. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  184396. #else
  184397. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  184398. #endif
  184399. {
  184400. png_free(png_ptr, info_ptr->trans);
  184401. info_ptr->valid &= ~PNG_INFO_tRNS;
  184402. #ifndef PNG_FREE_ME_SUPPORTED
  184403. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184404. #endif
  184405. info_ptr->trans = NULL;
  184406. }
  184407. #endif
  184408. #if defined(PNG_sCAL_SUPPORTED)
  184409. /* free any sCAL entry */
  184410. #ifdef PNG_FREE_ME_SUPPORTED
  184411. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  184412. #else
  184413. if (mask & PNG_FREE_SCAL)
  184414. #endif
  184415. {
  184416. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  184417. png_free(png_ptr, info_ptr->scal_s_width);
  184418. png_free(png_ptr, info_ptr->scal_s_height);
  184419. info_ptr->scal_s_width = NULL;
  184420. info_ptr->scal_s_height = NULL;
  184421. #endif
  184422. info_ptr->valid &= ~PNG_INFO_sCAL;
  184423. }
  184424. #endif
  184425. #if defined(PNG_pCAL_SUPPORTED)
  184426. /* free any pCAL entry */
  184427. #ifdef PNG_FREE_ME_SUPPORTED
  184428. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  184429. #else
  184430. if (mask & PNG_FREE_PCAL)
  184431. #endif
  184432. {
  184433. png_free(png_ptr, info_ptr->pcal_purpose);
  184434. png_free(png_ptr, info_ptr->pcal_units);
  184435. info_ptr->pcal_purpose = NULL;
  184436. info_ptr->pcal_units = NULL;
  184437. if (info_ptr->pcal_params != NULL)
  184438. {
  184439. int i;
  184440. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  184441. {
  184442. png_free(png_ptr, info_ptr->pcal_params[i]);
  184443. info_ptr->pcal_params[i]=NULL;
  184444. }
  184445. png_free(png_ptr, info_ptr->pcal_params);
  184446. info_ptr->pcal_params = NULL;
  184447. }
  184448. info_ptr->valid &= ~PNG_INFO_pCAL;
  184449. }
  184450. #endif
  184451. #if defined(PNG_iCCP_SUPPORTED)
  184452. /* free any iCCP entry */
  184453. #ifdef PNG_FREE_ME_SUPPORTED
  184454. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  184455. #else
  184456. if (mask & PNG_FREE_ICCP)
  184457. #endif
  184458. {
  184459. png_free(png_ptr, info_ptr->iccp_name);
  184460. png_free(png_ptr, info_ptr->iccp_profile);
  184461. info_ptr->iccp_name = NULL;
  184462. info_ptr->iccp_profile = NULL;
  184463. info_ptr->valid &= ~PNG_INFO_iCCP;
  184464. }
  184465. #endif
  184466. #if defined(PNG_sPLT_SUPPORTED)
  184467. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  184468. #ifdef PNG_FREE_ME_SUPPORTED
  184469. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  184470. #else
  184471. if (mask & PNG_FREE_SPLT)
  184472. #endif
  184473. {
  184474. if (num != -1)
  184475. {
  184476. if(info_ptr->splt_palettes)
  184477. {
  184478. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  184479. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  184480. info_ptr->splt_palettes[num].name = NULL;
  184481. info_ptr->splt_palettes[num].entries = NULL;
  184482. }
  184483. }
  184484. else
  184485. {
  184486. if(info_ptr->splt_palettes_num)
  184487. {
  184488. int i;
  184489. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  184490. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  184491. png_free(png_ptr, info_ptr->splt_palettes);
  184492. info_ptr->splt_palettes = NULL;
  184493. info_ptr->splt_palettes_num = 0;
  184494. }
  184495. info_ptr->valid &= ~PNG_INFO_sPLT;
  184496. }
  184497. }
  184498. #endif
  184499. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184500. if(png_ptr->unknown_chunk.data)
  184501. {
  184502. png_free(png_ptr, png_ptr->unknown_chunk.data);
  184503. png_ptr->unknown_chunk.data = NULL;
  184504. }
  184505. #ifdef PNG_FREE_ME_SUPPORTED
  184506. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  184507. #else
  184508. if (mask & PNG_FREE_UNKN)
  184509. #endif
  184510. {
  184511. if (num != -1)
  184512. {
  184513. if(info_ptr->unknown_chunks)
  184514. {
  184515. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  184516. info_ptr->unknown_chunks[num].data = NULL;
  184517. }
  184518. }
  184519. else
  184520. {
  184521. int i;
  184522. if(info_ptr->unknown_chunks_num)
  184523. {
  184524. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  184525. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  184526. png_free(png_ptr, info_ptr->unknown_chunks);
  184527. info_ptr->unknown_chunks = NULL;
  184528. info_ptr->unknown_chunks_num = 0;
  184529. }
  184530. }
  184531. }
  184532. #endif
  184533. #if defined(PNG_hIST_SUPPORTED)
  184534. /* free any hIST entry */
  184535. #ifdef PNG_FREE_ME_SUPPORTED
  184536. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  184537. #else
  184538. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  184539. #endif
  184540. {
  184541. png_free(png_ptr, info_ptr->hist);
  184542. info_ptr->hist = NULL;
  184543. info_ptr->valid &= ~PNG_INFO_hIST;
  184544. #ifndef PNG_FREE_ME_SUPPORTED
  184545. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  184546. #endif
  184547. }
  184548. #endif
  184549. /* free any PLTE entry that was internally allocated */
  184550. #ifdef PNG_FREE_ME_SUPPORTED
  184551. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  184552. #else
  184553. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  184554. #endif
  184555. {
  184556. png_zfree(png_ptr, info_ptr->palette);
  184557. info_ptr->palette = NULL;
  184558. info_ptr->valid &= ~PNG_INFO_PLTE;
  184559. #ifndef PNG_FREE_ME_SUPPORTED
  184560. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  184561. #endif
  184562. info_ptr->num_palette = 0;
  184563. }
  184564. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184565. /* free any image bits attached to the info structure */
  184566. #ifdef PNG_FREE_ME_SUPPORTED
  184567. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  184568. #else
  184569. if (mask & PNG_FREE_ROWS)
  184570. #endif
  184571. {
  184572. if(info_ptr->row_pointers)
  184573. {
  184574. int row;
  184575. for (row = 0; row < (int)info_ptr->height; row++)
  184576. {
  184577. png_free(png_ptr, info_ptr->row_pointers[row]);
  184578. info_ptr->row_pointers[row]=NULL;
  184579. }
  184580. png_free(png_ptr, info_ptr->row_pointers);
  184581. info_ptr->row_pointers=NULL;
  184582. }
  184583. info_ptr->valid &= ~PNG_INFO_IDAT;
  184584. }
  184585. #endif
  184586. #ifdef PNG_FREE_ME_SUPPORTED
  184587. if(num == -1)
  184588. info_ptr->free_me &= ~mask;
  184589. else
  184590. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  184591. #endif
  184592. }
  184593. /* This is an internal routine to free any memory that the info struct is
  184594. * pointing to before re-using it or freeing the struct itself. Recall
  184595. * that png_free() checks for NULL pointers for us.
  184596. */
  184597. void /* PRIVATE */
  184598. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  184599. {
  184600. png_debug(1, "in png_info_destroy\n");
  184601. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  184602. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184603. if (png_ptr->num_chunk_list)
  184604. {
  184605. png_free(png_ptr, png_ptr->chunk_list);
  184606. png_ptr->chunk_list=NULL;
  184607. png_ptr->num_chunk_list=0;
  184608. }
  184609. #endif
  184610. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184611. }
  184612. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184613. /* This function returns a pointer to the io_ptr associated with the user
  184614. * functions. The application should free any memory associated with this
  184615. * pointer before png_write_destroy() or png_read_destroy() are called.
  184616. */
  184617. png_voidp PNGAPI
  184618. png_get_io_ptr(png_structp png_ptr)
  184619. {
  184620. if(png_ptr == NULL) return (NULL);
  184621. return (png_ptr->io_ptr);
  184622. }
  184623. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184624. #if !defined(PNG_NO_STDIO)
  184625. /* Initialize the default input/output functions for the PNG file. If you
  184626. * use your own read or write routines, you can call either png_set_read_fn()
  184627. * or png_set_write_fn() instead of png_init_io(). If you have defined
  184628. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  184629. * necessarily available.
  184630. */
  184631. void PNGAPI
  184632. png_init_io(png_structp png_ptr, png_FILE_p fp)
  184633. {
  184634. png_debug(1, "in png_init_io\n");
  184635. if(png_ptr == NULL) return;
  184636. png_ptr->io_ptr = (png_voidp)fp;
  184637. }
  184638. #endif
  184639. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  184640. /* Convert the supplied time into an RFC 1123 string suitable for use in
  184641. * a "Creation Time" or other text-based time string.
  184642. */
  184643. png_charp PNGAPI
  184644. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  184645. {
  184646. static PNG_CONST char short_months[12][4] =
  184647. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  184648. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  184649. if(png_ptr == NULL) return (NULL);
  184650. if (png_ptr->time_buffer == NULL)
  184651. {
  184652. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  184653. png_sizeof(char)));
  184654. }
  184655. #if defined(_WIN32_WCE)
  184656. {
  184657. wchar_t time_buf[29];
  184658. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  184659. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184660. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184661. ptime->second % 61);
  184662. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  184663. NULL, NULL);
  184664. }
  184665. #else
  184666. #ifdef USE_FAR_KEYWORD
  184667. {
  184668. char near_time_buf[29];
  184669. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  184670. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184671. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184672. ptime->second % 61);
  184673. png_memcpy(png_ptr->time_buffer, near_time_buf,
  184674. 29*png_sizeof(char));
  184675. }
  184676. #else
  184677. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  184678. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184679. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184680. ptime->second % 61);
  184681. #endif
  184682. #endif /* _WIN32_WCE */
  184683. return ((png_charp)png_ptr->time_buffer);
  184684. }
  184685. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  184686. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184687. png_charp PNGAPI
  184688. png_get_copyright(png_structp png_ptr)
  184689. {
  184690. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184691. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  184692. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  184693. Copyright (c) 1996-1997 Andreas Dilger\n\
  184694. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  184695. }
  184696. /* The following return the library version as a short string in the
  184697. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  184698. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  184699. * is defined in png.h.
  184700. * Note: now there is no difference between png_get_libpng_ver() and
  184701. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  184702. * it is guaranteed that png.c uses the correct version of png.h.
  184703. */
  184704. png_charp PNGAPI
  184705. png_get_libpng_ver(png_structp png_ptr)
  184706. {
  184707. /* Version of *.c files used when building libpng */
  184708. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184709. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184710. }
  184711. png_charp PNGAPI
  184712. png_get_header_ver(png_structp png_ptr)
  184713. {
  184714. /* Version of *.h files used when building libpng */
  184715. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184716. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184717. }
  184718. png_charp PNGAPI
  184719. png_get_header_version(png_structp png_ptr)
  184720. {
  184721. /* Returns longer string containing both version and date */
  184722. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184723. return ((png_charp) PNG_HEADER_VERSION_STRING
  184724. #ifndef PNG_READ_SUPPORTED
  184725. " (NO READ SUPPORT)"
  184726. #endif
  184727. "\n");
  184728. }
  184729. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184730. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184731. int PNGAPI
  184732. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  184733. {
  184734. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  184735. int i;
  184736. png_bytep p;
  184737. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  184738. return 0;
  184739. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  184740. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  184741. if (!png_memcmp(chunk_name, p, 4))
  184742. return ((int)*(p+4));
  184743. return 0;
  184744. }
  184745. #endif
  184746. /* This function, added to libpng-1.0.6g, is untested. */
  184747. int PNGAPI
  184748. png_reset_zstream(png_structp png_ptr)
  184749. {
  184750. if (png_ptr == NULL) return Z_STREAM_ERROR;
  184751. return (inflateReset(&png_ptr->zstream));
  184752. }
  184753. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184754. /* This function was added to libpng-1.0.7 */
  184755. png_uint_32 PNGAPI
  184756. png_access_version_number(void)
  184757. {
  184758. /* Version of *.c files used when building libpng */
  184759. return((png_uint_32) PNG_LIBPNG_VER);
  184760. }
  184761. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184762. #if !defined(PNG_1_0_X)
  184763. /* this function was added to libpng 1.2.0 */
  184764. int PNGAPI
  184765. png_mmx_support(void)
  184766. {
  184767. /* obsolete, to be removed from libpng-1.4.0 */
  184768. return -1;
  184769. }
  184770. #endif /* PNG_1_0_X */
  184771. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  184772. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184773. #ifdef PNG_SIZE_T
  184774. /* Added at libpng version 1.2.6 */
  184775. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184776. png_size_t PNGAPI
  184777. png_convert_size(size_t size)
  184778. {
  184779. if (size > (png_size_t)-1)
  184780. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  184781. return ((png_size_t)size);
  184782. }
  184783. #endif /* PNG_SIZE_T */
  184784. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184785. /*** End of inlined file: png.c ***/
  184786. /*** Start of inlined file: pngerror.c ***/
  184787. /* pngerror.c - stub functions for i/o and memory allocation
  184788. *
  184789. * Last changed in libpng 1.2.20 October 4, 2007
  184790. * For conditions of distribution and use, see copyright notice in png.h
  184791. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184792. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184793. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184794. *
  184795. * This file provides a location for all error handling. Users who
  184796. * need special error handling are expected to write replacement functions
  184797. * and use png_set_error_fn() to use those functions. See the instructions
  184798. * at each function.
  184799. */
  184800. #define PNG_INTERNAL
  184801. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184802. static void /* PRIVATE */
  184803. png_default_error PNGARG((png_structp png_ptr,
  184804. png_const_charp error_message));
  184805. #ifndef PNG_NO_WARNINGS
  184806. static void /* PRIVATE */
  184807. png_default_warning PNGARG((png_structp png_ptr,
  184808. png_const_charp warning_message));
  184809. #endif /* PNG_NO_WARNINGS */
  184810. /* This function is called whenever there is a fatal error. This function
  184811. * should not be changed. If there is a need to handle errors differently,
  184812. * you should supply a replacement error function and use png_set_error_fn()
  184813. * to replace the error function at run-time.
  184814. */
  184815. #ifndef PNG_NO_ERROR_TEXT
  184816. void PNGAPI
  184817. png_error(png_structp png_ptr, png_const_charp error_message)
  184818. {
  184819. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184820. char msg[16];
  184821. if (png_ptr != NULL)
  184822. {
  184823. if (png_ptr->flags&
  184824. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  184825. {
  184826. if (*error_message == '#')
  184827. {
  184828. int offset;
  184829. for (offset=1; offset<15; offset++)
  184830. if (*(error_message+offset) == ' ')
  184831. break;
  184832. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  184833. {
  184834. int i;
  184835. for (i=0; i<offset-1; i++)
  184836. msg[i]=error_message[i+1];
  184837. msg[i]='\0';
  184838. error_message=msg;
  184839. }
  184840. else
  184841. error_message+=offset;
  184842. }
  184843. else
  184844. {
  184845. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  184846. {
  184847. msg[0]='0';
  184848. msg[1]='\0';
  184849. error_message=msg;
  184850. }
  184851. }
  184852. }
  184853. }
  184854. #endif
  184855. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  184856. (*(png_ptr->error_fn))(png_ptr, error_message);
  184857. /* If the custom handler doesn't exist, or if it returns,
  184858. use the default handler, which will not return. */
  184859. png_default_error(png_ptr, error_message);
  184860. }
  184861. #else
  184862. void PNGAPI
  184863. png_err(png_structp png_ptr)
  184864. {
  184865. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  184866. (*(png_ptr->error_fn))(png_ptr, '\0');
  184867. /* If the custom handler doesn't exist, or if it returns,
  184868. use the default handler, which will not return. */
  184869. png_default_error(png_ptr, '\0');
  184870. }
  184871. #endif /* PNG_NO_ERROR_TEXT */
  184872. #ifndef PNG_NO_WARNINGS
  184873. /* This function is called whenever there is a non-fatal error. This function
  184874. * should not be changed. If there is a need to handle warnings differently,
  184875. * you should supply a replacement warning function and use
  184876. * png_set_error_fn() to replace the warning function at run-time.
  184877. */
  184878. void PNGAPI
  184879. png_warning(png_structp png_ptr, png_const_charp warning_message)
  184880. {
  184881. int offset = 0;
  184882. if (png_ptr != NULL)
  184883. {
  184884. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184885. if (png_ptr->flags&
  184886. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  184887. #endif
  184888. {
  184889. if (*warning_message == '#')
  184890. {
  184891. for (offset=1; offset<15; offset++)
  184892. if (*(warning_message+offset) == ' ')
  184893. break;
  184894. }
  184895. }
  184896. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  184897. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  184898. }
  184899. else
  184900. png_default_warning(png_ptr, warning_message+offset);
  184901. }
  184902. #endif /* PNG_NO_WARNINGS */
  184903. /* These utilities are used internally to build an error message that relates
  184904. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  184905. * this is used to prefix the message. The message is limited in length
  184906. * to 63 bytes, the name characters are output as hex digits wrapped in []
  184907. * if the character is invalid.
  184908. */
  184909. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  184910. /*static PNG_CONST char png_digit[16] = {
  184911. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  184912. 'A', 'B', 'C', 'D', 'E', 'F'
  184913. };*/
  184914. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  184915. static void /* PRIVATE */
  184916. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  184917. error_message)
  184918. {
  184919. int iout = 0, iin = 0;
  184920. while (iin < 4)
  184921. {
  184922. int c = png_ptr->chunk_name[iin++];
  184923. if (isnonalpha(c))
  184924. {
  184925. buffer[iout++] = '[';
  184926. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  184927. buffer[iout++] = png_digit[c & 0x0f];
  184928. buffer[iout++] = ']';
  184929. }
  184930. else
  184931. {
  184932. buffer[iout++] = (png_byte)c;
  184933. }
  184934. }
  184935. if (error_message == NULL)
  184936. buffer[iout] = 0;
  184937. else
  184938. {
  184939. buffer[iout++] = ':';
  184940. buffer[iout++] = ' ';
  184941. png_strncpy(buffer+iout, error_message, 63);
  184942. buffer[iout+63] = 0;
  184943. }
  184944. }
  184945. #ifdef PNG_READ_SUPPORTED
  184946. void PNGAPI
  184947. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  184948. {
  184949. char msg[18+64];
  184950. if (png_ptr == NULL)
  184951. png_error(png_ptr, error_message);
  184952. else
  184953. {
  184954. png_format_buffer(png_ptr, msg, error_message);
  184955. png_error(png_ptr, msg);
  184956. }
  184957. }
  184958. #endif /* PNG_READ_SUPPORTED */
  184959. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  184960. #ifndef PNG_NO_WARNINGS
  184961. void PNGAPI
  184962. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  184963. {
  184964. char msg[18+64];
  184965. if (png_ptr == NULL)
  184966. png_warning(png_ptr, warning_message);
  184967. else
  184968. {
  184969. png_format_buffer(png_ptr, msg, warning_message);
  184970. png_warning(png_ptr, msg);
  184971. }
  184972. }
  184973. #endif /* PNG_NO_WARNINGS */
  184974. /* This is the default error handling function. Note that replacements for
  184975. * this function MUST NOT RETURN, or the program will likely crash. This
  184976. * function is used by default, or if the program supplies NULL for the
  184977. * error function pointer in png_set_error_fn().
  184978. */
  184979. static void /* PRIVATE */
  184980. png_default_error(png_structp, png_const_charp error_message)
  184981. {
  184982. #ifndef PNG_NO_CONSOLE_IO
  184983. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184984. if (*error_message == '#')
  184985. {
  184986. int offset;
  184987. char error_number[16];
  184988. for (offset=0; offset<15; offset++)
  184989. {
  184990. error_number[offset] = *(error_message+offset+1);
  184991. if (*(error_message+offset) == ' ')
  184992. break;
  184993. }
  184994. if((offset > 1) && (offset < 15))
  184995. {
  184996. error_number[offset-1]='\0';
  184997. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  184998. error_message+offset);
  184999. }
  185000. else
  185001. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185002. }
  185003. else
  185004. #endif
  185005. fprintf(stderr, "libpng error: %s\n", error_message);
  185006. #endif
  185007. #ifdef PNG_SETJMP_SUPPORTED
  185008. if (png_ptr)
  185009. {
  185010. # ifdef USE_FAR_KEYWORD
  185011. {
  185012. jmp_buf jmpbuf;
  185013. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185014. longjmp(jmpbuf, 1);
  185015. }
  185016. # else
  185017. longjmp(png_ptr->jmpbuf, 1);
  185018. # endif
  185019. }
  185020. #else
  185021. PNG_ABORT();
  185022. #endif
  185023. #ifdef PNG_NO_CONSOLE_IO
  185024. error_message = error_message; /* make compiler happy */
  185025. #endif
  185026. }
  185027. #ifndef PNG_NO_WARNINGS
  185028. /* This function is called when there is a warning, but the library thinks
  185029. * it can continue anyway. Replacement functions don't have to do anything
  185030. * here if you don't want them to. In the default configuration, png_ptr is
  185031. * not used, but it is passed in case it may be useful.
  185032. */
  185033. static void /* PRIVATE */
  185034. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185035. {
  185036. #ifndef PNG_NO_CONSOLE_IO
  185037. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185038. if (*warning_message == '#')
  185039. {
  185040. int offset;
  185041. char warning_number[16];
  185042. for (offset=0; offset<15; offset++)
  185043. {
  185044. warning_number[offset]=*(warning_message+offset+1);
  185045. if (*(warning_message+offset) == ' ')
  185046. break;
  185047. }
  185048. if((offset > 1) && (offset < 15))
  185049. {
  185050. warning_number[offset-1]='\0';
  185051. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185052. warning_message+offset);
  185053. }
  185054. else
  185055. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185056. }
  185057. else
  185058. # endif
  185059. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185060. #else
  185061. warning_message = warning_message; /* make compiler happy */
  185062. #endif
  185063. png_ptr = png_ptr; /* make compiler happy */
  185064. }
  185065. #endif /* PNG_NO_WARNINGS */
  185066. /* This function is called when the application wants to use another method
  185067. * of handling errors and warnings. Note that the error function MUST NOT
  185068. * return to the calling routine or serious problems will occur. The return
  185069. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185070. */
  185071. void PNGAPI
  185072. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185073. png_error_ptr error_fn, png_error_ptr warning_fn)
  185074. {
  185075. if (png_ptr == NULL)
  185076. return;
  185077. png_ptr->error_ptr = error_ptr;
  185078. png_ptr->error_fn = error_fn;
  185079. png_ptr->warning_fn = warning_fn;
  185080. }
  185081. /* This function returns a pointer to the error_ptr associated with the user
  185082. * functions. The application should free any memory associated with this
  185083. * pointer before png_write_destroy and png_read_destroy are called.
  185084. */
  185085. png_voidp PNGAPI
  185086. png_get_error_ptr(png_structp png_ptr)
  185087. {
  185088. if (png_ptr == NULL)
  185089. return NULL;
  185090. return ((png_voidp)png_ptr->error_ptr);
  185091. }
  185092. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185093. void PNGAPI
  185094. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185095. {
  185096. if(png_ptr != NULL)
  185097. {
  185098. png_ptr->flags &=
  185099. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185100. }
  185101. }
  185102. #endif
  185103. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185104. /*** End of inlined file: pngerror.c ***/
  185105. /*** Start of inlined file: pngget.c ***/
  185106. /* pngget.c - retrieval of values from info struct
  185107. *
  185108. * Last changed in libpng 1.2.15 January 5, 2007
  185109. * For conditions of distribution and use, see copyright notice in png.h
  185110. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185111. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185112. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185113. */
  185114. #define PNG_INTERNAL
  185115. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185116. png_uint_32 PNGAPI
  185117. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185118. {
  185119. if (png_ptr != NULL && info_ptr != NULL)
  185120. return(info_ptr->valid & flag);
  185121. else
  185122. return(0);
  185123. }
  185124. png_uint_32 PNGAPI
  185125. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185126. {
  185127. if (png_ptr != NULL && info_ptr != NULL)
  185128. return(info_ptr->rowbytes);
  185129. else
  185130. return(0);
  185131. }
  185132. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185133. png_bytepp PNGAPI
  185134. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185135. {
  185136. if (png_ptr != NULL && info_ptr != NULL)
  185137. return(info_ptr->row_pointers);
  185138. else
  185139. return(0);
  185140. }
  185141. #endif
  185142. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185143. /* easy access to info, added in libpng-0.99 */
  185144. png_uint_32 PNGAPI
  185145. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185146. {
  185147. if (png_ptr != NULL && info_ptr != NULL)
  185148. {
  185149. return info_ptr->width;
  185150. }
  185151. return (0);
  185152. }
  185153. png_uint_32 PNGAPI
  185154. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185155. {
  185156. if (png_ptr != NULL && info_ptr != NULL)
  185157. {
  185158. return info_ptr->height;
  185159. }
  185160. return (0);
  185161. }
  185162. png_byte PNGAPI
  185163. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185164. {
  185165. if (png_ptr != NULL && info_ptr != NULL)
  185166. {
  185167. return info_ptr->bit_depth;
  185168. }
  185169. return (0);
  185170. }
  185171. png_byte PNGAPI
  185172. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185173. {
  185174. if (png_ptr != NULL && info_ptr != NULL)
  185175. {
  185176. return info_ptr->color_type;
  185177. }
  185178. return (0);
  185179. }
  185180. png_byte PNGAPI
  185181. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185182. {
  185183. if (png_ptr != NULL && info_ptr != NULL)
  185184. {
  185185. return info_ptr->filter_type;
  185186. }
  185187. return (0);
  185188. }
  185189. png_byte PNGAPI
  185190. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185191. {
  185192. if (png_ptr != NULL && info_ptr != NULL)
  185193. {
  185194. return info_ptr->interlace_type;
  185195. }
  185196. return (0);
  185197. }
  185198. png_byte PNGAPI
  185199. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185200. {
  185201. if (png_ptr != NULL && info_ptr != NULL)
  185202. {
  185203. return info_ptr->compression_type;
  185204. }
  185205. return (0);
  185206. }
  185207. png_uint_32 PNGAPI
  185208. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185209. {
  185210. if (png_ptr != NULL && info_ptr != NULL)
  185211. #if defined(PNG_pHYs_SUPPORTED)
  185212. if (info_ptr->valid & PNG_INFO_pHYs)
  185213. {
  185214. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185215. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185216. return (0);
  185217. else return (info_ptr->x_pixels_per_unit);
  185218. }
  185219. #else
  185220. return (0);
  185221. #endif
  185222. return (0);
  185223. }
  185224. png_uint_32 PNGAPI
  185225. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185226. {
  185227. if (png_ptr != NULL && info_ptr != NULL)
  185228. #if defined(PNG_pHYs_SUPPORTED)
  185229. if (info_ptr->valid & PNG_INFO_pHYs)
  185230. {
  185231. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185232. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185233. return (0);
  185234. else return (info_ptr->y_pixels_per_unit);
  185235. }
  185236. #else
  185237. return (0);
  185238. #endif
  185239. return (0);
  185240. }
  185241. png_uint_32 PNGAPI
  185242. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185243. {
  185244. if (png_ptr != NULL && info_ptr != NULL)
  185245. #if defined(PNG_pHYs_SUPPORTED)
  185246. if (info_ptr->valid & PNG_INFO_pHYs)
  185247. {
  185248. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  185249. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185250. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185251. return (0);
  185252. else return (info_ptr->x_pixels_per_unit);
  185253. }
  185254. #else
  185255. return (0);
  185256. #endif
  185257. return (0);
  185258. }
  185259. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185260. float PNGAPI
  185261. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185262. {
  185263. if (png_ptr != NULL && info_ptr != NULL)
  185264. #if defined(PNG_pHYs_SUPPORTED)
  185265. if (info_ptr->valid & PNG_INFO_pHYs)
  185266. {
  185267. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  185268. if (info_ptr->x_pixels_per_unit == 0)
  185269. return ((float)0.0);
  185270. else
  185271. return ((float)((float)info_ptr->y_pixels_per_unit
  185272. /(float)info_ptr->x_pixels_per_unit));
  185273. }
  185274. #else
  185275. return (0.0);
  185276. #endif
  185277. return ((float)0.0);
  185278. }
  185279. #endif
  185280. png_int_32 PNGAPI
  185281. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185282. {
  185283. if (png_ptr != NULL && info_ptr != NULL)
  185284. #if defined(PNG_oFFs_SUPPORTED)
  185285. if (info_ptr->valid & PNG_INFO_oFFs)
  185286. {
  185287. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185288. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185289. return (0);
  185290. else return (info_ptr->x_offset);
  185291. }
  185292. #else
  185293. return (0);
  185294. #endif
  185295. return (0);
  185296. }
  185297. png_int_32 PNGAPI
  185298. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185299. {
  185300. if (png_ptr != NULL && info_ptr != NULL)
  185301. #if defined(PNG_oFFs_SUPPORTED)
  185302. if (info_ptr->valid & PNG_INFO_oFFs)
  185303. {
  185304. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185305. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185306. return (0);
  185307. else return (info_ptr->y_offset);
  185308. }
  185309. #else
  185310. return (0);
  185311. #endif
  185312. return (0);
  185313. }
  185314. png_int_32 PNGAPI
  185315. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185316. {
  185317. if (png_ptr != NULL && info_ptr != NULL)
  185318. #if defined(PNG_oFFs_SUPPORTED)
  185319. if (info_ptr->valid & PNG_INFO_oFFs)
  185320. {
  185321. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185322. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185323. return (0);
  185324. else return (info_ptr->x_offset);
  185325. }
  185326. #else
  185327. return (0);
  185328. #endif
  185329. return (0);
  185330. }
  185331. png_int_32 PNGAPI
  185332. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185333. {
  185334. if (png_ptr != NULL && info_ptr != NULL)
  185335. #if defined(PNG_oFFs_SUPPORTED)
  185336. if (info_ptr->valid & PNG_INFO_oFFs)
  185337. {
  185338. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185339. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185340. return (0);
  185341. else return (info_ptr->y_offset);
  185342. }
  185343. #else
  185344. return (0);
  185345. #endif
  185346. return (0);
  185347. }
  185348. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185349. png_uint_32 PNGAPI
  185350. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185351. {
  185352. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185353. *.0254 +.5));
  185354. }
  185355. png_uint_32 PNGAPI
  185356. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185357. {
  185358. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185359. *.0254 +.5));
  185360. }
  185361. png_uint_32 PNGAPI
  185362. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185363. {
  185364. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185365. *.0254 +.5));
  185366. }
  185367. float PNGAPI
  185368. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185369. {
  185370. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185371. *.00003937);
  185372. }
  185373. float PNGAPI
  185374. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185375. {
  185376. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185377. *.00003937);
  185378. }
  185379. #if defined(PNG_pHYs_SUPPORTED)
  185380. png_uint_32 PNGAPI
  185381. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  185382. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185383. {
  185384. png_uint_32 retval = 0;
  185385. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  185386. {
  185387. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185388. if (res_x != NULL)
  185389. {
  185390. *res_x = info_ptr->x_pixels_per_unit;
  185391. retval |= PNG_INFO_pHYs;
  185392. }
  185393. if (res_y != NULL)
  185394. {
  185395. *res_y = info_ptr->y_pixels_per_unit;
  185396. retval |= PNG_INFO_pHYs;
  185397. }
  185398. if (unit_type != NULL)
  185399. {
  185400. *unit_type = (int)info_ptr->phys_unit_type;
  185401. retval |= PNG_INFO_pHYs;
  185402. if(*unit_type == 1)
  185403. {
  185404. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  185405. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  185406. }
  185407. }
  185408. }
  185409. return (retval);
  185410. }
  185411. #endif /* PNG_pHYs_SUPPORTED */
  185412. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  185413. /* png_get_channels really belongs in here, too, but it's been around longer */
  185414. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  185415. png_byte PNGAPI
  185416. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  185417. {
  185418. if (png_ptr != NULL && info_ptr != NULL)
  185419. return(info_ptr->channels);
  185420. else
  185421. return (0);
  185422. }
  185423. png_bytep PNGAPI
  185424. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  185425. {
  185426. if (png_ptr != NULL && info_ptr != NULL)
  185427. return(info_ptr->signature);
  185428. else
  185429. return (NULL);
  185430. }
  185431. #if defined(PNG_bKGD_SUPPORTED)
  185432. png_uint_32 PNGAPI
  185433. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  185434. png_color_16p *background)
  185435. {
  185436. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  185437. && background != NULL)
  185438. {
  185439. png_debug1(1, "in %s retrieval function\n", "bKGD");
  185440. *background = &(info_ptr->background);
  185441. return (PNG_INFO_bKGD);
  185442. }
  185443. return (0);
  185444. }
  185445. #endif
  185446. #if defined(PNG_cHRM_SUPPORTED)
  185447. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185448. png_uint_32 PNGAPI
  185449. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  185450. double *white_x, double *white_y, double *red_x, double *red_y,
  185451. double *green_x, double *green_y, double *blue_x, double *blue_y)
  185452. {
  185453. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185454. {
  185455. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185456. if (white_x != NULL)
  185457. *white_x = (double)info_ptr->x_white;
  185458. if (white_y != NULL)
  185459. *white_y = (double)info_ptr->y_white;
  185460. if (red_x != NULL)
  185461. *red_x = (double)info_ptr->x_red;
  185462. if (red_y != NULL)
  185463. *red_y = (double)info_ptr->y_red;
  185464. if (green_x != NULL)
  185465. *green_x = (double)info_ptr->x_green;
  185466. if (green_y != NULL)
  185467. *green_y = (double)info_ptr->y_green;
  185468. if (blue_x != NULL)
  185469. *blue_x = (double)info_ptr->x_blue;
  185470. if (blue_y != NULL)
  185471. *blue_y = (double)info_ptr->y_blue;
  185472. return (PNG_INFO_cHRM);
  185473. }
  185474. return (0);
  185475. }
  185476. #endif
  185477. #ifdef PNG_FIXED_POINT_SUPPORTED
  185478. png_uint_32 PNGAPI
  185479. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  185480. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  185481. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  185482. png_fixed_point *blue_x, png_fixed_point *blue_y)
  185483. {
  185484. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185485. {
  185486. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185487. if (white_x != NULL)
  185488. *white_x = info_ptr->int_x_white;
  185489. if (white_y != NULL)
  185490. *white_y = info_ptr->int_y_white;
  185491. if (red_x != NULL)
  185492. *red_x = info_ptr->int_x_red;
  185493. if (red_y != NULL)
  185494. *red_y = info_ptr->int_y_red;
  185495. if (green_x != NULL)
  185496. *green_x = info_ptr->int_x_green;
  185497. if (green_y != NULL)
  185498. *green_y = info_ptr->int_y_green;
  185499. if (blue_x != NULL)
  185500. *blue_x = info_ptr->int_x_blue;
  185501. if (blue_y != NULL)
  185502. *blue_y = info_ptr->int_y_blue;
  185503. return (PNG_INFO_cHRM);
  185504. }
  185505. return (0);
  185506. }
  185507. #endif
  185508. #endif
  185509. #if defined(PNG_gAMA_SUPPORTED)
  185510. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185511. png_uint_32 PNGAPI
  185512. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  185513. {
  185514. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185515. && file_gamma != NULL)
  185516. {
  185517. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185518. *file_gamma = (double)info_ptr->gamma;
  185519. return (PNG_INFO_gAMA);
  185520. }
  185521. return (0);
  185522. }
  185523. #endif
  185524. #ifdef PNG_FIXED_POINT_SUPPORTED
  185525. png_uint_32 PNGAPI
  185526. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  185527. png_fixed_point *int_file_gamma)
  185528. {
  185529. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185530. && int_file_gamma != NULL)
  185531. {
  185532. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185533. *int_file_gamma = info_ptr->int_gamma;
  185534. return (PNG_INFO_gAMA);
  185535. }
  185536. return (0);
  185537. }
  185538. #endif
  185539. #endif
  185540. #if defined(PNG_sRGB_SUPPORTED)
  185541. png_uint_32 PNGAPI
  185542. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  185543. {
  185544. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  185545. && file_srgb_intent != NULL)
  185546. {
  185547. png_debug1(1, "in %s retrieval function\n", "sRGB");
  185548. *file_srgb_intent = (int)info_ptr->srgb_intent;
  185549. return (PNG_INFO_sRGB);
  185550. }
  185551. return (0);
  185552. }
  185553. #endif
  185554. #if defined(PNG_iCCP_SUPPORTED)
  185555. png_uint_32 PNGAPI
  185556. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  185557. png_charpp name, int *compression_type,
  185558. png_charpp profile, png_uint_32 *proflen)
  185559. {
  185560. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  185561. && name != NULL && profile != NULL && proflen != NULL)
  185562. {
  185563. png_debug1(1, "in %s retrieval function\n", "iCCP");
  185564. *name = info_ptr->iccp_name;
  185565. *profile = info_ptr->iccp_profile;
  185566. /* compression_type is a dummy so the API won't have to change
  185567. if we introduce multiple compression types later. */
  185568. *proflen = (int)info_ptr->iccp_proflen;
  185569. *compression_type = (int)info_ptr->iccp_compression;
  185570. return (PNG_INFO_iCCP);
  185571. }
  185572. return (0);
  185573. }
  185574. #endif
  185575. #if defined(PNG_sPLT_SUPPORTED)
  185576. png_uint_32 PNGAPI
  185577. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  185578. png_sPLT_tpp spalettes)
  185579. {
  185580. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  185581. {
  185582. *spalettes = info_ptr->splt_palettes;
  185583. return ((png_uint_32)info_ptr->splt_palettes_num);
  185584. }
  185585. return (0);
  185586. }
  185587. #endif
  185588. #if defined(PNG_hIST_SUPPORTED)
  185589. png_uint_32 PNGAPI
  185590. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  185591. {
  185592. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  185593. && hist != NULL)
  185594. {
  185595. png_debug1(1, "in %s retrieval function\n", "hIST");
  185596. *hist = info_ptr->hist;
  185597. return (PNG_INFO_hIST);
  185598. }
  185599. return (0);
  185600. }
  185601. #endif
  185602. png_uint_32 PNGAPI
  185603. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  185604. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  185605. int *color_type, int *interlace_type, int *compression_type,
  185606. int *filter_type)
  185607. {
  185608. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  185609. bit_depth != NULL && color_type != NULL)
  185610. {
  185611. png_debug1(1, "in %s retrieval function\n", "IHDR");
  185612. *width = info_ptr->width;
  185613. *height = info_ptr->height;
  185614. *bit_depth = info_ptr->bit_depth;
  185615. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  185616. png_error(png_ptr, "Invalid bit depth");
  185617. *color_type = info_ptr->color_type;
  185618. if (info_ptr->color_type > 6)
  185619. png_error(png_ptr, "Invalid color type");
  185620. if (compression_type != NULL)
  185621. *compression_type = info_ptr->compression_type;
  185622. if (filter_type != NULL)
  185623. *filter_type = info_ptr->filter_type;
  185624. if (interlace_type != NULL)
  185625. *interlace_type = info_ptr->interlace_type;
  185626. /* check for potential overflow of rowbytes */
  185627. if (*width == 0 || *width > PNG_UINT_31_MAX)
  185628. png_error(png_ptr, "Invalid image width");
  185629. if (*height == 0 || *height > PNG_UINT_31_MAX)
  185630. png_error(png_ptr, "Invalid image height");
  185631. if (info_ptr->width > (PNG_UINT_32_MAX
  185632. >> 3) /* 8-byte RGBA pixels */
  185633. - 64 /* bigrowbuf hack */
  185634. - 1 /* filter byte */
  185635. - 7*8 /* rounding of width to multiple of 8 pixels */
  185636. - 8) /* extra max_pixel_depth pad */
  185637. {
  185638. png_warning(png_ptr,
  185639. "Width too large for libpng to process image data.");
  185640. }
  185641. return (1);
  185642. }
  185643. return (0);
  185644. }
  185645. #if defined(PNG_oFFs_SUPPORTED)
  185646. png_uint_32 PNGAPI
  185647. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  185648. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  185649. {
  185650. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  185651. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  185652. {
  185653. png_debug1(1, "in %s retrieval function\n", "oFFs");
  185654. *offset_x = info_ptr->x_offset;
  185655. *offset_y = info_ptr->y_offset;
  185656. *unit_type = (int)info_ptr->offset_unit_type;
  185657. return (PNG_INFO_oFFs);
  185658. }
  185659. return (0);
  185660. }
  185661. #endif
  185662. #if defined(PNG_pCAL_SUPPORTED)
  185663. png_uint_32 PNGAPI
  185664. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  185665. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  185666. png_charp *units, png_charpp *params)
  185667. {
  185668. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  185669. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  185670. nparams != NULL && units != NULL && params != NULL)
  185671. {
  185672. png_debug1(1, "in %s retrieval function\n", "pCAL");
  185673. *purpose = info_ptr->pcal_purpose;
  185674. *X0 = info_ptr->pcal_X0;
  185675. *X1 = info_ptr->pcal_X1;
  185676. *type = (int)info_ptr->pcal_type;
  185677. *nparams = (int)info_ptr->pcal_nparams;
  185678. *units = info_ptr->pcal_units;
  185679. *params = info_ptr->pcal_params;
  185680. return (PNG_INFO_pCAL);
  185681. }
  185682. return (0);
  185683. }
  185684. #endif
  185685. #if defined(PNG_sCAL_SUPPORTED)
  185686. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185687. png_uint_32 PNGAPI
  185688. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  185689. int *unit, double *width, double *height)
  185690. {
  185691. if (png_ptr != NULL && info_ptr != NULL &&
  185692. (info_ptr->valid & PNG_INFO_sCAL))
  185693. {
  185694. *unit = info_ptr->scal_unit;
  185695. *width = info_ptr->scal_pixel_width;
  185696. *height = info_ptr->scal_pixel_height;
  185697. return (PNG_INFO_sCAL);
  185698. }
  185699. return(0);
  185700. }
  185701. #else
  185702. #ifdef PNG_FIXED_POINT_SUPPORTED
  185703. png_uint_32 PNGAPI
  185704. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  185705. int *unit, png_charpp width, png_charpp height)
  185706. {
  185707. if (png_ptr != NULL && info_ptr != NULL &&
  185708. (info_ptr->valid & PNG_INFO_sCAL))
  185709. {
  185710. *unit = info_ptr->scal_unit;
  185711. *width = info_ptr->scal_s_width;
  185712. *height = info_ptr->scal_s_height;
  185713. return (PNG_INFO_sCAL);
  185714. }
  185715. return(0);
  185716. }
  185717. #endif
  185718. #endif
  185719. #endif
  185720. #if defined(PNG_pHYs_SUPPORTED)
  185721. png_uint_32 PNGAPI
  185722. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  185723. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185724. {
  185725. png_uint_32 retval = 0;
  185726. if (png_ptr != NULL && info_ptr != NULL &&
  185727. (info_ptr->valid & PNG_INFO_pHYs))
  185728. {
  185729. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185730. if (res_x != NULL)
  185731. {
  185732. *res_x = info_ptr->x_pixels_per_unit;
  185733. retval |= PNG_INFO_pHYs;
  185734. }
  185735. if (res_y != NULL)
  185736. {
  185737. *res_y = info_ptr->y_pixels_per_unit;
  185738. retval |= PNG_INFO_pHYs;
  185739. }
  185740. if (unit_type != NULL)
  185741. {
  185742. *unit_type = (int)info_ptr->phys_unit_type;
  185743. retval |= PNG_INFO_pHYs;
  185744. }
  185745. }
  185746. return (retval);
  185747. }
  185748. #endif
  185749. png_uint_32 PNGAPI
  185750. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  185751. int *num_palette)
  185752. {
  185753. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  185754. && palette != NULL)
  185755. {
  185756. png_debug1(1, "in %s retrieval function\n", "PLTE");
  185757. *palette = info_ptr->palette;
  185758. *num_palette = info_ptr->num_palette;
  185759. png_debug1(3, "num_palette = %d\n", *num_palette);
  185760. return (PNG_INFO_PLTE);
  185761. }
  185762. return (0);
  185763. }
  185764. #if defined(PNG_sBIT_SUPPORTED)
  185765. png_uint_32 PNGAPI
  185766. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  185767. {
  185768. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  185769. && sig_bit != NULL)
  185770. {
  185771. png_debug1(1, "in %s retrieval function\n", "sBIT");
  185772. *sig_bit = &(info_ptr->sig_bit);
  185773. return (PNG_INFO_sBIT);
  185774. }
  185775. return (0);
  185776. }
  185777. #endif
  185778. #if defined(PNG_TEXT_SUPPORTED)
  185779. png_uint_32 PNGAPI
  185780. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  185781. int *num_text)
  185782. {
  185783. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  185784. {
  185785. png_debug1(1, "in %s retrieval function\n",
  185786. (png_ptr->chunk_name[0] == '\0' ? "text"
  185787. : (png_const_charp)png_ptr->chunk_name));
  185788. if (text_ptr != NULL)
  185789. *text_ptr = info_ptr->text;
  185790. if (num_text != NULL)
  185791. *num_text = info_ptr->num_text;
  185792. return ((png_uint_32)info_ptr->num_text);
  185793. }
  185794. if (num_text != NULL)
  185795. *num_text = 0;
  185796. return(0);
  185797. }
  185798. #endif
  185799. #if defined(PNG_tIME_SUPPORTED)
  185800. png_uint_32 PNGAPI
  185801. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  185802. {
  185803. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  185804. && mod_time != NULL)
  185805. {
  185806. png_debug1(1, "in %s retrieval function\n", "tIME");
  185807. *mod_time = &(info_ptr->mod_time);
  185808. return (PNG_INFO_tIME);
  185809. }
  185810. return (0);
  185811. }
  185812. #endif
  185813. #if defined(PNG_tRNS_SUPPORTED)
  185814. png_uint_32 PNGAPI
  185815. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  185816. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  185817. {
  185818. png_uint_32 retval = 0;
  185819. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  185820. {
  185821. png_debug1(1, "in %s retrieval function\n", "tRNS");
  185822. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  185823. {
  185824. if (trans != NULL)
  185825. {
  185826. *trans = info_ptr->trans;
  185827. retval |= PNG_INFO_tRNS;
  185828. }
  185829. if (trans_values != NULL)
  185830. *trans_values = &(info_ptr->trans_values);
  185831. }
  185832. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  185833. {
  185834. if (trans_values != NULL)
  185835. {
  185836. *trans_values = &(info_ptr->trans_values);
  185837. retval |= PNG_INFO_tRNS;
  185838. }
  185839. if(trans != NULL)
  185840. *trans = NULL;
  185841. }
  185842. if(num_trans != NULL)
  185843. {
  185844. *num_trans = info_ptr->num_trans;
  185845. retval |= PNG_INFO_tRNS;
  185846. }
  185847. }
  185848. return (retval);
  185849. }
  185850. #endif
  185851. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185852. png_uint_32 PNGAPI
  185853. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  185854. png_unknown_chunkpp unknowns)
  185855. {
  185856. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  185857. {
  185858. *unknowns = info_ptr->unknown_chunks;
  185859. return ((png_uint_32)info_ptr->unknown_chunks_num);
  185860. }
  185861. return (0);
  185862. }
  185863. #endif
  185864. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185865. png_byte PNGAPI
  185866. png_get_rgb_to_gray_status (png_structp png_ptr)
  185867. {
  185868. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  185869. }
  185870. #endif
  185871. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  185872. png_voidp PNGAPI
  185873. png_get_user_chunk_ptr(png_structp png_ptr)
  185874. {
  185875. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  185876. }
  185877. #endif
  185878. #ifdef PNG_WRITE_SUPPORTED
  185879. png_uint_32 PNGAPI
  185880. png_get_compression_buffer_size(png_structp png_ptr)
  185881. {
  185882. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  185883. }
  185884. #endif
  185885. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  185886. #ifndef PNG_1_0_X
  185887. /* this function was added to libpng 1.2.0 and should exist by default */
  185888. png_uint_32 PNGAPI
  185889. png_get_asm_flags (png_structp png_ptr)
  185890. {
  185891. /* obsolete, to be removed from libpng-1.4.0 */
  185892. return (png_ptr? 0L: 0L);
  185893. }
  185894. /* this function was added to libpng 1.2.0 and should exist by default */
  185895. png_uint_32 PNGAPI
  185896. png_get_asm_flagmask (int flag_select)
  185897. {
  185898. /* obsolete, to be removed from libpng-1.4.0 */
  185899. flag_select=flag_select;
  185900. return 0L;
  185901. }
  185902. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  185903. /* this function was added to libpng 1.2.0 */
  185904. png_uint_32 PNGAPI
  185905. png_get_mmx_flagmask (int flag_select, int *compilerID)
  185906. {
  185907. /* obsolete, to be removed from libpng-1.4.0 */
  185908. flag_select=flag_select;
  185909. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  185910. return 0L;
  185911. }
  185912. /* this function was added to libpng 1.2.0 */
  185913. png_byte PNGAPI
  185914. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  185915. {
  185916. /* obsolete, to be removed from libpng-1.4.0 */
  185917. return (png_ptr? 0: 0);
  185918. }
  185919. /* this function was added to libpng 1.2.0 */
  185920. png_uint_32 PNGAPI
  185921. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  185922. {
  185923. /* obsolete, to be removed from libpng-1.4.0 */
  185924. return (png_ptr? 0L: 0L);
  185925. }
  185926. #endif /* ?PNG_1_0_X */
  185927. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  185928. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  185929. /* these functions were added to libpng 1.2.6 */
  185930. png_uint_32 PNGAPI
  185931. png_get_user_width_max (png_structp png_ptr)
  185932. {
  185933. return (png_ptr? png_ptr->user_width_max : 0);
  185934. }
  185935. png_uint_32 PNGAPI
  185936. png_get_user_height_max (png_structp png_ptr)
  185937. {
  185938. return (png_ptr? png_ptr->user_height_max : 0);
  185939. }
  185940. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  185941. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185942. /*** End of inlined file: pngget.c ***/
  185943. /*** Start of inlined file: pngmem.c ***/
  185944. /* pngmem.c - stub functions for memory allocation
  185945. *
  185946. * Last changed in libpng 1.2.13 November 13, 2006
  185947. * For conditions of distribution and use, see copyright notice in png.h
  185948. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  185949. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185950. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185951. *
  185952. * This file provides a location for all memory allocation. Users who
  185953. * need special memory handling are expected to supply replacement
  185954. * functions for png_malloc() and png_free(), and to use
  185955. * png_create_read_struct_2() and png_create_write_struct_2() to
  185956. * identify the replacement functions.
  185957. */
  185958. #define PNG_INTERNAL
  185959. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185960. /* Borland DOS special memory handler */
  185961. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  185962. /* if you change this, be sure to change the one in png.h also */
  185963. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  185964. by a single call to calloc() if this is thought to improve performance. */
  185965. png_voidp /* PRIVATE */
  185966. png_create_struct(int type)
  185967. {
  185968. #ifdef PNG_USER_MEM_SUPPORTED
  185969. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  185970. }
  185971. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  185972. png_voidp /* PRIVATE */
  185973. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  185974. {
  185975. #endif /* PNG_USER_MEM_SUPPORTED */
  185976. png_size_t size;
  185977. png_voidp struct_ptr;
  185978. if (type == PNG_STRUCT_INFO)
  185979. size = png_sizeof(png_info);
  185980. else if (type == PNG_STRUCT_PNG)
  185981. size = png_sizeof(png_struct);
  185982. else
  185983. return (png_get_copyright(NULL));
  185984. #ifdef PNG_USER_MEM_SUPPORTED
  185985. if(malloc_fn != NULL)
  185986. {
  185987. png_struct dummy_struct;
  185988. png_structp png_ptr = &dummy_struct;
  185989. png_ptr->mem_ptr=mem_ptr;
  185990. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  185991. }
  185992. else
  185993. #endif /* PNG_USER_MEM_SUPPORTED */
  185994. struct_ptr = (png_voidp)farmalloc(size);
  185995. if (struct_ptr != NULL)
  185996. png_memset(struct_ptr, 0, size);
  185997. return (struct_ptr);
  185998. }
  185999. /* Free memory allocated by a png_create_struct() call */
  186000. void /* PRIVATE */
  186001. png_destroy_struct(png_voidp struct_ptr)
  186002. {
  186003. #ifdef PNG_USER_MEM_SUPPORTED
  186004. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186005. }
  186006. /* Free memory allocated by a png_create_struct() call */
  186007. void /* PRIVATE */
  186008. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186009. png_voidp mem_ptr)
  186010. {
  186011. #endif
  186012. if (struct_ptr != NULL)
  186013. {
  186014. #ifdef PNG_USER_MEM_SUPPORTED
  186015. if(free_fn != NULL)
  186016. {
  186017. png_struct dummy_struct;
  186018. png_structp png_ptr = &dummy_struct;
  186019. png_ptr->mem_ptr=mem_ptr;
  186020. (*(free_fn))(png_ptr, struct_ptr);
  186021. return;
  186022. }
  186023. #endif /* PNG_USER_MEM_SUPPORTED */
  186024. farfree (struct_ptr);
  186025. }
  186026. }
  186027. /* Allocate memory. For reasonable files, size should never exceed
  186028. * 64K. However, zlib may allocate more then 64K if you don't tell
  186029. * it not to. See zconf.h and png.h for more information. zlib does
  186030. * need to allocate exactly 64K, so whatever you call here must
  186031. * have the ability to do that.
  186032. *
  186033. * Borland seems to have a problem in DOS mode for exactly 64K.
  186034. * It gives you a segment with an offset of 8 (perhaps to store its
  186035. * memory stuff). zlib doesn't like this at all, so we have to
  186036. * detect and deal with it. This code should not be needed in
  186037. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186038. * been updated by Alexander Lehmann for version 0.89 to waste less
  186039. * memory.
  186040. *
  186041. * Note that we can't use png_size_t for the "size" declaration,
  186042. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186043. * result, we would be truncating potentially larger memory requests
  186044. * (which should cause a fatal error) and introducing major problems.
  186045. */
  186046. png_voidp PNGAPI
  186047. png_malloc(png_structp png_ptr, png_uint_32 size)
  186048. {
  186049. png_voidp ret;
  186050. if (png_ptr == NULL || size == 0)
  186051. return (NULL);
  186052. #ifdef PNG_USER_MEM_SUPPORTED
  186053. if(png_ptr->malloc_fn != NULL)
  186054. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186055. else
  186056. ret = (png_malloc_default(png_ptr, size));
  186057. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186058. png_error(png_ptr, "Out of memory!");
  186059. return (ret);
  186060. }
  186061. png_voidp PNGAPI
  186062. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186063. {
  186064. png_voidp ret;
  186065. #endif /* PNG_USER_MEM_SUPPORTED */
  186066. if (png_ptr == NULL || size == 0)
  186067. return (NULL);
  186068. #ifdef PNG_MAX_MALLOC_64K
  186069. if (size > (png_uint_32)65536L)
  186070. {
  186071. png_warning(png_ptr, "Cannot Allocate > 64K");
  186072. ret = NULL;
  186073. }
  186074. else
  186075. #endif
  186076. if (size != (size_t)size)
  186077. ret = NULL;
  186078. else if (size == (png_uint_32)65536L)
  186079. {
  186080. if (png_ptr->offset_table == NULL)
  186081. {
  186082. /* try to see if we need to do any of this fancy stuff */
  186083. ret = farmalloc(size);
  186084. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186085. {
  186086. int num_blocks;
  186087. png_uint_32 total_size;
  186088. png_bytep table;
  186089. int i;
  186090. png_byte huge * hptr;
  186091. if (ret != NULL)
  186092. {
  186093. farfree(ret);
  186094. ret = NULL;
  186095. }
  186096. if(png_ptr->zlib_window_bits > 14)
  186097. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186098. else
  186099. num_blocks = 1;
  186100. if (png_ptr->zlib_mem_level >= 7)
  186101. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186102. else
  186103. num_blocks++;
  186104. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186105. table = farmalloc(total_size);
  186106. if (table == NULL)
  186107. {
  186108. #ifndef PNG_USER_MEM_SUPPORTED
  186109. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186110. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186111. else
  186112. png_warning(png_ptr, "Out Of Memory.");
  186113. #endif
  186114. return (NULL);
  186115. }
  186116. if ((png_size_t)table & 0xfff0)
  186117. {
  186118. #ifndef PNG_USER_MEM_SUPPORTED
  186119. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186120. png_error(png_ptr,
  186121. "Farmalloc didn't return normalized pointer");
  186122. else
  186123. png_warning(png_ptr,
  186124. "Farmalloc didn't return normalized pointer");
  186125. #endif
  186126. return (NULL);
  186127. }
  186128. png_ptr->offset_table = table;
  186129. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186130. png_sizeof (png_bytep));
  186131. if (png_ptr->offset_table_ptr == NULL)
  186132. {
  186133. #ifndef PNG_USER_MEM_SUPPORTED
  186134. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186135. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186136. else
  186137. png_warning(png_ptr, "Out Of memory.");
  186138. #endif
  186139. return (NULL);
  186140. }
  186141. hptr = (png_byte huge *)table;
  186142. if ((png_size_t)hptr & 0xf)
  186143. {
  186144. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186145. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186146. }
  186147. for (i = 0; i < num_blocks; i++)
  186148. {
  186149. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186150. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186151. }
  186152. png_ptr->offset_table_number = num_blocks;
  186153. png_ptr->offset_table_count = 0;
  186154. png_ptr->offset_table_count_free = 0;
  186155. }
  186156. }
  186157. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186158. {
  186159. #ifndef PNG_USER_MEM_SUPPORTED
  186160. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186161. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186162. else
  186163. png_warning(png_ptr, "Out of Memory.");
  186164. #endif
  186165. return (NULL);
  186166. }
  186167. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186168. }
  186169. else
  186170. ret = farmalloc(size);
  186171. #ifndef PNG_USER_MEM_SUPPORTED
  186172. if (ret == NULL)
  186173. {
  186174. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186175. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186176. else
  186177. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186178. }
  186179. #endif
  186180. return (ret);
  186181. }
  186182. /* free a pointer allocated by png_malloc(). In the default
  186183. configuration, png_ptr is not used, but is passed in case it
  186184. is needed. If ptr is NULL, return without taking any action. */
  186185. void PNGAPI
  186186. png_free(png_structp png_ptr, png_voidp ptr)
  186187. {
  186188. if (png_ptr == NULL || ptr == NULL)
  186189. return;
  186190. #ifdef PNG_USER_MEM_SUPPORTED
  186191. if (png_ptr->free_fn != NULL)
  186192. {
  186193. (*(png_ptr->free_fn))(png_ptr, ptr);
  186194. return;
  186195. }
  186196. else png_free_default(png_ptr, ptr);
  186197. }
  186198. void PNGAPI
  186199. png_free_default(png_structp png_ptr, png_voidp ptr)
  186200. {
  186201. #endif /* PNG_USER_MEM_SUPPORTED */
  186202. if(png_ptr == NULL) return;
  186203. if (png_ptr->offset_table != NULL)
  186204. {
  186205. int i;
  186206. for (i = 0; i < png_ptr->offset_table_count; i++)
  186207. {
  186208. if (ptr == png_ptr->offset_table_ptr[i])
  186209. {
  186210. ptr = NULL;
  186211. png_ptr->offset_table_count_free++;
  186212. break;
  186213. }
  186214. }
  186215. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186216. {
  186217. farfree(png_ptr->offset_table);
  186218. farfree(png_ptr->offset_table_ptr);
  186219. png_ptr->offset_table = NULL;
  186220. png_ptr->offset_table_ptr = NULL;
  186221. }
  186222. }
  186223. if (ptr != NULL)
  186224. {
  186225. farfree(ptr);
  186226. }
  186227. }
  186228. #else /* Not the Borland DOS special memory handler */
  186229. /* Allocate memory for a png_struct or a png_info. The malloc and
  186230. memset can be replaced by a single call to calloc() if this is thought
  186231. to improve performance noticably. */
  186232. png_voidp /* PRIVATE */
  186233. png_create_struct(int type)
  186234. {
  186235. #ifdef PNG_USER_MEM_SUPPORTED
  186236. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186237. }
  186238. /* Allocate memory for a png_struct or a png_info. The malloc and
  186239. memset can be replaced by a single call to calloc() if this is thought
  186240. to improve performance noticably. */
  186241. png_voidp /* PRIVATE */
  186242. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186243. {
  186244. #endif /* PNG_USER_MEM_SUPPORTED */
  186245. png_size_t size;
  186246. png_voidp struct_ptr;
  186247. if (type == PNG_STRUCT_INFO)
  186248. size = png_sizeof(png_info);
  186249. else if (type == PNG_STRUCT_PNG)
  186250. size = png_sizeof(png_struct);
  186251. else
  186252. return (NULL);
  186253. #ifdef PNG_USER_MEM_SUPPORTED
  186254. if(malloc_fn != NULL)
  186255. {
  186256. png_struct dummy_struct;
  186257. png_structp png_ptr = &dummy_struct;
  186258. png_ptr->mem_ptr=mem_ptr;
  186259. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186260. if (struct_ptr != NULL)
  186261. png_memset(struct_ptr, 0, size);
  186262. return (struct_ptr);
  186263. }
  186264. #endif /* PNG_USER_MEM_SUPPORTED */
  186265. #if defined(__TURBOC__) && !defined(__FLAT__)
  186266. struct_ptr = (png_voidp)farmalloc(size);
  186267. #else
  186268. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186269. struct_ptr = (png_voidp)halloc(size,1);
  186270. # else
  186271. struct_ptr = (png_voidp)malloc(size);
  186272. # endif
  186273. #endif
  186274. if (struct_ptr != NULL)
  186275. png_memset(struct_ptr, 0, size);
  186276. return (struct_ptr);
  186277. }
  186278. /* Free memory allocated by a png_create_struct() call */
  186279. void /* PRIVATE */
  186280. png_destroy_struct(png_voidp struct_ptr)
  186281. {
  186282. #ifdef PNG_USER_MEM_SUPPORTED
  186283. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186284. }
  186285. /* Free memory allocated by a png_create_struct() call */
  186286. void /* PRIVATE */
  186287. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186288. png_voidp mem_ptr)
  186289. {
  186290. #endif /* PNG_USER_MEM_SUPPORTED */
  186291. if (struct_ptr != NULL)
  186292. {
  186293. #ifdef PNG_USER_MEM_SUPPORTED
  186294. if(free_fn != NULL)
  186295. {
  186296. png_struct dummy_struct;
  186297. png_structp png_ptr = &dummy_struct;
  186298. png_ptr->mem_ptr=mem_ptr;
  186299. (*(free_fn))(png_ptr, struct_ptr);
  186300. return;
  186301. }
  186302. #endif /* PNG_USER_MEM_SUPPORTED */
  186303. #if defined(__TURBOC__) && !defined(__FLAT__)
  186304. farfree(struct_ptr);
  186305. #else
  186306. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186307. hfree(struct_ptr);
  186308. # else
  186309. free(struct_ptr);
  186310. # endif
  186311. #endif
  186312. }
  186313. }
  186314. /* Allocate memory. For reasonable files, size should never exceed
  186315. 64K. However, zlib may allocate more then 64K if you don't tell
  186316. it not to. See zconf.h and png.h for more information. zlib does
  186317. need to allocate exactly 64K, so whatever you call here must
  186318. have the ability to do that. */
  186319. png_voidp PNGAPI
  186320. png_malloc(png_structp png_ptr, png_uint_32 size)
  186321. {
  186322. png_voidp ret;
  186323. #ifdef PNG_USER_MEM_SUPPORTED
  186324. if (png_ptr == NULL || size == 0)
  186325. return (NULL);
  186326. if(png_ptr->malloc_fn != NULL)
  186327. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186328. else
  186329. ret = (png_malloc_default(png_ptr, size));
  186330. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186331. png_error(png_ptr, "Out of Memory!");
  186332. return (ret);
  186333. }
  186334. png_voidp PNGAPI
  186335. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186336. {
  186337. png_voidp ret;
  186338. #endif /* PNG_USER_MEM_SUPPORTED */
  186339. if (png_ptr == NULL || size == 0)
  186340. return (NULL);
  186341. #ifdef PNG_MAX_MALLOC_64K
  186342. if (size > (png_uint_32)65536L)
  186343. {
  186344. #ifndef PNG_USER_MEM_SUPPORTED
  186345. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186346. png_error(png_ptr, "Cannot Allocate > 64K");
  186347. else
  186348. #endif
  186349. return NULL;
  186350. }
  186351. #endif
  186352. /* Check for overflow */
  186353. #if defined(__TURBOC__) && !defined(__FLAT__)
  186354. if (size != (unsigned long)size)
  186355. ret = NULL;
  186356. else
  186357. ret = farmalloc(size);
  186358. #else
  186359. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186360. if (size != (unsigned long)size)
  186361. ret = NULL;
  186362. else
  186363. ret = halloc(size, 1);
  186364. # else
  186365. if (size != (size_t)size)
  186366. ret = NULL;
  186367. else
  186368. ret = malloc((size_t)size);
  186369. # endif
  186370. #endif
  186371. #ifndef PNG_USER_MEM_SUPPORTED
  186372. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186373. png_error(png_ptr, "Out of Memory");
  186374. #endif
  186375. return (ret);
  186376. }
  186377. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186378. without taking any action. */
  186379. void PNGAPI
  186380. png_free(png_structp png_ptr, png_voidp ptr)
  186381. {
  186382. if (png_ptr == NULL || ptr == NULL)
  186383. return;
  186384. #ifdef PNG_USER_MEM_SUPPORTED
  186385. if (png_ptr->free_fn != NULL)
  186386. {
  186387. (*(png_ptr->free_fn))(png_ptr, ptr);
  186388. return;
  186389. }
  186390. else png_free_default(png_ptr, ptr);
  186391. }
  186392. void PNGAPI
  186393. png_free_default(png_structp png_ptr, png_voidp ptr)
  186394. {
  186395. if (png_ptr == NULL || ptr == NULL)
  186396. return;
  186397. #endif /* PNG_USER_MEM_SUPPORTED */
  186398. #if defined(__TURBOC__) && !defined(__FLAT__)
  186399. farfree(ptr);
  186400. #else
  186401. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186402. hfree(ptr);
  186403. # else
  186404. free(ptr);
  186405. # endif
  186406. #endif
  186407. }
  186408. #endif /* Not Borland DOS special memory handler */
  186409. #if defined(PNG_1_0_X)
  186410. # define png_malloc_warn png_malloc
  186411. #else
  186412. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  186413. * function will set up png_malloc() to issue a png_warning and return NULL
  186414. * instead of issuing a png_error, if it fails to allocate the requested
  186415. * memory.
  186416. */
  186417. png_voidp PNGAPI
  186418. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  186419. {
  186420. png_voidp ptr;
  186421. png_uint_32 save_flags;
  186422. if(png_ptr == NULL) return (NULL);
  186423. save_flags=png_ptr->flags;
  186424. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  186425. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  186426. png_ptr->flags=save_flags;
  186427. return(ptr);
  186428. }
  186429. #endif
  186430. png_voidp PNGAPI
  186431. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  186432. png_uint_32 length)
  186433. {
  186434. png_size_t size;
  186435. size = (png_size_t)length;
  186436. if ((png_uint_32)size != length)
  186437. png_error(png_ptr,"Overflow in png_memcpy_check.");
  186438. return(png_memcpy (s1, s2, size));
  186439. }
  186440. png_voidp PNGAPI
  186441. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  186442. png_uint_32 length)
  186443. {
  186444. png_size_t size;
  186445. size = (png_size_t)length;
  186446. if ((png_uint_32)size != length)
  186447. png_error(png_ptr,"Overflow in png_memset_check.");
  186448. return (png_memset (s1, value, size));
  186449. }
  186450. #ifdef PNG_USER_MEM_SUPPORTED
  186451. /* This function is called when the application wants to use another method
  186452. * of allocating and freeing memory.
  186453. */
  186454. void PNGAPI
  186455. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  186456. malloc_fn, png_free_ptr free_fn)
  186457. {
  186458. if(png_ptr != NULL) {
  186459. png_ptr->mem_ptr = mem_ptr;
  186460. png_ptr->malloc_fn = malloc_fn;
  186461. png_ptr->free_fn = free_fn;
  186462. }
  186463. }
  186464. /* This function returns a pointer to the mem_ptr associated with the user
  186465. * functions. The application should free any memory associated with this
  186466. * pointer before png_write_destroy and png_read_destroy are called.
  186467. */
  186468. png_voidp PNGAPI
  186469. png_get_mem_ptr(png_structp png_ptr)
  186470. {
  186471. if(png_ptr == NULL) return (NULL);
  186472. return ((png_voidp)png_ptr->mem_ptr);
  186473. }
  186474. #endif /* PNG_USER_MEM_SUPPORTED */
  186475. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186476. /*** End of inlined file: pngmem.c ***/
  186477. /*** Start of inlined file: pngread.c ***/
  186478. /* pngread.c - read a PNG file
  186479. *
  186480. * Last changed in libpng 1.2.20 September 7, 2007
  186481. * For conditions of distribution and use, see copyright notice in png.h
  186482. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186483. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186484. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186485. *
  186486. * This file contains routines that an application calls directly to
  186487. * read a PNG file or stream.
  186488. */
  186489. #define PNG_INTERNAL
  186490. #if defined(PNG_READ_SUPPORTED)
  186491. /* Create a PNG structure for reading, and allocate any memory needed. */
  186492. png_structp PNGAPI
  186493. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  186494. png_error_ptr error_fn, png_error_ptr warn_fn)
  186495. {
  186496. #ifdef PNG_USER_MEM_SUPPORTED
  186497. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  186498. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  186499. }
  186500. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  186501. png_structp PNGAPI
  186502. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  186503. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  186504. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  186505. {
  186506. #endif /* PNG_USER_MEM_SUPPORTED */
  186507. png_structp png_ptr;
  186508. #ifdef PNG_SETJMP_SUPPORTED
  186509. #ifdef USE_FAR_KEYWORD
  186510. jmp_buf jmpbuf;
  186511. #endif
  186512. #endif
  186513. int i;
  186514. png_debug(1, "in png_create_read_struct\n");
  186515. #ifdef PNG_USER_MEM_SUPPORTED
  186516. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  186517. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  186518. #else
  186519. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186520. #endif
  186521. if (png_ptr == NULL)
  186522. return (NULL);
  186523. /* added at libpng-1.2.6 */
  186524. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186525. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186526. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186527. #endif
  186528. #ifdef PNG_SETJMP_SUPPORTED
  186529. #ifdef USE_FAR_KEYWORD
  186530. if (setjmp(jmpbuf))
  186531. #else
  186532. if (setjmp(png_ptr->jmpbuf))
  186533. #endif
  186534. {
  186535. png_free(png_ptr, png_ptr->zbuf);
  186536. png_ptr->zbuf=NULL;
  186537. #ifdef PNG_USER_MEM_SUPPORTED
  186538. png_destroy_struct_2((png_voidp)png_ptr,
  186539. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  186540. #else
  186541. png_destroy_struct((png_voidp)png_ptr);
  186542. #endif
  186543. return (NULL);
  186544. }
  186545. #ifdef USE_FAR_KEYWORD
  186546. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186547. #endif
  186548. #endif
  186549. #ifdef PNG_USER_MEM_SUPPORTED
  186550. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  186551. #endif
  186552. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  186553. i=0;
  186554. do
  186555. {
  186556. if(user_png_ver[i] != png_libpng_ver[i])
  186557. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186558. } while (png_libpng_ver[i++]);
  186559. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  186560. {
  186561. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  186562. * we must recompile any applications that use any older library version.
  186563. * For versions after libpng 1.0, we will be compatible, so we need
  186564. * only check the first digit.
  186565. */
  186566. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  186567. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  186568. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  186569. {
  186570. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186571. char msg[80];
  186572. if (user_png_ver)
  186573. {
  186574. png_snprintf(msg, 80,
  186575. "Application was compiled with png.h from libpng-%.20s",
  186576. user_png_ver);
  186577. png_warning(png_ptr, msg);
  186578. }
  186579. png_snprintf(msg, 80,
  186580. "Application is running with png.c from libpng-%.20s",
  186581. png_libpng_ver);
  186582. png_warning(png_ptr, msg);
  186583. #endif
  186584. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186585. png_ptr->flags=0;
  186586. #endif
  186587. png_error(png_ptr,
  186588. "Incompatible libpng version in application and library");
  186589. }
  186590. }
  186591. /* initialize zbuf - compression buffer */
  186592. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186593. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186594. (png_uint_32)png_ptr->zbuf_size);
  186595. png_ptr->zstream.zalloc = png_zalloc;
  186596. png_ptr->zstream.zfree = png_zfree;
  186597. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186598. switch (inflateInit(&png_ptr->zstream))
  186599. {
  186600. case Z_OK: /* Do nothing */ break;
  186601. case Z_MEM_ERROR:
  186602. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  186603. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  186604. default: png_error(png_ptr, "Unknown zlib error");
  186605. }
  186606. png_ptr->zstream.next_out = png_ptr->zbuf;
  186607. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186608. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186609. #ifdef PNG_SETJMP_SUPPORTED
  186610. /* Applications that neglect to set up their own setjmp() and then encounter
  186611. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  186612. abort instead of returning. */
  186613. #ifdef USE_FAR_KEYWORD
  186614. if (setjmp(jmpbuf))
  186615. PNG_ABORT();
  186616. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186617. #else
  186618. if (setjmp(png_ptr->jmpbuf))
  186619. PNG_ABORT();
  186620. #endif
  186621. #endif
  186622. return (png_ptr);
  186623. }
  186624. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  186625. /* Initialize PNG structure for reading, and allocate any memory needed.
  186626. This interface is deprecated in favour of the png_create_read_struct(),
  186627. and it will disappear as of libpng-1.3.0. */
  186628. #undef png_read_init
  186629. void PNGAPI
  186630. png_read_init(png_structp png_ptr)
  186631. {
  186632. /* We only come here via pre-1.0.7-compiled applications */
  186633. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  186634. }
  186635. void PNGAPI
  186636. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  186637. png_size_t png_struct_size, png_size_t png_info_size)
  186638. {
  186639. /* We only come here via pre-1.0.12-compiled applications */
  186640. if(png_ptr == NULL) return;
  186641. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186642. if(png_sizeof(png_struct) > png_struct_size ||
  186643. png_sizeof(png_info) > png_info_size)
  186644. {
  186645. char msg[80];
  186646. png_ptr->warning_fn=NULL;
  186647. if (user_png_ver)
  186648. {
  186649. png_snprintf(msg, 80,
  186650. "Application was compiled with png.h from libpng-%.20s",
  186651. user_png_ver);
  186652. png_warning(png_ptr, msg);
  186653. }
  186654. png_snprintf(msg, 80,
  186655. "Application is running with png.c from libpng-%.20s",
  186656. png_libpng_ver);
  186657. png_warning(png_ptr, msg);
  186658. }
  186659. #endif
  186660. if(png_sizeof(png_struct) > png_struct_size)
  186661. {
  186662. png_ptr->error_fn=NULL;
  186663. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186664. png_ptr->flags=0;
  186665. #endif
  186666. png_error(png_ptr,
  186667. "The png struct allocated by the application for reading is too small.");
  186668. }
  186669. if(png_sizeof(png_info) > png_info_size)
  186670. {
  186671. png_ptr->error_fn=NULL;
  186672. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186673. png_ptr->flags=0;
  186674. #endif
  186675. png_error(png_ptr,
  186676. "The info struct allocated by application for reading is too small.");
  186677. }
  186678. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  186679. }
  186680. #endif /* PNG_1_0_X || PNG_1_2_X */
  186681. void PNGAPI
  186682. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  186683. png_size_t png_struct_size)
  186684. {
  186685. #ifdef PNG_SETJMP_SUPPORTED
  186686. jmp_buf tmp_jmp; /* to save current jump buffer */
  186687. #endif
  186688. int i=0;
  186689. png_structp png_ptr=*ptr_ptr;
  186690. if(png_ptr == NULL) return;
  186691. do
  186692. {
  186693. if(user_png_ver[i] != png_libpng_ver[i])
  186694. {
  186695. #ifdef PNG_LEGACY_SUPPORTED
  186696. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186697. #else
  186698. png_ptr->warning_fn=NULL;
  186699. png_warning(png_ptr,
  186700. "Application uses deprecated png_read_init() and should be recompiled.");
  186701. break;
  186702. #endif
  186703. }
  186704. } while (png_libpng_ver[i++]);
  186705. png_debug(1, "in png_read_init_3\n");
  186706. #ifdef PNG_SETJMP_SUPPORTED
  186707. /* save jump buffer and error functions */
  186708. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  186709. #endif
  186710. if(png_sizeof(png_struct) > png_struct_size)
  186711. {
  186712. png_destroy_struct(png_ptr);
  186713. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186714. png_ptr = *ptr_ptr;
  186715. }
  186716. /* reset all variables to 0 */
  186717. png_memset(png_ptr, 0, png_sizeof (png_struct));
  186718. #ifdef PNG_SETJMP_SUPPORTED
  186719. /* restore jump buffer */
  186720. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  186721. #endif
  186722. /* added at libpng-1.2.6 */
  186723. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186724. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186725. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186726. #endif
  186727. /* initialize zbuf - compression buffer */
  186728. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186729. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186730. (png_uint_32)png_ptr->zbuf_size);
  186731. png_ptr->zstream.zalloc = png_zalloc;
  186732. png_ptr->zstream.zfree = png_zfree;
  186733. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186734. switch (inflateInit(&png_ptr->zstream))
  186735. {
  186736. case Z_OK: /* Do nothing */ break;
  186737. case Z_MEM_ERROR:
  186738. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  186739. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  186740. default: png_error(png_ptr, "Unknown zlib error");
  186741. }
  186742. png_ptr->zstream.next_out = png_ptr->zbuf;
  186743. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186744. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186745. }
  186746. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186747. /* Read the information before the actual image data. This has been
  186748. * changed in v0.90 to allow reading a file that already has the magic
  186749. * bytes read from the stream. You can tell libpng how many bytes have
  186750. * been read from the beginning of the stream (up to the maximum of 8)
  186751. * via png_set_sig_bytes(), and we will only check the remaining bytes
  186752. * here. The application can then have access to the signature bytes we
  186753. * read if it is determined that this isn't a valid PNG file.
  186754. */
  186755. void PNGAPI
  186756. png_read_info(png_structp png_ptr, png_infop info_ptr)
  186757. {
  186758. if(png_ptr == NULL) return;
  186759. png_debug(1, "in png_read_info\n");
  186760. /* If we haven't checked all of the PNG signature bytes, do so now. */
  186761. if (png_ptr->sig_bytes < 8)
  186762. {
  186763. png_size_t num_checked = png_ptr->sig_bytes,
  186764. num_to_check = 8 - num_checked;
  186765. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  186766. png_ptr->sig_bytes = 8;
  186767. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  186768. {
  186769. if (num_checked < 4 &&
  186770. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  186771. png_error(png_ptr, "Not a PNG file");
  186772. else
  186773. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  186774. }
  186775. if (num_checked < 3)
  186776. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  186777. }
  186778. for(;;)
  186779. {
  186780. #ifdef PNG_USE_LOCAL_ARRAYS
  186781. PNG_CONST PNG_IHDR;
  186782. PNG_CONST PNG_IDAT;
  186783. PNG_CONST PNG_IEND;
  186784. PNG_CONST PNG_PLTE;
  186785. #if defined(PNG_READ_bKGD_SUPPORTED)
  186786. PNG_CONST PNG_bKGD;
  186787. #endif
  186788. #if defined(PNG_READ_cHRM_SUPPORTED)
  186789. PNG_CONST PNG_cHRM;
  186790. #endif
  186791. #if defined(PNG_READ_gAMA_SUPPORTED)
  186792. PNG_CONST PNG_gAMA;
  186793. #endif
  186794. #if defined(PNG_READ_hIST_SUPPORTED)
  186795. PNG_CONST PNG_hIST;
  186796. #endif
  186797. #if defined(PNG_READ_iCCP_SUPPORTED)
  186798. PNG_CONST PNG_iCCP;
  186799. #endif
  186800. #if defined(PNG_READ_iTXt_SUPPORTED)
  186801. PNG_CONST PNG_iTXt;
  186802. #endif
  186803. #if defined(PNG_READ_oFFs_SUPPORTED)
  186804. PNG_CONST PNG_oFFs;
  186805. #endif
  186806. #if defined(PNG_READ_pCAL_SUPPORTED)
  186807. PNG_CONST PNG_pCAL;
  186808. #endif
  186809. #if defined(PNG_READ_pHYs_SUPPORTED)
  186810. PNG_CONST PNG_pHYs;
  186811. #endif
  186812. #if defined(PNG_READ_sBIT_SUPPORTED)
  186813. PNG_CONST PNG_sBIT;
  186814. #endif
  186815. #if defined(PNG_READ_sCAL_SUPPORTED)
  186816. PNG_CONST PNG_sCAL;
  186817. #endif
  186818. #if defined(PNG_READ_sPLT_SUPPORTED)
  186819. PNG_CONST PNG_sPLT;
  186820. #endif
  186821. #if defined(PNG_READ_sRGB_SUPPORTED)
  186822. PNG_CONST PNG_sRGB;
  186823. #endif
  186824. #if defined(PNG_READ_tEXt_SUPPORTED)
  186825. PNG_CONST PNG_tEXt;
  186826. #endif
  186827. #if defined(PNG_READ_tIME_SUPPORTED)
  186828. PNG_CONST PNG_tIME;
  186829. #endif
  186830. #if defined(PNG_READ_tRNS_SUPPORTED)
  186831. PNG_CONST PNG_tRNS;
  186832. #endif
  186833. #if defined(PNG_READ_zTXt_SUPPORTED)
  186834. PNG_CONST PNG_zTXt;
  186835. #endif
  186836. #endif /* PNG_USE_LOCAL_ARRAYS */
  186837. png_byte chunk_length[4];
  186838. png_uint_32 length;
  186839. png_read_data(png_ptr, chunk_length, 4);
  186840. length = png_get_uint_31(png_ptr,chunk_length);
  186841. png_reset_crc(png_ptr);
  186842. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  186843. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  186844. length);
  186845. /* This should be a binary subdivision search or a hash for
  186846. * matching the chunk name rather than a linear search.
  186847. */
  186848. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186849. if(png_ptr->mode & PNG_AFTER_IDAT)
  186850. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  186851. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  186852. png_handle_IHDR(png_ptr, info_ptr, length);
  186853. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  186854. png_handle_IEND(png_ptr, info_ptr, length);
  186855. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  186856. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  186857. {
  186858. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186859. png_ptr->mode |= PNG_HAVE_IDAT;
  186860. png_handle_unknown(png_ptr, info_ptr, length);
  186861. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  186862. png_ptr->mode |= PNG_HAVE_PLTE;
  186863. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186864. {
  186865. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  186866. png_error(png_ptr, "Missing IHDR before IDAT");
  186867. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  186868. !(png_ptr->mode & PNG_HAVE_PLTE))
  186869. png_error(png_ptr, "Missing PLTE before IDAT");
  186870. break;
  186871. }
  186872. }
  186873. #endif
  186874. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  186875. png_handle_PLTE(png_ptr, info_ptr, length);
  186876. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186877. {
  186878. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  186879. png_error(png_ptr, "Missing IHDR before IDAT");
  186880. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  186881. !(png_ptr->mode & PNG_HAVE_PLTE))
  186882. png_error(png_ptr, "Missing PLTE before IDAT");
  186883. png_ptr->idat_size = length;
  186884. png_ptr->mode |= PNG_HAVE_IDAT;
  186885. break;
  186886. }
  186887. #if defined(PNG_READ_bKGD_SUPPORTED)
  186888. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  186889. png_handle_bKGD(png_ptr, info_ptr, length);
  186890. #endif
  186891. #if defined(PNG_READ_cHRM_SUPPORTED)
  186892. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  186893. png_handle_cHRM(png_ptr, info_ptr, length);
  186894. #endif
  186895. #if defined(PNG_READ_gAMA_SUPPORTED)
  186896. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  186897. png_handle_gAMA(png_ptr, info_ptr, length);
  186898. #endif
  186899. #if defined(PNG_READ_hIST_SUPPORTED)
  186900. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  186901. png_handle_hIST(png_ptr, info_ptr, length);
  186902. #endif
  186903. #if defined(PNG_READ_oFFs_SUPPORTED)
  186904. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  186905. png_handle_oFFs(png_ptr, info_ptr, length);
  186906. #endif
  186907. #if defined(PNG_READ_pCAL_SUPPORTED)
  186908. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  186909. png_handle_pCAL(png_ptr, info_ptr, length);
  186910. #endif
  186911. #if defined(PNG_READ_sCAL_SUPPORTED)
  186912. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  186913. png_handle_sCAL(png_ptr, info_ptr, length);
  186914. #endif
  186915. #if defined(PNG_READ_pHYs_SUPPORTED)
  186916. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  186917. png_handle_pHYs(png_ptr, info_ptr, length);
  186918. #endif
  186919. #if defined(PNG_READ_sBIT_SUPPORTED)
  186920. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  186921. png_handle_sBIT(png_ptr, info_ptr, length);
  186922. #endif
  186923. #if defined(PNG_READ_sRGB_SUPPORTED)
  186924. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  186925. png_handle_sRGB(png_ptr, info_ptr, length);
  186926. #endif
  186927. #if defined(PNG_READ_iCCP_SUPPORTED)
  186928. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  186929. png_handle_iCCP(png_ptr, info_ptr, length);
  186930. #endif
  186931. #if defined(PNG_READ_sPLT_SUPPORTED)
  186932. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  186933. png_handle_sPLT(png_ptr, info_ptr, length);
  186934. #endif
  186935. #if defined(PNG_READ_tEXt_SUPPORTED)
  186936. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  186937. png_handle_tEXt(png_ptr, info_ptr, length);
  186938. #endif
  186939. #if defined(PNG_READ_tIME_SUPPORTED)
  186940. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  186941. png_handle_tIME(png_ptr, info_ptr, length);
  186942. #endif
  186943. #if defined(PNG_READ_tRNS_SUPPORTED)
  186944. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  186945. png_handle_tRNS(png_ptr, info_ptr, length);
  186946. #endif
  186947. #if defined(PNG_READ_zTXt_SUPPORTED)
  186948. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  186949. png_handle_zTXt(png_ptr, info_ptr, length);
  186950. #endif
  186951. #if defined(PNG_READ_iTXt_SUPPORTED)
  186952. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  186953. png_handle_iTXt(png_ptr, info_ptr, length);
  186954. #endif
  186955. else
  186956. png_handle_unknown(png_ptr, info_ptr, length);
  186957. }
  186958. }
  186959. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186960. /* optional call to update the users info_ptr structure */
  186961. void PNGAPI
  186962. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  186963. {
  186964. png_debug(1, "in png_read_update_info\n");
  186965. if(png_ptr == NULL) return;
  186966. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186967. png_read_start_row(png_ptr);
  186968. else
  186969. png_warning(png_ptr,
  186970. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  186971. png_read_transform_info(png_ptr, info_ptr);
  186972. }
  186973. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186974. /* Initialize palette, background, etc, after transformations
  186975. * are set, but before any reading takes place. This allows
  186976. * the user to obtain a gamma-corrected palette, for example.
  186977. * If the user doesn't call this, we will do it ourselves.
  186978. */
  186979. void PNGAPI
  186980. png_start_read_image(png_structp png_ptr)
  186981. {
  186982. png_debug(1, "in png_start_read_image\n");
  186983. if(png_ptr == NULL) return;
  186984. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186985. png_read_start_row(png_ptr);
  186986. }
  186987. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186988. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186989. void PNGAPI
  186990. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  186991. {
  186992. #ifdef PNG_USE_LOCAL_ARRAYS
  186993. PNG_CONST PNG_IDAT;
  186994. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  186995. 0xff};
  186996. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  186997. #endif
  186998. int ret;
  186999. if(png_ptr == NULL) return;
  187000. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187001. png_ptr->row_number, png_ptr->pass);
  187002. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187003. png_read_start_row(png_ptr);
  187004. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187005. {
  187006. /* check for transforms that have been set but were defined out */
  187007. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187008. if (png_ptr->transformations & PNG_INVERT_MONO)
  187009. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187010. #endif
  187011. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187012. if (png_ptr->transformations & PNG_FILLER)
  187013. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187014. #endif
  187015. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187016. if (png_ptr->transformations & PNG_PACKSWAP)
  187017. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187018. #endif
  187019. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187020. if (png_ptr->transformations & PNG_PACK)
  187021. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187022. #endif
  187023. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187024. if (png_ptr->transformations & PNG_SHIFT)
  187025. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187026. #endif
  187027. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187028. if (png_ptr->transformations & PNG_BGR)
  187029. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187030. #endif
  187031. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187032. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187033. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187034. #endif
  187035. }
  187036. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187037. /* if interlaced and we do not need a new row, combine row and return */
  187038. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187039. {
  187040. switch (png_ptr->pass)
  187041. {
  187042. case 0:
  187043. if (png_ptr->row_number & 0x07)
  187044. {
  187045. if (dsp_row != NULL)
  187046. png_combine_row(png_ptr, dsp_row,
  187047. png_pass_dsp_mask[png_ptr->pass]);
  187048. png_read_finish_row(png_ptr);
  187049. return;
  187050. }
  187051. break;
  187052. case 1:
  187053. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187054. {
  187055. if (dsp_row != NULL)
  187056. png_combine_row(png_ptr, dsp_row,
  187057. png_pass_dsp_mask[png_ptr->pass]);
  187058. png_read_finish_row(png_ptr);
  187059. return;
  187060. }
  187061. break;
  187062. case 2:
  187063. if ((png_ptr->row_number & 0x07) != 4)
  187064. {
  187065. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187066. png_combine_row(png_ptr, dsp_row,
  187067. png_pass_dsp_mask[png_ptr->pass]);
  187068. png_read_finish_row(png_ptr);
  187069. return;
  187070. }
  187071. break;
  187072. case 3:
  187073. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187074. {
  187075. if (dsp_row != NULL)
  187076. png_combine_row(png_ptr, dsp_row,
  187077. png_pass_dsp_mask[png_ptr->pass]);
  187078. png_read_finish_row(png_ptr);
  187079. return;
  187080. }
  187081. break;
  187082. case 4:
  187083. if ((png_ptr->row_number & 3) != 2)
  187084. {
  187085. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187086. png_combine_row(png_ptr, dsp_row,
  187087. png_pass_dsp_mask[png_ptr->pass]);
  187088. png_read_finish_row(png_ptr);
  187089. return;
  187090. }
  187091. break;
  187092. case 5:
  187093. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187094. {
  187095. if (dsp_row != NULL)
  187096. png_combine_row(png_ptr, dsp_row,
  187097. png_pass_dsp_mask[png_ptr->pass]);
  187098. png_read_finish_row(png_ptr);
  187099. return;
  187100. }
  187101. break;
  187102. case 6:
  187103. if (!(png_ptr->row_number & 1))
  187104. {
  187105. png_read_finish_row(png_ptr);
  187106. return;
  187107. }
  187108. break;
  187109. }
  187110. }
  187111. #endif
  187112. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187113. png_error(png_ptr, "Invalid attempt to read row data");
  187114. png_ptr->zstream.next_out = png_ptr->row_buf;
  187115. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187116. do
  187117. {
  187118. if (!(png_ptr->zstream.avail_in))
  187119. {
  187120. while (!png_ptr->idat_size)
  187121. {
  187122. png_byte chunk_length[4];
  187123. png_crc_finish(png_ptr, 0);
  187124. png_read_data(png_ptr, chunk_length, 4);
  187125. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187126. png_reset_crc(png_ptr);
  187127. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187128. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187129. png_error(png_ptr, "Not enough image data");
  187130. }
  187131. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187132. png_ptr->zstream.next_in = png_ptr->zbuf;
  187133. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187134. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187135. png_crc_read(png_ptr, png_ptr->zbuf,
  187136. (png_size_t)png_ptr->zstream.avail_in);
  187137. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187138. }
  187139. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187140. if (ret == Z_STREAM_END)
  187141. {
  187142. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187143. png_ptr->idat_size)
  187144. png_error(png_ptr, "Extra compressed data");
  187145. png_ptr->mode |= PNG_AFTER_IDAT;
  187146. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187147. break;
  187148. }
  187149. if (ret != Z_OK)
  187150. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187151. "Decompression error");
  187152. } while (png_ptr->zstream.avail_out);
  187153. png_ptr->row_info.color_type = png_ptr->color_type;
  187154. png_ptr->row_info.width = png_ptr->iwidth;
  187155. png_ptr->row_info.channels = png_ptr->channels;
  187156. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187157. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187158. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187159. png_ptr->row_info.width);
  187160. if(png_ptr->row_buf[0])
  187161. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187162. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187163. (int)(png_ptr->row_buf[0]));
  187164. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187165. png_ptr->rowbytes + 1);
  187166. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187167. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187168. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187169. {
  187170. /* Intrapixel differencing */
  187171. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187172. }
  187173. #endif
  187174. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187175. png_do_read_transformations(png_ptr);
  187176. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187177. /* blow up interlaced rows to full size */
  187178. if (png_ptr->interlaced &&
  187179. (png_ptr->transformations & PNG_INTERLACE))
  187180. {
  187181. if (png_ptr->pass < 6)
  187182. /* old interface (pre-1.0.9):
  187183. png_do_read_interlace(&(png_ptr->row_info),
  187184. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187185. */
  187186. png_do_read_interlace(png_ptr);
  187187. if (dsp_row != NULL)
  187188. png_combine_row(png_ptr, dsp_row,
  187189. png_pass_dsp_mask[png_ptr->pass]);
  187190. if (row != NULL)
  187191. png_combine_row(png_ptr, row,
  187192. png_pass_mask[png_ptr->pass]);
  187193. }
  187194. else
  187195. #endif
  187196. {
  187197. if (row != NULL)
  187198. png_combine_row(png_ptr, row, 0xff);
  187199. if (dsp_row != NULL)
  187200. png_combine_row(png_ptr, dsp_row, 0xff);
  187201. }
  187202. png_read_finish_row(png_ptr);
  187203. if (png_ptr->read_row_fn != NULL)
  187204. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187205. }
  187206. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187207. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187208. /* Read one or more rows of image data. If the image is interlaced,
  187209. * and png_set_interlace_handling() has been called, the rows need to
  187210. * contain the contents of the rows from the previous pass. If the
  187211. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187212. * called, the rows contents must be initialized to the contents of the
  187213. * screen.
  187214. *
  187215. * "row" holds the actual image, and pixels are placed in it
  187216. * as they arrive. If the image is displayed after each pass, it will
  187217. * appear to "sparkle" in. "display_row" can be used to display a
  187218. * "chunky" progressive image, with finer detail added as it becomes
  187219. * available. If you do not want this "chunky" display, you may pass
  187220. * NULL for display_row. If you do not want the sparkle display, and
  187221. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187222. * If you have called png_handle_alpha(), and the image has either an
  187223. * alpha channel or a transparency chunk, you must provide a buffer for
  187224. * rows. In this case, you do not have to provide a display_row buffer
  187225. * also, but you may. If the image is not interlaced, or if you have
  187226. * not called png_set_interlace_handling(), the display_row buffer will
  187227. * be ignored, so pass NULL to it.
  187228. *
  187229. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187230. */
  187231. void PNGAPI
  187232. png_read_rows(png_structp png_ptr, png_bytepp row,
  187233. png_bytepp display_row, png_uint_32 num_rows)
  187234. {
  187235. png_uint_32 i;
  187236. png_bytepp rp;
  187237. png_bytepp dp;
  187238. png_debug(1, "in png_read_rows\n");
  187239. if(png_ptr == NULL) return;
  187240. rp = row;
  187241. dp = display_row;
  187242. if (rp != NULL && dp != NULL)
  187243. for (i = 0; i < num_rows; i++)
  187244. {
  187245. png_bytep rptr = *rp++;
  187246. png_bytep dptr = *dp++;
  187247. png_read_row(png_ptr, rptr, dptr);
  187248. }
  187249. else if(rp != NULL)
  187250. for (i = 0; i < num_rows; i++)
  187251. {
  187252. png_bytep rptr = *rp;
  187253. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187254. rp++;
  187255. }
  187256. else if(dp != NULL)
  187257. for (i = 0; i < num_rows; i++)
  187258. {
  187259. png_bytep dptr = *dp;
  187260. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187261. dp++;
  187262. }
  187263. }
  187264. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187265. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187266. /* Read the entire image. If the image has an alpha channel or a tRNS
  187267. * chunk, and you have called png_handle_alpha()[*], you will need to
  187268. * initialize the image to the current image that PNG will be overlaying.
  187269. * We set the num_rows again here, in case it was incorrectly set in
  187270. * png_read_start_row() by a call to png_read_update_info() or
  187271. * png_start_read_image() if png_set_interlace_handling() wasn't called
  187272. * prior to either of these functions like it should have been. You can
  187273. * only call this function once. If you desire to have an image for
  187274. * each pass of a interlaced image, use png_read_rows() instead.
  187275. *
  187276. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187277. */
  187278. void PNGAPI
  187279. png_read_image(png_structp png_ptr, png_bytepp image)
  187280. {
  187281. png_uint_32 i,image_height;
  187282. int pass, j;
  187283. png_bytepp rp;
  187284. png_debug(1, "in png_read_image\n");
  187285. if(png_ptr == NULL) return;
  187286. #ifdef PNG_READ_INTERLACING_SUPPORTED
  187287. pass = png_set_interlace_handling(png_ptr);
  187288. #else
  187289. if (png_ptr->interlaced)
  187290. png_error(png_ptr,
  187291. "Cannot read interlaced image -- interlace handler disabled.");
  187292. pass = 1;
  187293. #endif
  187294. image_height=png_ptr->height;
  187295. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  187296. for (j = 0; j < pass; j++)
  187297. {
  187298. rp = image;
  187299. for (i = 0; i < image_height; i++)
  187300. {
  187301. png_read_row(png_ptr, *rp, png_bytep_NULL);
  187302. rp++;
  187303. }
  187304. }
  187305. }
  187306. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187307. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187308. /* Read the end of the PNG file. Will not read past the end of the
  187309. * file, will verify the end is accurate, and will read any comments
  187310. * or time information at the end of the file, if info is not NULL.
  187311. */
  187312. void PNGAPI
  187313. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187314. {
  187315. png_byte chunk_length[4];
  187316. png_uint_32 length;
  187317. png_debug(1, "in png_read_end\n");
  187318. if(png_ptr == NULL) return;
  187319. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187320. do
  187321. {
  187322. #ifdef PNG_USE_LOCAL_ARRAYS
  187323. PNG_CONST PNG_IHDR;
  187324. PNG_CONST PNG_IDAT;
  187325. PNG_CONST PNG_IEND;
  187326. PNG_CONST PNG_PLTE;
  187327. #if defined(PNG_READ_bKGD_SUPPORTED)
  187328. PNG_CONST PNG_bKGD;
  187329. #endif
  187330. #if defined(PNG_READ_cHRM_SUPPORTED)
  187331. PNG_CONST PNG_cHRM;
  187332. #endif
  187333. #if defined(PNG_READ_gAMA_SUPPORTED)
  187334. PNG_CONST PNG_gAMA;
  187335. #endif
  187336. #if defined(PNG_READ_hIST_SUPPORTED)
  187337. PNG_CONST PNG_hIST;
  187338. #endif
  187339. #if defined(PNG_READ_iCCP_SUPPORTED)
  187340. PNG_CONST PNG_iCCP;
  187341. #endif
  187342. #if defined(PNG_READ_iTXt_SUPPORTED)
  187343. PNG_CONST PNG_iTXt;
  187344. #endif
  187345. #if defined(PNG_READ_oFFs_SUPPORTED)
  187346. PNG_CONST PNG_oFFs;
  187347. #endif
  187348. #if defined(PNG_READ_pCAL_SUPPORTED)
  187349. PNG_CONST PNG_pCAL;
  187350. #endif
  187351. #if defined(PNG_READ_pHYs_SUPPORTED)
  187352. PNG_CONST PNG_pHYs;
  187353. #endif
  187354. #if defined(PNG_READ_sBIT_SUPPORTED)
  187355. PNG_CONST PNG_sBIT;
  187356. #endif
  187357. #if defined(PNG_READ_sCAL_SUPPORTED)
  187358. PNG_CONST PNG_sCAL;
  187359. #endif
  187360. #if defined(PNG_READ_sPLT_SUPPORTED)
  187361. PNG_CONST PNG_sPLT;
  187362. #endif
  187363. #if defined(PNG_READ_sRGB_SUPPORTED)
  187364. PNG_CONST PNG_sRGB;
  187365. #endif
  187366. #if defined(PNG_READ_tEXt_SUPPORTED)
  187367. PNG_CONST PNG_tEXt;
  187368. #endif
  187369. #if defined(PNG_READ_tIME_SUPPORTED)
  187370. PNG_CONST PNG_tIME;
  187371. #endif
  187372. #if defined(PNG_READ_tRNS_SUPPORTED)
  187373. PNG_CONST PNG_tRNS;
  187374. #endif
  187375. #if defined(PNG_READ_zTXt_SUPPORTED)
  187376. PNG_CONST PNG_zTXt;
  187377. #endif
  187378. #endif /* PNG_USE_LOCAL_ARRAYS */
  187379. png_read_data(png_ptr, chunk_length, 4);
  187380. length = png_get_uint_31(png_ptr,chunk_length);
  187381. png_reset_crc(png_ptr);
  187382. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187383. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  187384. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187385. png_handle_IHDR(png_ptr, info_ptr, length);
  187386. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187387. png_handle_IEND(png_ptr, info_ptr, length);
  187388. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187389. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187390. {
  187391. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187392. {
  187393. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187394. png_error(png_ptr, "Too many IDAT's found");
  187395. }
  187396. png_handle_unknown(png_ptr, info_ptr, length);
  187397. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187398. png_ptr->mode |= PNG_HAVE_PLTE;
  187399. }
  187400. #endif
  187401. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187402. {
  187403. /* Zero length IDATs are legal after the last IDAT has been
  187404. * read, but not after other chunks have been read.
  187405. */
  187406. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187407. png_error(png_ptr, "Too many IDAT's found");
  187408. png_crc_finish(png_ptr, length);
  187409. }
  187410. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187411. png_handle_PLTE(png_ptr, info_ptr, length);
  187412. #if defined(PNG_READ_bKGD_SUPPORTED)
  187413. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187414. png_handle_bKGD(png_ptr, info_ptr, length);
  187415. #endif
  187416. #if defined(PNG_READ_cHRM_SUPPORTED)
  187417. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187418. png_handle_cHRM(png_ptr, info_ptr, length);
  187419. #endif
  187420. #if defined(PNG_READ_gAMA_SUPPORTED)
  187421. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187422. png_handle_gAMA(png_ptr, info_ptr, length);
  187423. #endif
  187424. #if defined(PNG_READ_hIST_SUPPORTED)
  187425. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187426. png_handle_hIST(png_ptr, info_ptr, length);
  187427. #endif
  187428. #if defined(PNG_READ_oFFs_SUPPORTED)
  187429. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187430. png_handle_oFFs(png_ptr, info_ptr, length);
  187431. #endif
  187432. #if defined(PNG_READ_pCAL_SUPPORTED)
  187433. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187434. png_handle_pCAL(png_ptr, info_ptr, length);
  187435. #endif
  187436. #if defined(PNG_READ_sCAL_SUPPORTED)
  187437. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187438. png_handle_sCAL(png_ptr, info_ptr, length);
  187439. #endif
  187440. #if defined(PNG_READ_pHYs_SUPPORTED)
  187441. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187442. png_handle_pHYs(png_ptr, info_ptr, length);
  187443. #endif
  187444. #if defined(PNG_READ_sBIT_SUPPORTED)
  187445. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187446. png_handle_sBIT(png_ptr, info_ptr, length);
  187447. #endif
  187448. #if defined(PNG_READ_sRGB_SUPPORTED)
  187449. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187450. png_handle_sRGB(png_ptr, info_ptr, length);
  187451. #endif
  187452. #if defined(PNG_READ_iCCP_SUPPORTED)
  187453. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187454. png_handle_iCCP(png_ptr, info_ptr, length);
  187455. #endif
  187456. #if defined(PNG_READ_sPLT_SUPPORTED)
  187457. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187458. png_handle_sPLT(png_ptr, info_ptr, length);
  187459. #endif
  187460. #if defined(PNG_READ_tEXt_SUPPORTED)
  187461. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187462. png_handle_tEXt(png_ptr, info_ptr, length);
  187463. #endif
  187464. #if defined(PNG_READ_tIME_SUPPORTED)
  187465. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187466. png_handle_tIME(png_ptr, info_ptr, length);
  187467. #endif
  187468. #if defined(PNG_READ_tRNS_SUPPORTED)
  187469. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187470. png_handle_tRNS(png_ptr, info_ptr, length);
  187471. #endif
  187472. #if defined(PNG_READ_zTXt_SUPPORTED)
  187473. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187474. png_handle_zTXt(png_ptr, info_ptr, length);
  187475. #endif
  187476. #if defined(PNG_READ_iTXt_SUPPORTED)
  187477. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187478. png_handle_iTXt(png_ptr, info_ptr, length);
  187479. #endif
  187480. else
  187481. png_handle_unknown(png_ptr, info_ptr, length);
  187482. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  187483. }
  187484. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187485. /* free all memory used by the read */
  187486. void PNGAPI
  187487. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  187488. png_infopp end_info_ptr_ptr)
  187489. {
  187490. png_structp png_ptr = NULL;
  187491. png_infop info_ptr = NULL, end_info_ptr = NULL;
  187492. #ifdef PNG_USER_MEM_SUPPORTED
  187493. png_free_ptr free_fn;
  187494. png_voidp mem_ptr;
  187495. #endif
  187496. png_debug(1, "in png_destroy_read_struct\n");
  187497. if (png_ptr_ptr != NULL)
  187498. png_ptr = *png_ptr_ptr;
  187499. if (info_ptr_ptr != NULL)
  187500. info_ptr = *info_ptr_ptr;
  187501. if (end_info_ptr_ptr != NULL)
  187502. end_info_ptr = *end_info_ptr_ptr;
  187503. #ifdef PNG_USER_MEM_SUPPORTED
  187504. free_fn = png_ptr->free_fn;
  187505. mem_ptr = png_ptr->mem_ptr;
  187506. #endif
  187507. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  187508. if (info_ptr != NULL)
  187509. {
  187510. #if defined(PNG_TEXT_SUPPORTED)
  187511. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  187512. #endif
  187513. #ifdef PNG_USER_MEM_SUPPORTED
  187514. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  187515. (png_voidp)mem_ptr);
  187516. #else
  187517. png_destroy_struct((png_voidp)info_ptr);
  187518. #endif
  187519. *info_ptr_ptr = NULL;
  187520. }
  187521. if (end_info_ptr != NULL)
  187522. {
  187523. #if defined(PNG_READ_TEXT_SUPPORTED)
  187524. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  187525. #endif
  187526. #ifdef PNG_USER_MEM_SUPPORTED
  187527. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  187528. (png_voidp)mem_ptr);
  187529. #else
  187530. png_destroy_struct((png_voidp)end_info_ptr);
  187531. #endif
  187532. *end_info_ptr_ptr = NULL;
  187533. }
  187534. if (png_ptr != NULL)
  187535. {
  187536. #ifdef PNG_USER_MEM_SUPPORTED
  187537. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  187538. (png_voidp)mem_ptr);
  187539. #else
  187540. png_destroy_struct((png_voidp)png_ptr);
  187541. #endif
  187542. *png_ptr_ptr = NULL;
  187543. }
  187544. }
  187545. /* free all memory used by the read (old method) */
  187546. void /* PRIVATE */
  187547. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  187548. {
  187549. #ifdef PNG_SETJMP_SUPPORTED
  187550. jmp_buf tmp_jmp;
  187551. #endif
  187552. png_error_ptr error_fn;
  187553. png_error_ptr warning_fn;
  187554. png_voidp error_ptr;
  187555. #ifdef PNG_USER_MEM_SUPPORTED
  187556. png_free_ptr free_fn;
  187557. #endif
  187558. png_debug(1, "in png_read_destroy\n");
  187559. if (info_ptr != NULL)
  187560. png_info_destroy(png_ptr, info_ptr);
  187561. if (end_info_ptr != NULL)
  187562. png_info_destroy(png_ptr, end_info_ptr);
  187563. png_free(png_ptr, png_ptr->zbuf);
  187564. png_free(png_ptr, png_ptr->big_row_buf);
  187565. png_free(png_ptr, png_ptr->prev_row);
  187566. #if defined(PNG_READ_DITHER_SUPPORTED)
  187567. png_free(png_ptr, png_ptr->palette_lookup);
  187568. png_free(png_ptr, png_ptr->dither_index);
  187569. #endif
  187570. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187571. png_free(png_ptr, png_ptr->gamma_table);
  187572. #endif
  187573. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187574. png_free(png_ptr, png_ptr->gamma_from_1);
  187575. png_free(png_ptr, png_ptr->gamma_to_1);
  187576. #endif
  187577. #ifdef PNG_FREE_ME_SUPPORTED
  187578. if (png_ptr->free_me & PNG_FREE_PLTE)
  187579. png_zfree(png_ptr, png_ptr->palette);
  187580. png_ptr->free_me &= ~PNG_FREE_PLTE;
  187581. #else
  187582. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  187583. png_zfree(png_ptr, png_ptr->palette);
  187584. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  187585. #endif
  187586. #if defined(PNG_tRNS_SUPPORTED) || \
  187587. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187588. #ifdef PNG_FREE_ME_SUPPORTED
  187589. if (png_ptr->free_me & PNG_FREE_TRNS)
  187590. png_free(png_ptr, png_ptr->trans);
  187591. png_ptr->free_me &= ~PNG_FREE_TRNS;
  187592. #else
  187593. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  187594. png_free(png_ptr, png_ptr->trans);
  187595. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  187596. #endif
  187597. #endif
  187598. #if defined(PNG_READ_hIST_SUPPORTED)
  187599. #ifdef PNG_FREE_ME_SUPPORTED
  187600. if (png_ptr->free_me & PNG_FREE_HIST)
  187601. png_free(png_ptr, png_ptr->hist);
  187602. png_ptr->free_me &= ~PNG_FREE_HIST;
  187603. #else
  187604. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  187605. png_free(png_ptr, png_ptr->hist);
  187606. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  187607. #endif
  187608. #endif
  187609. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187610. if (png_ptr->gamma_16_table != NULL)
  187611. {
  187612. int i;
  187613. int istop = (1 << (8 - png_ptr->gamma_shift));
  187614. for (i = 0; i < istop; i++)
  187615. {
  187616. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  187617. }
  187618. png_free(png_ptr, png_ptr->gamma_16_table);
  187619. }
  187620. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187621. if (png_ptr->gamma_16_from_1 != NULL)
  187622. {
  187623. int i;
  187624. int istop = (1 << (8 - png_ptr->gamma_shift));
  187625. for (i = 0; i < istop; i++)
  187626. {
  187627. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  187628. }
  187629. png_free(png_ptr, png_ptr->gamma_16_from_1);
  187630. }
  187631. if (png_ptr->gamma_16_to_1 != NULL)
  187632. {
  187633. int i;
  187634. int istop = (1 << (8 - png_ptr->gamma_shift));
  187635. for (i = 0; i < istop; i++)
  187636. {
  187637. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  187638. }
  187639. png_free(png_ptr, png_ptr->gamma_16_to_1);
  187640. }
  187641. #endif
  187642. #endif
  187643. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  187644. png_free(png_ptr, png_ptr->time_buffer);
  187645. #endif
  187646. inflateEnd(&png_ptr->zstream);
  187647. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187648. png_free(png_ptr, png_ptr->save_buffer);
  187649. #endif
  187650. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187651. #ifdef PNG_TEXT_SUPPORTED
  187652. png_free(png_ptr, png_ptr->current_text);
  187653. #endif /* PNG_TEXT_SUPPORTED */
  187654. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  187655. /* Save the important info out of the png_struct, in case it is
  187656. * being used again.
  187657. */
  187658. #ifdef PNG_SETJMP_SUPPORTED
  187659. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187660. #endif
  187661. error_fn = png_ptr->error_fn;
  187662. warning_fn = png_ptr->warning_fn;
  187663. error_ptr = png_ptr->error_ptr;
  187664. #ifdef PNG_USER_MEM_SUPPORTED
  187665. free_fn = png_ptr->free_fn;
  187666. #endif
  187667. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187668. png_ptr->error_fn = error_fn;
  187669. png_ptr->warning_fn = warning_fn;
  187670. png_ptr->error_ptr = error_ptr;
  187671. #ifdef PNG_USER_MEM_SUPPORTED
  187672. png_ptr->free_fn = free_fn;
  187673. #endif
  187674. #ifdef PNG_SETJMP_SUPPORTED
  187675. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187676. #endif
  187677. }
  187678. void PNGAPI
  187679. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  187680. {
  187681. if(png_ptr == NULL) return;
  187682. png_ptr->read_row_fn = read_row_fn;
  187683. }
  187684. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187685. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  187686. void PNGAPI
  187687. png_read_png(png_structp png_ptr, png_infop info_ptr,
  187688. int transforms,
  187689. voidp params)
  187690. {
  187691. int row;
  187692. if(png_ptr == NULL) return;
  187693. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187694. /* invert the alpha channel from opacity to transparency
  187695. */
  187696. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  187697. png_set_invert_alpha(png_ptr);
  187698. #endif
  187699. /* png_read_info() gives us all of the information from the
  187700. * PNG file before the first IDAT (image data chunk).
  187701. */
  187702. png_read_info(png_ptr, info_ptr);
  187703. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  187704. png_error(png_ptr,"Image is too high to process with png_read_png()");
  187705. /* -------------- image transformations start here ------------------- */
  187706. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187707. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  187708. */
  187709. if (transforms & PNG_TRANSFORM_STRIP_16)
  187710. png_set_strip_16(png_ptr);
  187711. #endif
  187712. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  187713. /* Strip alpha bytes from the input data without combining with
  187714. * the background (not recommended).
  187715. */
  187716. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  187717. png_set_strip_alpha(png_ptr);
  187718. #endif
  187719. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  187720. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  187721. * byte into separate bytes (useful for paletted and grayscale images).
  187722. */
  187723. if (transforms & PNG_TRANSFORM_PACKING)
  187724. png_set_packing(png_ptr);
  187725. #endif
  187726. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  187727. /* Change the order of packed pixels to least significant bit first
  187728. * (not useful if you are using png_set_packing).
  187729. */
  187730. if (transforms & PNG_TRANSFORM_PACKSWAP)
  187731. png_set_packswap(png_ptr);
  187732. #endif
  187733. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187734. /* Expand paletted colors into true RGB triplets
  187735. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  187736. * Expand paletted or RGB images with transparency to full alpha
  187737. * channels so the data will be available as RGBA quartets.
  187738. */
  187739. if (transforms & PNG_TRANSFORM_EXPAND)
  187740. if ((png_ptr->bit_depth < 8) ||
  187741. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  187742. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  187743. png_set_expand(png_ptr);
  187744. #endif
  187745. /* We don't handle background color or gamma transformation or dithering.
  187746. */
  187747. #if defined(PNG_READ_INVERT_SUPPORTED)
  187748. /* invert monochrome files to have 0 as white and 1 as black
  187749. */
  187750. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  187751. png_set_invert_mono(png_ptr);
  187752. #endif
  187753. #if defined(PNG_READ_SHIFT_SUPPORTED)
  187754. /* If you want to shift the pixel values from the range [0,255] or
  187755. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  187756. * colors were originally in:
  187757. */
  187758. if ((transforms & PNG_TRANSFORM_SHIFT)
  187759. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  187760. {
  187761. png_color_8p sig_bit;
  187762. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  187763. png_set_shift(png_ptr, sig_bit);
  187764. }
  187765. #endif
  187766. #if defined(PNG_READ_BGR_SUPPORTED)
  187767. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  187768. */
  187769. if (transforms & PNG_TRANSFORM_BGR)
  187770. png_set_bgr(png_ptr);
  187771. #endif
  187772. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  187773. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  187774. */
  187775. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  187776. png_set_swap_alpha(png_ptr);
  187777. #endif
  187778. #if defined(PNG_READ_SWAP_SUPPORTED)
  187779. /* swap bytes of 16 bit files to least significant byte first
  187780. */
  187781. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  187782. png_set_swap(png_ptr);
  187783. #endif
  187784. /* We don't handle adding filler bytes */
  187785. /* Optional call to gamma correct and add the background to the palette
  187786. * and update info structure. REQUIRED if you are expecting libpng to
  187787. * update the palette for you (i.e., you selected such a transform above).
  187788. */
  187789. png_read_update_info(png_ptr, info_ptr);
  187790. /* -------------- image transformations end here ------------------- */
  187791. #ifdef PNG_FREE_ME_SUPPORTED
  187792. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  187793. #endif
  187794. if(info_ptr->row_pointers == NULL)
  187795. {
  187796. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  187797. info_ptr->height * png_sizeof(png_bytep));
  187798. #ifdef PNG_FREE_ME_SUPPORTED
  187799. info_ptr->free_me |= PNG_FREE_ROWS;
  187800. #endif
  187801. for (row = 0; row < (int)info_ptr->height; row++)
  187802. {
  187803. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  187804. png_get_rowbytes(png_ptr, info_ptr));
  187805. }
  187806. }
  187807. png_read_image(png_ptr, info_ptr->row_pointers);
  187808. info_ptr->valid |= PNG_INFO_IDAT;
  187809. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  187810. png_read_end(png_ptr, info_ptr);
  187811. transforms = transforms; /* quiet compiler warnings */
  187812. params = params;
  187813. }
  187814. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  187815. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187816. #endif /* PNG_READ_SUPPORTED */
  187817. /*** End of inlined file: pngread.c ***/
  187818. /*** Start of inlined file: pngpread.c ***/
  187819. /* pngpread.c - read a png file in push mode
  187820. *
  187821. * Last changed in libpng 1.2.21 October 4, 2007
  187822. * For conditions of distribution and use, see copyright notice in png.h
  187823. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187824. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187825. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187826. */
  187827. #define PNG_INTERNAL
  187828. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187829. /* push model modes */
  187830. #define PNG_READ_SIG_MODE 0
  187831. #define PNG_READ_CHUNK_MODE 1
  187832. #define PNG_READ_IDAT_MODE 2
  187833. #define PNG_SKIP_MODE 3
  187834. #define PNG_READ_tEXt_MODE 4
  187835. #define PNG_READ_zTXt_MODE 5
  187836. #define PNG_READ_DONE_MODE 6
  187837. #define PNG_READ_iTXt_MODE 7
  187838. #define PNG_ERROR_MODE 8
  187839. void PNGAPI
  187840. png_process_data(png_structp png_ptr, png_infop info_ptr,
  187841. png_bytep buffer, png_size_t buffer_size)
  187842. {
  187843. if(png_ptr == NULL) return;
  187844. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  187845. while (png_ptr->buffer_size)
  187846. {
  187847. png_process_some_data(png_ptr, info_ptr);
  187848. }
  187849. }
  187850. /* What we do with the incoming data depends on what we were previously
  187851. * doing before we ran out of data...
  187852. */
  187853. void /* PRIVATE */
  187854. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  187855. {
  187856. if(png_ptr == NULL) return;
  187857. switch (png_ptr->process_mode)
  187858. {
  187859. case PNG_READ_SIG_MODE:
  187860. {
  187861. png_push_read_sig(png_ptr, info_ptr);
  187862. break;
  187863. }
  187864. case PNG_READ_CHUNK_MODE:
  187865. {
  187866. png_push_read_chunk(png_ptr, info_ptr);
  187867. break;
  187868. }
  187869. case PNG_READ_IDAT_MODE:
  187870. {
  187871. png_push_read_IDAT(png_ptr);
  187872. break;
  187873. }
  187874. #if defined(PNG_READ_tEXt_SUPPORTED)
  187875. case PNG_READ_tEXt_MODE:
  187876. {
  187877. png_push_read_tEXt(png_ptr, info_ptr);
  187878. break;
  187879. }
  187880. #endif
  187881. #if defined(PNG_READ_zTXt_SUPPORTED)
  187882. case PNG_READ_zTXt_MODE:
  187883. {
  187884. png_push_read_zTXt(png_ptr, info_ptr);
  187885. break;
  187886. }
  187887. #endif
  187888. #if defined(PNG_READ_iTXt_SUPPORTED)
  187889. case PNG_READ_iTXt_MODE:
  187890. {
  187891. png_push_read_iTXt(png_ptr, info_ptr);
  187892. break;
  187893. }
  187894. #endif
  187895. case PNG_SKIP_MODE:
  187896. {
  187897. png_push_crc_finish(png_ptr);
  187898. break;
  187899. }
  187900. default:
  187901. {
  187902. png_ptr->buffer_size = 0;
  187903. break;
  187904. }
  187905. }
  187906. }
  187907. /* Read any remaining signature bytes from the stream and compare them with
  187908. * the correct PNG signature. It is possible that this routine is called
  187909. * with bytes already read from the signature, either because they have been
  187910. * checked by the calling application, or because of multiple calls to this
  187911. * routine.
  187912. */
  187913. void /* PRIVATE */
  187914. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  187915. {
  187916. png_size_t num_checked = png_ptr->sig_bytes,
  187917. num_to_check = 8 - num_checked;
  187918. if (png_ptr->buffer_size < num_to_check)
  187919. {
  187920. num_to_check = png_ptr->buffer_size;
  187921. }
  187922. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  187923. num_to_check);
  187924. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  187925. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187926. {
  187927. if (num_checked < 4 &&
  187928. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187929. png_error(png_ptr, "Not a PNG file");
  187930. else
  187931. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187932. }
  187933. else
  187934. {
  187935. if (png_ptr->sig_bytes >= 8)
  187936. {
  187937. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  187938. }
  187939. }
  187940. }
  187941. void /* PRIVATE */
  187942. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  187943. {
  187944. #ifdef PNG_USE_LOCAL_ARRAYS
  187945. PNG_CONST PNG_IHDR;
  187946. PNG_CONST PNG_IDAT;
  187947. PNG_CONST PNG_IEND;
  187948. PNG_CONST PNG_PLTE;
  187949. #if defined(PNG_READ_bKGD_SUPPORTED)
  187950. PNG_CONST PNG_bKGD;
  187951. #endif
  187952. #if defined(PNG_READ_cHRM_SUPPORTED)
  187953. PNG_CONST PNG_cHRM;
  187954. #endif
  187955. #if defined(PNG_READ_gAMA_SUPPORTED)
  187956. PNG_CONST PNG_gAMA;
  187957. #endif
  187958. #if defined(PNG_READ_hIST_SUPPORTED)
  187959. PNG_CONST PNG_hIST;
  187960. #endif
  187961. #if defined(PNG_READ_iCCP_SUPPORTED)
  187962. PNG_CONST PNG_iCCP;
  187963. #endif
  187964. #if defined(PNG_READ_iTXt_SUPPORTED)
  187965. PNG_CONST PNG_iTXt;
  187966. #endif
  187967. #if defined(PNG_READ_oFFs_SUPPORTED)
  187968. PNG_CONST PNG_oFFs;
  187969. #endif
  187970. #if defined(PNG_READ_pCAL_SUPPORTED)
  187971. PNG_CONST PNG_pCAL;
  187972. #endif
  187973. #if defined(PNG_READ_pHYs_SUPPORTED)
  187974. PNG_CONST PNG_pHYs;
  187975. #endif
  187976. #if defined(PNG_READ_sBIT_SUPPORTED)
  187977. PNG_CONST PNG_sBIT;
  187978. #endif
  187979. #if defined(PNG_READ_sCAL_SUPPORTED)
  187980. PNG_CONST PNG_sCAL;
  187981. #endif
  187982. #if defined(PNG_READ_sRGB_SUPPORTED)
  187983. PNG_CONST PNG_sRGB;
  187984. #endif
  187985. #if defined(PNG_READ_sPLT_SUPPORTED)
  187986. PNG_CONST PNG_sPLT;
  187987. #endif
  187988. #if defined(PNG_READ_tEXt_SUPPORTED)
  187989. PNG_CONST PNG_tEXt;
  187990. #endif
  187991. #if defined(PNG_READ_tIME_SUPPORTED)
  187992. PNG_CONST PNG_tIME;
  187993. #endif
  187994. #if defined(PNG_READ_tRNS_SUPPORTED)
  187995. PNG_CONST PNG_tRNS;
  187996. #endif
  187997. #if defined(PNG_READ_zTXt_SUPPORTED)
  187998. PNG_CONST PNG_zTXt;
  187999. #endif
  188000. #endif /* PNG_USE_LOCAL_ARRAYS */
  188001. /* First we make sure we have enough data for the 4 byte chunk name
  188002. * and the 4 byte chunk length before proceeding with decoding the
  188003. * chunk data. To fully decode each of these chunks, we also make
  188004. * sure we have enough data in the buffer for the 4 byte CRC at the
  188005. * end of every chunk (except IDAT, which is handled separately).
  188006. */
  188007. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188008. {
  188009. png_byte chunk_length[4];
  188010. if (png_ptr->buffer_size < 8)
  188011. {
  188012. png_push_save_buffer(png_ptr);
  188013. return;
  188014. }
  188015. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188016. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188017. png_reset_crc(png_ptr);
  188018. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188019. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188020. }
  188021. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188022. if(png_ptr->mode & PNG_AFTER_IDAT)
  188023. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188024. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188025. {
  188026. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188027. {
  188028. png_push_save_buffer(png_ptr);
  188029. return;
  188030. }
  188031. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188032. }
  188033. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188034. {
  188035. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188036. {
  188037. png_push_save_buffer(png_ptr);
  188038. return;
  188039. }
  188040. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188041. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188042. png_push_have_end(png_ptr, info_ptr);
  188043. }
  188044. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188045. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188046. {
  188047. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188048. {
  188049. png_push_save_buffer(png_ptr);
  188050. return;
  188051. }
  188052. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188053. png_ptr->mode |= PNG_HAVE_IDAT;
  188054. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188055. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188056. png_ptr->mode |= PNG_HAVE_PLTE;
  188057. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188058. {
  188059. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188060. png_error(png_ptr, "Missing IHDR before IDAT");
  188061. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188062. !(png_ptr->mode & PNG_HAVE_PLTE))
  188063. png_error(png_ptr, "Missing PLTE before IDAT");
  188064. }
  188065. }
  188066. #endif
  188067. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188068. {
  188069. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188070. {
  188071. png_push_save_buffer(png_ptr);
  188072. return;
  188073. }
  188074. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188075. }
  188076. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188077. {
  188078. /* If we reach an IDAT chunk, this means we have read all of the
  188079. * header chunks, and we can start reading the image (or if this
  188080. * is called after the image has been read - we have an error).
  188081. */
  188082. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188083. png_error(png_ptr, "Missing IHDR before IDAT");
  188084. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188085. !(png_ptr->mode & PNG_HAVE_PLTE))
  188086. png_error(png_ptr, "Missing PLTE before IDAT");
  188087. if (png_ptr->mode & PNG_HAVE_IDAT)
  188088. {
  188089. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188090. if (png_ptr->push_length == 0)
  188091. return;
  188092. if (png_ptr->mode & PNG_AFTER_IDAT)
  188093. png_error(png_ptr, "Too many IDAT's found");
  188094. }
  188095. png_ptr->idat_size = png_ptr->push_length;
  188096. png_ptr->mode |= PNG_HAVE_IDAT;
  188097. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188098. png_push_have_info(png_ptr, info_ptr);
  188099. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188100. png_ptr->zstream.next_out = png_ptr->row_buf;
  188101. return;
  188102. }
  188103. #if defined(PNG_READ_gAMA_SUPPORTED)
  188104. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188105. {
  188106. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188107. {
  188108. png_push_save_buffer(png_ptr);
  188109. return;
  188110. }
  188111. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188112. }
  188113. #endif
  188114. #if defined(PNG_READ_sBIT_SUPPORTED)
  188115. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188116. {
  188117. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188118. {
  188119. png_push_save_buffer(png_ptr);
  188120. return;
  188121. }
  188122. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188123. }
  188124. #endif
  188125. #if defined(PNG_READ_cHRM_SUPPORTED)
  188126. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188127. {
  188128. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188129. {
  188130. png_push_save_buffer(png_ptr);
  188131. return;
  188132. }
  188133. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188134. }
  188135. #endif
  188136. #if defined(PNG_READ_sRGB_SUPPORTED)
  188137. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188138. {
  188139. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188140. {
  188141. png_push_save_buffer(png_ptr);
  188142. return;
  188143. }
  188144. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188145. }
  188146. #endif
  188147. #if defined(PNG_READ_iCCP_SUPPORTED)
  188148. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188149. {
  188150. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188151. {
  188152. png_push_save_buffer(png_ptr);
  188153. return;
  188154. }
  188155. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188156. }
  188157. #endif
  188158. #if defined(PNG_READ_sPLT_SUPPORTED)
  188159. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188160. {
  188161. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188162. {
  188163. png_push_save_buffer(png_ptr);
  188164. return;
  188165. }
  188166. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188167. }
  188168. #endif
  188169. #if defined(PNG_READ_tRNS_SUPPORTED)
  188170. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188171. {
  188172. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188173. {
  188174. png_push_save_buffer(png_ptr);
  188175. return;
  188176. }
  188177. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188178. }
  188179. #endif
  188180. #if defined(PNG_READ_bKGD_SUPPORTED)
  188181. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188182. {
  188183. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188184. {
  188185. png_push_save_buffer(png_ptr);
  188186. return;
  188187. }
  188188. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188189. }
  188190. #endif
  188191. #if defined(PNG_READ_hIST_SUPPORTED)
  188192. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188193. {
  188194. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188195. {
  188196. png_push_save_buffer(png_ptr);
  188197. return;
  188198. }
  188199. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188200. }
  188201. #endif
  188202. #if defined(PNG_READ_pHYs_SUPPORTED)
  188203. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188204. {
  188205. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188206. {
  188207. png_push_save_buffer(png_ptr);
  188208. return;
  188209. }
  188210. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188211. }
  188212. #endif
  188213. #if defined(PNG_READ_oFFs_SUPPORTED)
  188214. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188215. {
  188216. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188217. {
  188218. png_push_save_buffer(png_ptr);
  188219. return;
  188220. }
  188221. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188222. }
  188223. #endif
  188224. #if defined(PNG_READ_pCAL_SUPPORTED)
  188225. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188226. {
  188227. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188228. {
  188229. png_push_save_buffer(png_ptr);
  188230. return;
  188231. }
  188232. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188233. }
  188234. #endif
  188235. #if defined(PNG_READ_sCAL_SUPPORTED)
  188236. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188237. {
  188238. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188239. {
  188240. png_push_save_buffer(png_ptr);
  188241. return;
  188242. }
  188243. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188244. }
  188245. #endif
  188246. #if defined(PNG_READ_tIME_SUPPORTED)
  188247. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188248. {
  188249. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188250. {
  188251. png_push_save_buffer(png_ptr);
  188252. return;
  188253. }
  188254. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188255. }
  188256. #endif
  188257. #if defined(PNG_READ_tEXt_SUPPORTED)
  188258. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188259. {
  188260. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188261. {
  188262. png_push_save_buffer(png_ptr);
  188263. return;
  188264. }
  188265. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  188266. }
  188267. #endif
  188268. #if defined(PNG_READ_zTXt_SUPPORTED)
  188269. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188270. {
  188271. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188272. {
  188273. png_push_save_buffer(png_ptr);
  188274. return;
  188275. }
  188276. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  188277. }
  188278. #endif
  188279. #if defined(PNG_READ_iTXt_SUPPORTED)
  188280. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188281. {
  188282. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188283. {
  188284. png_push_save_buffer(png_ptr);
  188285. return;
  188286. }
  188287. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  188288. }
  188289. #endif
  188290. else
  188291. {
  188292. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188293. {
  188294. png_push_save_buffer(png_ptr);
  188295. return;
  188296. }
  188297. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188298. }
  188299. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188300. }
  188301. void /* PRIVATE */
  188302. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  188303. {
  188304. png_ptr->process_mode = PNG_SKIP_MODE;
  188305. png_ptr->skip_length = skip;
  188306. }
  188307. void /* PRIVATE */
  188308. png_push_crc_finish(png_structp png_ptr)
  188309. {
  188310. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188311. {
  188312. png_size_t save_size;
  188313. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188314. save_size = (png_size_t)png_ptr->skip_length;
  188315. else
  188316. save_size = png_ptr->save_buffer_size;
  188317. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188318. png_ptr->skip_length -= save_size;
  188319. png_ptr->buffer_size -= save_size;
  188320. png_ptr->save_buffer_size -= save_size;
  188321. png_ptr->save_buffer_ptr += save_size;
  188322. }
  188323. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188324. {
  188325. png_size_t save_size;
  188326. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188327. save_size = (png_size_t)png_ptr->skip_length;
  188328. else
  188329. save_size = png_ptr->current_buffer_size;
  188330. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188331. png_ptr->skip_length -= save_size;
  188332. png_ptr->buffer_size -= save_size;
  188333. png_ptr->current_buffer_size -= save_size;
  188334. png_ptr->current_buffer_ptr += save_size;
  188335. }
  188336. if (!png_ptr->skip_length)
  188337. {
  188338. if (png_ptr->buffer_size < 4)
  188339. {
  188340. png_push_save_buffer(png_ptr);
  188341. return;
  188342. }
  188343. png_crc_finish(png_ptr, 0);
  188344. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188345. }
  188346. }
  188347. void PNGAPI
  188348. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188349. {
  188350. png_bytep ptr;
  188351. if(png_ptr == NULL) return;
  188352. ptr = buffer;
  188353. if (png_ptr->save_buffer_size)
  188354. {
  188355. png_size_t save_size;
  188356. if (length < png_ptr->save_buffer_size)
  188357. save_size = length;
  188358. else
  188359. save_size = png_ptr->save_buffer_size;
  188360. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188361. length -= save_size;
  188362. ptr += save_size;
  188363. png_ptr->buffer_size -= save_size;
  188364. png_ptr->save_buffer_size -= save_size;
  188365. png_ptr->save_buffer_ptr += save_size;
  188366. }
  188367. if (length && png_ptr->current_buffer_size)
  188368. {
  188369. png_size_t save_size;
  188370. if (length < png_ptr->current_buffer_size)
  188371. save_size = length;
  188372. else
  188373. save_size = png_ptr->current_buffer_size;
  188374. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188375. png_ptr->buffer_size -= save_size;
  188376. png_ptr->current_buffer_size -= save_size;
  188377. png_ptr->current_buffer_ptr += save_size;
  188378. }
  188379. }
  188380. void /* PRIVATE */
  188381. png_push_save_buffer(png_structp png_ptr)
  188382. {
  188383. if (png_ptr->save_buffer_size)
  188384. {
  188385. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  188386. {
  188387. png_size_t i,istop;
  188388. png_bytep sp;
  188389. png_bytep dp;
  188390. istop = png_ptr->save_buffer_size;
  188391. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  188392. i < istop; i++, sp++, dp++)
  188393. {
  188394. *dp = *sp;
  188395. }
  188396. }
  188397. }
  188398. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  188399. png_ptr->save_buffer_max)
  188400. {
  188401. png_size_t new_max;
  188402. png_bytep old_buffer;
  188403. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  188404. (png_ptr->current_buffer_size + 256))
  188405. {
  188406. png_error(png_ptr, "Potential overflow of save_buffer");
  188407. }
  188408. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  188409. old_buffer = png_ptr->save_buffer;
  188410. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  188411. (png_uint_32)new_max);
  188412. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  188413. png_free(png_ptr, old_buffer);
  188414. png_ptr->save_buffer_max = new_max;
  188415. }
  188416. if (png_ptr->current_buffer_size)
  188417. {
  188418. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  188419. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  188420. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  188421. png_ptr->current_buffer_size = 0;
  188422. }
  188423. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  188424. png_ptr->buffer_size = 0;
  188425. }
  188426. void /* PRIVATE */
  188427. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  188428. png_size_t buffer_length)
  188429. {
  188430. png_ptr->current_buffer = buffer;
  188431. png_ptr->current_buffer_size = buffer_length;
  188432. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  188433. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  188434. }
  188435. void /* PRIVATE */
  188436. png_push_read_IDAT(png_structp png_ptr)
  188437. {
  188438. #ifdef PNG_USE_LOCAL_ARRAYS
  188439. PNG_CONST PNG_IDAT;
  188440. #endif
  188441. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188442. {
  188443. png_byte chunk_length[4];
  188444. if (png_ptr->buffer_size < 8)
  188445. {
  188446. png_push_save_buffer(png_ptr);
  188447. return;
  188448. }
  188449. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188450. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188451. png_reset_crc(png_ptr);
  188452. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188453. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188454. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188455. {
  188456. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188457. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188458. png_error(png_ptr, "Not enough compressed data");
  188459. return;
  188460. }
  188461. png_ptr->idat_size = png_ptr->push_length;
  188462. }
  188463. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  188464. {
  188465. png_size_t save_size;
  188466. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  188467. {
  188468. save_size = (png_size_t)png_ptr->idat_size;
  188469. /* check for overflow */
  188470. if((png_uint_32)save_size != png_ptr->idat_size)
  188471. png_error(png_ptr, "save_size overflowed in pngpread");
  188472. }
  188473. else
  188474. save_size = png_ptr->save_buffer_size;
  188475. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188476. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188477. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188478. png_ptr->idat_size -= save_size;
  188479. png_ptr->buffer_size -= save_size;
  188480. png_ptr->save_buffer_size -= save_size;
  188481. png_ptr->save_buffer_ptr += save_size;
  188482. }
  188483. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  188484. {
  188485. png_size_t save_size;
  188486. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  188487. {
  188488. save_size = (png_size_t)png_ptr->idat_size;
  188489. /* check for overflow */
  188490. if((png_uint_32)save_size != png_ptr->idat_size)
  188491. png_error(png_ptr, "save_size overflowed in pngpread");
  188492. }
  188493. else
  188494. save_size = png_ptr->current_buffer_size;
  188495. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188496. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188497. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188498. png_ptr->idat_size -= save_size;
  188499. png_ptr->buffer_size -= save_size;
  188500. png_ptr->current_buffer_size -= save_size;
  188501. png_ptr->current_buffer_ptr += save_size;
  188502. }
  188503. if (!png_ptr->idat_size)
  188504. {
  188505. if (png_ptr->buffer_size < 4)
  188506. {
  188507. png_push_save_buffer(png_ptr);
  188508. return;
  188509. }
  188510. png_crc_finish(png_ptr, 0);
  188511. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188512. png_ptr->mode |= PNG_AFTER_IDAT;
  188513. }
  188514. }
  188515. void /* PRIVATE */
  188516. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  188517. png_size_t buffer_length)
  188518. {
  188519. int ret;
  188520. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  188521. png_error(png_ptr, "Extra compression data");
  188522. png_ptr->zstream.next_in = buffer;
  188523. png_ptr->zstream.avail_in = (uInt)buffer_length;
  188524. for(;;)
  188525. {
  188526. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188527. if (ret != Z_OK)
  188528. {
  188529. if (ret == Z_STREAM_END)
  188530. {
  188531. if (png_ptr->zstream.avail_in)
  188532. png_error(png_ptr, "Extra compressed data");
  188533. if (!(png_ptr->zstream.avail_out))
  188534. {
  188535. png_push_process_row(png_ptr);
  188536. }
  188537. png_ptr->mode |= PNG_AFTER_IDAT;
  188538. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188539. break;
  188540. }
  188541. else if (ret == Z_BUF_ERROR)
  188542. break;
  188543. else
  188544. png_error(png_ptr, "Decompression Error");
  188545. }
  188546. if (!(png_ptr->zstream.avail_out))
  188547. {
  188548. if ((
  188549. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188550. png_ptr->interlaced && png_ptr->pass > 6) ||
  188551. (!png_ptr->interlaced &&
  188552. #endif
  188553. png_ptr->row_number == png_ptr->num_rows))
  188554. {
  188555. if (png_ptr->zstream.avail_in)
  188556. {
  188557. png_warning(png_ptr, "Too much data in IDAT chunks");
  188558. }
  188559. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188560. break;
  188561. }
  188562. png_push_process_row(png_ptr);
  188563. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188564. png_ptr->zstream.next_out = png_ptr->row_buf;
  188565. }
  188566. else
  188567. break;
  188568. }
  188569. }
  188570. void /* PRIVATE */
  188571. png_push_process_row(png_structp png_ptr)
  188572. {
  188573. png_ptr->row_info.color_type = png_ptr->color_type;
  188574. png_ptr->row_info.width = png_ptr->iwidth;
  188575. png_ptr->row_info.channels = png_ptr->channels;
  188576. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  188577. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  188578. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  188579. png_ptr->row_info.width);
  188580. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  188581. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  188582. (int)(png_ptr->row_buf[0]));
  188583. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  188584. png_ptr->rowbytes + 1);
  188585. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  188586. png_do_read_transformations(png_ptr);
  188587. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188588. /* blow up interlaced rows to full size */
  188589. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  188590. {
  188591. if (png_ptr->pass < 6)
  188592. /* old interface (pre-1.0.9):
  188593. png_do_read_interlace(&(png_ptr->row_info),
  188594. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  188595. */
  188596. png_do_read_interlace(png_ptr);
  188597. switch (png_ptr->pass)
  188598. {
  188599. case 0:
  188600. {
  188601. int i;
  188602. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  188603. {
  188604. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188605. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  188606. }
  188607. if (png_ptr->pass == 2) /* pass 1 might be empty */
  188608. {
  188609. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188610. {
  188611. png_push_have_row(png_ptr, png_bytep_NULL);
  188612. png_read_push_finish_row(png_ptr);
  188613. }
  188614. }
  188615. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  188616. {
  188617. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188618. {
  188619. png_push_have_row(png_ptr, png_bytep_NULL);
  188620. png_read_push_finish_row(png_ptr);
  188621. }
  188622. }
  188623. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  188624. {
  188625. png_push_have_row(png_ptr, png_bytep_NULL);
  188626. png_read_push_finish_row(png_ptr);
  188627. }
  188628. break;
  188629. }
  188630. case 1:
  188631. {
  188632. int i;
  188633. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  188634. {
  188635. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188636. png_read_push_finish_row(png_ptr);
  188637. }
  188638. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  188639. {
  188640. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188641. {
  188642. png_push_have_row(png_ptr, png_bytep_NULL);
  188643. png_read_push_finish_row(png_ptr);
  188644. }
  188645. }
  188646. break;
  188647. }
  188648. case 2:
  188649. {
  188650. int i;
  188651. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188652. {
  188653. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188654. png_read_push_finish_row(png_ptr);
  188655. }
  188656. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188657. {
  188658. png_push_have_row(png_ptr, png_bytep_NULL);
  188659. png_read_push_finish_row(png_ptr);
  188660. }
  188661. if (png_ptr->pass == 4) /* pass 3 might be empty */
  188662. {
  188663. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188664. {
  188665. png_push_have_row(png_ptr, png_bytep_NULL);
  188666. png_read_push_finish_row(png_ptr);
  188667. }
  188668. }
  188669. break;
  188670. }
  188671. case 3:
  188672. {
  188673. int i;
  188674. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  188675. {
  188676. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188677. png_read_push_finish_row(png_ptr);
  188678. }
  188679. if (png_ptr->pass == 4) /* skip top two generated rows */
  188680. {
  188681. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188682. {
  188683. png_push_have_row(png_ptr, png_bytep_NULL);
  188684. png_read_push_finish_row(png_ptr);
  188685. }
  188686. }
  188687. break;
  188688. }
  188689. case 4:
  188690. {
  188691. int i;
  188692. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188693. {
  188694. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188695. png_read_push_finish_row(png_ptr);
  188696. }
  188697. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188698. {
  188699. png_push_have_row(png_ptr, png_bytep_NULL);
  188700. png_read_push_finish_row(png_ptr);
  188701. }
  188702. if (png_ptr->pass == 6) /* pass 5 might be empty */
  188703. {
  188704. png_push_have_row(png_ptr, png_bytep_NULL);
  188705. png_read_push_finish_row(png_ptr);
  188706. }
  188707. break;
  188708. }
  188709. case 5:
  188710. {
  188711. int i;
  188712. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  188713. {
  188714. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188715. png_read_push_finish_row(png_ptr);
  188716. }
  188717. if (png_ptr->pass == 6) /* skip top generated row */
  188718. {
  188719. png_push_have_row(png_ptr, png_bytep_NULL);
  188720. png_read_push_finish_row(png_ptr);
  188721. }
  188722. break;
  188723. }
  188724. case 6:
  188725. {
  188726. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188727. png_read_push_finish_row(png_ptr);
  188728. if (png_ptr->pass != 6)
  188729. break;
  188730. png_push_have_row(png_ptr, png_bytep_NULL);
  188731. png_read_push_finish_row(png_ptr);
  188732. }
  188733. }
  188734. }
  188735. else
  188736. #endif
  188737. {
  188738. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188739. png_read_push_finish_row(png_ptr);
  188740. }
  188741. }
  188742. void /* PRIVATE */
  188743. png_read_push_finish_row(png_structp png_ptr)
  188744. {
  188745. #ifdef PNG_USE_LOCAL_ARRAYS
  188746. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  188747. /* start of interlace block */
  188748. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  188749. /* offset to next interlace block */
  188750. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  188751. /* start of interlace block in the y direction */
  188752. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  188753. /* offset to next interlace block in the y direction */
  188754. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  188755. /* Height of interlace block. This is not currently used - if you need
  188756. * it, uncomment it here and in png.h
  188757. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  188758. */
  188759. #endif
  188760. png_ptr->row_number++;
  188761. if (png_ptr->row_number < png_ptr->num_rows)
  188762. return;
  188763. if (png_ptr->interlaced)
  188764. {
  188765. png_ptr->row_number = 0;
  188766. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  188767. png_ptr->rowbytes + 1);
  188768. do
  188769. {
  188770. png_ptr->pass++;
  188771. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  188772. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  188773. (png_ptr->pass == 5 && png_ptr->width < 2))
  188774. png_ptr->pass++;
  188775. if (png_ptr->pass > 7)
  188776. png_ptr->pass--;
  188777. if (png_ptr->pass >= 7)
  188778. break;
  188779. png_ptr->iwidth = (png_ptr->width +
  188780. png_pass_inc[png_ptr->pass] - 1 -
  188781. png_pass_start[png_ptr->pass]) /
  188782. png_pass_inc[png_ptr->pass];
  188783. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  188784. png_ptr->iwidth) + 1;
  188785. if (png_ptr->transformations & PNG_INTERLACE)
  188786. break;
  188787. png_ptr->num_rows = (png_ptr->height +
  188788. png_pass_yinc[png_ptr->pass] - 1 -
  188789. png_pass_ystart[png_ptr->pass]) /
  188790. png_pass_yinc[png_ptr->pass];
  188791. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  188792. }
  188793. }
  188794. #if defined(PNG_READ_tEXt_SUPPORTED)
  188795. void /* PRIVATE */
  188796. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188797. length)
  188798. {
  188799. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188800. {
  188801. png_error(png_ptr, "Out of place tEXt");
  188802. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188803. }
  188804. #ifdef PNG_MAX_MALLOC_64K
  188805. png_ptr->skip_length = 0; /* This may not be necessary */
  188806. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  188807. {
  188808. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  188809. png_ptr->skip_length = length - (png_uint_32)65535L;
  188810. length = (png_uint_32)65535L;
  188811. }
  188812. #endif
  188813. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188814. (png_uint_32)(length+1));
  188815. png_ptr->current_text[length] = '\0';
  188816. png_ptr->current_text_ptr = png_ptr->current_text;
  188817. png_ptr->current_text_size = (png_size_t)length;
  188818. png_ptr->current_text_left = (png_size_t)length;
  188819. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  188820. }
  188821. void /* PRIVATE */
  188822. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  188823. {
  188824. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188825. {
  188826. png_size_t text_size;
  188827. if (png_ptr->buffer_size < png_ptr->current_text_left)
  188828. text_size = png_ptr->buffer_size;
  188829. else
  188830. text_size = png_ptr->current_text_left;
  188831. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188832. png_ptr->current_text_left -= text_size;
  188833. png_ptr->current_text_ptr += text_size;
  188834. }
  188835. if (!(png_ptr->current_text_left))
  188836. {
  188837. png_textp text_ptr;
  188838. png_charp text;
  188839. png_charp key;
  188840. int ret;
  188841. if (png_ptr->buffer_size < 4)
  188842. {
  188843. png_push_save_buffer(png_ptr);
  188844. return;
  188845. }
  188846. png_push_crc_finish(png_ptr);
  188847. #if defined(PNG_MAX_MALLOC_64K)
  188848. if (png_ptr->skip_length)
  188849. return;
  188850. #endif
  188851. key = png_ptr->current_text;
  188852. for (text = key; *text; text++)
  188853. /* empty loop */ ;
  188854. if (text < key + png_ptr->current_text_size)
  188855. text++;
  188856. text_ptr = (png_textp)png_malloc(png_ptr,
  188857. (png_uint_32)png_sizeof(png_text));
  188858. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  188859. text_ptr->key = key;
  188860. #ifdef PNG_iTXt_SUPPORTED
  188861. text_ptr->lang = NULL;
  188862. text_ptr->lang_key = NULL;
  188863. #endif
  188864. text_ptr->text = text;
  188865. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  188866. png_free(png_ptr, key);
  188867. png_free(png_ptr, text_ptr);
  188868. png_ptr->current_text = NULL;
  188869. if (ret)
  188870. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  188871. }
  188872. }
  188873. #endif
  188874. #if defined(PNG_READ_zTXt_SUPPORTED)
  188875. void /* PRIVATE */
  188876. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188877. length)
  188878. {
  188879. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188880. {
  188881. png_error(png_ptr, "Out of place zTXt");
  188882. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188883. }
  188884. #ifdef PNG_MAX_MALLOC_64K
  188885. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  188886. * to be able to store the uncompressed data. Actually, the threshold
  188887. * is probably around 32K, but it isn't as definite as 64K is.
  188888. */
  188889. if (length > (png_uint_32)65535L)
  188890. {
  188891. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  188892. png_push_crc_skip(png_ptr, length);
  188893. return;
  188894. }
  188895. #endif
  188896. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188897. (png_uint_32)(length+1));
  188898. png_ptr->current_text[length] = '\0';
  188899. png_ptr->current_text_ptr = png_ptr->current_text;
  188900. png_ptr->current_text_size = (png_size_t)length;
  188901. png_ptr->current_text_left = (png_size_t)length;
  188902. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  188903. }
  188904. void /* PRIVATE */
  188905. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  188906. {
  188907. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188908. {
  188909. png_size_t text_size;
  188910. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  188911. text_size = png_ptr->buffer_size;
  188912. else
  188913. text_size = png_ptr->current_text_left;
  188914. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188915. png_ptr->current_text_left -= text_size;
  188916. png_ptr->current_text_ptr += text_size;
  188917. }
  188918. if (!(png_ptr->current_text_left))
  188919. {
  188920. png_textp text_ptr;
  188921. png_charp text;
  188922. png_charp key;
  188923. int ret;
  188924. png_size_t text_size, key_size;
  188925. if (png_ptr->buffer_size < 4)
  188926. {
  188927. png_push_save_buffer(png_ptr);
  188928. return;
  188929. }
  188930. png_push_crc_finish(png_ptr);
  188931. key = png_ptr->current_text;
  188932. for (text = key; *text; text++)
  188933. /* empty loop */ ;
  188934. /* zTXt can't have zero text */
  188935. if (text >= key + png_ptr->current_text_size)
  188936. {
  188937. png_ptr->current_text = NULL;
  188938. png_free(png_ptr, key);
  188939. return;
  188940. }
  188941. text++;
  188942. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  188943. {
  188944. png_ptr->current_text = NULL;
  188945. png_free(png_ptr, key);
  188946. return;
  188947. }
  188948. text++;
  188949. png_ptr->zstream.next_in = (png_bytep )text;
  188950. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  188951. (text - key));
  188952. png_ptr->zstream.next_out = png_ptr->zbuf;
  188953. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188954. key_size = text - key;
  188955. text_size = 0;
  188956. text = NULL;
  188957. ret = Z_STREAM_END;
  188958. while (png_ptr->zstream.avail_in)
  188959. {
  188960. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188961. if (ret != Z_OK && ret != Z_STREAM_END)
  188962. {
  188963. inflateReset(&png_ptr->zstream);
  188964. png_ptr->zstream.avail_in = 0;
  188965. png_ptr->current_text = NULL;
  188966. png_free(png_ptr, key);
  188967. png_free(png_ptr, text);
  188968. return;
  188969. }
  188970. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  188971. {
  188972. if (text == NULL)
  188973. {
  188974. text = (png_charp)png_malloc(png_ptr,
  188975. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  188976. + key_size + 1));
  188977. png_memcpy(text + key_size, png_ptr->zbuf,
  188978. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  188979. png_memcpy(text, key, key_size);
  188980. text_size = key_size + png_ptr->zbuf_size -
  188981. png_ptr->zstream.avail_out;
  188982. *(text + text_size) = '\0';
  188983. }
  188984. else
  188985. {
  188986. png_charp tmp;
  188987. tmp = text;
  188988. text = (png_charp)png_malloc(png_ptr, text_size +
  188989. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  188990. + 1));
  188991. png_memcpy(text, tmp, text_size);
  188992. png_free(png_ptr, tmp);
  188993. png_memcpy(text + text_size, png_ptr->zbuf,
  188994. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  188995. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  188996. *(text + text_size) = '\0';
  188997. }
  188998. if (ret != Z_STREAM_END)
  188999. {
  189000. png_ptr->zstream.next_out = png_ptr->zbuf;
  189001. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189002. }
  189003. }
  189004. else
  189005. {
  189006. break;
  189007. }
  189008. if (ret == Z_STREAM_END)
  189009. break;
  189010. }
  189011. inflateReset(&png_ptr->zstream);
  189012. png_ptr->zstream.avail_in = 0;
  189013. if (ret != Z_STREAM_END)
  189014. {
  189015. png_ptr->current_text = NULL;
  189016. png_free(png_ptr, key);
  189017. png_free(png_ptr, text);
  189018. return;
  189019. }
  189020. png_ptr->current_text = NULL;
  189021. png_free(png_ptr, key);
  189022. key = text;
  189023. text += key_size;
  189024. text_ptr = (png_textp)png_malloc(png_ptr,
  189025. (png_uint_32)png_sizeof(png_text));
  189026. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189027. text_ptr->key = key;
  189028. #ifdef PNG_iTXt_SUPPORTED
  189029. text_ptr->lang = NULL;
  189030. text_ptr->lang_key = NULL;
  189031. #endif
  189032. text_ptr->text = text;
  189033. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189034. png_free(png_ptr, key);
  189035. png_free(png_ptr, text_ptr);
  189036. if (ret)
  189037. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189038. }
  189039. }
  189040. #endif
  189041. #if defined(PNG_READ_iTXt_SUPPORTED)
  189042. void /* PRIVATE */
  189043. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189044. length)
  189045. {
  189046. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189047. {
  189048. png_error(png_ptr, "Out of place iTXt");
  189049. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189050. }
  189051. #ifdef PNG_MAX_MALLOC_64K
  189052. png_ptr->skip_length = 0; /* This may not be necessary */
  189053. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189054. {
  189055. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189056. png_ptr->skip_length = length - (png_uint_32)65535L;
  189057. length = (png_uint_32)65535L;
  189058. }
  189059. #endif
  189060. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189061. (png_uint_32)(length+1));
  189062. png_ptr->current_text[length] = '\0';
  189063. png_ptr->current_text_ptr = png_ptr->current_text;
  189064. png_ptr->current_text_size = (png_size_t)length;
  189065. png_ptr->current_text_left = (png_size_t)length;
  189066. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189067. }
  189068. void /* PRIVATE */
  189069. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189070. {
  189071. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189072. {
  189073. png_size_t text_size;
  189074. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189075. text_size = png_ptr->buffer_size;
  189076. else
  189077. text_size = png_ptr->current_text_left;
  189078. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189079. png_ptr->current_text_left -= text_size;
  189080. png_ptr->current_text_ptr += text_size;
  189081. }
  189082. if (!(png_ptr->current_text_left))
  189083. {
  189084. png_textp text_ptr;
  189085. png_charp key;
  189086. int comp_flag;
  189087. png_charp lang;
  189088. png_charp lang_key;
  189089. png_charp text;
  189090. int ret;
  189091. if (png_ptr->buffer_size < 4)
  189092. {
  189093. png_push_save_buffer(png_ptr);
  189094. return;
  189095. }
  189096. png_push_crc_finish(png_ptr);
  189097. #if defined(PNG_MAX_MALLOC_64K)
  189098. if (png_ptr->skip_length)
  189099. return;
  189100. #endif
  189101. key = png_ptr->current_text;
  189102. for (lang = key; *lang; lang++)
  189103. /* empty loop */ ;
  189104. if (lang < key + png_ptr->current_text_size - 3)
  189105. lang++;
  189106. comp_flag = *lang++;
  189107. lang++; /* skip comp_type, always zero */
  189108. for (lang_key = lang; *lang_key; lang_key++)
  189109. /* empty loop */ ;
  189110. lang_key++; /* skip NUL separator */
  189111. text=lang_key;
  189112. if (lang_key < key + png_ptr->current_text_size - 1)
  189113. {
  189114. for (; *text; text++)
  189115. /* empty loop */ ;
  189116. }
  189117. if (text < key + png_ptr->current_text_size)
  189118. text++;
  189119. text_ptr = (png_textp)png_malloc(png_ptr,
  189120. (png_uint_32)png_sizeof(png_text));
  189121. text_ptr->compression = comp_flag + 2;
  189122. text_ptr->key = key;
  189123. text_ptr->lang = lang;
  189124. text_ptr->lang_key = lang_key;
  189125. text_ptr->text = text;
  189126. text_ptr->text_length = 0;
  189127. text_ptr->itxt_length = png_strlen(text);
  189128. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189129. png_ptr->current_text = NULL;
  189130. png_free(png_ptr, text_ptr);
  189131. if (ret)
  189132. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189133. }
  189134. }
  189135. #endif
  189136. /* This function is called when we haven't found a handler for this
  189137. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189138. * name or a critical chunk), the chunk is (currently) silently ignored.
  189139. */
  189140. void /* PRIVATE */
  189141. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189142. length)
  189143. {
  189144. png_uint_32 skip=0;
  189145. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189146. if (!(png_ptr->chunk_name[0] & 0x20))
  189147. {
  189148. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189149. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189150. PNG_HANDLE_CHUNK_ALWAYS
  189151. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189152. && png_ptr->read_user_chunk_fn == NULL
  189153. #endif
  189154. )
  189155. #endif
  189156. png_chunk_error(png_ptr, "unknown critical chunk");
  189157. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189158. }
  189159. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189160. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189161. {
  189162. #ifdef PNG_MAX_MALLOC_64K
  189163. if (length > (png_uint_32)65535L)
  189164. {
  189165. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189166. skip = length - (png_uint_32)65535L;
  189167. length = (png_uint_32)65535L;
  189168. }
  189169. #endif
  189170. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189171. (png_charp)png_ptr->chunk_name, 5);
  189172. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189173. png_ptr->unknown_chunk.size = (png_size_t)length;
  189174. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189175. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189176. if(png_ptr->read_user_chunk_fn != NULL)
  189177. {
  189178. /* callback to user unknown chunk handler */
  189179. int ret;
  189180. ret = (*(png_ptr->read_user_chunk_fn))
  189181. (png_ptr, &png_ptr->unknown_chunk);
  189182. if (ret < 0)
  189183. png_chunk_error(png_ptr, "error in user chunk");
  189184. if (ret == 0)
  189185. {
  189186. if (!(png_ptr->chunk_name[0] & 0x20))
  189187. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189188. PNG_HANDLE_CHUNK_ALWAYS)
  189189. png_chunk_error(png_ptr, "unknown critical chunk");
  189190. png_set_unknown_chunks(png_ptr, info_ptr,
  189191. &png_ptr->unknown_chunk, 1);
  189192. }
  189193. }
  189194. #else
  189195. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189196. #endif
  189197. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189198. png_ptr->unknown_chunk.data = NULL;
  189199. }
  189200. else
  189201. #endif
  189202. skip=length;
  189203. png_push_crc_skip(png_ptr, skip);
  189204. }
  189205. void /* PRIVATE */
  189206. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189207. {
  189208. if (png_ptr->info_fn != NULL)
  189209. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189210. }
  189211. void /* PRIVATE */
  189212. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189213. {
  189214. if (png_ptr->end_fn != NULL)
  189215. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189216. }
  189217. void /* PRIVATE */
  189218. png_push_have_row(png_structp png_ptr, png_bytep row)
  189219. {
  189220. if (png_ptr->row_fn != NULL)
  189221. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189222. (int)png_ptr->pass);
  189223. }
  189224. void PNGAPI
  189225. png_progressive_combine_row (png_structp png_ptr,
  189226. png_bytep old_row, png_bytep new_row)
  189227. {
  189228. #ifdef PNG_USE_LOCAL_ARRAYS
  189229. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189230. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189231. #endif
  189232. if(png_ptr == NULL) return;
  189233. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189234. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189235. }
  189236. void PNGAPI
  189237. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189238. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189239. png_progressive_end_ptr end_fn)
  189240. {
  189241. if(png_ptr == NULL) return;
  189242. png_ptr->info_fn = info_fn;
  189243. png_ptr->row_fn = row_fn;
  189244. png_ptr->end_fn = end_fn;
  189245. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189246. }
  189247. png_voidp PNGAPI
  189248. png_get_progressive_ptr(png_structp png_ptr)
  189249. {
  189250. if(png_ptr == NULL) return (NULL);
  189251. return png_ptr->io_ptr;
  189252. }
  189253. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189254. /*** End of inlined file: pngpread.c ***/
  189255. /*** Start of inlined file: pngrio.c ***/
  189256. /* pngrio.c - functions for data input
  189257. *
  189258. * Last changed in libpng 1.2.13 November 13, 2006
  189259. * For conditions of distribution and use, see copyright notice in png.h
  189260. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189261. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189262. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189263. *
  189264. * This file provides a location for all input. Users who need
  189265. * special handling are expected to write a function that has the same
  189266. * arguments as this and performs a similar function, but that possibly
  189267. * has a different input method. Note that you shouldn't change this
  189268. * function, but rather write a replacement function and then make
  189269. * libpng use it at run time with png_set_read_fn(...).
  189270. */
  189271. #define PNG_INTERNAL
  189272. #if defined(PNG_READ_SUPPORTED)
  189273. /* Read the data from whatever input you are using. The default routine
  189274. reads from a file pointer. Note that this routine sometimes gets called
  189275. with very small lengths, so you should implement some kind of simple
  189276. buffering if you are using unbuffered reads. This should never be asked
  189277. to read more then 64K on a 16 bit machine. */
  189278. void /* PRIVATE */
  189279. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189280. {
  189281. png_debug1(4,"reading %d bytes\n", (int)length);
  189282. if (png_ptr->read_data_fn != NULL)
  189283. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  189284. else
  189285. png_error(png_ptr, "Call to NULL read function");
  189286. }
  189287. #if !defined(PNG_NO_STDIO)
  189288. /* This is the function that does the actual reading of data. If you are
  189289. not reading from a standard C stream, you should create a replacement
  189290. read_data function and use it at run time with png_set_read_fn(), rather
  189291. than changing the library. */
  189292. #ifndef USE_FAR_KEYWORD
  189293. void PNGAPI
  189294. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189295. {
  189296. png_size_t check;
  189297. if(png_ptr == NULL) return;
  189298. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  189299. * instead of an int, which is what fread() actually returns.
  189300. */
  189301. #if defined(_WIN32_WCE)
  189302. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189303. check = 0;
  189304. #else
  189305. check = (png_size_t)fread(data, (png_size_t)1, length,
  189306. (png_FILE_p)png_ptr->io_ptr);
  189307. #endif
  189308. if (check != length)
  189309. png_error(png_ptr, "Read Error");
  189310. }
  189311. #else
  189312. /* this is the model-independent version. Since the standard I/O library
  189313. can't handle far buffers in the medium and small models, we have to copy
  189314. the data.
  189315. */
  189316. #define NEAR_BUF_SIZE 1024
  189317. #define MIN(a,b) (a <= b ? a : b)
  189318. static void PNGAPI
  189319. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189320. {
  189321. int check;
  189322. png_byte *n_data;
  189323. png_FILE_p io_ptr;
  189324. if(png_ptr == NULL) return;
  189325. /* Check if data really is near. If so, use usual code. */
  189326. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189327. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189328. if ((png_bytep)n_data == data)
  189329. {
  189330. #if defined(_WIN32_WCE)
  189331. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189332. check = 0;
  189333. #else
  189334. check = fread(n_data, 1, length, io_ptr);
  189335. #endif
  189336. }
  189337. else
  189338. {
  189339. png_byte buf[NEAR_BUF_SIZE];
  189340. png_size_t read, remaining, err;
  189341. check = 0;
  189342. remaining = length;
  189343. do
  189344. {
  189345. read = MIN(NEAR_BUF_SIZE, remaining);
  189346. #if defined(_WIN32_WCE)
  189347. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189348. err = 0;
  189349. #else
  189350. err = fread(buf, (png_size_t)1, read, io_ptr);
  189351. #endif
  189352. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189353. if(err != read)
  189354. break;
  189355. else
  189356. check += err;
  189357. data += read;
  189358. remaining -= read;
  189359. }
  189360. while (remaining != 0);
  189361. }
  189362. if ((png_uint_32)check != (png_uint_32)length)
  189363. png_error(png_ptr, "read Error");
  189364. }
  189365. #endif
  189366. #endif
  189367. /* This function allows the application to supply a new input function
  189368. for libpng if standard C streams aren't being used.
  189369. This function takes as its arguments:
  189370. png_ptr - pointer to a png input data structure
  189371. io_ptr - pointer to user supplied structure containing info about
  189372. the input functions. May be NULL.
  189373. read_data_fn - pointer to a new input function that takes as its
  189374. arguments a pointer to a png_struct, a pointer to
  189375. a location where input data can be stored, and a 32-bit
  189376. unsigned int that is the number of bytes to be read.
  189377. To exit and output any fatal error messages the new write
  189378. function should call png_error(png_ptr, "Error msg"). */
  189379. void PNGAPI
  189380. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  189381. png_rw_ptr read_data_fn)
  189382. {
  189383. if(png_ptr == NULL) return;
  189384. png_ptr->io_ptr = io_ptr;
  189385. #if !defined(PNG_NO_STDIO)
  189386. if (read_data_fn != NULL)
  189387. png_ptr->read_data_fn = read_data_fn;
  189388. else
  189389. png_ptr->read_data_fn = png_default_read_data;
  189390. #else
  189391. png_ptr->read_data_fn = read_data_fn;
  189392. #endif
  189393. /* It is an error to write to a read device */
  189394. if (png_ptr->write_data_fn != NULL)
  189395. {
  189396. png_ptr->write_data_fn = NULL;
  189397. png_warning(png_ptr,
  189398. "It's an error to set both read_data_fn and write_data_fn in the ");
  189399. png_warning(png_ptr,
  189400. "same structure. Resetting write_data_fn to NULL.");
  189401. }
  189402. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  189403. png_ptr->output_flush_fn = NULL;
  189404. #endif
  189405. }
  189406. #endif /* PNG_READ_SUPPORTED */
  189407. /*** End of inlined file: pngrio.c ***/
  189408. /*** Start of inlined file: pngrtran.c ***/
  189409. /* pngrtran.c - transforms the data in a row for PNG readers
  189410. *
  189411. * Last changed in libpng 1.2.21 [October 4, 2007]
  189412. * For conditions of distribution and use, see copyright notice in png.h
  189413. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189414. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189415. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189416. *
  189417. * This file contains functions optionally called by an application
  189418. * in order to tell libpng how to handle data when reading a PNG.
  189419. * Transformations that are used in both reading and writing are
  189420. * in pngtrans.c.
  189421. */
  189422. #define PNG_INTERNAL
  189423. #if defined(PNG_READ_SUPPORTED)
  189424. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  189425. void PNGAPI
  189426. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  189427. {
  189428. png_debug(1, "in png_set_crc_action\n");
  189429. /* Tell libpng how we react to CRC errors in critical chunks */
  189430. if(png_ptr == NULL) return;
  189431. switch (crit_action)
  189432. {
  189433. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189434. break;
  189435. case PNG_CRC_WARN_USE: /* warn/use data */
  189436. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189437. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  189438. break;
  189439. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189440. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189441. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  189442. PNG_FLAG_CRC_CRITICAL_IGNORE;
  189443. break;
  189444. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  189445. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  189446. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189447. case PNG_CRC_DEFAULT:
  189448. default:
  189449. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189450. break;
  189451. }
  189452. switch (ancil_action)
  189453. {
  189454. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189455. break;
  189456. case PNG_CRC_WARN_USE: /* warn/use data */
  189457. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189458. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  189459. break;
  189460. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189461. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189462. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  189463. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189464. break;
  189465. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189466. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189467. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189468. break;
  189469. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  189470. case PNG_CRC_DEFAULT:
  189471. default:
  189472. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189473. break;
  189474. }
  189475. }
  189476. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  189477. defined(PNG_FLOATING_POINT_SUPPORTED)
  189478. /* handle alpha and tRNS via a background color */
  189479. void PNGAPI
  189480. png_set_background(png_structp png_ptr,
  189481. png_color_16p background_color, int background_gamma_code,
  189482. int need_expand, double background_gamma)
  189483. {
  189484. png_debug(1, "in png_set_background\n");
  189485. if(png_ptr == NULL) return;
  189486. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  189487. {
  189488. png_warning(png_ptr, "Application must supply a known background gamma");
  189489. return;
  189490. }
  189491. png_ptr->transformations |= PNG_BACKGROUND;
  189492. png_memcpy(&(png_ptr->background), background_color,
  189493. png_sizeof(png_color_16));
  189494. png_ptr->background_gamma = (float)background_gamma;
  189495. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  189496. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  189497. }
  189498. #endif
  189499. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  189500. /* strip 16 bit depth files to 8 bit depth */
  189501. void PNGAPI
  189502. png_set_strip_16(png_structp png_ptr)
  189503. {
  189504. png_debug(1, "in png_set_strip_16\n");
  189505. if(png_ptr == NULL) return;
  189506. png_ptr->transformations |= PNG_16_TO_8;
  189507. }
  189508. #endif
  189509. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  189510. void PNGAPI
  189511. png_set_strip_alpha(png_structp png_ptr)
  189512. {
  189513. png_debug(1, "in png_set_strip_alpha\n");
  189514. if(png_ptr == NULL) return;
  189515. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  189516. }
  189517. #endif
  189518. #if defined(PNG_READ_DITHER_SUPPORTED)
  189519. /* Dither file to 8 bit. Supply a palette, the current number
  189520. * of elements in the palette, the maximum number of elements
  189521. * allowed, and a histogram if possible. If the current number
  189522. * of colors is greater then the maximum number, the palette will be
  189523. * modified to fit in the maximum number. "full_dither" indicates
  189524. * whether we need a dithering cube set up for RGB images, or if we
  189525. * simply are reducing the number of colors in a paletted image.
  189526. */
  189527. typedef struct png_dsort_struct
  189528. {
  189529. struct png_dsort_struct FAR * next;
  189530. png_byte left;
  189531. png_byte right;
  189532. } png_dsort;
  189533. typedef png_dsort FAR * png_dsortp;
  189534. typedef png_dsort FAR * FAR * png_dsortpp;
  189535. void PNGAPI
  189536. png_set_dither(png_structp png_ptr, png_colorp palette,
  189537. int num_palette, int maximum_colors, png_uint_16p histogram,
  189538. int full_dither)
  189539. {
  189540. png_debug(1, "in png_set_dither\n");
  189541. if(png_ptr == NULL) return;
  189542. png_ptr->transformations |= PNG_DITHER;
  189543. if (!full_dither)
  189544. {
  189545. int i;
  189546. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  189547. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189548. for (i = 0; i < num_palette; i++)
  189549. png_ptr->dither_index[i] = (png_byte)i;
  189550. }
  189551. if (num_palette > maximum_colors)
  189552. {
  189553. if (histogram != NULL)
  189554. {
  189555. /* This is easy enough, just throw out the least used colors.
  189556. Perhaps not the best solution, but good enough. */
  189557. int i;
  189558. /* initialize an array to sort colors */
  189559. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  189560. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189561. /* initialize the dither_sort array */
  189562. for (i = 0; i < num_palette; i++)
  189563. png_ptr->dither_sort[i] = (png_byte)i;
  189564. /* Find the least used palette entries by starting a
  189565. bubble sort, and running it until we have sorted
  189566. out enough colors. Note that we don't care about
  189567. sorting all the colors, just finding which are
  189568. least used. */
  189569. for (i = num_palette - 1; i >= maximum_colors; i--)
  189570. {
  189571. int done; /* to stop early if the list is pre-sorted */
  189572. int j;
  189573. done = 1;
  189574. for (j = 0; j < i; j++)
  189575. {
  189576. if (histogram[png_ptr->dither_sort[j]]
  189577. < histogram[png_ptr->dither_sort[j + 1]])
  189578. {
  189579. png_byte t;
  189580. t = png_ptr->dither_sort[j];
  189581. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  189582. png_ptr->dither_sort[j + 1] = t;
  189583. done = 0;
  189584. }
  189585. }
  189586. if (done)
  189587. break;
  189588. }
  189589. /* swap the palette around, and set up a table, if necessary */
  189590. if (full_dither)
  189591. {
  189592. int j = num_palette;
  189593. /* put all the useful colors within the max, but don't
  189594. move the others */
  189595. for (i = 0; i < maximum_colors; i++)
  189596. {
  189597. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189598. {
  189599. do
  189600. j--;
  189601. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189602. palette[i] = palette[j];
  189603. }
  189604. }
  189605. }
  189606. else
  189607. {
  189608. int j = num_palette;
  189609. /* move all the used colors inside the max limit, and
  189610. develop a translation table */
  189611. for (i = 0; i < maximum_colors; i++)
  189612. {
  189613. /* only move the colors we need to */
  189614. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189615. {
  189616. png_color tmp_color;
  189617. do
  189618. j--;
  189619. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189620. tmp_color = palette[j];
  189621. palette[j] = palette[i];
  189622. palette[i] = tmp_color;
  189623. /* indicate where the color went */
  189624. png_ptr->dither_index[j] = (png_byte)i;
  189625. png_ptr->dither_index[i] = (png_byte)j;
  189626. }
  189627. }
  189628. /* find closest color for those colors we are not using */
  189629. for (i = 0; i < num_palette; i++)
  189630. {
  189631. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  189632. {
  189633. int min_d, k, min_k, d_index;
  189634. /* find the closest color to one we threw out */
  189635. d_index = png_ptr->dither_index[i];
  189636. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  189637. for (k = 1, min_k = 0; k < maximum_colors; k++)
  189638. {
  189639. int d;
  189640. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  189641. if (d < min_d)
  189642. {
  189643. min_d = d;
  189644. min_k = k;
  189645. }
  189646. }
  189647. /* point to closest color */
  189648. png_ptr->dither_index[i] = (png_byte)min_k;
  189649. }
  189650. }
  189651. }
  189652. png_free(png_ptr, png_ptr->dither_sort);
  189653. png_ptr->dither_sort=NULL;
  189654. }
  189655. else
  189656. {
  189657. /* This is much harder to do simply (and quickly). Perhaps
  189658. we need to go through a median cut routine, but those
  189659. don't always behave themselves with only a few colors
  189660. as input. So we will just find the closest two colors,
  189661. and throw out one of them (chosen somewhat randomly).
  189662. [We don't understand this at all, so if someone wants to
  189663. work on improving it, be our guest - AED, GRP]
  189664. */
  189665. int i;
  189666. int max_d;
  189667. int num_new_palette;
  189668. png_dsortp t;
  189669. png_dsortpp hash;
  189670. t=NULL;
  189671. /* initialize palette index arrays */
  189672. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  189673. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189674. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  189675. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189676. /* initialize the sort array */
  189677. for (i = 0; i < num_palette; i++)
  189678. {
  189679. png_ptr->index_to_palette[i] = (png_byte)i;
  189680. png_ptr->palette_to_index[i] = (png_byte)i;
  189681. }
  189682. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  189683. png_sizeof (png_dsortp)));
  189684. for (i = 0; i < 769; i++)
  189685. hash[i] = NULL;
  189686. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  189687. num_new_palette = num_palette;
  189688. /* initial wild guess at how far apart the farthest pixel
  189689. pair we will be eliminating will be. Larger
  189690. numbers mean more areas will be allocated, Smaller
  189691. numbers run the risk of not saving enough data, and
  189692. having to do this all over again.
  189693. I have not done extensive checking on this number.
  189694. */
  189695. max_d = 96;
  189696. while (num_new_palette > maximum_colors)
  189697. {
  189698. for (i = 0; i < num_new_palette - 1; i++)
  189699. {
  189700. int j;
  189701. for (j = i + 1; j < num_new_palette; j++)
  189702. {
  189703. int d;
  189704. d = PNG_COLOR_DIST(palette[i], palette[j]);
  189705. if (d <= max_d)
  189706. {
  189707. t = (png_dsortp)png_malloc_warn(png_ptr,
  189708. (png_uint_32)(png_sizeof(png_dsort)));
  189709. if (t == NULL)
  189710. break;
  189711. t->next = hash[d];
  189712. t->left = (png_byte)i;
  189713. t->right = (png_byte)j;
  189714. hash[d] = t;
  189715. }
  189716. }
  189717. if (t == NULL)
  189718. break;
  189719. }
  189720. if (t != NULL)
  189721. for (i = 0; i <= max_d; i++)
  189722. {
  189723. if (hash[i] != NULL)
  189724. {
  189725. png_dsortp p;
  189726. for (p = hash[i]; p; p = p->next)
  189727. {
  189728. if ((int)png_ptr->index_to_palette[p->left]
  189729. < num_new_palette &&
  189730. (int)png_ptr->index_to_palette[p->right]
  189731. < num_new_palette)
  189732. {
  189733. int j, next_j;
  189734. if (num_new_palette & 0x01)
  189735. {
  189736. j = p->left;
  189737. next_j = p->right;
  189738. }
  189739. else
  189740. {
  189741. j = p->right;
  189742. next_j = p->left;
  189743. }
  189744. num_new_palette--;
  189745. palette[png_ptr->index_to_palette[j]]
  189746. = palette[num_new_palette];
  189747. if (!full_dither)
  189748. {
  189749. int k;
  189750. for (k = 0; k < num_palette; k++)
  189751. {
  189752. if (png_ptr->dither_index[k] ==
  189753. png_ptr->index_to_palette[j])
  189754. png_ptr->dither_index[k] =
  189755. png_ptr->index_to_palette[next_j];
  189756. if ((int)png_ptr->dither_index[k] ==
  189757. num_new_palette)
  189758. png_ptr->dither_index[k] =
  189759. png_ptr->index_to_palette[j];
  189760. }
  189761. }
  189762. png_ptr->index_to_palette[png_ptr->palette_to_index
  189763. [num_new_palette]] = png_ptr->index_to_palette[j];
  189764. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  189765. = png_ptr->palette_to_index[num_new_palette];
  189766. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  189767. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  189768. }
  189769. if (num_new_palette <= maximum_colors)
  189770. break;
  189771. }
  189772. if (num_new_palette <= maximum_colors)
  189773. break;
  189774. }
  189775. }
  189776. for (i = 0; i < 769; i++)
  189777. {
  189778. if (hash[i] != NULL)
  189779. {
  189780. png_dsortp p = hash[i];
  189781. while (p)
  189782. {
  189783. t = p->next;
  189784. png_free(png_ptr, p);
  189785. p = t;
  189786. }
  189787. }
  189788. hash[i] = 0;
  189789. }
  189790. max_d += 96;
  189791. }
  189792. png_free(png_ptr, hash);
  189793. png_free(png_ptr, png_ptr->palette_to_index);
  189794. png_free(png_ptr, png_ptr->index_to_palette);
  189795. png_ptr->palette_to_index=NULL;
  189796. png_ptr->index_to_palette=NULL;
  189797. }
  189798. num_palette = maximum_colors;
  189799. }
  189800. if (png_ptr->palette == NULL)
  189801. {
  189802. png_ptr->palette = palette;
  189803. }
  189804. png_ptr->num_palette = (png_uint_16)num_palette;
  189805. if (full_dither)
  189806. {
  189807. int i;
  189808. png_bytep distance;
  189809. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  189810. PNG_DITHER_BLUE_BITS;
  189811. int num_red = (1 << PNG_DITHER_RED_BITS);
  189812. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  189813. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  189814. png_size_t num_entries = ((png_size_t)1 << total_bits);
  189815. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  189816. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  189817. png_memset(png_ptr->palette_lookup, 0, num_entries *
  189818. png_sizeof (png_byte));
  189819. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  189820. png_sizeof(png_byte)));
  189821. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  189822. for (i = 0; i < num_palette; i++)
  189823. {
  189824. int ir, ig, ib;
  189825. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  189826. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  189827. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  189828. for (ir = 0; ir < num_red; ir++)
  189829. {
  189830. /* int dr = abs(ir - r); */
  189831. int dr = ((ir > r) ? ir - r : r - ir);
  189832. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  189833. for (ig = 0; ig < num_green; ig++)
  189834. {
  189835. /* int dg = abs(ig - g); */
  189836. int dg = ((ig > g) ? ig - g : g - ig);
  189837. int dt = dr + dg;
  189838. int dm = ((dr > dg) ? dr : dg);
  189839. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  189840. for (ib = 0; ib < num_blue; ib++)
  189841. {
  189842. int d_index = index_g | ib;
  189843. /* int db = abs(ib - b); */
  189844. int db = ((ib > b) ? ib - b : b - ib);
  189845. int dmax = ((dm > db) ? dm : db);
  189846. int d = dmax + dt + db;
  189847. if (d < (int)distance[d_index])
  189848. {
  189849. distance[d_index] = (png_byte)d;
  189850. png_ptr->palette_lookup[d_index] = (png_byte)i;
  189851. }
  189852. }
  189853. }
  189854. }
  189855. }
  189856. png_free(png_ptr, distance);
  189857. }
  189858. }
  189859. #endif
  189860. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  189861. /* Transform the image from the file_gamma to the screen_gamma. We
  189862. * only do transformations on images where the file_gamma and screen_gamma
  189863. * are not close reciprocals, otherwise it slows things down slightly, and
  189864. * also needlessly introduces small errors.
  189865. *
  189866. * We will turn off gamma transformation later if no semitransparent entries
  189867. * are present in the tRNS array for palette images. We can't do it here
  189868. * because we don't necessarily have the tRNS chunk yet.
  189869. */
  189870. void PNGAPI
  189871. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  189872. {
  189873. png_debug(1, "in png_set_gamma\n");
  189874. if(png_ptr == NULL) return;
  189875. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  189876. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  189877. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  189878. png_ptr->transformations |= PNG_GAMMA;
  189879. png_ptr->gamma = (float)file_gamma;
  189880. png_ptr->screen_gamma = (float)scrn_gamma;
  189881. }
  189882. #endif
  189883. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189884. /* Expand paletted images to RGB, expand grayscale images of
  189885. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  189886. * to alpha channels.
  189887. */
  189888. void PNGAPI
  189889. png_set_expand(png_structp png_ptr)
  189890. {
  189891. png_debug(1, "in png_set_expand\n");
  189892. if(png_ptr == NULL) return;
  189893. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189894. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189895. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189896. #endif
  189897. }
  189898. /* GRR 19990627: the following three functions currently are identical
  189899. * to png_set_expand(). However, it is entirely reasonable that someone
  189900. * might wish to expand an indexed image to RGB but *not* expand a single,
  189901. * fully transparent palette entry to a full alpha channel--perhaps instead
  189902. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  189903. * the transparent color with a particular RGB value, or drop tRNS entirely.
  189904. * IOW, a future version of the library may make the transformations flag
  189905. * a bit more fine-grained, with separate bits for each of these three
  189906. * functions.
  189907. *
  189908. * More to the point, these functions make it obvious what libpng will be
  189909. * doing, whereas "expand" can (and does) mean any number of things.
  189910. *
  189911. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  189912. * to expand only the sample depth but not to expand the tRNS to alpha.
  189913. */
  189914. /* Expand paletted images to RGB. */
  189915. void PNGAPI
  189916. png_set_palette_to_rgb(png_structp png_ptr)
  189917. {
  189918. png_debug(1, "in png_set_palette_to_rgb\n");
  189919. if(png_ptr == NULL) return;
  189920. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189921. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189922. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  189923. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189924. #endif
  189925. }
  189926. #if !defined(PNG_1_0_X)
  189927. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  189928. void PNGAPI
  189929. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  189930. {
  189931. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  189932. if(png_ptr == NULL) return;
  189933. png_ptr->transformations |= PNG_EXPAND;
  189934. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189935. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189936. #endif
  189937. }
  189938. #endif
  189939. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  189940. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  189941. /* Deprecated as of libpng-1.2.9 */
  189942. void PNGAPI
  189943. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  189944. {
  189945. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  189946. if(png_ptr == NULL) return;
  189947. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189948. }
  189949. #endif
  189950. /* Expand tRNS chunks to alpha channels. */
  189951. void PNGAPI
  189952. png_set_tRNS_to_alpha(png_structp png_ptr)
  189953. {
  189954. png_debug(1, "in png_set_tRNS_to_alpha\n");
  189955. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189956. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189957. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189958. #endif
  189959. }
  189960. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  189961. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  189962. void PNGAPI
  189963. png_set_gray_to_rgb(png_structp png_ptr)
  189964. {
  189965. png_debug(1, "in png_set_gray_to_rgb\n");
  189966. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  189967. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189968. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189969. #endif
  189970. }
  189971. #endif
  189972. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  189973. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  189974. /* Convert a RGB image to a grayscale of the same width. This allows us,
  189975. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  189976. */
  189977. void PNGAPI
  189978. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  189979. double green)
  189980. {
  189981. int red_fixed = (int)((float)red*100000.0 + 0.5);
  189982. int green_fixed = (int)((float)green*100000.0 + 0.5);
  189983. if(png_ptr == NULL) return;
  189984. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  189985. }
  189986. #endif
  189987. void PNGAPI
  189988. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  189989. png_fixed_point red, png_fixed_point green)
  189990. {
  189991. png_debug(1, "in png_set_rgb_to_gray\n");
  189992. if(png_ptr == NULL) return;
  189993. switch(error_action)
  189994. {
  189995. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  189996. break;
  189997. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  189998. break;
  189999. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190000. }
  190001. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190002. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190003. png_ptr->transformations |= PNG_EXPAND;
  190004. #else
  190005. {
  190006. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190007. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190008. }
  190009. #endif
  190010. {
  190011. png_uint_16 red_int, green_int;
  190012. if(red < 0 || green < 0)
  190013. {
  190014. red_int = 6968; /* .212671 * 32768 + .5 */
  190015. green_int = 23434; /* .715160 * 32768 + .5 */
  190016. }
  190017. else if(red + green < 100000L)
  190018. {
  190019. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190020. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190021. }
  190022. else
  190023. {
  190024. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190025. red_int = 6968;
  190026. green_int = 23434;
  190027. }
  190028. png_ptr->rgb_to_gray_red_coeff = red_int;
  190029. png_ptr->rgb_to_gray_green_coeff = green_int;
  190030. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190031. }
  190032. }
  190033. #endif
  190034. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190035. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190036. defined(PNG_LEGACY_SUPPORTED)
  190037. void PNGAPI
  190038. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190039. read_user_transform_fn)
  190040. {
  190041. png_debug(1, "in png_set_read_user_transform_fn\n");
  190042. if(png_ptr == NULL) return;
  190043. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190044. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190045. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190046. #endif
  190047. #ifdef PNG_LEGACY_SUPPORTED
  190048. if(read_user_transform_fn)
  190049. png_warning(png_ptr,
  190050. "This version of libpng does not support user transforms");
  190051. #endif
  190052. }
  190053. #endif
  190054. /* Initialize everything needed for the read. This includes modifying
  190055. * the palette.
  190056. */
  190057. void /* PRIVATE */
  190058. png_init_read_transformations(png_structp png_ptr)
  190059. {
  190060. png_debug(1, "in png_init_read_transformations\n");
  190061. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190062. if(png_ptr != NULL)
  190063. #endif
  190064. {
  190065. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190066. || defined(PNG_READ_GAMMA_SUPPORTED)
  190067. int color_type = png_ptr->color_type;
  190068. #endif
  190069. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190070. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190071. /* Detect gray background and attempt to enable optimization
  190072. * for gray --> RGB case */
  190073. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190074. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190075. * background color might actually be gray yet not be flagged as such.
  190076. * This is not a problem for the current code, which uses
  190077. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190078. * png_do_gray_to_rgb() transformation.
  190079. */
  190080. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190081. !(color_type & PNG_COLOR_MASK_COLOR))
  190082. {
  190083. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190084. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190085. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190086. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190087. png_ptr->background.red == png_ptr->background.green &&
  190088. png_ptr->background.red == png_ptr->background.blue)
  190089. {
  190090. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190091. png_ptr->background.gray = png_ptr->background.red;
  190092. }
  190093. #endif
  190094. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190095. (png_ptr->transformations & PNG_EXPAND))
  190096. {
  190097. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190098. {
  190099. /* expand background and tRNS chunks */
  190100. switch (png_ptr->bit_depth)
  190101. {
  190102. case 1:
  190103. png_ptr->background.gray *= (png_uint_16)0xff;
  190104. png_ptr->background.red = png_ptr->background.green
  190105. = png_ptr->background.blue = png_ptr->background.gray;
  190106. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190107. {
  190108. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190109. png_ptr->trans_values.red = png_ptr->trans_values.green
  190110. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190111. }
  190112. break;
  190113. case 2:
  190114. png_ptr->background.gray *= (png_uint_16)0x55;
  190115. png_ptr->background.red = png_ptr->background.green
  190116. = png_ptr->background.blue = png_ptr->background.gray;
  190117. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190118. {
  190119. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190120. png_ptr->trans_values.red = png_ptr->trans_values.green
  190121. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190122. }
  190123. break;
  190124. case 4:
  190125. png_ptr->background.gray *= (png_uint_16)0x11;
  190126. png_ptr->background.red = png_ptr->background.green
  190127. = png_ptr->background.blue = png_ptr->background.gray;
  190128. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190129. {
  190130. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190131. png_ptr->trans_values.red = png_ptr->trans_values.green
  190132. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190133. }
  190134. break;
  190135. case 8:
  190136. case 16:
  190137. png_ptr->background.red = png_ptr->background.green
  190138. = png_ptr->background.blue = png_ptr->background.gray;
  190139. break;
  190140. }
  190141. }
  190142. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190143. {
  190144. png_ptr->background.red =
  190145. png_ptr->palette[png_ptr->background.index].red;
  190146. png_ptr->background.green =
  190147. png_ptr->palette[png_ptr->background.index].green;
  190148. png_ptr->background.blue =
  190149. png_ptr->palette[png_ptr->background.index].blue;
  190150. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190151. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190152. {
  190153. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190154. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190155. #endif
  190156. {
  190157. /* invert the alpha channel (in tRNS) unless the pixels are
  190158. going to be expanded, in which case leave it for later */
  190159. int i,istop;
  190160. istop=(int)png_ptr->num_trans;
  190161. for (i=0; i<istop; i++)
  190162. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190163. }
  190164. }
  190165. #endif
  190166. }
  190167. }
  190168. #endif
  190169. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190170. png_ptr->background_1 = png_ptr->background;
  190171. #endif
  190172. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190173. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190174. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190175. < PNG_GAMMA_THRESHOLD))
  190176. {
  190177. int i,k;
  190178. k=0;
  190179. for (i=0; i<png_ptr->num_trans; i++)
  190180. {
  190181. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190182. k=1; /* partial transparency is present */
  190183. }
  190184. if (k == 0)
  190185. png_ptr->transformations &= (~PNG_GAMMA);
  190186. }
  190187. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190188. png_ptr->gamma != 0.0)
  190189. {
  190190. png_build_gamma_table(png_ptr);
  190191. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190192. if (png_ptr->transformations & PNG_BACKGROUND)
  190193. {
  190194. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190195. {
  190196. /* could skip if no transparency and
  190197. */
  190198. png_color back, back_1;
  190199. png_colorp palette = png_ptr->palette;
  190200. int num_palette = png_ptr->num_palette;
  190201. int i;
  190202. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190203. {
  190204. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190205. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190206. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190207. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190208. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190209. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190210. }
  190211. else
  190212. {
  190213. double g, gs;
  190214. switch (png_ptr->background_gamma_type)
  190215. {
  190216. case PNG_BACKGROUND_GAMMA_SCREEN:
  190217. g = (png_ptr->screen_gamma);
  190218. gs = 1.0;
  190219. break;
  190220. case PNG_BACKGROUND_GAMMA_FILE:
  190221. g = 1.0 / (png_ptr->gamma);
  190222. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190223. break;
  190224. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190225. g = 1.0 / (png_ptr->background_gamma);
  190226. gs = 1.0 / (png_ptr->background_gamma *
  190227. png_ptr->screen_gamma);
  190228. break;
  190229. default:
  190230. g = 1.0; /* back_1 */
  190231. gs = 1.0; /* back */
  190232. }
  190233. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190234. {
  190235. back.red = (png_byte)png_ptr->background.red;
  190236. back.green = (png_byte)png_ptr->background.green;
  190237. back.blue = (png_byte)png_ptr->background.blue;
  190238. }
  190239. else
  190240. {
  190241. back.red = (png_byte)(pow(
  190242. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190243. back.green = (png_byte)(pow(
  190244. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190245. back.blue = (png_byte)(pow(
  190246. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190247. }
  190248. back_1.red = (png_byte)(pow(
  190249. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190250. back_1.green = (png_byte)(pow(
  190251. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190252. back_1.blue = (png_byte)(pow(
  190253. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190254. }
  190255. for (i = 0; i < num_palette; i++)
  190256. {
  190257. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190258. {
  190259. if (png_ptr->trans[i] == 0)
  190260. {
  190261. palette[i] = back;
  190262. }
  190263. else /* if (png_ptr->trans[i] != 0xff) */
  190264. {
  190265. png_byte v, w;
  190266. v = png_ptr->gamma_to_1[palette[i].red];
  190267. png_composite(w, v, png_ptr->trans[i], back_1.red);
  190268. palette[i].red = png_ptr->gamma_from_1[w];
  190269. v = png_ptr->gamma_to_1[palette[i].green];
  190270. png_composite(w, v, png_ptr->trans[i], back_1.green);
  190271. palette[i].green = png_ptr->gamma_from_1[w];
  190272. v = png_ptr->gamma_to_1[palette[i].blue];
  190273. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  190274. palette[i].blue = png_ptr->gamma_from_1[w];
  190275. }
  190276. }
  190277. else
  190278. {
  190279. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190280. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190281. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190282. }
  190283. }
  190284. }
  190285. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  190286. else
  190287. /* color_type != PNG_COLOR_TYPE_PALETTE */
  190288. {
  190289. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  190290. double g = 1.0;
  190291. double gs = 1.0;
  190292. switch (png_ptr->background_gamma_type)
  190293. {
  190294. case PNG_BACKGROUND_GAMMA_SCREEN:
  190295. g = (png_ptr->screen_gamma);
  190296. gs = 1.0;
  190297. break;
  190298. case PNG_BACKGROUND_GAMMA_FILE:
  190299. g = 1.0 / (png_ptr->gamma);
  190300. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190301. break;
  190302. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190303. g = 1.0 / (png_ptr->background_gamma);
  190304. gs = 1.0 / (png_ptr->background_gamma *
  190305. png_ptr->screen_gamma);
  190306. break;
  190307. }
  190308. png_ptr->background_1.gray = (png_uint_16)(pow(
  190309. (double)png_ptr->background.gray / m, g) * m + .5);
  190310. png_ptr->background.gray = (png_uint_16)(pow(
  190311. (double)png_ptr->background.gray / m, gs) * m + .5);
  190312. if ((png_ptr->background.red != png_ptr->background.green) ||
  190313. (png_ptr->background.red != png_ptr->background.blue) ||
  190314. (png_ptr->background.red != png_ptr->background.gray))
  190315. {
  190316. /* RGB or RGBA with color background */
  190317. png_ptr->background_1.red = (png_uint_16)(pow(
  190318. (double)png_ptr->background.red / m, g) * m + .5);
  190319. png_ptr->background_1.green = (png_uint_16)(pow(
  190320. (double)png_ptr->background.green / m, g) * m + .5);
  190321. png_ptr->background_1.blue = (png_uint_16)(pow(
  190322. (double)png_ptr->background.blue / m, g) * m + .5);
  190323. png_ptr->background.red = (png_uint_16)(pow(
  190324. (double)png_ptr->background.red / m, gs) * m + .5);
  190325. png_ptr->background.green = (png_uint_16)(pow(
  190326. (double)png_ptr->background.green / m, gs) * m + .5);
  190327. png_ptr->background.blue = (png_uint_16)(pow(
  190328. (double)png_ptr->background.blue / m, gs) * m + .5);
  190329. }
  190330. else
  190331. {
  190332. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190333. png_ptr->background_1.red = png_ptr->background_1.green
  190334. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190335. png_ptr->background.red = png_ptr->background.green
  190336. = png_ptr->background.blue = png_ptr->background.gray;
  190337. }
  190338. }
  190339. }
  190340. else
  190341. /* transformation does not include PNG_BACKGROUND */
  190342. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190343. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190344. {
  190345. png_colorp palette = png_ptr->palette;
  190346. int num_palette = png_ptr->num_palette;
  190347. int i;
  190348. for (i = 0; i < num_palette; i++)
  190349. {
  190350. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190351. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190352. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190353. }
  190354. }
  190355. }
  190356. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190357. else
  190358. #endif
  190359. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190360. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190361. /* No GAMMA transformation */
  190362. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190363. (color_type == PNG_COLOR_TYPE_PALETTE))
  190364. {
  190365. int i;
  190366. int istop = (int)png_ptr->num_trans;
  190367. png_color back;
  190368. png_colorp palette = png_ptr->palette;
  190369. back.red = (png_byte)png_ptr->background.red;
  190370. back.green = (png_byte)png_ptr->background.green;
  190371. back.blue = (png_byte)png_ptr->background.blue;
  190372. for (i = 0; i < istop; i++)
  190373. {
  190374. if (png_ptr->trans[i] == 0)
  190375. {
  190376. palette[i] = back;
  190377. }
  190378. else if (png_ptr->trans[i] != 0xff)
  190379. {
  190380. /* The png_composite() macro is defined in png.h */
  190381. png_composite(palette[i].red, palette[i].red,
  190382. png_ptr->trans[i], back.red);
  190383. png_composite(palette[i].green, palette[i].green,
  190384. png_ptr->trans[i], back.green);
  190385. png_composite(palette[i].blue, palette[i].blue,
  190386. png_ptr->trans[i], back.blue);
  190387. }
  190388. }
  190389. }
  190390. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190391. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190392. if ((png_ptr->transformations & PNG_SHIFT) &&
  190393. (color_type == PNG_COLOR_TYPE_PALETTE))
  190394. {
  190395. png_uint_16 i;
  190396. png_uint_16 istop = png_ptr->num_palette;
  190397. int sr = 8 - png_ptr->sig_bit.red;
  190398. int sg = 8 - png_ptr->sig_bit.green;
  190399. int sb = 8 - png_ptr->sig_bit.blue;
  190400. if (sr < 0 || sr > 8)
  190401. sr = 0;
  190402. if (sg < 0 || sg > 8)
  190403. sg = 0;
  190404. if (sb < 0 || sb > 8)
  190405. sb = 0;
  190406. for (i = 0; i < istop; i++)
  190407. {
  190408. png_ptr->palette[i].red >>= sr;
  190409. png_ptr->palette[i].green >>= sg;
  190410. png_ptr->palette[i].blue >>= sb;
  190411. }
  190412. }
  190413. #endif /* PNG_READ_SHIFT_SUPPORTED */
  190414. }
  190415. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  190416. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  190417. if(png_ptr)
  190418. return;
  190419. #endif
  190420. }
  190421. /* Modify the info structure to reflect the transformations. The
  190422. * info should be updated so a PNG file could be written with it,
  190423. * assuming the transformations result in valid PNG data.
  190424. */
  190425. void /* PRIVATE */
  190426. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  190427. {
  190428. png_debug(1, "in png_read_transform_info\n");
  190429. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190430. if (png_ptr->transformations & PNG_EXPAND)
  190431. {
  190432. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190433. {
  190434. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  190435. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190436. else
  190437. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  190438. info_ptr->bit_depth = 8;
  190439. info_ptr->num_trans = 0;
  190440. }
  190441. else
  190442. {
  190443. if (png_ptr->num_trans)
  190444. {
  190445. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  190446. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190447. else
  190448. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190449. }
  190450. if (info_ptr->bit_depth < 8)
  190451. info_ptr->bit_depth = 8;
  190452. info_ptr->num_trans = 0;
  190453. }
  190454. }
  190455. #endif
  190456. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190457. if (png_ptr->transformations & PNG_BACKGROUND)
  190458. {
  190459. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190460. info_ptr->num_trans = 0;
  190461. info_ptr->background = png_ptr->background;
  190462. }
  190463. #endif
  190464. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190465. if (png_ptr->transformations & PNG_GAMMA)
  190466. {
  190467. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190468. info_ptr->gamma = png_ptr->gamma;
  190469. #endif
  190470. #ifdef PNG_FIXED_POINT_SUPPORTED
  190471. info_ptr->int_gamma = png_ptr->int_gamma;
  190472. #endif
  190473. }
  190474. #endif
  190475. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190476. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  190477. info_ptr->bit_depth = 8;
  190478. #endif
  190479. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190480. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  190481. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190482. #endif
  190483. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190484. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190485. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  190486. #endif
  190487. #if defined(PNG_READ_DITHER_SUPPORTED)
  190488. if (png_ptr->transformations & PNG_DITHER)
  190489. {
  190490. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190491. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  190492. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  190493. {
  190494. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  190495. }
  190496. }
  190497. #endif
  190498. #if defined(PNG_READ_PACK_SUPPORTED)
  190499. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  190500. info_ptr->bit_depth = 8;
  190501. #endif
  190502. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190503. info_ptr->channels = 1;
  190504. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190505. info_ptr->channels = 3;
  190506. else
  190507. info_ptr->channels = 1;
  190508. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190509. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190510. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190511. #endif
  190512. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  190513. info_ptr->channels++;
  190514. #if defined(PNG_READ_FILLER_SUPPORTED)
  190515. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  190516. if ((png_ptr->transformations & PNG_FILLER) &&
  190517. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190518. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  190519. {
  190520. info_ptr->channels++;
  190521. /* if adding a true alpha channel not just filler */
  190522. #if !defined(PNG_1_0_X)
  190523. if (png_ptr->transformations & PNG_ADD_ALPHA)
  190524. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190525. #endif
  190526. }
  190527. #endif
  190528. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  190529. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190530. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  190531. {
  190532. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  190533. info_ptr->bit_depth = png_ptr->user_transform_depth;
  190534. if(info_ptr->channels < png_ptr->user_transform_channels)
  190535. info_ptr->channels = png_ptr->user_transform_channels;
  190536. }
  190537. #endif
  190538. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  190539. info_ptr->bit_depth);
  190540. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  190541. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  190542. if(png_ptr)
  190543. return;
  190544. #endif
  190545. }
  190546. /* Transform the row. The order of transformations is significant,
  190547. * and is very touchy. If you add a transformation, take care to
  190548. * decide how it fits in with the other transformations here.
  190549. */
  190550. void /* PRIVATE */
  190551. png_do_read_transformations(png_structp png_ptr)
  190552. {
  190553. png_debug(1, "in png_do_read_transformations\n");
  190554. if (png_ptr->row_buf == NULL)
  190555. {
  190556. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  190557. char msg[50];
  190558. png_snprintf2(msg, 50,
  190559. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  190560. png_ptr->pass);
  190561. png_error(png_ptr, msg);
  190562. #else
  190563. png_error(png_ptr, "NULL row buffer");
  190564. #endif
  190565. }
  190566. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190567. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  190568. /* Application has failed to call either png_read_start_image()
  190569. * or png_read_update_info() after setting transforms that expand
  190570. * pixels. This check added to libpng-1.2.19 */
  190571. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  190572. png_error(png_ptr, "Uninitialized row");
  190573. #else
  190574. png_warning(png_ptr, "Uninitialized row");
  190575. #endif
  190576. #endif
  190577. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190578. if (png_ptr->transformations & PNG_EXPAND)
  190579. {
  190580. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  190581. {
  190582. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190583. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  190584. }
  190585. else
  190586. {
  190587. if (png_ptr->num_trans &&
  190588. (png_ptr->transformations & PNG_EXPAND_tRNS))
  190589. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190590. &(png_ptr->trans_values));
  190591. else
  190592. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190593. NULL);
  190594. }
  190595. }
  190596. #endif
  190597. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190598. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190599. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190600. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  190601. #endif
  190602. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190603. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190604. {
  190605. int rgb_error =
  190606. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  190607. if(rgb_error)
  190608. {
  190609. png_ptr->rgb_to_gray_status=1;
  190610. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190611. PNG_RGB_TO_GRAY_WARN)
  190612. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190613. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190614. PNG_RGB_TO_GRAY_ERR)
  190615. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190616. }
  190617. }
  190618. #endif
  190619. /*
  190620. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  190621. In most cases, the "simple transparency" should be done prior to doing
  190622. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  190623. pixel is transparent. You would also need to make sure that the
  190624. transparency information is upgraded to RGB.
  190625. To summarize, the current flow is:
  190626. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  190627. with background "in place" if transparent,
  190628. convert to RGB if necessary
  190629. - Gray + alpha -> composite with gray background and remove alpha bytes,
  190630. convert to RGB if necessary
  190631. To support RGB backgrounds for gray images we need:
  190632. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  190633. 3 or 6 bytes and composite with background
  190634. "in place" if transparent (3x compare/pixel
  190635. compared to doing composite with gray bkgrnd)
  190636. - Gray + alpha -> convert to RGB + alpha, composite with background and
  190637. remove alpha bytes (3x float operations/pixel
  190638. compared with composite on gray background)
  190639. Greg's change will do this. The reason it wasn't done before is for
  190640. performance, as this increases the per-pixel operations. If we would check
  190641. in advance if the background was gray or RGB, and position the gray-to-RGB
  190642. transform appropriately, then it would save a lot of work/time.
  190643. */
  190644. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190645. /* if gray -> RGB, do so now only if background is non-gray; else do later
  190646. * for performance reasons */
  190647. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190648. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190649. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190650. #endif
  190651. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190652. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190653. ((png_ptr->num_trans != 0 ) ||
  190654. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  190655. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190656. &(png_ptr->trans_values), &(png_ptr->background)
  190657. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190658. , &(png_ptr->background_1),
  190659. png_ptr->gamma_table, png_ptr->gamma_from_1,
  190660. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  190661. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  190662. png_ptr->gamma_shift
  190663. #endif
  190664. );
  190665. #endif
  190666. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190667. if ((png_ptr->transformations & PNG_GAMMA) &&
  190668. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190669. !((png_ptr->transformations & PNG_BACKGROUND) &&
  190670. ((png_ptr->num_trans != 0) ||
  190671. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  190672. #endif
  190673. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  190674. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190675. png_ptr->gamma_table, png_ptr->gamma_16_table,
  190676. png_ptr->gamma_shift);
  190677. #endif
  190678. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190679. if (png_ptr->transformations & PNG_16_TO_8)
  190680. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190681. #endif
  190682. #if defined(PNG_READ_DITHER_SUPPORTED)
  190683. if (png_ptr->transformations & PNG_DITHER)
  190684. {
  190685. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  190686. png_ptr->palette_lookup, png_ptr->dither_index);
  190687. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  190688. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  190689. }
  190690. #endif
  190691. #if defined(PNG_READ_INVERT_SUPPORTED)
  190692. if (png_ptr->transformations & PNG_INVERT_MONO)
  190693. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190694. #endif
  190695. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190696. if (png_ptr->transformations & PNG_SHIFT)
  190697. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190698. &(png_ptr->shift));
  190699. #endif
  190700. #if defined(PNG_READ_PACK_SUPPORTED)
  190701. if (png_ptr->transformations & PNG_PACK)
  190702. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190703. #endif
  190704. #if defined(PNG_READ_BGR_SUPPORTED)
  190705. if (png_ptr->transformations & PNG_BGR)
  190706. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190707. #endif
  190708. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190709. if (png_ptr->transformations & PNG_PACKSWAP)
  190710. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190711. #endif
  190712. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190713. /* if gray -> RGB, do so now only if we did not do so above */
  190714. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190715. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190716. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190717. #endif
  190718. #if defined(PNG_READ_FILLER_SUPPORTED)
  190719. if (png_ptr->transformations & PNG_FILLER)
  190720. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190721. (png_uint_32)png_ptr->filler, png_ptr->flags);
  190722. #endif
  190723. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190724. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190725. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190726. #endif
  190727. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  190728. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  190729. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190730. #endif
  190731. #if defined(PNG_READ_SWAP_SUPPORTED)
  190732. if (png_ptr->transformations & PNG_SWAP_BYTES)
  190733. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190734. #endif
  190735. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190736. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  190737. {
  190738. if(png_ptr->read_user_transform_fn != NULL)
  190739. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  190740. (png_ptr, /* png_ptr */
  190741. &(png_ptr->row_info), /* row_info: */
  190742. /* png_uint_32 width; width of row */
  190743. /* png_uint_32 rowbytes; number of bytes in row */
  190744. /* png_byte color_type; color type of pixels */
  190745. /* png_byte bit_depth; bit depth of samples */
  190746. /* png_byte channels; number of channels (1-4) */
  190747. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  190748. png_ptr->row_buf + 1); /* start of pixel data for row */
  190749. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  190750. if(png_ptr->user_transform_depth)
  190751. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  190752. if(png_ptr->user_transform_channels)
  190753. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  190754. #endif
  190755. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  190756. png_ptr->row_info.channels);
  190757. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  190758. png_ptr->row_info.width);
  190759. }
  190760. #endif
  190761. }
  190762. #if defined(PNG_READ_PACK_SUPPORTED)
  190763. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  190764. * without changing the actual values. Thus, if you had a row with
  190765. * a bit depth of 1, you would end up with bytes that only contained
  190766. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  190767. * png_do_shift() after this.
  190768. */
  190769. void /* PRIVATE */
  190770. png_do_unpack(png_row_infop row_info, png_bytep row)
  190771. {
  190772. png_debug(1, "in png_do_unpack\n");
  190773. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190774. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  190775. #else
  190776. if (row_info->bit_depth < 8)
  190777. #endif
  190778. {
  190779. png_uint_32 i;
  190780. png_uint_32 row_width=row_info->width;
  190781. switch (row_info->bit_depth)
  190782. {
  190783. case 1:
  190784. {
  190785. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  190786. png_bytep dp = row + (png_size_t)row_width - 1;
  190787. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  190788. for (i = 0; i < row_width; i++)
  190789. {
  190790. *dp = (png_byte)((*sp >> shift) & 0x01);
  190791. if (shift == 7)
  190792. {
  190793. shift = 0;
  190794. sp--;
  190795. }
  190796. else
  190797. shift++;
  190798. dp--;
  190799. }
  190800. break;
  190801. }
  190802. case 2:
  190803. {
  190804. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  190805. png_bytep dp = row + (png_size_t)row_width - 1;
  190806. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  190807. for (i = 0; i < row_width; i++)
  190808. {
  190809. *dp = (png_byte)((*sp >> shift) & 0x03);
  190810. if (shift == 6)
  190811. {
  190812. shift = 0;
  190813. sp--;
  190814. }
  190815. else
  190816. shift += 2;
  190817. dp--;
  190818. }
  190819. break;
  190820. }
  190821. case 4:
  190822. {
  190823. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  190824. png_bytep dp = row + (png_size_t)row_width - 1;
  190825. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  190826. for (i = 0; i < row_width; i++)
  190827. {
  190828. *dp = (png_byte)((*sp >> shift) & 0x0f);
  190829. if (shift == 4)
  190830. {
  190831. shift = 0;
  190832. sp--;
  190833. }
  190834. else
  190835. shift = 4;
  190836. dp--;
  190837. }
  190838. break;
  190839. }
  190840. }
  190841. row_info->bit_depth = 8;
  190842. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  190843. row_info->rowbytes = row_width * row_info->channels;
  190844. }
  190845. }
  190846. #endif
  190847. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190848. /* Reverse the effects of png_do_shift. This routine merely shifts the
  190849. * pixels back to their significant bits values. Thus, if you have
  190850. * a row of bit depth 8, but only 5 are significant, this will shift
  190851. * the values back to 0 through 31.
  190852. */
  190853. void /* PRIVATE */
  190854. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  190855. {
  190856. png_debug(1, "in png_do_unshift\n");
  190857. if (
  190858. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190859. row != NULL && row_info != NULL && sig_bits != NULL &&
  190860. #endif
  190861. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  190862. {
  190863. int shift[4];
  190864. int channels = 0;
  190865. int c;
  190866. png_uint_16 value = 0;
  190867. png_uint_32 row_width = row_info->width;
  190868. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  190869. {
  190870. shift[channels++] = row_info->bit_depth - sig_bits->red;
  190871. shift[channels++] = row_info->bit_depth - sig_bits->green;
  190872. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  190873. }
  190874. else
  190875. {
  190876. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  190877. }
  190878. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  190879. {
  190880. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  190881. }
  190882. for (c = 0; c < channels; c++)
  190883. {
  190884. if (shift[c] <= 0)
  190885. shift[c] = 0;
  190886. else
  190887. value = 1;
  190888. }
  190889. if (!value)
  190890. return;
  190891. switch (row_info->bit_depth)
  190892. {
  190893. case 2:
  190894. {
  190895. png_bytep bp;
  190896. png_uint_32 i;
  190897. png_uint_32 istop = row_info->rowbytes;
  190898. for (bp = row, i = 0; i < istop; i++)
  190899. {
  190900. *bp >>= 1;
  190901. *bp++ &= 0x55;
  190902. }
  190903. break;
  190904. }
  190905. case 4:
  190906. {
  190907. png_bytep bp = row;
  190908. png_uint_32 i;
  190909. png_uint_32 istop = row_info->rowbytes;
  190910. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  190911. (png_byte)((int)0xf >> shift[0]));
  190912. for (i = 0; i < istop; i++)
  190913. {
  190914. *bp >>= shift[0];
  190915. *bp++ &= mask;
  190916. }
  190917. break;
  190918. }
  190919. case 8:
  190920. {
  190921. png_bytep bp = row;
  190922. png_uint_32 i;
  190923. png_uint_32 istop = row_width * channels;
  190924. for (i = 0; i < istop; i++)
  190925. {
  190926. *bp++ >>= shift[i%channels];
  190927. }
  190928. break;
  190929. }
  190930. case 16:
  190931. {
  190932. png_bytep bp = row;
  190933. png_uint_32 i;
  190934. png_uint_32 istop = channels * row_width;
  190935. for (i = 0; i < istop; i++)
  190936. {
  190937. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  190938. value >>= shift[i%channels];
  190939. *bp++ = (png_byte)(value >> 8);
  190940. *bp++ = (png_byte)(value & 0xff);
  190941. }
  190942. break;
  190943. }
  190944. }
  190945. }
  190946. }
  190947. #endif
  190948. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190949. /* chop rows of bit depth 16 down to 8 */
  190950. void /* PRIVATE */
  190951. png_do_chop(png_row_infop row_info, png_bytep row)
  190952. {
  190953. png_debug(1, "in png_do_chop\n");
  190954. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190955. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  190956. #else
  190957. if (row_info->bit_depth == 16)
  190958. #endif
  190959. {
  190960. png_bytep sp = row;
  190961. png_bytep dp = row;
  190962. png_uint_32 i;
  190963. png_uint_32 istop = row_info->width * row_info->channels;
  190964. for (i = 0; i<istop; i++, sp += 2, dp++)
  190965. {
  190966. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  190967. /* This does a more accurate scaling of the 16-bit color
  190968. * value, rather than a simple low-byte truncation.
  190969. *
  190970. * What the ideal calculation should be:
  190971. * *dp = (((((png_uint_32)(*sp) << 8) |
  190972. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  190973. *
  190974. * GRR: no, I think this is what it really should be:
  190975. * *dp = (((((png_uint_32)(*sp) << 8) |
  190976. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  190977. *
  190978. * GRR: here's the exact calculation with shifts:
  190979. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  190980. * *dp = (temp - (temp >> 8)) >> 8;
  190981. *
  190982. * Approximate calculation with shift/add instead of multiply/divide:
  190983. * *dp = ((((png_uint_32)(*sp) << 8) |
  190984. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  190985. *
  190986. * What we actually do to avoid extra shifting and conversion:
  190987. */
  190988. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  190989. #else
  190990. /* Simply discard the low order byte */
  190991. *dp = *sp;
  190992. #endif
  190993. }
  190994. row_info->bit_depth = 8;
  190995. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  190996. row_info->rowbytes = row_info->width * row_info->channels;
  190997. }
  190998. }
  190999. #endif
  191000. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191001. void /* PRIVATE */
  191002. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191003. {
  191004. png_debug(1, "in png_do_read_swap_alpha\n");
  191005. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191006. if (row != NULL && row_info != NULL)
  191007. #endif
  191008. {
  191009. png_uint_32 row_width = row_info->width;
  191010. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191011. {
  191012. /* This converts from RGBA to ARGB */
  191013. if (row_info->bit_depth == 8)
  191014. {
  191015. png_bytep sp = row + row_info->rowbytes;
  191016. png_bytep dp = sp;
  191017. png_byte save;
  191018. png_uint_32 i;
  191019. for (i = 0; i < row_width; i++)
  191020. {
  191021. save = *(--sp);
  191022. *(--dp) = *(--sp);
  191023. *(--dp) = *(--sp);
  191024. *(--dp) = *(--sp);
  191025. *(--dp) = save;
  191026. }
  191027. }
  191028. /* This converts from RRGGBBAA to AARRGGBB */
  191029. else
  191030. {
  191031. png_bytep sp = row + row_info->rowbytes;
  191032. png_bytep dp = sp;
  191033. png_byte save[2];
  191034. png_uint_32 i;
  191035. for (i = 0; i < row_width; i++)
  191036. {
  191037. save[0] = *(--sp);
  191038. save[1] = *(--sp);
  191039. *(--dp) = *(--sp);
  191040. *(--dp) = *(--sp);
  191041. *(--dp) = *(--sp);
  191042. *(--dp) = *(--sp);
  191043. *(--dp) = *(--sp);
  191044. *(--dp) = *(--sp);
  191045. *(--dp) = save[0];
  191046. *(--dp) = save[1];
  191047. }
  191048. }
  191049. }
  191050. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191051. {
  191052. /* This converts from GA to AG */
  191053. if (row_info->bit_depth == 8)
  191054. {
  191055. png_bytep sp = row + row_info->rowbytes;
  191056. png_bytep dp = sp;
  191057. png_byte save;
  191058. png_uint_32 i;
  191059. for (i = 0; i < row_width; i++)
  191060. {
  191061. save = *(--sp);
  191062. *(--dp) = *(--sp);
  191063. *(--dp) = save;
  191064. }
  191065. }
  191066. /* This converts from GGAA to AAGG */
  191067. else
  191068. {
  191069. png_bytep sp = row + row_info->rowbytes;
  191070. png_bytep dp = sp;
  191071. png_byte save[2];
  191072. png_uint_32 i;
  191073. for (i = 0; i < row_width; i++)
  191074. {
  191075. save[0] = *(--sp);
  191076. save[1] = *(--sp);
  191077. *(--dp) = *(--sp);
  191078. *(--dp) = *(--sp);
  191079. *(--dp) = save[0];
  191080. *(--dp) = save[1];
  191081. }
  191082. }
  191083. }
  191084. }
  191085. }
  191086. #endif
  191087. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191088. void /* PRIVATE */
  191089. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191090. {
  191091. png_debug(1, "in png_do_read_invert_alpha\n");
  191092. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191093. if (row != NULL && row_info != NULL)
  191094. #endif
  191095. {
  191096. png_uint_32 row_width = row_info->width;
  191097. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191098. {
  191099. /* This inverts the alpha channel in RGBA */
  191100. if (row_info->bit_depth == 8)
  191101. {
  191102. png_bytep sp = row + row_info->rowbytes;
  191103. png_bytep dp = sp;
  191104. png_uint_32 i;
  191105. for (i = 0; i < row_width; i++)
  191106. {
  191107. *(--dp) = (png_byte)(255 - *(--sp));
  191108. /* This does nothing:
  191109. *(--dp) = *(--sp);
  191110. *(--dp) = *(--sp);
  191111. *(--dp) = *(--sp);
  191112. We can replace it with:
  191113. */
  191114. sp-=3;
  191115. dp=sp;
  191116. }
  191117. }
  191118. /* This inverts the alpha channel in RRGGBBAA */
  191119. else
  191120. {
  191121. png_bytep sp = row + row_info->rowbytes;
  191122. png_bytep dp = sp;
  191123. png_uint_32 i;
  191124. for (i = 0; i < row_width; i++)
  191125. {
  191126. *(--dp) = (png_byte)(255 - *(--sp));
  191127. *(--dp) = (png_byte)(255 - *(--sp));
  191128. /* This does nothing:
  191129. *(--dp) = *(--sp);
  191130. *(--dp) = *(--sp);
  191131. *(--dp) = *(--sp);
  191132. *(--dp) = *(--sp);
  191133. *(--dp) = *(--sp);
  191134. *(--dp) = *(--sp);
  191135. We can replace it with:
  191136. */
  191137. sp-=6;
  191138. dp=sp;
  191139. }
  191140. }
  191141. }
  191142. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191143. {
  191144. /* This inverts the alpha channel in GA */
  191145. if (row_info->bit_depth == 8)
  191146. {
  191147. png_bytep sp = row + row_info->rowbytes;
  191148. png_bytep dp = sp;
  191149. png_uint_32 i;
  191150. for (i = 0; i < row_width; i++)
  191151. {
  191152. *(--dp) = (png_byte)(255 - *(--sp));
  191153. *(--dp) = *(--sp);
  191154. }
  191155. }
  191156. /* This inverts the alpha channel in GGAA */
  191157. else
  191158. {
  191159. png_bytep sp = row + row_info->rowbytes;
  191160. png_bytep dp = sp;
  191161. png_uint_32 i;
  191162. for (i = 0; i < row_width; i++)
  191163. {
  191164. *(--dp) = (png_byte)(255 - *(--sp));
  191165. *(--dp) = (png_byte)(255 - *(--sp));
  191166. /*
  191167. *(--dp) = *(--sp);
  191168. *(--dp) = *(--sp);
  191169. */
  191170. sp-=2;
  191171. dp=sp;
  191172. }
  191173. }
  191174. }
  191175. }
  191176. }
  191177. #endif
  191178. #if defined(PNG_READ_FILLER_SUPPORTED)
  191179. /* Add filler channel if we have RGB color */
  191180. void /* PRIVATE */
  191181. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191182. png_uint_32 filler, png_uint_32 flags)
  191183. {
  191184. png_uint_32 i;
  191185. png_uint_32 row_width = row_info->width;
  191186. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191187. png_byte lo_filler = (png_byte)(filler & 0xff);
  191188. png_debug(1, "in png_do_read_filler\n");
  191189. if (
  191190. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191191. row != NULL && row_info != NULL &&
  191192. #endif
  191193. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191194. {
  191195. if(row_info->bit_depth == 8)
  191196. {
  191197. /* This changes the data from G to GX */
  191198. if (flags & PNG_FLAG_FILLER_AFTER)
  191199. {
  191200. png_bytep sp = row + (png_size_t)row_width;
  191201. png_bytep dp = sp + (png_size_t)row_width;
  191202. for (i = 1; i < row_width; i++)
  191203. {
  191204. *(--dp) = lo_filler;
  191205. *(--dp) = *(--sp);
  191206. }
  191207. *(--dp) = lo_filler;
  191208. row_info->channels = 2;
  191209. row_info->pixel_depth = 16;
  191210. row_info->rowbytes = row_width * 2;
  191211. }
  191212. /* This changes the data from G to XG */
  191213. else
  191214. {
  191215. png_bytep sp = row + (png_size_t)row_width;
  191216. png_bytep dp = sp + (png_size_t)row_width;
  191217. for (i = 0; i < row_width; i++)
  191218. {
  191219. *(--dp) = *(--sp);
  191220. *(--dp) = lo_filler;
  191221. }
  191222. row_info->channels = 2;
  191223. row_info->pixel_depth = 16;
  191224. row_info->rowbytes = row_width * 2;
  191225. }
  191226. }
  191227. else if(row_info->bit_depth == 16)
  191228. {
  191229. /* This changes the data from GG to GGXX */
  191230. if (flags & PNG_FLAG_FILLER_AFTER)
  191231. {
  191232. png_bytep sp = row + (png_size_t)row_width * 2;
  191233. png_bytep dp = sp + (png_size_t)row_width * 2;
  191234. for (i = 1; i < row_width; i++)
  191235. {
  191236. *(--dp) = hi_filler;
  191237. *(--dp) = lo_filler;
  191238. *(--dp) = *(--sp);
  191239. *(--dp) = *(--sp);
  191240. }
  191241. *(--dp) = hi_filler;
  191242. *(--dp) = lo_filler;
  191243. row_info->channels = 2;
  191244. row_info->pixel_depth = 32;
  191245. row_info->rowbytes = row_width * 4;
  191246. }
  191247. /* This changes the data from GG to XXGG */
  191248. else
  191249. {
  191250. png_bytep sp = row + (png_size_t)row_width * 2;
  191251. png_bytep dp = sp + (png_size_t)row_width * 2;
  191252. for (i = 0; i < row_width; i++)
  191253. {
  191254. *(--dp) = *(--sp);
  191255. *(--dp) = *(--sp);
  191256. *(--dp) = hi_filler;
  191257. *(--dp) = lo_filler;
  191258. }
  191259. row_info->channels = 2;
  191260. row_info->pixel_depth = 32;
  191261. row_info->rowbytes = row_width * 4;
  191262. }
  191263. }
  191264. } /* COLOR_TYPE == GRAY */
  191265. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191266. {
  191267. if(row_info->bit_depth == 8)
  191268. {
  191269. /* This changes the data from RGB to RGBX */
  191270. if (flags & PNG_FLAG_FILLER_AFTER)
  191271. {
  191272. png_bytep sp = row + (png_size_t)row_width * 3;
  191273. png_bytep dp = sp + (png_size_t)row_width;
  191274. for (i = 1; i < row_width; i++)
  191275. {
  191276. *(--dp) = lo_filler;
  191277. *(--dp) = *(--sp);
  191278. *(--dp) = *(--sp);
  191279. *(--dp) = *(--sp);
  191280. }
  191281. *(--dp) = lo_filler;
  191282. row_info->channels = 4;
  191283. row_info->pixel_depth = 32;
  191284. row_info->rowbytes = row_width * 4;
  191285. }
  191286. /* This changes the data from RGB to XRGB */
  191287. else
  191288. {
  191289. png_bytep sp = row + (png_size_t)row_width * 3;
  191290. png_bytep dp = sp + (png_size_t)row_width;
  191291. for (i = 0; i < row_width; i++)
  191292. {
  191293. *(--dp) = *(--sp);
  191294. *(--dp) = *(--sp);
  191295. *(--dp) = *(--sp);
  191296. *(--dp) = lo_filler;
  191297. }
  191298. row_info->channels = 4;
  191299. row_info->pixel_depth = 32;
  191300. row_info->rowbytes = row_width * 4;
  191301. }
  191302. }
  191303. else if(row_info->bit_depth == 16)
  191304. {
  191305. /* This changes the data from RRGGBB to RRGGBBXX */
  191306. if (flags & PNG_FLAG_FILLER_AFTER)
  191307. {
  191308. png_bytep sp = row + (png_size_t)row_width * 6;
  191309. png_bytep dp = sp + (png_size_t)row_width * 2;
  191310. for (i = 1; i < row_width; i++)
  191311. {
  191312. *(--dp) = hi_filler;
  191313. *(--dp) = lo_filler;
  191314. *(--dp) = *(--sp);
  191315. *(--dp) = *(--sp);
  191316. *(--dp) = *(--sp);
  191317. *(--dp) = *(--sp);
  191318. *(--dp) = *(--sp);
  191319. *(--dp) = *(--sp);
  191320. }
  191321. *(--dp) = hi_filler;
  191322. *(--dp) = lo_filler;
  191323. row_info->channels = 4;
  191324. row_info->pixel_depth = 64;
  191325. row_info->rowbytes = row_width * 8;
  191326. }
  191327. /* This changes the data from RRGGBB to XXRRGGBB */
  191328. else
  191329. {
  191330. png_bytep sp = row + (png_size_t)row_width * 6;
  191331. png_bytep dp = sp + (png_size_t)row_width * 2;
  191332. for (i = 0; i < row_width; i++)
  191333. {
  191334. *(--dp) = *(--sp);
  191335. *(--dp) = *(--sp);
  191336. *(--dp) = *(--sp);
  191337. *(--dp) = *(--sp);
  191338. *(--dp) = *(--sp);
  191339. *(--dp) = *(--sp);
  191340. *(--dp) = hi_filler;
  191341. *(--dp) = lo_filler;
  191342. }
  191343. row_info->channels = 4;
  191344. row_info->pixel_depth = 64;
  191345. row_info->rowbytes = row_width * 8;
  191346. }
  191347. }
  191348. } /* COLOR_TYPE == RGB */
  191349. }
  191350. #endif
  191351. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191352. /* expand grayscale files to RGB, with or without alpha */
  191353. void /* PRIVATE */
  191354. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191355. {
  191356. png_uint_32 i;
  191357. png_uint_32 row_width = row_info->width;
  191358. png_debug(1, "in png_do_gray_to_rgb\n");
  191359. if (row_info->bit_depth >= 8 &&
  191360. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191361. row != NULL && row_info != NULL &&
  191362. #endif
  191363. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191364. {
  191365. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191366. {
  191367. if (row_info->bit_depth == 8)
  191368. {
  191369. png_bytep sp = row + (png_size_t)row_width - 1;
  191370. png_bytep dp = sp + (png_size_t)row_width * 2;
  191371. for (i = 0; i < row_width; i++)
  191372. {
  191373. *(dp--) = *sp;
  191374. *(dp--) = *sp;
  191375. *(dp--) = *(sp--);
  191376. }
  191377. }
  191378. else
  191379. {
  191380. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191381. png_bytep dp = sp + (png_size_t)row_width * 4;
  191382. for (i = 0; i < row_width; i++)
  191383. {
  191384. *(dp--) = *sp;
  191385. *(dp--) = *(sp - 1);
  191386. *(dp--) = *sp;
  191387. *(dp--) = *(sp - 1);
  191388. *(dp--) = *(sp--);
  191389. *(dp--) = *(sp--);
  191390. }
  191391. }
  191392. }
  191393. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191394. {
  191395. if (row_info->bit_depth == 8)
  191396. {
  191397. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191398. png_bytep dp = sp + (png_size_t)row_width * 2;
  191399. for (i = 0; i < row_width; i++)
  191400. {
  191401. *(dp--) = *(sp--);
  191402. *(dp--) = *sp;
  191403. *(dp--) = *sp;
  191404. *(dp--) = *(sp--);
  191405. }
  191406. }
  191407. else
  191408. {
  191409. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  191410. png_bytep dp = sp + (png_size_t)row_width * 4;
  191411. for (i = 0; i < row_width; i++)
  191412. {
  191413. *(dp--) = *(sp--);
  191414. *(dp--) = *(sp--);
  191415. *(dp--) = *sp;
  191416. *(dp--) = *(sp - 1);
  191417. *(dp--) = *sp;
  191418. *(dp--) = *(sp - 1);
  191419. *(dp--) = *(sp--);
  191420. *(dp--) = *(sp--);
  191421. }
  191422. }
  191423. }
  191424. row_info->channels += (png_byte)2;
  191425. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  191426. row_info->pixel_depth = (png_byte)(row_info->channels *
  191427. row_info->bit_depth);
  191428. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191429. }
  191430. }
  191431. #endif
  191432. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191433. /* reduce RGB files to grayscale, with or without alpha
  191434. * using the equation given in Poynton's ColorFAQ at
  191435. * <http://www.inforamp.net/~poynton/>
  191436. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  191437. *
  191438. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  191439. *
  191440. * We approximate this with
  191441. *
  191442. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  191443. *
  191444. * which can be expressed with integers as
  191445. *
  191446. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  191447. *
  191448. * The calculation is to be done in a linear colorspace.
  191449. *
  191450. * Other integer coefficents can be used via png_set_rgb_to_gray().
  191451. */
  191452. int /* PRIVATE */
  191453. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  191454. {
  191455. png_uint_32 i;
  191456. png_uint_32 row_width = row_info->width;
  191457. int rgb_error = 0;
  191458. png_debug(1, "in png_do_rgb_to_gray\n");
  191459. if (
  191460. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191461. row != NULL && row_info != NULL &&
  191462. #endif
  191463. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  191464. {
  191465. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  191466. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  191467. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  191468. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191469. {
  191470. if (row_info->bit_depth == 8)
  191471. {
  191472. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191473. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191474. {
  191475. png_bytep sp = row;
  191476. png_bytep dp = row;
  191477. for (i = 0; i < row_width; i++)
  191478. {
  191479. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191480. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191481. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191482. if(red != green || red != blue)
  191483. {
  191484. rgb_error |= 1;
  191485. *(dp++) = png_ptr->gamma_from_1[
  191486. (rc*red+gc*green+bc*blue)>>15];
  191487. }
  191488. else
  191489. *(dp++) = *(sp-1);
  191490. }
  191491. }
  191492. else
  191493. #endif
  191494. {
  191495. png_bytep sp = row;
  191496. png_bytep dp = row;
  191497. for (i = 0; i < row_width; i++)
  191498. {
  191499. png_byte red = *(sp++);
  191500. png_byte green = *(sp++);
  191501. png_byte blue = *(sp++);
  191502. if(red != green || red != blue)
  191503. {
  191504. rgb_error |= 1;
  191505. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  191506. }
  191507. else
  191508. *(dp++) = *(sp-1);
  191509. }
  191510. }
  191511. }
  191512. else /* RGB bit_depth == 16 */
  191513. {
  191514. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191515. if (png_ptr->gamma_16_to_1 != NULL &&
  191516. png_ptr->gamma_16_from_1 != NULL)
  191517. {
  191518. png_bytep sp = row;
  191519. png_bytep dp = row;
  191520. for (i = 0; i < row_width; i++)
  191521. {
  191522. png_uint_16 red, green, blue, w;
  191523. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191524. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191525. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191526. if(red == green && red == blue)
  191527. w = red;
  191528. else
  191529. {
  191530. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191531. png_ptr->gamma_shift][red>>8];
  191532. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191533. png_ptr->gamma_shift][green>>8];
  191534. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191535. png_ptr->gamma_shift][blue>>8];
  191536. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  191537. + bc*blue_1)>>15);
  191538. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191539. png_ptr->gamma_shift][gray16 >> 8];
  191540. rgb_error |= 1;
  191541. }
  191542. *(dp++) = (png_byte)((w>>8) & 0xff);
  191543. *(dp++) = (png_byte)(w & 0xff);
  191544. }
  191545. }
  191546. else
  191547. #endif
  191548. {
  191549. png_bytep sp = row;
  191550. png_bytep dp = row;
  191551. for (i = 0; i < row_width; i++)
  191552. {
  191553. png_uint_16 red, green, blue, gray16;
  191554. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191555. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191556. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191557. if(red != green || red != blue)
  191558. rgb_error |= 1;
  191559. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191560. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191561. *(dp++) = (png_byte)(gray16 & 0xff);
  191562. }
  191563. }
  191564. }
  191565. }
  191566. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191567. {
  191568. if (row_info->bit_depth == 8)
  191569. {
  191570. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191571. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191572. {
  191573. png_bytep sp = row;
  191574. png_bytep dp = row;
  191575. for (i = 0; i < row_width; i++)
  191576. {
  191577. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191578. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191579. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191580. if(red != green || red != blue)
  191581. rgb_error |= 1;
  191582. *(dp++) = png_ptr->gamma_from_1
  191583. [(rc*red + gc*green + bc*blue)>>15];
  191584. *(dp++) = *(sp++); /* alpha */
  191585. }
  191586. }
  191587. else
  191588. #endif
  191589. {
  191590. png_bytep sp = row;
  191591. png_bytep dp = row;
  191592. for (i = 0; i < row_width; i++)
  191593. {
  191594. png_byte red = *(sp++);
  191595. png_byte green = *(sp++);
  191596. png_byte blue = *(sp++);
  191597. if(red != green || red != blue)
  191598. rgb_error |= 1;
  191599. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  191600. *(dp++) = *(sp++); /* alpha */
  191601. }
  191602. }
  191603. }
  191604. else /* RGBA bit_depth == 16 */
  191605. {
  191606. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191607. if (png_ptr->gamma_16_to_1 != NULL &&
  191608. png_ptr->gamma_16_from_1 != NULL)
  191609. {
  191610. png_bytep sp = row;
  191611. png_bytep dp = row;
  191612. for (i = 0; i < row_width; i++)
  191613. {
  191614. png_uint_16 red, green, blue, w;
  191615. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191616. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191617. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191618. if(red == green && red == blue)
  191619. w = red;
  191620. else
  191621. {
  191622. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191623. png_ptr->gamma_shift][red>>8];
  191624. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191625. png_ptr->gamma_shift][green>>8];
  191626. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191627. png_ptr->gamma_shift][blue>>8];
  191628. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  191629. + gc * green_1 + bc * blue_1)>>15);
  191630. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191631. png_ptr->gamma_shift][gray16 >> 8];
  191632. rgb_error |= 1;
  191633. }
  191634. *(dp++) = (png_byte)((w>>8) & 0xff);
  191635. *(dp++) = (png_byte)(w & 0xff);
  191636. *(dp++) = *(sp++); /* alpha */
  191637. *(dp++) = *(sp++);
  191638. }
  191639. }
  191640. else
  191641. #endif
  191642. {
  191643. png_bytep sp = row;
  191644. png_bytep dp = row;
  191645. for (i = 0; i < row_width; i++)
  191646. {
  191647. png_uint_16 red, green, blue, gray16;
  191648. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191649. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191650. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191651. if(red != green || red != blue)
  191652. rgb_error |= 1;
  191653. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191654. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191655. *(dp++) = (png_byte)(gray16 & 0xff);
  191656. *(dp++) = *(sp++); /* alpha */
  191657. *(dp++) = *(sp++);
  191658. }
  191659. }
  191660. }
  191661. }
  191662. row_info->channels -= (png_byte)2;
  191663. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  191664. row_info->pixel_depth = (png_byte)(row_info->channels *
  191665. row_info->bit_depth);
  191666. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191667. }
  191668. return rgb_error;
  191669. }
  191670. #endif
  191671. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  191672. * large of png_color. This lets grayscale images be treated as
  191673. * paletted. Most useful for gamma correction and simplification
  191674. * of code.
  191675. */
  191676. void PNGAPI
  191677. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  191678. {
  191679. int num_palette;
  191680. int color_inc;
  191681. int i;
  191682. int v;
  191683. png_debug(1, "in png_do_build_grayscale_palette\n");
  191684. if (palette == NULL)
  191685. return;
  191686. switch (bit_depth)
  191687. {
  191688. case 1:
  191689. num_palette = 2;
  191690. color_inc = 0xff;
  191691. break;
  191692. case 2:
  191693. num_palette = 4;
  191694. color_inc = 0x55;
  191695. break;
  191696. case 4:
  191697. num_palette = 16;
  191698. color_inc = 0x11;
  191699. break;
  191700. case 8:
  191701. num_palette = 256;
  191702. color_inc = 1;
  191703. break;
  191704. default:
  191705. num_palette = 0;
  191706. color_inc = 0;
  191707. break;
  191708. }
  191709. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  191710. {
  191711. palette[i].red = (png_byte)v;
  191712. palette[i].green = (png_byte)v;
  191713. palette[i].blue = (png_byte)v;
  191714. }
  191715. }
  191716. /* This function is currently unused. Do we really need it? */
  191717. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  191718. void /* PRIVATE */
  191719. png_correct_palette(png_structp png_ptr, png_colorp palette,
  191720. int num_palette)
  191721. {
  191722. png_debug(1, "in png_correct_palette\n");
  191723. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  191724. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  191725. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  191726. {
  191727. png_color back, back_1;
  191728. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  191729. {
  191730. back.red = png_ptr->gamma_table[png_ptr->background.red];
  191731. back.green = png_ptr->gamma_table[png_ptr->background.green];
  191732. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  191733. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  191734. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  191735. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  191736. }
  191737. else
  191738. {
  191739. double g;
  191740. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  191741. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  191742. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  191743. {
  191744. back.red = png_ptr->background.red;
  191745. back.green = png_ptr->background.green;
  191746. back.blue = png_ptr->background.blue;
  191747. }
  191748. else
  191749. {
  191750. back.red =
  191751. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  191752. 255.0 + 0.5);
  191753. back.green =
  191754. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  191755. 255.0 + 0.5);
  191756. back.blue =
  191757. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  191758. 255.0 + 0.5);
  191759. }
  191760. g = 1.0 / png_ptr->background_gamma;
  191761. back_1.red =
  191762. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  191763. 255.0 + 0.5);
  191764. back_1.green =
  191765. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  191766. 255.0 + 0.5);
  191767. back_1.blue =
  191768. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  191769. 255.0 + 0.5);
  191770. }
  191771. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191772. {
  191773. png_uint_32 i;
  191774. for (i = 0; i < (png_uint_32)num_palette; i++)
  191775. {
  191776. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  191777. {
  191778. palette[i] = back;
  191779. }
  191780. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  191781. {
  191782. png_byte v, w;
  191783. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  191784. png_composite(w, v, png_ptr->trans[i], back_1.red);
  191785. palette[i].red = png_ptr->gamma_from_1[w];
  191786. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  191787. png_composite(w, v, png_ptr->trans[i], back_1.green);
  191788. palette[i].green = png_ptr->gamma_from_1[w];
  191789. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  191790. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  191791. palette[i].blue = png_ptr->gamma_from_1[w];
  191792. }
  191793. else
  191794. {
  191795. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191796. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191797. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191798. }
  191799. }
  191800. }
  191801. else
  191802. {
  191803. int i;
  191804. for (i = 0; i < num_palette; i++)
  191805. {
  191806. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  191807. {
  191808. palette[i] = back;
  191809. }
  191810. else
  191811. {
  191812. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191813. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191814. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191815. }
  191816. }
  191817. }
  191818. }
  191819. else
  191820. #endif
  191821. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191822. if (png_ptr->transformations & PNG_GAMMA)
  191823. {
  191824. int i;
  191825. for (i = 0; i < num_palette; i++)
  191826. {
  191827. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191828. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191829. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191830. }
  191831. }
  191832. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191833. else
  191834. #endif
  191835. #endif
  191836. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191837. if (png_ptr->transformations & PNG_BACKGROUND)
  191838. {
  191839. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191840. {
  191841. png_color back;
  191842. back.red = (png_byte)png_ptr->background.red;
  191843. back.green = (png_byte)png_ptr->background.green;
  191844. back.blue = (png_byte)png_ptr->background.blue;
  191845. for (i = 0; i < (int)png_ptr->num_trans; i++)
  191846. {
  191847. if (png_ptr->trans[i] == 0)
  191848. {
  191849. palette[i].red = back.red;
  191850. palette[i].green = back.green;
  191851. palette[i].blue = back.blue;
  191852. }
  191853. else if (png_ptr->trans[i] != 0xff)
  191854. {
  191855. png_composite(palette[i].red, png_ptr->palette[i].red,
  191856. png_ptr->trans[i], back.red);
  191857. png_composite(palette[i].green, png_ptr->palette[i].green,
  191858. png_ptr->trans[i], back.green);
  191859. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  191860. png_ptr->trans[i], back.blue);
  191861. }
  191862. }
  191863. }
  191864. else /* assume grayscale palette (what else could it be?) */
  191865. {
  191866. int i;
  191867. for (i = 0; i < num_palette; i++)
  191868. {
  191869. if (i == (png_byte)png_ptr->trans_values.gray)
  191870. {
  191871. palette[i].red = (png_byte)png_ptr->background.red;
  191872. palette[i].green = (png_byte)png_ptr->background.green;
  191873. palette[i].blue = (png_byte)png_ptr->background.blue;
  191874. }
  191875. }
  191876. }
  191877. }
  191878. #endif
  191879. }
  191880. #endif
  191881. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191882. /* Replace any alpha or transparency with the supplied background color.
  191883. * "background" is already in the screen gamma, while "background_1" is
  191884. * at a gamma of 1.0. Paletted files have already been taken care of.
  191885. */
  191886. void /* PRIVATE */
  191887. png_do_background(png_row_infop row_info, png_bytep row,
  191888. png_color_16p trans_values, png_color_16p background
  191889. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191890. , png_color_16p background_1,
  191891. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  191892. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  191893. png_uint_16pp gamma_16_to_1, int gamma_shift
  191894. #endif
  191895. )
  191896. {
  191897. png_bytep sp, dp;
  191898. png_uint_32 i;
  191899. png_uint_32 row_width=row_info->width;
  191900. int shift;
  191901. png_debug(1, "in png_do_background\n");
  191902. if (background != NULL &&
  191903. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191904. row != NULL && row_info != NULL &&
  191905. #endif
  191906. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  191907. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  191908. {
  191909. switch (row_info->color_type)
  191910. {
  191911. case PNG_COLOR_TYPE_GRAY:
  191912. {
  191913. switch (row_info->bit_depth)
  191914. {
  191915. case 1:
  191916. {
  191917. sp = row;
  191918. shift = 7;
  191919. for (i = 0; i < row_width; i++)
  191920. {
  191921. if ((png_uint_16)((*sp >> shift) & 0x01)
  191922. == trans_values->gray)
  191923. {
  191924. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  191925. *sp |= (png_byte)(background->gray << shift);
  191926. }
  191927. if (!shift)
  191928. {
  191929. shift = 7;
  191930. sp++;
  191931. }
  191932. else
  191933. shift--;
  191934. }
  191935. break;
  191936. }
  191937. case 2:
  191938. {
  191939. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191940. if (gamma_table != NULL)
  191941. {
  191942. sp = row;
  191943. shift = 6;
  191944. for (i = 0; i < row_width; i++)
  191945. {
  191946. if ((png_uint_16)((*sp >> shift) & 0x03)
  191947. == trans_values->gray)
  191948. {
  191949. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191950. *sp |= (png_byte)(background->gray << shift);
  191951. }
  191952. else
  191953. {
  191954. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  191955. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  191956. (p << 4) | (p << 6)] >> 6) & 0x03);
  191957. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191958. *sp |= (png_byte)(g << shift);
  191959. }
  191960. if (!shift)
  191961. {
  191962. shift = 6;
  191963. sp++;
  191964. }
  191965. else
  191966. shift -= 2;
  191967. }
  191968. }
  191969. else
  191970. #endif
  191971. {
  191972. sp = row;
  191973. shift = 6;
  191974. for (i = 0; i < row_width; i++)
  191975. {
  191976. if ((png_uint_16)((*sp >> shift) & 0x03)
  191977. == trans_values->gray)
  191978. {
  191979. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191980. *sp |= (png_byte)(background->gray << shift);
  191981. }
  191982. if (!shift)
  191983. {
  191984. shift = 6;
  191985. sp++;
  191986. }
  191987. else
  191988. shift -= 2;
  191989. }
  191990. }
  191991. break;
  191992. }
  191993. case 4:
  191994. {
  191995. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191996. if (gamma_table != NULL)
  191997. {
  191998. sp = row;
  191999. shift = 4;
  192000. for (i = 0; i < row_width; i++)
  192001. {
  192002. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192003. == trans_values->gray)
  192004. {
  192005. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192006. *sp |= (png_byte)(background->gray << shift);
  192007. }
  192008. else
  192009. {
  192010. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192011. png_byte g = (png_byte)((gamma_table[p |
  192012. (p << 4)] >> 4) & 0x0f);
  192013. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192014. *sp |= (png_byte)(g << shift);
  192015. }
  192016. if (!shift)
  192017. {
  192018. shift = 4;
  192019. sp++;
  192020. }
  192021. else
  192022. shift -= 4;
  192023. }
  192024. }
  192025. else
  192026. #endif
  192027. {
  192028. sp = row;
  192029. shift = 4;
  192030. for (i = 0; i < row_width; i++)
  192031. {
  192032. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192033. == trans_values->gray)
  192034. {
  192035. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192036. *sp |= (png_byte)(background->gray << shift);
  192037. }
  192038. if (!shift)
  192039. {
  192040. shift = 4;
  192041. sp++;
  192042. }
  192043. else
  192044. shift -= 4;
  192045. }
  192046. }
  192047. break;
  192048. }
  192049. case 8:
  192050. {
  192051. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192052. if (gamma_table != NULL)
  192053. {
  192054. sp = row;
  192055. for (i = 0; i < row_width; i++, sp++)
  192056. {
  192057. if (*sp == trans_values->gray)
  192058. {
  192059. *sp = (png_byte)background->gray;
  192060. }
  192061. else
  192062. {
  192063. *sp = gamma_table[*sp];
  192064. }
  192065. }
  192066. }
  192067. else
  192068. #endif
  192069. {
  192070. sp = row;
  192071. for (i = 0; i < row_width; i++, sp++)
  192072. {
  192073. if (*sp == trans_values->gray)
  192074. {
  192075. *sp = (png_byte)background->gray;
  192076. }
  192077. }
  192078. }
  192079. break;
  192080. }
  192081. case 16:
  192082. {
  192083. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192084. if (gamma_16 != NULL)
  192085. {
  192086. sp = row;
  192087. for (i = 0; i < row_width; i++, sp += 2)
  192088. {
  192089. png_uint_16 v;
  192090. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192091. if (v == trans_values->gray)
  192092. {
  192093. /* background is already in screen gamma */
  192094. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192095. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192096. }
  192097. else
  192098. {
  192099. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192100. *sp = (png_byte)((v >> 8) & 0xff);
  192101. *(sp + 1) = (png_byte)(v & 0xff);
  192102. }
  192103. }
  192104. }
  192105. else
  192106. #endif
  192107. {
  192108. sp = row;
  192109. for (i = 0; i < row_width; i++, sp += 2)
  192110. {
  192111. png_uint_16 v;
  192112. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192113. if (v == trans_values->gray)
  192114. {
  192115. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192116. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192117. }
  192118. }
  192119. }
  192120. break;
  192121. }
  192122. }
  192123. break;
  192124. }
  192125. case PNG_COLOR_TYPE_RGB:
  192126. {
  192127. if (row_info->bit_depth == 8)
  192128. {
  192129. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192130. if (gamma_table != NULL)
  192131. {
  192132. sp = row;
  192133. for (i = 0; i < row_width; i++, sp += 3)
  192134. {
  192135. if (*sp == trans_values->red &&
  192136. *(sp + 1) == trans_values->green &&
  192137. *(sp + 2) == trans_values->blue)
  192138. {
  192139. *sp = (png_byte)background->red;
  192140. *(sp + 1) = (png_byte)background->green;
  192141. *(sp + 2) = (png_byte)background->blue;
  192142. }
  192143. else
  192144. {
  192145. *sp = gamma_table[*sp];
  192146. *(sp + 1) = gamma_table[*(sp + 1)];
  192147. *(sp + 2) = gamma_table[*(sp + 2)];
  192148. }
  192149. }
  192150. }
  192151. else
  192152. #endif
  192153. {
  192154. sp = row;
  192155. for (i = 0; i < row_width; i++, sp += 3)
  192156. {
  192157. if (*sp == trans_values->red &&
  192158. *(sp + 1) == trans_values->green &&
  192159. *(sp + 2) == trans_values->blue)
  192160. {
  192161. *sp = (png_byte)background->red;
  192162. *(sp + 1) = (png_byte)background->green;
  192163. *(sp + 2) = (png_byte)background->blue;
  192164. }
  192165. }
  192166. }
  192167. }
  192168. else /* if (row_info->bit_depth == 16) */
  192169. {
  192170. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192171. if (gamma_16 != NULL)
  192172. {
  192173. sp = row;
  192174. for (i = 0; i < row_width; i++, sp += 6)
  192175. {
  192176. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192177. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192178. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192179. if (r == trans_values->red && g == trans_values->green &&
  192180. b == trans_values->blue)
  192181. {
  192182. /* background is already in screen gamma */
  192183. *sp = (png_byte)((background->red >> 8) & 0xff);
  192184. *(sp + 1) = (png_byte)(background->red & 0xff);
  192185. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192186. *(sp + 3) = (png_byte)(background->green & 0xff);
  192187. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192188. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192189. }
  192190. else
  192191. {
  192192. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192193. *sp = (png_byte)((v >> 8) & 0xff);
  192194. *(sp + 1) = (png_byte)(v & 0xff);
  192195. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192196. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192197. *(sp + 3) = (png_byte)(v & 0xff);
  192198. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192199. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192200. *(sp + 5) = (png_byte)(v & 0xff);
  192201. }
  192202. }
  192203. }
  192204. else
  192205. #endif
  192206. {
  192207. sp = row;
  192208. for (i = 0; i < row_width; i++, sp += 6)
  192209. {
  192210. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192211. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192212. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192213. if (r == trans_values->red && g == trans_values->green &&
  192214. b == trans_values->blue)
  192215. {
  192216. *sp = (png_byte)((background->red >> 8) & 0xff);
  192217. *(sp + 1) = (png_byte)(background->red & 0xff);
  192218. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192219. *(sp + 3) = (png_byte)(background->green & 0xff);
  192220. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192221. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192222. }
  192223. }
  192224. }
  192225. }
  192226. break;
  192227. }
  192228. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192229. {
  192230. if (row_info->bit_depth == 8)
  192231. {
  192232. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192233. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192234. gamma_table != NULL)
  192235. {
  192236. sp = row;
  192237. dp = row;
  192238. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192239. {
  192240. png_uint_16 a = *(sp + 1);
  192241. if (a == 0xff)
  192242. {
  192243. *dp = gamma_table[*sp];
  192244. }
  192245. else if (a == 0)
  192246. {
  192247. /* background is already in screen gamma */
  192248. *dp = (png_byte)background->gray;
  192249. }
  192250. else
  192251. {
  192252. png_byte v, w;
  192253. v = gamma_to_1[*sp];
  192254. png_composite(w, v, a, background_1->gray);
  192255. *dp = gamma_from_1[w];
  192256. }
  192257. }
  192258. }
  192259. else
  192260. #endif
  192261. {
  192262. sp = row;
  192263. dp = row;
  192264. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192265. {
  192266. png_byte a = *(sp + 1);
  192267. if (a == 0xff)
  192268. {
  192269. *dp = *sp;
  192270. }
  192271. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192272. else if (a == 0)
  192273. {
  192274. *dp = (png_byte)background->gray;
  192275. }
  192276. else
  192277. {
  192278. png_composite(*dp, *sp, a, background_1->gray);
  192279. }
  192280. #else
  192281. *dp = (png_byte)background->gray;
  192282. #endif
  192283. }
  192284. }
  192285. }
  192286. else /* if (png_ptr->bit_depth == 16) */
  192287. {
  192288. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192289. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192290. gamma_16_to_1 != NULL)
  192291. {
  192292. sp = row;
  192293. dp = row;
  192294. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192295. {
  192296. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192297. if (a == (png_uint_16)0xffff)
  192298. {
  192299. png_uint_16 v;
  192300. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192301. *dp = (png_byte)((v >> 8) & 0xff);
  192302. *(dp + 1) = (png_byte)(v & 0xff);
  192303. }
  192304. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192305. else if (a == 0)
  192306. #else
  192307. else
  192308. #endif
  192309. {
  192310. /* background is already in screen gamma */
  192311. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192312. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192313. }
  192314. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192315. else
  192316. {
  192317. png_uint_16 g, v, w;
  192318. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192319. png_composite_16(v, g, a, background_1->gray);
  192320. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192321. *dp = (png_byte)((w >> 8) & 0xff);
  192322. *(dp + 1) = (png_byte)(w & 0xff);
  192323. }
  192324. #endif
  192325. }
  192326. }
  192327. else
  192328. #endif
  192329. {
  192330. sp = row;
  192331. dp = row;
  192332. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192333. {
  192334. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192335. if (a == (png_uint_16)0xffff)
  192336. {
  192337. png_memcpy(dp, sp, 2);
  192338. }
  192339. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192340. else if (a == 0)
  192341. #else
  192342. else
  192343. #endif
  192344. {
  192345. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192346. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192347. }
  192348. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192349. else
  192350. {
  192351. png_uint_16 g, v;
  192352. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192353. png_composite_16(v, g, a, background_1->gray);
  192354. *dp = (png_byte)((v >> 8) & 0xff);
  192355. *(dp + 1) = (png_byte)(v & 0xff);
  192356. }
  192357. #endif
  192358. }
  192359. }
  192360. }
  192361. break;
  192362. }
  192363. case PNG_COLOR_TYPE_RGB_ALPHA:
  192364. {
  192365. if (row_info->bit_depth == 8)
  192366. {
  192367. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192368. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192369. gamma_table != NULL)
  192370. {
  192371. sp = row;
  192372. dp = row;
  192373. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192374. {
  192375. png_byte a = *(sp + 3);
  192376. if (a == 0xff)
  192377. {
  192378. *dp = gamma_table[*sp];
  192379. *(dp + 1) = gamma_table[*(sp + 1)];
  192380. *(dp + 2) = gamma_table[*(sp + 2)];
  192381. }
  192382. else if (a == 0)
  192383. {
  192384. /* background is already in screen gamma */
  192385. *dp = (png_byte)background->red;
  192386. *(dp + 1) = (png_byte)background->green;
  192387. *(dp + 2) = (png_byte)background->blue;
  192388. }
  192389. else
  192390. {
  192391. png_byte v, w;
  192392. v = gamma_to_1[*sp];
  192393. png_composite(w, v, a, background_1->red);
  192394. *dp = gamma_from_1[w];
  192395. v = gamma_to_1[*(sp + 1)];
  192396. png_composite(w, v, a, background_1->green);
  192397. *(dp + 1) = gamma_from_1[w];
  192398. v = gamma_to_1[*(sp + 2)];
  192399. png_composite(w, v, a, background_1->blue);
  192400. *(dp + 2) = gamma_from_1[w];
  192401. }
  192402. }
  192403. }
  192404. else
  192405. #endif
  192406. {
  192407. sp = row;
  192408. dp = row;
  192409. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192410. {
  192411. png_byte a = *(sp + 3);
  192412. if (a == 0xff)
  192413. {
  192414. *dp = *sp;
  192415. *(dp + 1) = *(sp + 1);
  192416. *(dp + 2) = *(sp + 2);
  192417. }
  192418. else if (a == 0)
  192419. {
  192420. *dp = (png_byte)background->red;
  192421. *(dp + 1) = (png_byte)background->green;
  192422. *(dp + 2) = (png_byte)background->blue;
  192423. }
  192424. else
  192425. {
  192426. png_composite(*dp, *sp, a, background->red);
  192427. png_composite(*(dp + 1), *(sp + 1), a,
  192428. background->green);
  192429. png_composite(*(dp + 2), *(sp + 2), a,
  192430. background->blue);
  192431. }
  192432. }
  192433. }
  192434. }
  192435. else /* if (row_info->bit_depth == 16) */
  192436. {
  192437. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192438. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192439. gamma_16_to_1 != NULL)
  192440. {
  192441. sp = row;
  192442. dp = row;
  192443. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192444. {
  192445. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192446. << 8) + (png_uint_16)(*(sp + 7)));
  192447. if (a == (png_uint_16)0xffff)
  192448. {
  192449. png_uint_16 v;
  192450. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192451. *dp = (png_byte)((v >> 8) & 0xff);
  192452. *(dp + 1) = (png_byte)(v & 0xff);
  192453. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192454. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192455. *(dp + 3) = (png_byte)(v & 0xff);
  192456. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192457. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192458. *(dp + 5) = (png_byte)(v & 0xff);
  192459. }
  192460. else if (a == 0)
  192461. {
  192462. /* background is already in screen gamma */
  192463. *dp = (png_byte)((background->red >> 8) & 0xff);
  192464. *(dp + 1) = (png_byte)(background->red & 0xff);
  192465. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192466. *(dp + 3) = (png_byte)(background->green & 0xff);
  192467. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192468. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192469. }
  192470. else
  192471. {
  192472. png_uint_16 v, w, x;
  192473. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192474. png_composite_16(w, v, a, background_1->red);
  192475. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192476. *dp = (png_byte)((x >> 8) & 0xff);
  192477. *(dp + 1) = (png_byte)(x & 0xff);
  192478. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192479. png_composite_16(w, v, a, background_1->green);
  192480. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192481. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  192482. *(dp + 3) = (png_byte)(x & 0xff);
  192483. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192484. png_composite_16(w, v, a, background_1->blue);
  192485. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  192486. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  192487. *(dp + 5) = (png_byte)(x & 0xff);
  192488. }
  192489. }
  192490. }
  192491. else
  192492. #endif
  192493. {
  192494. sp = row;
  192495. dp = row;
  192496. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192497. {
  192498. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192499. << 8) + (png_uint_16)(*(sp + 7)));
  192500. if (a == (png_uint_16)0xffff)
  192501. {
  192502. png_memcpy(dp, sp, 6);
  192503. }
  192504. else if (a == 0)
  192505. {
  192506. *dp = (png_byte)((background->red >> 8) & 0xff);
  192507. *(dp + 1) = (png_byte)(background->red & 0xff);
  192508. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192509. *(dp + 3) = (png_byte)(background->green & 0xff);
  192510. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192511. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192512. }
  192513. else
  192514. {
  192515. png_uint_16 v;
  192516. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192517. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  192518. + *(sp + 3));
  192519. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  192520. + *(sp + 5));
  192521. png_composite_16(v, r, a, background->red);
  192522. *dp = (png_byte)((v >> 8) & 0xff);
  192523. *(dp + 1) = (png_byte)(v & 0xff);
  192524. png_composite_16(v, g, a, background->green);
  192525. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192526. *(dp + 3) = (png_byte)(v & 0xff);
  192527. png_composite_16(v, b, a, background->blue);
  192528. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192529. *(dp + 5) = (png_byte)(v & 0xff);
  192530. }
  192531. }
  192532. }
  192533. }
  192534. break;
  192535. }
  192536. }
  192537. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  192538. {
  192539. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  192540. row_info->channels--;
  192541. row_info->pixel_depth = (png_byte)(row_info->channels *
  192542. row_info->bit_depth);
  192543. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192544. }
  192545. }
  192546. }
  192547. #endif
  192548. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192549. /* Gamma correct the image, avoiding the alpha channel. Make sure
  192550. * you do this after you deal with the transparency issue on grayscale
  192551. * or RGB images. If your bit depth is 8, use gamma_table, if it
  192552. * is 16, use gamma_16_table and gamma_shift. Build these with
  192553. * build_gamma_table().
  192554. */
  192555. void /* PRIVATE */
  192556. png_do_gamma(png_row_infop row_info, png_bytep row,
  192557. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  192558. int gamma_shift)
  192559. {
  192560. png_bytep sp;
  192561. png_uint_32 i;
  192562. png_uint_32 row_width=row_info->width;
  192563. png_debug(1, "in png_do_gamma\n");
  192564. if (
  192565. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192566. row != NULL && row_info != NULL &&
  192567. #endif
  192568. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  192569. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  192570. {
  192571. switch (row_info->color_type)
  192572. {
  192573. case PNG_COLOR_TYPE_RGB:
  192574. {
  192575. if (row_info->bit_depth == 8)
  192576. {
  192577. sp = row;
  192578. for (i = 0; i < row_width; i++)
  192579. {
  192580. *sp = gamma_table[*sp];
  192581. sp++;
  192582. *sp = gamma_table[*sp];
  192583. sp++;
  192584. *sp = gamma_table[*sp];
  192585. sp++;
  192586. }
  192587. }
  192588. else /* if (row_info->bit_depth == 16) */
  192589. {
  192590. sp = row;
  192591. for (i = 0; i < row_width; i++)
  192592. {
  192593. png_uint_16 v;
  192594. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192595. *sp = (png_byte)((v >> 8) & 0xff);
  192596. *(sp + 1) = (png_byte)(v & 0xff);
  192597. sp += 2;
  192598. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192599. *sp = (png_byte)((v >> 8) & 0xff);
  192600. *(sp + 1) = (png_byte)(v & 0xff);
  192601. sp += 2;
  192602. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192603. *sp = (png_byte)((v >> 8) & 0xff);
  192604. *(sp + 1) = (png_byte)(v & 0xff);
  192605. sp += 2;
  192606. }
  192607. }
  192608. break;
  192609. }
  192610. case PNG_COLOR_TYPE_RGB_ALPHA:
  192611. {
  192612. if (row_info->bit_depth == 8)
  192613. {
  192614. sp = row;
  192615. for (i = 0; i < row_width; i++)
  192616. {
  192617. *sp = gamma_table[*sp];
  192618. sp++;
  192619. *sp = gamma_table[*sp];
  192620. sp++;
  192621. *sp = gamma_table[*sp];
  192622. sp++;
  192623. sp++;
  192624. }
  192625. }
  192626. else /* if (row_info->bit_depth == 16) */
  192627. {
  192628. sp = row;
  192629. for (i = 0; i < row_width; i++)
  192630. {
  192631. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192632. *sp = (png_byte)((v >> 8) & 0xff);
  192633. *(sp + 1) = (png_byte)(v & 0xff);
  192634. sp += 2;
  192635. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192636. *sp = (png_byte)((v >> 8) & 0xff);
  192637. *(sp + 1) = (png_byte)(v & 0xff);
  192638. sp += 2;
  192639. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192640. *sp = (png_byte)((v >> 8) & 0xff);
  192641. *(sp + 1) = (png_byte)(v & 0xff);
  192642. sp += 4;
  192643. }
  192644. }
  192645. break;
  192646. }
  192647. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192648. {
  192649. if (row_info->bit_depth == 8)
  192650. {
  192651. sp = row;
  192652. for (i = 0; i < row_width; i++)
  192653. {
  192654. *sp = gamma_table[*sp];
  192655. sp += 2;
  192656. }
  192657. }
  192658. else /* if (row_info->bit_depth == 16) */
  192659. {
  192660. sp = row;
  192661. for (i = 0; i < row_width; i++)
  192662. {
  192663. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192664. *sp = (png_byte)((v >> 8) & 0xff);
  192665. *(sp + 1) = (png_byte)(v & 0xff);
  192666. sp += 4;
  192667. }
  192668. }
  192669. break;
  192670. }
  192671. case PNG_COLOR_TYPE_GRAY:
  192672. {
  192673. if (row_info->bit_depth == 2)
  192674. {
  192675. sp = row;
  192676. for (i = 0; i < row_width; i += 4)
  192677. {
  192678. int a = *sp & 0xc0;
  192679. int b = *sp & 0x30;
  192680. int c = *sp & 0x0c;
  192681. int d = *sp & 0x03;
  192682. *sp = (png_byte)(
  192683. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  192684. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  192685. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  192686. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  192687. sp++;
  192688. }
  192689. }
  192690. if (row_info->bit_depth == 4)
  192691. {
  192692. sp = row;
  192693. for (i = 0; i < row_width; i += 2)
  192694. {
  192695. int msb = *sp & 0xf0;
  192696. int lsb = *sp & 0x0f;
  192697. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  192698. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  192699. sp++;
  192700. }
  192701. }
  192702. else if (row_info->bit_depth == 8)
  192703. {
  192704. sp = row;
  192705. for (i = 0; i < row_width; i++)
  192706. {
  192707. *sp = gamma_table[*sp];
  192708. sp++;
  192709. }
  192710. }
  192711. else if (row_info->bit_depth == 16)
  192712. {
  192713. sp = row;
  192714. for (i = 0; i < row_width; i++)
  192715. {
  192716. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192717. *sp = (png_byte)((v >> 8) & 0xff);
  192718. *(sp + 1) = (png_byte)(v & 0xff);
  192719. sp += 2;
  192720. }
  192721. }
  192722. break;
  192723. }
  192724. }
  192725. }
  192726. }
  192727. #endif
  192728. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192729. /* Expands a palette row to an RGB or RGBA row depending
  192730. * upon whether you supply trans and num_trans.
  192731. */
  192732. void /* PRIVATE */
  192733. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  192734. png_colorp palette, png_bytep trans, int num_trans)
  192735. {
  192736. int shift, value;
  192737. png_bytep sp, dp;
  192738. png_uint_32 i;
  192739. png_uint_32 row_width=row_info->width;
  192740. png_debug(1, "in png_do_expand_palette\n");
  192741. if (
  192742. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192743. row != NULL && row_info != NULL &&
  192744. #endif
  192745. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  192746. {
  192747. if (row_info->bit_depth < 8)
  192748. {
  192749. switch (row_info->bit_depth)
  192750. {
  192751. case 1:
  192752. {
  192753. sp = row + (png_size_t)((row_width - 1) >> 3);
  192754. dp = row + (png_size_t)row_width - 1;
  192755. shift = 7 - (int)((row_width + 7) & 0x07);
  192756. for (i = 0; i < row_width; i++)
  192757. {
  192758. if ((*sp >> shift) & 0x01)
  192759. *dp = 1;
  192760. else
  192761. *dp = 0;
  192762. if (shift == 7)
  192763. {
  192764. shift = 0;
  192765. sp--;
  192766. }
  192767. else
  192768. shift++;
  192769. dp--;
  192770. }
  192771. break;
  192772. }
  192773. case 2:
  192774. {
  192775. sp = row + (png_size_t)((row_width - 1) >> 2);
  192776. dp = row + (png_size_t)row_width - 1;
  192777. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  192778. for (i = 0; i < row_width; i++)
  192779. {
  192780. value = (*sp >> shift) & 0x03;
  192781. *dp = (png_byte)value;
  192782. if (shift == 6)
  192783. {
  192784. shift = 0;
  192785. sp--;
  192786. }
  192787. else
  192788. shift += 2;
  192789. dp--;
  192790. }
  192791. break;
  192792. }
  192793. case 4:
  192794. {
  192795. sp = row + (png_size_t)((row_width - 1) >> 1);
  192796. dp = row + (png_size_t)row_width - 1;
  192797. shift = (int)((row_width & 0x01) << 2);
  192798. for (i = 0; i < row_width; i++)
  192799. {
  192800. value = (*sp >> shift) & 0x0f;
  192801. *dp = (png_byte)value;
  192802. if (shift == 4)
  192803. {
  192804. shift = 0;
  192805. sp--;
  192806. }
  192807. else
  192808. shift += 4;
  192809. dp--;
  192810. }
  192811. break;
  192812. }
  192813. }
  192814. row_info->bit_depth = 8;
  192815. row_info->pixel_depth = 8;
  192816. row_info->rowbytes = row_width;
  192817. }
  192818. switch (row_info->bit_depth)
  192819. {
  192820. case 8:
  192821. {
  192822. if (trans != NULL)
  192823. {
  192824. sp = row + (png_size_t)row_width - 1;
  192825. dp = row + (png_size_t)(row_width << 2) - 1;
  192826. for (i = 0; i < row_width; i++)
  192827. {
  192828. if ((int)(*sp) >= num_trans)
  192829. *dp-- = 0xff;
  192830. else
  192831. *dp-- = trans[*sp];
  192832. *dp-- = palette[*sp].blue;
  192833. *dp-- = palette[*sp].green;
  192834. *dp-- = palette[*sp].red;
  192835. sp--;
  192836. }
  192837. row_info->bit_depth = 8;
  192838. row_info->pixel_depth = 32;
  192839. row_info->rowbytes = row_width * 4;
  192840. row_info->color_type = 6;
  192841. row_info->channels = 4;
  192842. }
  192843. else
  192844. {
  192845. sp = row + (png_size_t)row_width - 1;
  192846. dp = row + (png_size_t)(row_width * 3) - 1;
  192847. for (i = 0; i < row_width; i++)
  192848. {
  192849. *dp-- = palette[*sp].blue;
  192850. *dp-- = palette[*sp].green;
  192851. *dp-- = palette[*sp].red;
  192852. sp--;
  192853. }
  192854. row_info->bit_depth = 8;
  192855. row_info->pixel_depth = 24;
  192856. row_info->rowbytes = row_width * 3;
  192857. row_info->color_type = 2;
  192858. row_info->channels = 3;
  192859. }
  192860. break;
  192861. }
  192862. }
  192863. }
  192864. }
  192865. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  192866. * expanded transparency value is supplied, an alpha channel is built.
  192867. */
  192868. void /* PRIVATE */
  192869. png_do_expand(png_row_infop row_info, png_bytep row,
  192870. png_color_16p trans_value)
  192871. {
  192872. int shift, value;
  192873. png_bytep sp, dp;
  192874. png_uint_32 i;
  192875. png_uint_32 row_width=row_info->width;
  192876. png_debug(1, "in png_do_expand\n");
  192877. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192878. if (row != NULL && row_info != NULL)
  192879. #endif
  192880. {
  192881. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192882. {
  192883. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  192884. if (row_info->bit_depth < 8)
  192885. {
  192886. switch (row_info->bit_depth)
  192887. {
  192888. case 1:
  192889. {
  192890. gray = (png_uint_16)((gray&0x01)*0xff);
  192891. sp = row + (png_size_t)((row_width - 1) >> 3);
  192892. dp = row + (png_size_t)row_width - 1;
  192893. shift = 7 - (int)((row_width + 7) & 0x07);
  192894. for (i = 0; i < row_width; i++)
  192895. {
  192896. if ((*sp >> shift) & 0x01)
  192897. *dp = 0xff;
  192898. else
  192899. *dp = 0;
  192900. if (shift == 7)
  192901. {
  192902. shift = 0;
  192903. sp--;
  192904. }
  192905. else
  192906. shift++;
  192907. dp--;
  192908. }
  192909. break;
  192910. }
  192911. case 2:
  192912. {
  192913. gray = (png_uint_16)((gray&0x03)*0x55);
  192914. sp = row + (png_size_t)((row_width - 1) >> 2);
  192915. dp = row + (png_size_t)row_width - 1;
  192916. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  192917. for (i = 0; i < row_width; i++)
  192918. {
  192919. value = (*sp >> shift) & 0x03;
  192920. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  192921. (value << 6));
  192922. if (shift == 6)
  192923. {
  192924. shift = 0;
  192925. sp--;
  192926. }
  192927. else
  192928. shift += 2;
  192929. dp--;
  192930. }
  192931. break;
  192932. }
  192933. case 4:
  192934. {
  192935. gray = (png_uint_16)((gray&0x0f)*0x11);
  192936. sp = row + (png_size_t)((row_width - 1) >> 1);
  192937. dp = row + (png_size_t)row_width - 1;
  192938. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  192939. for (i = 0; i < row_width; i++)
  192940. {
  192941. value = (*sp >> shift) & 0x0f;
  192942. *dp = (png_byte)(value | (value << 4));
  192943. if (shift == 4)
  192944. {
  192945. shift = 0;
  192946. sp--;
  192947. }
  192948. else
  192949. shift = 4;
  192950. dp--;
  192951. }
  192952. break;
  192953. }
  192954. }
  192955. row_info->bit_depth = 8;
  192956. row_info->pixel_depth = 8;
  192957. row_info->rowbytes = row_width;
  192958. }
  192959. if (trans_value != NULL)
  192960. {
  192961. if (row_info->bit_depth == 8)
  192962. {
  192963. gray = gray & 0xff;
  192964. sp = row + (png_size_t)row_width - 1;
  192965. dp = row + (png_size_t)(row_width << 1) - 1;
  192966. for (i = 0; i < row_width; i++)
  192967. {
  192968. if (*sp == gray)
  192969. *dp-- = 0;
  192970. else
  192971. *dp-- = 0xff;
  192972. *dp-- = *sp--;
  192973. }
  192974. }
  192975. else if (row_info->bit_depth == 16)
  192976. {
  192977. png_byte gray_high = (gray >> 8) & 0xff;
  192978. png_byte gray_low = gray & 0xff;
  192979. sp = row + row_info->rowbytes - 1;
  192980. dp = row + (row_info->rowbytes << 1) - 1;
  192981. for (i = 0; i < row_width; i++)
  192982. {
  192983. if (*(sp-1) == gray_high && *(sp) == gray_low)
  192984. {
  192985. *dp-- = 0;
  192986. *dp-- = 0;
  192987. }
  192988. else
  192989. {
  192990. *dp-- = 0xff;
  192991. *dp-- = 0xff;
  192992. }
  192993. *dp-- = *sp--;
  192994. *dp-- = *sp--;
  192995. }
  192996. }
  192997. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  192998. row_info->channels = 2;
  192999. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193000. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193001. row_width);
  193002. }
  193003. }
  193004. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193005. {
  193006. if (row_info->bit_depth == 8)
  193007. {
  193008. png_byte red = trans_value->red & 0xff;
  193009. png_byte green = trans_value->green & 0xff;
  193010. png_byte blue = trans_value->blue & 0xff;
  193011. sp = row + (png_size_t)row_info->rowbytes - 1;
  193012. dp = row + (png_size_t)(row_width << 2) - 1;
  193013. for (i = 0; i < row_width; i++)
  193014. {
  193015. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193016. *dp-- = 0;
  193017. else
  193018. *dp-- = 0xff;
  193019. *dp-- = *sp--;
  193020. *dp-- = *sp--;
  193021. *dp-- = *sp--;
  193022. }
  193023. }
  193024. else if (row_info->bit_depth == 16)
  193025. {
  193026. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193027. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193028. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193029. png_byte red_low = trans_value->red & 0xff;
  193030. png_byte green_low = trans_value->green & 0xff;
  193031. png_byte blue_low = trans_value->blue & 0xff;
  193032. sp = row + row_info->rowbytes - 1;
  193033. dp = row + (png_size_t)(row_width << 3) - 1;
  193034. for (i = 0; i < row_width; i++)
  193035. {
  193036. if (*(sp - 5) == red_high &&
  193037. *(sp - 4) == red_low &&
  193038. *(sp - 3) == green_high &&
  193039. *(sp - 2) == green_low &&
  193040. *(sp - 1) == blue_high &&
  193041. *(sp ) == blue_low)
  193042. {
  193043. *dp-- = 0;
  193044. *dp-- = 0;
  193045. }
  193046. else
  193047. {
  193048. *dp-- = 0xff;
  193049. *dp-- = 0xff;
  193050. }
  193051. *dp-- = *sp--;
  193052. *dp-- = *sp--;
  193053. *dp-- = *sp--;
  193054. *dp-- = *sp--;
  193055. *dp-- = *sp--;
  193056. *dp-- = *sp--;
  193057. }
  193058. }
  193059. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193060. row_info->channels = 4;
  193061. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193062. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193063. }
  193064. }
  193065. }
  193066. #endif
  193067. #if defined(PNG_READ_DITHER_SUPPORTED)
  193068. void /* PRIVATE */
  193069. png_do_dither(png_row_infop row_info, png_bytep row,
  193070. png_bytep palette_lookup, png_bytep dither_lookup)
  193071. {
  193072. png_bytep sp, dp;
  193073. png_uint_32 i;
  193074. png_uint_32 row_width=row_info->width;
  193075. png_debug(1, "in png_do_dither\n");
  193076. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193077. if (row != NULL && row_info != NULL)
  193078. #endif
  193079. {
  193080. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193081. palette_lookup && row_info->bit_depth == 8)
  193082. {
  193083. int r, g, b, p;
  193084. sp = row;
  193085. dp = row;
  193086. for (i = 0; i < row_width; i++)
  193087. {
  193088. r = *sp++;
  193089. g = *sp++;
  193090. b = *sp++;
  193091. /* this looks real messy, but the compiler will reduce
  193092. it down to a reasonable formula. For example, with
  193093. 5 bits per color, we get:
  193094. p = (((r >> 3) & 0x1f) << 10) |
  193095. (((g >> 3) & 0x1f) << 5) |
  193096. ((b >> 3) & 0x1f);
  193097. */
  193098. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193099. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193100. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193101. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193102. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193103. (PNG_DITHER_BLUE_BITS)) |
  193104. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193105. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193106. *dp++ = palette_lookup[p];
  193107. }
  193108. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193109. row_info->channels = 1;
  193110. row_info->pixel_depth = row_info->bit_depth;
  193111. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193112. }
  193113. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193114. palette_lookup != NULL && row_info->bit_depth == 8)
  193115. {
  193116. int r, g, b, p;
  193117. sp = row;
  193118. dp = row;
  193119. for (i = 0; i < row_width; i++)
  193120. {
  193121. r = *sp++;
  193122. g = *sp++;
  193123. b = *sp++;
  193124. sp++;
  193125. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193126. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193127. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193128. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193129. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193130. (PNG_DITHER_BLUE_BITS)) |
  193131. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193132. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193133. *dp++ = palette_lookup[p];
  193134. }
  193135. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193136. row_info->channels = 1;
  193137. row_info->pixel_depth = row_info->bit_depth;
  193138. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193139. }
  193140. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193141. dither_lookup && row_info->bit_depth == 8)
  193142. {
  193143. sp = row;
  193144. for (i = 0; i < row_width; i++, sp++)
  193145. {
  193146. *sp = dither_lookup[*sp];
  193147. }
  193148. }
  193149. }
  193150. }
  193151. #endif
  193152. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193153. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193154. static PNG_CONST int png_gamma_shift[] =
  193155. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193156. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193157. * tables, we don't make a full table if we are reducing to 8-bit in
  193158. * the future. Note also how the gamma_16 tables are segmented so that
  193159. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193160. */
  193161. void /* PRIVATE */
  193162. png_build_gamma_table(png_structp png_ptr)
  193163. {
  193164. png_debug(1, "in png_build_gamma_table\n");
  193165. if (png_ptr->bit_depth <= 8)
  193166. {
  193167. int i;
  193168. double g;
  193169. if (png_ptr->screen_gamma > .000001)
  193170. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193171. else
  193172. g = 1.0;
  193173. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193174. (png_uint_32)256);
  193175. for (i = 0; i < 256; i++)
  193176. {
  193177. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193178. g) * 255.0 + .5);
  193179. }
  193180. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193181. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193182. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193183. {
  193184. g = 1.0 / (png_ptr->gamma);
  193185. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193186. (png_uint_32)256);
  193187. for (i = 0; i < 256; i++)
  193188. {
  193189. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193190. g) * 255.0 + .5);
  193191. }
  193192. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193193. (png_uint_32)256);
  193194. if(png_ptr->screen_gamma > 0.000001)
  193195. g = 1.0 / png_ptr->screen_gamma;
  193196. else
  193197. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193198. for (i = 0; i < 256; i++)
  193199. {
  193200. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193201. g) * 255.0 + .5);
  193202. }
  193203. }
  193204. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193205. }
  193206. else
  193207. {
  193208. double g;
  193209. int i, j, shift, num;
  193210. int sig_bit;
  193211. png_uint_32 ig;
  193212. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193213. {
  193214. sig_bit = (int)png_ptr->sig_bit.red;
  193215. if ((int)png_ptr->sig_bit.green > sig_bit)
  193216. sig_bit = png_ptr->sig_bit.green;
  193217. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193218. sig_bit = png_ptr->sig_bit.blue;
  193219. }
  193220. else
  193221. {
  193222. sig_bit = (int)png_ptr->sig_bit.gray;
  193223. }
  193224. if (sig_bit > 0)
  193225. shift = 16 - sig_bit;
  193226. else
  193227. shift = 0;
  193228. if (png_ptr->transformations & PNG_16_TO_8)
  193229. {
  193230. if (shift < (16 - PNG_MAX_GAMMA_8))
  193231. shift = (16 - PNG_MAX_GAMMA_8);
  193232. }
  193233. if (shift > 8)
  193234. shift = 8;
  193235. if (shift < 0)
  193236. shift = 0;
  193237. png_ptr->gamma_shift = (png_byte)shift;
  193238. num = (1 << (8 - shift));
  193239. if (png_ptr->screen_gamma > .000001)
  193240. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193241. else
  193242. g = 1.0;
  193243. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193244. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193245. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193246. {
  193247. double fin, fout;
  193248. png_uint_32 last, max;
  193249. for (i = 0; i < num; i++)
  193250. {
  193251. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193252. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193253. }
  193254. g = 1.0 / g;
  193255. last = 0;
  193256. for (i = 0; i < 256; i++)
  193257. {
  193258. fout = ((double)i + 0.5) / 256.0;
  193259. fin = pow(fout, g);
  193260. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193261. while (last <= max)
  193262. {
  193263. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193264. [(int)(last >> (8 - shift))] = (png_uint_16)(
  193265. (png_uint_16)i | ((png_uint_16)i << 8));
  193266. last++;
  193267. }
  193268. }
  193269. while (last < ((png_uint_32)num << 8))
  193270. {
  193271. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193272. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  193273. last++;
  193274. }
  193275. }
  193276. else
  193277. {
  193278. for (i = 0; i < num; i++)
  193279. {
  193280. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193281. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193282. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  193283. for (j = 0; j < 256; j++)
  193284. {
  193285. png_ptr->gamma_16_table[i][j] =
  193286. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193287. 65535.0, g) * 65535.0 + .5);
  193288. }
  193289. }
  193290. }
  193291. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193292. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193293. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  193294. {
  193295. g = 1.0 / (png_ptr->gamma);
  193296. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  193297. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  193298. for (i = 0; i < num; i++)
  193299. {
  193300. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193301. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193302. ig = (((png_uint_32)i *
  193303. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193304. for (j = 0; j < 256; j++)
  193305. {
  193306. png_ptr->gamma_16_to_1[i][j] =
  193307. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193308. 65535.0, g) * 65535.0 + .5);
  193309. }
  193310. }
  193311. if(png_ptr->screen_gamma > 0.000001)
  193312. g = 1.0 / png_ptr->screen_gamma;
  193313. else
  193314. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193315. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193316. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193317. for (i = 0; i < num; i++)
  193318. {
  193319. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193320. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193321. ig = (((png_uint_32)i *
  193322. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193323. for (j = 0; j < 256; j++)
  193324. {
  193325. png_ptr->gamma_16_from_1[i][j] =
  193326. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193327. 65535.0, g) * 65535.0 + .5);
  193328. }
  193329. }
  193330. }
  193331. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193332. }
  193333. }
  193334. #endif
  193335. /* To do: install integer version of png_build_gamma_table here */
  193336. #endif
  193337. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193338. /* undoes intrapixel differencing */
  193339. void /* PRIVATE */
  193340. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193341. {
  193342. png_debug(1, "in png_do_read_intrapixel\n");
  193343. if (
  193344. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193345. row != NULL && row_info != NULL &&
  193346. #endif
  193347. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193348. {
  193349. int bytes_per_pixel;
  193350. png_uint_32 row_width = row_info->width;
  193351. if (row_info->bit_depth == 8)
  193352. {
  193353. png_bytep rp;
  193354. png_uint_32 i;
  193355. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193356. bytes_per_pixel = 3;
  193357. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193358. bytes_per_pixel = 4;
  193359. else
  193360. return;
  193361. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193362. {
  193363. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193364. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193365. }
  193366. }
  193367. else if (row_info->bit_depth == 16)
  193368. {
  193369. png_bytep rp;
  193370. png_uint_32 i;
  193371. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193372. bytes_per_pixel = 6;
  193373. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193374. bytes_per_pixel = 8;
  193375. else
  193376. return;
  193377. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193378. {
  193379. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193380. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193381. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193382. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  193383. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  193384. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193385. *(rp+1) = (png_byte)(red & 0xff);
  193386. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193387. *(rp+5) = (png_byte)(blue & 0xff);
  193388. }
  193389. }
  193390. }
  193391. }
  193392. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193393. #endif /* PNG_READ_SUPPORTED */
  193394. /*** End of inlined file: pngrtran.c ***/
  193395. /*** Start of inlined file: pngrutil.c ***/
  193396. /* pngrutil.c - utilities to read a PNG file
  193397. *
  193398. * Last changed in libpng 1.2.21 [October 4, 2007]
  193399. * For conditions of distribution and use, see copyright notice in png.h
  193400. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193401. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193402. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193403. *
  193404. * This file contains routines that are only called from within
  193405. * libpng itself during the course of reading an image.
  193406. */
  193407. #define PNG_INTERNAL
  193408. #if defined(PNG_READ_SUPPORTED)
  193409. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  193410. # define WIN32_WCE_OLD
  193411. #endif
  193412. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193413. # if defined(WIN32_WCE_OLD)
  193414. /* strtod() function is not supported on WindowsCE */
  193415. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  193416. {
  193417. double result = 0;
  193418. int len;
  193419. wchar_t *str, *end;
  193420. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  193421. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  193422. if ( NULL != str )
  193423. {
  193424. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  193425. result = wcstod(str, &end);
  193426. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  193427. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  193428. png_free(png_ptr, str);
  193429. }
  193430. return result;
  193431. }
  193432. # else
  193433. # define png_strtod(p,a,b) strtod(a,b)
  193434. # endif
  193435. #endif
  193436. png_uint_32 PNGAPI
  193437. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  193438. {
  193439. png_uint_32 i = png_get_uint_32(buf);
  193440. if (i > PNG_UINT_31_MAX)
  193441. png_error(png_ptr, "PNG unsigned integer out of range.");
  193442. return (i);
  193443. }
  193444. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  193445. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  193446. png_uint_32 PNGAPI
  193447. png_get_uint_32(png_bytep buf)
  193448. {
  193449. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  193450. ((png_uint_32)(*(buf + 1)) << 16) +
  193451. ((png_uint_32)(*(buf + 2)) << 8) +
  193452. (png_uint_32)(*(buf + 3));
  193453. return (i);
  193454. }
  193455. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  193456. * data is stored in the PNG file in two's complement format, and it is
  193457. * assumed that the machine format for signed integers is the same. */
  193458. png_int_32 PNGAPI
  193459. png_get_int_32(png_bytep buf)
  193460. {
  193461. png_int_32 i = ((png_int_32)(*buf) << 24) +
  193462. ((png_int_32)(*(buf + 1)) << 16) +
  193463. ((png_int_32)(*(buf + 2)) << 8) +
  193464. (png_int_32)(*(buf + 3));
  193465. return (i);
  193466. }
  193467. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  193468. png_uint_16 PNGAPI
  193469. png_get_uint_16(png_bytep buf)
  193470. {
  193471. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  193472. (png_uint_16)(*(buf + 1)));
  193473. return (i);
  193474. }
  193475. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  193476. /* Read data, and (optionally) run it through the CRC. */
  193477. void /* PRIVATE */
  193478. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  193479. {
  193480. if(png_ptr == NULL) return;
  193481. png_read_data(png_ptr, buf, length);
  193482. png_calculate_crc(png_ptr, buf, length);
  193483. }
  193484. /* Optionally skip data and then check the CRC. Depending on whether we
  193485. are reading a ancillary or critical chunk, and how the program has set
  193486. things up, we may calculate the CRC on the data and print a message.
  193487. Returns '1' if there was a CRC error, '0' otherwise. */
  193488. int /* PRIVATE */
  193489. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  193490. {
  193491. png_size_t i;
  193492. png_size_t istop = png_ptr->zbuf_size;
  193493. for (i = (png_size_t)skip; i > istop; i -= istop)
  193494. {
  193495. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  193496. }
  193497. if (i)
  193498. {
  193499. png_crc_read(png_ptr, png_ptr->zbuf, i);
  193500. }
  193501. if (png_crc_error(png_ptr))
  193502. {
  193503. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  193504. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  193505. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  193506. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  193507. {
  193508. png_chunk_warning(png_ptr, "CRC error");
  193509. }
  193510. else
  193511. {
  193512. png_chunk_error(png_ptr, "CRC error");
  193513. }
  193514. return (1);
  193515. }
  193516. return (0);
  193517. }
  193518. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  193519. the data it has read thus far. */
  193520. int /* PRIVATE */
  193521. png_crc_error(png_structp png_ptr)
  193522. {
  193523. png_byte crc_bytes[4];
  193524. png_uint_32 crc;
  193525. int need_crc = 1;
  193526. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  193527. {
  193528. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  193529. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193530. need_crc = 0;
  193531. }
  193532. else /* critical */
  193533. {
  193534. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  193535. need_crc = 0;
  193536. }
  193537. png_read_data(png_ptr, crc_bytes, 4);
  193538. if (need_crc)
  193539. {
  193540. crc = png_get_uint_32(crc_bytes);
  193541. return ((int)(crc != png_ptr->crc));
  193542. }
  193543. else
  193544. return (0);
  193545. }
  193546. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  193547. defined(PNG_READ_iCCP_SUPPORTED)
  193548. /*
  193549. * Decompress trailing data in a chunk. The assumption is that chunkdata
  193550. * points at an allocated area holding the contents of a chunk with a
  193551. * trailing compressed part. What we get back is an allocated area
  193552. * holding the original prefix part and an uncompressed version of the
  193553. * trailing part (the malloc area passed in is freed).
  193554. */
  193555. png_charp /* PRIVATE */
  193556. png_decompress_chunk(png_structp png_ptr, int comp_type,
  193557. png_charp chunkdata, png_size_t chunklength,
  193558. png_size_t prefix_size, png_size_t *newlength)
  193559. {
  193560. static PNG_CONST char msg[] = "Error decoding compressed text";
  193561. png_charp text;
  193562. png_size_t text_size;
  193563. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  193564. {
  193565. int ret = Z_OK;
  193566. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  193567. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  193568. png_ptr->zstream.next_out = png_ptr->zbuf;
  193569. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193570. text_size = 0;
  193571. text = NULL;
  193572. while (png_ptr->zstream.avail_in)
  193573. {
  193574. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  193575. if (ret != Z_OK && ret != Z_STREAM_END)
  193576. {
  193577. if (png_ptr->zstream.msg != NULL)
  193578. png_warning(png_ptr, png_ptr->zstream.msg);
  193579. else
  193580. png_warning(png_ptr, msg);
  193581. inflateReset(&png_ptr->zstream);
  193582. png_ptr->zstream.avail_in = 0;
  193583. if (text == NULL)
  193584. {
  193585. text_size = prefix_size + png_sizeof(msg) + 1;
  193586. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  193587. if (text == NULL)
  193588. {
  193589. png_free(png_ptr,chunkdata);
  193590. png_error(png_ptr,"Not enough memory to decompress chunk");
  193591. }
  193592. png_memcpy(text, chunkdata, prefix_size);
  193593. }
  193594. text[text_size - 1] = 0x00;
  193595. /* Copy what we can of the error message into the text chunk */
  193596. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  193597. text_size = png_sizeof(msg) > text_size ? text_size :
  193598. png_sizeof(msg);
  193599. png_memcpy(text + prefix_size, msg, text_size + 1);
  193600. break;
  193601. }
  193602. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  193603. {
  193604. if (text == NULL)
  193605. {
  193606. text_size = prefix_size +
  193607. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193608. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  193609. if (text == NULL)
  193610. {
  193611. png_free(png_ptr,chunkdata);
  193612. png_error(png_ptr,"Not enough memory to decompress chunk.");
  193613. }
  193614. png_memcpy(text + prefix_size, png_ptr->zbuf,
  193615. text_size - prefix_size);
  193616. png_memcpy(text, chunkdata, prefix_size);
  193617. *(text + text_size) = 0x00;
  193618. }
  193619. else
  193620. {
  193621. png_charp tmp;
  193622. tmp = text;
  193623. text = (png_charp)png_malloc_warn(png_ptr,
  193624. (png_uint_32)(text_size +
  193625. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  193626. if (text == NULL)
  193627. {
  193628. png_free(png_ptr, tmp);
  193629. png_free(png_ptr, chunkdata);
  193630. png_error(png_ptr,"Not enough memory to decompress chunk..");
  193631. }
  193632. png_memcpy(text, tmp, text_size);
  193633. png_free(png_ptr, tmp);
  193634. png_memcpy(text + text_size, png_ptr->zbuf,
  193635. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  193636. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193637. *(text + text_size) = 0x00;
  193638. }
  193639. if (ret == Z_STREAM_END)
  193640. break;
  193641. else
  193642. {
  193643. png_ptr->zstream.next_out = png_ptr->zbuf;
  193644. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193645. }
  193646. }
  193647. }
  193648. if (ret != Z_STREAM_END)
  193649. {
  193650. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193651. char umsg[52];
  193652. if (ret == Z_BUF_ERROR)
  193653. png_snprintf(umsg, 52,
  193654. "Buffer error in compressed datastream in %s chunk",
  193655. png_ptr->chunk_name);
  193656. else if (ret == Z_DATA_ERROR)
  193657. png_snprintf(umsg, 52,
  193658. "Data error in compressed datastream in %s chunk",
  193659. png_ptr->chunk_name);
  193660. else
  193661. png_snprintf(umsg, 52,
  193662. "Incomplete compressed datastream in %s chunk",
  193663. png_ptr->chunk_name);
  193664. png_warning(png_ptr, umsg);
  193665. #else
  193666. png_warning(png_ptr,
  193667. "Incomplete compressed datastream in chunk other than IDAT");
  193668. #endif
  193669. text_size=prefix_size;
  193670. if (text == NULL)
  193671. {
  193672. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  193673. if (text == NULL)
  193674. {
  193675. png_free(png_ptr, chunkdata);
  193676. png_error(png_ptr,"Not enough memory for text.");
  193677. }
  193678. png_memcpy(text, chunkdata, prefix_size);
  193679. }
  193680. *(text + text_size) = 0x00;
  193681. }
  193682. inflateReset(&png_ptr->zstream);
  193683. png_ptr->zstream.avail_in = 0;
  193684. png_free(png_ptr, chunkdata);
  193685. chunkdata = text;
  193686. *newlength=text_size;
  193687. }
  193688. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  193689. {
  193690. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193691. char umsg[50];
  193692. png_snprintf(umsg, 50,
  193693. "Unknown zTXt compression type %d", comp_type);
  193694. png_warning(png_ptr, umsg);
  193695. #else
  193696. png_warning(png_ptr, "Unknown zTXt compression type");
  193697. #endif
  193698. *(chunkdata + prefix_size) = 0x00;
  193699. *newlength=prefix_size;
  193700. }
  193701. return chunkdata;
  193702. }
  193703. #endif
  193704. /* read and check the IDHR chunk */
  193705. void /* PRIVATE */
  193706. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193707. {
  193708. png_byte buf[13];
  193709. png_uint_32 width, height;
  193710. int bit_depth, color_type, compression_type, filter_type;
  193711. int interlace_type;
  193712. png_debug(1, "in png_handle_IHDR\n");
  193713. if (png_ptr->mode & PNG_HAVE_IHDR)
  193714. png_error(png_ptr, "Out of place IHDR");
  193715. /* check the length */
  193716. if (length != 13)
  193717. png_error(png_ptr, "Invalid IHDR chunk");
  193718. png_ptr->mode |= PNG_HAVE_IHDR;
  193719. png_crc_read(png_ptr, buf, 13);
  193720. png_crc_finish(png_ptr, 0);
  193721. width = png_get_uint_31(png_ptr, buf);
  193722. height = png_get_uint_31(png_ptr, buf + 4);
  193723. bit_depth = buf[8];
  193724. color_type = buf[9];
  193725. compression_type = buf[10];
  193726. filter_type = buf[11];
  193727. interlace_type = buf[12];
  193728. /* set internal variables */
  193729. png_ptr->width = width;
  193730. png_ptr->height = height;
  193731. png_ptr->bit_depth = (png_byte)bit_depth;
  193732. png_ptr->interlaced = (png_byte)interlace_type;
  193733. png_ptr->color_type = (png_byte)color_type;
  193734. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193735. png_ptr->filter_type = (png_byte)filter_type;
  193736. #endif
  193737. png_ptr->compression_type = (png_byte)compression_type;
  193738. /* find number of channels */
  193739. switch (png_ptr->color_type)
  193740. {
  193741. case PNG_COLOR_TYPE_GRAY:
  193742. case PNG_COLOR_TYPE_PALETTE:
  193743. png_ptr->channels = 1;
  193744. break;
  193745. case PNG_COLOR_TYPE_RGB:
  193746. png_ptr->channels = 3;
  193747. break;
  193748. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193749. png_ptr->channels = 2;
  193750. break;
  193751. case PNG_COLOR_TYPE_RGB_ALPHA:
  193752. png_ptr->channels = 4;
  193753. break;
  193754. }
  193755. /* set up other useful info */
  193756. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  193757. png_ptr->channels);
  193758. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  193759. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  193760. png_debug1(3,"channels = %d\n", png_ptr->channels);
  193761. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  193762. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  193763. color_type, interlace_type, compression_type, filter_type);
  193764. }
  193765. /* read and check the palette */
  193766. void /* PRIVATE */
  193767. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193768. {
  193769. png_color palette[PNG_MAX_PALETTE_LENGTH];
  193770. int num, i;
  193771. #ifndef PNG_NO_POINTER_INDEXING
  193772. png_colorp pal_ptr;
  193773. #endif
  193774. png_debug(1, "in png_handle_PLTE\n");
  193775. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193776. png_error(png_ptr, "Missing IHDR before PLTE");
  193777. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193778. {
  193779. png_warning(png_ptr, "Invalid PLTE after IDAT");
  193780. png_crc_finish(png_ptr, length);
  193781. return;
  193782. }
  193783. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193784. png_error(png_ptr, "Duplicate PLTE chunk");
  193785. png_ptr->mode |= PNG_HAVE_PLTE;
  193786. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  193787. {
  193788. png_warning(png_ptr,
  193789. "Ignoring PLTE chunk in grayscale PNG");
  193790. png_crc_finish(png_ptr, length);
  193791. return;
  193792. }
  193793. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193794. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  193795. {
  193796. png_crc_finish(png_ptr, length);
  193797. return;
  193798. }
  193799. #endif
  193800. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  193801. {
  193802. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  193803. {
  193804. png_warning(png_ptr, "Invalid palette chunk");
  193805. png_crc_finish(png_ptr, length);
  193806. return;
  193807. }
  193808. else
  193809. {
  193810. png_error(png_ptr, "Invalid palette chunk");
  193811. }
  193812. }
  193813. num = (int)length / 3;
  193814. #ifndef PNG_NO_POINTER_INDEXING
  193815. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  193816. {
  193817. png_byte buf[3];
  193818. png_crc_read(png_ptr, buf, 3);
  193819. pal_ptr->red = buf[0];
  193820. pal_ptr->green = buf[1];
  193821. pal_ptr->blue = buf[2];
  193822. }
  193823. #else
  193824. for (i = 0; i < num; i++)
  193825. {
  193826. png_byte buf[3];
  193827. png_crc_read(png_ptr, buf, 3);
  193828. /* don't depend upon png_color being any order */
  193829. palette[i].red = buf[0];
  193830. palette[i].green = buf[1];
  193831. palette[i].blue = buf[2];
  193832. }
  193833. #endif
  193834. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  193835. whatever the normal CRC configuration tells us. However, if we
  193836. have an RGB image, the PLTE can be considered ancillary, so
  193837. we will act as though it is. */
  193838. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193839. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193840. #endif
  193841. {
  193842. png_crc_finish(png_ptr, 0);
  193843. }
  193844. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193845. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  193846. {
  193847. /* If we don't want to use the data from an ancillary chunk,
  193848. we have two options: an error abort, or a warning and we
  193849. ignore the data in this chunk (which should be OK, since
  193850. it's considered ancillary for a RGB or RGBA image). */
  193851. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  193852. {
  193853. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  193854. {
  193855. png_chunk_error(png_ptr, "CRC error");
  193856. }
  193857. else
  193858. {
  193859. png_chunk_warning(png_ptr, "CRC error");
  193860. return;
  193861. }
  193862. }
  193863. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  193864. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193865. {
  193866. png_chunk_warning(png_ptr, "CRC error");
  193867. }
  193868. }
  193869. #endif
  193870. png_set_PLTE(png_ptr, info_ptr, palette, num);
  193871. #if defined(PNG_READ_tRNS_SUPPORTED)
  193872. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193873. {
  193874. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  193875. {
  193876. if (png_ptr->num_trans > (png_uint_16)num)
  193877. {
  193878. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  193879. png_ptr->num_trans = (png_uint_16)num;
  193880. }
  193881. if (info_ptr->num_trans > (png_uint_16)num)
  193882. {
  193883. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  193884. info_ptr->num_trans = (png_uint_16)num;
  193885. }
  193886. }
  193887. }
  193888. #endif
  193889. }
  193890. void /* PRIVATE */
  193891. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193892. {
  193893. png_debug(1, "in png_handle_IEND\n");
  193894. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  193895. {
  193896. png_error(png_ptr, "No image in file");
  193897. }
  193898. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  193899. if (length != 0)
  193900. {
  193901. png_warning(png_ptr, "Incorrect IEND chunk length");
  193902. }
  193903. png_crc_finish(png_ptr, length);
  193904. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  193905. }
  193906. #if defined(PNG_READ_gAMA_SUPPORTED)
  193907. void /* PRIVATE */
  193908. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193909. {
  193910. png_fixed_point igamma;
  193911. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193912. float file_gamma;
  193913. #endif
  193914. png_byte buf[4];
  193915. png_debug(1, "in png_handle_gAMA\n");
  193916. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193917. png_error(png_ptr, "Missing IHDR before gAMA");
  193918. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193919. {
  193920. png_warning(png_ptr, "Invalid gAMA after IDAT");
  193921. png_crc_finish(png_ptr, length);
  193922. return;
  193923. }
  193924. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193925. /* Should be an error, but we can cope with it */
  193926. png_warning(png_ptr, "Out of place gAMA chunk");
  193927. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  193928. #if defined(PNG_READ_sRGB_SUPPORTED)
  193929. && !(info_ptr->valid & PNG_INFO_sRGB)
  193930. #endif
  193931. )
  193932. {
  193933. png_warning(png_ptr, "Duplicate gAMA chunk");
  193934. png_crc_finish(png_ptr, length);
  193935. return;
  193936. }
  193937. if (length != 4)
  193938. {
  193939. png_warning(png_ptr, "Incorrect gAMA chunk length");
  193940. png_crc_finish(png_ptr, length);
  193941. return;
  193942. }
  193943. png_crc_read(png_ptr, buf, 4);
  193944. if (png_crc_finish(png_ptr, 0))
  193945. return;
  193946. igamma = (png_fixed_point)png_get_uint_32(buf);
  193947. /* check for zero gamma */
  193948. if (igamma == 0)
  193949. {
  193950. png_warning(png_ptr,
  193951. "Ignoring gAMA chunk with gamma=0");
  193952. return;
  193953. }
  193954. #if defined(PNG_READ_sRGB_SUPPORTED)
  193955. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  193956. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  193957. {
  193958. png_warning(png_ptr,
  193959. "Ignoring incorrect gAMA value when sRGB is also present");
  193960. #ifndef PNG_NO_CONSOLE_IO
  193961. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  193962. #endif
  193963. return;
  193964. }
  193965. #endif /* PNG_READ_sRGB_SUPPORTED */
  193966. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193967. file_gamma = (float)igamma / (float)100000.0;
  193968. # ifdef PNG_READ_GAMMA_SUPPORTED
  193969. png_ptr->gamma = file_gamma;
  193970. # endif
  193971. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  193972. #endif
  193973. #ifdef PNG_FIXED_POINT_SUPPORTED
  193974. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  193975. #endif
  193976. }
  193977. #endif
  193978. #if defined(PNG_READ_sBIT_SUPPORTED)
  193979. void /* PRIVATE */
  193980. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193981. {
  193982. png_size_t truelen;
  193983. png_byte buf[4];
  193984. png_debug(1, "in png_handle_sBIT\n");
  193985. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  193986. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193987. png_error(png_ptr, "Missing IHDR before sBIT");
  193988. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193989. {
  193990. png_warning(png_ptr, "Invalid sBIT after IDAT");
  193991. png_crc_finish(png_ptr, length);
  193992. return;
  193993. }
  193994. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193995. {
  193996. /* Should be an error, but we can cope with it */
  193997. png_warning(png_ptr, "Out of place sBIT chunk");
  193998. }
  193999. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194000. {
  194001. png_warning(png_ptr, "Duplicate sBIT chunk");
  194002. png_crc_finish(png_ptr, length);
  194003. return;
  194004. }
  194005. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194006. truelen = 3;
  194007. else
  194008. truelen = (png_size_t)png_ptr->channels;
  194009. if (length != truelen || length > 4)
  194010. {
  194011. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194012. png_crc_finish(png_ptr, length);
  194013. return;
  194014. }
  194015. png_crc_read(png_ptr, buf, truelen);
  194016. if (png_crc_finish(png_ptr, 0))
  194017. return;
  194018. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194019. {
  194020. png_ptr->sig_bit.red = buf[0];
  194021. png_ptr->sig_bit.green = buf[1];
  194022. png_ptr->sig_bit.blue = buf[2];
  194023. png_ptr->sig_bit.alpha = buf[3];
  194024. }
  194025. else
  194026. {
  194027. png_ptr->sig_bit.gray = buf[0];
  194028. png_ptr->sig_bit.red = buf[0];
  194029. png_ptr->sig_bit.green = buf[0];
  194030. png_ptr->sig_bit.blue = buf[0];
  194031. png_ptr->sig_bit.alpha = buf[1];
  194032. }
  194033. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194034. }
  194035. #endif
  194036. #if defined(PNG_READ_cHRM_SUPPORTED)
  194037. void /* PRIVATE */
  194038. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194039. {
  194040. png_byte buf[4];
  194041. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194042. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194043. #endif
  194044. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194045. int_y_green, int_x_blue, int_y_blue;
  194046. png_uint_32 uint_x, uint_y;
  194047. png_debug(1, "in png_handle_cHRM\n");
  194048. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194049. png_error(png_ptr, "Missing IHDR before cHRM");
  194050. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194051. {
  194052. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194053. png_crc_finish(png_ptr, length);
  194054. return;
  194055. }
  194056. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194057. /* Should be an error, but we can cope with it */
  194058. png_warning(png_ptr, "Missing PLTE before cHRM");
  194059. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194060. #if defined(PNG_READ_sRGB_SUPPORTED)
  194061. && !(info_ptr->valid & PNG_INFO_sRGB)
  194062. #endif
  194063. )
  194064. {
  194065. png_warning(png_ptr, "Duplicate cHRM chunk");
  194066. png_crc_finish(png_ptr, length);
  194067. return;
  194068. }
  194069. if (length != 32)
  194070. {
  194071. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194072. png_crc_finish(png_ptr, length);
  194073. return;
  194074. }
  194075. png_crc_read(png_ptr, buf, 4);
  194076. uint_x = png_get_uint_32(buf);
  194077. png_crc_read(png_ptr, buf, 4);
  194078. uint_y = png_get_uint_32(buf);
  194079. if (uint_x > 80000L || uint_y > 80000L ||
  194080. uint_x + uint_y > 100000L)
  194081. {
  194082. png_warning(png_ptr, "Invalid cHRM white point");
  194083. png_crc_finish(png_ptr, 24);
  194084. return;
  194085. }
  194086. int_x_white = (png_fixed_point)uint_x;
  194087. int_y_white = (png_fixed_point)uint_y;
  194088. png_crc_read(png_ptr, buf, 4);
  194089. uint_x = png_get_uint_32(buf);
  194090. png_crc_read(png_ptr, buf, 4);
  194091. uint_y = png_get_uint_32(buf);
  194092. if (uint_x + uint_y > 100000L)
  194093. {
  194094. png_warning(png_ptr, "Invalid cHRM red point");
  194095. png_crc_finish(png_ptr, 16);
  194096. return;
  194097. }
  194098. int_x_red = (png_fixed_point)uint_x;
  194099. int_y_red = (png_fixed_point)uint_y;
  194100. png_crc_read(png_ptr, buf, 4);
  194101. uint_x = png_get_uint_32(buf);
  194102. png_crc_read(png_ptr, buf, 4);
  194103. uint_y = png_get_uint_32(buf);
  194104. if (uint_x + uint_y > 100000L)
  194105. {
  194106. png_warning(png_ptr, "Invalid cHRM green point");
  194107. png_crc_finish(png_ptr, 8);
  194108. return;
  194109. }
  194110. int_x_green = (png_fixed_point)uint_x;
  194111. int_y_green = (png_fixed_point)uint_y;
  194112. png_crc_read(png_ptr, buf, 4);
  194113. uint_x = png_get_uint_32(buf);
  194114. png_crc_read(png_ptr, buf, 4);
  194115. uint_y = png_get_uint_32(buf);
  194116. if (uint_x + uint_y > 100000L)
  194117. {
  194118. png_warning(png_ptr, "Invalid cHRM blue point");
  194119. png_crc_finish(png_ptr, 0);
  194120. return;
  194121. }
  194122. int_x_blue = (png_fixed_point)uint_x;
  194123. int_y_blue = (png_fixed_point)uint_y;
  194124. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194125. white_x = (float)int_x_white / (float)100000.0;
  194126. white_y = (float)int_y_white / (float)100000.0;
  194127. red_x = (float)int_x_red / (float)100000.0;
  194128. red_y = (float)int_y_red / (float)100000.0;
  194129. green_x = (float)int_x_green / (float)100000.0;
  194130. green_y = (float)int_y_green / (float)100000.0;
  194131. blue_x = (float)int_x_blue / (float)100000.0;
  194132. blue_y = (float)int_y_blue / (float)100000.0;
  194133. #endif
  194134. #if defined(PNG_READ_sRGB_SUPPORTED)
  194135. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194136. {
  194137. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194138. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194139. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194140. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194141. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194142. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194143. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194144. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194145. {
  194146. png_warning(png_ptr,
  194147. "Ignoring incorrect cHRM value when sRGB is also present");
  194148. #ifndef PNG_NO_CONSOLE_IO
  194149. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194150. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194151. white_x, white_y, red_x, red_y);
  194152. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194153. green_x, green_y, blue_x, blue_y);
  194154. #else
  194155. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194156. int_x_white, int_y_white, int_x_red, int_y_red);
  194157. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194158. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194159. #endif
  194160. #endif /* PNG_NO_CONSOLE_IO */
  194161. }
  194162. png_crc_finish(png_ptr, 0);
  194163. return;
  194164. }
  194165. #endif /* PNG_READ_sRGB_SUPPORTED */
  194166. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194167. png_set_cHRM(png_ptr, info_ptr,
  194168. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194169. #endif
  194170. #ifdef PNG_FIXED_POINT_SUPPORTED
  194171. png_set_cHRM_fixed(png_ptr, info_ptr,
  194172. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194173. int_y_green, int_x_blue, int_y_blue);
  194174. #endif
  194175. if (png_crc_finish(png_ptr, 0))
  194176. return;
  194177. }
  194178. #endif
  194179. #if defined(PNG_READ_sRGB_SUPPORTED)
  194180. void /* PRIVATE */
  194181. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194182. {
  194183. int intent;
  194184. png_byte buf[1];
  194185. png_debug(1, "in png_handle_sRGB\n");
  194186. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194187. png_error(png_ptr, "Missing IHDR before sRGB");
  194188. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194189. {
  194190. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194191. png_crc_finish(png_ptr, length);
  194192. return;
  194193. }
  194194. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194195. /* Should be an error, but we can cope with it */
  194196. png_warning(png_ptr, "Out of place sRGB chunk");
  194197. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194198. {
  194199. png_warning(png_ptr, "Duplicate sRGB chunk");
  194200. png_crc_finish(png_ptr, length);
  194201. return;
  194202. }
  194203. if (length != 1)
  194204. {
  194205. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194206. png_crc_finish(png_ptr, length);
  194207. return;
  194208. }
  194209. png_crc_read(png_ptr, buf, 1);
  194210. if (png_crc_finish(png_ptr, 0))
  194211. return;
  194212. intent = buf[0];
  194213. /* check for bad intent */
  194214. if (intent >= PNG_sRGB_INTENT_LAST)
  194215. {
  194216. png_warning(png_ptr, "Unknown sRGB intent");
  194217. return;
  194218. }
  194219. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194220. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194221. {
  194222. png_fixed_point igamma;
  194223. #ifdef PNG_FIXED_POINT_SUPPORTED
  194224. igamma=info_ptr->int_gamma;
  194225. #else
  194226. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194227. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194228. # endif
  194229. #endif
  194230. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194231. {
  194232. png_warning(png_ptr,
  194233. "Ignoring incorrect gAMA value when sRGB is also present");
  194234. #ifndef PNG_NO_CONSOLE_IO
  194235. # ifdef PNG_FIXED_POINT_SUPPORTED
  194236. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194237. # else
  194238. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194239. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194240. # endif
  194241. # endif
  194242. #endif
  194243. }
  194244. }
  194245. #endif /* PNG_READ_gAMA_SUPPORTED */
  194246. #ifdef PNG_READ_cHRM_SUPPORTED
  194247. #ifdef PNG_FIXED_POINT_SUPPORTED
  194248. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194249. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194250. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194251. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194252. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194253. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194254. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194255. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194256. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194257. {
  194258. png_warning(png_ptr,
  194259. "Ignoring incorrect cHRM value when sRGB is also present");
  194260. }
  194261. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194262. #endif /* PNG_READ_cHRM_SUPPORTED */
  194263. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194264. }
  194265. #endif /* PNG_READ_sRGB_SUPPORTED */
  194266. #if defined(PNG_READ_iCCP_SUPPORTED)
  194267. void /* PRIVATE */
  194268. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194269. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194270. {
  194271. png_charp chunkdata;
  194272. png_byte compression_type;
  194273. png_bytep pC;
  194274. png_charp profile;
  194275. png_uint_32 skip = 0;
  194276. png_uint_32 profile_size, profile_length;
  194277. png_size_t slength, prefix_length, data_length;
  194278. png_debug(1, "in png_handle_iCCP\n");
  194279. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194280. png_error(png_ptr, "Missing IHDR before iCCP");
  194281. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194282. {
  194283. png_warning(png_ptr, "Invalid iCCP after IDAT");
  194284. png_crc_finish(png_ptr, length);
  194285. return;
  194286. }
  194287. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194288. /* Should be an error, but we can cope with it */
  194289. png_warning(png_ptr, "Out of place iCCP chunk");
  194290. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  194291. {
  194292. png_warning(png_ptr, "Duplicate iCCP chunk");
  194293. png_crc_finish(png_ptr, length);
  194294. return;
  194295. }
  194296. #ifdef PNG_MAX_MALLOC_64K
  194297. if (length > (png_uint_32)65535L)
  194298. {
  194299. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  194300. skip = length - (png_uint_32)65535L;
  194301. length = (png_uint_32)65535L;
  194302. }
  194303. #endif
  194304. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194305. slength = (png_size_t)length;
  194306. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194307. if (png_crc_finish(png_ptr, skip))
  194308. {
  194309. png_free(png_ptr, chunkdata);
  194310. return;
  194311. }
  194312. chunkdata[slength] = 0x00;
  194313. for (profile = chunkdata; *profile; profile++)
  194314. /* empty loop to find end of name */ ;
  194315. ++profile;
  194316. /* there should be at least one zero (the compression type byte)
  194317. following the separator, and we should be on it */
  194318. if ( profile >= chunkdata + slength - 1)
  194319. {
  194320. png_free(png_ptr, chunkdata);
  194321. png_warning(png_ptr, "Malformed iCCP chunk");
  194322. return;
  194323. }
  194324. /* compression_type should always be zero */
  194325. compression_type = *profile++;
  194326. if (compression_type)
  194327. {
  194328. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194329. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194330. wrote nonzero) */
  194331. }
  194332. prefix_length = profile - chunkdata;
  194333. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194334. slength, prefix_length, &data_length);
  194335. profile_length = data_length - prefix_length;
  194336. if ( prefix_length > data_length || profile_length < 4)
  194337. {
  194338. png_free(png_ptr, chunkdata);
  194339. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194340. return;
  194341. }
  194342. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194343. pC = (png_bytep)(chunkdata+prefix_length);
  194344. profile_size = ((*(pC ))<<24) |
  194345. ((*(pC+1))<<16) |
  194346. ((*(pC+2))<< 8) |
  194347. ((*(pC+3)) );
  194348. if(profile_size < profile_length)
  194349. profile_length = profile_size;
  194350. if(profile_size > profile_length)
  194351. {
  194352. png_free(png_ptr, chunkdata);
  194353. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194354. return;
  194355. }
  194356. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194357. chunkdata + prefix_length, profile_length);
  194358. png_free(png_ptr, chunkdata);
  194359. }
  194360. #endif /* PNG_READ_iCCP_SUPPORTED */
  194361. #if defined(PNG_READ_sPLT_SUPPORTED)
  194362. void /* PRIVATE */
  194363. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194364. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194365. {
  194366. png_bytep chunkdata;
  194367. png_bytep entry_start;
  194368. png_sPLT_t new_palette;
  194369. #ifdef PNG_NO_POINTER_INDEXING
  194370. png_sPLT_entryp pp;
  194371. #endif
  194372. int data_length, entry_size, i;
  194373. png_uint_32 skip = 0;
  194374. png_size_t slength;
  194375. png_debug(1, "in png_handle_sPLT\n");
  194376. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194377. png_error(png_ptr, "Missing IHDR before sPLT");
  194378. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194379. {
  194380. png_warning(png_ptr, "Invalid sPLT after IDAT");
  194381. png_crc_finish(png_ptr, length);
  194382. return;
  194383. }
  194384. #ifdef PNG_MAX_MALLOC_64K
  194385. if (length > (png_uint_32)65535L)
  194386. {
  194387. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  194388. skip = length - (png_uint_32)65535L;
  194389. length = (png_uint_32)65535L;
  194390. }
  194391. #endif
  194392. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  194393. slength = (png_size_t)length;
  194394. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194395. if (png_crc_finish(png_ptr, skip))
  194396. {
  194397. png_free(png_ptr, chunkdata);
  194398. return;
  194399. }
  194400. chunkdata[slength] = 0x00;
  194401. for (entry_start = chunkdata; *entry_start; entry_start++)
  194402. /* empty loop to find end of name */ ;
  194403. ++entry_start;
  194404. /* a sample depth should follow the separator, and we should be on it */
  194405. if (entry_start > chunkdata + slength - 2)
  194406. {
  194407. png_free(png_ptr, chunkdata);
  194408. png_warning(png_ptr, "malformed sPLT chunk");
  194409. return;
  194410. }
  194411. new_palette.depth = *entry_start++;
  194412. entry_size = (new_palette.depth == 8 ? 6 : 10);
  194413. data_length = (slength - (entry_start - chunkdata));
  194414. /* integrity-check the data length */
  194415. if (data_length % entry_size)
  194416. {
  194417. png_free(png_ptr, chunkdata);
  194418. png_warning(png_ptr, "sPLT chunk has bad length");
  194419. return;
  194420. }
  194421. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  194422. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  194423. png_sizeof(png_sPLT_entry)))
  194424. {
  194425. png_warning(png_ptr, "sPLT chunk too long");
  194426. return;
  194427. }
  194428. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  194429. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  194430. if (new_palette.entries == NULL)
  194431. {
  194432. png_warning(png_ptr, "sPLT chunk requires too much memory");
  194433. return;
  194434. }
  194435. #ifndef PNG_NO_POINTER_INDEXING
  194436. for (i = 0; i < new_palette.nentries; i++)
  194437. {
  194438. png_sPLT_entryp pp = new_palette.entries + i;
  194439. if (new_palette.depth == 8)
  194440. {
  194441. pp->red = *entry_start++;
  194442. pp->green = *entry_start++;
  194443. pp->blue = *entry_start++;
  194444. pp->alpha = *entry_start++;
  194445. }
  194446. else
  194447. {
  194448. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  194449. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  194450. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  194451. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  194452. }
  194453. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194454. }
  194455. #else
  194456. pp = new_palette.entries;
  194457. for (i = 0; i < new_palette.nentries; i++)
  194458. {
  194459. if (new_palette.depth == 8)
  194460. {
  194461. pp[i].red = *entry_start++;
  194462. pp[i].green = *entry_start++;
  194463. pp[i].blue = *entry_start++;
  194464. pp[i].alpha = *entry_start++;
  194465. }
  194466. else
  194467. {
  194468. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  194469. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  194470. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  194471. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  194472. }
  194473. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194474. }
  194475. #endif
  194476. /* discard all chunk data except the name and stash that */
  194477. new_palette.name = (png_charp)chunkdata;
  194478. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  194479. png_free(png_ptr, chunkdata);
  194480. png_free(png_ptr, new_palette.entries);
  194481. }
  194482. #endif /* PNG_READ_sPLT_SUPPORTED */
  194483. #if defined(PNG_READ_tRNS_SUPPORTED)
  194484. void /* PRIVATE */
  194485. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194486. {
  194487. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  194488. int bit_mask;
  194489. png_debug(1, "in png_handle_tRNS\n");
  194490. /* For non-indexed color, mask off any bits in the tRNS value that
  194491. * exceed the bit depth. Some creators were writing extra bits there.
  194492. * This is not needed for indexed color. */
  194493. bit_mask = (1 << png_ptr->bit_depth) - 1;
  194494. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194495. png_error(png_ptr, "Missing IHDR before tRNS");
  194496. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194497. {
  194498. png_warning(png_ptr, "Invalid tRNS after IDAT");
  194499. png_crc_finish(png_ptr, length);
  194500. return;
  194501. }
  194502. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194503. {
  194504. png_warning(png_ptr, "Duplicate tRNS chunk");
  194505. png_crc_finish(png_ptr, length);
  194506. return;
  194507. }
  194508. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  194509. {
  194510. png_byte buf[2];
  194511. if (length != 2)
  194512. {
  194513. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194514. png_crc_finish(png_ptr, length);
  194515. return;
  194516. }
  194517. png_crc_read(png_ptr, buf, 2);
  194518. png_ptr->num_trans = 1;
  194519. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  194520. }
  194521. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  194522. {
  194523. png_byte buf[6];
  194524. if (length != 6)
  194525. {
  194526. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194527. png_crc_finish(png_ptr, length);
  194528. return;
  194529. }
  194530. png_crc_read(png_ptr, buf, (png_size_t)length);
  194531. png_ptr->num_trans = 1;
  194532. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  194533. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  194534. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  194535. }
  194536. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194537. {
  194538. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194539. {
  194540. /* Should be an error, but we can cope with it. */
  194541. png_warning(png_ptr, "Missing PLTE before tRNS");
  194542. }
  194543. if (length > (png_uint_32)png_ptr->num_palette ||
  194544. length > PNG_MAX_PALETTE_LENGTH)
  194545. {
  194546. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194547. png_crc_finish(png_ptr, length);
  194548. return;
  194549. }
  194550. if (length == 0)
  194551. {
  194552. png_warning(png_ptr, "Zero length tRNS chunk");
  194553. png_crc_finish(png_ptr, length);
  194554. return;
  194555. }
  194556. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  194557. png_ptr->num_trans = (png_uint_16)length;
  194558. }
  194559. else
  194560. {
  194561. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  194562. png_crc_finish(png_ptr, length);
  194563. return;
  194564. }
  194565. if (png_crc_finish(png_ptr, 0))
  194566. {
  194567. png_ptr->num_trans = 0;
  194568. return;
  194569. }
  194570. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  194571. &(png_ptr->trans_values));
  194572. }
  194573. #endif
  194574. #if defined(PNG_READ_bKGD_SUPPORTED)
  194575. void /* PRIVATE */
  194576. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194577. {
  194578. png_size_t truelen;
  194579. png_byte buf[6];
  194580. png_debug(1, "in png_handle_bKGD\n");
  194581. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194582. png_error(png_ptr, "Missing IHDR before bKGD");
  194583. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194584. {
  194585. png_warning(png_ptr, "Invalid bKGD after IDAT");
  194586. png_crc_finish(png_ptr, length);
  194587. return;
  194588. }
  194589. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  194590. !(png_ptr->mode & PNG_HAVE_PLTE))
  194591. {
  194592. png_warning(png_ptr, "Missing PLTE before bKGD");
  194593. png_crc_finish(png_ptr, length);
  194594. return;
  194595. }
  194596. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  194597. {
  194598. png_warning(png_ptr, "Duplicate bKGD chunk");
  194599. png_crc_finish(png_ptr, length);
  194600. return;
  194601. }
  194602. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194603. truelen = 1;
  194604. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194605. truelen = 6;
  194606. else
  194607. truelen = 2;
  194608. if (length != truelen)
  194609. {
  194610. png_warning(png_ptr, "Incorrect bKGD chunk length");
  194611. png_crc_finish(png_ptr, length);
  194612. return;
  194613. }
  194614. png_crc_read(png_ptr, buf, truelen);
  194615. if (png_crc_finish(png_ptr, 0))
  194616. return;
  194617. /* We convert the index value into RGB components so that we can allow
  194618. * arbitrary RGB values for background when we have transparency, and
  194619. * so it is easy to determine the RGB values of the background color
  194620. * from the info_ptr struct. */
  194621. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194622. {
  194623. png_ptr->background.index = buf[0];
  194624. if(info_ptr->num_palette)
  194625. {
  194626. if(buf[0] > info_ptr->num_palette)
  194627. {
  194628. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  194629. return;
  194630. }
  194631. png_ptr->background.red =
  194632. (png_uint_16)png_ptr->palette[buf[0]].red;
  194633. png_ptr->background.green =
  194634. (png_uint_16)png_ptr->palette[buf[0]].green;
  194635. png_ptr->background.blue =
  194636. (png_uint_16)png_ptr->palette[buf[0]].blue;
  194637. }
  194638. }
  194639. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  194640. {
  194641. png_ptr->background.red =
  194642. png_ptr->background.green =
  194643. png_ptr->background.blue =
  194644. png_ptr->background.gray = png_get_uint_16(buf);
  194645. }
  194646. else
  194647. {
  194648. png_ptr->background.red = png_get_uint_16(buf);
  194649. png_ptr->background.green = png_get_uint_16(buf + 2);
  194650. png_ptr->background.blue = png_get_uint_16(buf + 4);
  194651. }
  194652. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  194653. }
  194654. #endif
  194655. #if defined(PNG_READ_hIST_SUPPORTED)
  194656. void /* PRIVATE */
  194657. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194658. {
  194659. unsigned int num, i;
  194660. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  194661. png_debug(1, "in png_handle_hIST\n");
  194662. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194663. png_error(png_ptr, "Missing IHDR before hIST");
  194664. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194665. {
  194666. png_warning(png_ptr, "Invalid hIST after IDAT");
  194667. png_crc_finish(png_ptr, length);
  194668. return;
  194669. }
  194670. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194671. {
  194672. png_warning(png_ptr, "Missing PLTE before hIST");
  194673. png_crc_finish(png_ptr, length);
  194674. return;
  194675. }
  194676. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  194677. {
  194678. png_warning(png_ptr, "Duplicate hIST chunk");
  194679. png_crc_finish(png_ptr, length);
  194680. return;
  194681. }
  194682. num = length / 2 ;
  194683. if (num != (unsigned int) png_ptr->num_palette || num >
  194684. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  194685. {
  194686. png_warning(png_ptr, "Incorrect hIST chunk length");
  194687. png_crc_finish(png_ptr, length);
  194688. return;
  194689. }
  194690. for (i = 0; i < num; i++)
  194691. {
  194692. png_byte buf[2];
  194693. png_crc_read(png_ptr, buf, 2);
  194694. readbuf[i] = png_get_uint_16(buf);
  194695. }
  194696. if (png_crc_finish(png_ptr, 0))
  194697. return;
  194698. png_set_hIST(png_ptr, info_ptr, readbuf);
  194699. }
  194700. #endif
  194701. #if defined(PNG_READ_pHYs_SUPPORTED)
  194702. void /* PRIVATE */
  194703. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194704. {
  194705. png_byte buf[9];
  194706. png_uint_32 res_x, res_y;
  194707. int unit_type;
  194708. png_debug(1, "in png_handle_pHYs\n");
  194709. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194710. png_error(png_ptr, "Missing IHDR before pHYs");
  194711. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194712. {
  194713. png_warning(png_ptr, "Invalid pHYs after IDAT");
  194714. png_crc_finish(png_ptr, length);
  194715. return;
  194716. }
  194717. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  194718. {
  194719. png_warning(png_ptr, "Duplicate pHYs chunk");
  194720. png_crc_finish(png_ptr, length);
  194721. return;
  194722. }
  194723. if (length != 9)
  194724. {
  194725. png_warning(png_ptr, "Incorrect pHYs chunk length");
  194726. png_crc_finish(png_ptr, length);
  194727. return;
  194728. }
  194729. png_crc_read(png_ptr, buf, 9);
  194730. if (png_crc_finish(png_ptr, 0))
  194731. return;
  194732. res_x = png_get_uint_32(buf);
  194733. res_y = png_get_uint_32(buf + 4);
  194734. unit_type = buf[8];
  194735. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  194736. }
  194737. #endif
  194738. #if defined(PNG_READ_oFFs_SUPPORTED)
  194739. void /* PRIVATE */
  194740. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194741. {
  194742. png_byte buf[9];
  194743. png_int_32 offset_x, offset_y;
  194744. int unit_type;
  194745. png_debug(1, "in png_handle_oFFs\n");
  194746. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194747. png_error(png_ptr, "Missing IHDR before oFFs");
  194748. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194749. {
  194750. png_warning(png_ptr, "Invalid oFFs after IDAT");
  194751. png_crc_finish(png_ptr, length);
  194752. return;
  194753. }
  194754. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  194755. {
  194756. png_warning(png_ptr, "Duplicate oFFs chunk");
  194757. png_crc_finish(png_ptr, length);
  194758. return;
  194759. }
  194760. if (length != 9)
  194761. {
  194762. png_warning(png_ptr, "Incorrect oFFs chunk length");
  194763. png_crc_finish(png_ptr, length);
  194764. return;
  194765. }
  194766. png_crc_read(png_ptr, buf, 9);
  194767. if (png_crc_finish(png_ptr, 0))
  194768. return;
  194769. offset_x = png_get_int_32(buf);
  194770. offset_y = png_get_int_32(buf + 4);
  194771. unit_type = buf[8];
  194772. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  194773. }
  194774. #endif
  194775. #if defined(PNG_READ_pCAL_SUPPORTED)
  194776. /* read the pCAL chunk (described in the PNG Extensions document) */
  194777. void /* PRIVATE */
  194778. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194779. {
  194780. png_charp purpose;
  194781. png_int_32 X0, X1;
  194782. png_byte type, nparams;
  194783. png_charp buf, units, endptr;
  194784. png_charpp params;
  194785. png_size_t slength;
  194786. int i;
  194787. png_debug(1, "in png_handle_pCAL\n");
  194788. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194789. png_error(png_ptr, "Missing IHDR before pCAL");
  194790. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194791. {
  194792. png_warning(png_ptr, "Invalid pCAL after IDAT");
  194793. png_crc_finish(png_ptr, length);
  194794. return;
  194795. }
  194796. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  194797. {
  194798. png_warning(png_ptr, "Duplicate pCAL chunk");
  194799. png_crc_finish(png_ptr, length);
  194800. return;
  194801. }
  194802. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  194803. length + 1);
  194804. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194805. if (purpose == NULL)
  194806. {
  194807. png_warning(png_ptr, "No memory for pCAL purpose.");
  194808. return;
  194809. }
  194810. slength = (png_size_t)length;
  194811. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  194812. if (png_crc_finish(png_ptr, 0))
  194813. {
  194814. png_free(png_ptr, purpose);
  194815. return;
  194816. }
  194817. purpose[slength] = 0x00; /* null terminate the last string */
  194818. png_debug(3, "Finding end of pCAL purpose string\n");
  194819. for (buf = purpose; *buf; buf++)
  194820. /* empty loop */ ;
  194821. endptr = purpose + slength;
  194822. /* We need to have at least 12 bytes after the purpose string
  194823. in order to get the parameter information. */
  194824. if (endptr <= buf + 12)
  194825. {
  194826. png_warning(png_ptr, "Invalid pCAL data");
  194827. png_free(png_ptr, purpose);
  194828. return;
  194829. }
  194830. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  194831. X0 = png_get_int_32((png_bytep)buf+1);
  194832. X1 = png_get_int_32((png_bytep)buf+5);
  194833. type = buf[9];
  194834. nparams = buf[10];
  194835. units = buf + 11;
  194836. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  194837. /* Check that we have the right number of parameters for known
  194838. equation types. */
  194839. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  194840. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  194841. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  194842. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  194843. {
  194844. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  194845. png_free(png_ptr, purpose);
  194846. return;
  194847. }
  194848. else if (type >= PNG_EQUATION_LAST)
  194849. {
  194850. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  194851. }
  194852. for (buf = units; *buf; buf++)
  194853. /* Empty loop to move past the units string. */ ;
  194854. png_debug(3, "Allocating pCAL parameters array\n");
  194855. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  194856. *png_sizeof(png_charp))) ;
  194857. if (params == NULL)
  194858. {
  194859. png_free(png_ptr, purpose);
  194860. png_warning(png_ptr, "No memory for pCAL params.");
  194861. return;
  194862. }
  194863. /* Get pointers to the start of each parameter string. */
  194864. for (i = 0; i < (int)nparams; i++)
  194865. {
  194866. buf++; /* Skip the null string terminator from previous parameter. */
  194867. png_debug1(3, "Reading pCAL parameter %d\n", i);
  194868. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  194869. /* Empty loop to move past each parameter string */ ;
  194870. /* Make sure we haven't run out of data yet */
  194871. if (buf > endptr)
  194872. {
  194873. png_warning(png_ptr, "Invalid pCAL data");
  194874. png_free(png_ptr, purpose);
  194875. png_free(png_ptr, params);
  194876. return;
  194877. }
  194878. }
  194879. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  194880. units, params);
  194881. png_free(png_ptr, purpose);
  194882. png_free(png_ptr, params);
  194883. }
  194884. #endif
  194885. #if defined(PNG_READ_sCAL_SUPPORTED)
  194886. /* read the sCAL chunk */
  194887. void /* PRIVATE */
  194888. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194889. {
  194890. png_charp buffer, ep;
  194891. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194892. double width, height;
  194893. png_charp vp;
  194894. #else
  194895. #ifdef PNG_FIXED_POINT_SUPPORTED
  194896. png_charp swidth, sheight;
  194897. #endif
  194898. #endif
  194899. png_size_t slength;
  194900. png_debug(1, "in png_handle_sCAL\n");
  194901. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194902. png_error(png_ptr, "Missing IHDR before sCAL");
  194903. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194904. {
  194905. png_warning(png_ptr, "Invalid sCAL after IDAT");
  194906. png_crc_finish(png_ptr, length);
  194907. return;
  194908. }
  194909. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  194910. {
  194911. png_warning(png_ptr, "Duplicate sCAL chunk");
  194912. png_crc_finish(png_ptr, length);
  194913. return;
  194914. }
  194915. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  194916. length + 1);
  194917. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194918. if (buffer == NULL)
  194919. {
  194920. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  194921. return;
  194922. }
  194923. slength = (png_size_t)length;
  194924. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  194925. if (png_crc_finish(png_ptr, 0))
  194926. {
  194927. png_free(png_ptr, buffer);
  194928. return;
  194929. }
  194930. buffer[slength] = 0x00; /* null terminate the last string */
  194931. ep = buffer + 1; /* skip unit byte */
  194932. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194933. width = png_strtod(png_ptr, ep, &vp);
  194934. if (*vp)
  194935. {
  194936. png_warning(png_ptr, "malformed width string in sCAL chunk");
  194937. return;
  194938. }
  194939. #else
  194940. #ifdef PNG_FIXED_POINT_SUPPORTED
  194941. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  194942. if (swidth == NULL)
  194943. {
  194944. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  194945. return;
  194946. }
  194947. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  194948. #endif
  194949. #endif
  194950. for (ep = buffer; *ep; ep++)
  194951. /* empty loop */ ;
  194952. ep++;
  194953. if (buffer + slength < ep)
  194954. {
  194955. png_warning(png_ptr, "Truncated sCAL chunk");
  194956. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  194957. !defined(PNG_FLOATING_POINT_SUPPORTED)
  194958. png_free(png_ptr, swidth);
  194959. #endif
  194960. png_free(png_ptr, buffer);
  194961. return;
  194962. }
  194963. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194964. height = png_strtod(png_ptr, ep, &vp);
  194965. if (*vp)
  194966. {
  194967. png_warning(png_ptr, "malformed height string in sCAL chunk");
  194968. return;
  194969. }
  194970. #else
  194971. #ifdef PNG_FIXED_POINT_SUPPORTED
  194972. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  194973. if (swidth == NULL)
  194974. {
  194975. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  194976. return;
  194977. }
  194978. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  194979. #endif
  194980. #endif
  194981. if (buffer + slength < ep
  194982. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194983. || width <= 0. || height <= 0.
  194984. #endif
  194985. )
  194986. {
  194987. png_warning(png_ptr, "Invalid sCAL data");
  194988. png_free(png_ptr, buffer);
  194989. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  194990. png_free(png_ptr, swidth);
  194991. png_free(png_ptr, sheight);
  194992. #endif
  194993. return;
  194994. }
  194995. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194996. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  194997. #else
  194998. #ifdef PNG_FIXED_POINT_SUPPORTED
  194999. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195000. #endif
  195001. #endif
  195002. png_free(png_ptr, buffer);
  195003. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195004. png_free(png_ptr, swidth);
  195005. png_free(png_ptr, sheight);
  195006. #endif
  195007. }
  195008. #endif
  195009. #if defined(PNG_READ_tIME_SUPPORTED)
  195010. void /* PRIVATE */
  195011. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195012. {
  195013. png_byte buf[7];
  195014. png_time mod_time;
  195015. png_debug(1, "in png_handle_tIME\n");
  195016. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195017. png_error(png_ptr, "Out of place tIME chunk");
  195018. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195019. {
  195020. png_warning(png_ptr, "Duplicate tIME chunk");
  195021. png_crc_finish(png_ptr, length);
  195022. return;
  195023. }
  195024. if (png_ptr->mode & PNG_HAVE_IDAT)
  195025. png_ptr->mode |= PNG_AFTER_IDAT;
  195026. if (length != 7)
  195027. {
  195028. png_warning(png_ptr, "Incorrect tIME chunk length");
  195029. png_crc_finish(png_ptr, length);
  195030. return;
  195031. }
  195032. png_crc_read(png_ptr, buf, 7);
  195033. if (png_crc_finish(png_ptr, 0))
  195034. return;
  195035. mod_time.second = buf[6];
  195036. mod_time.minute = buf[5];
  195037. mod_time.hour = buf[4];
  195038. mod_time.day = buf[3];
  195039. mod_time.month = buf[2];
  195040. mod_time.year = png_get_uint_16(buf);
  195041. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195042. }
  195043. #endif
  195044. #if defined(PNG_READ_tEXt_SUPPORTED)
  195045. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195046. void /* PRIVATE */
  195047. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195048. {
  195049. png_textp text_ptr;
  195050. png_charp key;
  195051. png_charp text;
  195052. png_uint_32 skip = 0;
  195053. png_size_t slength;
  195054. int ret;
  195055. png_debug(1, "in png_handle_tEXt\n");
  195056. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195057. png_error(png_ptr, "Missing IHDR before tEXt");
  195058. if (png_ptr->mode & PNG_HAVE_IDAT)
  195059. png_ptr->mode |= PNG_AFTER_IDAT;
  195060. #ifdef PNG_MAX_MALLOC_64K
  195061. if (length > (png_uint_32)65535L)
  195062. {
  195063. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195064. skip = length - (png_uint_32)65535L;
  195065. length = (png_uint_32)65535L;
  195066. }
  195067. #endif
  195068. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195069. if (key == NULL)
  195070. {
  195071. png_warning(png_ptr, "No memory to process text chunk.");
  195072. return;
  195073. }
  195074. slength = (png_size_t)length;
  195075. png_crc_read(png_ptr, (png_bytep)key, slength);
  195076. if (png_crc_finish(png_ptr, skip))
  195077. {
  195078. png_free(png_ptr, key);
  195079. return;
  195080. }
  195081. key[slength] = 0x00;
  195082. for (text = key; *text; text++)
  195083. /* empty loop to find end of key */ ;
  195084. if (text != key + slength)
  195085. text++;
  195086. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195087. (png_uint_32)png_sizeof(png_text));
  195088. if (text_ptr == NULL)
  195089. {
  195090. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195091. png_free(png_ptr, key);
  195092. return;
  195093. }
  195094. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195095. text_ptr->key = key;
  195096. #ifdef PNG_iTXt_SUPPORTED
  195097. text_ptr->lang = NULL;
  195098. text_ptr->lang_key = NULL;
  195099. text_ptr->itxt_length = 0;
  195100. #endif
  195101. text_ptr->text = text;
  195102. text_ptr->text_length = png_strlen(text);
  195103. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195104. png_free(png_ptr, key);
  195105. png_free(png_ptr, text_ptr);
  195106. if (ret)
  195107. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195108. }
  195109. #endif
  195110. #if defined(PNG_READ_zTXt_SUPPORTED)
  195111. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195112. void /* PRIVATE */
  195113. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195114. {
  195115. png_textp text_ptr;
  195116. png_charp chunkdata;
  195117. png_charp text;
  195118. int comp_type;
  195119. int ret;
  195120. png_size_t slength, prefix_len, data_len;
  195121. png_debug(1, "in png_handle_zTXt\n");
  195122. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195123. png_error(png_ptr, "Missing IHDR before zTXt");
  195124. if (png_ptr->mode & PNG_HAVE_IDAT)
  195125. png_ptr->mode |= PNG_AFTER_IDAT;
  195126. #ifdef PNG_MAX_MALLOC_64K
  195127. /* We will no doubt have problems with chunks even half this size, but
  195128. there is no hard and fast rule to tell us where to stop. */
  195129. if (length > (png_uint_32)65535L)
  195130. {
  195131. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195132. png_crc_finish(png_ptr, length);
  195133. return;
  195134. }
  195135. #endif
  195136. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195137. if (chunkdata == NULL)
  195138. {
  195139. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195140. return;
  195141. }
  195142. slength = (png_size_t)length;
  195143. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195144. if (png_crc_finish(png_ptr, 0))
  195145. {
  195146. png_free(png_ptr, chunkdata);
  195147. return;
  195148. }
  195149. chunkdata[slength] = 0x00;
  195150. for (text = chunkdata; *text; text++)
  195151. /* empty loop */ ;
  195152. /* zTXt must have some text after the chunkdataword */
  195153. if (text >= chunkdata + slength - 2)
  195154. {
  195155. png_warning(png_ptr, "Truncated zTXt chunk");
  195156. png_free(png_ptr, chunkdata);
  195157. return;
  195158. }
  195159. else
  195160. {
  195161. comp_type = *(++text);
  195162. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195163. {
  195164. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195165. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195166. }
  195167. text++; /* skip the compression_method byte */
  195168. }
  195169. prefix_len = text - chunkdata;
  195170. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195171. (png_size_t)length, prefix_len, &data_len);
  195172. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195173. (png_uint_32)png_sizeof(png_text));
  195174. if (text_ptr == NULL)
  195175. {
  195176. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195177. png_free(png_ptr, chunkdata);
  195178. return;
  195179. }
  195180. text_ptr->compression = comp_type;
  195181. text_ptr->key = chunkdata;
  195182. #ifdef PNG_iTXt_SUPPORTED
  195183. text_ptr->lang = NULL;
  195184. text_ptr->lang_key = NULL;
  195185. text_ptr->itxt_length = 0;
  195186. #endif
  195187. text_ptr->text = chunkdata + prefix_len;
  195188. text_ptr->text_length = data_len;
  195189. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195190. png_free(png_ptr, text_ptr);
  195191. png_free(png_ptr, chunkdata);
  195192. if (ret)
  195193. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195194. }
  195195. #endif
  195196. #if defined(PNG_READ_iTXt_SUPPORTED)
  195197. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195198. void /* PRIVATE */
  195199. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195200. {
  195201. png_textp text_ptr;
  195202. png_charp chunkdata;
  195203. png_charp key, lang, text, lang_key;
  195204. int comp_flag;
  195205. int comp_type = 0;
  195206. int ret;
  195207. png_size_t slength, prefix_len, data_len;
  195208. png_debug(1, "in png_handle_iTXt\n");
  195209. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195210. png_error(png_ptr, "Missing IHDR before iTXt");
  195211. if (png_ptr->mode & PNG_HAVE_IDAT)
  195212. png_ptr->mode |= PNG_AFTER_IDAT;
  195213. #ifdef PNG_MAX_MALLOC_64K
  195214. /* We will no doubt have problems with chunks even half this size, but
  195215. there is no hard and fast rule to tell us where to stop. */
  195216. if (length > (png_uint_32)65535L)
  195217. {
  195218. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195219. png_crc_finish(png_ptr, length);
  195220. return;
  195221. }
  195222. #endif
  195223. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195224. if (chunkdata == NULL)
  195225. {
  195226. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195227. return;
  195228. }
  195229. slength = (png_size_t)length;
  195230. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195231. if (png_crc_finish(png_ptr, 0))
  195232. {
  195233. png_free(png_ptr, chunkdata);
  195234. return;
  195235. }
  195236. chunkdata[slength] = 0x00;
  195237. for (lang = chunkdata; *lang; lang++)
  195238. /* empty loop */ ;
  195239. lang++; /* skip NUL separator */
  195240. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195241. translated keyword (possibly empty), and possibly some text after the
  195242. keyword */
  195243. if (lang >= chunkdata + slength - 3)
  195244. {
  195245. png_warning(png_ptr, "Truncated iTXt chunk");
  195246. png_free(png_ptr, chunkdata);
  195247. return;
  195248. }
  195249. else
  195250. {
  195251. comp_flag = *lang++;
  195252. comp_type = *lang++;
  195253. }
  195254. for (lang_key = lang; *lang_key; lang_key++)
  195255. /* empty loop */ ;
  195256. lang_key++; /* skip NUL separator */
  195257. if (lang_key >= chunkdata + slength)
  195258. {
  195259. png_warning(png_ptr, "Truncated iTXt chunk");
  195260. png_free(png_ptr, chunkdata);
  195261. return;
  195262. }
  195263. for (text = lang_key; *text; text++)
  195264. /* empty loop */ ;
  195265. text++; /* skip NUL separator */
  195266. if (text >= chunkdata + slength)
  195267. {
  195268. png_warning(png_ptr, "Malformed iTXt chunk");
  195269. png_free(png_ptr, chunkdata);
  195270. return;
  195271. }
  195272. prefix_len = text - chunkdata;
  195273. key=chunkdata;
  195274. if (comp_flag)
  195275. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195276. (size_t)length, prefix_len, &data_len);
  195277. else
  195278. data_len=png_strlen(chunkdata + prefix_len);
  195279. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195280. (png_uint_32)png_sizeof(png_text));
  195281. if (text_ptr == NULL)
  195282. {
  195283. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  195284. png_free(png_ptr, chunkdata);
  195285. return;
  195286. }
  195287. text_ptr->compression = (int)comp_flag + 1;
  195288. text_ptr->lang_key = chunkdata+(lang_key-key);
  195289. text_ptr->lang = chunkdata+(lang-key);
  195290. text_ptr->itxt_length = data_len;
  195291. text_ptr->text_length = 0;
  195292. text_ptr->key = chunkdata;
  195293. text_ptr->text = chunkdata + prefix_len;
  195294. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195295. png_free(png_ptr, text_ptr);
  195296. png_free(png_ptr, chunkdata);
  195297. if (ret)
  195298. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  195299. }
  195300. #endif
  195301. /* This function is called when we haven't found a handler for a
  195302. chunk. If there isn't a problem with the chunk itself (ie bad
  195303. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  195304. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195305. case it will be saved away to be written out later. */
  195306. void /* PRIVATE */
  195307. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195308. {
  195309. png_uint_32 skip = 0;
  195310. png_debug(1, "in png_handle_unknown\n");
  195311. if (png_ptr->mode & PNG_HAVE_IDAT)
  195312. {
  195313. #ifdef PNG_USE_LOCAL_ARRAYS
  195314. PNG_CONST PNG_IDAT;
  195315. #endif
  195316. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195317. png_ptr->mode |= PNG_AFTER_IDAT;
  195318. }
  195319. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195320. if (!(png_ptr->chunk_name[0] & 0x20))
  195321. {
  195322. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195323. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195324. PNG_HANDLE_CHUNK_ALWAYS
  195325. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195326. && png_ptr->read_user_chunk_fn == NULL
  195327. #endif
  195328. )
  195329. #endif
  195330. png_chunk_error(png_ptr, "unknown critical chunk");
  195331. }
  195332. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195333. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195334. (png_ptr->read_user_chunk_fn != NULL))
  195335. {
  195336. #ifdef PNG_MAX_MALLOC_64K
  195337. if (length > (png_uint_32)65535L)
  195338. {
  195339. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195340. skip = length - (png_uint_32)65535L;
  195341. length = (png_uint_32)65535L;
  195342. }
  195343. #endif
  195344. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195345. (png_charp)png_ptr->chunk_name, 5);
  195346. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195347. png_ptr->unknown_chunk.size = (png_size_t)length;
  195348. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195349. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195350. if(png_ptr->read_user_chunk_fn != NULL)
  195351. {
  195352. /* callback to user unknown chunk handler */
  195353. int ret;
  195354. ret = (*(png_ptr->read_user_chunk_fn))
  195355. (png_ptr, &png_ptr->unknown_chunk);
  195356. if (ret < 0)
  195357. png_chunk_error(png_ptr, "error in user chunk");
  195358. if (ret == 0)
  195359. {
  195360. if (!(png_ptr->chunk_name[0] & 0x20))
  195361. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195362. PNG_HANDLE_CHUNK_ALWAYS)
  195363. png_chunk_error(png_ptr, "unknown critical chunk");
  195364. png_set_unknown_chunks(png_ptr, info_ptr,
  195365. &png_ptr->unknown_chunk, 1);
  195366. }
  195367. }
  195368. #else
  195369. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195370. #endif
  195371. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195372. png_ptr->unknown_chunk.data = NULL;
  195373. }
  195374. else
  195375. #endif
  195376. skip = length;
  195377. png_crc_finish(png_ptr, skip);
  195378. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195379. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  195380. #endif
  195381. }
  195382. /* This function is called to verify that a chunk name is valid.
  195383. This function can't have the "critical chunk check" incorporated
  195384. into it, since in the future we will need to be able to call user
  195385. functions to handle unknown critical chunks after we check that
  195386. the chunk name itself is valid. */
  195387. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  195388. void /* PRIVATE */
  195389. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  195390. {
  195391. png_debug(1, "in png_check_chunk_name\n");
  195392. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  195393. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  195394. {
  195395. png_chunk_error(png_ptr, "invalid chunk type");
  195396. }
  195397. }
  195398. /* Combines the row recently read in with the existing pixels in the
  195399. row. This routine takes care of alpha and transparency if requested.
  195400. This routine also handles the two methods of progressive display
  195401. of interlaced images, depending on the mask value.
  195402. The mask value describes which pixels are to be combined with
  195403. the row. The pattern always repeats every 8 pixels, so just 8
  195404. bits are needed. A one indicates the pixel is to be combined,
  195405. a zero indicates the pixel is to be skipped. This is in addition
  195406. to any alpha or transparency value associated with the pixel. If
  195407. you want all pixels to be combined, pass 0xff (255) in mask. */
  195408. void /* PRIVATE */
  195409. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  195410. {
  195411. png_debug(1,"in png_combine_row\n");
  195412. if (mask == 0xff)
  195413. {
  195414. png_memcpy(row, png_ptr->row_buf + 1,
  195415. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  195416. }
  195417. else
  195418. {
  195419. switch (png_ptr->row_info.pixel_depth)
  195420. {
  195421. case 1:
  195422. {
  195423. png_bytep sp = png_ptr->row_buf + 1;
  195424. png_bytep dp = row;
  195425. int s_inc, s_start, s_end;
  195426. int m = 0x80;
  195427. int shift;
  195428. png_uint_32 i;
  195429. png_uint_32 row_width = png_ptr->width;
  195430. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195431. if (png_ptr->transformations & PNG_PACKSWAP)
  195432. {
  195433. s_start = 0;
  195434. s_end = 7;
  195435. s_inc = 1;
  195436. }
  195437. else
  195438. #endif
  195439. {
  195440. s_start = 7;
  195441. s_end = 0;
  195442. s_inc = -1;
  195443. }
  195444. shift = s_start;
  195445. for (i = 0; i < row_width; i++)
  195446. {
  195447. if (m & mask)
  195448. {
  195449. int value;
  195450. value = (*sp >> shift) & 0x01;
  195451. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  195452. *dp |= (png_byte)(value << shift);
  195453. }
  195454. if (shift == s_end)
  195455. {
  195456. shift = s_start;
  195457. sp++;
  195458. dp++;
  195459. }
  195460. else
  195461. shift += s_inc;
  195462. if (m == 1)
  195463. m = 0x80;
  195464. else
  195465. m >>= 1;
  195466. }
  195467. break;
  195468. }
  195469. case 2:
  195470. {
  195471. png_bytep sp = png_ptr->row_buf + 1;
  195472. png_bytep dp = row;
  195473. int s_start, s_end, s_inc;
  195474. int m = 0x80;
  195475. int shift;
  195476. png_uint_32 i;
  195477. png_uint_32 row_width = png_ptr->width;
  195478. int value;
  195479. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195480. if (png_ptr->transformations & PNG_PACKSWAP)
  195481. {
  195482. s_start = 0;
  195483. s_end = 6;
  195484. s_inc = 2;
  195485. }
  195486. else
  195487. #endif
  195488. {
  195489. s_start = 6;
  195490. s_end = 0;
  195491. s_inc = -2;
  195492. }
  195493. shift = s_start;
  195494. for (i = 0; i < row_width; i++)
  195495. {
  195496. if (m & mask)
  195497. {
  195498. value = (*sp >> shift) & 0x03;
  195499. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  195500. *dp |= (png_byte)(value << shift);
  195501. }
  195502. if (shift == s_end)
  195503. {
  195504. shift = s_start;
  195505. sp++;
  195506. dp++;
  195507. }
  195508. else
  195509. shift += s_inc;
  195510. if (m == 1)
  195511. m = 0x80;
  195512. else
  195513. m >>= 1;
  195514. }
  195515. break;
  195516. }
  195517. case 4:
  195518. {
  195519. png_bytep sp = png_ptr->row_buf + 1;
  195520. png_bytep dp = row;
  195521. int s_start, s_end, s_inc;
  195522. int m = 0x80;
  195523. int shift;
  195524. png_uint_32 i;
  195525. png_uint_32 row_width = png_ptr->width;
  195526. int value;
  195527. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195528. if (png_ptr->transformations & PNG_PACKSWAP)
  195529. {
  195530. s_start = 0;
  195531. s_end = 4;
  195532. s_inc = 4;
  195533. }
  195534. else
  195535. #endif
  195536. {
  195537. s_start = 4;
  195538. s_end = 0;
  195539. s_inc = -4;
  195540. }
  195541. shift = s_start;
  195542. for (i = 0; i < row_width; i++)
  195543. {
  195544. if (m & mask)
  195545. {
  195546. value = (*sp >> shift) & 0xf;
  195547. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  195548. *dp |= (png_byte)(value << shift);
  195549. }
  195550. if (shift == s_end)
  195551. {
  195552. shift = s_start;
  195553. sp++;
  195554. dp++;
  195555. }
  195556. else
  195557. shift += s_inc;
  195558. if (m == 1)
  195559. m = 0x80;
  195560. else
  195561. m >>= 1;
  195562. }
  195563. break;
  195564. }
  195565. default:
  195566. {
  195567. png_bytep sp = png_ptr->row_buf + 1;
  195568. png_bytep dp = row;
  195569. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  195570. png_uint_32 i;
  195571. png_uint_32 row_width = png_ptr->width;
  195572. png_byte m = 0x80;
  195573. for (i = 0; i < row_width; i++)
  195574. {
  195575. if (m & mask)
  195576. {
  195577. png_memcpy(dp, sp, pixel_bytes);
  195578. }
  195579. sp += pixel_bytes;
  195580. dp += pixel_bytes;
  195581. if (m == 1)
  195582. m = 0x80;
  195583. else
  195584. m >>= 1;
  195585. }
  195586. break;
  195587. }
  195588. }
  195589. }
  195590. }
  195591. #ifdef PNG_READ_INTERLACING_SUPPORTED
  195592. /* OLD pre-1.0.9 interface:
  195593. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  195594. png_uint_32 transformations)
  195595. */
  195596. void /* PRIVATE */
  195597. png_do_read_interlace(png_structp png_ptr)
  195598. {
  195599. png_row_infop row_info = &(png_ptr->row_info);
  195600. png_bytep row = png_ptr->row_buf + 1;
  195601. int pass = png_ptr->pass;
  195602. png_uint_32 transformations = png_ptr->transformations;
  195603. #ifdef PNG_USE_LOCAL_ARRAYS
  195604. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195605. /* offset to next interlace block */
  195606. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195607. #endif
  195608. png_debug(1,"in png_do_read_interlace\n");
  195609. if (row != NULL && row_info != NULL)
  195610. {
  195611. png_uint_32 final_width;
  195612. final_width = row_info->width * png_pass_inc[pass];
  195613. switch (row_info->pixel_depth)
  195614. {
  195615. case 1:
  195616. {
  195617. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  195618. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  195619. int sshift, dshift;
  195620. int s_start, s_end, s_inc;
  195621. int jstop = png_pass_inc[pass];
  195622. png_byte v;
  195623. png_uint_32 i;
  195624. int j;
  195625. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195626. if (transformations & PNG_PACKSWAP)
  195627. {
  195628. sshift = (int)((row_info->width + 7) & 0x07);
  195629. dshift = (int)((final_width + 7) & 0x07);
  195630. s_start = 7;
  195631. s_end = 0;
  195632. s_inc = -1;
  195633. }
  195634. else
  195635. #endif
  195636. {
  195637. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  195638. dshift = 7 - (int)((final_width + 7) & 0x07);
  195639. s_start = 0;
  195640. s_end = 7;
  195641. s_inc = 1;
  195642. }
  195643. for (i = 0; i < row_info->width; i++)
  195644. {
  195645. v = (png_byte)((*sp >> sshift) & 0x01);
  195646. for (j = 0; j < jstop; j++)
  195647. {
  195648. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  195649. *dp |= (png_byte)(v << dshift);
  195650. if (dshift == s_end)
  195651. {
  195652. dshift = s_start;
  195653. dp--;
  195654. }
  195655. else
  195656. dshift += s_inc;
  195657. }
  195658. if (sshift == s_end)
  195659. {
  195660. sshift = s_start;
  195661. sp--;
  195662. }
  195663. else
  195664. sshift += s_inc;
  195665. }
  195666. break;
  195667. }
  195668. case 2:
  195669. {
  195670. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  195671. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  195672. int sshift, dshift;
  195673. int s_start, s_end, s_inc;
  195674. int jstop = png_pass_inc[pass];
  195675. png_uint_32 i;
  195676. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195677. if (transformations & PNG_PACKSWAP)
  195678. {
  195679. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  195680. dshift = (int)(((final_width + 3) & 0x03) << 1);
  195681. s_start = 6;
  195682. s_end = 0;
  195683. s_inc = -2;
  195684. }
  195685. else
  195686. #endif
  195687. {
  195688. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  195689. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  195690. s_start = 0;
  195691. s_end = 6;
  195692. s_inc = 2;
  195693. }
  195694. for (i = 0; i < row_info->width; i++)
  195695. {
  195696. png_byte v;
  195697. int j;
  195698. v = (png_byte)((*sp >> sshift) & 0x03);
  195699. for (j = 0; j < jstop; j++)
  195700. {
  195701. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  195702. *dp |= (png_byte)(v << dshift);
  195703. if (dshift == s_end)
  195704. {
  195705. dshift = s_start;
  195706. dp--;
  195707. }
  195708. else
  195709. dshift += s_inc;
  195710. }
  195711. if (sshift == s_end)
  195712. {
  195713. sshift = s_start;
  195714. sp--;
  195715. }
  195716. else
  195717. sshift += s_inc;
  195718. }
  195719. break;
  195720. }
  195721. case 4:
  195722. {
  195723. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  195724. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  195725. int sshift, dshift;
  195726. int s_start, s_end, s_inc;
  195727. png_uint_32 i;
  195728. int jstop = png_pass_inc[pass];
  195729. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195730. if (transformations & PNG_PACKSWAP)
  195731. {
  195732. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  195733. dshift = (int)(((final_width + 1) & 0x01) << 2);
  195734. s_start = 4;
  195735. s_end = 0;
  195736. s_inc = -4;
  195737. }
  195738. else
  195739. #endif
  195740. {
  195741. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  195742. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  195743. s_start = 0;
  195744. s_end = 4;
  195745. s_inc = 4;
  195746. }
  195747. for (i = 0; i < row_info->width; i++)
  195748. {
  195749. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  195750. int j;
  195751. for (j = 0; j < jstop; j++)
  195752. {
  195753. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  195754. *dp |= (png_byte)(v << dshift);
  195755. if (dshift == s_end)
  195756. {
  195757. dshift = s_start;
  195758. dp--;
  195759. }
  195760. else
  195761. dshift += s_inc;
  195762. }
  195763. if (sshift == s_end)
  195764. {
  195765. sshift = s_start;
  195766. sp--;
  195767. }
  195768. else
  195769. sshift += s_inc;
  195770. }
  195771. break;
  195772. }
  195773. default:
  195774. {
  195775. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  195776. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  195777. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  195778. int jstop = png_pass_inc[pass];
  195779. png_uint_32 i;
  195780. for (i = 0; i < row_info->width; i++)
  195781. {
  195782. png_byte v[8];
  195783. int j;
  195784. png_memcpy(v, sp, pixel_bytes);
  195785. for (j = 0; j < jstop; j++)
  195786. {
  195787. png_memcpy(dp, v, pixel_bytes);
  195788. dp -= pixel_bytes;
  195789. }
  195790. sp -= pixel_bytes;
  195791. }
  195792. break;
  195793. }
  195794. }
  195795. row_info->width = final_width;
  195796. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  195797. }
  195798. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  195799. transformations = transformations; /* silence compiler warning */
  195800. #endif
  195801. }
  195802. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  195803. void /* PRIVATE */
  195804. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  195805. png_bytep prev_row, int filter)
  195806. {
  195807. png_debug(1, "in png_read_filter_row\n");
  195808. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  195809. switch (filter)
  195810. {
  195811. case PNG_FILTER_VALUE_NONE:
  195812. break;
  195813. case PNG_FILTER_VALUE_SUB:
  195814. {
  195815. png_uint_32 i;
  195816. png_uint_32 istop = row_info->rowbytes;
  195817. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195818. png_bytep rp = row + bpp;
  195819. png_bytep lp = row;
  195820. for (i = bpp; i < istop; i++)
  195821. {
  195822. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  195823. rp++;
  195824. }
  195825. break;
  195826. }
  195827. case PNG_FILTER_VALUE_UP:
  195828. {
  195829. png_uint_32 i;
  195830. png_uint_32 istop = row_info->rowbytes;
  195831. png_bytep rp = row;
  195832. png_bytep pp = prev_row;
  195833. for (i = 0; i < istop; i++)
  195834. {
  195835. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  195836. rp++;
  195837. }
  195838. break;
  195839. }
  195840. case PNG_FILTER_VALUE_AVG:
  195841. {
  195842. png_uint_32 i;
  195843. png_bytep rp = row;
  195844. png_bytep pp = prev_row;
  195845. png_bytep lp = row;
  195846. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195847. png_uint_32 istop = row_info->rowbytes - bpp;
  195848. for (i = 0; i < bpp; i++)
  195849. {
  195850. *rp = (png_byte)(((int)(*rp) +
  195851. ((int)(*pp++) / 2 )) & 0xff);
  195852. rp++;
  195853. }
  195854. for (i = 0; i < istop; i++)
  195855. {
  195856. *rp = (png_byte)(((int)(*rp) +
  195857. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  195858. rp++;
  195859. }
  195860. break;
  195861. }
  195862. case PNG_FILTER_VALUE_PAETH:
  195863. {
  195864. png_uint_32 i;
  195865. png_bytep rp = row;
  195866. png_bytep pp = prev_row;
  195867. png_bytep lp = row;
  195868. png_bytep cp = prev_row;
  195869. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195870. png_uint_32 istop=row_info->rowbytes - bpp;
  195871. for (i = 0; i < bpp; i++)
  195872. {
  195873. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  195874. rp++;
  195875. }
  195876. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  195877. {
  195878. int a, b, c, pa, pb, pc, p;
  195879. a = *lp++;
  195880. b = *pp++;
  195881. c = *cp++;
  195882. p = b - c;
  195883. pc = a - c;
  195884. #ifdef PNG_USE_ABS
  195885. pa = abs(p);
  195886. pb = abs(pc);
  195887. pc = abs(p + pc);
  195888. #else
  195889. pa = p < 0 ? -p : p;
  195890. pb = pc < 0 ? -pc : pc;
  195891. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  195892. #endif
  195893. /*
  195894. if (pa <= pb && pa <= pc)
  195895. p = a;
  195896. else if (pb <= pc)
  195897. p = b;
  195898. else
  195899. p = c;
  195900. */
  195901. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  195902. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  195903. rp++;
  195904. }
  195905. break;
  195906. }
  195907. default:
  195908. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  195909. *row=0;
  195910. break;
  195911. }
  195912. }
  195913. void /* PRIVATE */
  195914. png_read_finish_row(png_structp png_ptr)
  195915. {
  195916. #ifdef PNG_USE_LOCAL_ARRAYS
  195917. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195918. /* start of interlace block */
  195919. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  195920. /* offset to next interlace block */
  195921. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195922. /* start of interlace block in the y direction */
  195923. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  195924. /* offset to next interlace block in the y direction */
  195925. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  195926. #endif
  195927. png_debug(1, "in png_read_finish_row\n");
  195928. png_ptr->row_number++;
  195929. if (png_ptr->row_number < png_ptr->num_rows)
  195930. return;
  195931. if (png_ptr->interlaced)
  195932. {
  195933. png_ptr->row_number = 0;
  195934. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  195935. png_ptr->rowbytes + 1);
  195936. do
  195937. {
  195938. png_ptr->pass++;
  195939. if (png_ptr->pass >= 7)
  195940. break;
  195941. png_ptr->iwidth = (png_ptr->width +
  195942. png_pass_inc[png_ptr->pass] - 1 -
  195943. png_pass_start[png_ptr->pass]) /
  195944. png_pass_inc[png_ptr->pass];
  195945. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  195946. png_ptr->iwidth) + 1;
  195947. if (!(png_ptr->transformations & PNG_INTERLACE))
  195948. {
  195949. png_ptr->num_rows = (png_ptr->height +
  195950. png_pass_yinc[png_ptr->pass] - 1 -
  195951. png_pass_ystart[png_ptr->pass]) /
  195952. png_pass_yinc[png_ptr->pass];
  195953. if (!(png_ptr->num_rows))
  195954. continue;
  195955. }
  195956. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  195957. break;
  195958. } while (png_ptr->iwidth == 0);
  195959. if (png_ptr->pass < 7)
  195960. return;
  195961. }
  195962. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  195963. {
  195964. #ifdef PNG_USE_LOCAL_ARRAYS
  195965. PNG_CONST PNG_IDAT;
  195966. #endif
  195967. char extra;
  195968. int ret;
  195969. png_ptr->zstream.next_out = (Bytef *)&extra;
  195970. png_ptr->zstream.avail_out = (uInt)1;
  195971. for(;;)
  195972. {
  195973. if (!(png_ptr->zstream.avail_in))
  195974. {
  195975. while (!png_ptr->idat_size)
  195976. {
  195977. png_byte chunk_length[4];
  195978. png_crc_finish(png_ptr, 0);
  195979. png_read_data(png_ptr, chunk_length, 4);
  195980. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  195981. png_reset_crc(png_ptr);
  195982. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  195983. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  195984. png_error(png_ptr, "Not enough image data");
  195985. }
  195986. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  195987. png_ptr->zstream.next_in = png_ptr->zbuf;
  195988. if (png_ptr->zbuf_size > png_ptr->idat_size)
  195989. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  195990. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  195991. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  195992. }
  195993. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  195994. if (ret == Z_STREAM_END)
  195995. {
  195996. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  195997. png_ptr->idat_size)
  195998. png_warning(png_ptr, "Extra compressed data");
  195999. png_ptr->mode |= PNG_AFTER_IDAT;
  196000. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196001. break;
  196002. }
  196003. if (ret != Z_OK)
  196004. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196005. "Decompression Error");
  196006. if (!(png_ptr->zstream.avail_out))
  196007. {
  196008. png_warning(png_ptr, "Extra compressed data.");
  196009. png_ptr->mode |= PNG_AFTER_IDAT;
  196010. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196011. break;
  196012. }
  196013. }
  196014. png_ptr->zstream.avail_out = 0;
  196015. }
  196016. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196017. png_warning(png_ptr, "Extra compression data");
  196018. inflateReset(&png_ptr->zstream);
  196019. png_ptr->mode |= PNG_AFTER_IDAT;
  196020. }
  196021. void /* PRIVATE */
  196022. png_read_start_row(png_structp png_ptr)
  196023. {
  196024. #ifdef PNG_USE_LOCAL_ARRAYS
  196025. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196026. /* start of interlace block */
  196027. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196028. /* offset to next interlace block */
  196029. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196030. /* start of interlace block in the y direction */
  196031. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196032. /* offset to next interlace block in the y direction */
  196033. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196034. #endif
  196035. int max_pixel_depth;
  196036. png_uint_32 row_bytes;
  196037. png_debug(1, "in png_read_start_row\n");
  196038. png_ptr->zstream.avail_in = 0;
  196039. png_init_read_transformations(png_ptr);
  196040. if (png_ptr->interlaced)
  196041. {
  196042. if (!(png_ptr->transformations & PNG_INTERLACE))
  196043. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196044. png_pass_ystart[0]) / png_pass_yinc[0];
  196045. else
  196046. png_ptr->num_rows = png_ptr->height;
  196047. png_ptr->iwidth = (png_ptr->width +
  196048. png_pass_inc[png_ptr->pass] - 1 -
  196049. png_pass_start[png_ptr->pass]) /
  196050. png_pass_inc[png_ptr->pass];
  196051. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196052. png_ptr->irowbytes = (png_size_t)row_bytes;
  196053. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196054. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196055. }
  196056. else
  196057. {
  196058. png_ptr->num_rows = png_ptr->height;
  196059. png_ptr->iwidth = png_ptr->width;
  196060. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196061. }
  196062. max_pixel_depth = png_ptr->pixel_depth;
  196063. #if defined(PNG_READ_PACK_SUPPORTED)
  196064. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196065. max_pixel_depth = 8;
  196066. #endif
  196067. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196068. if (png_ptr->transformations & PNG_EXPAND)
  196069. {
  196070. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196071. {
  196072. if (png_ptr->num_trans)
  196073. max_pixel_depth = 32;
  196074. else
  196075. max_pixel_depth = 24;
  196076. }
  196077. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196078. {
  196079. if (max_pixel_depth < 8)
  196080. max_pixel_depth = 8;
  196081. if (png_ptr->num_trans)
  196082. max_pixel_depth *= 2;
  196083. }
  196084. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196085. {
  196086. if (png_ptr->num_trans)
  196087. {
  196088. max_pixel_depth *= 4;
  196089. max_pixel_depth /= 3;
  196090. }
  196091. }
  196092. }
  196093. #endif
  196094. #if defined(PNG_READ_FILLER_SUPPORTED)
  196095. if (png_ptr->transformations & (PNG_FILLER))
  196096. {
  196097. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196098. max_pixel_depth = 32;
  196099. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196100. {
  196101. if (max_pixel_depth <= 8)
  196102. max_pixel_depth = 16;
  196103. else
  196104. max_pixel_depth = 32;
  196105. }
  196106. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196107. {
  196108. if (max_pixel_depth <= 32)
  196109. max_pixel_depth = 32;
  196110. else
  196111. max_pixel_depth = 64;
  196112. }
  196113. }
  196114. #endif
  196115. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196116. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196117. {
  196118. if (
  196119. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196120. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196121. #endif
  196122. #if defined(PNG_READ_FILLER_SUPPORTED)
  196123. (png_ptr->transformations & (PNG_FILLER)) ||
  196124. #endif
  196125. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196126. {
  196127. if (max_pixel_depth <= 16)
  196128. max_pixel_depth = 32;
  196129. else
  196130. max_pixel_depth = 64;
  196131. }
  196132. else
  196133. {
  196134. if (max_pixel_depth <= 8)
  196135. {
  196136. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196137. max_pixel_depth = 32;
  196138. else
  196139. max_pixel_depth = 24;
  196140. }
  196141. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196142. max_pixel_depth = 64;
  196143. else
  196144. max_pixel_depth = 48;
  196145. }
  196146. }
  196147. #endif
  196148. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196149. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196150. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196151. {
  196152. int user_pixel_depth=png_ptr->user_transform_depth*
  196153. png_ptr->user_transform_channels;
  196154. if(user_pixel_depth > max_pixel_depth)
  196155. max_pixel_depth=user_pixel_depth;
  196156. }
  196157. #endif
  196158. /* align the width on the next larger 8 pixels. Mainly used
  196159. for interlacing */
  196160. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196161. /* calculate the maximum bytes needed, adding a byte and a pixel
  196162. for safety's sake */
  196163. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196164. 1 + ((max_pixel_depth + 7) >> 3);
  196165. #ifdef PNG_MAX_MALLOC_64K
  196166. if (row_bytes > (png_uint_32)65536L)
  196167. png_error(png_ptr, "This image requires a row greater than 64KB");
  196168. #endif
  196169. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196170. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196171. #ifdef PNG_MAX_MALLOC_64K
  196172. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196173. png_error(png_ptr, "This image requires a row greater than 64KB");
  196174. #endif
  196175. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196176. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196177. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196178. png_ptr->rowbytes + 1));
  196179. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196180. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196181. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196182. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196183. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196184. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196185. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196186. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196187. }
  196188. #endif /* PNG_READ_SUPPORTED */
  196189. /*** End of inlined file: pngrutil.c ***/
  196190. /*** Start of inlined file: pngset.c ***/
  196191. /* pngset.c - storage of image information into info struct
  196192. *
  196193. * Last changed in libpng 1.2.21 [October 4, 2007]
  196194. * For conditions of distribution and use, see copyright notice in png.h
  196195. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196196. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196197. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196198. *
  196199. * The functions here are used during reads to store data from the file
  196200. * into the info struct, and during writes to store application data
  196201. * into the info struct for writing into the file. This abstracts the
  196202. * info struct and allows us to change the structure in the future.
  196203. */
  196204. #define PNG_INTERNAL
  196205. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196206. #if defined(PNG_bKGD_SUPPORTED)
  196207. void PNGAPI
  196208. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196209. {
  196210. png_debug1(1, "in %s storage function\n", "bKGD");
  196211. if (png_ptr == NULL || info_ptr == NULL)
  196212. return;
  196213. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196214. info_ptr->valid |= PNG_INFO_bKGD;
  196215. }
  196216. #endif
  196217. #if defined(PNG_cHRM_SUPPORTED)
  196218. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196219. void PNGAPI
  196220. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196221. double white_x, double white_y, double red_x, double red_y,
  196222. double green_x, double green_y, double blue_x, double blue_y)
  196223. {
  196224. png_debug1(1, "in %s storage function\n", "cHRM");
  196225. if (png_ptr == NULL || info_ptr == NULL)
  196226. return;
  196227. if (white_x < 0.0 || white_y < 0.0 ||
  196228. red_x < 0.0 || red_y < 0.0 ||
  196229. green_x < 0.0 || green_y < 0.0 ||
  196230. blue_x < 0.0 || blue_y < 0.0)
  196231. {
  196232. png_warning(png_ptr,
  196233. "Ignoring attempt to set negative chromaticity value");
  196234. return;
  196235. }
  196236. if (white_x > 21474.83 || white_y > 21474.83 ||
  196237. red_x > 21474.83 || red_y > 21474.83 ||
  196238. green_x > 21474.83 || green_y > 21474.83 ||
  196239. blue_x > 21474.83 || blue_y > 21474.83)
  196240. {
  196241. png_warning(png_ptr,
  196242. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196243. return;
  196244. }
  196245. info_ptr->x_white = (float)white_x;
  196246. info_ptr->y_white = (float)white_y;
  196247. info_ptr->x_red = (float)red_x;
  196248. info_ptr->y_red = (float)red_y;
  196249. info_ptr->x_green = (float)green_x;
  196250. info_ptr->y_green = (float)green_y;
  196251. info_ptr->x_blue = (float)blue_x;
  196252. info_ptr->y_blue = (float)blue_y;
  196253. #ifdef PNG_FIXED_POINT_SUPPORTED
  196254. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196255. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196256. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196257. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196258. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196259. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196260. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196261. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196262. #endif
  196263. info_ptr->valid |= PNG_INFO_cHRM;
  196264. }
  196265. #endif
  196266. #ifdef PNG_FIXED_POINT_SUPPORTED
  196267. void PNGAPI
  196268. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  196269. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  196270. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  196271. png_fixed_point blue_x, png_fixed_point blue_y)
  196272. {
  196273. png_debug1(1, "in %s storage function\n", "cHRM");
  196274. if (png_ptr == NULL || info_ptr == NULL)
  196275. return;
  196276. if (white_x < 0 || white_y < 0 ||
  196277. red_x < 0 || red_y < 0 ||
  196278. green_x < 0 || green_y < 0 ||
  196279. blue_x < 0 || blue_y < 0)
  196280. {
  196281. png_warning(png_ptr,
  196282. "Ignoring attempt to set negative chromaticity value");
  196283. return;
  196284. }
  196285. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196286. if (white_x > (double) PNG_UINT_31_MAX ||
  196287. white_y > (double) PNG_UINT_31_MAX ||
  196288. red_x > (double) PNG_UINT_31_MAX ||
  196289. red_y > (double) PNG_UINT_31_MAX ||
  196290. green_x > (double) PNG_UINT_31_MAX ||
  196291. green_y > (double) PNG_UINT_31_MAX ||
  196292. blue_x > (double) PNG_UINT_31_MAX ||
  196293. blue_y > (double) PNG_UINT_31_MAX)
  196294. #else
  196295. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196296. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196297. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196298. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196299. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196300. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196301. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196302. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  196303. #endif
  196304. {
  196305. png_warning(png_ptr,
  196306. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196307. return;
  196308. }
  196309. info_ptr->int_x_white = white_x;
  196310. info_ptr->int_y_white = white_y;
  196311. info_ptr->int_x_red = red_x;
  196312. info_ptr->int_y_red = red_y;
  196313. info_ptr->int_x_green = green_x;
  196314. info_ptr->int_y_green = green_y;
  196315. info_ptr->int_x_blue = blue_x;
  196316. info_ptr->int_y_blue = blue_y;
  196317. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196318. info_ptr->x_white = (float)(white_x/100000.);
  196319. info_ptr->y_white = (float)(white_y/100000.);
  196320. info_ptr->x_red = (float)( red_x/100000.);
  196321. info_ptr->y_red = (float)( red_y/100000.);
  196322. info_ptr->x_green = (float)(green_x/100000.);
  196323. info_ptr->y_green = (float)(green_y/100000.);
  196324. info_ptr->x_blue = (float)( blue_x/100000.);
  196325. info_ptr->y_blue = (float)( blue_y/100000.);
  196326. #endif
  196327. info_ptr->valid |= PNG_INFO_cHRM;
  196328. }
  196329. #endif
  196330. #endif
  196331. #if defined(PNG_gAMA_SUPPORTED)
  196332. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196333. void PNGAPI
  196334. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196335. {
  196336. double gamma;
  196337. png_debug1(1, "in %s storage function\n", "gAMA");
  196338. if (png_ptr == NULL || info_ptr == NULL)
  196339. return;
  196340. /* Check for overflow */
  196341. if (file_gamma > 21474.83)
  196342. {
  196343. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196344. gamma=21474.83;
  196345. }
  196346. else
  196347. gamma=file_gamma;
  196348. info_ptr->gamma = (float)gamma;
  196349. #ifdef PNG_FIXED_POINT_SUPPORTED
  196350. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196351. #endif
  196352. info_ptr->valid |= PNG_INFO_gAMA;
  196353. if(gamma == 0.0)
  196354. png_warning(png_ptr, "Setting gamma=0");
  196355. }
  196356. #endif
  196357. void PNGAPI
  196358. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196359. int_gamma)
  196360. {
  196361. png_fixed_point gamma;
  196362. png_debug1(1, "in %s storage function\n", "gAMA");
  196363. if (png_ptr == NULL || info_ptr == NULL)
  196364. return;
  196365. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196366. {
  196367. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196368. gamma=PNG_UINT_31_MAX;
  196369. }
  196370. else
  196371. {
  196372. if (int_gamma < 0)
  196373. {
  196374. png_warning(png_ptr, "Setting negative gamma to zero");
  196375. gamma=0;
  196376. }
  196377. else
  196378. gamma=int_gamma;
  196379. }
  196380. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196381. info_ptr->gamma = (float)(gamma/100000.);
  196382. #endif
  196383. #ifdef PNG_FIXED_POINT_SUPPORTED
  196384. info_ptr->int_gamma = gamma;
  196385. #endif
  196386. info_ptr->valid |= PNG_INFO_gAMA;
  196387. if(gamma == 0)
  196388. png_warning(png_ptr, "Setting gamma=0");
  196389. }
  196390. #endif
  196391. #if defined(PNG_hIST_SUPPORTED)
  196392. void PNGAPI
  196393. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  196394. {
  196395. int i;
  196396. png_debug1(1, "in %s storage function\n", "hIST");
  196397. if (png_ptr == NULL || info_ptr == NULL)
  196398. return;
  196399. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  196400. > PNG_MAX_PALETTE_LENGTH)
  196401. {
  196402. png_warning(png_ptr,
  196403. "Invalid palette size, hIST allocation skipped.");
  196404. return;
  196405. }
  196406. #ifdef PNG_FREE_ME_SUPPORTED
  196407. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  196408. #endif
  196409. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  196410. 1.2.1 */
  196411. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  196412. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  196413. if (png_ptr->hist == NULL)
  196414. {
  196415. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  196416. return;
  196417. }
  196418. for (i = 0; i < info_ptr->num_palette; i++)
  196419. png_ptr->hist[i] = hist[i];
  196420. info_ptr->hist = png_ptr->hist;
  196421. info_ptr->valid |= PNG_INFO_hIST;
  196422. #ifdef PNG_FREE_ME_SUPPORTED
  196423. info_ptr->free_me |= PNG_FREE_HIST;
  196424. #else
  196425. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  196426. #endif
  196427. }
  196428. #endif
  196429. void PNGAPI
  196430. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  196431. png_uint_32 width, png_uint_32 height, int bit_depth,
  196432. int color_type, int interlace_type, int compression_type,
  196433. int filter_type)
  196434. {
  196435. png_debug1(1, "in %s storage function\n", "IHDR");
  196436. if (png_ptr == NULL || info_ptr == NULL)
  196437. return;
  196438. /* check for width and height valid values */
  196439. if (width == 0 || height == 0)
  196440. png_error(png_ptr, "Image width or height is zero in IHDR");
  196441. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196442. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  196443. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196444. #else
  196445. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  196446. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196447. #endif
  196448. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  196449. png_error(png_ptr, "Invalid image size in IHDR");
  196450. if ( width > (PNG_UINT_32_MAX
  196451. >> 3) /* 8-byte RGBA pixels */
  196452. - 64 /* bigrowbuf hack */
  196453. - 1 /* filter byte */
  196454. - 7*8 /* rounding of width to multiple of 8 pixels */
  196455. - 8) /* extra max_pixel_depth pad */
  196456. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  196457. /* check other values */
  196458. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  196459. bit_depth != 8 && bit_depth != 16)
  196460. png_error(png_ptr, "Invalid bit depth in IHDR");
  196461. if (color_type < 0 || color_type == 1 ||
  196462. color_type == 5 || color_type > 6)
  196463. png_error(png_ptr, "Invalid color type in IHDR");
  196464. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  196465. ((color_type == PNG_COLOR_TYPE_RGB ||
  196466. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  196467. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  196468. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  196469. if (interlace_type >= PNG_INTERLACE_LAST)
  196470. png_error(png_ptr, "Unknown interlace method in IHDR");
  196471. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196472. png_error(png_ptr, "Unknown compression method in IHDR");
  196473. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196474. /* Accept filter_method 64 (intrapixel differencing) only if
  196475. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196476. * 2. Libpng did not read a PNG signature (this filter_method is only
  196477. * used in PNG datastreams that are embedded in MNG datastreams) and
  196478. * 3. The application called png_permit_mng_features with a mask that
  196479. * included PNG_FLAG_MNG_FILTER_64 and
  196480. * 4. The filter_method is 64 and
  196481. * 5. The color_type is RGB or RGBA
  196482. */
  196483. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  196484. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  196485. if(filter_type != PNG_FILTER_TYPE_BASE)
  196486. {
  196487. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196488. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  196489. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196490. (color_type == PNG_COLOR_TYPE_RGB ||
  196491. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  196492. png_error(png_ptr, "Unknown filter method in IHDR");
  196493. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  196494. png_warning(png_ptr, "Invalid filter method in IHDR");
  196495. }
  196496. #else
  196497. if(filter_type != PNG_FILTER_TYPE_BASE)
  196498. png_error(png_ptr, "Unknown filter method in IHDR");
  196499. #endif
  196500. info_ptr->width = width;
  196501. info_ptr->height = height;
  196502. info_ptr->bit_depth = (png_byte)bit_depth;
  196503. info_ptr->color_type =(png_byte) color_type;
  196504. info_ptr->compression_type = (png_byte)compression_type;
  196505. info_ptr->filter_type = (png_byte)filter_type;
  196506. info_ptr->interlace_type = (png_byte)interlace_type;
  196507. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196508. info_ptr->channels = 1;
  196509. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  196510. info_ptr->channels = 3;
  196511. else
  196512. info_ptr->channels = 1;
  196513. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  196514. info_ptr->channels++;
  196515. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  196516. /* check for potential overflow */
  196517. if (width > (PNG_UINT_32_MAX
  196518. >> 3) /* 8-byte RGBA pixels */
  196519. - 64 /* bigrowbuf hack */
  196520. - 1 /* filter byte */
  196521. - 7*8 /* rounding of width to multiple of 8 pixels */
  196522. - 8) /* extra max_pixel_depth pad */
  196523. info_ptr->rowbytes = (png_size_t)0;
  196524. else
  196525. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  196526. }
  196527. #if defined(PNG_oFFs_SUPPORTED)
  196528. void PNGAPI
  196529. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  196530. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  196531. {
  196532. png_debug1(1, "in %s storage function\n", "oFFs");
  196533. if (png_ptr == NULL || info_ptr == NULL)
  196534. return;
  196535. info_ptr->x_offset = offset_x;
  196536. info_ptr->y_offset = offset_y;
  196537. info_ptr->offset_unit_type = (png_byte)unit_type;
  196538. info_ptr->valid |= PNG_INFO_oFFs;
  196539. }
  196540. #endif
  196541. #if defined(PNG_pCAL_SUPPORTED)
  196542. void PNGAPI
  196543. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  196544. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  196545. png_charp units, png_charpp params)
  196546. {
  196547. png_uint_32 length;
  196548. int i;
  196549. png_debug1(1, "in %s storage function\n", "pCAL");
  196550. if (png_ptr == NULL || info_ptr == NULL)
  196551. return;
  196552. length = png_strlen(purpose) + 1;
  196553. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  196554. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  196555. if (info_ptr->pcal_purpose == NULL)
  196556. {
  196557. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  196558. return;
  196559. }
  196560. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  196561. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  196562. info_ptr->pcal_X0 = X0;
  196563. info_ptr->pcal_X1 = X1;
  196564. info_ptr->pcal_type = (png_byte)type;
  196565. info_ptr->pcal_nparams = (png_byte)nparams;
  196566. length = png_strlen(units) + 1;
  196567. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  196568. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  196569. if (info_ptr->pcal_units == NULL)
  196570. {
  196571. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  196572. return;
  196573. }
  196574. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  196575. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  196576. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  196577. if (info_ptr->pcal_params == NULL)
  196578. {
  196579. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  196580. return;
  196581. }
  196582. info_ptr->pcal_params[nparams] = NULL;
  196583. for (i = 0; i < nparams; i++)
  196584. {
  196585. length = png_strlen(params[i]) + 1;
  196586. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  196587. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  196588. if (info_ptr->pcal_params[i] == NULL)
  196589. {
  196590. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  196591. return;
  196592. }
  196593. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  196594. }
  196595. info_ptr->valid |= PNG_INFO_pCAL;
  196596. #ifdef PNG_FREE_ME_SUPPORTED
  196597. info_ptr->free_me |= PNG_FREE_PCAL;
  196598. #endif
  196599. }
  196600. #endif
  196601. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  196602. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196603. void PNGAPI
  196604. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  196605. int unit, double width, double height)
  196606. {
  196607. png_debug1(1, "in %s storage function\n", "sCAL");
  196608. if (png_ptr == NULL || info_ptr == NULL)
  196609. return;
  196610. info_ptr->scal_unit = (png_byte)unit;
  196611. info_ptr->scal_pixel_width = width;
  196612. info_ptr->scal_pixel_height = height;
  196613. info_ptr->valid |= PNG_INFO_sCAL;
  196614. }
  196615. #else
  196616. #ifdef PNG_FIXED_POINT_SUPPORTED
  196617. void PNGAPI
  196618. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  196619. int unit, png_charp swidth, png_charp sheight)
  196620. {
  196621. png_uint_32 length;
  196622. png_debug1(1, "in %s storage function\n", "sCAL");
  196623. if (png_ptr == NULL || info_ptr == NULL)
  196624. return;
  196625. info_ptr->scal_unit = (png_byte)unit;
  196626. length = png_strlen(swidth) + 1;
  196627. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196628. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  196629. if (info_ptr->scal_s_width == NULL)
  196630. {
  196631. png_warning(png_ptr,
  196632. "Memory allocation failed while processing sCAL.");
  196633. }
  196634. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  196635. length = png_strlen(sheight) + 1;
  196636. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196637. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  196638. if (info_ptr->scal_s_height == NULL)
  196639. {
  196640. png_free (png_ptr, info_ptr->scal_s_width);
  196641. png_warning(png_ptr,
  196642. "Memory allocation failed while processing sCAL.");
  196643. }
  196644. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  196645. info_ptr->valid |= PNG_INFO_sCAL;
  196646. #ifdef PNG_FREE_ME_SUPPORTED
  196647. info_ptr->free_me |= PNG_FREE_SCAL;
  196648. #endif
  196649. }
  196650. #endif
  196651. #endif
  196652. #endif
  196653. #if defined(PNG_pHYs_SUPPORTED)
  196654. void PNGAPI
  196655. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  196656. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  196657. {
  196658. png_debug1(1, "in %s storage function\n", "pHYs");
  196659. if (png_ptr == NULL || info_ptr == NULL)
  196660. return;
  196661. info_ptr->x_pixels_per_unit = res_x;
  196662. info_ptr->y_pixels_per_unit = res_y;
  196663. info_ptr->phys_unit_type = (png_byte)unit_type;
  196664. info_ptr->valid |= PNG_INFO_pHYs;
  196665. }
  196666. #endif
  196667. void PNGAPI
  196668. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  196669. png_colorp palette, int num_palette)
  196670. {
  196671. png_debug1(1, "in %s storage function\n", "PLTE");
  196672. if (png_ptr == NULL || info_ptr == NULL)
  196673. return;
  196674. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  196675. {
  196676. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196677. png_error(png_ptr, "Invalid palette length");
  196678. else
  196679. {
  196680. png_warning(png_ptr, "Invalid palette length");
  196681. return;
  196682. }
  196683. }
  196684. /*
  196685. * It may not actually be necessary to set png_ptr->palette here;
  196686. * we do it for backward compatibility with the way the png_handle_tRNS
  196687. * function used to do the allocation.
  196688. */
  196689. #ifdef PNG_FREE_ME_SUPPORTED
  196690. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  196691. #endif
  196692. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  196693. of num_palette entries,
  196694. in case of an invalid PNG file that has too-large sample values. */
  196695. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  196696. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  196697. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  196698. png_sizeof(png_color));
  196699. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  196700. info_ptr->palette = png_ptr->palette;
  196701. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  196702. #ifdef PNG_FREE_ME_SUPPORTED
  196703. info_ptr->free_me |= PNG_FREE_PLTE;
  196704. #else
  196705. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  196706. #endif
  196707. info_ptr->valid |= PNG_INFO_PLTE;
  196708. }
  196709. #if defined(PNG_sBIT_SUPPORTED)
  196710. void PNGAPI
  196711. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  196712. png_color_8p sig_bit)
  196713. {
  196714. png_debug1(1, "in %s storage function\n", "sBIT");
  196715. if (png_ptr == NULL || info_ptr == NULL)
  196716. return;
  196717. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  196718. info_ptr->valid |= PNG_INFO_sBIT;
  196719. }
  196720. #endif
  196721. #if defined(PNG_sRGB_SUPPORTED)
  196722. void PNGAPI
  196723. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  196724. {
  196725. png_debug1(1, "in %s storage function\n", "sRGB");
  196726. if (png_ptr == NULL || info_ptr == NULL)
  196727. return;
  196728. info_ptr->srgb_intent = (png_byte)intent;
  196729. info_ptr->valid |= PNG_INFO_sRGB;
  196730. }
  196731. void PNGAPI
  196732. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  196733. int intent)
  196734. {
  196735. #if defined(PNG_gAMA_SUPPORTED)
  196736. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196737. float file_gamma;
  196738. #endif
  196739. #ifdef PNG_FIXED_POINT_SUPPORTED
  196740. png_fixed_point int_file_gamma;
  196741. #endif
  196742. #endif
  196743. #if defined(PNG_cHRM_SUPPORTED)
  196744. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196745. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  196746. #endif
  196747. #ifdef PNG_FIXED_POINT_SUPPORTED
  196748. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  196749. int_green_y, int_blue_x, int_blue_y;
  196750. #endif
  196751. #endif
  196752. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  196753. if (png_ptr == NULL || info_ptr == NULL)
  196754. return;
  196755. png_set_sRGB(png_ptr, info_ptr, intent);
  196756. #if defined(PNG_gAMA_SUPPORTED)
  196757. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196758. file_gamma = (float).45455;
  196759. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  196760. #endif
  196761. #ifdef PNG_FIXED_POINT_SUPPORTED
  196762. int_file_gamma = 45455L;
  196763. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  196764. #endif
  196765. #endif
  196766. #if defined(PNG_cHRM_SUPPORTED)
  196767. #ifdef PNG_FIXED_POINT_SUPPORTED
  196768. int_white_x = 31270L;
  196769. int_white_y = 32900L;
  196770. int_red_x = 64000L;
  196771. int_red_y = 33000L;
  196772. int_green_x = 30000L;
  196773. int_green_y = 60000L;
  196774. int_blue_x = 15000L;
  196775. int_blue_y = 6000L;
  196776. png_set_cHRM_fixed(png_ptr, info_ptr,
  196777. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  196778. int_blue_x, int_blue_y);
  196779. #endif
  196780. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196781. white_x = (float).3127;
  196782. white_y = (float).3290;
  196783. red_x = (float).64;
  196784. red_y = (float).33;
  196785. green_x = (float).30;
  196786. green_y = (float).60;
  196787. blue_x = (float).15;
  196788. blue_y = (float).06;
  196789. png_set_cHRM(png_ptr, info_ptr,
  196790. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  196791. #endif
  196792. #endif
  196793. }
  196794. #endif
  196795. #if defined(PNG_iCCP_SUPPORTED)
  196796. void PNGAPI
  196797. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  196798. png_charp name, int compression_type,
  196799. png_charp profile, png_uint_32 proflen)
  196800. {
  196801. png_charp new_iccp_name;
  196802. png_charp new_iccp_profile;
  196803. png_debug1(1, "in %s storage function\n", "iCCP");
  196804. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  196805. return;
  196806. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  196807. if (new_iccp_name == NULL)
  196808. {
  196809. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  196810. return;
  196811. }
  196812. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  196813. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  196814. if (new_iccp_profile == NULL)
  196815. {
  196816. png_free (png_ptr, new_iccp_name);
  196817. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  196818. return;
  196819. }
  196820. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  196821. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  196822. info_ptr->iccp_proflen = proflen;
  196823. info_ptr->iccp_name = new_iccp_name;
  196824. info_ptr->iccp_profile = new_iccp_profile;
  196825. /* Compression is always zero but is here so the API and info structure
  196826. * does not have to change if we introduce multiple compression types */
  196827. info_ptr->iccp_compression = (png_byte)compression_type;
  196828. #ifdef PNG_FREE_ME_SUPPORTED
  196829. info_ptr->free_me |= PNG_FREE_ICCP;
  196830. #endif
  196831. info_ptr->valid |= PNG_INFO_iCCP;
  196832. }
  196833. #endif
  196834. #if defined(PNG_TEXT_SUPPORTED)
  196835. void PNGAPI
  196836. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  196837. int num_text)
  196838. {
  196839. int ret;
  196840. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  196841. if (ret)
  196842. png_error(png_ptr, "Insufficient memory to store text");
  196843. }
  196844. int /* PRIVATE */
  196845. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  196846. int num_text)
  196847. {
  196848. int i;
  196849. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  196850. "text" : (png_const_charp)png_ptr->chunk_name));
  196851. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  196852. return(0);
  196853. /* Make sure we have enough space in the "text" array in info_struct
  196854. * to hold all of the incoming text_ptr objects.
  196855. */
  196856. if (info_ptr->num_text + num_text > info_ptr->max_text)
  196857. {
  196858. if (info_ptr->text != NULL)
  196859. {
  196860. png_textp old_text;
  196861. int old_max;
  196862. old_max = info_ptr->max_text;
  196863. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  196864. old_text = info_ptr->text;
  196865. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  196866. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  196867. if (info_ptr->text == NULL)
  196868. {
  196869. png_free(png_ptr, old_text);
  196870. return(1);
  196871. }
  196872. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  196873. png_sizeof(png_text)));
  196874. png_free(png_ptr, old_text);
  196875. }
  196876. else
  196877. {
  196878. info_ptr->max_text = num_text + 8;
  196879. info_ptr->num_text = 0;
  196880. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  196881. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  196882. if (info_ptr->text == NULL)
  196883. return(1);
  196884. #ifdef PNG_FREE_ME_SUPPORTED
  196885. info_ptr->free_me |= PNG_FREE_TEXT;
  196886. #endif
  196887. }
  196888. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  196889. info_ptr->max_text);
  196890. }
  196891. for (i = 0; i < num_text; i++)
  196892. {
  196893. png_size_t text_length,key_len;
  196894. png_size_t lang_len,lang_key_len;
  196895. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  196896. if (text_ptr[i].key == NULL)
  196897. continue;
  196898. key_len = png_strlen(text_ptr[i].key);
  196899. if(text_ptr[i].compression <= 0)
  196900. {
  196901. lang_len = 0;
  196902. lang_key_len = 0;
  196903. }
  196904. else
  196905. #ifdef PNG_iTXt_SUPPORTED
  196906. {
  196907. /* set iTXt data */
  196908. if (text_ptr[i].lang != NULL)
  196909. lang_len = png_strlen(text_ptr[i].lang);
  196910. else
  196911. lang_len = 0;
  196912. if (text_ptr[i].lang_key != NULL)
  196913. lang_key_len = png_strlen(text_ptr[i].lang_key);
  196914. else
  196915. lang_key_len = 0;
  196916. }
  196917. #else
  196918. {
  196919. png_warning(png_ptr, "iTXt chunk not supported.");
  196920. continue;
  196921. }
  196922. #endif
  196923. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  196924. {
  196925. text_length = 0;
  196926. #ifdef PNG_iTXt_SUPPORTED
  196927. if(text_ptr[i].compression > 0)
  196928. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  196929. else
  196930. #endif
  196931. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  196932. }
  196933. else
  196934. {
  196935. text_length = png_strlen(text_ptr[i].text);
  196936. textp->compression = text_ptr[i].compression;
  196937. }
  196938. textp->key = (png_charp)png_malloc_warn(png_ptr,
  196939. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  196940. if (textp->key == NULL)
  196941. return(1);
  196942. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  196943. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  196944. (int)textp->key);
  196945. png_memcpy(textp->key, text_ptr[i].key,
  196946. (png_size_t)(key_len));
  196947. *(textp->key+key_len) = '\0';
  196948. #ifdef PNG_iTXt_SUPPORTED
  196949. if (text_ptr[i].compression > 0)
  196950. {
  196951. textp->lang=textp->key + key_len + 1;
  196952. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  196953. *(textp->lang+lang_len) = '\0';
  196954. textp->lang_key=textp->lang + lang_len + 1;
  196955. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  196956. *(textp->lang_key+lang_key_len) = '\0';
  196957. textp->text=textp->lang_key + lang_key_len + 1;
  196958. }
  196959. else
  196960. #endif
  196961. {
  196962. #ifdef PNG_iTXt_SUPPORTED
  196963. textp->lang=NULL;
  196964. textp->lang_key=NULL;
  196965. #endif
  196966. textp->text=textp->key + key_len + 1;
  196967. }
  196968. if(text_length)
  196969. png_memcpy(textp->text, text_ptr[i].text,
  196970. (png_size_t)(text_length));
  196971. *(textp->text+text_length) = '\0';
  196972. #ifdef PNG_iTXt_SUPPORTED
  196973. if(textp->compression > 0)
  196974. {
  196975. textp->text_length = 0;
  196976. textp->itxt_length = text_length;
  196977. }
  196978. else
  196979. #endif
  196980. {
  196981. textp->text_length = text_length;
  196982. #ifdef PNG_iTXt_SUPPORTED
  196983. textp->itxt_length = 0;
  196984. #endif
  196985. }
  196986. info_ptr->num_text++;
  196987. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  196988. }
  196989. return(0);
  196990. }
  196991. #endif
  196992. #if defined(PNG_tIME_SUPPORTED)
  196993. void PNGAPI
  196994. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  196995. {
  196996. png_debug1(1, "in %s storage function\n", "tIME");
  196997. if (png_ptr == NULL || info_ptr == NULL ||
  196998. (png_ptr->mode & PNG_WROTE_tIME))
  196999. return;
  197000. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197001. info_ptr->valid |= PNG_INFO_tIME;
  197002. }
  197003. #endif
  197004. #if defined(PNG_tRNS_SUPPORTED)
  197005. void PNGAPI
  197006. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197007. png_bytep trans, int num_trans, png_color_16p trans_values)
  197008. {
  197009. png_debug1(1, "in %s storage function\n", "tRNS");
  197010. if (png_ptr == NULL || info_ptr == NULL)
  197011. return;
  197012. if (trans != NULL)
  197013. {
  197014. /*
  197015. * It may not actually be necessary to set png_ptr->trans here;
  197016. * we do it for backward compatibility with the way the png_handle_tRNS
  197017. * function used to do the allocation.
  197018. */
  197019. #ifdef PNG_FREE_ME_SUPPORTED
  197020. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197021. #endif
  197022. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197023. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197024. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197025. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197026. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197027. #ifdef PNG_FREE_ME_SUPPORTED
  197028. info_ptr->free_me |= PNG_FREE_TRNS;
  197029. #else
  197030. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197031. #endif
  197032. }
  197033. if (trans_values != NULL)
  197034. {
  197035. png_memcpy(&(info_ptr->trans_values), trans_values,
  197036. png_sizeof(png_color_16));
  197037. if (num_trans == 0)
  197038. num_trans = 1;
  197039. }
  197040. info_ptr->num_trans = (png_uint_16)num_trans;
  197041. info_ptr->valid |= PNG_INFO_tRNS;
  197042. }
  197043. #endif
  197044. #if defined(PNG_sPLT_SUPPORTED)
  197045. void PNGAPI
  197046. png_set_sPLT(png_structp png_ptr,
  197047. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197048. {
  197049. png_sPLT_tp np;
  197050. int i;
  197051. if (png_ptr == NULL || info_ptr == NULL)
  197052. return;
  197053. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197054. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197055. if (np == NULL)
  197056. {
  197057. png_warning(png_ptr, "No memory for sPLT palettes.");
  197058. return;
  197059. }
  197060. png_memcpy(np, info_ptr->splt_palettes,
  197061. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197062. png_free(png_ptr, info_ptr->splt_palettes);
  197063. info_ptr->splt_palettes=NULL;
  197064. for (i = 0; i < nentries; i++)
  197065. {
  197066. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197067. png_sPLT_tp from = entries + i;
  197068. to->name = (png_charp)png_malloc_warn(png_ptr,
  197069. png_strlen(from->name) + 1);
  197070. if (to->name == NULL)
  197071. {
  197072. png_warning(png_ptr,
  197073. "Out of memory while processing sPLT chunk");
  197074. }
  197075. /* TODO: use png_malloc_warn */
  197076. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197077. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197078. from->nentries * png_sizeof(png_sPLT_entry));
  197079. /* TODO: use png_malloc_warn */
  197080. png_memcpy(to->entries, from->entries,
  197081. from->nentries * png_sizeof(png_sPLT_entry));
  197082. if (to->entries == NULL)
  197083. {
  197084. png_warning(png_ptr,
  197085. "Out of memory while processing sPLT chunk");
  197086. png_free(png_ptr,to->name);
  197087. to->name = NULL;
  197088. }
  197089. to->nentries = from->nentries;
  197090. to->depth = from->depth;
  197091. }
  197092. info_ptr->splt_palettes = np;
  197093. info_ptr->splt_palettes_num += nentries;
  197094. info_ptr->valid |= PNG_INFO_sPLT;
  197095. #ifdef PNG_FREE_ME_SUPPORTED
  197096. info_ptr->free_me |= PNG_FREE_SPLT;
  197097. #endif
  197098. }
  197099. #endif /* PNG_sPLT_SUPPORTED */
  197100. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197101. void PNGAPI
  197102. png_set_unknown_chunks(png_structp png_ptr,
  197103. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197104. {
  197105. png_unknown_chunkp np;
  197106. int i;
  197107. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197108. return;
  197109. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197110. (info_ptr->unknown_chunks_num + num_unknowns) *
  197111. png_sizeof(png_unknown_chunk));
  197112. if (np == NULL)
  197113. {
  197114. png_warning(png_ptr,
  197115. "Out of memory while processing unknown chunk.");
  197116. return;
  197117. }
  197118. png_memcpy(np, info_ptr->unknown_chunks,
  197119. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197120. png_free(png_ptr, info_ptr->unknown_chunks);
  197121. info_ptr->unknown_chunks=NULL;
  197122. for (i = 0; i < num_unknowns; i++)
  197123. {
  197124. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197125. png_unknown_chunkp from = unknowns + i;
  197126. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197127. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197128. if (to->data == NULL)
  197129. {
  197130. png_warning(png_ptr,
  197131. "Out of memory while processing unknown chunk.");
  197132. }
  197133. else
  197134. {
  197135. png_memcpy(to->data, from->data, from->size);
  197136. to->size = from->size;
  197137. /* note our location in the read or write sequence */
  197138. to->location = (png_byte)(png_ptr->mode & 0xff);
  197139. }
  197140. }
  197141. info_ptr->unknown_chunks = np;
  197142. info_ptr->unknown_chunks_num += num_unknowns;
  197143. #ifdef PNG_FREE_ME_SUPPORTED
  197144. info_ptr->free_me |= PNG_FREE_UNKN;
  197145. #endif
  197146. }
  197147. void PNGAPI
  197148. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197149. int chunk, int location)
  197150. {
  197151. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197152. (int)info_ptr->unknown_chunks_num)
  197153. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197154. }
  197155. #endif
  197156. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197157. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197158. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197159. void PNGAPI
  197160. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197161. {
  197162. /* This function is deprecated in favor of png_permit_mng_features()
  197163. and will be removed from libpng-1.3.0 */
  197164. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197165. if (png_ptr == NULL)
  197166. return;
  197167. png_ptr->mng_features_permitted = (png_byte)
  197168. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197169. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197170. }
  197171. #endif
  197172. #endif
  197173. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197174. png_uint_32 PNGAPI
  197175. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197176. {
  197177. png_debug(1, "in png_permit_mng_features\n");
  197178. if (png_ptr == NULL)
  197179. return (png_uint_32)0;
  197180. png_ptr->mng_features_permitted =
  197181. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197182. return (png_uint_32)png_ptr->mng_features_permitted;
  197183. }
  197184. #endif
  197185. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197186. void PNGAPI
  197187. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197188. chunk_list, int num_chunks)
  197189. {
  197190. png_bytep new_list, p;
  197191. int i, old_num_chunks;
  197192. if (png_ptr == NULL)
  197193. return;
  197194. if (num_chunks == 0)
  197195. {
  197196. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197197. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197198. else
  197199. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197200. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197201. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197202. else
  197203. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197204. return;
  197205. }
  197206. if (chunk_list == NULL)
  197207. return;
  197208. old_num_chunks=png_ptr->num_chunk_list;
  197209. new_list=(png_bytep)png_malloc(png_ptr,
  197210. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197211. if(png_ptr->chunk_list != NULL)
  197212. {
  197213. png_memcpy(new_list, png_ptr->chunk_list,
  197214. (png_size_t)(5*old_num_chunks));
  197215. png_free(png_ptr, png_ptr->chunk_list);
  197216. png_ptr->chunk_list=NULL;
  197217. }
  197218. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197219. (png_size_t)(5*num_chunks));
  197220. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197221. *p=(png_byte)keep;
  197222. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197223. png_ptr->chunk_list=new_list;
  197224. #ifdef PNG_FREE_ME_SUPPORTED
  197225. png_ptr->free_me |= PNG_FREE_LIST;
  197226. #endif
  197227. }
  197228. #endif
  197229. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197230. void PNGAPI
  197231. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197232. png_user_chunk_ptr read_user_chunk_fn)
  197233. {
  197234. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197235. if (png_ptr == NULL)
  197236. return;
  197237. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197238. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197239. }
  197240. #endif
  197241. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197242. void PNGAPI
  197243. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197244. {
  197245. png_debug1(1, "in %s storage function\n", "rows");
  197246. if (png_ptr == NULL || info_ptr == NULL)
  197247. return;
  197248. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197249. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197250. info_ptr->row_pointers = row_pointers;
  197251. if(row_pointers)
  197252. info_ptr->valid |= PNG_INFO_IDAT;
  197253. }
  197254. #endif
  197255. #ifdef PNG_WRITE_SUPPORTED
  197256. void PNGAPI
  197257. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197258. {
  197259. if (png_ptr == NULL)
  197260. return;
  197261. if(png_ptr->zbuf)
  197262. png_free(png_ptr, png_ptr->zbuf);
  197263. png_ptr->zbuf_size = (png_size_t)size;
  197264. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  197265. png_ptr->zstream.next_out = png_ptr->zbuf;
  197266. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197267. }
  197268. #endif
  197269. void PNGAPI
  197270. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  197271. {
  197272. if (png_ptr && info_ptr)
  197273. info_ptr->valid &= ~(mask);
  197274. }
  197275. #ifndef PNG_1_0_X
  197276. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  197277. /* function was added to libpng 1.2.0 and should always exist by default */
  197278. void PNGAPI
  197279. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  197280. {
  197281. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197282. if (png_ptr != NULL)
  197283. png_ptr->asm_flags = 0;
  197284. }
  197285. /* this function was added to libpng 1.2.0 */
  197286. void PNGAPI
  197287. png_set_mmx_thresholds (png_structp png_ptr,
  197288. png_byte,
  197289. png_uint_32)
  197290. {
  197291. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197292. if (png_ptr == NULL)
  197293. return;
  197294. }
  197295. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  197296. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197297. /* this function was added to libpng 1.2.6 */
  197298. void PNGAPI
  197299. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  197300. png_uint_32 user_height_max)
  197301. {
  197302. /* Images with dimensions larger than these limits will be
  197303. * rejected by png_set_IHDR(). To accept any PNG datastream
  197304. * regardless of dimensions, set both limits to 0x7ffffffL.
  197305. */
  197306. if(png_ptr == NULL) return;
  197307. png_ptr->user_width_max = user_width_max;
  197308. png_ptr->user_height_max = user_height_max;
  197309. }
  197310. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197311. #endif /* ?PNG_1_0_X */
  197312. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197313. /*** End of inlined file: pngset.c ***/
  197314. /*** Start of inlined file: pngtrans.c ***/
  197315. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197316. *
  197317. * Last changed in libpng 1.2.17 May 15, 2007
  197318. * For conditions of distribution and use, see copyright notice in png.h
  197319. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197320. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197321. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197322. */
  197323. #define PNG_INTERNAL
  197324. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197325. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197326. /* turn on BGR-to-RGB mapping */
  197327. void PNGAPI
  197328. png_set_bgr(png_structp png_ptr)
  197329. {
  197330. png_debug(1, "in png_set_bgr\n");
  197331. if(png_ptr == NULL) return;
  197332. png_ptr->transformations |= PNG_BGR;
  197333. }
  197334. #endif
  197335. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197336. /* turn on 16 bit byte swapping */
  197337. void PNGAPI
  197338. png_set_swap(png_structp png_ptr)
  197339. {
  197340. png_debug(1, "in png_set_swap\n");
  197341. if(png_ptr == NULL) return;
  197342. if (png_ptr->bit_depth == 16)
  197343. png_ptr->transformations |= PNG_SWAP_BYTES;
  197344. }
  197345. #endif
  197346. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197347. /* turn on pixel packing */
  197348. void PNGAPI
  197349. png_set_packing(png_structp png_ptr)
  197350. {
  197351. png_debug(1, "in png_set_packing\n");
  197352. if(png_ptr == NULL) return;
  197353. if (png_ptr->bit_depth < 8)
  197354. {
  197355. png_ptr->transformations |= PNG_PACK;
  197356. png_ptr->usr_bit_depth = 8;
  197357. }
  197358. }
  197359. #endif
  197360. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197361. /* turn on packed pixel swapping */
  197362. void PNGAPI
  197363. png_set_packswap(png_structp png_ptr)
  197364. {
  197365. png_debug(1, "in png_set_packswap\n");
  197366. if(png_ptr == NULL) return;
  197367. if (png_ptr->bit_depth < 8)
  197368. png_ptr->transformations |= PNG_PACKSWAP;
  197369. }
  197370. #endif
  197371. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197372. void PNGAPI
  197373. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197374. {
  197375. png_debug(1, "in png_set_shift\n");
  197376. if(png_ptr == NULL) return;
  197377. png_ptr->transformations |= PNG_SHIFT;
  197378. png_ptr->shift = *true_bits;
  197379. }
  197380. #endif
  197381. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  197382. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197383. int PNGAPI
  197384. png_set_interlace_handling(png_structp png_ptr)
  197385. {
  197386. png_debug(1, "in png_set_interlace handling\n");
  197387. if (png_ptr && png_ptr->interlaced)
  197388. {
  197389. png_ptr->transformations |= PNG_INTERLACE;
  197390. return (7);
  197391. }
  197392. return (1);
  197393. }
  197394. #endif
  197395. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  197396. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  197397. * The filler type has changed in v0.95 to allow future 2-byte fillers
  197398. * for 48-bit input data, as well as to avoid problems with some compilers
  197399. * that don't like bytes as parameters.
  197400. */
  197401. void PNGAPI
  197402. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197403. {
  197404. png_debug(1, "in png_set_filler\n");
  197405. if(png_ptr == NULL) return;
  197406. png_ptr->transformations |= PNG_FILLER;
  197407. png_ptr->filler = (png_byte)filler;
  197408. if (filler_loc == PNG_FILLER_AFTER)
  197409. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  197410. else
  197411. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  197412. /* This should probably go in the "do_read_filler" routine.
  197413. * I attempted to do that in libpng-1.0.1a but that caused problems
  197414. * so I restored it in libpng-1.0.2a
  197415. */
  197416. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197417. {
  197418. png_ptr->usr_channels = 4;
  197419. }
  197420. /* Also I added this in libpng-1.0.2a (what happens when we expand
  197421. * a less-than-8-bit grayscale to GA? */
  197422. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  197423. {
  197424. png_ptr->usr_channels = 2;
  197425. }
  197426. }
  197427. #if !defined(PNG_1_0_X)
  197428. /* Added to libpng-1.2.7 */
  197429. void PNGAPI
  197430. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197431. {
  197432. png_debug(1, "in png_set_add_alpha\n");
  197433. if(png_ptr == NULL) return;
  197434. png_set_filler(png_ptr, filler, filler_loc);
  197435. png_ptr->transformations |= PNG_ADD_ALPHA;
  197436. }
  197437. #endif
  197438. #endif
  197439. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  197440. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197441. void PNGAPI
  197442. png_set_swap_alpha(png_structp png_ptr)
  197443. {
  197444. png_debug(1, "in png_set_swap_alpha\n");
  197445. if(png_ptr == NULL) return;
  197446. png_ptr->transformations |= PNG_SWAP_ALPHA;
  197447. }
  197448. #endif
  197449. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  197450. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197451. void PNGAPI
  197452. png_set_invert_alpha(png_structp png_ptr)
  197453. {
  197454. png_debug(1, "in png_set_invert_alpha\n");
  197455. if(png_ptr == NULL) return;
  197456. png_ptr->transformations |= PNG_INVERT_ALPHA;
  197457. }
  197458. #endif
  197459. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  197460. void PNGAPI
  197461. png_set_invert_mono(png_structp png_ptr)
  197462. {
  197463. png_debug(1, "in png_set_invert_mono\n");
  197464. if(png_ptr == NULL) return;
  197465. png_ptr->transformations |= PNG_INVERT_MONO;
  197466. }
  197467. /* invert monochrome grayscale data */
  197468. void /* PRIVATE */
  197469. png_do_invert(png_row_infop row_info, png_bytep row)
  197470. {
  197471. png_debug(1, "in png_do_invert\n");
  197472. /* This test removed from libpng version 1.0.13 and 1.2.0:
  197473. * if (row_info->bit_depth == 1 &&
  197474. */
  197475. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197476. if (row == NULL || row_info == NULL)
  197477. return;
  197478. #endif
  197479. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  197480. {
  197481. png_bytep rp = row;
  197482. png_uint_32 i;
  197483. png_uint_32 istop = row_info->rowbytes;
  197484. for (i = 0; i < istop; i++)
  197485. {
  197486. *rp = (png_byte)(~(*rp));
  197487. rp++;
  197488. }
  197489. }
  197490. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197491. row_info->bit_depth == 8)
  197492. {
  197493. png_bytep rp = row;
  197494. png_uint_32 i;
  197495. png_uint_32 istop = row_info->rowbytes;
  197496. for (i = 0; i < istop; i+=2)
  197497. {
  197498. *rp = (png_byte)(~(*rp));
  197499. rp+=2;
  197500. }
  197501. }
  197502. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197503. row_info->bit_depth == 16)
  197504. {
  197505. png_bytep rp = row;
  197506. png_uint_32 i;
  197507. png_uint_32 istop = row_info->rowbytes;
  197508. for (i = 0; i < istop; i+=4)
  197509. {
  197510. *rp = (png_byte)(~(*rp));
  197511. *(rp+1) = (png_byte)(~(*(rp+1)));
  197512. rp+=4;
  197513. }
  197514. }
  197515. }
  197516. #endif
  197517. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197518. /* swaps byte order on 16 bit depth images */
  197519. void /* PRIVATE */
  197520. png_do_swap(png_row_infop row_info, png_bytep row)
  197521. {
  197522. png_debug(1, "in png_do_swap\n");
  197523. if (
  197524. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197525. row != NULL && row_info != NULL &&
  197526. #endif
  197527. row_info->bit_depth == 16)
  197528. {
  197529. png_bytep rp = row;
  197530. png_uint_32 i;
  197531. png_uint_32 istop= row_info->width * row_info->channels;
  197532. for (i = 0; i < istop; i++, rp += 2)
  197533. {
  197534. png_byte t = *rp;
  197535. *rp = *(rp + 1);
  197536. *(rp + 1) = t;
  197537. }
  197538. }
  197539. }
  197540. #endif
  197541. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197542. static PNG_CONST png_byte onebppswaptable[256] = {
  197543. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  197544. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  197545. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  197546. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  197547. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  197548. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  197549. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  197550. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  197551. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  197552. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  197553. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  197554. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  197555. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  197556. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  197557. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  197558. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  197559. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  197560. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  197561. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  197562. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  197563. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  197564. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  197565. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  197566. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  197567. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  197568. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  197569. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  197570. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  197571. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  197572. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  197573. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  197574. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  197575. };
  197576. static PNG_CONST png_byte twobppswaptable[256] = {
  197577. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  197578. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  197579. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  197580. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  197581. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  197582. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  197583. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  197584. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  197585. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  197586. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  197587. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  197588. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  197589. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  197590. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  197591. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  197592. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  197593. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  197594. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  197595. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  197596. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  197597. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  197598. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  197599. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  197600. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  197601. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  197602. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  197603. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  197604. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  197605. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  197606. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  197607. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  197608. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  197609. };
  197610. static PNG_CONST png_byte fourbppswaptable[256] = {
  197611. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  197612. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  197613. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  197614. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  197615. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  197616. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  197617. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  197618. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  197619. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  197620. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  197621. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  197622. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  197623. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  197624. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  197625. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  197626. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  197627. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  197628. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  197629. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  197630. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  197631. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  197632. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  197633. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  197634. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  197635. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  197636. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  197637. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  197638. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  197639. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  197640. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  197641. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  197642. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  197643. };
  197644. /* swaps pixel packing order within bytes */
  197645. void /* PRIVATE */
  197646. png_do_packswap(png_row_infop row_info, png_bytep row)
  197647. {
  197648. png_debug(1, "in png_do_packswap\n");
  197649. if (
  197650. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197651. row != NULL && row_info != NULL &&
  197652. #endif
  197653. row_info->bit_depth < 8)
  197654. {
  197655. png_bytep rp, end, table;
  197656. end = row + row_info->rowbytes;
  197657. if (row_info->bit_depth == 1)
  197658. table = (png_bytep)onebppswaptable;
  197659. else if (row_info->bit_depth == 2)
  197660. table = (png_bytep)twobppswaptable;
  197661. else if (row_info->bit_depth == 4)
  197662. table = (png_bytep)fourbppswaptable;
  197663. else
  197664. return;
  197665. for (rp = row; rp < end; rp++)
  197666. *rp = table[*rp];
  197667. }
  197668. }
  197669. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  197670. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  197671. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  197672. /* remove filler or alpha byte(s) */
  197673. void /* PRIVATE */
  197674. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  197675. {
  197676. png_debug(1, "in png_do_strip_filler\n");
  197677. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197678. if (row != NULL && row_info != NULL)
  197679. #endif
  197680. {
  197681. png_bytep sp=row;
  197682. png_bytep dp=row;
  197683. png_uint_32 row_width=row_info->width;
  197684. png_uint_32 i;
  197685. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  197686. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  197687. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197688. row_info->channels == 4)
  197689. {
  197690. if (row_info->bit_depth == 8)
  197691. {
  197692. /* This converts from RGBX or RGBA to RGB */
  197693. if (flags & PNG_FLAG_FILLER_AFTER)
  197694. {
  197695. dp+=3; sp+=4;
  197696. for (i = 1; i < row_width; i++)
  197697. {
  197698. *dp++ = *sp++;
  197699. *dp++ = *sp++;
  197700. *dp++ = *sp++;
  197701. sp++;
  197702. }
  197703. }
  197704. /* This converts from XRGB or ARGB to RGB */
  197705. else
  197706. {
  197707. for (i = 0; i < row_width; i++)
  197708. {
  197709. sp++;
  197710. *dp++ = *sp++;
  197711. *dp++ = *sp++;
  197712. *dp++ = *sp++;
  197713. }
  197714. }
  197715. row_info->pixel_depth = 24;
  197716. row_info->rowbytes = row_width * 3;
  197717. }
  197718. else /* if (row_info->bit_depth == 16) */
  197719. {
  197720. if (flags & PNG_FLAG_FILLER_AFTER)
  197721. {
  197722. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  197723. sp += 8; dp += 6;
  197724. for (i = 1; i < row_width; i++)
  197725. {
  197726. /* This could be (although png_memcpy is probably slower):
  197727. png_memcpy(dp, sp, 6);
  197728. sp += 8;
  197729. dp += 6;
  197730. */
  197731. *dp++ = *sp++;
  197732. *dp++ = *sp++;
  197733. *dp++ = *sp++;
  197734. *dp++ = *sp++;
  197735. *dp++ = *sp++;
  197736. *dp++ = *sp++;
  197737. sp += 2;
  197738. }
  197739. }
  197740. else
  197741. {
  197742. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  197743. for (i = 0; i < row_width; i++)
  197744. {
  197745. /* This could be (although png_memcpy is probably slower):
  197746. png_memcpy(dp, sp, 6);
  197747. sp += 8;
  197748. dp += 6;
  197749. */
  197750. sp+=2;
  197751. *dp++ = *sp++;
  197752. *dp++ = *sp++;
  197753. *dp++ = *sp++;
  197754. *dp++ = *sp++;
  197755. *dp++ = *sp++;
  197756. *dp++ = *sp++;
  197757. }
  197758. }
  197759. row_info->pixel_depth = 48;
  197760. row_info->rowbytes = row_width * 6;
  197761. }
  197762. row_info->channels = 3;
  197763. }
  197764. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  197765. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197766. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197767. row_info->channels == 2)
  197768. {
  197769. if (row_info->bit_depth == 8)
  197770. {
  197771. /* This converts from GX or GA to G */
  197772. if (flags & PNG_FLAG_FILLER_AFTER)
  197773. {
  197774. for (i = 0; i < row_width; i++)
  197775. {
  197776. *dp++ = *sp++;
  197777. sp++;
  197778. }
  197779. }
  197780. /* This converts from XG or AG to G */
  197781. else
  197782. {
  197783. for (i = 0; i < row_width; i++)
  197784. {
  197785. sp++;
  197786. *dp++ = *sp++;
  197787. }
  197788. }
  197789. row_info->pixel_depth = 8;
  197790. row_info->rowbytes = row_width;
  197791. }
  197792. else /* if (row_info->bit_depth == 16) */
  197793. {
  197794. if (flags & PNG_FLAG_FILLER_AFTER)
  197795. {
  197796. /* This converts from GGXX or GGAA to GG */
  197797. sp += 4; dp += 2;
  197798. for (i = 1; i < row_width; i++)
  197799. {
  197800. *dp++ = *sp++;
  197801. *dp++ = *sp++;
  197802. sp += 2;
  197803. }
  197804. }
  197805. else
  197806. {
  197807. /* This converts from XXGG or AAGG to GG */
  197808. for (i = 0; i < row_width; i++)
  197809. {
  197810. sp += 2;
  197811. *dp++ = *sp++;
  197812. *dp++ = *sp++;
  197813. }
  197814. }
  197815. row_info->pixel_depth = 16;
  197816. row_info->rowbytes = row_width * 2;
  197817. }
  197818. row_info->channels = 1;
  197819. }
  197820. if (flags & PNG_FLAG_STRIP_ALPHA)
  197821. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  197822. }
  197823. }
  197824. #endif
  197825. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197826. /* swaps red and blue bytes within a pixel */
  197827. void /* PRIVATE */
  197828. png_do_bgr(png_row_infop row_info, png_bytep row)
  197829. {
  197830. png_debug(1, "in png_do_bgr\n");
  197831. if (
  197832. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197833. row != NULL && row_info != NULL &&
  197834. #endif
  197835. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  197836. {
  197837. png_uint_32 row_width = row_info->width;
  197838. if (row_info->bit_depth == 8)
  197839. {
  197840. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197841. {
  197842. png_bytep rp;
  197843. png_uint_32 i;
  197844. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  197845. {
  197846. png_byte save = *rp;
  197847. *rp = *(rp + 2);
  197848. *(rp + 2) = save;
  197849. }
  197850. }
  197851. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197852. {
  197853. png_bytep rp;
  197854. png_uint_32 i;
  197855. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  197856. {
  197857. png_byte save = *rp;
  197858. *rp = *(rp + 2);
  197859. *(rp + 2) = save;
  197860. }
  197861. }
  197862. }
  197863. else if (row_info->bit_depth == 16)
  197864. {
  197865. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197866. {
  197867. png_bytep rp;
  197868. png_uint_32 i;
  197869. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  197870. {
  197871. png_byte save = *rp;
  197872. *rp = *(rp + 4);
  197873. *(rp + 4) = save;
  197874. save = *(rp + 1);
  197875. *(rp + 1) = *(rp + 5);
  197876. *(rp + 5) = save;
  197877. }
  197878. }
  197879. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197880. {
  197881. png_bytep rp;
  197882. png_uint_32 i;
  197883. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  197884. {
  197885. png_byte save = *rp;
  197886. *rp = *(rp + 4);
  197887. *(rp + 4) = save;
  197888. save = *(rp + 1);
  197889. *(rp + 1) = *(rp + 5);
  197890. *(rp + 5) = save;
  197891. }
  197892. }
  197893. }
  197894. }
  197895. }
  197896. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  197897. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  197898. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  197899. defined(PNG_LEGACY_SUPPORTED)
  197900. void PNGAPI
  197901. png_set_user_transform_info(png_structp png_ptr, png_voidp
  197902. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  197903. {
  197904. png_debug(1, "in png_set_user_transform_info\n");
  197905. if(png_ptr == NULL) return;
  197906. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  197907. png_ptr->user_transform_ptr = user_transform_ptr;
  197908. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  197909. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  197910. #else
  197911. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  197912. png_warning(png_ptr,
  197913. "This version of libpng does not support user transform info");
  197914. #endif
  197915. }
  197916. #endif
  197917. /* This function returns a pointer to the user_transform_ptr associated with
  197918. * the user transform functions. The application should free any memory
  197919. * associated with this pointer before png_write_destroy and png_read_destroy
  197920. * are called.
  197921. */
  197922. png_voidp PNGAPI
  197923. png_get_user_transform_ptr(png_structp png_ptr)
  197924. {
  197925. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  197926. if (png_ptr == NULL) return (NULL);
  197927. return ((png_voidp)png_ptr->user_transform_ptr);
  197928. #else
  197929. return (NULL);
  197930. #endif
  197931. }
  197932. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197933. /*** End of inlined file: pngtrans.c ***/
  197934. /*** Start of inlined file: pngwio.c ***/
  197935. /* pngwio.c - functions for data output
  197936. *
  197937. * Last changed in libpng 1.2.13 November 13, 2006
  197938. * For conditions of distribution and use, see copyright notice in png.h
  197939. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  197940. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197941. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197942. *
  197943. * This file provides a location for all output. Users who need
  197944. * special handling are expected to write functions that have the same
  197945. * arguments as these and perform similar functions, but that possibly
  197946. * use different output methods. Note that you shouldn't change these
  197947. * functions, but rather write replacement functions and then change
  197948. * them at run time with png_set_write_fn(...).
  197949. */
  197950. #define PNG_INTERNAL
  197951. #ifdef PNG_WRITE_SUPPORTED
  197952. /* Write the data to whatever output you are using. The default routine
  197953. writes to a file pointer. Note that this routine sometimes gets called
  197954. with very small lengths, so you should implement some kind of simple
  197955. buffering if you are using unbuffered writes. This should never be asked
  197956. to write more than 64K on a 16 bit machine. */
  197957. void /* PRIVATE */
  197958. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197959. {
  197960. if (png_ptr->write_data_fn != NULL )
  197961. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  197962. else
  197963. png_error(png_ptr, "Call to NULL write function");
  197964. }
  197965. #if !defined(PNG_NO_STDIO)
  197966. /* This is the function that does the actual writing of data. If you are
  197967. not writing to a standard C stream, you should create a replacement
  197968. write_data function and use it at run time with png_set_write_fn(), rather
  197969. than changing the library. */
  197970. #ifndef USE_FAR_KEYWORD
  197971. void PNGAPI
  197972. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197973. {
  197974. png_uint_32 check;
  197975. if(png_ptr == NULL) return;
  197976. #if defined(_WIN32_WCE)
  197977. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  197978. check = 0;
  197979. #else
  197980. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  197981. #endif
  197982. if (check != length)
  197983. png_error(png_ptr, "Write Error");
  197984. }
  197985. #else
  197986. /* this is the model-independent version. Since the standard I/O library
  197987. can't handle far buffers in the medium and small models, we have to copy
  197988. the data.
  197989. */
  197990. #define NEAR_BUF_SIZE 1024
  197991. #define MIN(a,b) (a <= b ? a : b)
  197992. void PNGAPI
  197993. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197994. {
  197995. png_uint_32 check;
  197996. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  197997. png_FILE_p io_ptr;
  197998. if(png_ptr == NULL) return;
  197999. /* Check if data really is near. If so, use usual code. */
  198000. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198001. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198002. if ((png_bytep)near_data == data)
  198003. {
  198004. #if defined(_WIN32_WCE)
  198005. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198006. check = 0;
  198007. #else
  198008. check = fwrite(near_data, 1, length, io_ptr);
  198009. #endif
  198010. }
  198011. else
  198012. {
  198013. png_byte buf[NEAR_BUF_SIZE];
  198014. png_size_t written, remaining, err;
  198015. check = 0;
  198016. remaining = length;
  198017. do
  198018. {
  198019. written = MIN(NEAR_BUF_SIZE, remaining);
  198020. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198021. #if defined(_WIN32_WCE)
  198022. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198023. err = 0;
  198024. #else
  198025. err = fwrite(buf, 1, written, io_ptr);
  198026. #endif
  198027. if (err != written)
  198028. break;
  198029. else
  198030. check += err;
  198031. data += written;
  198032. remaining -= written;
  198033. }
  198034. while (remaining != 0);
  198035. }
  198036. if (check != length)
  198037. png_error(png_ptr, "Write Error");
  198038. }
  198039. #endif
  198040. #endif
  198041. /* This function is called to output any data pending writing (normally
  198042. to disk). After png_flush is called, there should be no data pending
  198043. writing in any buffers. */
  198044. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198045. void /* PRIVATE */
  198046. png_flush(png_structp png_ptr)
  198047. {
  198048. if (png_ptr->output_flush_fn != NULL)
  198049. (*(png_ptr->output_flush_fn))(png_ptr);
  198050. }
  198051. #if !defined(PNG_NO_STDIO)
  198052. void PNGAPI
  198053. png_default_flush(png_structp png_ptr)
  198054. {
  198055. #if !defined(_WIN32_WCE)
  198056. png_FILE_p io_ptr;
  198057. #endif
  198058. if(png_ptr == NULL) return;
  198059. #if !defined(_WIN32_WCE)
  198060. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198061. if (io_ptr != NULL)
  198062. fflush(io_ptr);
  198063. #endif
  198064. }
  198065. #endif
  198066. #endif
  198067. /* This function allows the application to supply new output functions for
  198068. libpng if standard C streams aren't being used.
  198069. This function takes as its arguments:
  198070. png_ptr - pointer to a png output data structure
  198071. io_ptr - pointer to user supplied structure containing info about
  198072. the output functions. May be NULL.
  198073. write_data_fn - pointer to a new output function that takes as its
  198074. arguments a pointer to a png_struct, a pointer to
  198075. data to be written, and a 32-bit unsigned int that is
  198076. the number of bytes to be written. The new write
  198077. function should call png_error(png_ptr, "Error msg")
  198078. to exit and output any fatal error messages.
  198079. flush_data_fn - pointer to a new flush function that takes as its
  198080. arguments a pointer to a png_struct. After a call to
  198081. the flush function, there should be no data in any buffers
  198082. or pending transmission. If the output method doesn't do
  198083. any buffering of ouput, a function prototype must still be
  198084. supplied although it doesn't have to do anything. If
  198085. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198086. time, output_flush_fn will be ignored, although it must be
  198087. supplied for compatibility. */
  198088. void PNGAPI
  198089. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198090. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198091. {
  198092. if(png_ptr == NULL) return;
  198093. png_ptr->io_ptr = io_ptr;
  198094. #if !defined(PNG_NO_STDIO)
  198095. if (write_data_fn != NULL)
  198096. png_ptr->write_data_fn = write_data_fn;
  198097. else
  198098. png_ptr->write_data_fn = png_default_write_data;
  198099. #else
  198100. png_ptr->write_data_fn = write_data_fn;
  198101. #endif
  198102. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198103. #if !defined(PNG_NO_STDIO)
  198104. if (output_flush_fn != NULL)
  198105. png_ptr->output_flush_fn = output_flush_fn;
  198106. else
  198107. png_ptr->output_flush_fn = png_default_flush;
  198108. #else
  198109. png_ptr->output_flush_fn = output_flush_fn;
  198110. #endif
  198111. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198112. /* It is an error to read while writing a png file */
  198113. if (png_ptr->read_data_fn != NULL)
  198114. {
  198115. png_ptr->read_data_fn = NULL;
  198116. png_warning(png_ptr,
  198117. "Attempted to set both read_data_fn and write_data_fn in");
  198118. png_warning(png_ptr,
  198119. "the same structure. Resetting read_data_fn to NULL.");
  198120. }
  198121. }
  198122. #if defined(USE_FAR_KEYWORD)
  198123. #if defined(_MSC_VER)
  198124. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198125. {
  198126. void *near_ptr;
  198127. void FAR *far_ptr;
  198128. FP_OFF(near_ptr) = FP_OFF(ptr);
  198129. far_ptr = (void FAR *)near_ptr;
  198130. if(check != 0)
  198131. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198132. png_error(png_ptr,"segment lost in conversion");
  198133. return(near_ptr);
  198134. }
  198135. # else
  198136. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198137. {
  198138. void *near_ptr;
  198139. void FAR *far_ptr;
  198140. near_ptr = (void FAR *)ptr;
  198141. far_ptr = (void FAR *)near_ptr;
  198142. if(check != 0)
  198143. if(far_ptr != ptr)
  198144. png_error(png_ptr,"segment lost in conversion");
  198145. return(near_ptr);
  198146. }
  198147. # endif
  198148. # endif
  198149. #endif /* PNG_WRITE_SUPPORTED */
  198150. /*** End of inlined file: pngwio.c ***/
  198151. /*** Start of inlined file: pngwrite.c ***/
  198152. /* pngwrite.c - general routines to write a PNG file
  198153. *
  198154. * Last changed in libpng 1.2.15 January 5, 2007
  198155. * For conditions of distribution and use, see copyright notice in png.h
  198156. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198157. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198158. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198159. */
  198160. /* get internal access to png.h */
  198161. #define PNG_INTERNAL
  198162. #ifdef PNG_WRITE_SUPPORTED
  198163. /* Writes all the PNG information. This is the suggested way to use the
  198164. * library. If you have a new chunk to add, make a function to write it,
  198165. * and put it in the correct location here. If you want the chunk written
  198166. * after the image data, put it in png_write_end(). I strongly encourage
  198167. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198168. * the chunk, as that will keep the code from breaking if you want to just
  198169. * write a plain PNG file. If you have long comments, I suggest writing
  198170. * them in png_write_end(), and compressing them.
  198171. */
  198172. void PNGAPI
  198173. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198174. {
  198175. png_debug(1, "in png_write_info_before_PLTE\n");
  198176. if (png_ptr == NULL || info_ptr == NULL)
  198177. return;
  198178. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198179. {
  198180. png_write_sig(png_ptr); /* write PNG signature */
  198181. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198182. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198183. {
  198184. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198185. png_ptr->mng_features_permitted=0;
  198186. }
  198187. #endif
  198188. /* write IHDR information. */
  198189. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198190. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198191. info_ptr->filter_type,
  198192. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198193. info_ptr->interlace_type);
  198194. #else
  198195. 0);
  198196. #endif
  198197. /* the rest of these check to see if the valid field has the appropriate
  198198. flag set, and if it does, writes the chunk. */
  198199. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198200. if (info_ptr->valid & PNG_INFO_gAMA)
  198201. {
  198202. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198203. png_write_gAMA(png_ptr, info_ptr->gamma);
  198204. #else
  198205. #ifdef PNG_FIXED_POINT_SUPPORTED
  198206. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198207. # endif
  198208. #endif
  198209. }
  198210. #endif
  198211. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198212. if (info_ptr->valid & PNG_INFO_sRGB)
  198213. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198214. #endif
  198215. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198216. if (info_ptr->valid & PNG_INFO_iCCP)
  198217. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198218. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198219. #endif
  198220. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198221. if (info_ptr->valid & PNG_INFO_sBIT)
  198222. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198223. #endif
  198224. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198225. if (info_ptr->valid & PNG_INFO_cHRM)
  198226. {
  198227. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198228. png_write_cHRM(png_ptr,
  198229. info_ptr->x_white, info_ptr->y_white,
  198230. info_ptr->x_red, info_ptr->y_red,
  198231. info_ptr->x_green, info_ptr->y_green,
  198232. info_ptr->x_blue, info_ptr->y_blue);
  198233. #else
  198234. # ifdef PNG_FIXED_POINT_SUPPORTED
  198235. png_write_cHRM_fixed(png_ptr,
  198236. info_ptr->int_x_white, info_ptr->int_y_white,
  198237. info_ptr->int_x_red, info_ptr->int_y_red,
  198238. info_ptr->int_x_green, info_ptr->int_y_green,
  198239. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198240. # endif
  198241. #endif
  198242. }
  198243. #endif
  198244. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198245. if (info_ptr->unknown_chunks_num)
  198246. {
  198247. png_unknown_chunk *up;
  198248. png_debug(5, "writing extra chunks\n");
  198249. for (up = info_ptr->unknown_chunks;
  198250. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198251. up++)
  198252. {
  198253. int keep=png_handle_as_unknown(png_ptr, up->name);
  198254. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198255. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198256. !(up->location & PNG_HAVE_IDAT) &&
  198257. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198258. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198259. {
  198260. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198261. }
  198262. }
  198263. }
  198264. #endif
  198265. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198266. }
  198267. }
  198268. void PNGAPI
  198269. png_write_info(png_structp png_ptr, png_infop info_ptr)
  198270. {
  198271. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198272. int i;
  198273. #endif
  198274. png_debug(1, "in png_write_info\n");
  198275. if (png_ptr == NULL || info_ptr == NULL)
  198276. return;
  198277. png_write_info_before_PLTE(png_ptr, info_ptr);
  198278. if (info_ptr->valid & PNG_INFO_PLTE)
  198279. png_write_PLTE(png_ptr, info_ptr->palette,
  198280. (png_uint_32)info_ptr->num_palette);
  198281. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198282. png_error(png_ptr, "Valid palette required for paletted images");
  198283. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198284. if (info_ptr->valid & PNG_INFO_tRNS)
  198285. {
  198286. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198287. /* invert the alpha channel (in tRNS) */
  198288. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  198289. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198290. {
  198291. int j;
  198292. for (j=0; j<(int)info_ptr->num_trans; j++)
  198293. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  198294. }
  198295. #endif
  198296. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  198297. info_ptr->num_trans, info_ptr->color_type);
  198298. }
  198299. #endif
  198300. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198301. if (info_ptr->valid & PNG_INFO_bKGD)
  198302. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  198303. #endif
  198304. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198305. if (info_ptr->valid & PNG_INFO_hIST)
  198306. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198307. #endif
  198308. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198309. if (info_ptr->valid & PNG_INFO_oFFs)
  198310. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198311. info_ptr->offset_unit_type);
  198312. #endif
  198313. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198314. if (info_ptr->valid & PNG_INFO_pCAL)
  198315. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198316. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198317. info_ptr->pcal_units, info_ptr->pcal_params);
  198318. #endif
  198319. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198320. if (info_ptr->valid & PNG_INFO_sCAL)
  198321. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198322. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198323. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198324. #else
  198325. #ifdef PNG_FIXED_POINT_SUPPORTED
  198326. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198327. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198328. #else
  198329. png_warning(png_ptr,
  198330. "png_write_sCAL not supported; sCAL chunk not written.");
  198331. #endif
  198332. #endif
  198333. #endif
  198334. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198335. if (info_ptr->valid & PNG_INFO_pHYs)
  198336. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198337. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198338. #endif
  198339. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198340. if (info_ptr->valid & PNG_INFO_tIME)
  198341. {
  198342. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198343. png_ptr->mode |= PNG_WROTE_tIME;
  198344. }
  198345. #endif
  198346. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198347. if (info_ptr->valid & PNG_INFO_sPLT)
  198348. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198349. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198350. #endif
  198351. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198352. /* Check to see if we need to write text chunks */
  198353. for (i = 0; i < info_ptr->num_text; i++)
  198354. {
  198355. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198356. info_ptr->text[i].compression);
  198357. /* an internationalized chunk? */
  198358. if (info_ptr->text[i].compression > 0)
  198359. {
  198360. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198361. /* write international chunk */
  198362. png_write_iTXt(png_ptr,
  198363. info_ptr->text[i].compression,
  198364. info_ptr->text[i].key,
  198365. info_ptr->text[i].lang,
  198366. info_ptr->text[i].lang_key,
  198367. info_ptr->text[i].text);
  198368. #else
  198369. png_warning(png_ptr, "Unable to write international text");
  198370. #endif
  198371. /* Mark this chunk as written */
  198372. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198373. }
  198374. /* If we want a compressed text chunk */
  198375. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198376. {
  198377. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198378. /* write compressed chunk */
  198379. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198380. info_ptr->text[i].text, 0,
  198381. info_ptr->text[i].compression);
  198382. #else
  198383. png_warning(png_ptr, "Unable to write compressed text");
  198384. #endif
  198385. /* Mark this chunk as written */
  198386. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198387. }
  198388. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198389. {
  198390. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198391. /* write uncompressed chunk */
  198392. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198393. info_ptr->text[i].text,
  198394. 0);
  198395. #else
  198396. png_warning(png_ptr, "Unable to write uncompressed text");
  198397. #endif
  198398. /* Mark this chunk as written */
  198399. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198400. }
  198401. }
  198402. #endif
  198403. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198404. if (info_ptr->unknown_chunks_num)
  198405. {
  198406. png_unknown_chunk *up;
  198407. png_debug(5, "writing extra chunks\n");
  198408. for (up = info_ptr->unknown_chunks;
  198409. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198410. up++)
  198411. {
  198412. int keep=png_handle_as_unknown(png_ptr, up->name);
  198413. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198414. up->location && (up->location & PNG_HAVE_PLTE) &&
  198415. !(up->location & PNG_HAVE_IDAT) &&
  198416. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198417. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198418. {
  198419. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198420. }
  198421. }
  198422. }
  198423. #endif
  198424. }
  198425. /* Writes the end of the PNG file. If you don't want to write comments or
  198426. * time information, you can pass NULL for info. If you already wrote these
  198427. * in png_write_info(), do not write them again here. If you have long
  198428. * comments, I suggest writing them here, and compressing them.
  198429. */
  198430. void PNGAPI
  198431. png_write_end(png_structp png_ptr, png_infop info_ptr)
  198432. {
  198433. png_debug(1, "in png_write_end\n");
  198434. if (png_ptr == NULL)
  198435. return;
  198436. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  198437. png_error(png_ptr, "No IDATs written into file");
  198438. /* see if user wants us to write information chunks */
  198439. if (info_ptr != NULL)
  198440. {
  198441. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198442. int i; /* local index variable */
  198443. #endif
  198444. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198445. /* check to see if user has supplied a time chunk */
  198446. if ((info_ptr->valid & PNG_INFO_tIME) &&
  198447. !(png_ptr->mode & PNG_WROTE_tIME))
  198448. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198449. #endif
  198450. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198451. /* loop through comment chunks */
  198452. for (i = 0; i < info_ptr->num_text; i++)
  198453. {
  198454. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  198455. info_ptr->text[i].compression);
  198456. /* an internationalized chunk? */
  198457. if (info_ptr->text[i].compression > 0)
  198458. {
  198459. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198460. /* write international chunk */
  198461. png_write_iTXt(png_ptr,
  198462. info_ptr->text[i].compression,
  198463. info_ptr->text[i].key,
  198464. info_ptr->text[i].lang,
  198465. info_ptr->text[i].lang_key,
  198466. info_ptr->text[i].text);
  198467. #else
  198468. png_warning(png_ptr, "Unable to write international text");
  198469. #endif
  198470. /* Mark this chunk as written */
  198471. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198472. }
  198473. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  198474. {
  198475. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198476. /* write compressed chunk */
  198477. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198478. info_ptr->text[i].text, 0,
  198479. info_ptr->text[i].compression);
  198480. #else
  198481. png_warning(png_ptr, "Unable to write compressed text");
  198482. #endif
  198483. /* Mark this chunk as written */
  198484. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198485. }
  198486. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198487. {
  198488. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198489. /* write uncompressed chunk */
  198490. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198491. info_ptr->text[i].text, 0);
  198492. #else
  198493. png_warning(png_ptr, "Unable to write uncompressed text");
  198494. #endif
  198495. /* Mark this chunk as written */
  198496. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198497. }
  198498. }
  198499. #endif
  198500. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198501. if (info_ptr->unknown_chunks_num)
  198502. {
  198503. png_unknown_chunk *up;
  198504. png_debug(5, "writing extra chunks\n");
  198505. for (up = info_ptr->unknown_chunks;
  198506. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198507. up++)
  198508. {
  198509. int keep=png_handle_as_unknown(png_ptr, up->name);
  198510. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198511. up->location && (up->location & PNG_AFTER_IDAT) &&
  198512. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198513. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198514. {
  198515. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198516. }
  198517. }
  198518. }
  198519. #endif
  198520. }
  198521. png_ptr->mode |= PNG_AFTER_IDAT;
  198522. /* write end of PNG file */
  198523. png_write_IEND(png_ptr);
  198524. }
  198525. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198526. #if !defined(_WIN32_WCE)
  198527. /* "time.h" functions are not supported on WindowsCE */
  198528. void PNGAPI
  198529. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  198530. {
  198531. png_debug(1, "in png_convert_from_struct_tm\n");
  198532. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  198533. ptime->month = (png_byte)(ttime->tm_mon + 1);
  198534. ptime->day = (png_byte)ttime->tm_mday;
  198535. ptime->hour = (png_byte)ttime->tm_hour;
  198536. ptime->minute = (png_byte)ttime->tm_min;
  198537. ptime->second = (png_byte)ttime->tm_sec;
  198538. }
  198539. void PNGAPI
  198540. png_convert_from_time_t(png_timep ptime, time_t ttime)
  198541. {
  198542. struct tm *tbuf;
  198543. png_debug(1, "in png_convert_from_time_t\n");
  198544. tbuf = gmtime(&ttime);
  198545. png_convert_from_struct_tm(ptime, tbuf);
  198546. }
  198547. #endif
  198548. #endif
  198549. /* Initialize png_ptr structure, and allocate any memory needed */
  198550. png_structp PNGAPI
  198551. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  198552. png_error_ptr error_fn, png_error_ptr warn_fn)
  198553. {
  198554. #ifdef PNG_USER_MEM_SUPPORTED
  198555. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  198556. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  198557. }
  198558. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  198559. png_structp PNGAPI
  198560. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  198561. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  198562. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  198563. {
  198564. #endif /* PNG_USER_MEM_SUPPORTED */
  198565. png_structp png_ptr;
  198566. #ifdef PNG_SETJMP_SUPPORTED
  198567. #ifdef USE_FAR_KEYWORD
  198568. jmp_buf jmpbuf;
  198569. #endif
  198570. #endif
  198571. int i;
  198572. png_debug(1, "in png_create_write_struct\n");
  198573. #ifdef PNG_USER_MEM_SUPPORTED
  198574. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  198575. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  198576. #else
  198577. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198578. #endif /* PNG_USER_MEM_SUPPORTED */
  198579. if (png_ptr == NULL)
  198580. return (NULL);
  198581. /* added at libpng-1.2.6 */
  198582. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198583. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198584. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198585. #endif
  198586. #ifdef PNG_SETJMP_SUPPORTED
  198587. #ifdef USE_FAR_KEYWORD
  198588. if (setjmp(jmpbuf))
  198589. #else
  198590. if (setjmp(png_ptr->jmpbuf))
  198591. #endif
  198592. {
  198593. png_free(png_ptr, png_ptr->zbuf);
  198594. png_ptr->zbuf=NULL;
  198595. png_destroy_struct(png_ptr);
  198596. return (NULL);
  198597. }
  198598. #ifdef USE_FAR_KEYWORD
  198599. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198600. #endif
  198601. #endif
  198602. #ifdef PNG_USER_MEM_SUPPORTED
  198603. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  198604. #endif /* PNG_USER_MEM_SUPPORTED */
  198605. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  198606. i=0;
  198607. do
  198608. {
  198609. if(user_png_ver[i] != png_libpng_ver[i])
  198610. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198611. } while (png_libpng_ver[i++]);
  198612. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  198613. {
  198614. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  198615. * we must recompile any applications that use any older library version.
  198616. * For versions after libpng 1.0, we will be compatible, so we need
  198617. * only check the first digit.
  198618. */
  198619. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  198620. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  198621. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  198622. {
  198623. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198624. char msg[80];
  198625. if (user_png_ver)
  198626. {
  198627. png_snprintf(msg, 80,
  198628. "Application was compiled with png.h from libpng-%.20s",
  198629. user_png_ver);
  198630. png_warning(png_ptr, msg);
  198631. }
  198632. png_snprintf(msg, 80,
  198633. "Application is running with png.c from libpng-%.20s",
  198634. png_libpng_ver);
  198635. png_warning(png_ptr, msg);
  198636. #endif
  198637. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198638. png_ptr->flags=0;
  198639. #endif
  198640. png_error(png_ptr,
  198641. "Incompatible libpng version in application and library");
  198642. }
  198643. }
  198644. /* initialize zbuf - compression buffer */
  198645. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198646. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198647. (png_uint_32)png_ptr->zbuf_size);
  198648. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198649. png_flush_ptr_NULL);
  198650. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198651. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198652. 1, png_doublep_NULL, png_doublep_NULL);
  198653. #endif
  198654. #ifdef PNG_SETJMP_SUPPORTED
  198655. /* Applications that neglect to set up their own setjmp() and then encounter
  198656. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  198657. abort instead of returning. */
  198658. #ifdef USE_FAR_KEYWORD
  198659. if (setjmp(jmpbuf))
  198660. PNG_ABORT();
  198661. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198662. #else
  198663. if (setjmp(png_ptr->jmpbuf))
  198664. PNG_ABORT();
  198665. #endif
  198666. #endif
  198667. return (png_ptr);
  198668. }
  198669. /* Initialize png_ptr structure, and allocate any memory needed */
  198670. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  198671. /* Deprecated. */
  198672. #undef png_write_init
  198673. void PNGAPI
  198674. png_write_init(png_structp png_ptr)
  198675. {
  198676. /* We only come here via pre-1.0.7-compiled applications */
  198677. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  198678. }
  198679. void PNGAPI
  198680. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  198681. png_size_t png_struct_size, png_size_t png_info_size)
  198682. {
  198683. /* We only come here via pre-1.0.12-compiled applications */
  198684. if(png_ptr == NULL) return;
  198685. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198686. if(png_sizeof(png_struct) > png_struct_size ||
  198687. png_sizeof(png_info) > png_info_size)
  198688. {
  198689. char msg[80];
  198690. png_ptr->warning_fn=NULL;
  198691. if (user_png_ver)
  198692. {
  198693. png_snprintf(msg, 80,
  198694. "Application was compiled with png.h from libpng-%.20s",
  198695. user_png_ver);
  198696. png_warning(png_ptr, msg);
  198697. }
  198698. png_snprintf(msg, 80,
  198699. "Application is running with png.c from libpng-%.20s",
  198700. png_libpng_ver);
  198701. png_warning(png_ptr, msg);
  198702. }
  198703. #endif
  198704. if(png_sizeof(png_struct) > png_struct_size)
  198705. {
  198706. png_ptr->error_fn=NULL;
  198707. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198708. png_ptr->flags=0;
  198709. #endif
  198710. png_error(png_ptr,
  198711. "The png struct allocated by the application for writing is too small.");
  198712. }
  198713. if(png_sizeof(png_info) > png_info_size)
  198714. {
  198715. png_ptr->error_fn=NULL;
  198716. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198717. png_ptr->flags=0;
  198718. #endif
  198719. png_error(png_ptr,
  198720. "The info struct allocated by the application for writing is too small.");
  198721. }
  198722. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  198723. }
  198724. #endif /* PNG_1_0_X || PNG_1_2_X */
  198725. void PNGAPI
  198726. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  198727. png_size_t png_struct_size)
  198728. {
  198729. png_structp png_ptr=*ptr_ptr;
  198730. #ifdef PNG_SETJMP_SUPPORTED
  198731. jmp_buf tmp_jmp; /* to save current jump buffer */
  198732. #endif
  198733. int i = 0;
  198734. if (png_ptr == NULL)
  198735. return;
  198736. do
  198737. {
  198738. if (user_png_ver[i] != png_libpng_ver[i])
  198739. {
  198740. #ifdef PNG_LEGACY_SUPPORTED
  198741. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198742. #else
  198743. png_ptr->warning_fn=NULL;
  198744. png_warning(png_ptr,
  198745. "Application uses deprecated png_write_init() and should be recompiled.");
  198746. break;
  198747. #endif
  198748. }
  198749. } while (png_libpng_ver[i++]);
  198750. png_debug(1, "in png_write_init_3\n");
  198751. #ifdef PNG_SETJMP_SUPPORTED
  198752. /* save jump buffer and error functions */
  198753. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  198754. #endif
  198755. if (png_sizeof(png_struct) > png_struct_size)
  198756. {
  198757. png_destroy_struct(png_ptr);
  198758. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198759. *ptr_ptr = png_ptr;
  198760. }
  198761. /* reset all variables to 0 */
  198762. png_memset(png_ptr, 0, png_sizeof (png_struct));
  198763. /* added at libpng-1.2.6 */
  198764. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198765. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198766. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198767. #endif
  198768. #ifdef PNG_SETJMP_SUPPORTED
  198769. /* restore jump buffer */
  198770. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  198771. #endif
  198772. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198773. png_flush_ptr_NULL);
  198774. /* initialize zbuf - compression buffer */
  198775. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198776. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198777. (png_uint_32)png_ptr->zbuf_size);
  198778. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198779. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198780. 1, png_doublep_NULL, png_doublep_NULL);
  198781. #endif
  198782. }
  198783. /* Write a few rows of image data. If the image is interlaced,
  198784. * either you will have to write the 7 sub images, or, if you
  198785. * have called png_set_interlace_handling(), you will have to
  198786. * "write" the image seven times.
  198787. */
  198788. void PNGAPI
  198789. png_write_rows(png_structp png_ptr, png_bytepp row,
  198790. png_uint_32 num_rows)
  198791. {
  198792. png_uint_32 i; /* row counter */
  198793. png_bytepp rp; /* row pointer */
  198794. png_debug(1, "in png_write_rows\n");
  198795. if (png_ptr == NULL)
  198796. return;
  198797. /* loop through the rows */
  198798. for (i = 0, rp = row; i < num_rows; i++, rp++)
  198799. {
  198800. png_write_row(png_ptr, *rp);
  198801. }
  198802. }
  198803. /* Write the image. You only need to call this function once, even
  198804. * if you are writing an interlaced image.
  198805. */
  198806. void PNGAPI
  198807. png_write_image(png_structp png_ptr, png_bytepp image)
  198808. {
  198809. png_uint_32 i; /* row index */
  198810. int pass, num_pass; /* pass variables */
  198811. png_bytepp rp; /* points to current row */
  198812. if (png_ptr == NULL)
  198813. return;
  198814. png_debug(1, "in png_write_image\n");
  198815. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198816. /* intialize interlace handling. If image is not interlaced,
  198817. this will set pass to 1 */
  198818. num_pass = png_set_interlace_handling(png_ptr);
  198819. #else
  198820. num_pass = 1;
  198821. #endif
  198822. /* loop through passes */
  198823. for (pass = 0; pass < num_pass; pass++)
  198824. {
  198825. /* loop through image */
  198826. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  198827. {
  198828. png_write_row(png_ptr, *rp);
  198829. }
  198830. }
  198831. }
  198832. /* called by user to write a row of image data */
  198833. void PNGAPI
  198834. png_write_row(png_structp png_ptr, png_bytep row)
  198835. {
  198836. if (png_ptr == NULL)
  198837. return;
  198838. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  198839. png_ptr->row_number, png_ptr->pass);
  198840. /* initialize transformations and other stuff if first time */
  198841. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  198842. {
  198843. /* make sure we wrote the header info */
  198844. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198845. png_error(png_ptr,
  198846. "png_write_info was never called before png_write_row.");
  198847. /* check for transforms that have been set but were defined out */
  198848. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  198849. if (png_ptr->transformations & PNG_INVERT_MONO)
  198850. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  198851. #endif
  198852. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  198853. if (png_ptr->transformations & PNG_FILLER)
  198854. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  198855. #endif
  198856. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  198857. if (png_ptr->transformations & PNG_PACKSWAP)
  198858. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  198859. #endif
  198860. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  198861. if (png_ptr->transformations & PNG_PACK)
  198862. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  198863. #endif
  198864. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  198865. if (png_ptr->transformations & PNG_SHIFT)
  198866. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  198867. #endif
  198868. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  198869. if (png_ptr->transformations & PNG_BGR)
  198870. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  198871. #endif
  198872. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  198873. if (png_ptr->transformations & PNG_SWAP_BYTES)
  198874. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  198875. #endif
  198876. png_write_start_row(png_ptr);
  198877. }
  198878. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198879. /* if interlaced and not interested in row, return */
  198880. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  198881. {
  198882. switch (png_ptr->pass)
  198883. {
  198884. case 0:
  198885. if (png_ptr->row_number & 0x07)
  198886. {
  198887. png_write_finish_row(png_ptr);
  198888. return;
  198889. }
  198890. break;
  198891. case 1:
  198892. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  198893. {
  198894. png_write_finish_row(png_ptr);
  198895. return;
  198896. }
  198897. break;
  198898. case 2:
  198899. if ((png_ptr->row_number & 0x07) != 4)
  198900. {
  198901. png_write_finish_row(png_ptr);
  198902. return;
  198903. }
  198904. break;
  198905. case 3:
  198906. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  198907. {
  198908. png_write_finish_row(png_ptr);
  198909. return;
  198910. }
  198911. break;
  198912. case 4:
  198913. if ((png_ptr->row_number & 0x03) != 2)
  198914. {
  198915. png_write_finish_row(png_ptr);
  198916. return;
  198917. }
  198918. break;
  198919. case 5:
  198920. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  198921. {
  198922. png_write_finish_row(png_ptr);
  198923. return;
  198924. }
  198925. break;
  198926. case 6:
  198927. if (!(png_ptr->row_number & 0x01))
  198928. {
  198929. png_write_finish_row(png_ptr);
  198930. return;
  198931. }
  198932. break;
  198933. }
  198934. }
  198935. #endif
  198936. /* set up row info for transformations */
  198937. png_ptr->row_info.color_type = png_ptr->color_type;
  198938. png_ptr->row_info.width = png_ptr->usr_width;
  198939. png_ptr->row_info.channels = png_ptr->usr_channels;
  198940. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  198941. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  198942. png_ptr->row_info.channels);
  198943. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  198944. png_ptr->row_info.width);
  198945. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  198946. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  198947. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  198948. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  198949. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  198950. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  198951. /* Copy user's row into buffer, leaving room for filter byte. */
  198952. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  198953. png_ptr->row_info.rowbytes);
  198954. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198955. /* handle interlacing */
  198956. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  198957. (png_ptr->transformations & PNG_INTERLACE))
  198958. {
  198959. png_do_write_interlace(&(png_ptr->row_info),
  198960. png_ptr->row_buf + 1, png_ptr->pass);
  198961. /* this should always get caught above, but still ... */
  198962. if (!(png_ptr->row_info.width))
  198963. {
  198964. png_write_finish_row(png_ptr);
  198965. return;
  198966. }
  198967. }
  198968. #endif
  198969. /* handle other transformations */
  198970. if (png_ptr->transformations)
  198971. png_do_write_transformations(png_ptr);
  198972. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198973. /* Write filter_method 64 (intrapixel differencing) only if
  198974. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  198975. * 2. Libpng did not write a PNG signature (this filter_method is only
  198976. * used in PNG datastreams that are embedded in MNG datastreams) and
  198977. * 3. The application called png_permit_mng_features with a mask that
  198978. * included PNG_FLAG_MNG_FILTER_64 and
  198979. * 4. The filter_method is 64 and
  198980. * 5. The color_type is RGB or RGBA
  198981. */
  198982. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  198983. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  198984. {
  198985. /* Intrapixel differencing */
  198986. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  198987. }
  198988. #endif
  198989. /* Find a filter if necessary, filter the row and write it out. */
  198990. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  198991. if (png_ptr->write_row_fn != NULL)
  198992. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  198993. }
  198994. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198995. /* Set the automatic flush interval or 0 to turn flushing off */
  198996. void PNGAPI
  198997. png_set_flush(png_structp png_ptr, int nrows)
  198998. {
  198999. png_debug(1, "in png_set_flush\n");
  199000. if (png_ptr == NULL)
  199001. return;
  199002. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199003. }
  199004. /* flush the current output buffers now */
  199005. void PNGAPI
  199006. png_write_flush(png_structp png_ptr)
  199007. {
  199008. int wrote_IDAT;
  199009. png_debug(1, "in png_write_flush\n");
  199010. if (png_ptr == NULL)
  199011. return;
  199012. /* We have already written out all of the data */
  199013. if (png_ptr->row_number >= png_ptr->num_rows)
  199014. return;
  199015. do
  199016. {
  199017. int ret;
  199018. /* compress the data */
  199019. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199020. wrote_IDAT = 0;
  199021. /* check for compression errors */
  199022. if (ret != Z_OK)
  199023. {
  199024. if (png_ptr->zstream.msg != NULL)
  199025. png_error(png_ptr, png_ptr->zstream.msg);
  199026. else
  199027. png_error(png_ptr, "zlib error");
  199028. }
  199029. if (!(png_ptr->zstream.avail_out))
  199030. {
  199031. /* write the IDAT and reset the zlib output buffer */
  199032. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199033. png_ptr->zbuf_size);
  199034. png_ptr->zstream.next_out = png_ptr->zbuf;
  199035. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199036. wrote_IDAT = 1;
  199037. }
  199038. } while(wrote_IDAT == 1);
  199039. /* If there is any data left to be output, write it into a new IDAT */
  199040. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199041. {
  199042. /* write the IDAT and reset the zlib output buffer */
  199043. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199044. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199045. png_ptr->zstream.next_out = png_ptr->zbuf;
  199046. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199047. }
  199048. png_ptr->flush_rows = 0;
  199049. png_flush(png_ptr);
  199050. }
  199051. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199052. /* free all memory used by the write */
  199053. void PNGAPI
  199054. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199055. {
  199056. png_structp png_ptr = NULL;
  199057. png_infop info_ptr = NULL;
  199058. #ifdef PNG_USER_MEM_SUPPORTED
  199059. png_free_ptr free_fn = NULL;
  199060. png_voidp mem_ptr = NULL;
  199061. #endif
  199062. png_debug(1, "in png_destroy_write_struct\n");
  199063. if (png_ptr_ptr != NULL)
  199064. {
  199065. png_ptr = *png_ptr_ptr;
  199066. #ifdef PNG_USER_MEM_SUPPORTED
  199067. free_fn = png_ptr->free_fn;
  199068. mem_ptr = png_ptr->mem_ptr;
  199069. #endif
  199070. }
  199071. if (info_ptr_ptr != NULL)
  199072. info_ptr = *info_ptr_ptr;
  199073. if (info_ptr != NULL)
  199074. {
  199075. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199076. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199077. if (png_ptr->num_chunk_list)
  199078. {
  199079. png_free(png_ptr, png_ptr->chunk_list);
  199080. png_ptr->chunk_list=NULL;
  199081. png_ptr->num_chunk_list=0;
  199082. }
  199083. #endif
  199084. #ifdef PNG_USER_MEM_SUPPORTED
  199085. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199086. (png_voidp)mem_ptr);
  199087. #else
  199088. png_destroy_struct((png_voidp)info_ptr);
  199089. #endif
  199090. *info_ptr_ptr = NULL;
  199091. }
  199092. if (png_ptr != NULL)
  199093. {
  199094. png_write_destroy(png_ptr);
  199095. #ifdef PNG_USER_MEM_SUPPORTED
  199096. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199097. (png_voidp)mem_ptr);
  199098. #else
  199099. png_destroy_struct((png_voidp)png_ptr);
  199100. #endif
  199101. *png_ptr_ptr = NULL;
  199102. }
  199103. }
  199104. /* Free any memory used in png_ptr struct (old method) */
  199105. void /* PRIVATE */
  199106. png_write_destroy(png_structp png_ptr)
  199107. {
  199108. #ifdef PNG_SETJMP_SUPPORTED
  199109. jmp_buf tmp_jmp; /* save jump buffer */
  199110. #endif
  199111. png_error_ptr error_fn;
  199112. png_error_ptr warning_fn;
  199113. png_voidp error_ptr;
  199114. #ifdef PNG_USER_MEM_SUPPORTED
  199115. png_free_ptr free_fn;
  199116. #endif
  199117. png_debug(1, "in png_write_destroy\n");
  199118. /* free any memory zlib uses */
  199119. deflateEnd(&png_ptr->zstream);
  199120. /* free our memory. png_free checks NULL for us. */
  199121. png_free(png_ptr, png_ptr->zbuf);
  199122. png_free(png_ptr, png_ptr->row_buf);
  199123. png_free(png_ptr, png_ptr->prev_row);
  199124. png_free(png_ptr, png_ptr->sub_row);
  199125. png_free(png_ptr, png_ptr->up_row);
  199126. png_free(png_ptr, png_ptr->avg_row);
  199127. png_free(png_ptr, png_ptr->paeth_row);
  199128. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199129. png_free(png_ptr, png_ptr->time_buffer);
  199130. #endif
  199131. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199132. png_free(png_ptr, png_ptr->prev_filters);
  199133. png_free(png_ptr, png_ptr->filter_weights);
  199134. png_free(png_ptr, png_ptr->inv_filter_weights);
  199135. png_free(png_ptr, png_ptr->filter_costs);
  199136. png_free(png_ptr, png_ptr->inv_filter_costs);
  199137. #endif
  199138. #ifdef PNG_SETJMP_SUPPORTED
  199139. /* reset structure */
  199140. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199141. #endif
  199142. error_fn = png_ptr->error_fn;
  199143. warning_fn = png_ptr->warning_fn;
  199144. error_ptr = png_ptr->error_ptr;
  199145. #ifdef PNG_USER_MEM_SUPPORTED
  199146. free_fn = png_ptr->free_fn;
  199147. #endif
  199148. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199149. png_ptr->error_fn = error_fn;
  199150. png_ptr->warning_fn = warning_fn;
  199151. png_ptr->error_ptr = error_ptr;
  199152. #ifdef PNG_USER_MEM_SUPPORTED
  199153. png_ptr->free_fn = free_fn;
  199154. #endif
  199155. #ifdef PNG_SETJMP_SUPPORTED
  199156. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199157. #endif
  199158. }
  199159. /* Allow the application to select one or more row filters to use. */
  199160. void PNGAPI
  199161. png_set_filter(png_structp png_ptr, int method, int filters)
  199162. {
  199163. png_debug(1, "in png_set_filter\n");
  199164. if (png_ptr == NULL)
  199165. return;
  199166. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199167. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199168. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199169. method = PNG_FILTER_TYPE_BASE;
  199170. #endif
  199171. if (method == PNG_FILTER_TYPE_BASE)
  199172. {
  199173. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199174. {
  199175. #ifndef PNG_NO_WRITE_FILTER
  199176. case 5:
  199177. case 6:
  199178. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199179. #endif /* PNG_NO_WRITE_FILTER */
  199180. case PNG_FILTER_VALUE_NONE:
  199181. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199182. #ifndef PNG_NO_WRITE_FILTER
  199183. case PNG_FILTER_VALUE_SUB:
  199184. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199185. case PNG_FILTER_VALUE_UP:
  199186. png_ptr->do_filter=PNG_FILTER_UP; break;
  199187. case PNG_FILTER_VALUE_AVG:
  199188. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199189. case PNG_FILTER_VALUE_PAETH:
  199190. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199191. default: png_ptr->do_filter = (png_byte)filters; break;
  199192. #else
  199193. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199194. #endif /* PNG_NO_WRITE_FILTER */
  199195. }
  199196. /* If we have allocated the row_buf, this means we have already started
  199197. * with the image and we should have allocated all of the filter buffers
  199198. * that have been selected. If prev_row isn't already allocated, then
  199199. * it is too late to start using the filters that need it, since we
  199200. * will be missing the data in the previous row. If an application
  199201. * wants to start and stop using particular filters during compression,
  199202. * it should start out with all of the filters, and then add and
  199203. * remove them after the start of compression.
  199204. */
  199205. if (png_ptr->row_buf != NULL)
  199206. {
  199207. #ifndef PNG_NO_WRITE_FILTER
  199208. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199209. {
  199210. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199211. (png_ptr->rowbytes + 1));
  199212. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199213. }
  199214. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199215. {
  199216. if (png_ptr->prev_row == NULL)
  199217. {
  199218. png_warning(png_ptr, "Can't add Up filter after starting");
  199219. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199220. }
  199221. else
  199222. {
  199223. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199224. (png_ptr->rowbytes + 1));
  199225. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199226. }
  199227. }
  199228. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199229. {
  199230. if (png_ptr->prev_row == NULL)
  199231. {
  199232. png_warning(png_ptr, "Can't add Average filter after starting");
  199233. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199234. }
  199235. else
  199236. {
  199237. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199238. (png_ptr->rowbytes + 1));
  199239. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199240. }
  199241. }
  199242. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199243. png_ptr->paeth_row == NULL)
  199244. {
  199245. if (png_ptr->prev_row == NULL)
  199246. {
  199247. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199248. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199249. }
  199250. else
  199251. {
  199252. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199253. (png_ptr->rowbytes + 1));
  199254. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199255. }
  199256. }
  199257. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199258. #endif /* PNG_NO_WRITE_FILTER */
  199259. png_ptr->do_filter = PNG_FILTER_NONE;
  199260. }
  199261. }
  199262. else
  199263. png_error(png_ptr, "Unknown custom filter method");
  199264. }
  199265. /* This allows us to influence the way in which libpng chooses the "best"
  199266. * filter for the current scanline. While the "minimum-sum-of-absolute-
  199267. * differences metric is relatively fast and effective, there is some
  199268. * question as to whether it can be improved upon by trying to keep the
  199269. * filtered data going to zlib more consistent, hopefully resulting in
  199270. * better compression.
  199271. */
  199272. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  199273. void PNGAPI
  199274. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  199275. int num_weights, png_doublep filter_weights,
  199276. png_doublep filter_costs)
  199277. {
  199278. int i;
  199279. png_debug(1, "in png_set_filter_heuristics\n");
  199280. if (png_ptr == NULL)
  199281. return;
  199282. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  199283. {
  199284. png_warning(png_ptr, "Unknown filter heuristic method");
  199285. return;
  199286. }
  199287. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  199288. {
  199289. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  199290. }
  199291. if (num_weights < 0 || filter_weights == NULL ||
  199292. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  199293. {
  199294. num_weights = 0;
  199295. }
  199296. png_ptr->num_prev_filters = (png_byte)num_weights;
  199297. png_ptr->heuristic_method = (png_byte)heuristic_method;
  199298. if (num_weights > 0)
  199299. {
  199300. if (png_ptr->prev_filters == NULL)
  199301. {
  199302. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  199303. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  199304. /* To make sure that the weighting starts out fairly */
  199305. for (i = 0; i < num_weights; i++)
  199306. {
  199307. png_ptr->prev_filters[i] = 255;
  199308. }
  199309. }
  199310. if (png_ptr->filter_weights == NULL)
  199311. {
  199312. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199313. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199314. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199315. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199316. for (i = 0; i < num_weights; i++)
  199317. {
  199318. png_ptr->inv_filter_weights[i] =
  199319. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199320. }
  199321. }
  199322. for (i = 0; i < num_weights; i++)
  199323. {
  199324. if (filter_weights[i] < 0.0)
  199325. {
  199326. png_ptr->inv_filter_weights[i] =
  199327. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199328. }
  199329. else
  199330. {
  199331. png_ptr->inv_filter_weights[i] =
  199332. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199333. png_ptr->filter_weights[i] =
  199334. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199335. }
  199336. }
  199337. }
  199338. /* If, in the future, there are other filter methods, this would
  199339. * need to be based on png_ptr->filter.
  199340. */
  199341. if (png_ptr->filter_costs == NULL)
  199342. {
  199343. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199344. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199345. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199346. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199347. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199348. {
  199349. png_ptr->inv_filter_costs[i] =
  199350. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199351. }
  199352. }
  199353. /* Here is where we set the relative costs of the different filters. We
  199354. * should take the desired compression level into account when setting
  199355. * the costs, so that Paeth, for instance, has a high relative cost at low
  199356. * compression levels, while it has a lower relative cost at higher
  199357. * compression settings. The filter types are in order of increasing
  199358. * relative cost, so it would be possible to do this with an algorithm.
  199359. */
  199360. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199361. {
  199362. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199363. {
  199364. png_ptr->inv_filter_costs[i] =
  199365. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199366. }
  199367. else if (filter_costs[i] >= 1.0)
  199368. {
  199369. png_ptr->inv_filter_costs[i] =
  199370. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199371. png_ptr->filter_costs[i] =
  199372. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199373. }
  199374. }
  199375. }
  199376. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199377. void PNGAPI
  199378. png_set_compression_level(png_structp png_ptr, int level)
  199379. {
  199380. png_debug(1, "in png_set_compression_level\n");
  199381. if (png_ptr == NULL)
  199382. return;
  199383. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  199384. png_ptr->zlib_level = level;
  199385. }
  199386. void PNGAPI
  199387. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  199388. {
  199389. png_debug(1, "in png_set_compression_mem_level\n");
  199390. if (png_ptr == NULL)
  199391. return;
  199392. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  199393. png_ptr->zlib_mem_level = mem_level;
  199394. }
  199395. void PNGAPI
  199396. png_set_compression_strategy(png_structp png_ptr, int strategy)
  199397. {
  199398. png_debug(1, "in png_set_compression_strategy\n");
  199399. if (png_ptr == NULL)
  199400. return;
  199401. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  199402. png_ptr->zlib_strategy = strategy;
  199403. }
  199404. void PNGAPI
  199405. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  199406. {
  199407. if (png_ptr == NULL)
  199408. return;
  199409. if (window_bits > 15)
  199410. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  199411. else if (window_bits < 8)
  199412. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  199413. #ifndef WBITS_8_OK
  199414. /* avoid libpng bug with 256-byte windows */
  199415. if (window_bits == 8)
  199416. {
  199417. png_warning(png_ptr, "Compression window is being reset to 512");
  199418. window_bits=9;
  199419. }
  199420. #endif
  199421. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  199422. png_ptr->zlib_window_bits = window_bits;
  199423. }
  199424. void PNGAPI
  199425. png_set_compression_method(png_structp png_ptr, int method)
  199426. {
  199427. png_debug(1, "in png_set_compression_method\n");
  199428. if (png_ptr == NULL)
  199429. return;
  199430. if (method != 8)
  199431. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  199432. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  199433. png_ptr->zlib_method = method;
  199434. }
  199435. void PNGAPI
  199436. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  199437. {
  199438. if (png_ptr == NULL)
  199439. return;
  199440. png_ptr->write_row_fn = write_row_fn;
  199441. }
  199442. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199443. void PNGAPI
  199444. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  199445. write_user_transform_fn)
  199446. {
  199447. png_debug(1, "in png_set_write_user_transform_fn\n");
  199448. if (png_ptr == NULL)
  199449. return;
  199450. png_ptr->transformations |= PNG_USER_TRANSFORM;
  199451. png_ptr->write_user_transform_fn = write_user_transform_fn;
  199452. }
  199453. #endif
  199454. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  199455. void PNGAPI
  199456. png_write_png(png_structp png_ptr, png_infop info_ptr,
  199457. int transforms, voidp params)
  199458. {
  199459. if (png_ptr == NULL || info_ptr == NULL)
  199460. return;
  199461. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199462. /* invert the alpha channel from opacity to transparency */
  199463. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  199464. png_set_invert_alpha(png_ptr);
  199465. #endif
  199466. /* Write the file header information. */
  199467. png_write_info(png_ptr, info_ptr);
  199468. /* ------ these transformations don't touch the info structure ------- */
  199469. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199470. /* invert monochrome pixels */
  199471. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  199472. png_set_invert_mono(png_ptr);
  199473. #endif
  199474. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199475. /* Shift the pixels up to a legal bit depth and fill in
  199476. * as appropriate to correctly scale the image.
  199477. */
  199478. if ((transforms & PNG_TRANSFORM_SHIFT)
  199479. && (info_ptr->valid & PNG_INFO_sBIT))
  199480. png_set_shift(png_ptr, &info_ptr->sig_bit);
  199481. #endif
  199482. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199483. /* pack pixels into bytes */
  199484. if (transforms & PNG_TRANSFORM_PACKING)
  199485. png_set_packing(png_ptr);
  199486. #endif
  199487. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199488. /* swap location of alpha bytes from ARGB to RGBA */
  199489. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  199490. png_set_swap_alpha(png_ptr);
  199491. #endif
  199492. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199493. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  199494. * RGB (4 channels -> 3 channels). The second parameter is not used.
  199495. */
  199496. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  199497. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  199498. #endif
  199499. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199500. /* flip BGR pixels to RGB */
  199501. if (transforms & PNG_TRANSFORM_BGR)
  199502. png_set_bgr(png_ptr);
  199503. #endif
  199504. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199505. /* swap bytes of 16-bit files to most significant byte first */
  199506. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  199507. png_set_swap(png_ptr);
  199508. #endif
  199509. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199510. /* swap bits of 1, 2, 4 bit packed pixel formats */
  199511. if (transforms & PNG_TRANSFORM_PACKSWAP)
  199512. png_set_packswap(png_ptr);
  199513. #endif
  199514. /* ----------------------- end of transformations ------------------- */
  199515. /* write the bits */
  199516. if (info_ptr->valid & PNG_INFO_IDAT)
  199517. png_write_image(png_ptr, info_ptr->row_pointers);
  199518. /* It is REQUIRED to call this to finish writing the rest of the file */
  199519. png_write_end(png_ptr, info_ptr);
  199520. transforms = transforms; /* quiet compiler warnings */
  199521. params = params;
  199522. }
  199523. #endif
  199524. #endif /* PNG_WRITE_SUPPORTED */
  199525. /*** End of inlined file: pngwrite.c ***/
  199526. /*** Start of inlined file: pngwtran.c ***/
  199527. /* pngwtran.c - transforms the data in a row for PNG writers
  199528. *
  199529. * Last changed in libpng 1.2.9 April 14, 2006
  199530. * For conditions of distribution and use, see copyright notice in png.h
  199531. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  199532. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199533. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199534. */
  199535. #define PNG_INTERNAL
  199536. #ifdef PNG_WRITE_SUPPORTED
  199537. /* Transform the data according to the user's wishes. The order of
  199538. * transformations is significant.
  199539. */
  199540. void /* PRIVATE */
  199541. png_do_write_transformations(png_structp png_ptr)
  199542. {
  199543. png_debug(1, "in png_do_write_transformations\n");
  199544. if (png_ptr == NULL)
  199545. return;
  199546. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199547. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  199548. if(png_ptr->write_user_transform_fn != NULL)
  199549. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  199550. (png_ptr, /* png_ptr */
  199551. &(png_ptr->row_info), /* row_info: */
  199552. /* png_uint_32 width; width of row */
  199553. /* png_uint_32 rowbytes; number of bytes in row */
  199554. /* png_byte color_type; color type of pixels */
  199555. /* png_byte bit_depth; bit depth of samples */
  199556. /* png_byte channels; number of channels (1-4) */
  199557. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  199558. png_ptr->row_buf + 1); /* start of pixel data for row */
  199559. #endif
  199560. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199561. if (png_ptr->transformations & PNG_FILLER)
  199562. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199563. png_ptr->flags);
  199564. #endif
  199565. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199566. if (png_ptr->transformations & PNG_PACKSWAP)
  199567. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199568. #endif
  199569. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199570. if (png_ptr->transformations & PNG_PACK)
  199571. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199572. (png_uint_32)png_ptr->bit_depth);
  199573. #endif
  199574. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199575. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199576. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199577. #endif
  199578. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199579. if (png_ptr->transformations & PNG_SHIFT)
  199580. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199581. &(png_ptr->shift));
  199582. #endif
  199583. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199584. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  199585. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199586. #endif
  199587. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199588. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  199589. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199590. #endif
  199591. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199592. if (png_ptr->transformations & PNG_BGR)
  199593. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199594. #endif
  199595. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199596. if (png_ptr->transformations & PNG_INVERT_MONO)
  199597. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199598. #endif
  199599. }
  199600. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199601. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  199602. * row_info bit depth should be 8 (one pixel per byte). The channels
  199603. * should be 1 (this only happens on grayscale and paletted images).
  199604. */
  199605. void /* PRIVATE */
  199606. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  199607. {
  199608. png_debug(1, "in png_do_pack\n");
  199609. if (row_info->bit_depth == 8 &&
  199610. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199611. row != NULL && row_info != NULL &&
  199612. #endif
  199613. row_info->channels == 1)
  199614. {
  199615. switch ((int)bit_depth)
  199616. {
  199617. case 1:
  199618. {
  199619. png_bytep sp, dp;
  199620. int mask, v;
  199621. png_uint_32 i;
  199622. png_uint_32 row_width = row_info->width;
  199623. sp = row;
  199624. dp = row;
  199625. mask = 0x80;
  199626. v = 0;
  199627. for (i = 0; i < row_width; i++)
  199628. {
  199629. if (*sp != 0)
  199630. v |= mask;
  199631. sp++;
  199632. if (mask > 1)
  199633. mask >>= 1;
  199634. else
  199635. {
  199636. mask = 0x80;
  199637. *dp = (png_byte)v;
  199638. dp++;
  199639. v = 0;
  199640. }
  199641. }
  199642. if (mask != 0x80)
  199643. *dp = (png_byte)v;
  199644. break;
  199645. }
  199646. case 2:
  199647. {
  199648. png_bytep sp, dp;
  199649. int shift, v;
  199650. png_uint_32 i;
  199651. png_uint_32 row_width = row_info->width;
  199652. sp = row;
  199653. dp = row;
  199654. shift = 6;
  199655. v = 0;
  199656. for (i = 0; i < row_width; i++)
  199657. {
  199658. png_byte value;
  199659. value = (png_byte)(*sp & 0x03);
  199660. v |= (value << shift);
  199661. if (shift == 0)
  199662. {
  199663. shift = 6;
  199664. *dp = (png_byte)v;
  199665. dp++;
  199666. v = 0;
  199667. }
  199668. else
  199669. shift -= 2;
  199670. sp++;
  199671. }
  199672. if (shift != 6)
  199673. *dp = (png_byte)v;
  199674. break;
  199675. }
  199676. case 4:
  199677. {
  199678. png_bytep sp, dp;
  199679. int shift, v;
  199680. png_uint_32 i;
  199681. png_uint_32 row_width = row_info->width;
  199682. sp = row;
  199683. dp = row;
  199684. shift = 4;
  199685. v = 0;
  199686. for (i = 0; i < row_width; i++)
  199687. {
  199688. png_byte value;
  199689. value = (png_byte)(*sp & 0x0f);
  199690. v |= (value << shift);
  199691. if (shift == 0)
  199692. {
  199693. shift = 4;
  199694. *dp = (png_byte)v;
  199695. dp++;
  199696. v = 0;
  199697. }
  199698. else
  199699. shift -= 4;
  199700. sp++;
  199701. }
  199702. if (shift != 4)
  199703. *dp = (png_byte)v;
  199704. break;
  199705. }
  199706. }
  199707. row_info->bit_depth = (png_byte)bit_depth;
  199708. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  199709. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  199710. row_info->width);
  199711. }
  199712. }
  199713. #endif
  199714. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199715. /* Shift pixel values to take advantage of whole range. Pass the
  199716. * true number of bits in bit_depth. The row should be packed
  199717. * according to row_info->bit_depth. Thus, if you had a row of
  199718. * bit depth 4, but the pixels only had values from 0 to 7, you
  199719. * would pass 3 as bit_depth, and this routine would translate the
  199720. * data to 0 to 15.
  199721. */
  199722. void /* PRIVATE */
  199723. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  199724. {
  199725. png_debug(1, "in png_do_shift\n");
  199726. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199727. if (row != NULL && row_info != NULL &&
  199728. #else
  199729. if (
  199730. #endif
  199731. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  199732. {
  199733. int shift_start[4], shift_dec[4];
  199734. int channels = 0;
  199735. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  199736. {
  199737. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  199738. shift_dec[channels] = bit_depth->red;
  199739. channels++;
  199740. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  199741. shift_dec[channels] = bit_depth->green;
  199742. channels++;
  199743. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  199744. shift_dec[channels] = bit_depth->blue;
  199745. channels++;
  199746. }
  199747. else
  199748. {
  199749. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  199750. shift_dec[channels] = bit_depth->gray;
  199751. channels++;
  199752. }
  199753. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  199754. {
  199755. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  199756. shift_dec[channels] = bit_depth->alpha;
  199757. channels++;
  199758. }
  199759. /* with low row depths, could only be grayscale, so one channel */
  199760. if (row_info->bit_depth < 8)
  199761. {
  199762. png_bytep bp = row;
  199763. png_uint_32 i;
  199764. png_byte mask;
  199765. png_uint_32 row_bytes = row_info->rowbytes;
  199766. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  199767. mask = 0x55;
  199768. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  199769. mask = 0x11;
  199770. else
  199771. mask = 0xff;
  199772. for (i = 0; i < row_bytes; i++, bp++)
  199773. {
  199774. png_uint_16 v;
  199775. int j;
  199776. v = *bp;
  199777. *bp = 0;
  199778. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  199779. {
  199780. if (j > 0)
  199781. *bp |= (png_byte)((v << j) & 0xff);
  199782. else
  199783. *bp |= (png_byte)((v >> (-j)) & mask);
  199784. }
  199785. }
  199786. }
  199787. else if (row_info->bit_depth == 8)
  199788. {
  199789. png_bytep bp = row;
  199790. png_uint_32 i;
  199791. png_uint_32 istop = channels * row_info->width;
  199792. for (i = 0; i < istop; i++, bp++)
  199793. {
  199794. png_uint_16 v;
  199795. int j;
  199796. int c = (int)(i%channels);
  199797. v = *bp;
  199798. *bp = 0;
  199799. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  199800. {
  199801. if (j > 0)
  199802. *bp |= (png_byte)((v << j) & 0xff);
  199803. else
  199804. *bp |= (png_byte)((v >> (-j)) & 0xff);
  199805. }
  199806. }
  199807. }
  199808. else
  199809. {
  199810. png_bytep bp;
  199811. png_uint_32 i;
  199812. png_uint_32 istop = channels * row_info->width;
  199813. for (bp = row, i = 0; i < istop; i++)
  199814. {
  199815. int c = (int)(i%channels);
  199816. png_uint_16 value, v;
  199817. int j;
  199818. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  199819. value = 0;
  199820. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  199821. {
  199822. if (j > 0)
  199823. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  199824. else
  199825. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  199826. }
  199827. *bp++ = (png_byte)(value >> 8);
  199828. *bp++ = (png_byte)(value & 0xff);
  199829. }
  199830. }
  199831. }
  199832. }
  199833. #endif
  199834. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199835. void /* PRIVATE */
  199836. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  199837. {
  199838. png_debug(1, "in png_do_write_swap_alpha\n");
  199839. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199840. if (row != NULL && row_info != NULL)
  199841. #endif
  199842. {
  199843. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199844. {
  199845. /* This converts from ARGB to RGBA */
  199846. if (row_info->bit_depth == 8)
  199847. {
  199848. png_bytep sp, dp;
  199849. png_uint_32 i;
  199850. png_uint_32 row_width = row_info->width;
  199851. for (i = 0, sp = dp = row; i < row_width; i++)
  199852. {
  199853. png_byte save = *(sp++);
  199854. *(dp++) = *(sp++);
  199855. *(dp++) = *(sp++);
  199856. *(dp++) = *(sp++);
  199857. *(dp++) = save;
  199858. }
  199859. }
  199860. /* This converts from AARRGGBB to RRGGBBAA */
  199861. else
  199862. {
  199863. png_bytep sp, dp;
  199864. png_uint_32 i;
  199865. png_uint_32 row_width = row_info->width;
  199866. for (i = 0, sp = dp = row; i < row_width; i++)
  199867. {
  199868. png_byte save[2];
  199869. save[0] = *(sp++);
  199870. save[1] = *(sp++);
  199871. *(dp++) = *(sp++);
  199872. *(dp++) = *(sp++);
  199873. *(dp++) = *(sp++);
  199874. *(dp++) = *(sp++);
  199875. *(dp++) = *(sp++);
  199876. *(dp++) = *(sp++);
  199877. *(dp++) = save[0];
  199878. *(dp++) = save[1];
  199879. }
  199880. }
  199881. }
  199882. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  199883. {
  199884. /* This converts from AG to GA */
  199885. if (row_info->bit_depth == 8)
  199886. {
  199887. png_bytep sp, dp;
  199888. png_uint_32 i;
  199889. png_uint_32 row_width = row_info->width;
  199890. for (i = 0, sp = dp = row; i < row_width; i++)
  199891. {
  199892. png_byte save = *(sp++);
  199893. *(dp++) = *(sp++);
  199894. *(dp++) = save;
  199895. }
  199896. }
  199897. /* This converts from AAGG to GGAA */
  199898. else
  199899. {
  199900. png_bytep sp, dp;
  199901. png_uint_32 i;
  199902. png_uint_32 row_width = row_info->width;
  199903. for (i = 0, sp = dp = row; i < row_width; i++)
  199904. {
  199905. png_byte save[2];
  199906. save[0] = *(sp++);
  199907. save[1] = *(sp++);
  199908. *(dp++) = *(sp++);
  199909. *(dp++) = *(sp++);
  199910. *(dp++) = save[0];
  199911. *(dp++) = save[1];
  199912. }
  199913. }
  199914. }
  199915. }
  199916. }
  199917. #endif
  199918. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199919. void /* PRIVATE */
  199920. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  199921. {
  199922. png_debug(1, "in png_do_write_invert_alpha\n");
  199923. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199924. if (row != NULL && row_info != NULL)
  199925. #endif
  199926. {
  199927. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199928. {
  199929. /* This inverts the alpha channel in RGBA */
  199930. if (row_info->bit_depth == 8)
  199931. {
  199932. png_bytep sp, dp;
  199933. png_uint_32 i;
  199934. png_uint_32 row_width = row_info->width;
  199935. for (i = 0, sp = dp = row; i < row_width; i++)
  199936. {
  199937. /* does nothing
  199938. *(dp++) = *(sp++);
  199939. *(dp++) = *(sp++);
  199940. *(dp++) = *(sp++);
  199941. */
  199942. sp+=3; dp = sp;
  199943. *(dp++) = (png_byte)(255 - *(sp++));
  199944. }
  199945. }
  199946. /* This inverts the alpha channel in RRGGBBAA */
  199947. else
  199948. {
  199949. png_bytep sp, dp;
  199950. png_uint_32 i;
  199951. png_uint_32 row_width = row_info->width;
  199952. for (i = 0, sp = dp = row; i < row_width; i++)
  199953. {
  199954. /* does nothing
  199955. *(dp++) = *(sp++);
  199956. *(dp++) = *(sp++);
  199957. *(dp++) = *(sp++);
  199958. *(dp++) = *(sp++);
  199959. *(dp++) = *(sp++);
  199960. *(dp++) = *(sp++);
  199961. */
  199962. sp+=6; dp = sp;
  199963. *(dp++) = (png_byte)(255 - *(sp++));
  199964. *(dp++) = (png_byte)(255 - *(sp++));
  199965. }
  199966. }
  199967. }
  199968. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  199969. {
  199970. /* This inverts the alpha channel in GA */
  199971. if (row_info->bit_depth == 8)
  199972. {
  199973. png_bytep sp, dp;
  199974. png_uint_32 i;
  199975. png_uint_32 row_width = row_info->width;
  199976. for (i = 0, sp = dp = row; i < row_width; i++)
  199977. {
  199978. *(dp++) = *(sp++);
  199979. *(dp++) = (png_byte)(255 - *(sp++));
  199980. }
  199981. }
  199982. /* This inverts the alpha channel in GGAA */
  199983. else
  199984. {
  199985. png_bytep sp, dp;
  199986. png_uint_32 i;
  199987. png_uint_32 row_width = row_info->width;
  199988. for (i = 0, sp = dp = row; i < row_width; i++)
  199989. {
  199990. /* does nothing
  199991. *(dp++) = *(sp++);
  199992. *(dp++) = *(sp++);
  199993. */
  199994. sp+=2; dp = sp;
  199995. *(dp++) = (png_byte)(255 - *(sp++));
  199996. *(dp++) = (png_byte)(255 - *(sp++));
  199997. }
  199998. }
  199999. }
  200000. }
  200001. }
  200002. #endif
  200003. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200004. /* undoes intrapixel differencing */
  200005. void /* PRIVATE */
  200006. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200007. {
  200008. png_debug(1, "in png_do_write_intrapixel\n");
  200009. if (
  200010. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200011. row != NULL && row_info != NULL &&
  200012. #endif
  200013. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200014. {
  200015. int bytes_per_pixel;
  200016. png_uint_32 row_width = row_info->width;
  200017. if (row_info->bit_depth == 8)
  200018. {
  200019. png_bytep rp;
  200020. png_uint_32 i;
  200021. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200022. bytes_per_pixel = 3;
  200023. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200024. bytes_per_pixel = 4;
  200025. else
  200026. return;
  200027. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200028. {
  200029. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200030. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200031. }
  200032. }
  200033. else if (row_info->bit_depth == 16)
  200034. {
  200035. png_bytep rp;
  200036. png_uint_32 i;
  200037. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200038. bytes_per_pixel = 6;
  200039. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200040. bytes_per_pixel = 8;
  200041. else
  200042. return;
  200043. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200044. {
  200045. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200046. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200047. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200048. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200049. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200050. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200051. *(rp+1) = (png_byte)(red & 0xff);
  200052. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200053. *(rp+5) = (png_byte)(blue & 0xff);
  200054. }
  200055. }
  200056. }
  200057. }
  200058. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200059. #endif /* PNG_WRITE_SUPPORTED */
  200060. /*** End of inlined file: pngwtran.c ***/
  200061. /*** Start of inlined file: pngwutil.c ***/
  200062. /* pngwutil.c - utilities to write a PNG file
  200063. *
  200064. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200065. * For conditions of distribution and use, see copyright notice in png.h
  200066. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200067. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200068. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200069. */
  200070. #define PNG_INTERNAL
  200071. #ifdef PNG_WRITE_SUPPORTED
  200072. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200073. * with unsigned numbers for convenience, although one supported
  200074. * ancillary chunk uses signed (two's complement) numbers.
  200075. */
  200076. void PNGAPI
  200077. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200078. {
  200079. buf[0] = (png_byte)((i >> 24) & 0xff);
  200080. buf[1] = (png_byte)((i >> 16) & 0xff);
  200081. buf[2] = (png_byte)((i >> 8) & 0xff);
  200082. buf[3] = (png_byte)(i & 0xff);
  200083. }
  200084. /* The png_save_int_32 function assumes integers are stored in two's
  200085. * complement format. If this isn't the case, then this routine needs to
  200086. * be modified to write data in two's complement format.
  200087. */
  200088. void PNGAPI
  200089. png_save_int_32(png_bytep buf, png_int_32 i)
  200090. {
  200091. buf[0] = (png_byte)((i >> 24) & 0xff);
  200092. buf[1] = (png_byte)((i >> 16) & 0xff);
  200093. buf[2] = (png_byte)((i >> 8) & 0xff);
  200094. buf[3] = (png_byte)(i & 0xff);
  200095. }
  200096. /* Place a 16-bit number into a buffer in PNG byte order.
  200097. * The parameter is declared unsigned int, not png_uint_16,
  200098. * just to avoid potential problems on pre-ANSI C compilers.
  200099. */
  200100. void PNGAPI
  200101. png_save_uint_16(png_bytep buf, unsigned int i)
  200102. {
  200103. buf[0] = (png_byte)((i >> 8) & 0xff);
  200104. buf[1] = (png_byte)(i & 0xff);
  200105. }
  200106. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200107. * representing the chunk name. The array must be at least 4 bytes in
  200108. * length, and does not need to be null terminated. To be safe, pass the
  200109. * pre-defined chunk names here, and if you need a new one, define it
  200110. * where the others are defined. The length is the length of the data.
  200111. * All the data must be present. If that is not possible, use the
  200112. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200113. * functions instead.
  200114. */
  200115. void PNGAPI
  200116. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200117. png_bytep data, png_size_t length)
  200118. {
  200119. if(png_ptr == NULL) return;
  200120. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200121. png_write_chunk_data(png_ptr, data, length);
  200122. png_write_chunk_end(png_ptr);
  200123. }
  200124. /* Write the start of a PNG chunk. The type is the chunk type.
  200125. * The total_length is the sum of the lengths of all the data you will be
  200126. * passing in png_write_chunk_data().
  200127. */
  200128. void PNGAPI
  200129. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200130. png_uint_32 length)
  200131. {
  200132. png_byte buf[4];
  200133. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200134. if(png_ptr == NULL) return;
  200135. /* write the length */
  200136. png_save_uint_32(buf, length);
  200137. png_write_data(png_ptr, buf, (png_size_t)4);
  200138. /* write the chunk name */
  200139. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200140. /* reset the crc and run it over the chunk name */
  200141. png_reset_crc(png_ptr);
  200142. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200143. }
  200144. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200145. * Note that multiple calls to this function are allowed, and that the
  200146. * sum of the lengths from these calls *must* add up to the total_length
  200147. * given to png_write_chunk_start().
  200148. */
  200149. void PNGAPI
  200150. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200151. {
  200152. /* write the data, and run the CRC over it */
  200153. if(png_ptr == NULL) return;
  200154. if (data != NULL && length > 0)
  200155. {
  200156. png_calculate_crc(png_ptr, data, length);
  200157. png_write_data(png_ptr, data, length);
  200158. }
  200159. }
  200160. /* Finish a chunk started with png_write_chunk_start(). */
  200161. void PNGAPI
  200162. png_write_chunk_end(png_structp png_ptr)
  200163. {
  200164. png_byte buf[4];
  200165. if(png_ptr == NULL) return;
  200166. /* write the crc */
  200167. png_save_uint_32(buf, png_ptr->crc);
  200168. png_write_data(png_ptr, buf, (png_size_t)4);
  200169. }
  200170. /* Simple function to write the signature. If we have already written
  200171. * the magic bytes of the signature, or more likely, the PNG stream is
  200172. * being embedded into another stream and doesn't need its own signature,
  200173. * we should call png_set_sig_bytes() to tell libpng how many of the
  200174. * bytes have already been written.
  200175. */
  200176. void /* PRIVATE */
  200177. png_write_sig(png_structp png_ptr)
  200178. {
  200179. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200180. /* write the rest of the 8 byte signature */
  200181. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200182. (png_size_t)8 - png_ptr->sig_bytes);
  200183. if(png_ptr->sig_bytes < 3)
  200184. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200185. }
  200186. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200187. /*
  200188. * This pair of functions encapsulates the operation of (a) compressing a
  200189. * text string, and (b) issuing it later as a series of chunk data writes.
  200190. * The compression_state structure is shared context for these functions
  200191. * set up by the caller in order to make the whole mess thread-safe.
  200192. */
  200193. typedef struct
  200194. {
  200195. char *input; /* the uncompressed input data */
  200196. int input_len; /* its length */
  200197. int num_output_ptr; /* number of output pointers used */
  200198. int max_output_ptr; /* size of output_ptr */
  200199. png_charpp output_ptr; /* array of pointers to output */
  200200. } compression_state;
  200201. /* compress given text into storage in the png_ptr structure */
  200202. static int /* PRIVATE */
  200203. png_text_compress(png_structp png_ptr,
  200204. png_charp text, png_size_t text_len, int compression,
  200205. compression_state *comp)
  200206. {
  200207. int ret;
  200208. comp->num_output_ptr = 0;
  200209. comp->max_output_ptr = 0;
  200210. comp->output_ptr = NULL;
  200211. comp->input = NULL;
  200212. comp->input_len = 0;
  200213. /* we may just want to pass the text right through */
  200214. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200215. {
  200216. comp->input = text;
  200217. comp->input_len = text_len;
  200218. return((int)text_len);
  200219. }
  200220. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200221. {
  200222. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200223. char msg[50];
  200224. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200225. png_warning(png_ptr, msg);
  200226. #else
  200227. png_warning(png_ptr, "Unknown compression type");
  200228. #endif
  200229. }
  200230. /* We can't write the chunk until we find out how much data we have,
  200231. * which means we need to run the compressor first and save the
  200232. * output. This shouldn't be a problem, as the vast majority of
  200233. * comments should be reasonable, but we will set up an array of
  200234. * malloc'd pointers to be sure.
  200235. *
  200236. * If we knew the application was well behaved, we could simplify this
  200237. * greatly by assuming we can always malloc an output buffer large
  200238. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200239. * and malloc this directly. The only time this would be a bad idea is
  200240. * if we can't malloc more than 64K and we have 64K of random input
  200241. * data, or if the input string is incredibly large (although this
  200242. * wouldn't cause a failure, just a slowdown due to swapping).
  200243. */
  200244. /* set up the compression buffers */
  200245. png_ptr->zstream.avail_in = (uInt)text_len;
  200246. png_ptr->zstream.next_in = (Bytef *)text;
  200247. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200248. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200249. /* this is the same compression loop as in png_write_row() */
  200250. do
  200251. {
  200252. /* compress the data */
  200253. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200254. if (ret != Z_OK)
  200255. {
  200256. /* error */
  200257. if (png_ptr->zstream.msg != NULL)
  200258. png_error(png_ptr, png_ptr->zstream.msg);
  200259. else
  200260. png_error(png_ptr, "zlib error");
  200261. }
  200262. /* check to see if we need more room */
  200263. if (!(png_ptr->zstream.avail_out))
  200264. {
  200265. /* make sure the output array has room */
  200266. if (comp->num_output_ptr >= comp->max_output_ptr)
  200267. {
  200268. int old_max;
  200269. old_max = comp->max_output_ptr;
  200270. comp->max_output_ptr = comp->num_output_ptr + 4;
  200271. if (comp->output_ptr != NULL)
  200272. {
  200273. png_charpp old_ptr;
  200274. old_ptr = comp->output_ptr;
  200275. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200276. (png_uint_32)(comp->max_output_ptr *
  200277. png_sizeof (png_charpp)));
  200278. png_memcpy(comp->output_ptr, old_ptr, old_max
  200279. * png_sizeof (png_charp));
  200280. png_free(png_ptr, old_ptr);
  200281. }
  200282. else
  200283. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200284. (png_uint_32)(comp->max_output_ptr *
  200285. png_sizeof (png_charp)));
  200286. }
  200287. /* save the data */
  200288. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  200289. (png_uint_32)png_ptr->zbuf_size);
  200290. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200291. png_ptr->zbuf_size);
  200292. comp->num_output_ptr++;
  200293. /* and reset the buffer */
  200294. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200295. png_ptr->zstream.next_out = png_ptr->zbuf;
  200296. }
  200297. /* continue until we don't have any more to compress */
  200298. } while (png_ptr->zstream.avail_in);
  200299. /* finish the compression */
  200300. do
  200301. {
  200302. /* tell zlib we are finished */
  200303. ret = deflate(&png_ptr->zstream, Z_FINISH);
  200304. if (ret == Z_OK)
  200305. {
  200306. /* check to see if we need more room */
  200307. if (!(png_ptr->zstream.avail_out))
  200308. {
  200309. /* check to make sure our output array has room */
  200310. if (comp->num_output_ptr >= comp->max_output_ptr)
  200311. {
  200312. int old_max;
  200313. old_max = comp->max_output_ptr;
  200314. comp->max_output_ptr = comp->num_output_ptr + 4;
  200315. if (comp->output_ptr != NULL)
  200316. {
  200317. png_charpp old_ptr;
  200318. old_ptr = comp->output_ptr;
  200319. /* This could be optimized to realloc() */
  200320. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200321. (png_uint_32)(comp->max_output_ptr *
  200322. png_sizeof (png_charpp)));
  200323. png_memcpy(comp->output_ptr, old_ptr,
  200324. old_max * png_sizeof (png_charp));
  200325. png_free(png_ptr, old_ptr);
  200326. }
  200327. else
  200328. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200329. (png_uint_32)(comp->max_output_ptr *
  200330. png_sizeof (png_charp)));
  200331. }
  200332. /* save off the data */
  200333. comp->output_ptr[comp->num_output_ptr] =
  200334. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200335. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200336. png_ptr->zbuf_size);
  200337. comp->num_output_ptr++;
  200338. /* and reset the buffer pointers */
  200339. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200340. png_ptr->zstream.next_out = png_ptr->zbuf;
  200341. }
  200342. }
  200343. else if (ret != Z_STREAM_END)
  200344. {
  200345. /* we got an error */
  200346. if (png_ptr->zstream.msg != NULL)
  200347. png_error(png_ptr, png_ptr->zstream.msg);
  200348. else
  200349. png_error(png_ptr, "zlib error");
  200350. }
  200351. } while (ret != Z_STREAM_END);
  200352. /* text length is number of buffers plus last buffer */
  200353. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200354. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200355. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200356. return((int)text_len);
  200357. }
  200358. /* ship the compressed text out via chunk writes */
  200359. static void /* PRIVATE */
  200360. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200361. {
  200362. int i;
  200363. /* handle the no-compression case */
  200364. if (comp->input)
  200365. {
  200366. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200367. (png_size_t)comp->input_len);
  200368. return;
  200369. }
  200370. /* write saved output buffers, if any */
  200371. for (i = 0; i < comp->num_output_ptr; i++)
  200372. {
  200373. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200374. png_ptr->zbuf_size);
  200375. png_free(png_ptr, comp->output_ptr[i]);
  200376. comp->output_ptr[i]=NULL;
  200377. }
  200378. if (comp->max_output_ptr != 0)
  200379. png_free(png_ptr, comp->output_ptr);
  200380. comp->output_ptr=NULL;
  200381. /* write anything left in zbuf */
  200382. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  200383. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  200384. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200385. /* reset zlib for another zTXt/iTXt or image data */
  200386. deflateReset(&png_ptr->zstream);
  200387. png_ptr->zstream.data_type = Z_BINARY;
  200388. }
  200389. #endif
  200390. /* Write the IHDR chunk, and update the png_struct with the necessary
  200391. * information. Note that the rest of this code depends upon this
  200392. * information being correct.
  200393. */
  200394. void /* PRIVATE */
  200395. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  200396. int bit_depth, int color_type, int compression_type, int filter_type,
  200397. int interlace_type)
  200398. {
  200399. #ifdef PNG_USE_LOCAL_ARRAYS
  200400. PNG_IHDR;
  200401. #endif
  200402. png_byte buf[13]; /* buffer to store the IHDR info */
  200403. png_debug(1, "in png_write_IHDR\n");
  200404. /* Check that we have valid input data from the application info */
  200405. switch (color_type)
  200406. {
  200407. case PNG_COLOR_TYPE_GRAY:
  200408. switch (bit_depth)
  200409. {
  200410. case 1:
  200411. case 2:
  200412. case 4:
  200413. case 8:
  200414. case 16: png_ptr->channels = 1; break;
  200415. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  200416. }
  200417. break;
  200418. case PNG_COLOR_TYPE_RGB:
  200419. if (bit_depth != 8 && bit_depth != 16)
  200420. png_error(png_ptr, "Invalid bit depth for RGB image");
  200421. png_ptr->channels = 3;
  200422. break;
  200423. case PNG_COLOR_TYPE_PALETTE:
  200424. switch (bit_depth)
  200425. {
  200426. case 1:
  200427. case 2:
  200428. case 4:
  200429. case 8: png_ptr->channels = 1; break;
  200430. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  200431. }
  200432. break;
  200433. case PNG_COLOR_TYPE_GRAY_ALPHA:
  200434. if (bit_depth != 8 && bit_depth != 16)
  200435. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  200436. png_ptr->channels = 2;
  200437. break;
  200438. case PNG_COLOR_TYPE_RGB_ALPHA:
  200439. if (bit_depth != 8 && bit_depth != 16)
  200440. png_error(png_ptr, "Invalid bit depth for RGBA image");
  200441. png_ptr->channels = 4;
  200442. break;
  200443. default:
  200444. png_error(png_ptr, "Invalid image color type specified");
  200445. }
  200446. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200447. {
  200448. png_warning(png_ptr, "Invalid compression type specified");
  200449. compression_type = PNG_COMPRESSION_TYPE_BASE;
  200450. }
  200451. /* Write filter_method 64 (intrapixel differencing) only if
  200452. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  200453. * 2. Libpng did not write a PNG signature (this filter_method is only
  200454. * used in PNG datastreams that are embedded in MNG datastreams) and
  200455. * 3. The application called png_permit_mng_features with a mask that
  200456. * included PNG_FLAG_MNG_FILTER_64 and
  200457. * 4. The filter_method is 64 and
  200458. * 5. The color_type is RGB or RGBA
  200459. */
  200460. if (
  200461. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200462. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  200463. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  200464. (color_type == PNG_COLOR_TYPE_RGB ||
  200465. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  200466. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  200467. #endif
  200468. filter_type != PNG_FILTER_TYPE_BASE)
  200469. {
  200470. png_warning(png_ptr, "Invalid filter type specified");
  200471. filter_type = PNG_FILTER_TYPE_BASE;
  200472. }
  200473. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  200474. if (interlace_type != PNG_INTERLACE_NONE &&
  200475. interlace_type != PNG_INTERLACE_ADAM7)
  200476. {
  200477. png_warning(png_ptr, "Invalid interlace type specified");
  200478. interlace_type = PNG_INTERLACE_ADAM7;
  200479. }
  200480. #else
  200481. interlace_type=PNG_INTERLACE_NONE;
  200482. #endif
  200483. /* save off the relevent information */
  200484. png_ptr->bit_depth = (png_byte)bit_depth;
  200485. png_ptr->color_type = (png_byte)color_type;
  200486. png_ptr->interlaced = (png_byte)interlace_type;
  200487. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200488. png_ptr->filter_type = (png_byte)filter_type;
  200489. #endif
  200490. png_ptr->compression_type = (png_byte)compression_type;
  200491. png_ptr->width = width;
  200492. png_ptr->height = height;
  200493. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  200494. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  200495. /* set the usr info, so any transformations can modify it */
  200496. png_ptr->usr_width = png_ptr->width;
  200497. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  200498. png_ptr->usr_channels = png_ptr->channels;
  200499. /* pack the header information into the buffer */
  200500. png_save_uint_32(buf, width);
  200501. png_save_uint_32(buf + 4, height);
  200502. buf[8] = (png_byte)bit_depth;
  200503. buf[9] = (png_byte)color_type;
  200504. buf[10] = (png_byte)compression_type;
  200505. buf[11] = (png_byte)filter_type;
  200506. buf[12] = (png_byte)interlace_type;
  200507. /* write the chunk */
  200508. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  200509. /* initialize zlib with PNG info */
  200510. png_ptr->zstream.zalloc = png_zalloc;
  200511. png_ptr->zstream.zfree = png_zfree;
  200512. png_ptr->zstream.opaque = (voidpf)png_ptr;
  200513. if (!(png_ptr->do_filter))
  200514. {
  200515. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  200516. png_ptr->bit_depth < 8)
  200517. png_ptr->do_filter = PNG_FILTER_NONE;
  200518. else
  200519. png_ptr->do_filter = PNG_ALL_FILTERS;
  200520. }
  200521. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  200522. {
  200523. if (png_ptr->do_filter != PNG_FILTER_NONE)
  200524. png_ptr->zlib_strategy = Z_FILTERED;
  200525. else
  200526. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  200527. }
  200528. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  200529. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  200530. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  200531. png_ptr->zlib_mem_level = 8;
  200532. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  200533. png_ptr->zlib_window_bits = 15;
  200534. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  200535. png_ptr->zlib_method = 8;
  200536. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  200537. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  200538. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  200539. png_error(png_ptr, "zlib failed to initialize compressor");
  200540. png_ptr->zstream.next_out = png_ptr->zbuf;
  200541. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200542. /* libpng is not interested in zstream.data_type */
  200543. /* set it to a predefined value, to avoid its evaluation inside zlib */
  200544. png_ptr->zstream.data_type = Z_BINARY;
  200545. png_ptr->mode = PNG_HAVE_IHDR;
  200546. }
  200547. /* write the palette. We are careful not to trust png_color to be in the
  200548. * correct order for PNG, so people can redefine it to any convenient
  200549. * structure.
  200550. */
  200551. void /* PRIVATE */
  200552. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  200553. {
  200554. #ifdef PNG_USE_LOCAL_ARRAYS
  200555. PNG_PLTE;
  200556. #endif
  200557. png_uint_32 i;
  200558. png_colorp pal_ptr;
  200559. png_byte buf[3];
  200560. png_debug(1, "in png_write_PLTE\n");
  200561. if ((
  200562. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200563. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  200564. #endif
  200565. num_pal == 0) || num_pal > 256)
  200566. {
  200567. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  200568. {
  200569. png_error(png_ptr, "Invalid number of colors in palette");
  200570. }
  200571. else
  200572. {
  200573. png_warning(png_ptr, "Invalid number of colors in palette");
  200574. return;
  200575. }
  200576. }
  200577. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  200578. {
  200579. png_warning(png_ptr,
  200580. "Ignoring request to write a PLTE chunk in grayscale PNG");
  200581. return;
  200582. }
  200583. png_ptr->num_palette = (png_uint_16)num_pal;
  200584. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  200585. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  200586. #ifndef PNG_NO_POINTER_INDEXING
  200587. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  200588. {
  200589. buf[0] = pal_ptr->red;
  200590. buf[1] = pal_ptr->green;
  200591. buf[2] = pal_ptr->blue;
  200592. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200593. }
  200594. #else
  200595. /* This is a little slower but some buggy compilers need to do this instead */
  200596. pal_ptr=palette;
  200597. for (i = 0; i < num_pal; i++)
  200598. {
  200599. buf[0] = pal_ptr[i].red;
  200600. buf[1] = pal_ptr[i].green;
  200601. buf[2] = pal_ptr[i].blue;
  200602. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200603. }
  200604. #endif
  200605. png_write_chunk_end(png_ptr);
  200606. png_ptr->mode |= PNG_HAVE_PLTE;
  200607. }
  200608. /* write an IDAT chunk */
  200609. void /* PRIVATE */
  200610. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  200611. {
  200612. #ifdef PNG_USE_LOCAL_ARRAYS
  200613. PNG_IDAT;
  200614. #endif
  200615. png_debug(1, "in png_write_IDAT\n");
  200616. /* Optimize the CMF field in the zlib stream. */
  200617. /* This hack of the zlib stream is compliant to the stream specification. */
  200618. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  200619. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  200620. {
  200621. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  200622. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  200623. {
  200624. /* Avoid memory underflows and multiplication overflows. */
  200625. /* The conditions below are practically always satisfied;
  200626. however, they still must be checked. */
  200627. if (length >= 2 &&
  200628. png_ptr->height < 16384 && png_ptr->width < 16384)
  200629. {
  200630. png_uint_32 uncompressed_idat_size = png_ptr->height *
  200631. ((png_ptr->width *
  200632. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  200633. unsigned int z_cinfo = z_cmf >> 4;
  200634. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  200635. while (uncompressed_idat_size <= half_z_window_size &&
  200636. half_z_window_size >= 256)
  200637. {
  200638. z_cinfo--;
  200639. half_z_window_size >>= 1;
  200640. }
  200641. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  200642. if (data[0] != (png_byte)z_cmf)
  200643. {
  200644. data[0] = (png_byte)z_cmf;
  200645. data[1] &= 0xe0;
  200646. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  200647. }
  200648. }
  200649. }
  200650. else
  200651. png_error(png_ptr,
  200652. "Invalid zlib compression method or flags in IDAT");
  200653. }
  200654. png_write_chunk(png_ptr, png_IDAT, data, length);
  200655. png_ptr->mode |= PNG_HAVE_IDAT;
  200656. }
  200657. /* write an IEND chunk */
  200658. void /* PRIVATE */
  200659. png_write_IEND(png_structp png_ptr)
  200660. {
  200661. #ifdef PNG_USE_LOCAL_ARRAYS
  200662. PNG_IEND;
  200663. #endif
  200664. png_debug(1, "in png_write_IEND\n");
  200665. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  200666. (png_size_t)0);
  200667. png_ptr->mode |= PNG_HAVE_IEND;
  200668. }
  200669. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  200670. /* write a gAMA chunk */
  200671. #ifdef PNG_FLOATING_POINT_SUPPORTED
  200672. void /* PRIVATE */
  200673. png_write_gAMA(png_structp png_ptr, double file_gamma)
  200674. {
  200675. #ifdef PNG_USE_LOCAL_ARRAYS
  200676. PNG_gAMA;
  200677. #endif
  200678. png_uint_32 igamma;
  200679. png_byte buf[4];
  200680. png_debug(1, "in png_write_gAMA\n");
  200681. /* file_gamma is saved in 1/100,000ths */
  200682. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  200683. png_save_uint_32(buf, igamma);
  200684. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200685. }
  200686. #endif
  200687. #ifdef PNG_FIXED_POINT_SUPPORTED
  200688. void /* PRIVATE */
  200689. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  200690. {
  200691. #ifdef PNG_USE_LOCAL_ARRAYS
  200692. PNG_gAMA;
  200693. #endif
  200694. png_byte buf[4];
  200695. png_debug(1, "in png_write_gAMA\n");
  200696. /* file_gamma is saved in 1/100,000ths */
  200697. png_save_uint_32(buf, (png_uint_32)file_gamma);
  200698. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200699. }
  200700. #endif
  200701. #endif
  200702. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  200703. /* write a sRGB chunk */
  200704. void /* PRIVATE */
  200705. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  200706. {
  200707. #ifdef PNG_USE_LOCAL_ARRAYS
  200708. PNG_sRGB;
  200709. #endif
  200710. png_byte buf[1];
  200711. png_debug(1, "in png_write_sRGB\n");
  200712. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  200713. png_warning(png_ptr,
  200714. "Invalid sRGB rendering intent specified");
  200715. buf[0]=(png_byte)srgb_intent;
  200716. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  200717. }
  200718. #endif
  200719. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  200720. /* write an iCCP chunk */
  200721. void /* PRIVATE */
  200722. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  200723. png_charp profile, int profile_len)
  200724. {
  200725. #ifdef PNG_USE_LOCAL_ARRAYS
  200726. PNG_iCCP;
  200727. #endif
  200728. png_size_t name_len;
  200729. png_charp new_name;
  200730. compression_state comp;
  200731. int embedded_profile_len = 0;
  200732. png_debug(1, "in png_write_iCCP\n");
  200733. comp.num_output_ptr = 0;
  200734. comp.max_output_ptr = 0;
  200735. comp.output_ptr = NULL;
  200736. comp.input = NULL;
  200737. comp.input_len = 0;
  200738. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  200739. &new_name)) == 0)
  200740. {
  200741. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  200742. return;
  200743. }
  200744. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200745. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  200746. if (profile == NULL)
  200747. profile_len = 0;
  200748. if (profile_len > 3)
  200749. embedded_profile_len =
  200750. ((*( (png_bytep)profile ))<<24) |
  200751. ((*( (png_bytep)profile+1))<<16) |
  200752. ((*( (png_bytep)profile+2))<< 8) |
  200753. ((*( (png_bytep)profile+3)) );
  200754. if (profile_len < embedded_profile_len)
  200755. {
  200756. png_warning(png_ptr,
  200757. "Embedded profile length too large in iCCP chunk");
  200758. return;
  200759. }
  200760. if (profile_len > embedded_profile_len)
  200761. {
  200762. png_warning(png_ptr,
  200763. "Truncating profile to actual length in iCCP chunk");
  200764. profile_len = embedded_profile_len;
  200765. }
  200766. if (profile_len)
  200767. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  200768. PNG_COMPRESSION_TYPE_BASE, &comp);
  200769. /* make sure we include the NULL after the name and the compression type */
  200770. png_write_chunk_start(png_ptr, png_iCCP,
  200771. (png_uint_32)name_len+profile_len+2);
  200772. new_name[name_len+1]=0x00;
  200773. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  200774. if (profile_len)
  200775. png_write_compressed_data_out(png_ptr, &comp);
  200776. png_write_chunk_end(png_ptr);
  200777. png_free(png_ptr, new_name);
  200778. }
  200779. #endif
  200780. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  200781. /* write a sPLT chunk */
  200782. void /* PRIVATE */
  200783. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  200784. {
  200785. #ifdef PNG_USE_LOCAL_ARRAYS
  200786. PNG_sPLT;
  200787. #endif
  200788. png_size_t name_len;
  200789. png_charp new_name;
  200790. png_byte entrybuf[10];
  200791. int entry_size = (spalette->depth == 8 ? 6 : 10);
  200792. int palette_size = entry_size * spalette->nentries;
  200793. png_sPLT_entryp ep;
  200794. #ifdef PNG_NO_POINTER_INDEXING
  200795. int i;
  200796. #endif
  200797. png_debug(1, "in png_write_sPLT\n");
  200798. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  200799. spalette->name, &new_name))==0)
  200800. {
  200801. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  200802. return;
  200803. }
  200804. /* make sure we include the NULL after the name */
  200805. png_write_chunk_start(png_ptr, png_sPLT,
  200806. (png_uint_32)(name_len + 2 + palette_size));
  200807. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  200808. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  200809. /* loop through each palette entry, writing appropriately */
  200810. #ifndef PNG_NO_POINTER_INDEXING
  200811. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  200812. {
  200813. if (spalette->depth == 8)
  200814. {
  200815. entrybuf[0] = (png_byte)ep->red;
  200816. entrybuf[1] = (png_byte)ep->green;
  200817. entrybuf[2] = (png_byte)ep->blue;
  200818. entrybuf[3] = (png_byte)ep->alpha;
  200819. png_save_uint_16(entrybuf + 4, ep->frequency);
  200820. }
  200821. else
  200822. {
  200823. png_save_uint_16(entrybuf + 0, ep->red);
  200824. png_save_uint_16(entrybuf + 2, ep->green);
  200825. png_save_uint_16(entrybuf + 4, ep->blue);
  200826. png_save_uint_16(entrybuf + 6, ep->alpha);
  200827. png_save_uint_16(entrybuf + 8, ep->frequency);
  200828. }
  200829. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  200830. }
  200831. #else
  200832. ep=spalette->entries;
  200833. for (i=0; i>spalette->nentries; i++)
  200834. {
  200835. if (spalette->depth == 8)
  200836. {
  200837. entrybuf[0] = (png_byte)ep[i].red;
  200838. entrybuf[1] = (png_byte)ep[i].green;
  200839. entrybuf[2] = (png_byte)ep[i].blue;
  200840. entrybuf[3] = (png_byte)ep[i].alpha;
  200841. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  200842. }
  200843. else
  200844. {
  200845. png_save_uint_16(entrybuf + 0, ep[i].red);
  200846. png_save_uint_16(entrybuf + 2, ep[i].green);
  200847. png_save_uint_16(entrybuf + 4, ep[i].blue);
  200848. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  200849. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  200850. }
  200851. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  200852. }
  200853. #endif
  200854. png_write_chunk_end(png_ptr);
  200855. png_free(png_ptr, new_name);
  200856. }
  200857. #endif
  200858. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  200859. /* write the sBIT chunk */
  200860. void /* PRIVATE */
  200861. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  200862. {
  200863. #ifdef PNG_USE_LOCAL_ARRAYS
  200864. PNG_sBIT;
  200865. #endif
  200866. png_byte buf[4];
  200867. png_size_t size;
  200868. png_debug(1, "in png_write_sBIT\n");
  200869. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  200870. if (color_type & PNG_COLOR_MASK_COLOR)
  200871. {
  200872. png_byte maxbits;
  200873. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  200874. png_ptr->usr_bit_depth);
  200875. if (sbit->red == 0 || sbit->red > maxbits ||
  200876. sbit->green == 0 || sbit->green > maxbits ||
  200877. sbit->blue == 0 || sbit->blue > maxbits)
  200878. {
  200879. png_warning(png_ptr, "Invalid sBIT depth specified");
  200880. return;
  200881. }
  200882. buf[0] = sbit->red;
  200883. buf[1] = sbit->green;
  200884. buf[2] = sbit->blue;
  200885. size = 3;
  200886. }
  200887. else
  200888. {
  200889. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  200890. {
  200891. png_warning(png_ptr, "Invalid sBIT depth specified");
  200892. return;
  200893. }
  200894. buf[0] = sbit->gray;
  200895. size = 1;
  200896. }
  200897. if (color_type & PNG_COLOR_MASK_ALPHA)
  200898. {
  200899. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  200900. {
  200901. png_warning(png_ptr, "Invalid sBIT depth specified");
  200902. return;
  200903. }
  200904. buf[size++] = sbit->alpha;
  200905. }
  200906. png_write_chunk(png_ptr, png_sBIT, buf, size);
  200907. }
  200908. #endif
  200909. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  200910. /* write the cHRM chunk */
  200911. #ifdef PNG_FLOATING_POINT_SUPPORTED
  200912. void /* PRIVATE */
  200913. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  200914. double red_x, double red_y, double green_x, double green_y,
  200915. double blue_x, double blue_y)
  200916. {
  200917. #ifdef PNG_USE_LOCAL_ARRAYS
  200918. PNG_cHRM;
  200919. #endif
  200920. png_byte buf[32];
  200921. png_uint_32 itemp;
  200922. png_debug(1, "in png_write_cHRM\n");
  200923. /* each value is saved in 1/100,000ths */
  200924. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  200925. white_x + white_y > 1.0)
  200926. {
  200927. png_warning(png_ptr, "Invalid cHRM white point specified");
  200928. #if !defined(PNG_NO_CONSOLE_IO)
  200929. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  200930. #endif
  200931. return;
  200932. }
  200933. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  200934. png_save_uint_32(buf, itemp);
  200935. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  200936. png_save_uint_32(buf + 4, itemp);
  200937. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  200938. {
  200939. png_warning(png_ptr, "Invalid cHRM red point specified");
  200940. return;
  200941. }
  200942. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  200943. png_save_uint_32(buf + 8, itemp);
  200944. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  200945. png_save_uint_32(buf + 12, itemp);
  200946. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  200947. {
  200948. png_warning(png_ptr, "Invalid cHRM green point specified");
  200949. return;
  200950. }
  200951. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  200952. png_save_uint_32(buf + 16, itemp);
  200953. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  200954. png_save_uint_32(buf + 20, itemp);
  200955. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  200956. {
  200957. png_warning(png_ptr, "Invalid cHRM blue point specified");
  200958. return;
  200959. }
  200960. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  200961. png_save_uint_32(buf + 24, itemp);
  200962. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  200963. png_save_uint_32(buf + 28, itemp);
  200964. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  200965. }
  200966. #endif
  200967. #ifdef PNG_FIXED_POINT_SUPPORTED
  200968. void /* PRIVATE */
  200969. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  200970. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  200971. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  200972. png_fixed_point blue_y)
  200973. {
  200974. #ifdef PNG_USE_LOCAL_ARRAYS
  200975. PNG_cHRM;
  200976. #endif
  200977. png_byte buf[32];
  200978. png_debug(1, "in png_write_cHRM\n");
  200979. /* each value is saved in 1/100,000ths */
  200980. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  200981. {
  200982. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  200983. #if !defined(PNG_NO_CONSOLE_IO)
  200984. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  200985. #endif
  200986. return;
  200987. }
  200988. png_save_uint_32(buf, (png_uint_32)white_x);
  200989. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  200990. if (red_x + red_y > 100000L)
  200991. {
  200992. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  200993. return;
  200994. }
  200995. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  200996. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  200997. if (green_x + green_y > 100000L)
  200998. {
  200999. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201000. return;
  201001. }
  201002. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201003. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201004. if (blue_x + blue_y > 100000L)
  201005. {
  201006. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201007. return;
  201008. }
  201009. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201010. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201011. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201012. }
  201013. #endif
  201014. #endif
  201015. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201016. /* write the tRNS chunk */
  201017. void /* PRIVATE */
  201018. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201019. int num_trans, int color_type)
  201020. {
  201021. #ifdef PNG_USE_LOCAL_ARRAYS
  201022. PNG_tRNS;
  201023. #endif
  201024. png_byte buf[6];
  201025. png_debug(1, "in png_write_tRNS\n");
  201026. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201027. {
  201028. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201029. {
  201030. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201031. return;
  201032. }
  201033. /* write the chunk out as it is */
  201034. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201035. }
  201036. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201037. {
  201038. /* one 16 bit value */
  201039. if(tran->gray >= (1 << png_ptr->bit_depth))
  201040. {
  201041. png_warning(png_ptr,
  201042. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201043. return;
  201044. }
  201045. png_save_uint_16(buf, tran->gray);
  201046. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201047. }
  201048. else if (color_type == PNG_COLOR_TYPE_RGB)
  201049. {
  201050. /* three 16 bit values */
  201051. png_save_uint_16(buf, tran->red);
  201052. png_save_uint_16(buf + 2, tran->green);
  201053. png_save_uint_16(buf + 4, tran->blue);
  201054. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201055. {
  201056. png_warning(png_ptr,
  201057. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201058. return;
  201059. }
  201060. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201061. }
  201062. else
  201063. {
  201064. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201065. }
  201066. }
  201067. #endif
  201068. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201069. /* write the background chunk */
  201070. void /* PRIVATE */
  201071. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201072. {
  201073. #ifdef PNG_USE_LOCAL_ARRAYS
  201074. PNG_bKGD;
  201075. #endif
  201076. png_byte buf[6];
  201077. png_debug(1, "in png_write_bKGD\n");
  201078. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201079. {
  201080. if (
  201081. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201082. (png_ptr->num_palette ||
  201083. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201084. #endif
  201085. back->index > png_ptr->num_palette)
  201086. {
  201087. png_warning(png_ptr, "Invalid background palette index");
  201088. return;
  201089. }
  201090. buf[0] = back->index;
  201091. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201092. }
  201093. else if (color_type & PNG_COLOR_MASK_COLOR)
  201094. {
  201095. png_save_uint_16(buf, back->red);
  201096. png_save_uint_16(buf + 2, back->green);
  201097. png_save_uint_16(buf + 4, back->blue);
  201098. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201099. {
  201100. png_warning(png_ptr,
  201101. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201102. return;
  201103. }
  201104. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201105. }
  201106. else
  201107. {
  201108. if(back->gray >= (1 << png_ptr->bit_depth))
  201109. {
  201110. png_warning(png_ptr,
  201111. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201112. return;
  201113. }
  201114. png_save_uint_16(buf, back->gray);
  201115. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201116. }
  201117. }
  201118. #endif
  201119. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201120. /* write the histogram */
  201121. void /* PRIVATE */
  201122. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201123. {
  201124. #ifdef PNG_USE_LOCAL_ARRAYS
  201125. PNG_hIST;
  201126. #endif
  201127. int i;
  201128. png_byte buf[3];
  201129. png_debug(1, "in png_write_hIST\n");
  201130. if (num_hist > (int)png_ptr->num_palette)
  201131. {
  201132. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201133. png_ptr->num_palette);
  201134. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201135. return;
  201136. }
  201137. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201138. for (i = 0; i < num_hist; i++)
  201139. {
  201140. png_save_uint_16(buf, hist[i]);
  201141. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201142. }
  201143. png_write_chunk_end(png_ptr);
  201144. }
  201145. #endif
  201146. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201147. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201148. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201149. * and if invalid, correct the keyword rather than discarding the entire
  201150. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201151. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201152. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201153. *
  201154. * The new_key is allocated to hold the corrected keyword and must be freed
  201155. * by the calling routine. This avoids problems with trying to write to
  201156. * static keywords without having to have duplicate copies of the strings.
  201157. */
  201158. png_size_t /* PRIVATE */
  201159. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201160. {
  201161. png_size_t key_len;
  201162. png_charp kp, dp;
  201163. int kflag;
  201164. int kwarn=0;
  201165. png_debug(1, "in png_check_keyword\n");
  201166. *new_key = NULL;
  201167. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201168. {
  201169. png_warning(png_ptr, "zero length keyword");
  201170. return ((png_size_t)0);
  201171. }
  201172. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201173. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201174. if (*new_key == NULL)
  201175. {
  201176. png_warning(png_ptr, "Out of memory while procesing keyword");
  201177. return ((png_size_t)0);
  201178. }
  201179. /* Replace non-printing characters with a blank and print a warning */
  201180. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201181. {
  201182. if ((png_byte)*kp < 0x20 ||
  201183. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201184. {
  201185. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201186. char msg[40];
  201187. png_snprintf(msg, 40,
  201188. "invalid keyword character 0x%02X", (png_byte)*kp);
  201189. png_warning(png_ptr, msg);
  201190. #else
  201191. png_warning(png_ptr, "invalid character in keyword");
  201192. #endif
  201193. *dp = ' ';
  201194. }
  201195. else
  201196. {
  201197. *dp = *kp;
  201198. }
  201199. }
  201200. *dp = '\0';
  201201. /* Remove any trailing white space. */
  201202. kp = *new_key + key_len - 1;
  201203. if (*kp == ' ')
  201204. {
  201205. png_warning(png_ptr, "trailing spaces removed from keyword");
  201206. while (*kp == ' ')
  201207. {
  201208. *(kp--) = '\0';
  201209. key_len--;
  201210. }
  201211. }
  201212. /* Remove any leading white space. */
  201213. kp = *new_key;
  201214. if (*kp == ' ')
  201215. {
  201216. png_warning(png_ptr, "leading spaces removed from keyword");
  201217. while (*kp == ' ')
  201218. {
  201219. kp++;
  201220. key_len--;
  201221. }
  201222. }
  201223. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201224. /* Remove multiple internal spaces. */
  201225. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201226. {
  201227. if (*kp == ' ' && kflag == 0)
  201228. {
  201229. *(dp++) = *kp;
  201230. kflag = 1;
  201231. }
  201232. else if (*kp == ' ')
  201233. {
  201234. key_len--;
  201235. kwarn=1;
  201236. }
  201237. else
  201238. {
  201239. *(dp++) = *kp;
  201240. kflag = 0;
  201241. }
  201242. }
  201243. *dp = '\0';
  201244. if(kwarn)
  201245. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201246. if (key_len == 0)
  201247. {
  201248. png_free(png_ptr, *new_key);
  201249. *new_key=NULL;
  201250. png_warning(png_ptr, "Zero length keyword");
  201251. }
  201252. if (key_len > 79)
  201253. {
  201254. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201255. new_key[79] = '\0';
  201256. key_len = 79;
  201257. }
  201258. return (key_len);
  201259. }
  201260. #endif
  201261. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201262. /* write a tEXt chunk */
  201263. void /* PRIVATE */
  201264. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  201265. png_size_t text_len)
  201266. {
  201267. #ifdef PNG_USE_LOCAL_ARRAYS
  201268. PNG_tEXt;
  201269. #endif
  201270. png_size_t key_len;
  201271. png_charp new_key;
  201272. png_debug(1, "in png_write_tEXt\n");
  201273. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201274. {
  201275. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  201276. return;
  201277. }
  201278. if (text == NULL || *text == '\0')
  201279. text_len = 0;
  201280. else
  201281. text_len = png_strlen(text);
  201282. /* make sure we include the 0 after the key */
  201283. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  201284. /*
  201285. * We leave it to the application to meet PNG-1.0 requirements on the
  201286. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201287. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201288. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201289. */
  201290. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201291. if (text_len)
  201292. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  201293. png_write_chunk_end(png_ptr);
  201294. png_free(png_ptr, new_key);
  201295. }
  201296. #endif
  201297. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  201298. /* write a compressed text chunk */
  201299. void /* PRIVATE */
  201300. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  201301. png_size_t text_len, int compression)
  201302. {
  201303. #ifdef PNG_USE_LOCAL_ARRAYS
  201304. PNG_zTXt;
  201305. #endif
  201306. png_size_t key_len;
  201307. char buf[1];
  201308. png_charp new_key;
  201309. compression_state comp;
  201310. png_debug(1, "in png_write_zTXt\n");
  201311. comp.num_output_ptr = 0;
  201312. comp.max_output_ptr = 0;
  201313. comp.output_ptr = NULL;
  201314. comp.input = NULL;
  201315. comp.input_len = 0;
  201316. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201317. {
  201318. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201319. return;
  201320. }
  201321. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201322. {
  201323. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201324. png_free(png_ptr, new_key);
  201325. return;
  201326. }
  201327. text_len = png_strlen(text);
  201328. /* compute the compressed data; do it now for the length */
  201329. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201330. &comp);
  201331. /* write start of chunk */
  201332. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201333. (key_len+text_len+2));
  201334. /* write key */
  201335. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201336. png_free(png_ptr, new_key);
  201337. buf[0] = (png_byte)compression;
  201338. /* write compression */
  201339. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201340. /* write the compressed data */
  201341. png_write_compressed_data_out(png_ptr, &comp);
  201342. /* close the chunk */
  201343. png_write_chunk_end(png_ptr);
  201344. }
  201345. #endif
  201346. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201347. /* write an iTXt chunk */
  201348. void /* PRIVATE */
  201349. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201350. png_charp lang, png_charp lang_key, png_charp text)
  201351. {
  201352. #ifdef PNG_USE_LOCAL_ARRAYS
  201353. PNG_iTXt;
  201354. #endif
  201355. png_size_t lang_len, key_len, lang_key_len, text_len;
  201356. png_charp new_lang, new_key;
  201357. png_byte cbuf[2];
  201358. compression_state comp;
  201359. png_debug(1, "in png_write_iTXt\n");
  201360. comp.num_output_ptr = 0;
  201361. comp.max_output_ptr = 0;
  201362. comp.output_ptr = NULL;
  201363. comp.input = NULL;
  201364. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201365. {
  201366. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201367. return;
  201368. }
  201369. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201370. {
  201371. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201372. new_lang = NULL;
  201373. lang_len = 0;
  201374. }
  201375. if (lang_key == NULL)
  201376. lang_key_len = 0;
  201377. else
  201378. lang_key_len = png_strlen(lang_key);
  201379. if (text == NULL)
  201380. text_len = 0;
  201381. else
  201382. text_len = png_strlen(text);
  201383. /* compute the compressed data; do it now for the length */
  201384. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  201385. &comp);
  201386. /* make sure we include the compression flag, the compression byte,
  201387. * and the NULs after the key, lang, and lang_key parts */
  201388. png_write_chunk_start(png_ptr, png_iTXt,
  201389. (png_uint_32)(
  201390. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  201391. + key_len
  201392. + lang_len
  201393. + lang_key_len
  201394. + text_len));
  201395. /*
  201396. * We leave it to the application to meet PNG-1.0 requirements on the
  201397. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201398. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201399. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201400. */
  201401. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201402. /* set the compression flag */
  201403. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  201404. compression == PNG_TEXT_COMPRESSION_NONE)
  201405. cbuf[0] = 0;
  201406. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  201407. cbuf[0] = 1;
  201408. /* set the compression method */
  201409. cbuf[1] = 0;
  201410. png_write_chunk_data(png_ptr, cbuf, 2);
  201411. cbuf[0] = 0;
  201412. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  201413. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  201414. png_write_compressed_data_out(png_ptr, &comp);
  201415. png_write_chunk_end(png_ptr);
  201416. png_free(png_ptr, new_key);
  201417. if (new_lang)
  201418. png_free(png_ptr, new_lang);
  201419. }
  201420. #endif
  201421. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  201422. /* write the oFFs chunk */
  201423. void /* PRIVATE */
  201424. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  201425. int unit_type)
  201426. {
  201427. #ifdef PNG_USE_LOCAL_ARRAYS
  201428. PNG_oFFs;
  201429. #endif
  201430. png_byte buf[9];
  201431. png_debug(1, "in png_write_oFFs\n");
  201432. if (unit_type >= PNG_OFFSET_LAST)
  201433. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  201434. png_save_int_32(buf, x_offset);
  201435. png_save_int_32(buf + 4, y_offset);
  201436. buf[8] = (png_byte)unit_type;
  201437. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  201438. }
  201439. #endif
  201440. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  201441. /* write the pCAL chunk (described in the PNG extensions document) */
  201442. void /* PRIVATE */
  201443. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  201444. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  201445. {
  201446. #ifdef PNG_USE_LOCAL_ARRAYS
  201447. PNG_pCAL;
  201448. #endif
  201449. png_size_t purpose_len, units_len, total_len;
  201450. png_uint_32p params_len;
  201451. png_byte buf[10];
  201452. png_charp new_purpose;
  201453. int i;
  201454. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  201455. if (type >= PNG_EQUATION_LAST)
  201456. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  201457. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  201458. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  201459. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  201460. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  201461. total_len = purpose_len + units_len + 10;
  201462. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  201463. *png_sizeof(png_uint_32)));
  201464. /* Find the length of each parameter, making sure we don't count the
  201465. null terminator for the last parameter. */
  201466. for (i = 0; i < nparams; i++)
  201467. {
  201468. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  201469. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  201470. total_len += (png_size_t)params_len[i];
  201471. }
  201472. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  201473. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  201474. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  201475. png_save_int_32(buf, X0);
  201476. png_save_int_32(buf + 4, X1);
  201477. buf[8] = (png_byte)type;
  201478. buf[9] = (png_byte)nparams;
  201479. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  201480. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  201481. png_free(png_ptr, new_purpose);
  201482. for (i = 0; i < nparams; i++)
  201483. {
  201484. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  201485. (png_size_t)params_len[i]);
  201486. }
  201487. png_free(png_ptr, params_len);
  201488. png_write_chunk_end(png_ptr);
  201489. }
  201490. #endif
  201491. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  201492. /* write the sCAL chunk */
  201493. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  201494. void /* PRIVATE */
  201495. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  201496. {
  201497. #ifdef PNG_USE_LOCAL_ARRAYS
  201498. PNG_sCAL;
  201499. #endif
  201500. char buf[64];
  201501. png_size_t total_len;
  201502. png_debug(1, "in png_write_sCAL\n");
  201503. buf[0] = (char)unit;
  201504. #if defined(_WIN32_WCE)
  201505. /* sprintf() function is not supported on WindowsCE */
  201506. {
  201507. wchar_t wc_buf[32];
  201508. size_t wc_len;
  201509. swprintf(wc_buf, TEXT("%12.12e"), width);
  201510. wc_len = wcslen(wc_buf);
  201511. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  201512. total_len = wc_len + 2;
  201513. swprintf(wc_buf, TEXT("%12.12e"), height);
  201514. wc_len = wcslen(wc_buf);
  201515. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  201516. NULL, NULL);
  201517. total_len += wc_len;
  201518. }
  201519. #else
  201520. png_snprintf(buf + 1, 63, "%12.12e", width);
  201521. total_len = 1 + png_strlen(buf + 1) + 1;
  201522. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  201523. total_len += png_strlen(buf + total_len);
  201524. #endif
  201525. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201526. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  201527. }
  201528. #else
  201529. #ifdef PNG_FIXED_POINT_SUPPORTED
  201530. void /* PRIVATE */
  201531. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  201532. png_charp height)
  201533. {
  201534. #ifdef PNG_USE_LOCAL_ARRAYS
  201535. PNG_sCAL;
  201536. #endif
  201537. png_byte buf[64];
  201538. png_size_t wlen, hlen, total_len;
  201539. png_debug(1, "in png_write_sCAL_s\n");
  201540. wlen = png_strlen(width);
  201541. hlen = png_strlen(height);
  201542. total_len = wlen + hlen + 2;
  201543. if (total_len > 64)
  201544. {
  201545. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  201546. return;
  201547. }
  201548. buf[0] = (png_byte)unit;
  201549. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  201550. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  201551. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201552. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  201553. }
  201554. #endif
  201555. #endif
  201556. #endif
  201557. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  201558. /* write the pHYs chunk */
  201559. void /* PRIVATE */
  201560. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  201561. png_uint_32 y_pixels_per_unit,
  201562. int unit_type)
  201563. {
  201564. #ifdef PNG_USE_LOCAL_ARRAYS
  201565. PNG_pHYs;
  201566. #endif
  201567. png_byte buf[9];
  201568. png_debug(1, "in png_write_pHYs\n");
  201569. if (unit_type >= PNG_RESOLUTION_LAST)
  201570. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  201571. png_save_uint_32(buf, x_pixels_per_unit);
  201572. png_save_uint_32(buf + 4, y_pixels_per_unit);
  201573. buf[8] = (png_byte)unit_type;
  201574. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  201575. }
  201576. #endif
  201577. #if defined(PNG_WRITE_tIME_SUPPORTED)
  201578. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  201579. * or png_convert_from_time_t(), or fill in the structure yourself.
  201580. */
  201581. void /* PRIVATE */
  201582. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  201583. {
  201584. #ifdef PNG_USE_LOCAL_ARRAYS
  201585. PNG_tIME;
  201586. #endif
  201587. png_byte buf[7];
  201588. png_debug(1, "in png_write_tIME\n");
  201589. if (mod_time->month > 12 || mod_time->month < 1 ||
  201590. mod_time->day > 31 || mod_time->day < 1 ||
  201591. mod_time->hour > 23 || mod_time->second > 60)
  201592. {
  201593. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  201594. return;
  201595. }
  201596. png_save_uint_16(buf, mod_time->year);
  201597. buf[2] = mod_time->month;
  201598. buf[3] = mod_time->day;
  201599. buf[4] = mod_time->hour;
  201600. buf[5] = mod_time->minute;
  201601. buf[6] = mod_time->second;
  201602. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  201603. }
  201604. #endif
  201605. /* initializes the row writing capability of libpng */
  201606. void /* PRIVATE */
  201607. png_write_start_row(png_structp png_ptr)
  201608. {
  201609. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201610. #ifdef PNG_USE_LOCAL_ARRAYS
  201611. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201612. /* start of interlace block */
  201613. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201614. /* offset to next interlace block */
  201615. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201616. /* start of interlace block in the y direction */
  201617. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201618. /* offset to next interlace block in the y direction */
  201619. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201620. #endif
  201621. #endif
  201622. png_size_t buf_size;
  201623. png_debug(1, "in png_write_start_row\n");
  201624. buf_size = (png_size_t)(PNG_ROWBYTES(
  201625. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  201626. /* set up row buffer */
  201627. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201628. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  201629. #ifndef PNG_NO_WRITE_FILTERING
  201630. /* set up filtering buffer, if using this filter */
  201631. if (png_ptr->do_filter & PNG_FILTER_SUB)
  201632. {
  201633. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  201634. (png_ptr->rowbytes + 1));
  201635. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  201636. }
  201637. /* We only need to keep the previous row if we are using one of these. */
  201638. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  201639. {
  201640. /* set up previous row buffer */
  201641. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201642. png_memset(png_ptr->prev_row, 0, buf_size);
  201643. if (png_ptr->do_filter & PNG_FILTER_UP)
  201644. {
  201645. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  201646. (png_ptr->rowbytes + 1));
  201647. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  201648. }
  201649. if (png_ptr->do_filter & PNG_FILTER_AVG)
  201650. {
  201651. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  201652. (png_ptr->rowbytes + 1));
  201653. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  201654. }
  201655. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  201656. {
  201657. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  201658. (png_ptr->rowbytes + 1));
  201659. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  201660. }
  201661. #endif /* PNG_NO_WRITE_FILTERING */
  201662. }
  201663. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201664. /* if interlaced, we need to set up width and height of pass */
  201665. if (png_ptr->interlaced)
  201666. {
  201667. if (!(png_ptr->transformations & PNG_INTERLACE))
  201668. {
  201669. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  201670. png_pass_ystart[0]) / png_pass_yinc[0];
  201671. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  201672. png_pass_start[0]) / png_pass_inc[0];
  201673. }
  201674. else
  201675. {
  201676. png_ptr->num_rows = png_ptr->height;
  201677. png_ptr->usr_width = png_ptr->width;
  201678. }
  201679. }
  201680. else
  201681. #endif
  201682. {
  201683. png_ptr->num_rows = png_ptr->height;
  201684. png_ptr->usr_width = png_ptr->width;
  201685. }
  201686. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201687. png_ptr->zstream.next_out = png_ptr->zbuf;
  201688. }
  201689. /* Internal use only. Called when finished processing a row of data. */
  201690. void /* PRIVATE */
  201691. png_write_finish_row(png_structp png_ptr)
  201692. {
  201693. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201694. #ifdef PNG_USE_LOCAL_ARRAYS
  201695. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201696. /* start of interlace block */
  201697. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201698. /* offset to next interlace block */
  201699. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201700. /* start of interlace block in the y direction */
  201701. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201702. /* offset to next interlace block in the y direction */
  201703. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201704. #endif
  201705. #endif
  201706. int ret;
  201707. png_debug(1, "in png_write_finish_row\n");
  201708. /* next row */
  201709. png_ptr->row_number++;
  201710. /* see if we are done */
  201711. if (png_ptr->row_number < png_ptr->num_rows)
  201712. return;
  201713. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201714. /* if interlaced, go to next pass */
  201715. if (png_ptr->interlaced)
  201716. {
  201717. png_ptr->row_number = 0;
  201718. if (png_ptr->transformations & PNG_INTERLACE)
  201719. {
  201720. png_ptr->pass++;
  201721. }
  201722. else
  201723. {
  201724. /* loop until we find a non-zero width or height pass */
  201725. do
  201726. {
  201727. png_ptr->pass++;
  201728. if (png_ptr->pass >= 7)
  201729. break;
  201730. png_ptr->usr_width = (png_ptr->width +
  201731. png_pass_inc[png_ptr->pass] - 1 -
  201732. png_pass_start[png_ptr->pass]) /
  201733. png_pass_inc[png_ptr->pass];
  201734. png_ptr->num_rows = (png_ptr->height +
  201735. png_pass_yinc[png_ptr->pass] - 1 -
  201736. png_pass_ystart[png_ptr->pass]) /
  201737. png_pass_yinc[png_ptr->pass];
  201738. if (png_ptr->transformations & PNG_INTERLACE)
  201739. break;
  201740. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  201741. }
  201742. /* reset the row above the image for the next pass */
  201743. if (png_ptr->pass < 7)
  201744. {
  201745. if (png_ptr->prev_row != NULL)
  201746. png_memset(png_ptr->prev_row, 0,
  201747. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  201748. png_ptr->usr_bit_depth,png_ptr->width))+1);
  201749. return;
  201750. }
  201751. }
  201752. #endif
  201753. /* if we get here, we've just written the last row, so we need
  201754. to flush the compressor */
  201755. do
  201756. {
  201757. /* tell the compressor we are done */
  201758. ret = deflate(&png_ptr->zstream, Z_FINISH);
  201759. /* check for an error */
  201760. if (ret == Z_OK)
  201761. {
  201762. /* check to see if we need more room */
  201763. if (!(png_ptr->zstream.avail_out))
  201764. {
  201765. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  201766. png_ptr->zstream.next_out = png_ptr->zbuf;
  201767. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201768. }
  201769. }
  201770. else if (ret != Z_STREAM_END)
  201771. {
  201772. if (png_ptr->zstream.msg != NULL)
  201773. png_error(png_ptr, png_ptr->zstream.msg);
  201774. else
  201775. png_error(png_ptr, "zlib error");
  201776. }
  201777. } while (ret != Z_STREAM_END);
  201778. /* write any extra space */
  201779. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  201780. {
  201781. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  201782. png_ptr->zstream.avail_out);
  201783. }
  201784. deflateReset(&png_ptr->zstream);
  201785. png_ptr->zstream.data_type = Z_BINARY;
  201786. }
  201787. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  201788. /* Pick out the correct pixels for the interlace pass.
  201789. * The basic idea here is to go through the row with a source
  201790. * pointer and a destination pointer (sp and dp), and copy the
  201791. * correct pixels for the pass. As the row gets compacted,
  201792. * sp will always be >= dp, so we should never overwrite anything.
  201793. * See the default: case for the easiest code to understand.
  201794. */
  201795. void /* PRIVATE */
  201796. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  201797. {
  201798. #ifdef PNG_USE_LOCAL_ARRAYS
  201799. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201800. /* start of interlace block */
  201801. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201802. /* offset to next interlace block */
  201803. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201804. #endif
  201805. png_debug(1, "in png_do_write_interlace\n");
  201806. /* we don't have to do anything on the last pass (6) */
  201807. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  201808. if (row != NULL && row_info != NULL && pass < 6)
  201809. #else
  201810. if (pass < 6)
  201811. #endif
  201812. {
  201813. /* each pixel depth is handled separately */
  201814. switch (row_info->pixel_depth)
  201815. {
  201816. case 1:
  201817. {
  201818. png_bytep sp;
  201819. png_bytep dp;
  201820. int shift;
  201821. int d;
  201822. int value;
  201823. png_uint_32 i;
  201824. png_uint_32 row_width = row_info->width;
  201825. dp = row;
  201826. d = 0;
  201827. shift = 7;
  201828. for (i = png_pass_start[pass]; i < row_width;
  201829. i += png_pass_inc[pass])
  201830. {
  201831. sp = row + (png_size_t)(i >> 3);
  201832. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  201833. d |= (value << shift);
  201834. if (shift == 0)
  201835. {
  201836. shift = 7;
  201837. *dp++ = (png_byte)d;
  201838. d = 0;
  201839. }
  201840. else
  201841. shift--;
  201842. }
  201843. if (shift != 7)
  201844. *dp = (png_byte)d;
  201845. break;
  201846. }
  201847. case 2:
  201848. {
  201849. png_bytep sp;
  201850. png_bytep dp;
  201851. int shift;
  201852. int d;
  201853. int value;
  201854. png_uint_32 i;
  201855. png_uint_32 row_width = row_info->width;
  201856. dp = row;
  201857. shift = 6;
  201858. d = 0;
  201859. for (i = png_pass_start[pass]; i < row_width;
  201860. i += png_pass_inc[pass])
  201861. {
  201862. sp = row + (png_size_t)(i >> 2);
  201863. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  201864. d |= (value << shift);
  201865. if (shift == 0)
  201866. {
  201867. shift = 6;
  201868. *dp++ = (png_byte)d;
  201869. d = 0;
  201870. }
  201871. else
  201872. shift -= 2;
  201873. }
  201874. if (shift != 6)
  201875. *dp = (png_byte)d;
  201876. break;
  201877. }
  201878. case 4:
  201879. {
  201880. png_bytep sp;
  201881. png_bytep dp;
  201882. int shift;
  201883. int d;
  201884. int value;
  201885. png_uint_32 i;
  201886. png_uint_32 row_width = row_info->width;
  201887. dp = row;
  201888. shift = 4;
  201889. d = 0;
  201890. for (i = png_pass_start[pass]; i < row_width;
  201891. i += png_pass_inc[pass])
  201892. {
  201893. sp = row + (png_size_t)(i >> 1);
  201894. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  201895. d |= (value << shift);
  201896. if (shift == 0)
  201897. {
  201898. shift = 4;
  201899. *dp++ = (png_byte)d;
  201900. d = 0;
  201901. }
  201902. else
  201903. shift -= 4;
  201904. }
  201905. if (shift != 4)
  201906. *dp = (png_byte)d;
  201907. break;
  201908. }
  201909. default:
  201910. {
  201911. png_bytep sp;
  201912. png_bytep dp;
  201913. png_uint_32 i;
  201914. png_uint_32 row_width = row_info->width;
  201915. png_size_t pixel_bytes;
  201916. /* start at the beginning */
  201917. dp = row;
  201918. /* find out how many bytes each pixel takes up */
  201919. pixel_bytes = (row_info->pixel_depth >> 3);
  201920. /* loop through the row, only looking at the pixels that
  201921. matter */
  201922. for (i = png_pass_start[pass]; i < row_width;
  201923. i += png_pass_inc[pass])
  201924. {
  201925. /* find out where the original pixel is */
  201926. sp = row + (png_size_t)i * pixel_bytes;
  201927. /* move the pixel */
  201928. if (dp != sp)
  201929. png_memcpy(dp, sp, pixel_bytes);
  201930. /* next pixel */
  201931. dp += pixel_bytes;
  201932. }
  201933. break;
  201934. }
  201935. }
  201936. /* set new row width */
  201937. row_info->width = (row_info->width +
  201938. png_pass_inc[pass] - 1 -
  201939. png_pass_start[pass]) /
  201940. png_pass_inc[pass];
  201941. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  201942. row_info->width);
  201943. }
  201944. }
  201945. #endif
  201946. /* This filters the row, chooses which filter to use, if it has not already
  201947. * been specified by the application, and then writes the row out with the
  201948. * chosen filter.
  201949. */
  201950. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  201951. #define PNG_HISHIFT 10
  201952. #define PNG_LOMASK ((png_uint_32)0xffffL)
  201953. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  201954. void /* PRIVATE */
  201955. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  201956. {
  201957. png_bytep best_row;
  201958. #ifndef PNG_NO_WRITE_FILTER
  201959. png_bytep prev_row, row_buf;
  201960. png_uint_32 mins, bpp;
  201961. png_byte filter_to_do = png_ptr->do_filter;
  201962. png_uint_32 row_bytes = row_info->rowbytes;
  201963. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201964. int num_p_filters = (int)png_ptr->num_prev_filters;
  201965. #endif
  201966. png_debug(1, "in png_write_find_filter\n");
  201967. /* find out how many bytes offset each pixel is */
  201968. bpp = (row_info->pixel_depth + 7) >> 3;
  201969. prev_row = png_ptr->prev_row;
  201970. #endif
  201971. best_row = png_ptr->row_buf;
  201972. #ifndef PNG_NO_WRITE_FILTER
  201973. row_buf = best_row;
  201974. mins = PNG_MAXSUM;
  201975. /* The prediction method we use is to find which method provides the
  201976. * smallest value when summing the absolute values of the distances
  201977. * from zero, using anything >= 128 as negative numbers. This is known
  201978. * as the "minimum sum of absolute differences" heuristic. Other
  201979. * heuristics are the "weighted minimum sum of absolute differences"
  201980. * (experimental and can in theory improve compression), and the "zlib
  201981. * predictive" method (not implemented yet), which does test compressions
  201982. * of lines using different filter methods, and then chooses the
  201983. * (series of) filter(s) that give minimum compressed data size (VERY
  201984. * computationally expensive).
  201985. *
  201986. * GRR 980525: consider also
  201987. * (1) minimum sum of absolute differences from running average (i.e.,
  201988. * keep running sum of non-absolute differences & count of bytes)
  201989. * [track dispersion, too? restart average if dispersion too large?]
  201990. * (1b) minimum sum of absolute differences from sliding average, probably
  201991. * with window size <= deflate window (usually 32K)
  201992. * (2) minimum sum of squared differences from zero or running average
  201993. * (i.e., ~ root-mean-square approach)
  201994. */
  201995. /* We don't need to test the 'no filter' case if this is the only filter
  201996. * that has been chosen, as it doesn't actually do anything to the data.
  201997. */
  201998. if ((filter_to_do & PNG_FILTER_NONE) &&
  201999. filter_to_do != PNG_FILTER_NONE)
  202000. {
  202001. png_bytep rp;
  202002. png_uint_32 sum = 0;
  202003. png_uint_32 i;
  202004. int v;
  202005. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202006. {
  202007. v = *rp;
  202008. sum += (v < 128) ? v : 256 - v;
  202009. }
  202010. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202011. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202012. {
  202013. png_uint_32 sumhi, sumlo;
  202014. int j;
  202015. sumlo = sum & PNG_LOMASK;
  202016. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202017. /* Reduce the sum if we match any of the previous rows */
  202018. for (j = 0; j < num_p_filters; j++)
  202019. {
  202020. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202021. {
  202022. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202023. PNG_WEIGHT_SHIFT;
  202024. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202025. PNG_WEIGHT_SHIFT;
  202026. }
  202027. }
  202028. /* Factor in the cost of this filter (this is here for completeness,
  202029. * but it makes no sense to have a "cost" for the NONE filter, as
  202030. * it has the minimum possible computational cost - none).
  202031. */
  202032. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202033. PNG_COST_SHIFT;
  202034. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202035. PNG_COST_SHIFT;
  202036. if (sumhi > PNG_HIMASK)
  202037. sum = PNG_MAXSUM;
  202038. else
  202039. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202040. }
  202041. #endif
  202042. mins = sum;
  202043. }
  202044. /* sub filter */
  202045. if (filter_to_do == PNG_FILTER_SUB)
  202046. /* it's the only filter so no testing is needed */
  202047. {
  202048. png_bytep rp, lp, dp;
  202049. png_uint_32 i;
  202050. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202051. i++, rp++, dp++)
  202052. {
  202053. *dp = *rp;
  202054. }
  202055. for (lp = row_buf + 1; i < row_bytes;
  202056. i++, rp++, lp++, dp++)
  202057. {
  202058. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202059. }
  202060. best_row = png_ptr->sub_row;
  202061. }
  202062. else if (filter_to_do & PNG_FILTER_SUB)
  202063. {
  202064. png_bytep rp, dp, lp;
  202065. png_uint_32 sum = 0, lmins = mins;
  202066. png_uint_32 i;
  202067. int v;
  202068. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202069. /* We temporarily increase the "minimum sum" by the factor we
  202070. * would reduce the sum of this filter, so that we can do the
  202071. * early exit comparison without scaling the sum each time.
  202072. */
  202073. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202074. {
  202075. int j;
  202076. png_uint_32 lmhi, lmlo;
  202077. lmlo = lmins & PNG_LOMASK;
  202078. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202079. for (j = 0; j < num_p_filters; j++)
  202080. {
  202081. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202082. {
  202083. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202084. PNG_WEIGHT_SHIFT;
  202085. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202086. PNG_WEIGHT_SHIFT;
  202087. }
  202088. }
  202089. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202090. PNG_COST_SHIFT;
  202091. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202092. PNG_COST_SHIFT;
  202093. if (lmhi > PNG_HIMASK)
  202094. lmins = PNG_MAXSUM;
  202095. else
  202096. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202097. }
  202098. #endif
  202099. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202100. i++, rp++, dp++)
  202101. {
  202102. v = *dp = *rp;
  202103. sum += (v < 128) ? v : 256 - v;
  202104. }
  202105. for (lp = row_buf + 1; i < row_bytes;
  202106. i++, rp++, lp++, dp++)
  202107. {
  202108. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202109. sum += (v < 128) ? v : 256 - v;
  202110. if (sum > lmins) /* We are already worse, don't continue. */
  202111. break;
  202112. }
  202113. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202114. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202115. {
  202116. int j;
  202117. png_uint_32 sumhi, sumlo;
  202118. sumlo = sum & PNG_LOMASK;
  202119. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202120. for (j = 0; j < num_p_filters; j++)
  202121. {
  202122. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202123. {
  202124. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202125. PNG_WEIGHT_SHIFT;
  202126. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202127. PNG_WEIGHT_SHIFT;
  202128. }
  202129. }
  202130. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202131. PNG_COST_SHIFT;
  202132. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202133. PNG_COST_SHIFT;
  202134. if (sumhi > PNG_HIMASK)
  202135. sum = PNG_MAXSUM;
  202136. else
  202137. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202138. }
  202139. #endif
  202140. if (sum < mins)
  202141. {
  202142. mins = sum;
  202143. best_row = png_ptr->sub_row;
  202144. }
  202145. }
  202146. /* up filter */
  202147. if (filter_to_do == PNG_FILTER_UP)
  202148. {
  202149. png_bytep rp, dp, pp;
  202150. png_uint_32 i;
  202151. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202152. pp = prev_row + 1; i < row_bytes;
  202153. i++, rp++, pp++, dp++)
  202154. {
  202155. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202156. }
  202157. best_row = png_ptr->up_row;
  202158. }
  202159. else if (filter_to_do & PNG_FILTER_UP)
  202160. {
  202161. png_bytep rp, dp, pp;
  202162. png_uint_32 sum = 0, lmins = mins;
  202163. png_uint_32 i;
  202164. int v;
  202165. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202166. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202167. {
  202168. int j;
  202169. png_uint_32 lmhi, lmlo;
  202170. lmlo = lmins & PNG_LOMASK;
  202171. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202172. for (j = 0; j < num_p_filters; j++)
  202173. {
  202174. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202175. {
  202176. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202177. PNG_WEIGHT_SHIFT;
  202178. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202179. PNG_WEIGHT_SHIFT;
  202180. }
  202181. }
  202182. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202183. PNG_COST_SHIFT;
  202184. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202185. PNG_COST_SHIFT;
  202186. if (lmhi > PNG_HIMASK)
  202187. lmins = PNG_MAXSUM;
  202188. else
  202189. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202190. }
  202191. #endif
  202192. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202193. pp = prev_row + 1; i < row_bytes; i++)
  202194. {
  202195. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202196. sum += (v < 128) ? v : 256 - v;
  202197. if (sum > lmins) /* We are already worse, don't continue. */
  202198. break;
  202199. }
  202200. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202201. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202202. {
  202203. int j;
  202204. png_uint_32 sumhi, sumlo;
  202205. sumlo = sum & PNG_LOMASK;
  202206. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202207. for (j = 0; j < num_p_filters; j++)
  202208. {
  202209. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202210. {
  202211. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202212. PNG_WEIGHT_SHIFT;
  202213. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202214. PNG_WEIGHT_SHIFT;
  202215. }
  202216. }
  202217. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202218. PNG_COST_SHIFT;
  202219. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202220. PNG_COST_SHIFT;
  202221. if (sumhi > PNG_HIMASK)
  202222. sum = PNG_MAXSUM;
  202223. else
  202224. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202225. }
  202226. #endif
  202227. if (sum < mins)
  202228. {
  202229. mins = sum;
  202230. best_row = png_ptr->up_row;
  202231. }
  202232. }
  202233. /* avg filter */
  202234. if (filter_to_do == PNG_FILTER_AVG)
  202235. {
  202236. png_bytep rp, dp, pp, lp;
  202237. png_uint_32 i;
  202238. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202239. pp = prev_row + 1; i < bpp; i++)
  202240. {
  202241. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202242. }
  202243. for (lp = row_buf + 1; i < row_bytes; i++)
  202244. {
  202245. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202246. & 0xff);
  202247. }
  202248. best_row = png_ptr->avg_row;
  202249. }
  202250. else if (filter_to_do & PNG_FILTER_AVG)
  202251. {
  202252. png_bytep rp, dp, pp, lp;
  202253. png_uint_32 sum = 0, lmins = mins;
  202254. png_uint_32 i;
  202255. int v;
  202256. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202257. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202258. {
  202259. int j;
  202260. png_uint_32 lmhi, lmlo;
  202261. lmlo = lmins & PNG_LOMASK;
  202262. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202263. for (j = 0; j < num_p_filters; j++)
  202264. {
  202265. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  202266. {
  202267. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202268. PNG_WEIGHT_SHIFT;
  202269. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202270. PNG_WEIGHT_SHIFT;
  202271. }
  202272. }
  202273. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202274. PNG_COST_SHIFT;
  202275. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202276. PNG_COST_SHIFT;
  202277. if (lmhi > PNG_HIMASK)
  202278. lmins = PNG_MAXSUM;
  202279. else
  202280. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202281. }
  202282. #endif
  202283. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202284. pp = prev_row + 1; i < bpp; i++)
  202285. {
  202286. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202287. sum += (v < 128) ? v : 256 - v;
  202288. }
  202289. for (lp = row_buf + 1; i < row_bytes; i++)
  202290. {
  202291. v = *dp++ =
  202292. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  202293. sum += (v < 128) ? v : 256 - v;
  202294. if (sum > lmins) /* We are already worse, don't continue. */
  202295. break;
  202296. }
  202297. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202298. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202299. {
  202300. int j;
  202301. png_uint_32 sumhi, sumlo;
  202302. sumlo = sum & PNG_LOMASK;
  202303. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202304. for (j = 0; j < num_p_filters; j++)
  202305. {
  202306. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202307. {
  202308. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202309. PNG_WEIGHT_SHIFT;
  202310. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202311. PNG_WEIGHT_SHIFT;
  202312. }
  202313. }
  202314. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202315. PNG_COST_SHIFT;
  202316. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202317. PNG_COST_SHIFT;
  202318. if (sumhi > PNG_HIMASK)
  202319. sum = PNG_MAXSUM;
  202320. else
  202321. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202322. }
  202323. #endif
  202324. if (sum < mins)
  202325. {
  202326. mins = sum;
  202327. best_row = png_ptr->avg_row;
  202328. }
  202329. }
  202330. /* Paeth filter */
  202331. if (filter_to_do == PNG_FILTER_PAETH)
  202332. {
  202333. png_bytep rp, dp, pp, cp, lp;
  202334. png_uint_32 i;
  202335. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202336. pp = prev_row + 1; i < bpp; i++)
  202337. {
  202338. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202339. }
  202340. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202341. {
  202342. int a, b, c, pa, pb, pc, p;
  202343. b = *pp++;
  202344. c = *cp++;
  202345. a = *lp++;
  202346. p = b - c;
  202347. pc = a - c;
  202348. #ifdef PNG_USE_ABS
  202349. pa = abs(p);
  202350. pb = abs(pc);
  202351. pc = abs(p + pc);
  202352. #else
  202353. pa = p < 0 ? -p : p;
  202354. pb = pc < 0 ? -pc : pc;
  202355. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202356. #endif
  202357. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202358. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202359. }
  202360. best_row = png_ptr->paeth_row;
  202361. }
  202362. else if (filter_to_do & PNG_FILTER_PAETH)
  202363. {
  202364. png_bytep rp, dp, pp, cp, lp;
  202365. png_uint_32 sum = 0, lmins = mins;
  202366. png_uint_32 i;
  202367. int v;
  202368. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202369. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202370. {
  202371. int j;
  202372. png_uint_32 lmhi, lmlo;
  202373. lmlo = lmins & PNG_LOMASK;
  202374. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202375. for (j = 0; j < num_p_filters; j++)
  202376. {
  202377. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202378. {
  202379. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202380. PNG_WEIGHT_SHIFT;
  202381. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202382. PNG_WEIGHT_SHIFT;
  202383. }
  202384. }
  202385. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202386. PNG_COST_SHIFT;
  202387. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202388. PNG_COST_SHIFT;
  202389. if (lmhi > PNG_HIMASK)
  202390. lmins = PNG_MAXSUM;
  202391. else
  202392. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202393. }
  202394. #endif
  202395. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202396. pp = prev_row + 1; i < bpp; i++)
  202397. {
  202398. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202399. sum += (v < 128) ? v : 256 - v;
  202400. }
  202401. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202402. {
  202403. int a, b, c, pa, pb, pc, p;
  202404. b = *pp++;
  202405. c = *cp++;
  202406. a = *lp++;
  202407. #ifndef PNG_SLOW_PAETH
  202408. p = b - c;
  202409. pc = a - c;
  202410. #ifdef PNG_USE_ABS
  202411. pa = abs(p);
  202412. pb = abs(pc);
  202413. pc = abs(p + pc);
  202414. #else
  202415. pa = p < 0 ? -p : p;
  202416. pb = pc < 0 ? -pc : pc;
  202417. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202418. #endif
  202419. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202420. #else /* PNG_SLOW_PAETH */
  202421. p = a + b - c;
  202422. pa = abs(p - a);
  202423. pb = abs(p - b);
  202424. pc = abs(p - c);
  202425. if (pa <= pb && pa <= pc)
  202426. p = a;
  202427. else if (pb <= pc)
  202428. p = b;
  202429. else
  202430. p = c;
  202431. #endif /* PNG_SLOW_PAETH */
  202432. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202433. sum += (v < 128) ? v : 256 - v;
  202434. if (sum > lmins) /* We are already worse, don't continue. */
  202435. break;
  202436. }
  202437. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202438. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202439. {
  202440. int j;
  202441. png_uint_32 sumhi, sumlo;
  202442. sumlo = sum & PNG_LOMASK;
  202443. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202444. for (j = 0; j < num_p_filters; j++)
  202445. {
  202446. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202447. {
  202448. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202449. PNG_WEIGHT_SHIFT;
  202450. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202451. PNG_WEIGHT_SHIFT;
  202452. }
  202453. }
  202454. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202455. PNG_COST_SHIFT;
  202456. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202457. PNG_COST_SHIFT;
  202458. if (sumhi > PNG_HIMASK)
  202459. sum = PNG_MAXSUM;
  202460. else
  202461. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202462. }
  202463. #endif
  202464. if (sum < mins)
  202465. {
  202466. best_row = png_ptr->paeth_row;
  202467. }
  202468. }
  202469. #endif /* PNG_NO_WRITE_FILTER */
  202470. /* Do the actual writing of the filtered row data from the chosen filter. */
  202471. png_write_filtered_row(png_ptr, best_row);
  202472. #ifndef PNG_NO_WRITE_FILTER
  202473. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202474. /* Save the type of filter we picked this time for future calculations */
  202475. if (png_ptr->num_prev_filters > 0)
  202476. {
  202477. int j;
  202478. for (j = 1; j < num_p_filters; j++)
  202479. {
  202480. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  202481. }
  202482. png_ptr->prev_filters[j] = best_row[0];
  202483. }
  202484. #endif
  202485. #endif /* PNG_NO_WRITE_FILTER */
  202486. }
  202487. /* Do the actual writing of a previously filtered row. */
  202488. void /* PRIVATE */
  202489. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  202490. {
  202491. png_debug(1, "in png_write_filtered_row\n");
  202492. png_debug1(2, "filter = %d\n", filtered_row[0]);
  202493. /* set up the zlib input buffer */
  202494. png_ptr->zstream.next_in = filtered_row;
  202495. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  202496. /* repeat until we have compressed all the data */
  202497. do
  202498. {
  202499. int ret; /* return of zlib */
  202500. /* compress the data */
  202501. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  202502. /* check for compression errors */
  202503. if (ret != Z_OK)
  202504. {
  202505. if (png_ptr->zstream.msg != NULL)
  202506. png_error(png_ptr, png_ptr->zstream.msg);
  202507. else
  202508. png_error(png_ptr, "zlib error");
  202509. }
  202510. /* see if it is time to write another IDAT */
  202511. if (!(png_ptr->zstream.avail_out))
  202512. {
  202513. /* write the IDAT and reset the zlib output buffer */
  202514. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202515. png_ptr->zstream.next_out = png_ptr->zbuf;
  202516. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202517. }
  202518. /* repeat until all data has been compressed */
  202519. } while (png_ptr->zstream.avail_in);
  202520. /* swap the current and previous rows */
  202521. if (png_ptr->prev_row != NULL)
  202522. {
  202523. png_bytep tptr;
  202524. tptr = png_ptr->prev_row;
  202525. png_ptr->prev_row = png_ptr->row_buf;
  202526. png_ptr->row_buf = tptr;
  202527. }
  202528. /* finish row - updates counters and flushes zlib if last row */
  202529. png_write_finish_row(png_ptr);
  202530. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  202531. png_ptr->flush_rows++;
  202532. if (png_ptr->flush_dist > 0 &&
  202533. png_ptr->flush_rows >= png_ptr->flush_dist)
  202534. {
  202535. png_write_flush(png_ptr);
  202536. }
  202537. #endif
  202538. }
  202539. #endif /* PNG_WRITE_SUPPORTED */
  202540. /*** End of inlined file: pngwutil.c ***/
  202541. }
  202542. #else
  202543. extern "C"
  202544. {
  202545. #include <png.h>
  202546. #include <pngconf.h>
  202547. }
  202548. #endif
  202549. }
  202550. #undef max
  202551. #undef min
  202552. #if JUCE_MSVC
  202553. #pragma warning (pop)
  202554. #endif
  202555. BEGIN_JUCE_NAMESPACE
  202556. using ::calloc;
  202557. using ::malloc;
  202558. using ::free;
  202559. namespace PNGHelpers
  202560. {
  202561. using namespace pnglibNamespace;
  202562. static void readCallback (png_structp png, png_bytep data, png_size_t length)
  202563. {
  202564. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  202565. }
  202566. static void writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  202567. {
  202568. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  202569. }
  202570. struct PNGErrorStruct {};
  202571. static void errorCallback (png_structp, png_const_charp)
  202572. {
  202573. throw PNGErrorStruct();
  202574. }
  202575. }
  202576. PNGImageFormat::PNGImageFormat() {}
  202577. PNGImageFormat::~PNGImageFormat() {}
  202578. const String PNGImageFormat::getFormatName()
  202579. {
  202580. return "PNG";
  202581. }
  202582. bool PNGImageFormat::canUnderstand (InputStream& in)
  202583. {
  202584. const int bytesNeeded = 4;
  202585. char header [bytesNeeded];
  202586. return in.read (header, bytesNeeded) == bytesNeeded
  202587. && header[1] == 'P'
  202588. && header[2] == 'N'
  202589. && header[3] == 'G';
  202590. }
  202591. const Image PNGImageFormat::decodeImage (InputStream& in)
  202592. {
  202593. using namespace pnglibNamespace;
  202594. Image image;
  202595. png_structp pngReadStruct;
  202596. png_infop pngInfoStruct;
  202597. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202598. if (pngReadStruct != 0)
  202599. {
  202600. pngInfoStruct = png_create_info_struct (pngReadStruct);
  202601. if (pngInfoStruct == 0)
  202602. {
  202603. png_destroy_read_struct (&pngReadStruct, 0, 0);
  202604. return Image::null;
  202605. }
  202606. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  202607. // read the header..
  202608. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  202609. png_uint_32 width, height;
  202610. int bitDepth, colorType, interlaceType;
  202611. png_read_info (pngReadStruct, pngInfoStruct);
  202612. png_get_IHDR (pngReadStruct, pngInfoStruct,
  202613. &width, &height,
  202614. &bitDepth, &colorType,
  202615. &interlaceType, 0, 0);
  202616. if (bitDepth == 16)
  202617. png_set_strip_16 (pngReadStruct);
  202618. if (colorType == PNG_COLOR_TYPE_PALETTE)
  202619. png_set_expand (pngReadStruct);
  202620. if (bitDepth < 8)
  202621. png_set_expand (pngReadStruct);
  202622. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  202623. png_set_expand (pngReadStruct);
  202624. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  202625. png_set_gray_to_rgb (pngReadStruct);
  202626. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  202627. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  202628. || pngInfoStruct->num_trans > 0;
  202629. // Load the image into a temp buffer in the pnglib format..
  202630. HeapBlock <uint8> tempBuffer (height * (width << 2));
  202631. {
  202632. HeapBlock <png_bytep> rows (height);
  202633. for (int y = (int) height; --y >= 0;)
  202634. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  202635. png_read_image (pngReadStruct, rows);
  202636. png_read_end (pngReadStruct, pngInfoStruct);
  202637. }
  202638. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  202639. // now convert the data to a juce image format..
  202640. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  202641. (int) width, (int) height, hasAlphaChan);
  202642. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  202643. const Image::BitmapData destData (image, true);
  202644. uint8* srcRow = tempBuffer;
  202645. uint8* destRow = destData.data;
  202646. for (int y = 0; y < (int) height; ++y)
  202647. {
  202648. const uint8* src = srcRow;
  202649. srcRow += (width << 2);
  202650. uint8* dest = destRow;
  202651. destRow += destData.lineStride;
  202652. if (hasAlphaChan)
  202653. {
  202654. for (int i = (int) width; --i >= 0;)
  202655. {
  202656. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  202657. ((PixelARGB*) dest)->premultiply();
  202658. dest += destData.pixelStride;
  202659. src += 4;
  202660. }
  202661. }
  202662. else
  202663. {
  202664. for (int i = (int) width; --i >= 0;)
  202665. {
  202666. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  202667. dest += destData.pixelStride;
  202668. src += 4;
  202669. }
  202670. }
  202671. }
  202672. }
  202673. return image;
  202674. }
  202675. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  202676. {
  202677. using namespace pnglibNamespace;
  202678. const int width = image.getWidth();
  202679. const int height = image.getHeight();
  202680. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202681. if (pngWriteStruct == 0)
  202682. return false;
  202683. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  202684. if (pngInfoStruct == 0)
  202685. {
  202686. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  202687. return false;
  202688. }
  202689. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  202690. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  202691. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  202692. : PNG_COLOR_TYPE_RGB,
  202693. PNG_INTERLACE_NONE,
  202694. PNG_COMPRESSION_TYPE_BASE,
  202695. PNG_FILTER_TYPE_BASE);
  202696. HeapBlock <uint8> rowData (width * 4);
  202697. png_color_8 sig_bit;
  202698. sig_bit.red = 8;
  202699. sig_bit.green = 8;
  202700. sig_bit.blue = 8;
  202701. sig_bit.alpha = 8;
  202702. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  202703. png_write_info (pngWriteStruct, pngInfoStruct);
  202704. png_set_shift (pngWriteStruct, &sig_bit);
  202705. png_set_packing (pngWriteStruct);
  202706. const Image::BitmapData srcData (image, false);
  202707. for (int y = 0; y < height; ++y)
  202708. {
  202709. uint8* dst = rowData;
  202710. const uint8* src = srcData.getLinePointer (y);
  202711. if (image.hasAlphaChannel())
  202712. {
  202713. for (int i = width; --i >= 0;)
  202714. {
  202715. PixelARGB p (*(const PixelARGB*) src);
  202716. p.unpremultiply();
  202717. *dst++ = p.getRed();
  202718. *dst++ = p.getGreen();
  202719. *dst++ = p.getBlue();
  202720. *dst++ = p.getAlpha();
  202721. src += srcData.pixelStride;
  202722. }
  202723. }
  202724. else
  202725. {
  202726. for (int i = width; --i >= 0;)
  202727. {
  202728. *dst++ = ((const PixelRGB*) src)->getRed();
  202729. *dst++ = ((const PixelRGB*) src)->getGreen();
  202730. *dst++ = ((const PixelRGB*) src)->getBlue();
  202731. src += srcData.pixelStride;
  202732. }
  202733. }
  202734. png_write_rows (pngWriteStruct, &rowData, 1);
  202735. }
  202736. png_write_end (pngWriteStruct, pngInfoStruct);
  202737. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  202738. out.flush();
  202739. return true;
  202740. }
  202741. END_JUCE_NAMESPACE
  202742. /*** End of inlined file: juce_PNGLoader.cpp ***/
  202743. #endif
  202744. //==============================================================================
  202745. #if JUCE_BUILD_NATIVE
  202746. #if JUCE_WINDOWS
  202747. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  202748. /*
  202749. This file wraps together all the win32-specific code, so that
  202750. we can include all the native headers just once, and compile all our
  202751. platform-specific stuff in one big lump, keeping it out of the way of
  202752. the rest of the codebase.
  202753. */
  202754. #if JUCE_WINDOWS
  202755. BEGIN_JUCE_NAMESPACE
  202756. #define JUCE_INCLUDED_FILE 1
  202757. // Now include the actual code files..
  202758. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  202759. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202760. // compiled on its own).
  202761. #if JUCE_INCLUDED_FILE
  202762. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  202763. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202764. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202765. #ifndef DOXYGEN
  202766. // use with DynamicLibraryLoader to simplify importing functions
  202767. //
  202768. // functionName: function to import
  202769. // localFunctionName: name you want to use to actually call it (must be different)
  202770. // returnType: the return type
  202771. // object: the DynamicLibraryLoader to use
  202772. // params: list of params (bracketed)
  202773. //
  202774. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  202775. typedef returnType (WINAPI *type##localFunctionName) params; \
  202776. type##localFunctionName localFunctionName \
  202777. = (type##localFunctionName)object.findProcAddress (#functionName);
  202778. // loads and unloads a DLL automatically
  202779. class JUCE_API DynamicLibraryLoader
  202780. {
  202781. public:
  202782. DynamicLibraryLoader (const String& name);
  202783. ~DynamicLibraryLoader();
  202784. void* findProcAddress (const String& functionName);
  202785. private:
  202786. void* libHandle;
  202787. };
  202788. #endif
  202789. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202790. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  202791. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  202792. {
  202793. libHandle = LoadLibrary (name);
  202794. }
  202795. DynamicLibraryLoader::~DynamicLibraryLoader()
  202796. {
  202797. FreeLibrary ((HMODULE) libHandle);
  202798. }
  202799. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  202800. {
  202801. return GetProcAddress ((HMODULE) libHandle, functionName.toCString());
  202802. }
  202803. #endif
  202804. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  202805. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  202806. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202807. // compiled on its own).
  202808. #if JUCE_INCLUDED_FILE
  202809. extern void juce_initialiseThreadEvents();
  202810. void Logger::outputDebugString (const String& text)
  202811. {
  202812. OutputDebugString (text + "\n");
  202813. }
  202814. static int64 hiResTicksPerSecond;
  202815. static double hiResTicksScaleFactor;
  202816. #if JUCE_USE_INTRINSICS
  202817. // CPU info functions using intrinsics...
  202818. #pragma intrinsic (__cpuid)
  202819. #pragma intrinsic (__rdtsc)
  202820. const String SystemStats::getCpuVendor()
  202821. {
  202822. int info [4];
  202823. __cpuid (info, 0);
  202824. char v [12];
  202825. memcpy (v, info + 1, 4);
  202826. memcpy (v + 4, info + 3, 4);
  202827. memcpy (v + 8, info + 2, 4);
  202828. return String (v, 12);
  202829. }
  202830. #else
  202831. // CPU info functions using old fashioned inline asm...
  202832. static void juce_getCpuVendor (char* const v)
  202833. {
  202834. int vendor[4];
  202835. zeromem (vendor, 16);
  202836. #ifdef JUCE_64BIT
  202837. #else
  202838. #ifndef __MINGW32__
  202839. __try
  202840. #endif
  202841. {
  202842. #if JUCE_GCC
  202843. unsigned int dummy = 0;
  202844. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  202845. #else
  202846. __asm
  202847. {
  202848. mov eax, 0
  202849. cpuid
  202850. mov [vendor], ebx
  202851. mov [vendor + 4], edx
  202852. mov [vendor + 8], ecx
  202853. }
  202854. #endif
  202855. }
  202856. #ifndef __MINGW32__
  202857. __except (EXCEPTION_EXECUTE_HANDLER)
  202858. {
  202859. *v = 0;
  202860. }
  202861. #endif
  202862. #endif
  202863. memcpy (v, vendor, 16);
  202864. }
  202865. const String SystemStats::getCpuVendor()
  202866. {
  202867. char v [16];
  202868. juce_getCpuVendor (v);
  202869. return String (v, 16);
  202870. }
  202871. #endif
  202872. void SystemStats::initialiseStats()
  202873. {
  202874. juce_initialiseThreadEvents();
  202875. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  202876. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  202877. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  202878. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  202879. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  202880. #else
  202881. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  202882. #endif
  202883. {
  202884. SYSTEM_INFO systemInfo;
  202885. GetSystemInfo (&systemInfo);
  202886. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  202887. }
  202888. LARGE_INTEGER f;
  202889. QueryPerformanceFrequency (&f);
  202890. hiResTicksPerSecond = f.QuadPart;
  202891. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  202892. String s (SystemStats::getJUCEVersion());
  202893. const MMRESULT res = timeBeginPeriod (1);
  202894. (void) res;
  202895. jassert (res == TIMERR_NOERROR);
  202896. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  202897. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  202898. #endif
  202899. }
  202900. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  202901. {
  202902. OSVERSIONINFO info;
  202903. info.dwOSVersionInfoSize = sizeof (info);
  202904. GetVersionEx (&info);
  202905. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  202906. {
  202907. switch (info.dwMajorVersion)
  202908. {
  202909. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  202910. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  202911. default: jassertfalse; break; // !! not a supported OS!
  202912. }
  202913. }
  202914. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  202915. {
  202916. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  202917. return Win98;
  202918. }
  202919. return UnknownOS;
  202920. }
  202921. const String SystemStats::getOperatingSystemName()
  202922. {
  202923. const char* name = "Unknown OS";
  202924. switch (getOperatingSystemType())
  202925. {
  202926. case Windows7: name = "Windows 7"; break;
  202927. case WinVista: name = "Windows Vista"; break;
  202928. case WinXP: name = "Windows XP"; break;
  202929. case Win2000: name = "Windows 2000"; break;
  202930. case Win98: name = "Windows 98"; break;
  202931. default: jassertfalse; break; // !! new type of OS?
  202932. }
  202933. return name;
  202934. }
  202935. bool SystemStats::isOperatingSystem64Bit()
  202936. {
  202937. #ifdef _WIN64
  202938. return true;
  202939. #else
  202940. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  202941. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  202942. BOOL isWow64 = FALSE;
  202943. return (fnIsWow64Process != 0)
  202944. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  202945. && (isWow64 != FALSE);
  202946. #endif
  202947. }
  202948. int SystemStats::getMemorySizeInMegabytes()
  202949. {
  202950. MEMORYSTATUSEX mem;
  202951. mem.dwLength = sizeof (mem);
  202952. GlobalMemoryStatusEx (&mem);
  202953. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  202954. }
  202955. uint32 juce_millisecondsSinceStartup() throw()
  202956. {
  202957. return (uint32) GetTickCount();
  202958. }
  202959. int64 Time::getHighResolutionTicks() throw()
  202960. {
  202961. LARGE_INTEGER ticks;
  202962. QueryPerformanceCounter (&ticks);
  202963. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  202964. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  202965. // fix for a very obscure PCI hardware bug that can make the counter
  202966. // sometimes jump forwards by a few seconds..
  202967. static int64 hiResTicksOffset = 0;
  202968. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  202969. if (offsetDrift > (hiResTicksPerSecond >> 1))
  202970. hiResTicksOffset = newOffset;
  202971. return ticks.QuadPart + hiResTicksOffset;
  202972. }
  202973. double Time::getMillisecondCounterHiRes() throw()
  202974. {
  202975. return getHighResolutionTicks() * hiResTicksScaleFactor;
  202976. }
  202977. int64 Time::getHighResolutionTicksPerSecond() throw()
  202978. {
  202979. return hiResTicksPerSecond;
  202980. }
  202981. static int64 juce_getClockCycleCounter() throw()
  202982. {
  202983. #if JUCE_USE_INTRINSICS
  202984. // MS intrinsics version...
  202985. return __rdtsc();
  202986. #elif JUCE_GCC
  202987. // GNU inline asm version...
  202988. unsigned int hi = 0, lo = 0;
  202989. __asm__ __volatile__ (
  202990. "xor %%eax, %%eax \n\
  202991. xor %%edx, %%edx \n\
  202992. rdtsc \n\
  202993. movl %%eax, %[lo] \n\
  202994. movl %%edx, %[hi]"
  202995. :
  202996. : [hi] "m" (hi),
  202997. [lo] "m" (lo)
  202998. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  202999. return (int64) ((((uint64) hi) << 32) | lo);
  203000. #else
  203001. // MSVC inline asm version...
  203002. unsigned int hi = 0, lo = 0;
  203003. __asm
  203004. {
  203005. xor eax, eax
  203006. xor edx, edx
  203007. rdtsc
  203008. mov lo, eax
  203009. mov hi, edx
  203010. }
  203011. return (int64) ((((uint64) hi) << 32) | lo);
  203012. #endif
  203013. }
  203014. int SystemStats::getCpuSpeedInMegaherz()
  203015. {
  203016. const int64 cycles = juce_getClockCycleCounter();
  203017. const uint32 millis = Time::getMillisecondCounter();
  203018. int lastResult = 0;
  203019. for (;;)
  203020. {
  203021. int n = 1000000;
  203022. while (--n > 0) {}
  203023. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203024. const int64 cyclesNow = juce_getClockCycleCounter();
  203025. if (millisElapsed > 80)
  203026. {
  203027. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203028. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203029. return newResult;
  203030. lastResult = newResult;
  203031. }
  203032. }
  203033. }
  203034. bool Time::setSystemTimeToThisTime() const
  203035. {
  203036. SYSTEMTIME st;
  203037. st.wDayOfWeek = 0;
  203038. st.wYear = (WORD) getYear();
  203039. st.wMonth = (WORD) (getMonth() + 1);
  203040. st.wDay = (WORD) getDayOfMonth();
  203041. st.wHour = (WORD) getHours();
  203042. st.wMinute = (WORD) getMinutes();
  203043. st.wSecond = (WORD) getSeconds();
  203044. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203045. // do this twice because of daylight saving conversion problems - the
  203046. // first one sets it up, the second one kicks it in.
  203047. return SetLocalTime (&st) != 0
  203048. && SetLocalTime (&st) != 0;
  203049. }
  203050. int SystemStats::getPageSize()
  203051. {
  203052. SYSTEM_INFO systemInfo;
  203053. GetSystemInfo (&systemInfo);
  203054. return systemInfo.dwPageSize;
  203055. }
  203056. const String SystemStats::getLogonName()
  203057. {
  203058. TCHAR text [256];
  203059. DWORD len = numElementsInArray (text) - 2;
  203060. zerostruct (text);
  203061. GetUserName (text, &len);
  203062. return String (text, len);
  203063. }
  203064. const String SystemStats::getFullUserName()
  203065. {
  203066. return getLogonName();
  203067. }
  203068. #endif
  203069. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203070. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203071. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203072. // compiled on its own).
  203073. #if JUCE_INCLUDED_FILE
  203074. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203075. extern HWND juce_messageWindowHandle;
  203076. #endif
  203077. #if ! JUCE_USE_INTRINSICS
  203078. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203079. // older ones we have to actually call the ops as win32 functions..
  203080. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203081. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203082. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203083. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203084. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203085. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203086. {
  203087. jassertfalse; // This operation isn't available in old MS compiler versions!
  203088. __int64 oldValue = *value;
  203089. if (oldValue == valueToCompare)
  203090. *value = newValue;
  203091. return oldValue;
  203092. }
  203093. #endif
  203094. CriticalSection::CriticalSection() throw()
  203095. {
  203096. // (just to check the MS haven't changed this structure and broken things...)
  203097. #if _MSC_VER >= 1400
  203098. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203099. #else
  203100. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203101. #endif
  203102. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203103. }
  203104. CriticalSection::~CriticalSection() throw()
  203105. {
  203106. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203107. }
  203108. void CriticalSection::enter() const throw()
  203109. {
  203110. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203111. }
  203112. bool CriticalSection::tryEnter() const throw()
  203113. {
  203114. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203115. }
  203116. void CriticalSection::exit() const throw()
  203117. {
  203118. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203119. }
  203120. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203121. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203122. {
  203123. }
  203124. WaitableEvent::~WaitableEvent() throw()
  203125. {
  203126. CloseHandle (internal);
  203127. }
  203128. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203129. {
  203130. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203131. }
  203132. void WaitableEvent::signal() const throw()
  203133. {
  203134. SetEvent (internal);
  203135. }
  203136. void WaitableEvent::reset() const throw()
  203137. {
  203138. ResetEvent (internal);
  203139. }
  203140. void JUCE_API juce_threadEntryPoint (void*);
  203141. static unsigned int __stdcall threadEntryProc (void* userData)
  203142. {
  203143. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203144. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  203145. GetCurrentThreadId(), TRUE);
  203146. #endif
  203147. juce_threadEntryPoint (userData);
  203148. _endthreadex (0);
  203149. return 0;
  203150. }
  203151. void juce_CloseThreadHandle (void* handle)
  203152. {
  203153. CloseHandle ((HANDLE) handle);
  203154. }
  203155. void* juce_createThread (void* userData)
  203156. {
  203157. unsigned int threadId;
  203158. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  203159. }
  203160. void juce_killThread (void* handle)
  203161. {
  203162. if (handle != 0)
  203163. {
  203164. #if JUCE_DEBUG
  203165. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  203166. #endif
  203167. TerminateThread (handle, 0);
  203168. }
  203169. }
  203170. void juce_setCurrentThreadName (const String& name)
  203171. {
  203172. #if JUCE_DEBUG && JUCE_MSVC
  203173. struct
  203174. {
  203175. DWORD dwType;
  203176. LPCSTR szName;
  203177. DWORD dwThreadID;
  203178. DWORD dwFlags;
  203179. } info;
  203180. info.dwType = 0x1000;
  203181. info.szName = name.toCString();
  203182. info.dwThreadID = GetCurrentThreadId();
  203183. info.dwFlags = 0;
  203184. __try
  203185. {
  203186. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203187. }
  203188. __except (EXCEPTION_CONTINUE_EXECUTION)
  203189. {}
  203190. #else
  203191. (void) name;
  203192. #endif
  203193. }
  203194. Thread::ThreadID Thread::getCurrentThreadId()
  203195. {
  203196. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203197. }
  203198. // priority 1 to 10 where 5=normal, 1=low
  203199. bool juce_setThreadPriority (void* threadHandle, int priority)
  203200. {
  203201. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203202. if (priority < 1)
  203203. pri = THREAD_PRIORITY_IDLE;
  203204. else if (priority < 2)
  203205. pri = THREAD_PRIORITY_LOWEST;
  203206. else if (priority < 5)
  203207. pri = THREAD_PRIORITY_BELOW_NORMAL;
  203208. else if (priority < 7)
  203209. pri = THREAD_PRIORITY_NORMAL;
  203210. else if (priority < 9)
  203211. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203212. else if (priority < 10)
  203213. pri = THREAD_PRIORITY_HIGHEST;
  203214. if (threadHandle == 0)
  203215. threadHandle = GetCurrentThread();
  203216. return SetThreadPriority (threadHandle, pri) != FALSE;
  203217. }
  203218. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203219. {
  203220. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203221. }
  203222. static HANDLE sleepEvent = 0;
  203223. void juce_initialiseThreadEvents()
  203224. {
  203225. if (sleepEvent == 0)
  203226. #if JUCE_DEBUG
  203227. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  203228. #else
  203229. sleepEvent = CreateEvent (0, 0, 0, 0);
  203230. #endif
  203231. }
  203232. void Thread::yield()
  203233. {
  203234. Sleep (0);
  203235. }
  203236. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  203237. {
  203238. if (millisecs >= 10)
  203239. {
  203240. Sleep (millisecs);
  203241. }
  203242. else
  203243. {
  203244. jassert (sleepEvent != 0);
  203245. // unlike Sleep() this is guaranteed to return to the current thread after
  203246. // the time expires, so we'll use this for short waits, which are more likely
  203247. // to need to be accurate
  203248. WaitForSingleObject (sleepEvent, millisecs);
  203249. }
  203250. }
  203251. static int lastProcessPriority = -1;
  203252. // called by WindowDriver because Windows does wierd things to process priority
  203253. // when you swap apps, and this forces an update when the app is brought to the front.
  203254. void juce_repeatLastProcessPriority()
  203255. {
  203256. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  203257. {
  203258. DWORD p;
  203259. switch (lastProcessPriority)
  203260. {
  203261. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  203262. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  203263. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  203264. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  203265. default: jassertfalse; return; // bad priority value
  203266. }
  203267. SetPriorityClass (GetCurrentProcess(), p);
  203268. }
  203269. }
  203270. void Process::setPriority (ProcessPriority prior)
  203271. {
  203272. if (lastProcessPriority != (int) prior)
  203273. {
  203274. lastProcessPriority = (int) prior;
  203275. juce_repeatLastProcessPriority();
  203276. }
  203277. }
  203278. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  203279. {
  203280. return IsDebuggerPresent() != FALSE;
  203281. }
  203282. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  203283. {
  203284. return juce_isRunningUnderDebugger();
  203285. }
  203286. void Process::raisePrivilege()
  203287. {
  203288. jassertfalse; // xxx not implemented
  203289. }
  203290. void Process::lowerPrivilege()
  203291. {
  203292. jassertfalse; // xxx not implemented
  203293. }
  203294. void Process::terminate()
  203295. {
  203296. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203297. _CrtDumpMemoryLeaks();
  203298. #endif
  203299. // bullet in the head in case there's a problem shutting down..
  203300. ExitProcess (0);
  203301. }
  203302. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  203303. {
  203304. void* result = 0;
  203305. JUCE_TRY
  203306. {
  203307. result = LoadLibrary (name);
  203308. }
  203309. JUCE_CATCH_ALL
  203310. return result;
  203311. }
  203312. void PlatformUtilities::freeDynamicLibrary (void* h)
  203313. {
  203314. JUCE_TRY
  203315. {
  203316. if (h != 0)
  203317. FreeLibrary ((HMODULE) h);
  203318. }
  203319. JUCE_CATCH_ALL
  203320. }
  203321. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  203322. {
  203323. return (h != 0) ? GetProcAddress ((HMODULE) h, name.toCString()) : 0;
  203324. }
  203325. class InterProcessLock::Pimpl
  203326. {
  203327. public:
  203328. Pimpl (const String& name, const int timeOutMillisecs)
  203329. : handle (0), refCount (1)
  203330. {
  203331. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  203332. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  203333. {
  203334. if (timeOutMillisecs == 0)
  203335. {
  203336. close();
  203337. return;
  203338. }
  203339. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  203340. {
  203341. case WAIT_OBJECT_0:
  203342. case WAIT_ABANDONED:
  203343. break;
  203344. case WAIT_TIMEOUT:
  203345. default:
  203346. close();
  203347. break;
  203348. }
  203349. }
  203350. }
  203351. ~Pimpl()
  203352. {
  203353. close();
  203354. }
  203355. void close()
  203356. {
  203357. if (handle != 0)
  203358. {
  203359. ReleaseMutex (handle);
  203360. CloseHandle (handle);
  203361. handle = 0;
  203362. }
  203363. }
  203364. HANDLE handle;
  203365. int refCount;
  203366. };
  203367. InterProcessLock::InterProcessLock (const String& name_)
  203368. : name (name_)
  203369. {
  203370. }
  203371. InterProcessLock::~InterProcessLock()
  203372. {
  203373. }
  203374. bool InterProcessLock::enter (const int timeOutMillisecs)
  203375. {
  203376. const ScopedLock sl (lock);
  203377. if (pimpl == 0)
  203378. {
  203379. pimpl = new Pimpl (name, timeOutMillisecs);
  203380. if (pimpl->handle == 0)
  203381. pimpl = 0;
  203382. }
  203383. else
  203384. {
  203385. pimpl->refCount++;
  203386. }
  203387. return pimpl != 0;
  203388. }
  203389. void InterProcessLock::exit()
  203390. {
  203391. const ScopedLock sl (lock);
  203392. // Trying to release the lock too many times!
  203393. jassert (pimpl != 0);
  203394. if (pimpl != 0 && --(pimpl->refCount) == 0)
  203395. pimpl = 0;
  203396. }
  203397. #endif
  203398. /*** End of inlined file: juce_win32_Threads.cpp ***/
  203399. /*** Start of inlined file: juce_win32_Files.cpp ***/
  203400. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203401. // compiled on its own).
  203402. #if JUCE_INCLUDED_FILE
  203403. #ifndef CSIDL_MYMUSIC
  203404. #define CSIDL_MYMUSIC 0x000d
  203405. #endif
  203406. #ifndef CSIDL_MYVIDEO
  203407. #define CSIDL_MYVIDEO 0x000e
  203408. #endif
  203409. #ifndef INVALID_FILE_ATTRIBUTES
  203410. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  203411. #endif
  203412. const juce_wchar File::separator = '\\';
  203413. const String File::separatorString ("\\");
  203414. bool File::exists() const
  203415. {
  203416. return fullPath.isNotEmpty()
  203417. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  203418. }
  203419. bool File::existsAsFile() const
  203420. {
  203421. return fullPath.isNotEmpty()
  203422. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  203423. }
  203424. bool File::isDirectory() const
  203425. {
  203426. const DWORD attr = GetFileAttributes (fullPath);
  203427. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  203428. }
  203429. bool File::hasWriteAccess() const
  203430. {
  203431. if (exists())
  203432. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  203433. // on windows, it seems that even read-only directories can still be written into,
  203434. // so checking the parent directory's permissions would return the wrong result..
  203435. return true;
  203436. }
  203437. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  203438. {
  203439. DWORD attr = GetFileAttributes (fullPath);
  203440. if (attr == INVALID_FILE_ATTRIBUTES)
  203441. return false;
  203442. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  203443. return true;
  203444. if (shouldBeReadOnly)
  203445. attr |= FILE_ATTRIBUTE_READONLY;
  203446. else
  203447. attr &= ~FILE_ATTRIBUTE_READONLY;
  203448. return SetFileAttributes (fullPath, attr) != FALSE;
  203449. }
  203450. bool File::isHidden() const
  203451. {
  203452. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  203453. }
  203454. bool File::deleteFile() const
  203455. {
  203456. if (! exists())
  203457. return true;
  203458. else if (isDirectory())
  203459. return RemoveDirectory (fullPath) != 0;
  203460. else
  203461. return DeleteFile (fullPath) != 0;
  203462. }
  203463. bool File::moveToTrash() const
  203464. {
  203465. if (! exists())
  203466. return true;
  203467. SHFILEOPSTRUCT fos;
  203468. zerostruct (fos);
  203469. // The string we pass in must be double null terminated..
  203470. String doubleNullTermPath (getFullPathName() + " ");
  203471. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  203472. p [getFullPathName().length()] = 0;
  203473. fos.wFunc = FO_DELETE;
  203474. fos.pFrom = p;
  203475. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  203476. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  203477. return SHFileOperation (&fos) == 0;
  203478. }
  203479. bool File::copyInternal (const File& dest) const
  203480. {
  203481. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  203482. }
  203483. bool File::moveInternal (const File& dest) const
  203484. {
  203485. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  203486. }
  203487. void File::createDirectoryInternal (const String& fileName) const
  203488. {
  203489. CreateDirectory (fileName, 0);
  203490. }
  203491. // return 0 if not possible
  203492. void* juce_fileOpen (const File& file, bool forWriting)
  203493. {
  203494. HANDLE h;
  203495. if (forWriting)
  203496. {
  203497. h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  203498. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  203499. if (h != INVALID_HANDLE_VALUE)
  203500. SetFilePointer (h, 0, 0, FILE_END);
  203501. else
  203502. h = 0;
  203503. }
  203504. else
  203505. {
  203506. h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  203507. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  203508. if (h == INVALID_HANDLE_VALUE)
  203509. h = 0;
  203510. }
  203511. return h;
  203512. }
  203513. void juce_fileClose (void* handle)
  203514. {
  203515. CloseHandle (handle);
  203516. }
  203517. int juce_fileRead (void* handle, void* buffer, int size)
  203518. {
  203519. DWORD num = 0;
  203520. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  203521. return (int) num;
  203522. }
  203523. int juce_fileWrite (void* handle, const void* buffer, int size)
  203524. {
  203525. DWORD num;
  203526. WriteFile ((HANDLE) handle, buffer, size, &num, 0);
  203527. return (int) num;
  203528. }
  203529. int64 juce_fileSetPosition (void* handle, int64 pos)
  203530. {
  203531. LARGE_INTEGER li;
  203532. li.QuadPart = pos;
  203533. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  203534. return li.QuadPart;
  203535. }
  203536. int64 FileOutputStream::getPositionInternal() const
  203537. {
  203538. if (fileHandle == 0)
  203539. return -1;
  203540. LARGE_INTEGER li;
  203541. li.QuadPart = 0;
  203542. li.LowPart = SetFilePointer ((HANDLE) fileHandle, 0, &li.HighPart, FILE_CURRENT); // (returns -1 if it fails)
  203543. return jmax ((int64) 0, li.QuadPart);
  203544. }
  203545. void FileOutputStream::flushInternal()
  203546. {
  203547. if (fileHandle != 0)
  203548. FlushFileBuffers ((HANDLE) fileHandle);
  203549. }
  203550. int64 File::getSize() const
  203551. {
  203552. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203553. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  203554. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  203555. return 0;
  203556. }
  203557. static int64 fileTimeToTime (const FILETIME* const ft)
  203558. {
  203559. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  203560. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  203561. }
  203562. static void timeToFileTime (const int64 time, FILETIME* const ft)
  203563. {
  203564. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  203565. }
  203566. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  203567. {
  203568. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203569. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  203570. {
  203571. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  203572. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  203573. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  203574. }
  203575. else
  203576. {
  203577. creationTime = accessTime = modificationTime = 0;
  203578. }
  203579. }
  203580. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  203581. {
  203582. void* const h = juce_fileOpen (fullPath, true);
  203583. bool ok = false;
  203584. if (h != 0)
  203585. {
  203586. FILETIME m, a, c;
  203587. timeToFileTime (modificationTime, &m);
  203588. timeToFileTime (accessTime, &a);
  203589. timeToFileTime (creationTime, &c);
  203590. ok = SetFileTime ((HANDLE) h,
  203591. creationTime > 0 ? &c : 0,
  203592. accessTime > 0 ? &a : 0,
  203593. modificationTime > 0 ? &m : 0) != 0;
  203594. juce_fileClose (h);
  203595. }
  203596. return ok;
  203597. }
  203598. void File::findFileSystemRoots (Array<File>& destArray)
  203599. {
  203600. TCHAR buffer [2048];
  203601. buffer[0] = 0;
  203602. buffer[1] = 0;
  203603. GetLogicalDriveStrings (2048, buffer);
  203604. const TCHAR* n = buffer;
  203605. StringArray roots;
  203606. while (*n != 0)
  203607. {
  203608. roots.add (String (n));
  203609. while (*n++ != 0)
  203610. {}
  203611. }
  203612. roots.sort (true);
  203613. for (int i = 0; i < roots.size(); ++i)
  203614. destArray.add (roots [i]);
  203615. }
  203616. static const String getDriveFromPath (const String& path)
  203617. {
  203618. if (path.isNotEmpty() && path[1] == ':')
  203619. return path.substring (0, 2) + '\\';
  203620. return path;
  203621. }
  203622. const String File::getVolumeLabel() const
  203623. {
  203624. TCHAR dest[64];
  203625. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  203626. numElementsInArray (dest), 0, 0, 0, 0, 0))
  203627. dest[0] = 0;
  203628. return dest;
  203629. }
  203630. int File::getVolumeSerialNumber() const
  203631. {
  203632. TCHAR dest[64];
  203633. DWORD serialNum;
  203634. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  203635. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  203636. return 0;
  203637. return (int) serialNum;
  203638. }
  203639. static int64 getDiskSpaceInfo (const String& path, const bool total)
  203640. {
  203641. ULARGE_INTEGER spc, tot, totFree;
  203642. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  203643. return total ? (int64) tot.QuadPart
  203644. : (int64) spc.QuadPart;
  203645. return 0;
  203646. }
  203647. int64 File::getBytesFreeOnVolume() const
  203648. {
  203649. return getDiskSpaceInfo (getFullPathName(), false);
  203650. }
  203651. int64 File::getVolumeTotalSize() const
  203652. {
  203653. return getDiskSpaceInfo (getFullPathName(), true);
  203654. }
  203655. static unsigned int getWindowsDriveType (const String& path)
  203656. {
  203657. return GetDriveType (getDriveFromPath (path));
  203658. }
  203659. bool File::isOnCDRomDrive() const
  203660. {
  203661. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  203662. }
  203663. bool File::isOnHardDisk() const
  203664. {
  203665. if (fullPath.isEmpty())
  203666. return false;
  203667. const unsigned int n = getWindowsDriveType (getFullPathName());
  203668. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  203669. return n != DRIVE_REMOVABLE;
  203670. else
  203671. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  203672. }
  203673. bool File::isOnRemovableDrive() const
  203674. {
  203675. if (fullPath.isEmpty())
  203676. return false;
  203677. const unsigned int n = getWindowsDriveType (getFullPathName());
  203678. return n == DRIVE_CDROM
  203679. || n == DRIVE_REMOTE
  203680. || n == DRIVE_REMOVABLE
  203681. || n == DRIVE_RAMDISK;
  203682. }
  203683. static const File juce_getSpecialFolderPath (int type)
  203684. {
  203685. WCHAR path [MAX_PATH + 256];
  203686. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  203687. return File (String (path));
  203688. return File::nonexistent;
  203689. }
  203690. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  203691. {
  203692. int csidlType = 0;
  203693. switch (type)
  203694. {
  203695. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  203696. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  203697. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  203698. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  203699. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  203700. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  203701. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  203702. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  203703. case tempDirectory:
  203704. {
  203705. WCHAR dest [2048];
  203706. dest[0] = 0;
  203707. GetTempPath (numElementsInArray (dest), dest);
  203708. return File (String (dest));
  203709. }
  203710. case invokedExecutableFile:
  203711. case currentExecutableFile:
  203712. case currentApplicationFile:
  203713. {
  203714. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  203715. WCHAR dest [MAX_PATH + 256];
  203716. dest[0] = 0;
  203717. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  203718. return File (String (dest));
  203719. }
  203720. break;
  203721. default:
  203722. jassertfalse; // unknown type?
  203723. return File::nonexistent;
  203724. }
  203725. return juce_getSpecialFolderPath (csidlType);
  203726. }
  203727. const File File::getCurrentWorkingDirectory()
  203728. {
  203729. WCHAR dest [MAX_PATH + 256];
  203730. dest[0] = 0;
  203731. GetCurrentDirectory (numElementsInArray (dest), dest);
  203732. return File (String (dest));
  203733. }
  203734. bool File::setAsCurrentWorkingDirectory() const
  203735. {
  203736. return SetCurrentDirectory (getFullPathName()) != FALSE;
  203737. }
  203738. const String File::getVersion() const
  203739. {
  203740. String result;
  203741. DWORD handle = 0;
  203742. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  203743. HeapBlock<char> buffer;
  203744. buffer.calloc (bufferSize);
  203745. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  203746. {
  203747. VS_FIXEDFILEINFO* vffi;
  203748. UINT len = 0;
  203749. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  203750. {
  203751. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  203752. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  203753. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  203754. << (int) LOWORD (vffi->dwFileVersionLS);
  203755. }
  203756. }
  203757. return result;
  203758. }
  203759. const File File::getLinkedTarget() const
  203760. {
  203761. File result (*this);
  203762. String p (getFullPathName());
  203763. if (! exists())
  203764. p += ".lnk";
  203765. else if (getFileExtension() != ".lnk")
  203766. return result;
  203767. ComSmartPtr <IShellLink> shellLink;
  203768. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  203769. {
  203770. ComSmartPtr <IPersistFile> persistFile;
  203771. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  203772. {
  203773. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  203774. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  203775. {
  203776. WIN32_FIND_DATA winFindData;
  203777. WCHAR resolvedPath [MAX_PATH];
  203778. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  203779. result = File (resolvedPath);
  203780. }
  203781. }
  203782. }
  203783. return result;
  203784. }
  203785. class DirectoryIterator::NativeIterator::Pimpl
  203786. {
  203787. public:
  203788. Pimpl (const File& directory, const String& wildCard)
  203789. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  203790. handle (INVALID_HANDLE_VALUE)
  203791. {
  203792. }
  203793. ~Pimpl()
  203794. {
  203795. if (handle != INVALID_HANDLE_VALUE)
  203796. FindClose (handle);
  203797. }
  203798. bool next (String& filenameFound,
  203799. bool* const isDir, bool* const isHidden, int64* const fileSize,
  203800. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  203801. {
  203802. WIN32_FIND_DATA findData;
  203803. if (handle == INVALID_HANDLE_VALUE)
  203804. {
  203805. handle = FindFirstFile (directoryWithWildCard, &findData);
  203806. if (handle == INVALID_HANDLE_VALUE)
  203807. return false;
  203808. }
  203809. else
  203810. {
  203811. if (FindNextFile (handle, &findData) == 0)
  203812. return false;
  203813. }
  203814. filenameFound = findData.cFileName;
  203815. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  203816. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  203817. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  203818. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  203819. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  203820. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  203821. return true;
  203822. }
  203823. juce_UseDebuggingNewOperator
  203824. private:
  203825. const String directoryWithWildCard;
  203826. HANDLE handle;
  203827. Pimpl (const Pimpl&);
  203828. Pimpl& operator= (const Pimpl&);
  203829. };
  203830. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  203831. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  203832. {
  203833. }
  203834. DirectoryIterator::NativeIterator::~NativeIterator()
  203835. {
  203836. }
  203837. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  203838. bool* const isDir, bool* const isHidden, int64* const fileSize,
  203839. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  203840. {
  203841. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  203842. }
  203843. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  203844. {
  203845. HINSTANCE hInstance = 0;
  203846. JUCE_TRY
  203847. {
  203848. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  203849. }
  203850. JUCE_CATCH_ALL
  203851. return hInstance > (HINSTANCE) 32;
  203852. }
  203853. void File::revealToUser() const
  203854. {
  203855. if (isDirectory())
  203856. startAsProcess();
  203857. else if (getParentDirectory().exists())
  203858. getParentDirectory().startAsProcess();
  203859. }
  203860. class NamedPipeInternal
  203861. {
  203862. public:
  203863. NamedPipeInternal (const String& file, const bool isPipe_)
  203864. : pipeH (0),
  203865. cancelEvent (0),
  203866. connected (false),
  203867. isPipe (isPipe_)
  203868. {
  203869. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  203870. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  203871. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  203872. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  203873. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  203874. }
  203875. ~NamedPipeInternal()
  203876. {
  203877. disconnectPipe();
  203878. if (pipeH != 0)
  203879. CloseHandle (pipeH);
  203880. CloseHandle (cancelEvent);
  203881. }
  203882. bool connect (const int timeOutMs)
  203883. {
  203884. if (! isPipe)
  203885. return true;
  203886. if (! connected)
  203887. {
  203888. OVERLAPPED over;
  203889. zerostruct (over);
  203890. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203891. if (ConnectNamedPipe (pipeH, &over))
  203892. {
  203893. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  203894. }
  203895. else
  203896. {
  203897. const int err = GetLastError();
  203898. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  203899. {
  203900. HANDLE handles[] = { over.hEvent, cancelEvent };
  203901. if (WaitForMultipleObjects (2, handles, FALSE,
  203902. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  203903. connected = true;
  203904. }
  203905. else if (err == ERROR_PIPE_CONNECTED)
  203906. {
  203907. connected = true;
  203908. }
  203909. }
  203910. CloseHandle (over.hEvent);
  203911. }
  203912. return connected;
  203913. }
  203914. void disconnectPipe()
  203915. {
  203916. if (connected)
  203917. {
  203918. DisconnectNamedPipe (pipeH);
  203919. connected = false;
  203920. }
  203921. }
  203922. HANDLE pipeH;
  203923. HANDLE cancelEvent;
  203924. bool connected, isPipe;
  203925. };
  203926. void NamedPipe::close()
  203927. {
  203928. cancelPendingReads();
  203929. const ScopedLock sl (lock);
  203930. delete static_cast<NamedPipeInternal*> (internal);
  203931. internal = 0;
  203932. }
  203933. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  203934. {
  203935. close();
  203936. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  203937. if (intern->pipeH != INVALID_HANDLE_VALUE)
  203938. {
  203939. internal = intern.release();
  203940. return true;
  203941. }
  203942. return false;
  203943. }
  203944. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  203945. {
  203946. const ScopedLock sl (lock);
  203947. int bytesRead = -1;
  203948. bool waitAgain = true;
  203949. while (waitAgain && internal != 0)
  203950. {
  203951. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  203952. waitAgain = false;
  203953. if (! intern->connect (timeOutMilliseconds))
  203954. break;
  203955. if (maxBytesToRead <= 0)
  203956. return 0;
  203957. OVERLAPPED over;
  203958. zerostruct (over);
  203959. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203960. unsigned long numRead;
  203961. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  203962. {
  203963. bytesRead = (int) numRead;
  203964. }
  203965. else if (GetLastError() == ERROR_IO_PENDING)
  203966. {
  203967. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  203968. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  203969. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  203970. : INFINITE);
  203971. if (waitResult != WAIT_OBJECT_0)
  203972. {
  203973. // if the operation timed out, let's cancel it...
  203974. CancelIo (intern->pipeH);
  203975. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  203976. }
  203977. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  203978. {
  203979. bytesRead = (int) numRead;
  203980. }
  203981. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  203982. {
  203983. intern->disconnectPipe();
  203984. waitAgain = true;
  203985. }
  203986. }
  203987. else
  203988. {
  203989. waitAgain = internal != 0;
  203990. Sleep (5);
  203991. }
  203992. CloseHandle (over.hEvent);
  203993. }
  203994. return bytesRead;
  203995. }
  203996. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  203997. {
  203998. int bytesWritten = -1;
  203999. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204000. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204001. {
  204002. if (numBytesToWrite <= 0)
  204003. return 0;
  204004. OVERLAPPED over;
  204005. zerostruct (over);
  204006. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204007. unsigned long numWritten;
  204008. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204009. {
  204010. bytesWritten = (int) numWritten;
  204011. }
  204012. else if (GetLastError() == ERROR_IO_PENDING)
  204013. {
  204014. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204015. DWORD waitResult;
  204016. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204017. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204018. : INFINITE);
  204019. if (waitResult != WAIT_OBJECT_0)
  204020. {
  204021. CancelIo (intern->pipeH);
  204022. WaitForSingleObject (over.hEvent, INFINITE);
  204023. }
  204024. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204025. {
  204026. bytesWritten = (int) numWritten;
  204027. }
  204028. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204029. {
  204030. intern->disconnectPipe();
  204031. }
  204032. }
  204033. CloseHandle (over.hEvent);
  204034. }
  204035. return bytesWritten;
  204036. }
  204037. void NamedPipe::cancelPendingReads()
  204038. {
  204039. if (internal != 0)
  204040. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204041. }
  204042. #endif
  204043. /*** End of inlined file: juce_win32_Files.cpp ***/
  204044. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204045. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204046. // compiled on its own).
  204047. #if JUCE_INCLUDED_FILE
  204048. #ifndef INTERNET_FLAG_NEED_FILE
  204049. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204050. #endif
  204051. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204052. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204053. #endif
  204054. struct ConnectionAndRequestStruct
  204055. {
  204056. HINTERNET connection, request;
  204057. };
  204058. static HINTERNET sessionHandle = 0;
  204059. #ifndef WORKAROUND_TIMEOUT_BUG
  204060. //#define WORKAROUND_TIMEOUT_BUG 1
  204061. #endif
  204062. #if WORKAROUND_TIMEOUT_BUG
  204063. // Required because of a Microsoft bug in setting a timeout
  204064. class InternetConnectThread : public Thread
  204065. {
  204066. public:
  204067. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  204068. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  204069. {
  204070. startThread();
  204071. }
  204072. ~InternetConnectThread()
  204073. {
  204074. stopThread (60000);
  204075. }
  204076. void run()
  204077. {
  204078. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204079. uc.nPort, _T(""), _T(""),
  204080. isFtp ? INTERNET_SERVICE_FTP
  204081. : INTERNET_SERVICE_HTTP,
  204082. 0, 0);
  204083. notify();
  204084. }
  204085. juce_UseDebuggingNewOperator
  204086. private:
  204087. URL_COMPONENTS& uc;
  204088. HINTERNET& connection;
  204089. const bool isFtp;
  204090. InternetConnectThread (const InternetConnectThread&);
  204091. InternetConnectThread& operator= (const InternetConnectThread&);
  204092. };
  204093. #endif
  204094. void* juce_openInternetFile (const String& url,
  204095. const String& headers,
  204096. const MemoryBlock& postData,
  204097. const bool isPost,
  204098. URL::OpenStreamProgressCallback* callback,
  204099. void* callbackContext,
  204100. int timeOutMs)
  204101. {
  204102. if (sessionHandle == 0)
  204103. sessionHandle = InternetOpen (_T("juce"),
  204104. INTERNET_OPEN_TYPE_PRECONFIG,
  204105. 0, 0, 0);
  204106. if (sessionHandle != 0)
  204107. {
  204108. // break up the url..
  204109. TCHAR file[1024], server[1024];
  204110. URL_COMPONENTS uc;
  204111. zerostruct (uc);
  204112. uc.dwStructSize = sizeof (uc);
  204113. uc.dwUrlPathLength = sizeof (file);
  204114. uc.dwHostNameLength = sizeof (server);
  204115. uc.lpszUrlPath = file;
  204116. uc.lpszHostName = server;
  204117. if (InternetCrackUrl (url, 0, 0, &uc))
  204118. {
  204119. int disable = 1;
  204120. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204121. if (timeOutMs == 0)
  204122. timeOutMs = 30000;
  204123. else if (timeOutMs < 0)
  204124. timeOutMs = -1;
  204125. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204126. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  204127. #if WORKAROUND_TIMEOUT_BUG
  204128. HINTERNET connection = 0;
  204129. {
  204130. InternetConnectThread connectThread (uc, connection, isFtp);
  204131. connectThread.wait (timeOutMs);
  204132. if (connection == 0)
  204133. {
  204134. InternetCloseHandle (sessionHandle);
  204135. sessionHandle = 0;
  204136. }
  204137. }
  204138. #else
  204139. HINTERNET connection = InternetConnect (sessionHandle,
  204140. uc.lpszHostName,
  204141. uc.nPort,
  204142. _T(""), _T(""),
  204143. isFtp ? INTERNET_SERVICE_FTP
  204144. : INTERNET_SERVICE_HTTP,
  204145. 0, 0);
  204146. #endif
  204147. if (connection != 0)
  204148. {
  204149. if (isFtp)
  204150. {
  204151. HINTERNET request = FtpOpenFile (connection,
  204152. uc.lpszUrlPath,
  204153. GENERIC_READ,
  204154. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  204155. 0);
  204156. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  204157. result->connection = connection;
  204158. result->request = request;
  204159. return result;
  204160. }
  204161. else
  204162. {
  204163. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  204164. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  204165. if (url.startsWithIgnoreCase ("https:"))
  204166. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  204167. // IE7 seems to automatically work out when it's https)
  204168. HINTERNET request = HttpOpenRequest (connection,
  204169. isPost ? _T("POST")
  204170. : _T("GET"),
  204171. uc.lpszUrlPath,
  204172. 0, 0, mimeTypes, flags, 0);
  204173. if (request != 0)
  204174. {
  204175. INTERNET_BUFFERS buffers;
  204176. zerostruct (buffers);
  204177. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204178. buffers.lpcszHeader = (LPCTSTR) headers;
  204179. buffers.dwHeadersLength = headers.length();
  204180. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204181. ConnectionAndRequestStruct* result = 0;
  204182. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204183. {
  204184. int bytesSent = 0;
  204185. for (;;)
  204186. {
  204187. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204188. DWORD bytesDone = 0;
  204189. if (bytesToDo > 0
  204190. && ! InternetWriteFile (request,
  204191. static_cast <const char*> (postData.getData()) + bytesSent,
  204192. bytesToDo, &bytesDone))
  204193. {
  204194. break;
  204195. }
  204196. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204197. {
  204198. result = new ConnectionAndRequestStruct();
  204199. result->connection = connection;
  204200. result->request = request;
  204201. if (! HttpEndRequest (request, 0, 0, 0))
  204202. break;
  204203. return result;
  204204. }
  204205. bytesSent += bytesDone;
  204206. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  204207. break;
  204208. }
  204209. }
  204210. InternetCloseHandle (request);
  204211. }
  204212. InternetCloseHandle (connection);
  204213. }
  204214. }
  204215. }
  204216. }
  204217. return 0;
  204218. }
  204219. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  204220. {
  204221. DWORD bytesRead = 0;
  204222. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204223. if (crs != 0)
  204224. InternetReadFile (crs->request,
  204225. buffer, bytesToRead,
  204226. &bytesRead);
  204227. return bytesRead;
  204228. }
  204229. int juce_seekInInternetFile (void* handle, int newPosition)
  204230. {
  204231. if (handle != 0)
  204232. {
  204233. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204234. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  204235. }
  204236. return -1;
  204237. }
  204238. int64 juce_getInternetFileContentLength (void* handle)
  204239. {
  204240. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204241. if (crs != 0)
  204242. {
  204243. DWORD index = 0, result = 0, size = sizeof (result);
  204244. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  204245. return (int64) result;
  204246. }
  204247. return -1;
  204248. }
  204249. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  204250. {
  204251. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204252. if (crs != 0)
  204253. {
  204254. DWORD bufferSizeBytes = 4096;
  204255. for (;;)
  204256. {
  204257. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  204258. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  204259. {
  204260. StringArray headersArray;
  204261. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  204262. for (int i = 0; i < headersArray.size(); ++i)
  204263. {
  204264. const String& header = headersArray[i];
  204265. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  204266. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  204267. const String previousValue (headers [key]);
  204268. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  204269. }
  204270. break;
  204271. }
  204272. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  204273. break;
  204274. }
  204275. }
  204276. }
  204277. void juce_closeInternetFile (void* handle)
  204278. {
  204279. if (handle != 0)
  204280. {
  204281. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  204282. InternetCloseHandle (crs->request);
  204283. InternetCloseHandle (crs->connection);
  204284. }
  204285. }
  204286. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  204287. {
  204288. int numFound = 0;
  204289. DynamicLibraryLoader dll ("iphlpapi.dll");
  204290. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  204291. if (getAdaptersInfo != 0)
  204292. {
  204293. ULONG len = sizeof (IP_ADAPTER_INFO);
  204294. MemoryBlock mb;
  204295. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204296. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  204297. {
  204298. mb.setSize (len);
  204299. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204300. }
  204301. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  204302. {
  204303. PIP_ADAPTER_INFO adapter = adapterInfo;
  204304. while (adapter != 0)
  204305. {
  204306. int64 mac = 0;
  204307. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  204308. mac = (mac << 8) | adapter->Address[i];
  204309. if (littleEndian)
  204310. mac = (int64) ByteOrder::swap ((uint64) mac);
  204311. if (numFound < maxNum && mac != 0)
  204312. addresses [numFound++] = mac;
  204313. adapter = adapter->Next;
  204314. }
  204315. }
  204316. }
  204317. return numFound;
  204318. }
  204319. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  204320. {
  204321. int numFound = 0;
  204322. DynamicLibraryLoader dll ("netapi32.dll");
  204323. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  204324. if (NetbiosCall != 0)
  204325. {
  204326. NCB ncb;
  204327. zerostruct (ncb);
  204328. struct ASTAT
  204329. {
  204330. ADAPTER_STATUS adapt;
  204331. NAME_BUFFER NameBuff [30];
  204332. };
  204333. ASTAT astat;
  204334. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  204335. LANA_ENUM enums;
  204336. zerostruct (enums);
  204337. ncb.ncb_command = NCBENUM;
  204338. ncb.ncb_buffer = (unsigned char*) &enums;
  204339. ncb.ncb_length = sizeof (LANA_ENUM);
  204340. NetbiosCall (&ncb);
  204341. for (int i = 0; i < enums.length; ++i)
  204342. {
  204343. zerostruct (ncb);
  204344. ncb.ncb_command = NCBRESET;
  204345. ncb.ncb_lana_num = enums.lana[i];
  204346. if (NetbiosCall (&ncb) == 0)
  204347. {
  204348. zerostruct (ncb);
  204349. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  204350. ncb.ncb_command = NCBASTAT;
  204351. ncb.ncb_lana_num = enums.lana[i];
  204352. ncb.ncb_buffer = (unsigned char*) &astat;
  204353. ncb.ncb_length = sizeof (ASTAT);
  204354. if (NetbiosCall (&ncb) == 0)
  204355. {
  204356. if (astat.adapt.adapter_type == 0xfe)
  204357. {
  204358. uint64 mac = 0;
  204359. for (int i = 6; --i >= 0;)
  204360. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  204361. if (numFound < maxNum && mac != 0)
  204362. addresses [numFound++] = mac;
  204363. }
  204364. }
  204365. }
  204366. }
  204367. }
  204368. return numFound;
  204369. }
  204370. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  204371. {
  204372. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  204373. if (numFound == 0)
  204374. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  204375. return numFound;
  204376. }
  204377. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  204378. const String& emailSubject,
  204379. const String& bodyText,
  204380. const StringArray& filesToAttach)
  204381. {
  204382. HMODULE h = LoadLibraryA ("MAPI32.dll");
  204383. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  204384. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  204385. bool ok = false;
  204386. if (mapiSendMail != 0)
  204387. {
  204388. MapiMessage message;
  204389. zerostruct (message);
  204390. message.lpszSubject = (LPSTR) emailSubject.toCString();
  204391. message.lpszNoteText = (LPSTR) bodyText.toCString();
  204392. MapiRecipDesc recip;
  204393. zerostruct (recip);
  204394. recip.ulRecipClass = MAPI_TO;
  204395. String targetEmailAddress_ (targetEmailAddress);
  204396. if (targetEmailAddress_.isEmpty())
  204397. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  204398. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  204399. message.nRecipCount = 1;
  204400. message.lpRecips = &recip;
  204401. HeapBlock <MapiFileDesc> files;
  204402. files.calloc (filesToAttach.size());
  204403. message.nFileCount = filesToAttach.size();
  204404. message.lpFiles = files;
  204405. for (int i = 0; i < filesToAttach.size(); ++i)
  204406. {
  204407. files[i].nPosition = (ULONG) -1;
  204408. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  204409. }
  204410. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  204411. }
  204412. FreeLibrary (h);
  204413. return ok;
  204414. }
  204415. #endif
  204416. /*** End of inlined file: juce_win32_Network.cpp ***/
  204417. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  204418. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204419. // compiled on its own).
  204420. #if JUCE_INCLUDED_FILE
  204421. static HKEY findKeyForPath (String name,
  204422. const bool createForWriting,
  204423. String& valueName)
  204424. {
  204425. HKEY rootKey = 0;
  204426. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  204427. rootKey = HKEY_CURRENT_USER;
  204428. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  204429. rootKey = HKEY_LOCAL_MACHINE;
  204430. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  204431. rootKey = HKEY_CLASSES_ROOT;
  204432. if (rootKey != 0)
  204433. {
  204434. name = name.substring (name.indexOfChar ('\\') + 1);
  204435. const int lastSlash = name.lastIndexOfChar ('\\');
  204436. valueName = name.substring (lastSlash + 1);
  204437. name = name.substring (0, lastSlash);
  204438. HKEY key;
  204439. DWORD result;
  204440. if (createForWriting)
  204441. {
  204442. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  204443. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  204444. return key;
  204445. }
  204446. else
  204447. {
  204448. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  204449. return key;
  204450. }
  204451. }
  204452. return 0;
  204453. }
  204454. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  204455. const String& defaultValue)
  204456. {
  204457. String valueName, result (defaultValue);
  204458. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204459. if (k != 0)
  204460. {
  204461. WCHAR buffer [2048];
  204462. unsigned long bufferSize = sizeof (buffer);
  204463. DWORD type = REG_SZ;
  204464. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  204465. {
  204466. if (type == REG_SZ)
  204467. result = buffer;
  204468. else if (type == REG_DWORD)
  204469. result = String ((int) *(DWORD*) buffer);
  204470. }
  204471. RegCloseKey (k);
  204472. }
  204473. return result;
  204474. }
  204475. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  204476. const String& value)
  204477. {
  204478. String valueName;
  204479. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204480. if (k != 0)
  204481. {
  204482. RegSetValueEx (k, valueName, 0, REG_SZ,
  204483. (const BYTE*) (const WCHAR*) value,
  204484. sizeof (WCHAR) * (value.length() + 1));
  204485. RegCloseKey (k);
  204486. }
  204487. }
  204488. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  204489. {
  204490. bool exists = false;
  204491. String valueName;
  204492. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204493. if (k != 0)
  204494. {
  204495. unsigned char buffer [2048];
  204496. unsigned long bufferSize = sizeof (buffer);
  204497. DWORD type = 0;
  204498. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  204499. exists = true;
  204500. RegCloseKey (k);
  204501. }
  204502. return exists;
  204503. }
  204504. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  204505. {
  204506. String valueName;
  204507. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204508. if (k != 0)
  204509. {
  204510. RegDeleteValue (k, valueName);
  204511. RegCloseKey (k);
  204512. }
  204513. }
  204514. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  204515. {
  204516. String valueName;
  204517. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  204518. if (k != 0)
  204519. {
  204520. RegDeleteKey (k, valueName);
  204521. RegCloseKey (k);
  204522. }
  204523. }
  204524. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  204525. const String& symbolicDescription,
  204526. const String& fullDescription,
  204527. const File& targetExecutable,
  204528. int iconResourceNumber)
  204529. {
  204530. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  204531. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  204532. if (iconResourceNumber != 0)
  204533. setRegistryValue (key + "\\DefaultIcon\\",
  204534. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  204535. setRegistryValue (key + "\\", fullDescription);
  204536. setRegistryValue (key + "\\shell\\open\\command\\",
  204537. targetExecutable.getFullPathName() + " %1");
  204538. }
  204539. bool juce_IsRunningInWine()
  204540. {
  204541. HKEY key;
  204542. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  204543. {
  204544. RegCloseKey (key);
  204545. return true;
  204546. }
  204547. return false;
  204548. }
  204549. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  204550. {
  204551. String s (::GetCommandLineW());
  204552. StringArray tokens;
  204553. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  204554. return tokens.joinIntoString (" ", 1);
  204555. }
  204556. static void* currentModuleHandle = 0;
  204557. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  204558. {
  204559. if (currentModuleHandle == 0)
  204560. currentModuleHandle = GetModuleHandle (0);
  204561. return currentModuleHandle;
  204562. }
  204563. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  204564. {
  204565. currentModuleHandle = newHandle;
  204566. }
  204567. void PlatformUtilities::fpuReset()
  204568. {
  204569. #if JUCE_MSVC
  204570. _clearfp();
  204571. #endif
  204572. }
  204573. void PlatformUtilities::beep()
  204574. {
  204575. MessageBeep (MB_OK);
  204576. }
  204577. #endif
  204578. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  204579. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204580. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  204581. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204582. // compiled on its own).
  204583. #if JUCE_INCLUDED_FILE
  204584. static const unsigned int specialId = WM_APP + 0x4400;
  204585. static const unsigned int broadcastId = WM_APP + 0x4403;
  204586. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  204587. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  204588. HWND juce_messageWindowHandle = 0;
  204589. extern long improbableWindowNumber; // defined in windowing.cpp
  204590. #ifndef WM_APPCOMMAND
  204591. #define WM_APPCOMMAND 0x0319
  204592. #endif
  204593. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  204594. const UINT message,
  204595. const WPARAM wParam,
  204596. const LPARAM lParam) throw()
  204597. {
  204598. JUCE_TRY
  204599. {
  204600. if (h == juce_messageWindowHandle)
  204601. {
  204602. if (message == specialCallbackId)
  204603. {
  204604. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  204605. return (LRESULT) (*func) ((void*) lParam);
  204606. }
  204607. else if (message == specialId)
  204608. {
  204609. // these are trapped early in the dispatch call, but must also be checked
  204610. // here in case there are windows modal dialog boxes doing their own
  204611. // dispatch loop and not calling our version
  204612. MessageManager::getInstance()->deliverMessage ((Message*) lParam);
  204613. return 0;
  204614. }
  204615. else if (message == broadcastId)
  204616. {
  204617. const ScopedPointer <String> messageString ((String*) lParam);
  204618. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  204619. return 0;
  204620. }
  204621. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  204622. {
  204623. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  204624. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  204625. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  204626. return 0;
  204627. }
  204628. }
  204629. }
  204630. JUCE_CATCH_EXCEPTION
  204631. return DefWindowProc (h, message, wParam, lParam);
  204632. }
  204633. static bool isEventBlockedByModalComps (MSG& m)
  204634. {
  204635. if (Component::getNumCurrentlyModalComponents() == 0
  204636. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  204637. return false;
  204638. switch (m.message)
  204639. {
  204640. case WM_MOUSEMOVE:
  204641. case WM_NCMOUSEMOVE:
  204642. case 0x020A: /* WM_MOUSEWHEEL */
  204643. case 0x020E: /* WM_MOUSEHWHEEL */
  204644. case WM_KEYUP:
  204645. case WM_SYSKEYUP:
  204646. case WM_CHAR:
  204647. case WM_APPCOMMAND:
  204648. case WM_LBUTTONUP:
  204649. case WM_MBUTTONUP:
  204650. case WM_RBUTTONUP:
  204651. case WM_MOUSEACTIVATE:
  204652. case WM_NCMOUSEHOVER:
  204653. case WM_MOUSEHOVER:
  204654. return true;
  204655. case WM_NCLBUTTONDOWN:
  204656. case WM_NCLBUTTONDBLCLK:
  204657. case WM_NCRBUTTONDOWN:
  204658. case WM_NCRBUTTONDBLCLK:
  204659. case WM_NCMBUTTONDOWN:
  204660. case WM_NCMBUTTONDBLCLK:
  204661. case WM_LBUTTONDOWN:
  204662. case WM_LBUTTONDBLCLK:
  204663. case WM_MBUTTONDOWN:
  204664. case WM_MBUTTONDBLCLK:
  204665. case WM_RBUTTONDOWN:
  204666. case WM_RBUTTONDBLCLK:
  204667. case WM_KEYDOWN:
  204668. case WM_SYSKEYDOWN:
  204669. {
  204670. Component* const modal = Component::getCurrentlyModalComponent (0);
  204671. if (modal != 0)
  204672. modal->inputAttemptWhenModal();
  204673. return true;
  204674. }
  204675. default:
  204676. break;
  204677. }
  204678. return false;
  204679. }
  204680. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  204681. {
  204682. MSG m;
  204683. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  204684. return false;
  204685. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  204686. {
  204687. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  204688. {
  204689. MessageManager::getInstance()->deliverMessage ((Message*) (void*) m.lParam);
  204690. }
  204691. else if (m.message == WM_QUIT)
  204692. {
  204693. if (JUCEApplication::getInstance() != 0)
  204694. JUCEApplication::getInstance()->systemRequestedQuit();
  204695. }
  204696. else if (! isEventBlockedByModalComps (m))
  204697. {
  204698. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  204699. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  204700. {
  204701. // if it's someone else's window being clicked on, and the focus is
  204702. // currently on a juce window, pass the kb focus over..
  204703. HWND currentFocus = GetFocus();
  204704. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  204705. SetFocus (m.hwnd);
  204706. }
  204707. TranslateMessage (&m);
  204708. DispatchMessage (&m);
  204709. }
  204710. }
  204711. return true;
  204712. }
  204713. bool juce_postMessageToSystemQueue (Message* message)
  204714. {
  204715. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  204716. }
  204717. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  204718. void* userData)
  204719. {
  204720. if (MessageManager::getInstance()->isThisTheMessageThread())
  204721. {
  204722. return (*callback) (userData);
  204723. }
  204724. else
  204725. {
  204726. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  204727. // deadlock because the message manager is blocked from running, and can't
  204728. // call your function..
  204729. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  204730. return (void*) SendMessage (juce_messageWindowHandle,
  204731. specialCallbackId,
  204732. (WPARAM) callback,
  204733. (LPARAM) userData);
  204734. }
  204735. }
  204736. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  204737. {
  204738. if (hwnd != juce_messageWindowHandle)
  204739. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  204740. return TRUE;
  204741. }
  204742. void MessageManager::broadcastMessage (const String& value) throw()
  204743. {
  204744. Array<void*> windows;
  204745. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  204746. const String localCopy (value);
  204747. COPYDATASTRUCT data;
  204748. data.dwData = broadcastId;
  204749. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  204750. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  204751. for (int i = windows.size(); --i >= 0;)
  204752. {
  204753. HWND hwnd = (HWND) windows.getUnchecked(i);
  204754. TCHAR windowName [64]; // no need to read longer strings than this
  204755. GetWindowText (hwnd, windowName, 64);
  204756. windowName [63] = 0;
  204757. if (String (windowName) == messageWindowName)
  204758. {
  204759. DWORD_PTR result;
  204760. SendMessageTimeout (hwnd, WM_COPYDATA,
  204761. (WPARAM) juce_messageWindowHandle,
  204762. (LPARAM) &data,
  204763. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  204764. 8000,
  204765. &result);
  204766. }
  204767. }
  204768. }
  204769. static const String getMessageWindowClassName()
  204770. {
  204771. // this name has to be different for each app/dll instance because otherwise
  204772. // poor old Win32 can get a bit confused (even despite it not being a process-global
  204773. // window class).
  204774. static int number = 0;
  204775. if (number == 0)
  204776. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  204777. return "JUCEcs_" + String (number);
  204778. }
  204779. void MessageManager::doPlatformSpecificInitialisation()
  204780. {
  204781. OleInitialize (0);
  204782. const String className (getMessageWindowClassName());
  204783. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204784. WNDCLASSEX wc;
  204785. zerostruct (wc);
  204786. wc.cbSize = sizeof (wc);
  204787. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  204788. wc.cbWndExtra = 4;
  204789. wc.hInstance = hmod;
  204790. wc.lpszClassName = className;
  204791. RegisterClassEx (&wc);
  204792. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  204793. messageWindowName,
  204794. 0, 0, 0, 0, 0, 0, 0,
  204795. hmod, 0);
  204796. }
  204797. void MessageManager::doPlatformSpecificShutdown()
  204798. {
  204799. DestroyWindow (juce_messageWindowHandle);
  204800. UnregisterClass (getMessageWindowClassName(), 0);
  204801. OleUninitialize();
  204802. }
  204803. #endif
  204804. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  204805. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  204806. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204807. // compiled on its own).
  204808. #if JUCE_INCLUDED_FILE
  204809. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  204810. // these are in the windows SDK, but need to be repeated here for GCC..
  204811. #ifndef GET_APPCOMMAND_LPARAM
  204812. #define FAPPCOMMAND_MASK 0xF000
  204813. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  204814. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  204815. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  204816. #define APPCOMMAND_MEDIA_STOP 13
  204817. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  204818. #define WM_APPCOMMAND 0x0319
  204819. #endif
  204820. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  204821. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  204822. extern bool juce_IsRunningInWine();
  204823. #ifndef ULW_ALPHA
  204824. #define ULW_ALPHA 0x00000002
  204825. #endif
  204826. #ifndef AC_SRC_ALPHA
  204827. #define AC_SRC_ALPHA 0x01
  204828. #endif
  204829. static HPALETTE palette = 0;
  204830. static bool createPaletteIfNeeded = true;
  204831. static bool shouldDeactivateTitleBar = true;
  204832. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY);
  204833. #define WM_TRAYNOTIFY WM_USER + 100
  204834. using ::abs;
  204835. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  204836. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  204837. bool Desktop::canUseSemiTransparentWindows() throw()
  204838. {
  204839. if (updateLayeredWindow == 0)
  204840. {
  204841. if (! juce_IsRunningInWine())
  204842. {
  204843. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  204844. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  204845. }
  204846. }
  204847. return updateLayeredWindow != 0;
  204848. }
  204849. const int extendedKeyModifier = 0x10000;
  204850. const int KeyPress::spaceKey = VK_SPACE;
  204851. const int KeyPress::returnKey = VK_RETURN;
  204852. const int KeyPress::escapeKey = VK_ESCAPE;
  204853. const int KeyPress::backspaceKey = VK_BACK;
  204854. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  204855. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  204856. const int KeyPress::tabKey = VK_TAB;
  204857. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  204858. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  204859. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  204860. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  204861. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  204862. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  204863. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  204864. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  204865. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  204866. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  204867. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  204868. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  204869. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  204870. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  204871. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  204872. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  204873. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  204874. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  204875. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  204876. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  204877. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  204878. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  204879. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  204880. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  204881. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  204882. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  204883. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  204884. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  204885. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  204886. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  204887. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  204888. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  204889. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  204890. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  204891. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  204892. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  204893. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  204894. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  204895. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  204896. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  204897. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  204898. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  204899. const int KeyPress::playKey = 0x30000;
  204900. const int KeyPress::stopKey = 0x30001;
  204901. const int KeyPress::fastForwardKey = 0x30002;
  204902. const int KeyPress::rewindKey = 0x30003;
  204903. class WindowsBitmapImage : public Image::SharedImage
  204904. {
  204905. public:
  204906. HBITMAP hBitmap;
  204907. BITMAPV4HEADER bitmapInfo;
  204908. HDC hdc;
  204909. unsigned char* bitmapData;
  204910. WindowsBitmapImage (const Image::PixelFormat format_,
  204911. const int w, const int h, const bool clearImage)
  204912. : Image::SharedImage (format_, w, h)
  204913. {
  204914. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  204915. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  204916. zerostruct (bitmapInfo);
  204917. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  204918. bitmapInfo.bV4Width = w;
  204919. bitmapInfo.bV4Height = h;
  204920. bitmapInfo.bV4Planes = 1;
  204921. bitmapInfo.bV4CSType = 1;
  204922. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  204923. if (format_ == Image::ARGB)
  204924. {
  204925. bitmapInfo.bV4AlphaMask = 0xff000000;
  204926. bitmapInfo.bV4RedMask = 0xff0000;
  204927. bitmapInfo.bV4GreenMask = 0xff00;
  204928. bitmapInfo.bV4BlueMask = 0xff;
  204929. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  204930. }
  204931. else
  204932. {
  204933. bitmapInfo.bV4V4Compression = BI_RGB;
  204934. }
  204935. lineStride = -((w * pixelStride + 3) & ~3);
  204936. HDC dc = GetDC (0);
  204937. hdc = CreateCompatibleDC (dc);
  204938. ReleaseDC (0, dc);
  204939. SetMapMode (hdc, MM_TEXT);
  204940. hBitmap = CreateDIBSection (hdc,
  204941. (BITMAPINFO*) &(bitmapInfo),
  204942. DIB_RGB_COLORS,
  204943. (void**) &bitmapData,
  204944. 0, 0);
  204945. SelectObject (hdc, hBitmap);
  204946. if (format_ == Image::ARGB && clearImage)
  204947. zeromem (bitmapData, abs (h * lineStride));
  204948. imageData = bitmapData - (lineStride * (h - 1));
  204949. }
  204950. ~WindowsBitmapImage()
  204951. {
  204952. DeleteDC (hdc);
  204953. DeleteObject (hBitmap);
  204954. }
  204955. Image::ImageType getType() const { return Image::NativeImage; }
  204956. LowLevelGraphicsContext* createLowLevelContext()
  204957. {
  204958. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  204959. }
  204960. SharedImage* clone()
  204961. {
  204962. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  204963. for (int i = 0; i < height; ++i)
  204964. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  204965. return im;
  204966. }
  204967. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  204968. const int x, const int y,
  204969. const RectangleList& maskedRegion) throw()
  204970. {
  204971. static HDRAWDIB hdd = 0;
  204972. static bool needToCreateDrawDib = true;
  204973. if (needToCreateDrawDib)
  204974. {
  204975. needToCreateDrawDib = false;
  204976. HDC dc = GetDC (0);
  204977. const int n = GetDeviceCaps (dc, BITSPIXEL);
  204978. ReleaseDC (0, dc);
  204979. // only open if we're not palettised
  204980. if (n > 8)
  204981. hdd = DrawDibOpen();
  204982. }
  204983. if (createPaletteIfNeeded)
  204984. {
  204985. HDC dc = GetDC (0);
  204986. const int n = GetDeviceCaps (dc, BITSPIXEL);
  204987. ReleaseDC (0, dc);
  204988. if (n <= 8)
  204989. palette = CreateHalftonePalette (dc);
  204990. createPaletteIfNeeded = false;
  204991. }
  204992. if (palette != 0)
  204993. {
  204994. SelectPalette (dc, palette, FALSE);
  204995. RealizePalette (dc);
  204996. SetStretchBltMode (dc, HALFTONE);
  204997. }
  204998. SetMapMode (dc, MM_TEXT);
  204999. if (transparent)
  205000. {
  205001. POINT p, pos;
  205002. SIZE size;
  205003. RECT windowBounds;
  205004. GetWindowRect (hwnd, &windowBounds);
  205005. p.x = -x;
  205006. p.y = -y;
  205007. pos.x = windowBounds.left;
  205008. pos.y = windowBounds.top;
  205009. size.cx = windowBounds.right - windowBounds.left;
  205010. size.cy = windowBounds.bottom - windowBounds.top;
  205011. BLENDFUNCTION bf;
  205012. bf.AlphaFormat = AC_SRC_ALPHA;
  205013. bf.BlendFlags = 0;
  205014. bf.BlendOp = AC_SRC_OVER;
  205015. bf.SourceConstantAlpha = 0xff;
  205016. if (! maskedRegion.isEmpty())
  205017. {
  205018. for (RectangleList::Iterator i (maskedRegion); i.next();)
  205019. {
  205020. const Rectangle<int>& r = *i.getRectangle();
  205021. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  205022. }
  205023. }
  205024. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  205025. }
  205026. else
  205027. {
  205028. int savedDC = 0;
  205029. if (! maskedRegion.isEmpty())
  205030. {
  205031. savedDC = SaveDC (dc);
  205032. for (RectangleList::Iterator i (maskedRegion); i.next();)
  205033. {
  205034. const Rectangle<int>& r = *i.getRectangle();
  205035. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  205036. }
  205037. }
  205038. if (hdd == 0)
  205039. {
  205040. StretchDIBits (dc,
  205041. x, y, width, height,
  205042. 0, 0, width, height,
  205043. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  205044. DIB_RGB_COLORS, SRCCOPY);
  205045. }
  205046. else
  205047. {
  205048. DrawDibDraw (hdd, dc, x, y, -1, -1,
  205049. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  205050. 0, 0, width, height, 0);
  205051. }
  205052. if (! maskedRegion.isEmpty())
  205053. RestoreDC (dc, savedDC);
  205054. }
  205055. }
  205056. juce_UseDebuggingNewOperator
  205057. private:
  205058. WindowsBitmapImage (const WindowsBitmapImage&);
  205059. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  205060. };
  205061. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  205062. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  205063. {
  205064. SHORT k = (SHORT) keyCode;
  205065. if ((keyCode & extendedKeyModifier) == 0
  205066. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  205067. k += (SHORT) 'A' - (SHORT) 'a';
  205068. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  205069. (SHORT) '+', VK_OEM_PLUS,
  205070. (SHORT) '-', VK_OEM_MINUS,
  205071. (SHORT) '.', VK_OEM_PERIOD,
  205072. (SHORT) ';', VK_OEM_1,
  205073. (SHORT) ':', VK_OEM_1,
  205074. (SHORT) '/', VK_OEM_2,
  205075. (SHORT) '?', VK_OEM_2,
  205076. (SHORT) '[', VK_OEM_4,
  205077. (SHORT) ']', VK_OEM_6 };
  205078. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  205079. if (k == translatedValues [i])
  205080. k = translatedValues [i + 1];
  205081. return (GetKeyState (k) & 0x8000) != 0;
  205082. }
  205083. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  205084. {
  205085. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  205086. return callback (userData);
  205087. else
  205088. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  205089. }
  205090. class Win32ComponentPeer : public ComponentPeer
  205091. {
  205092. public:
  205093. Win32ComponentPeer (Component* const component,
  205094. const int windowStyleFlags)
  205095. : ComponentPeer (component, windowStyleFlags),
  205096. dontRepaint (false),
  205097. fullScreen (false),
  205098. isDragging (false),
  205099. isMouseOver (false),
  205100. hasCreatedCaret (false),
  205101. currentWindowIcon (0),
  205102. taskBarIcon (0),
  205103. dropTarget (0)
  205104. {
  205105. callFunctionIfNotLocked (&createWindowCallback, this);
  205106. setTitle (component->getName());
  205107. if ((windowStyleFlags & windowHasDropShadow) != 0
  205108. && Desktop::canUseSemiTransparentWindows())
  205109. {
  205110. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  205111. if (shadower != 0)
  205112. shadower->setOwner (component);
  205113. }
  205114. else
  205115. {
  205116. shadower = 0;
  205117. }
  205118. }
  205119. ~Win32ComponentPeer()
  205120. {
  205121. setTaskBarIcon (Image());
  205122. deleteAndZero (shadower);
  205123. // do this before the next bit to avoid messages arriving for this window
  205124. // before it's destroyed
  205125. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  205126. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  205127. if (currentWindowIcon != 0)
  205128. DestroyIcon (currentWindowIcon);
  205129. if (dropTarget != 0)
  205130. {
  205131. dropTarget->Release();
  205132. dropTarget = 0;
  205133. }
  205134. }
  205135. void* getNativeHandle() const
  205136. {
  205137. return hwnd;
  205138. }
  205139. void setVisible (bool shouldBeVisible)
  205140. {
  205141. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  205142. if (shouldBeVisible)
  205143. InvalidateRect (hwnd, 0, 0);
  205144. else
  205145. lastPaintTime = 0;
  205146. }
  205147. void setTitle (const String& title)
  205148. {
  205149. SetWindowText (hwnd, title);
  205150. }
  205151. void setPosition (int x, int y)
  205152. {
  205153. offsetWithinParent (x, y);
  205154. SetWindowPos (hwnd, 0,
  205155. x - windowBorder.getLeft(),
  205156. y - windowBorder.getTop(),
  205157. 0, 0,
  205158. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205159. }
  205160. void repaintNowIfTransparent()
  205161. {
  205162. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  205163. handlePaintMessage();
  205164. }
  205165. void updateBorderSize()
  205166. {
  205167. WINDOWINFO info;
  205168. info.cbSize = sizeof (info);
  205169. if (GetWindowInfo (hwnd, &info))
  205170. {
  205171. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  205172. info.rcClient.left - info.rcWindow.left,
  205173. info.rcWindow.bottom - info.rcClient.bottom,
  205174. info.rcWindow.right - info.rcClient.right);
  205175. }
  205176. }
  205177. void setSize (int w, int h)
  205178. {
  205179. SetWindowPos (hwnd, 0, 0, 0,
  205180. w + windowBorder.getLeftAndRight(),
  205181. h + windowBorder.getTopAndBottom(),
  205182. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205183. updateBorderSize();
  205184. repaintNowIfTransparent();
  205185. }
  205186. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  205187. {
  205188. fullScreen = isNowFullScreen;
  205189. offsetWithinParent (x, y);
  205190. SetWindowPos (hwnd, 0,
  205191. x - windowBorder.getLeft(),
  205192. y - windowBorder.getTop(),
  205193. w + windowBorder.getLeftAndRight(),
  205194. h + windowBorder.getTopAndBottom(),
  205195. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205196. updateBorderSize();
  205197. repaintNowIfTransparent();
  205198. }
  205199. const Rectangle<int> getBounds() const
  205200. {
  205201. RECT r;
  205202. GetWindowRect (hwnd, &r);
  205203. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  205204. HWND parentH = GetParent (hwnd);
  205205. if (parentH != 0)
  205206. {
  205207. GetWindowRect (parentH, &r);
  205208. bounds.translate (-r.left, -r.top);
  205209. }
  205210. return windowBorder.subtractedFrom (bounds);
  205211. }
  205212. const Point<int> getScreenPosition() const
  205213. {
  205214. RECT r;
  205215. GetWindowRect (hwnd, &r);
  205216. return Point<int> (r.left + windowBorder.getLeft(),
  205217. r.top + windowBorder.getTop());
  205218. }
  205219. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  205220. {
  205221. return relativePosition + getScreenPosition();
  205222. }
  205223. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  205224. {
  205225. return screenPosition - getScreenPosition();
  205226. }
  205227. void setMinimised (bool shouldBeMinimised)
  205228. {
  205229. if (shouldBeMinimised != isMinimised())
  205230. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  205231. }
  205232. bool isMinimised() const
  205233. {
  205234. WINDOWPLACEMENT wp;
  205235. wp.length = sizeof (WINDOWPLACEMENT);
  205236. GetWindowPlacement (hwnd, &wp);
  205237. return wp.showCmd == SW_SHOWMINIMIZED;
  205238. }
  205239. void setFullScreen (bool shouldBeFullScreen)
  205240. {
  205241. setMinimised (false);
  205242. if (fullScreen != shouldBeFullScreen)
  205243. {
  205244. fullScreen = shouldBeFullScreen;
  205245. const Component::SafePointer<Component> deletionChecker (component);
  205246. if (! fullScreen)
  205247. {
  205248. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  205249. if (hasTitleBar())
  205250. ShowWindow (hwnd, SW_SHOWNORMAL);
  205251. if (! boundsCopy.isEmpty())
  205252. {
  205253. setBounds (boundsCopy.getX(),
  205254. boundsCopy.getY(),
  205255. boundsCopy.getWidth(),
  205256. boundsCopy.getHeight(),
  205257. false);
  205258. }
  205259. }
  205260. else
  205261. {
  205262. if (hasTitleBar())
  205263. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  205264. else
  205265. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  205266. }
  205267. if (deletionChecker != 0)
  205268. handleMovedOrResized();
  205269. }
  205270. }
  205271. bool isFullScreen() const
  205272. {
  205273. if (! hasTitleBar())
  205274. return fullScreen;
  205275. WINDOWPLACEMENT wp;
  205276. wp.length = sizeof (wp);
  205277. GetWindowPlacement (hwnd, &wp);
  205278. return wp.showCmd == SW_SHOWMAXIMIZED;
  205279. }
  205280. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  205281. {
  205282. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  205283. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  205284. return false;
  205285. RECT r;
  205286. GetWindowRect (hwnd, &r);
  205287. POINT p;
  205288. p.x = position.getX() + r.left + windowBorder.getLeft();
  205289. p.y = position.getY() + r.top + windowBorder.getTop();
  205290. HWND w = WindowFromPoint (p);
  205291. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  205292. }
  205293. const BorderSize getFrameSize() const
  205294. {
  205295. return windowBorder;
  205296. }
  205297. bool setAlwaysOnTop (bool alwaysOnTop)
  205298. {
  205299. const bool oldDeactivate = shouldDeactivateTitleBar;
  205300. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205301. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  205302. 0, 0, 0, 0,
  205303. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205304. shouldDeactivateTitleBar = oldDeactivate;
  205305. if (shadower != 0)
  205306. shadower->componentBroughtToFront (*component);
  205307. return true;
  205308. }
  205309. void toFront (bool makeActive)
  205310. {
  205311. setMinimised (false);
  205312. const bool oldDeactivate = shouldDeactivateTitleBar;
  205313. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205314. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  205315. shouldDeactivateTitleBar = oldDeactivate;
  205316. if (! makeActive)
  205317. {
  205318. // in this case a broughttofront call won't have occured, so do it now..
  205319. handleBroughtToFront();
  205320. }
  205321. }
  205322. void toBehind (ComponentPeer* other)
  205323. {
  205324. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  205325. jassert (otherPeer != 0); // wrong type of window?
  205326. if (otherPeer != 0)
  205327. {
  205328. setMinimised (false);
  205329. // must be careful not to try to put a topmost window behind a normal one, or win32
  205330. // promotes the normal one to be topmost!
  205331. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  205332. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  205333. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205334. else if (otherPeer->getComponent()->isAlwaysOnTop())
  205335. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  205336. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205337. }
  205338. }
  205339. bool isFocused() const
  205340. {
  205341. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  205342. }
  205343. void grabFocus()
  205344. {
  205345. const bool oldDeactivate = shouldDeactivateTitleBar;
  205346. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205347. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  205348. shouldDeactivateTitleBar = oldDeactivate;
  205349. }
  205350. void textInputRequired (const Point<int>&)
  205351. {
  205352. if (! hasCreatedCaret)
  205353. {
  205354. hasCreatedCaret = true;
  205355. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  205356. }
  205357. ShowCaret (hwnd);
  205358. SetCaretPos (0, 0);
  205359. }
  205360. void repaint (const Rectangle<int>& area)
  205361. {
  205362. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  205363. InvalidateRect (hwnd, &r, FALSE);
  205364. }
  205365. void performAnyPendingRepaintsNow()
  205366. {
  205367. MSG m;
  205368. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  205369. DispatchMessage (&m);
  205370. }
  205371. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  205372. {
  205373. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  205374. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  205375. return 0;
  205376. }
  205377. void setTaskBarIcon (const Image& image)
  205378. {
  205379. if (image.isValid())
  205380. {
  205381. HICON hicon = createHICONFromImage (image, TRUE, 0, 0);
  205382. if (taskBarIcon == 0)
  205383. {
  205384. taskBarIcon = new NOTIFYICONDATA();
  205385. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  205386. taskBarIcon->hWnd = (HWND) hwnd;
  205387. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  205388. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  205389. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  205390. taskBarIcon->hIcon = hicon;
  205391. taskBarIcon->szTip[0] = 0;
  205392. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  205393. }
  205394. else
  205395. {
  205396. HICON oldIcon = taskBarIcon->hIcon;
  205397. taskBarIcon->hIcon = hicon;
  205398. taskBarIcon->uFlags = NIF_ICON;
  205399. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  205400. DestroyIcon (oldIcon);
  205401. }
  205402. DestroyIcon (hicon);
  205403. }
  205404. else if (taskBarIcon != 0)
  205405. {
  205406. taskBarIcon->uFlags = 0;
  205407. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  205408. DestroyIcon (taskBarIcon->hIcon);
  205409. deleteAndZero (taskBarIcon);
  205410. }
  205411. }
  205412. void setTaskBarIconToolTip (const String& toolTip) const
  205413. {
  205414. if (taskBarIcon != 0)
  205415. {
  205416. taskBarIcon->uFlags = NIF_TIP;
  205417. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  205418. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  205419. }
  205420. }
  205421. bool isInside (HWND h) const
  205422. {
  205423. return GetAncestor (hwnd, GA_ROOT) == h;
  205424. }
  205425. static void updateKeyModifiers() throw()
  205426. {
  205427. int keyMods = 0;
  205428. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  205429. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  205430. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  205431. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  205432. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  205433. }
  205434. static void updateModifiersFromWParam (const WPARAM wParam)
  205435. {
  205436. int mouseMods = 0;
  205437. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  205438. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  205439. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  205440. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  205441. updateKeyModifiers();
  205442. }
  205443. static int64 getMouseEventTime()
  205444. {
  205445. static int64 eventTimeOffset = 0;
  205446. static DWORD lastMessageTime = 0;
  205447. const DWORD thisMessageTime = GetMessageTime();
  205448. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  205449. {
  205450. lastMessageTime = thisMessageTime;
  205451. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  205452. }
  205453. return eventTimeOffset + thisMessageTime;
  205454. }
  205455. juce_UseDebuggingNewOperator
  205456. bool dontRepaint;
  205457. static ModifierKeys currentModifiers;
  205458. static ModifierKeys modifiersAtLastCallback;
  205459. private:
  205460. HWND hwnd;
  205461. DropShadower* shadower;
  205462. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  205463. BorderSize windowBorder;
  205464. HICON currentWindowIcon;
  205465. NOTIFYICONDATA* taskBarIcon;
  205466. IDropTarget* dropTarget;
  205467. class TemporaryImage : public Timer
  205468. {
  205469. public:
  205470. TemporaryImage() {}
  205471. ~TemporaryImage() {}
  205472. const Image& getImage (const bool transparent, const int w, const int h)
  205473. {
  205474. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  205475. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  205476. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  205477. startTimer (3000);
  205478. return image;
  205479. }
  205480. void timerCallback()
  205481. {
  205482. stopTimer();
  205483. image = Image::null;
  205484. }
  205485. private:
  205486. Image image;
  205487. TemporaryImage (const TemporaryImage&);
  205488. TemporaryImage& operator= (const TemporaryImage&);
  205489. };
  205490. TemporaryImage offscreenImageGenerator;
  205491. class WindowClassHolder : public DeletedAtShutdown
  205492. {
  205493. public:
  205494. WindowClassHolder()
  205495. : windowClassName ("JUCE_")
  205496. {
  205497. // this name has to be different for each app/dll instance because otherwise
  205498. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205499. // window class).
  205500. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  205501. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205502. TCHAR moduleFile [1024];
  205503. moduleFile[0] = 0;
  205504. GetModuleFileName (moduleHandle, moduleFile, 1024);
  205505. WORD iconNum = 0;
  205506. WNDCLASSEX wcex;
  205507. wcex.cbSize = sizeof (wcex);
  205508. wcex.style = CS_OWNDC;
  205509. wcex.lpfnWndProc = (WNDPROC) windowProc;
  205510. wcex.lpszClassName = windowClassName;
  205511. wcex.cbClsExtra = 0;
  205512. wcex.cbWndExtra = 32;
  205513. wcex.hInstance = moduleHandle;
  205514. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  205515. iconNum = 1;
  205516. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  205517. wcex.hCursor = 0;
  205518. wcex.hbrBackground = 0;
  205519. wcex.lpszMenuName = 0;
  205520. RegisterClassEx (&wcex);
  205521. }
  205522. ~WindowClassHolder()
  205523. {
  205524. if (ComponentPeer::getNumPeers() == 0)
  205525. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  205526. clearSingletonInstance();
  205527. }
  205528. String windowClassName;
  205529. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  205530. };
  205531. static void* createWindowCallback (void* userData)
  205532. {
  205533. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  205534. return 0;
  205535. }
  205536. void createWindow()
  205537. {
  205538. DWORD exstyle = WS_EX_ACCEPTFILES;
  205539. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  205540. if (hasTitleBar())
  205541. {
  205542. type |= WS_OVERLAPPED;
  205543. if ((styleFlags & windowHasCloseButton) != 0)
  205544. {
  205545. type |= WS_SYSMENU;
  205546. }
  205547. else
  205548. {
  205549. // annoyingly, windows won't let you have a min/max button without a close button
  205550. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  205551. }
  205552. if ((styleFlags & windowIsResizable) != 0)
  205553. type |= WS_THICKFRAME;
  205554. }
  205555. else
  205556. {
  205557. type |= WS_POPUP | WS_SYSMENU;
  205558. }
  205559. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  205560. exstyle |= WS_EX_TOOLWINDOW;
  205561. else
  205562. exstyle |= WS_EX_APPWINDOW;
  205563. if ((styleFlags & windowHasMinimiseButton) != 0)
  205564. type |= WS_MINIMIZEBOX;
  205565. if ((styleFlags & windowHasMaximiseButton) != 0)
  205566. type |= WS_MAXIMIZEBOX;
  205567. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  205568. exstyle |= WS_EX_TRANSPARENT;
  205569. if ((styleFlags & windowIsSemiTransparent) != 0
  205570. && Desktop::canUseSemiTransparentWindows())
  205571. exstyle |= WS_EX_LAYERED;
  205572. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  205573. if (hwnd != 0)
  205574. {
  205575. SetWindowLongPtr (hwnd, 0, 0);
  205576. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  205577. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  205578. if (dropTarget == 0)
  205579. dropTarget = new JuceDropTarget (this);
  205580. RegisterDragDrop (hwnd, dropTarget);
  205581. updateBorderSize();
  205582. // Calling this function here is (for some reason) necessary to make Windows
  205583. // correctly enable the menu items that we specify in the wm_initmenu message.
  205584. GetSystemMenu (hwnd, false);
  205585. }
  205586. else
  205587. {
  205588. jassertfalse;
  205589. }
  205590. }
  205591. static void* destroyWindowCallback (void* handle)
  205592. {
  205593. RevokeDragDrop ((HWND) handle);
  205594. DestroyWindow ((HWND) handle);
  205595. return 0;
  205596. }
  205597. static void* toFrontCallback1 (void* h)
  205598. {
  205599. SetForegroundWindow ((HWND) h);
  205600. return 0;
  205601. }
  205602. static void* toFrontCallback2 (void* h)
  205603. {
  205604. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205605. return 0;
  205606. }
  205607. static void* setFocusCallback (void* h)
  205608. {
  205609. SetFocus ((HWND) h);
  205610. return 0;
  205611. }
  205612. static void* getFocusCallback (void*)
  205613. {
  205614. return GetFocus();
  205615. }
  205616. void offsetWithinParent (int& x, int& y) const
  205617. {
  205618. if (isTransparent())
  205619. {
  205620. HWND parentHwnd = GetParent (hwnd);
  205621. if (parentHwnd != 0)
  205622. {
  205623. RECT parentRect;
  205624. GetWindowRect (parentHwnd, &parentRect);
  205625. x += parentRect.left;
  205626. y += parentRect.top;
  205627. }
  205628. }
  205629. }
  205630. bool isTransparent() const
  205631. {
  205632. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  205633. }
  205634. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  205635. void setIcon (const Image& newIcon)
  205636. {
  205637. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  205638. if (hicon != 0)
  205639. {
  205640. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  205641. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  205642. if (currentWindowIcon != 0)
  205643. DestroyIcon (currentWindowIcon);
  205644. currentWindowIcon = hicon;
  205645. }
  205646. }
  205647. void handlePaintMessage()
  205648. {
  205649. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  205650. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  205651. PAINTSTRUCT paintStruct;
  205652. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  205653. // message and become re-entrant, but that's OK
  205654. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  205655. // corrupt the image it's using to paint into, so do a check here.
  205656. static bool reentrant = false;
  205657. if (reentrant)
  205658. {
  205659. DeleteObject (rgn);
  205660. EndPaint (hwnd, &paintStruct);
  205661. return;
  205662. }
  205663. reentrant = true;
  205664. // this is the rectangle to update..
  205665. int x = paintStruct.rcPaint.left;
  205666. int y = paintStruct.rcPaint.top;
  205667. int w = paintStruct.rcPaint.right - x;
  205668. int h = paintStruct.rcPaint.bottom - y;
  205669. const bool transparent = isTransparent();
  205670. if (transparent)
  205671. {
  205672. // it's not possible to have a transparent window with a title bar at the moment!
  205673. jassert (! hasTitleBar());
  205674. RECT r;
  205675. GetWindowRect (hwnd, &r);
  205676. x = y = 0;
  205677. w = r.right - r.left;
  205678. h = r.bottom - r.top;
  205679. }
  205680. if (w > 0 && h > 0)
  205681. {
  205682. clearMaskedRegion();
  205683. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  205684. RectangleList contextClip;
  205685. const Rectangle<int> clipBounds (0, 0, w, h);
  205686. bool needToPaintAll = true;
  205687. if (regionType == COMPLEXREGION && ! transparent)
  205688. {
  205689. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  205690. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  205691. DeleteObject (clipRgn);
  205692. char rgnData [8192];
  205693. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  205694. if (res > 0 && res <= sizeof (rgnData))
  205695. {
  205696. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  205697. if (hdr->iType == RDH_RECTANGLES
  205698. && hdr->rcBound.right - hdr->rcBound.left >= w
  205699. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  205700. {
  205701. needToPaintAll = false;
  205702. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  205703. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  205704. while (--num >= 0)
  205705. {
  205706. if (rects->right <= x + w && rects->bottom <= y + h)
  205707. {
  205708. // (need to move this one pixel to the left because of a win32 bug)
  205709. const int cx = jmax (x, (int) rects->left - 1);
  205710. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  205711. .getIntersection (clipBounds));
  205712. }
  205713. else
  205714. {
  205715. needToPaintAll = true;
  205716. break;
  205717. }
  205718. ++rects;
  205719. }
  205720. }
  205721. }
  205722. }
  205723. if (needToPaintAll)
  205724. {
  205725. contextClip.clear();
  205726. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  205727. }
  205728. if (transparent)
  205729. {
  205730. RectangleList::Iterator i (contextClip);
  205731. while (i.next())
  205732. offscreenImage.clear (*i.getRectangle());
  205733. }
  205734. // if the component's not opaque, this won't draw properly unless the platform can support this
  205735. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  205736. updateCurrentModifiers();
  205737. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  205738. handlePaint (context);
  205739. if (! dontRepaint)
  205740. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  205741. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  205742. }
  205743. DeleteObject (rgn);
  205744. EndPaint (hwnd, &paintStruct);
  205745. reentrant = false;
  205746. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  205747. _fpreset(); // because some graphics cards can unmask FP exceptions
  205748. #endif
  205749. lastPaintTime = Time::getMillisecondCounter();
  205750. }
  205751. void doMouseEvent (const Point<int>& position)
  205752. {
  205753. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  205754. }
  205755. void doMouseMove (const Point<int>& position)
  205756. {
  205757. if (! isMouseOver)
  205758. {
  205759. isMouseOver = true;
  205760. updateKeyModifiers();
  205761. TRACKMOUSEEVENT tme;
  205762. tme.cbSize = sizeof (tme);
  205763. tme.dwFlags = TME_LEAVE;
  205764. tme.hwndTrack = hwnd;
  205765. tme.dwHoverTime = 0;
  205766. if (! TrackMouseEvent (&tme))
  205767. jassertfalse;
  205768. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  205769. }
  205770. else if (! isDragging)
  205771. {
  205772. if (! contains (position, false))
  205773. return;
  205774. }
  205775. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  205776. static uint32 lastMouseTime = 0;
  205777. const uint32 now = Time::getMillisecondCounter();
  205778. const int maxMouseMovesPerSecond = 60;
  205779. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  205780. {
  205781. lastMouseTime = now;
  205782. doMouseEvent (position);
  205783. }
  205784. }
  205785. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  205786. {
  205787. if (GetCapture() != hwnd)
  205788. SetCapture (hwnd);
  205789. doMouseMove (position);
  205790. updateModifiersFromWParam (wParam);
  205791. isDragging = true;
  205792. doMouseEvent (position);
  205793. }
  205794. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  205795. {
  205796. updateModifiersFromWParam (wParam);
  205797. isDragging = false;
  205798. // release the mouse capture if the user has released all buttons
  205799. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  205800. ReleaseCapture();
  205801. doMouseEvent (position);
  205802. }
  205803. void doCaptureChanged()
  205804. {
  205805. if (isDragging)
  205806. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  205807. }
  205808. void doMouseExit()
  205809. {
  205810. isMouseOver = false;
  205811. doMouseEvent (getCurrentMousePos());
  205812. }
  205813. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  205814. {
  205815. updateKeyModifiers();
  205816. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  205817. handleMouseWheel (0, position, getMouseEventTime(),
  205818. isVertical ? 0.0f : amount,
  205819. isVertical ? amount : 0.0f);
  205820. }
  205821. void sendModifierKeyChangeIfNeeded()
  205822. {
  205823. if (modifiersAtLastCallback != currentModifiers)
  205824. {
  205825. modifiersAtLastCallback = currentModifiers;
  205826. handleModifierKeysChange();
  205827. }
  205828. }
  205829. bool doKeyUp (const WPARAM key)
  205830. {
  205831. updateKeyModifiers();
  205832. switch (key)
  205833. {
  205834. case VK_SHIFT:
  205835. case VK_CONTROL:
  205836. case VK_MENU:
  205837. case VK_CAPITAL:
  205838. case VK_LWIN:
  205839. case VK_RWIN:
  205840. case VK_APPS:
  205841. case VK_NUMLOCK:
  205842. case VK_SCROLL:
  205843. case VK_LSHIFT:
  205844. case VK_RSHIFT:
  205845. case VK_LCONTROL:
  205846. case VK_LMENU:
  205847. case VK_RCONTROL:
  205848. case VK_RMENU:
  205849. sendModifierKeyChangeIfNeeded();
  205850. }
  205851. return handleKeyUpOrDown (false)
  205852. || Component::getCurrentlyModalComponent() != 0;
  205853. }
  205854. bool doKeyDown (const WPARAM key)
  205855. {
  205856. updateKeyModifiers();
  205857. bool used = false;
  205858. switch (key)
  205859. {
  205860. case VK_SHIFT:
  205861. case VK_LSHIFT:
  205862. case VK_RSHIFT:
  205863. case VK_CONTROL:
  205864. case VK_LCONTROL:
  205865. case VK_RCONTROL:
  205866. case VK_MENU:
  205867. case VK_LMENU:
  205868. case VK_RMENU:
  205869. case VK_LWIN:
  205870. case VK_RWIN:
  205871. case VK_CAPITAL:
  205872. case VK_NUMLOCK:
  205873. case VK_SCROLL:
  205874. case VK_APPS:
  205875. sendModifierKeyChangeIfNeeded();
  205876. break;
  205877. case VK_LEFT:
  205878. case VK_RIGHT:
  205879. case VK_UP:
  205880. case VK_DOWN:
  205881. case VK_PRIOR:
  205882. case VK_NEXT:
  205883. case VK_HOME:
  205884. case VK_END:
  205885. case VK_DELETE:
  205886. case VK_INSERT:
  205887. case VK_F1:
  205888. case VK_F2:
  205889. case VK_F3:
  205890. case VK_F4:
  205891. case VK_F5:
  205892. case VK_F6:
  205893. case VK_F7:
  205894. case VK_F8:
  205895. case VK_F9:
  205896. case VK_F10:
  205897. case VK_F11:
  205898. case VK_F12:
  205899. case VK_F13:
  205900. case VK_F14:
  205901. case VK_F15:
  205902. case VK_F16:
  205903. used = handleKeyUpOrDown (true);
  205904. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  205905. break;
  205906. case VK_ADD:
  205907. case VK_SUBTRACT:
  205908. case VK_MULTIPLY:
  205909. case VK_DIVIDE:
  205910. case VK_SEPARATOR:
  205911. case VK_DECIMAL:
  205912. used = handleKeyUpOrDown (true);
  205913. break;
  205914. default:
  205915. used = handleKeyUpOrDown (true);
  205916. {
  205917. MSG msg;
  205918. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  205919. {
  205920. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  205921. // manually generate the key-press event that matches this key-down.
  205922. const UINT keyChar = MapVirtualKey (key, 2);
  205923. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  205924. }
  205925. }
  205926. break;
  205927. }
  205928. if (Component::getCurrentlyModalComponent() != 0)
  205929. used = true;
  205930. return used;
  205931. }
  205932. bool doKeyChar (int key, const LPARAM flags)
  205933. {
  205934. updateKeyModifiers();
  205935. juce_wchar textChar = (juce_wchar) key;
  205936. const int virtualScanCode = (flags >> 16) & 0xff;
  205937. if (key >= '0' && key <= '9')
  205938. {
  205939. switch (virtualScanCode) // check for a numeric keypad scan-code
  205940. {
  205941. case 0x52:
  205942. case 0x4f:
  205943. case 0x50:
  205944. case 0x51:
  205945. case 0x4b:
  205946. case 0x4c:
  205947. case 0x4d:
  205948. case 0x47:
  205949. case 0x48:
  205950. case 0x49:
  205951. key = (key - '0') + KeyPress::numberPad0;
  205952. break;
  205953. default:
  205954. break;
  205955. }
  205956. }
  205957. else
  205958. {
  205959. // convert the scan code to an unmodified character code..
  205960. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  205961. UINT keyChar = MapVirtualKey (virtualKey, 2);
  205962. keyChar = LOWORD (keyChar);
  205963. if (keyChar != 0)
  205964. key = (int) keyChar;
  205965. // avoid sending junk text characters for some control-key combinations
  205966. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  205967. textChar = 0;
  205968. }
  205969. return handleKeyPress (key, textChar);
  205970. }
  205971. bool doAppCommand (const LPARAM lParam)
  205972. {
  205973. int key = 0;
  205974. switch (GET_APPCOMMAND_LPARAM (lParam))
  205975. {
  205976. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  205977. key = KeyPress::playKey;
  205978. break;
  205979. case APPCOMMAND_MEDIA_STOP:
  205980. key = KeyPress::stopKey;
  205981. break;
  205982. case APPCOMMAND_MEDIA_NEXTTRACK:
  205983. key = KeyPress::fastForwardKey;
  205984. break;
  205985. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  205986. key = KeyPress::rewindKey;
  205987. break;
  205988. }
  205989. if (key != 0)
  205990. {
  205991. updateKeyModifiers();
  205992. if (hwnd == GetActiveWindow())
  205993. {
  205994. handleKeyPress (key, 0);
  205995. return true;
  205996. }
  205997. }
  205998. return false;
  205999. }
  206000. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  206001. {
  206002. public:
  206003. JuceDropTarget (Win32ComponentPeer* const owner_)
  206004. : owner (owner_)
  206005. {
  206006. }
  206007. ~JuceDropTarget() {}
  206008. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206009. {
  206010. updateFileList (pDataObject);
  206011. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  206012. *pdwEffect = DROPEFFECT_COPY;
  206013. return S_OK;
  206014. }
  206015. HRESULT __stdcall DragLeave()
  206016. {
  206017. owner->handleFileDragExit (files);
  206018. return S_OK;
  206019. }
  206020. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206021. {
  206022. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  206023. *pdwEffect = DROPEFFECT_COPY;
  206024. return S_OK;
  206025. }
  206026. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206027. {
  206028. updateFileList (pDataObject);
  206029. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  206030. *pdwEffect = DROPEFFECT_COPY;
  206031. return S_OK;
  206032. }
  206033. private:
  206034. Win32ComponentPeer* const owner;
  206035. StringArray files;
  206036. void updateFileList (IDataObject* const pDataObject)
  206037. {
  206038. files.clear();
  206039. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206040. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206041. if (pDataObject->GetData (&format, &medium) == S_OK)
  206042. {
  206043. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  206044. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  206045. unsigned int i = 0;
  206046. if (pDropFiles->fWide)
  206047. {
  206048. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  206049. for (;;)
  206050. {
  206051. unsigned int len = 0;
  206052. while (i + len < totalLen && fname [i + len] != 0)
  206053. ++len;
  206054. if (len == 0)
  206055. break;
  206056. files.add (String (fname + i, len));
  206057. i += len + 1;
  206058. }
  206059. }
  206060. else
  206061. {
  206062. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  206063. for (;;)
  206064. {
  206065. unsigned int len = 0;
  206066. while (i + len < totalLen && fname [i + len] != 0)
  206067. ++len;
  206068. if (len == 0)
  206069. break;
  206070. files.add (String (fname + i, len));
  206071. i += len + 1;
  206072. }
  206073. }
  206074. GlobalUnlock (medium.hGlobal);
  206075. }
  206076. }
  206077. JuceDropTarget (const JuceDropTarget&);
  206078. JuceDropTarget& operator= (const JuceDropTarget&);
  206079. };
  206080. void doSettingChange()
  206081. {
  206082. Desktop::getInstance().refreshMonitorSizes();
  206083. if (fullScreen && ! isMinimised())
  206084. {
  206085. const Rectangle<int> r (component->getParentMonitorArea());
  206086. SetWindowPos (hwnd, 0,
  206087. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  206088. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  206089. }
  206090. }
  206091. public:
  206092. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  206093. {
  206094. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  206095. if (peer != 0)
  206096. return peer->peerWindowProc (h, message, wParam, lParam);
  206097. return DefWindowProcW (h, message, wParam, lParam);
  206098. }
  206099. private:
  206100. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  206101. {
  206102. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  206103. }
  206104. const Point<int> getCurrentMousePos() throw()
  206105. {
  206106. RECT wr;
  206107. GetWindowRect (hwnd, &wr);
  206108. const DWORD mp = GetMessagePos();
  206109. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  206110. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  206111. }
  206112. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  206113. {
  206114. if (isValidPeer (this))
  206115. {
  206116. switch (message)
  206117. {
  206118. case WM_NCHITTEST:
  206119. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  206120. return HTTRANSPARENT;
  206121. if (hasTitleBar())
  206122. break;
  206123. return HTCLIENT;
  206124. case WM_PAINT:
  206125. handlePaintMessage();
  206126. return 0;
  206127. case WM_NCPAINT:
  206128. if (wParam != 1)
  206129. handlePaintMessage();
  206130. if (hasTitleBar())
  206131. break;
  206132. return 0;
  206133. case WM_ERASEBKGND:
  206134. case WM_NCCALCSIZE:
  206135. if (hasTitleBar())
  206136. break;
  206137. return 1;
  206138. case WM_MOUSEMOVE:
  206139. doMouseMove (getPointFromLParam (lParam));
  206140. return 0;
  206141. case WM_MOUSELEAVE:
  206142. doMouseExit();
  206143. return 0;
  206144. case WM_LBUTTONDOWN:
  206145. case WM_MBUTTONDOWN:
  206146. case WM_RBUTTONDOWN:
  206147. doMouseDown (getPointFromLParam (lParam), wParam);
  206148. return 0;
  206149. case WM_LBUTTONUP:
  206150. case WM_MBUTTONUP:
  206151. case WM_RBUTTONUP:
  206152. doMouseUp (getPointFromLParam (lParam), wParam);
  206153. return 0;
  206154. case WM_CAPTURECHANGED:
  206155. doCaptureChanged();
  206156. return 0;
  206157. case WM_NCMOUSEMOVE:
  206158. if (hasTitleBar())
  206159. break;
  206160. return 0;
  206161. case 0x020A: /* WM_MOUSEWHEEL */
  206162. doMouseWheel (getCurrentMousePos(), wParam, true);
  206163. return 0;
  206164. case 0x020E: /* WM_MOUSEHWHEEL */
  206165. doMouseWheel (getCurrentMousePos(), wParam, false);
  206166. return 0;
  206167. case WM_WINDOWPOSCHANGING:
  206168. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  206169. {
  206170. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  206171. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  206172. {
  206173. if (constrainer != 0)
  206174. {
  206175. const Rectangle<int> current (component->getX() - windowBorder.getLeft(),
  206176. component->getY() - windowBorder.getTop(),
  206177. component->getWidth() + windowBorder.getLeftAndRight(),
  206178. component->getHeight() + windowBorder.getTopAndBottom());
  206179. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  206180. constrainer->checkBounds (pos, current,
  206181. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  206182. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  206183. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  206184. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  206185. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  206186. wp->x = pos.getX();
  206187. wp->y = pos.getY();
  206188. wp->cx = pos.getWidth();
  206189. wp->cy = pos.getHeight();
  206190. }
  206191. }
  206192. }
  206193. return 0;
  206194. case WM_WINDOWPOSCHANGED:
  206195. handleMovedOrResized();
  206196. if (dontRepaint)
  206197. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  206198. return 0;
  206199. case WM_KEYDOWN:
  206200. case WM_SYSKEYDOWN:
  206201. if (doKeyDown (wParam))
  206202. return 0;
  206203. break;
  206204. case WM_KEYUP:
  206205. case WM_SYSKEYUP:
  206206. if (doKeyUp (wParam))
  206207. return 0;
  206208. break;
  206209. case WM_CHAR:
  206210. if (doKeyChar ((int) wParam, lParam))
  206211. return 0;
  206212. break;
  206213. case WM_APPCOMMAND:
  206214. if (doAppCommand (lParam))
  206215. return TRUE;
  206216. break;
  206217. case WM_SETFOCUS:
  206218. updateKeyModifiers();
  206219. handleFocusGain();
  206220. break;
  206221. case WM_KILLFOCUS:
  206222. if (hasCreatedCaret)
  206223. {
  206224. hasCreatedCaret = false;
  206225. DestroyCaret();
  206226. }
  206227. handleFocusLoss();
  206228. break;
  206229. case WM_ACTIVATEAPP:
  206230. // Windows does weird things to process priority when you swap apps,
  206231. // so this forces an update when the app is brought to the front
  206232. if (wParam != FALSE)
  206233. juce_repeatLastProcessPriority();
  206234. else
  206235. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  206236. juce_CheckCurrentlyFocusedTopLevelWindow();
  206237. modifiersAtLastCallback = -1;
  206238. return 0;
  206239. case WM_ACTIVATE:
  206240. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  206241. {
  206242. modifiersAtLastCallback = -1;
  206243. updateKeyModifiers();
  206244. if (isMinimised())
  206245. {
  206246. component->repaint();
  206247. handleMovedOrResized();
  206248. if (! ComponentPeer::isValidPeer (this))
  206249. return 0;
  206250. }
  206251. if (LOWORD (wParam) == WA_CLICKACTIVE
  206252. && component->isCurrentlyBlockedByAnotherModalComponent())
  206253. {
  206254. const Point<int> mousePos (component->getMouseXYRelative());
  206255. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  206256. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  206257. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  206258. return 0;
  206259. }
  206260. handleBroughtToFront();
  206261. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206262. Component::getCurrentlyModalComponent()->toFront (true);
  206263. return 0;
  206264. }
  206265. break;
  206266. case WM_NCACTIVATE:
  206267. // while a temporary window is being shown, prevent Windows from deactivating the
  206268. // title bars of our main windows.
  206269. if (wParam == 0 && ! shouldDeactivateTitleBar)
  206270. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  206271. break;
  206272. case WM_MOUSEACTIVATE:
  206273. if (! component->getMouseClickGrabsKeyboardFocus())
  206274. return MA_NOACTIVATE;
  206275. break;
  206276. case WM_SHOWWINDOW:
  206277. if (wParam != 0)
  206278. handleBroughtToFront();
  206279. break;
  206280. case WM_CLOSE:
  206281. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  206282. handleUserClosingWindow();
  206283. return 0;
  206284. case WM_QUERYENDSESSION:
  206285. if (JUCEApplication::getInstance() != 0)
  206286. {
  206287. JUCEApplication::getInstance()->systemRequestedQuit();
  206288. return MessageManager::getInstance()->hasStopMessageBeenSent();
  206289. }
  206290. return TRUE;
  206291. case WM_TRAYNOTIFY:
  206292. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206293. {
  206294. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  206295. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206296. {
  206297. Component* const current = Component::getCurrentlyModalComponent();
  206298. if (current != 0)
  206299. current->inputAttemptWhenModal();
  206300. }
  206301. }
  206302. else
  206303. {
  206304. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  206305. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  206306. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  206307. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  206308. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  206309. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206310. eventMods = eventMods.withoutMouseButtons();
  206311. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  206312. Point<int>(), eventMods, component, component, getMouseEventTime(),
  206313. Point<int>(), getMouseEventTime(), 1, false);
  206314. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  206315. {
  206316. SetFocus (hwnd);
  206317. SetForegroundWindow (hwnd);
  206318. component->mouseDown (e);
  206319. }
  206320. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206321. {
  206322. component->mouseUp (e);
  206323. }
  206324. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206325. {
  206326. component->mouseDoubleClick (e);
  206327. }
  206328. else if (lParam == WM_MOUSEMOVE)
  206329. {
  206330. component->mouseMove (e);
  206331. }
  206332. }
  206333. break;
  206334. case WM_SYNCPAINT:
  206335. return 0;
  206336. case WM_PALETTECHANGED:
  206337. InvalidateRect (h, 0, 0);
  206338. break;
  206339. case WM_DISPLAYCHANGE:
  206340. InvalidateRect (h, 0, 0);
  206341. createPaletteIfNeeded = true;
  206342. // intentional fall-through...
  206343. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  206344. doSettingChange();
  206345. break;
  206346. case WM_INITMENU:
  206347. if (! hasTitleBar())
  206348. {
  206349. if (isFullScreen())
  206350. {
  206351. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  206352. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  206353. }
  206354. else if (! isMinimised())
  206355. {
  206356. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  206357. }
  206358. }
  206359. break;
  206360. case WM_SYSCOMMAND:
  206361. switch (wParam & 0xfff0)
  206362. {
  206363. case SC_CLOSE:
  206364. if (sendInputAttemptWhenModalMessage())
  206365. return 0;
  206366. if (hasTitleBar())
  206367. {
  206368. PostMessage (h, WM_CLOSE, 0, 0);
  206369. return 0;
  206370. }
  206371. break;
  206372. case SC_KEYMENU:
  206373. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  206374. // obscure situations that can arise if a modal loop is started from an alt-key
  206375. // keypress).
  206376. if (hasTitleBar() && h == GetCapture())
  206377. ReleaseCapture();
  206378. break;
  206379. case SC_MAXIMIZE:
  206380. if (sendInputAttemptWhenModalMessage())
  206381. return 0;
  206382. setFullScreen (true);
  206383. return 0;
  206384. case SC_MINIMIZE:
  206385. if (sendInputAttemptWhenModalMessage())
  206386. return 0;
  206387. if (! hasTitleBar())
  206388. {
  206389. setMinimised (true);
  206390. return 0;
  206391. }
  206392. break;
  206393. case SC_RESTORE:
  206394. if (sendInputAttemptWhenModalMessage())
  206395. return 0;
  206396. if (hasTitleBar())
  206397. {
  206398. if (isFullScreen())
  206399. {
  206400. setFullScreen (false);
  206401. return 0;
  206402. }
  206403. }
  206404. else
  206405. {
  206406. if (isMinimised())
  206407. setMinimised (false);
  206408. else if (isFullScreen())
  206409. setFullScreen (false);
  206410. return 0;
  206411. }
  206412. break;
  206413. }
  206414. break;
  206415. case WM_NCLBUTTONDOWN:
  206416. case WM_NCRBUTTONDOWN:
  206417. case WM_NCMBUTTONDOWN:
  206418. sendInputAttemptWhenModalMessage();
  206419. break;
  206420. //case WM_IME_STARTCOMPOSITION;
  206421. // return 0;
  206422. case WM_GETDLGCODE:
  206423. return DLGC_WANTALLKEYS;
  206424. default:
  206425. break;
  206426. }
  206427. }
  206428. return DefWindowProcW (h, message, wParam, lParam);
  206429. }
  206430. bool sendInputAttemptWhenModalMessage()
  206431. {
  206432. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206433. {
  206434. Component* const current = Component::getCurrentlyModalComponent();
  206435. if (current != 0)
  206436. current->inputAttemptWhenModal();
  206437. return true;
  206438. }
  206439. return false;
  206440. }
  206441. Win32ComponentPeer (const Win32ComponentPeer&);
  206442. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  206443. };
  206444. ModifierKeys Win32ComponentPeer::currentModifiers;
  206445. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  206446. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  206447. {
  206448. return new Win32ComponentPeer (this, styleFlags);
  206449. }
  206450. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  206451. void ModifierKeys::updateCurrentModifiers() throw()
  206452. {
  206453. currentModifiers = Win32ComponentPeer::currentModifiers;
  206454. }
  206455. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  206456. {
  206457. Win32ComponentPeer::updateKeyModifiers();
  206458. int keyMods = 0;
  206459. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  206460. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  206461. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  206462. Win32ComponentPeer::currentModifiers
  206463. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  206464. return Win32ComponentPeer::currentModifiers;
  206465. }
  206466. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  206467. {
  206468. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  206469. if (wp != 0)
  206470. wp->setTaskBarIcon (newImage);
  206471. }
  206472. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  206473. {
  206474. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  206475. if (wp != 0)
  206476. wp->setTaskBarIconToolTip (tooltip);
  206477. }
  206478. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  206479. {
  206480. DWORD val = GetWindowLong (h, styleType);
  206481. if (bitIsSet)
  206482. val |= feature;
  206483. else
  206484. val &= ~feature;
  206485. SetWindowLongPtr (h, styleType, val);
  206486. SetWindowPos (h, 0, 0, 0, 0, 0,
  206487. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  206488. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  206489. }
  206490. bool Process::isForegroundProcess()
  206491. {
  206492. HWND fg = GetForegroundWindow();
  206493. if (fg == 0)
  206494. return true;
  206495. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  206496. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  206497. // have to see if any of our windows are children of the foreground window
  206498. fg = GetAncestor (fg, GA_ROOT);
  206499. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  206500. {
  206501. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  206502. if (wp != 0 && wp->isInside (fg))
  206503. return true;
  206504. }
  206505. return false;
  206506. }
  206507. bool AlertWindow::showNativeDialogBox (const String& title,
  206508. const String& bodyText,
  206509. bool isOkCancel)
  206510. {
  206511. return MessageBox (0, bodyText, title,
  206512. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  206513. : MB_OK)) == IDOK;
  206514. }
  206515. void Desktop::createMouseInputSources()
  206516. {
  206517. mouseSources.add (new MouseInputSource (0, true));
  206518. }
  206519. const Point<int> Desktop::getMousePosition()
  206520. {
  206521. POINT mousePos;
  206522. GetCursorPos (&mousePos);
  206523. return Point<int> (mousePos.x, mousePos.y);
  206524. }
  206525. void Desktop::setMousePosition (const Point<int>& newPosition)
  206526. {
  206527. SetCursorPos (newPosition.getX(), newPosition.getY());
  206528. }
  206529. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  206530. {
  206531. return createSoftwareImage (format, width, height, clearImage);
  206532. }
  206533. class ScreenSaverDefeater : public Timer,
  206534. public DeletedAtShutdown
  206535. {
  206536. public:
  206537. ScreenSaverDefeater()
  206538. {
  206539. startTimer (10000);
  206540. timerCallback();
  206541. }
  206542. ~ScreenSaverDefeater() {}
  206543. void timerCallback()
  206544. {
  206545. if (Process::isForegroundProcess())
  206546. {
  206547. // simulate a shift key getting pressed..
  206548. INPUT input[2];
  206549. input[0].type = INPUT_KEYBOARD;
  206550. input[0].ki.wVk = VK_SHIFT;
  206551. input[0].ki.dwFlags = 0;
  206552. input[0].ki.dwExtraInfo = 0;
  206553. input[1].type = INPUT_KEYBOARD;
  206554. input[1].ki.wVk = VK_SHIFT;
  206555. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  206556. input[1].ki.dwExtraInfo = 0;
  206557. SendInput (2, input, sizeof (INPUT));
  206558. }
  206559. }
  206560. };
  206561. static ScreenSaverDefeater* screenSaverDefeater = 0;
  206562. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  206563. {
  206564. if (isEnabled)
  206565. deleteAndZero (screenSaverDefeater);
  206566. else if (screenSaverDefeater == 0)
  206567. screenSaverDefeater = new ScreenSaverDefeater();
  206568. }
  206569. bool Desktop::isScreenSaverEnabled()
  206570. {
  206571. return screenSaverDefeater == 0;
  206572. }
  206573. /* (The code below is the "correct" way to disable the screen saver, but it
  206574. completely fails on winXP when the saver is password-protected...)
  206575. static bool juce_screenSaverEnabled = true;
  206576. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  206577. {
  206578. juce_screenSaverEnabled = isEnabled;
  206579. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  206580. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  206581. }
  206582. bool Desktop::isScreenSaverEnabled() throw()
  206583. {
  206584. return juce_screenSaverEnabled;
  206585. }
  206586. */
  206587. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  206588. {
  206589. if (enableOrDisable)
  206590. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  206591. }
  206592. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  206593. {
  206594. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  206595. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  206596. return TRUE;
  206597. }
  206598. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  206599. {
  206600. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  206601. // make sure the first in the list is the main monitor
  206602. for (int i = 1; i < monitorCoords.size(); ++i)
  206603. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  206604. monitorCoords.swap (i, 0);
  206605. if (monitorCoords.size() == 0)
  206606. {
  206607. RECT r;
  206608. GetWindowRect (GetDesktopWindow(), &r);
  206609. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  206610. }
  206611. if (clipToWorkArea)
  206612. {
  206613. // clip the main monitor to the active non-taskbar area
  206614. RECT r;
  206615. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  206616. Rectangle<int>& screen = monitorCoords.getReference (0);
  206617. screen.setPosition (jmax (screen.getX(), (int) r.left),
  206618. jmax (screen.getY(), (int) r.top));
  206619. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  206620. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  206621. }
  206622. }
  206623. static const Image createImageFromHBITMAP (HBITMAP bitmap)
  206624. {
  206625. Image im;
  206626. if (bitmap != 0)
  206627. {
  206628. BITMAP bm;
  206629. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206630. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206631. {
  206632. HDC tempDC = GetDC (0);
  206633. HDC dc = CreateCompatibleDC (tempDC);
  206634. ReleaseDC (0, tempDC);
  206635. SelectObject (dc, bitmap);
  206636. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206637. Image::BitmapData imageData (im, true);
  206638. for (int y = bm.bmHeight; --y >= 0;)
  206639. {
  206640. for (int x = bm.bmWidth; --x >= 0;)
  206641. {
  206642. COLORREF col = GetPixel (dc, x, y);
  206643. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206644. (uint8) GetGValue (col),
  206645. (uint8) GetBValue (col)));
  206646. }
  206647. }
  206648. DeleteDC (dc);
  206649. }
  206650. }
  206651. return im;
  206652. }
  206653. static const Image createImageFromHICON (HICON icon)
  206654. {
  206655. ICONINFO info;
  206656. if (GetIconInfo (icon, &info))
  206657. {
  206658. Image mask (createImageFromHBITMAP (info.hbmMask));
  206659. Image image (createImageFromHBITMAP (info.hbmColor));
  206660. if (mask.isValid() && image.isValid())
  206661. {
  206662. for (int y = image.getHeight(); --y >= 0;)
  206663. {
  206664. for (int x = image.getWidth(); --x >= 0;)
  206665. {
  206666. const float brightness = mask.getPixelAt (x, y).getBrightness();
  206667. if (brightness > 0.0f)
  206668. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  206669. }
  206670. }
  206671. return image;
  206672. }
  206673. }
  206674. return Image::null;
  206675. }
  206676. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  206677. {
  206678. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  206679. Image bitmap (nativeBitmap);
  206680. {
  206681. Graphics g (bitmap);
  206682. g.drawImageAt (image, 0, 0);
  206683. }
  206684. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  206685. ICONINFO info;
  206686. info.fIcon = isIcon;
  206687. info.xHotspot = hotspotX;
  206688. info.yHotspot = hotspotY;
  206689. info.hbmMask = mask;
  206690. info.hbmColor = nativeBitmap->hBitmap;
  206691. HICON hi = CreateIconIndirect (&info);
  206692. DeleteObject (mask);
  206693. return hi;
  206694. }
  206695. const Image juce_createIconForFile (const File& file)
  206696. {
  206697. Image image;
  206698. WCHAR filename [1024];
  206699. file.getFullPathName().copyToUnicode (filename, 1023);
  206700. WORD iconNum = 0;
  206701. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  206702. filename, &iconNum);
  206703. if (icon != 0)
  206704. {
  206705. image = createImageFromHICON (icon);
  206706. DestroyIcon (icon);
  206707. }
  206708. return image;
  206709. }
  206710. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  206711. {
  206712. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  206713. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  206714. Image im (image);
  206715. if (im.getWidth() > maxW || im.getHeight() > maxH)
  206716. {
  206717. im = im.rescaled (maxW, maxH);
  206718. hotspotX = (hotspotX * maxW) / image.getWidth();
  206719. hotspotY = (hotspotY * maxH) / image.getHeight();
  206720. }
  206721. return createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  206722. }
  206723. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  206724. {
  206725. if (cursorHandle != 0 && ! isStandard)
  206726. DestroyCursor ((HCURSOR) cursorHandle);
  206727. }
  206728. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  206729. {
  206730. LPCTSTR cursorName = IDC_ARROW;
  206731. switch (type)
  206732. {
  206733. case NormalCursor: break;
  206734. case NoCursor: return 0;
  206735. case WaitCursor: cursorName = IDC_WAIT; break;
  206736. case IBeamCursor: cursorName = IDC_IBEAM; break;
  206737. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  206738. case CrosshairCursor: cursorName = IDC_CROSS; break;
  206739. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  206740. case LeftRightResizeCursor:
  206741. case LeftEdgeResizeCursor:
  206742. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  206743. case UpDownResizeCursor:
  206744. case TopEdgeResizeCursor:
  206745. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  206746. case TopLeftCornerResizeCursor:
  206747. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  206748. case TopRightCornerResizeCursor:
  206749. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  206750. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  206751. case DraggingHandCursor:
  206752. {
  206753. static void* dragHandCursor = 0;
  206754. if (dragHandCursor == 0)
  206755. {
  206756. static const unsigned char dragHandData[] =
  206757. { 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,
  206758. 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,
  206759. 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 };
  206760. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  206761. }
  206762. return dragHandCursor;
  206763. }
  206764. default:
  206765. jassertfalse; break;
  206766. }
  206767. HCURSOR cursorH = LoadCursor (0, cursorName);
  206768. if (cursorH == 0)
  206769. cursorH = LoadCursor (0, IDC_ARROW);
  206770. return cursorH;
  206771. }
  206772. void MouseCursor::showInWindow (ComponentPeer*) const
  206773. {
  206774. SetCursor ((HCURSOR) getHandle());
  206775. }
  206776. void MouseCursor::showInAllWindows() const
  206777. {
  206778. showInWindow (0);
  206779. }
  206780. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  206781. {
  206782. public:
  206783. JuceDropSource() {}
  206784. ~JuceDropSource() {}
  206785. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  206786. {
  206787. if (escapePressed)
  206788. return DRAGDROP_S_CANCEL;
  206789. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  206790. return DRAGDROP_S_DROP;
  206791. return S_OK;
  206792. }
  206793. HRESULT __stdcall GiveFeedback (DWORD)
  206794. {
  206795. return DRAGDROP_S_USEDEFAULTCURSORS;
  206796. }
  206797. };
  206798. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  206799. {
  206800. public:
  206801. JuceEnumFormatEtc (const FORMATETC* const format_)
  206802. : format (format_),
  206803. index (0)
  206804. {
  206805. }
  206806. ~JuceEnumFormatEtc() {}
  206807. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  206808. {
  206809. if (result == 0)
  206810. return E_POINTER;
  206811. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  206812. newOne->index = index;
  206813. *result = newOne;
  206814. return S_OK;
  206815. }
  206816. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  206817. {
  206818. if (pceltFetched != 0)
  206819. *pceltFetched = 0;
  206820. else if (celt != 1)
  206821. return S_FALSE;
  206822. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  206823. {
  206824. copyFormatEtc (lpFormatEtc [0], *format);
  206825. ++index;
  206826. if (pceltFetched != 0)
  206827. *pceltFetched = 1;
  206828. return S_OK;
  206829. }
  206830. return S_FALSE;
  206831. }
  206832. HRESULT __stdcall Skip (ULONG celt)
  206833. {
  206834. if (index + (int) celt >= 1)
  206835. return S_FALSE;
  206836. index += celt;
  206837. return S_OK;
  206838. }
  206839. HRESULT __stdcall Reset()
  206840. {
  206841. index = 0;
  206842. return S_OK;
  206843. }
  206844. private:
  206845. const FORMATETC* const format;
  206846. int index;
  206847. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  206848. {
  206849. dest = source;
  206850. if (source.ptd != 0)
  206851. {
  206852. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  206853. *(dest.ptd) = *(source.ptd);
  206854. }
  206855. }
  206856. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  206857. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  206858. };
  206859. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  206860. {
  206861. public:
  206862. JuceDataObject (JuceDropSource* const dropSource_,
  206863. const FORMATETC* const format_,
  206864. const STGMEDIUM* const medium_)
  206865. : dropSource (dropSource_),
  206866. format (format_),
  206867. medium (medium_)
  206868. {
  206869. }
  206870. virtual ~JuceDataObject()
  206871. {
  206872. jassert (refCount == 0);
  206873. }
  206874. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  206875. {
  206876. if ((pFormatEtc->tymed & format->tymed) != 0
  206877. && pFormatEtc->cfFormat == format->cfFormat
  206878. && pFormatEtc->dwAspect == format->dwAspect)
  206879. {
  206880. pMedium->tymed = format->tymed;
  206881. pMedium->pUnkForRelease = 0;
  206882. if (format->tymed == TYMED_HGLOBAL)
  206883. {
  206884. const SIZE_T len = GlobalSize (medium->hGlobal);
  206885. void* const src = GlobalLock (medium->hGlobal);
  206886. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  206887. memcpy (dst, src, len);
  206888. GlobalUnlock (medium->hGlobal);
  206889. pMedium->hGlobal = dst;
  206890. return S_OK;
  206891. }
  206892. }
  206893. return DV_E_FORMATETC;
  206894. }
  206895. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  206896. {
  206897. if (f == 0)
  206898. return E_INVALIDARG;
  206899. if (f->tymed == format->tymed
  206900. && f->cfFormat == format->cfFormat
  206901. && f->dwAspect == format->dwAspect)
  206902. return S_OK;
  206903. return DV_E_FORMATETC;
  206904. }
  206905. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  206906. {
  206907. pFormatEtcOut->ptd = 0;
  206908. return E_NOTIMPL;
  206909. }
  206910. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  206911. {
  206912. if (result == 0)
  206913. return E_POINTER;
  206914. if (direction == DATADIR_GET)
  206915. {
  206916. *result = new JuceEnumFormatEtc (format);
  206917. return S_OK;
  206918. }
  206919. *result = 0;
  206920. return E_NOTIMPL;
  206921. }
  206922. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  206923. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  206924. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  206925. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  206926. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  206927. private:
  206928. JuceDropSource* const dropSource;
  206929. const FORMATETC* const format;
  206930. const STGMEDIUM* const medium;
  206931. JuceDataObject (const JuceDataObject&);
  206932. JuceDataObject& operator= (const JuceDataObject&);
  206933. };
  206934. static HDROP createHDrop (const StringArray& fileNames)
  206935. {
  206936. int totalChars = 0;
  206937. for (int i = fileNames.size(); --i >= 0;)
  206938. totalChars += fileNames[i].length() + 1;
  206939. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  206940. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  206941. if (hDrop != 0)
  206942. {
  206943. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  206944. pDropFiles->pFiles = sizeof (DROPFILES);
  206945. pDropFiles->fWide = true;
  206946. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  206947. for (int i = 0; i < fileNames.size(); ++i)
  206948. {
  206949. fileNames[i].copyToUnicode (fname, 2048);
  206950. fname += fileNames[i].length() + 1;
  206951. }
  206952. *fname = 0;
  206953. GlobalUnlock (hDrop);
  206954. }
  206955. return hDrop;
  206956. }
  206957. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  206958. {
  206959. JuceDropSource* const source = new JuceDropSource();
  206960. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  206961. DWORD effect;
  206962. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  206963. data->Release();
  206964. source->Release();
  206965. return res == DRAGDROP_S_DROP;
  206966. }
  206967. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  206968. {
  206969. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206970. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206971. medium.hGlobal = createHDrop (files);
  206972. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  206973. : DROPEFFECT_COPY);
  206974. }
  206975. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  206976. {
  206977. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206978. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206979. const int numChars = text.length();
  206980. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  206981. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  206982. text.copyToUnicode (data, numChars + 1);
  206983. format.cfFormat = CF_UNICODETEXT;
  206984. GlobalUnlock (medium.hGlobal);
  206985. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  206986. }
  206987. #endif
  206988. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  206989. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  206990. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206991. // compiled on its own).
  206992. #if JUCE_INCLUDED_FILE
  206993. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  206994. NEWTEXTMETRICEXW*,
  206995. int type,
  206996. LPARAM lParam)
  206997. {
  206998. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  206999. {
  207000. const String fontName (lpelfe->elfLogFont.lfFaceName);
  207001. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  207002. }
  207003. return 1;
  207004. }
  207005. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  207006. NEWTEXTMETRICEXW*,
  207007. int type,
  207008. LPARAM lParam)
  207009. {
  207010. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  207011. {
  207012. LOGFONTW lf;
  207013. zerostruct (lf);
  207014. lf.lfWeight = FW_DONTCARE;
  207015. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  207016. lf.lfQuality = DEFAULT_QUALITY;
  207017. lf.lfCharSet = DEFAULT_CHARSET;
  207018. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  207019. lf.lfPitchAndFamily = FF_DONTCARE;
  207020. const String fontName (lpelfe->elfLogFont.lfFaceName);
  207021. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  207022. HDC dc = CreateCompatibleDC (0);
  207023. EnumFontFamiliesEx (dc, &lf,
  207024. (FONTENUMPROCW) &wfontEnum2,
  207025. lParam, 0);
  207026. DeleteDC (dc);
  207027. }
  207028. return 1;
  207029. }
  207030. const StringArray Font::findAllTypefaceNames()
  207031. {
  207032. StringArray results;
  207033. HDC dc = CreateCompatibleDC (0);
  207034. {
  207035. LOGFONTW lf;
  207036. zerostruct (lf);
  207037. lf.lfWeight = FW_DONTCARE;
  207038. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  207039. lf.lfQuality = DEFAULT_QUALITY;
  207040. lf.lfCharSet = DEFAULT_CHARSET;
  207041. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  207042. lf.lfPitchAndFamily = FF_DONTCARE;
  207043. lf.lfFaceName[0] = 0;
  207044. EnumFontFamiliesEx (dc, &lf,
  207045. (FONTENUMPROCW) &wfontEnum1,
  207046. (LPARAM) &results, 0);
  207047. }
  207048. DeleteDC (dc);
  207049. results.sort (true);
  207050. return results;
  207051. }
  207052. extern bool juce_IsRunningInWine();
  207053. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  207054. {
  207055. if (juce_IsRunningInWine())
  207056. {
  207057. // If we're running in Wine, then use fonts that might be available on Linux..
  207058. defaultSans = "Bitstream Vera Sans";
  207059. defaultSerif = "Bitstream Vera Serif";
  207060. defaultFixed = "Bitstream Vera Sans Mono";
  207061. }
  207062. else
  207063. {
  207064. defaultSans = "Verdana";
  207065. defaultSerif = "Times";
  207066. defaultFixed = "Lucida Console";
  207067. }
  207068. }
  207069. class FontDCHolder : private DeletedAtShutdown
  207070. {
  207071. public:
  207072. FontDCHolder()
  207073. : dc (0), numKPs (0), size (0),
  207074. bold (false), italic (false)
  207075. {
  207076. }
  207077. ~FontDCHolder()
  207078. {
  207079. if (dc != 0)
  207080. {
  207081. DeleteDC (dc);
  207082. DeleteObject (fontH);
  207083. }
  207084. clearSingletonInstance();
  207085. }
  207086. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  207087. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  207088. {
  207089. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  207090. {
  207091. fontName = fontName_;
  207092. bold = bold_;
  207093. italic = italic_;
  207094. size = size_;
  207095. if (dc != 0)
  207096. {
  207097. DeleteDC (dc);
  207098. DeleteObject (fontH);
  207099. kps.free();
  207100. }
  207101. fontH = 0;
  207102. dc = CreateCompatibleDC (0);
  207103. SetMapperFlags (dc, 0);
  207104. SetMapMode (dc, MM_TEXT);
  207105. LOGFONTW lfw;
  207106. zerostruct (lfw);
  207107. lfw.lfCharSet = DEFAULT_CHARSET;
  207108. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  207109. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  207110. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  207111. lfw.lfQuality = PROOF_QUALITY;
  207112. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  207113. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  207114. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  207115. lfw.lfHeight = size > 0 ? size : -256;
  207116. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  207117. if (standardSizedFont != 0)
  207118. {
  207119. if (SelectObject (dc, standardSizedFont) != 0)
  207120. {
  207121. fontH = standardSizedFont;
  207122. if (size == 0)
  207123. {
  207124. OUTLINETEXTMETRIC otm;
  207125. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  207126. {
  207127. lfw.lfHeight = -(int) otm.otmEMSquare;
  207128. fontH = CreateFontIndirect (&lfw);
  207129. SelectObject (dc, fontH);
  207130. DeleteObject (standardSizedFont);
  207131. }
  207132. }
  207133. }
  207134. else
  207135. {
  207136. jassertfalse;
  207137. }
  207138. }
  207139. else
  207140. {
  207141. jassertfalse;
  207142. }
  207143. }
  207144. return dc;
  207145. }
  207146. KERNINGPAIR* getKerningPairs (int& numKPs_)
  207147. {
  207148. if (kps == 0)
  207149. {
  207150. numKPs = GetKerningPairs (dc, 0, 0);
  207151. kps.calloc (numKPs);
  207152. GetKerningPairs (dc, numKPs, kps);
  207153. }
  207154. numKPs_ = numKPs;
  207155. return kps;
  207156. }
  207157. private:
  207158. HFONT fontH;
  207159. HDC dc;
  207160. String fontName;
  207161. HeapBlock <KERNINGPAIR> kps;
  207162. int numKPs, size;
  207163. bool bold, italic;
  207164. FontDCHolder (const FontDCHolder&);
  207165. FontDCHolder& operator= (const FontDCHolder&);
  207166. };
  207167. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  207168. class WindowsTypeface : public CustomTypeface
  207169. {
  207170. public:
  207171. WindowsTypeface (const Font& font)
  207172. {
  207173. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  207174. font.isBold(), font.isItalic(), 0);
  207175. TEXTMETRIC tm;
  207176. tm.tmAscent = tm.tmHeight = 1;
  207177. tm.tmDefaultChar = 0;
  207178. GetTextMetrics (dc, &tm);
  207179. setCharacteristics (font.getTypefaceName(),
  207180. tm.tmAscent / (float) tm.tmHeight,
  207181. font.isBold(), font.isItalic(),
  207182. tm.tmDefaultChar);
  207183. }
  207184. bool loadGlyphIfPossible (juce_wchar character)
  207185. {
  207186. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  207187. GLYPHMETRICS gm;
  207188. {
  207189. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  207190. WORD index = 0;
  207191. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  207192. && index == 0xffff)
  207193. {
  207194. return false;
  207195. }
  207196. }
  207197. Path glyphPath;
  207198. TEXTMETRIC tm;
  207199. if (! GetTextMetrics (dc, &tm))
  207200. {
  207201. addGlyph (character, glyphPath, 0);
  207202. return true;
  207203. }
  207204. const float height = (float) tm.tmHeight;
  207205. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  207206. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  207207. &gm, 0, 0, &identityMatrix);
  207208. if (bufSize > 0)
  207209. {
  207210. HeapBlock<char> data (bufSize);
  207211. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  207212. bufSize, data, &identityMatrix);
  207213. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  207214. const float scaleX = 1.0f / height;
  207215. const float scaleY = -1.0f / height;
  207216. while ((char*) pheader < data + bufSize)
  207217. {
  207218. float x = scaleX * pheader->pfxStart.x.value;
  207219. float y = scaleY * pheader->pfxStart.y.value;
  207220. glyphPath.startNewSubPath (x, y);
  207221. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  207222. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  207223. while ((const char*) curve < curveEnd)
  207224. {
  207225. if (curve->wType == TT_PRIM_LINE)
  207226. {
  207227. for (int i = 0; i < curve->cpfx; ++i)
  207228. {
  207229. x = scaleX * curve->apfx[i].x.value;
  207230. y = scaleY * curve->apfx[i].y.value;
  207231. glyphPath.lineTo (x, y);
  207232. }
  207233. }
  207234. else if (curve->wType == TT_PRIM_QSPLINE)
  207235. {
  207236. for (int i = 0; i < curve->cpfx - 1; ++i)
  207237. {
  207238. const float x2 = scaleX * curve->apfx[i].x.value;
  207239. const float y2 = scaleY * curve->apfx[i].y.value;
  207240. float x3, y3;
  207241. if (i < curve->cpfx - 2)
  207242. {
  207243. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  207244. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  207245. }
  207246. else
  207247. {
  207248. x3 = scaleX * curve->apfx[i + 1].x.value;
  207249. y3 = scaleY * curve->apfx[i + 1].y.value;
  207250. }
  207251. glyphPath.quadraticTo (x2, y2, x3, y3);
  207252. x = x3;
  207253. y = y3;
  207254. }
  207255. }
  207256. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  207257. }
  207258. pheader = (const TTPOLYGONHEADER*) curve;
  207259. glyphPath.closeSubPath();
  207260. }
  207261. }
  207262. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  207263. int numKPs;
  207264. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  207265. for (int i = 0; i < numKPs; ++i)
  207266. {
  207267. if (kps[i].wFirst == character)
  207268. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  207269. kps[i].iKernAmount / height);
  207270. }
  207271. return true;
  207272. }
  207273. juce_UseDebuggingNewOperator
  207274. };
  207275. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  207276. {
  207277. return new WindowsTypeface (font);
  207278. }
  207279. #endif
  207280. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  207281. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  207282. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207283. // compiled on its own).
  207284. #if JUCE_INCLUDED_FILE
  207285. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  207286. namespace FileChooserHelpers
  207287. {
  207288. static const void* defaultDirPath = 0;
  207289. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  207290. static Component* currentExtraFileWin = 0;
  207291. static bool areThereAnyAlwaysOnTopWindows()
  207292. {
  207293. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  207294. {
  207295. Component* c = Desktop::getInstance().getComponent (i);
  207296. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  207297. return true;
  207298. }
  207299. return false;
  207300. }
  207301. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  207302. {
  207303. if (msg == BFFM_INITIALIZED)
  207304. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  207305. else if (msg == BFFM_VALIDATEFAILEDW)
  207306. returnedString = (LPCWSTR) lParam;
  207307. else if (msg == BFFM_VALIDATEFAILEDA)
  207308. returnedString = (const char*) lParam;
  207309. return 0;
  207310. }
  207311. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  207312. {
  207313. if (currentExtraFileWin != 0)
  207314. {
  207315. if (uiMsg == WM_INITDIALOG)
  207316. {
  207317. HWND dialogH = GetParent (hdlg);
  207318. jassert (dialogH != 0);
  207319. if (dialogH == 0)
  207320. dialogH = hdlg;
  207321. RECT r, cr;
  207322. GetWindowRect (dialogH, &r);
  207323. GetClientRect (dialogH, &cr);
  207324. SetWindowPos (dialogH, 0,
  207325. r.left, r.top,
  207326. currentExtraFileWin->getWidth() + jmax (150, (int) (r.right - r.left)),
  207327. jmax (150, (int) (r.bottom - r.top)),
  207328. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  207329. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  207330. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  207331. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  207332. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  207333. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  207334. }
  207335. else if (uiMsg == WM_NOTIFY)
  207336. {
  207337. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  207338. if (ofn->hdr.code == CDN_SELCHANGE)
  207339. {
  207340. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  207341. if (comp != 0)
  207342. {
  207343. TCHAR path [MAX_PATH * 2];
  207344. path[0] = 0;
  207345. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  207346. const String fn ((const WCHAR*) path);
  207347. comp->selectedFileChanged (File (fn));
  207348. }
  207349. }
  207350. }
  207351. }
  207352. return 0;
  207353. }
  207354. class FPComponentHolder : public Component
  207355. {
  207356. public:
  207357. FPComponentHolder()
  207358. {
  207359. setVisible (true);
  207360. setOpaque (true);
  207361. }
  207362. ~FPComponentHolder()
  207363. {
  207364. }
  207365. void paint (Graphics& g)
  207366. {
  207367. g.fillAll (Colours::lightgrey);
  207368. }
  207369. private:
  207370. FPComponentHolder (const FPComponentHolder&);
  207371. FPComponentHolder& operator= (const FPComponentHolder&);
  207372. };
  207373. }
  207374. void FileChooser::showPlatformDialog (Array<File>& results,
  207375. const String& title,
  207376. const File& currentFileOrDirectory,
  207377. const String& filter,
  207378. bool selectsDirectory,
  207379. bool /*selectsFiles*/,
  207380. bool isSaveDialogue,
  207381. bool warnAboutOverwritingExistingFiles,
  207382. bool selectMultipleFiles,
  207383. FilePreviewComponent* extraInfoComponent)
  207384. {
  207385. using namespace FileChooserHelpers;
  207386. const int numCharsAvailable = 32768;
  207387. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  207388. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  207389. int fnameIdx = 0;
  207390. JUCE_TRY
  207391. {
  207392. // use a modal window as the parent for this dialog box
  207393. // to block input from other app windows
  207394. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  207395. Component w (String::empty);
  207396. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  207397. mainMon.getY() + mainMon.getHeight() / 4,
  207398. 0, 0);
  207399. w.setOpaque (true);
  207400. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  207401. w.addToDesktop (0);
  207402. if (extraInfoComponent == 0)
  207403. w.enterModalState();
  207404. String initialDir;
  207405. if (currentFileOrDirectory.isDirectory())
  207406. {
  207407. initialDir = currentFileOrDirectory.getFullPathName();
  207408. }
  207409. else
  207410. {
  207411. currentFileOrDirectory.getFileName().copyToUnicode (fname, numCharsAvailable);
  207412. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  207413. }
  207414. if (currentExtraFileWin->isValidComponent())
  207415. {
  207416. jassertfalse;
  207417. return;
  207418. }
  207419. if (selectsDirectory)
  207420. {
  207421. LPITEMIDLIST list = 0;
  207422. filenameSpace.fillWith (0);
  207423. {
  207424. BROWSEINFO bi;
  207425. zerostruct (bi);
  207426. bi.hwndOwner = (HWND) w.getWindowHandle();
  207427. bi.pszDisplayName = fname;
  207428. bi.lpszTitle = title;
  207429. bi.lpfn = browseCallbackProc;
  207430. #ifdef BIF_USENEWUI
  207431. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  207432. #else
  207433. bi.ulFlags = 0x50;
  207434. #endif
  207435. defaultDirPath = (const WCHAR*) initialDir;
  207436. list = SHBrowseForFolder (&bi);
  207437. if (! SHGetPathFromIDListW (list, fname))
  207438. {
  207439. fname[0] = 0;
  207440. returnedString = String::empty;
  207441. }
  207442. }
  207443. LPMALLOC al;
  207444. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  207445. al->Free (list);
  207446. defaultDirPath = 0;
  207447. if (returnedString.isNotEmpty())
  207448. {
  207449. const String stringFName (fname);
  207450. results.add (File (stringFName).getSiblingFile (returnedString));
  207451. returnedString = String::empty;
  207452. return;
  207453. }
  207454. }
  207455. else
  207456. {
  207457. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  207458. if (warnAboutOverwritingExistingFiles)
  207459. flags |= OFN_OVERWRITEPROMPT;
  207460. if (selectMultipleFiles)
  207461. flags |= OFN_ALLOWMULTISELECT;
  207462. if (extraInfoComponent != 0)
  207463. {
  207464. flags |= OFN_ENABLEHOOK;
  207465. currentExtraFileWin = new FPComponentHolder();
  207466. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  207467. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  207468. extraInfoComponent->getHeight());
  207469. currentExtraFileWin->addToDesktop (0);
  207470. currentExtraFileWin->enterModalState();
  207471. }
  207472. {
  207473. WCHAR filters [1024];
  207474. zeromem (filters, sizeof (filters));
  207475. filter.copyToUnicode (filters, 1024);
  207476. filter.copyToUnicode (filters + filter.length() + 1,
  207477. 1022 - filter.length());
  207478. OPENFILENAMEW of;
  207479. zerostruct (of);
  207480. #ifdef OPENFILENAME_SIZE_VERSION_400W
  207481. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  207482. #else
  207483. of.lStructSize = sizeof (of);
  207484. #endif
  207485. of.hwndOwner = (HWND) w.getWindowHandle();
  207486. of.lpstrFilter = filters;
  207487. of.nFilterIndex = 1;
  207488. of.lpstrFile = fname;
  207489. of.nMaxFile = numCharsAvailable;
  207490. of.lpstrInitialDir = initialDir;
  207491. of.lpstrTitle = title;
  207492. of.Flags = flags;
  207493. if (extraInfoComponent != 0)
  207494. of.lpfnHook = &openCallback;
  207495. if (isSaveDialogue)
  207496. {
  207497. if (! GetSaveFileName (&of))
  207498. fname[0] = 0;
  207499. else
  207500. fnameIdx = of.nFileOffset;
  207501. }
  207502. else
  207503. {
  207504. if (! GetOpenFileName (&of))
  207505. fname[0] = 0;
  207506. else
  207507. fnameIdx = of.nFileOffset;
  207508. }
  207509. }
  207510. }
  207511. }
  207512. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  207513. catch (...)
  207514. {
  207515. fname[0] = 0;
  207516. }
  207517. #endif
  207518. deleteAndZero (currentExtraFileWin);
  207519. const WCHAR* const files = fname;
  207520. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  207521. {
  207522. const WCHAR* filename = files + fnameIdx;
  207523. while (*filename != 0)
  207524. {
  207525. const String filepath (String (files) + "\\" + String (filename));
  207526. results.add (File (filepath));
  207527. filename += CharacterFunctions::length (filename) + 1;
  207528. }
  207529. }
  207530. else if (files[0] != 0)
  207531. {
  207532. results.add (File (files));
  207533. }
  207534. }
  207535. #endif
  207536. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  207537. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  207538. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207539. // compiled on its own).
  207540. #if JUCE_INCLUDED_FILE
  207541. void SystemClipboard::copyTextToClipboard (const String& text)
  207542. {
  207543. if (OpenClipboard (0) != 0)
  207544. {
  207545. if (EmptyClipboard() != 0)
  207546. {
  207547. const int len = text.length();
  207548. if (len > 0)
  207549. {
  207550. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  207551. (len + 1) * sizeof (wchar_t));
  207552. if (bufH != 0)
  207553. {
  207554. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  207555. text.copyToUnicode (data, len);
  207556. GlobalUnlock (bufH);
  207557. SetClipboardData (CF_UNICODETEXT, bufH);
  207558. }
  207559. }
  207560. }
  207561. CloseClipboard();
  207562. }
  207563. }
  207564. const String SystemClipboard::getTextFromClipboard()
  207565. {
  207566. String result;
  207567. if (OpenClipboard (0) != 0)
  207568. {
  207569. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  207570. if (bufH != 0)
  207571. {
  207572. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  207573. if (data != 0)
  207574. {
  207575. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  207576. GlobalUnlock (bufH);
  207577. }
  207578. }
  207579. CloseClipboard();
  207580. }
  207581. return result;
  207582. }
  207583. #endif
  207584. /*** End of inlined file: juce_win32_Misc.cpp ***/
  207585. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  207586. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207587. // compiled on its own).
  207588. #if JUCE_INCLUDED_FILE
  207589. namespace ActiveXHelpers
  207590. {
  207591. class JuceIStorage : public ComBaseClassHelper <IStorage>
  207592. {
  207593. public:
  207594. JuceIStorage() {}
  207595. ~JuceIStorage() {}
  207596. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  207597. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  207598. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  207599. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  207600. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  207601. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  207602. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  207603. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  207604. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  207605. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  207606. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  207607. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  207608. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  207609. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  207610. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  207611. juce_UseDebuggingNewOperator
  207612. };
  207613. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  207614. {
  207615. HWND window;
  207616. public:
  207617. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  207618. ~JuceOleInPlaceFrame() {}
  207619. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  207620. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  207621. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  207622. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  207623. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  207624. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  207625. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  207626. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  207627. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  207628. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  207629. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  207630. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  207631. juce_UseDebuggingNewOperator
  207632. };
  207633. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  207634. {
  207635. HWND window;
  207636. JuceOleInPlaceFrame* frame;
  207637. public:
  207638. JuceIOleInPlaceSite (HWND window_)
  207639. : window (window_),
  207640. frame (new JuceOleInPlaceFrame (window))
  207641. {}
  207642. ~JuceIOleInPlaceSite()
  207643. {
  207644. frame->Release();
  207645. }
  207646. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  207647. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  207648. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  207649. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  207650. HRESULT __stdcall OnUIActivate() { return S_OK; }
  207651. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  207652. {
  207653. *lplpFrame = frame;
  207654. *lplpDoc = 0;
  207655. lpFrameInfo->fMDIApp = FALSE;
  207656. lpFrameInfo->hwndFrame = window;
  207657. lpFrameInfo->haccel = 0;
  207658. lpFrameInfo->cAccelEntries = 0;
  207659. return S_OK;
  207660. }
  207661. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  207662. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  207663. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  207664. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  207665. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  207666. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  207667. juce_UseDebuggingNewOperator
  207668. };
  207669. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  207670. {
  207671. JuceIOleInPlaceSite* inplaceSite;
  207672. public:
  207673. JuceIOleClientSite (HWND window)
  207674. : inplaceSite (new JuceIOleInPlaceSite (window))
  207675. {}
  207676. ~JuceIOleClientSite()
  207677. {
  207678. inplaceSite->Release();
  207679. }
  207680. HRESULT __stdcall QueryInterface (REFIID type, void __RPC_FAR* __RPC_FAR* result)
  207681. {
  207682. if (type == IID_IOleInPlaceSite)
  207683. {
  207684. inplaceSite->AddRef();
  207685. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  207686. return S_OK;
  207687. }
  207688. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  207689. }
  207690. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  207691. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  207692. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  207693. HRESULT __stdcall ShowObject() { return S_OK; }
  207694. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  207695. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  207696. juce_UseDebuggingNewOperator
  207697. };
  207698. static Array<ActiveXControlComponent*> activeXComps;
  207699. static HWND getHWND (const ActiveXControlComponent* const component)
  207700. {
  207701. HWND hwnd = 0;
  207702. const IID iid = IID_IOleWindow;
  207703. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  207704. if (window != 0)
  207705. {
  207706. window->GetWindow (&hwnd);
  207707. window->Release();
  207708. }
  207709. return hwnd;
  207710. }
  207711. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  207712. {
  207713. RECT activeXRect, peerRect;
  207714. GetWindowRect (hwnd, &activeXRect);
  207715. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  207716. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  207717. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  207718. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  207719. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  207720. switch (message)
  207721. {
  207722. case WM_MOUSEMOVE:
  207723. case WM_LBUTTONDOWN:
  207724. case WM_MBUTTONDOWN:
  207725. case WM_RBUTTONDOWN:
  207726. case WM_LBUTTONUP:
  207727. case WM_MBUTTONUP:
  207728. case WM_RBUTTONUP:
  207729. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  207730. break;
  207731. default:
  207732. break;
  207733. }
  207734. }
  207735. }
  207736. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  207737. {
  207738. ActiveXControlComponent* const owner;
  207739. bool wasShowing;
  207740. public:
  207741. HWND controlHWND;
  207742. IStorage* storage;
  207743. IOleClientSite* clientSite;
  207744. IOleObject* control;
  207745. Pimpl (HWND hwnd, ActiveXControlComponent* const owner_)
  207746. : ComponentMovementWatcher (owner_),
  207747. owner (owner_),
  207748. wasShowing (owner_ != 0 && owner_->isShowing()),
  207749. controlHWND (0),
  207750. storage (new ActiveXHelpers::JuceIStorage()),
  207751. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  207752. control (0)
  207753. {
  207754. }
  207755. ~Pimpl()
  207756. {
  207757. if (control != 0)
  207758. {
  207759. control->Close (OLECLOSE_NOSAVE);
  207760. control->Release();
  207761. }
  207762. clientSite->Release();
  207763. storage->Release();
  207764. }
  207765. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  207766. {
  207767. Component* const topComp = owner->getTopLevelComponent();
  207768. if (topComp->getPeer() != 0)
  207769. {
  207770. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  207771. owner->setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner->getWidth(), owner->getHeight()));
  207772. }
  207773. }
  207774. void componentPeerChanged()
  207775. {
  207776. const bool isShowingNow = owner->isShowing();
  207777. if (wasShowing != isShowingNow)
  207778. {
  207779. wasShowing = isShowingNow;
  207780. owner->setControlVisible (isShowingNow);
  207781. }
  207782. componentMovedOrResized (true, true);
  207783. }
  207784. void componentVisibilityChanged (Component&)
  207785. {
  207786. componentPeerChanged();
  207787. }
  207788. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  207789. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  207790. {
  207791. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  207792. {
  207793. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  207794. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  207795. {
  207796. switch (message)
  207797. {
  207798. case WM_MOUSEMOVE:
  207799. case WM_LBUTTONDOWN:
  207800. case WM_MBUTTONDOWN:
  207801. case WM_RBUTTONDOWN:
  207802. case WM_LBUTTONUP:
  207803. case WM_MBUTTONUP:
  207804. case WM_RBUTTONUP:
  207805. case WM_LBUTTONDBLCLK:
  207806. case WM_MBUTTONDBLCLK:
  207807. case WM_RBUTTONDBLCLK:
  207808. if (ax->isShowing())
  207809. {
  207810. ComponentPeer* const peer = ax->getPeer();
  207811. if (peer != 0)
  207812. {
  207813. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  207814. if (! ax->areMouseEventsAllowed())
  207815. return 0;
  207816. }
  207817. }
  207818. break;
  207819. default:
  207820. break;
  207821. }
  207822. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  207823. }
  207824. }
  207825. return DefWindowProc (hwnd, message, wParam, lParam);
  207826. }
  207827. };
  207828. ActiveXControlComponent::ActiveXControlComponent()
  207829. : originalWndProc (0),
  207830. mouseEventsAllowed (true)
  207831. {
  207832. ActiveXHelpers::activeXComps.add (this);
  207833. }
  207834. ActiveXControlComponent::~ActiveXControlComponent()
  207835. {
  207836. deleteControl();
  207837. ActiveXHelpers::activeXComps.removeValue (this);
  207838. }
  207839. void ActiveXControlComponent::paint (Graphics& g)
  207840. {
  207841. if (control == 0)
  207842. g.fillAll (Colours::lightgrey);
  207843. }
  207844. bool ActiveXControlComponent::createControl (const void* controlIID)
  207845. {
  207846. deleteControl();
  207847. ComponentPeer* const peer = getPeer();
  207848. // the component must have already been added to a real window when you call this!
  207849. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  207850. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  207851. {
  207852. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  207853. HWND hwnd = (HWND) peer->getNativeHandle();
  207854. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, this));
  207855. HRESULT hr;
  207856. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  207857. newControl->clientSite, newControl->storage,
  207858. (void**) &(newControl->control))) == S_OK)
  207859. {
  207860. newControl->control->SetHostNames (L"Juce", 0);
  207861. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  207862. {
  207863. RECT rect;
  207864. rect.left = pos.getX();
  207865. rect.top = pos.getY();
  207866. rect.right = pos.getX() + getWidth();
  207867. rect.bottom = pos.getY() + getHeight();
  207868. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  207869. {
  207870. control = newControl;
  207871. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  207872. control->controlHWND = ActiveXHelpers::getHWND (this);
  207873. if (control->controlHWND != 0)
  207874. {
  207875. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  207876. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  207877. }
  207878. return true;
  207879. }
  207880. }
  207881. }
  207882. }
  207883. return false;
  207884. }
  207885. void ActiveXControlComponent::deleteControl()
  207886. {
  207887. control = 0;
  207888. originalWndProc = 0;
  207889. }
  207890. void* ActiveXControlComponent::queryInterface (const void* iid) const
  207891. {
  207892. void* result = 0;
  207893. if (control != 0 && control->control != 0
  207894. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  207895. return result;
  207896. return 0;
  207897. }
  207898. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  207899. {
  207900. if (control->controlHWND != 0)
  207901. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  207902. }
  207903. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  207904. {
  207905. if (control->controlHWND != 0)
  207906. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  207907. }
  207908. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  207909. {
  207910. mouseEventsAllowed = eventsCanReachControl;
  207911. }
  207912. #endif
  207913. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  207914. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  207915. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207916. // compiled on its own).
  207917. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  207918. using namespace QTOLibrary;
  207919. using namespace QTOControlLib;
  207920. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  207921. static bool isQTAvailable = false;
  207922. class QuickTimeMovieComponent::Pimpl
  207923. {
  207924. public:
  207925. Pimpl() : dataHandle (0)
  207926. {
  207927. }
  207928. ~Pimpl()
  207929. {
  207930. clearHandle();
  207931. }
  207932. void clearHandle()
  207933. {
  207934. if (dataHandle != 0)
  207935. {
  207936. DisposeHandle (dataHandle);
  207937. dataHandle = 0;
  207938. }
  207939. }
  207940. IQTControlPtr qtControl;
  207941. IQTMoviePtr qtMovie;
  207942. Handle dataHandle;
  207943. };
  207944. QuickTimeMovieComponent::QuickTimeMovieComponent()
  207945. : movieLoaded (false),
  207946. controllerVisible (true)
  207947. {
  207948. pimpl = new Pimpl();
  207949. setMouseEventsAllowed (false);
  207950. }
  207951. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  207952. {
  207953. closeMovie();
  207954. pimpl->qtControl = 0;
  207955. deleteControl();
  207956. pimpl = 0;
  207957. }
  207958. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  207959. {
  207960. if (! isQTAvailable)
  207961. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  207962. return isQTAvailable;
  207963. }
  207964. void QuickTimeMovieComponent::createControlIfNeeded()
  207965. {
  207966. if (isShowing() && ! isControlCreated())
  207967. {
  207968. const IID qtIID = __uuidof (QTControl);
  207969. if (createControl (&qtIID))
  207970. {
  207971. const IID qtInterfaceIID = __uuidof (IQTControl);
  207972. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  207973. if (pimpl->qtControl != 0)
  207974. {
  207975. pimpl->qtControl->Release(); // it has one ref too many at this point
  207976. pimpl->qtControl->QuickTimeInitialize();
  207977. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  207978. if (movieFile != File::nonexistent)
  207979. loadMovie (movieFile, controllerVisible);
  207980. }
  207981. }
  207982. }
  207983. }
  207984. bool QuickTimeMovieComponent::isControlCreated() const
  207985. {
  207986. return isControlOpen();
  207987. }
  207988. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  207989. const bool isControllerVisible)
  207990. {
  207991. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  207992. movieFile = File::nonexistent;
  207993. movieLoaded = false;
  207994. pimpl->qtMovie = 0;
  207995. controllerVisible = isControllerVisible;
  207996. createControlIfNeeded();
  207997. if (isControlCreated())
  207998. {
  207999. if (pimpl->qtControl != 0)
  208000. {
  208001. pimpl->qtControl->Put_MovieHandle (0);
  208002. pimpl->clearHandle();
  208003. Movie movie;
  208004. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  208005. {
  208006. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  208007. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  208008. if (pimpl->qtMovie != 0)
  208009. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  208010. : qtMovieControllerTypeNone);
  208011. }
  208012. if (movie == 0)
  208013. pimpl->clearHandle();
  208014. }
  208015. movieLoaded = (pimpl->qtMovie != 0);
  208016. }
  208017. else
  208018. {
  208019. // You're trying to open a movie when the control hasn't yet been created, probably because
  208020. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  208021. jassertfalse;
  208022. }
  208023. return movieLoaded;
  208024. }
  208025. void QuickTimeMovieComponent::closeMovie()
  208026. {
  208027. stop();
  208028. movieFile = File::nonexistent;
  208029. movieLoaded = false;
  208030. pimpl->qtMovie = 0;
  208031. if (pimpl->qtControl != 0)
  208032. pimpl->qtControl->Put_MovieHandle (0);
  208033. pimpl->clearHandle();
  208034. }
  208035. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  208036. {
  208037. return movieFile;
  208038. }
  208039. bool QuickTimeMovieComponent::isMovieOpen() const
  208040. {
  208041. return movieLoaded;
  208042. }
  208043. double QuickTimeMovieComponent::getMovieDuration() const
  208044. {
  208045. if (pimpl->qtMovie != 0)
  208046. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  208047. return 0.0;
  208048. }
  208049. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  208050. {
  208051. if (pimpl->qtMovie != 0)
  208052. {
  208053. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  208054. width = r.right - r.left;
  208055. height = r.bottom - r.top;
  208056. }
  208057. else
  208058. {
  208059. width = height = 0;
  208060. }
  208061. }
  208062. void QuickTimeMovieComponent::play()
  208063. {
  208064. if (pimpl->qtMovie != 0)
  208065. pimpl->qtMovie->Play();
  208066. }
  208067. void QuickTimeMovieComponent::stop()
  208068. {
  208069. if (pimpl->qtMovie != 0)
  208070. pimpl->qtMovie->Stop();
  208071. }
  208072. bool QuickTimeMovieComponent::isPlaying() const
  208073. {
  208074. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  208075. }
  208076. void QuickTimeMovieComponent::setPosition (const double seconds)
  208077. {
  208078. if (pimpl->qtMovie != 0)
  208079. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  208080. }
  208081. double QuickTimeMovieComponent::getPosition() const
  208082. {
  208083. if (pimpl->qtMovie != 0)
  208084. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  208085. return 0.0;
  208086. }
  208087. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  208088. {
  208089. if (pimpl->qtMovie != 0)
  208090. pimpl->qtMovie->PutRate (newSpeed);
  208091. }
  208092. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  208093. {
  208094. if (pimpl->qtMovie != 0)
  208095. {
  208096. pimpl->qtMovie->PutAudioVolume (newVolume);
  208097. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  208098. }
  208099. }
  208100. float QuickTimeMovieComponent::getMovieVolume() const
  208101. {
  208102. if (pimpl->qtMovie != 0)
  208103. return pimpl->qtMovie->GetAudioVolume();
  208104. return 0.0f;
  208105. }
  208106. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  208107. {
  208108. if (pimpl->qtMovie != 0)
  208109. pimpl->qtMovie->PutLoop (shouldLoop);
  208110. }
  208111. bool QuickTimeMovieComponent::isLooping() const
  208112. {
  208113. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  208114. }
  208115. bool QuickTimeMovieComponent::isControllerVisible() const
  208116. {
  208117. return controllerVisible;
  208118. }
  208119. void QuickTimeMovieComponent::parentHierarchyChanged()
  208120. {
  208121. createControlIfNeeded();
  208122. QTCompBaseClass::parentHierarchyChanged();
  208123. }
  208124. void QuickTimeMovieComponent::visibilityChanged()
  208125. {
  208126. createControlIfNeeded();
  208127. QTCompBaseClass::visibilityChanged();
  208128. }
  208129. void QuickTimeMovieComponent::paint (Graphics& g)
  208130. {
  208131. if (! isControlCreated())
  208132. g.fillAll (Colours::black);
  208133. }
  208134. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  208135. {
  208136. Handle dataRef = 0;
  208137. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  208138. if (err == noErr)
  208139. {
  208140. Str255 suffix;
  208141. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  208142. StringPtr name = suffix;
  208143. err = PtrAndHand (name, dataRef, name[0] + 1);
  208144. if (err == noErr)
  208145. {
  208146. long atoms[3];
  208147. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  208148. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  208149. atoms[2] = EndianU32_NtoB (MovieFileType);
  208150. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  208151. if (err == noErr)
  208152. return dataRef;
  208153. }
  208154. DisposeHandle (dataRef);
  208155. }
  208156. return 0;
  208157. }
  208158. static CFStringRef juceStringToCFString (const String& s)
  208159. {
  208160. const int len = s.length();
  208161. const juce_wchar* const t = s;
  208162. HeapBlock <UniChar> temp (len + 2);
  208163. for (int i = 0; i <= len; ++i)
  208164. temp[i] = t[i];
  208165. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  208166. }
  208167. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  208168. {
  208169. Boolean trueBool = true;
  208170. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  208171. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  208172. props[prop].propValueSize = sizeof (trueBool);
  208173. props[prop].propValueAddress = &trueBool;
  208174. ++prop;
  208175. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  208176. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  208177. props[prop].propValueSize = sizeof (trueBool);
  208178. props[prop].propValueAddress = &trueBool;
  208179. ++prop;
  208180. Boolean isActive = true;
  208181. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  208182. props[prop].propID = kQTNewMoviePropertyID_Active;
  208183. props[prop].propValueSize = sizeof (isActive);
  208184. props[prop].propValueAddress = &isActive;
  208185. ++prop;
  208186. MacSetPort (0);
  208187. jassert (prop <= 5);
  208188. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  208189. return err == noErr;
  208190. }
  208191. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  208192. {
  208193. if (input == 0)
  208194. return false;
  208195. dataHandle = 0;
  208196. bool ok = false;
  208197. QTNewMoviePropertyElement props[5];
  208198. zeromem (props, sizeof (props));
  208199. int prop = 0;
  208200. DataReferenceRecord dr;
  208201. props[prop].propClass = kQTPropertyClass_DataLocation;
  208202. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  208203. props[prop].propValueSize = sizeof (dr);
  208204. props[prop].propValueAddress = &dr;
  208205. ++prop;
  208206. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  208207. if (fin != 0)
  208208. {
  208209. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  208210. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  208211. &dr.dataRef, &dr.dataRefType);
  208212. ok = openMovie (props, prop, movie);
  208213. DisposeHandle (dr.dataRef);
  208214. CFRelease (filePath);
  208215. }
  208216. else
  208217. {
  208218. // sanity-check because this currently needs to load the whole stream into memory..
  208219. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  208220. dataHandle = NewHandle ((Size) input->getTotalLength());
  208221. HLock (dataHandle);
  208222. // read the entire stream into memory - this is a pain, but can't get it to work
  208223. // properly using a custom callback to supply the data.
  208224. input->read (*dataHandle, (int) input->getTotalLength());
  208225. HUnlock (dataHandle);
  208226. // different types to get QT to try. (We should really be a bit smarter here by
  208227. // working out in advance which one the stream contains, rather than just trying
  208228. // each one)
  208229. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  208230. "\04.avi", "\04.m4a" };
  208231. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  208232. {
  208233. /* // this fails for some bizarre reason - it can be bodged to work with
  208234. // movies, but can't seem to do it for other file types..
  208235. QTNewMovieUserProcRecord procInfo;
  208236. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  208237. procInfo.getMovieUserProcRefcon = this;
  208238. procInfo.defaultDataRef.dataRef = dataRef;
  208239. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  208240. props[prop].propClass = kQTPropertyClass_DataLocation;
  208241. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  208242. props[prop].propValueSize = sizeof (procInfo);
  208243. props[prop].propValueAddress = (void*) &procInfo;
  208244. ++prop; */
  208245. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  208246. dr.dataRefType = HandleDataHandlerSubType;
  208247. ok = openMovie (props, prop, movie);
  208248. DisposeHandle (dr.dataRef);
  208249. }
  208250. }
  208251. return ok;
  208252. }
  208253. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  208254. const bool isControllerVisible)
  208255. {
  208256. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  208257. movieFile = movieFile_;
  208258. return ok;
  208259. }
  208260. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  208261. const bool isControllerVisible)
  208262. {
  208263. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  208264. }
  208265. void QuickTimeMovieComponent::goToStart()
  208266. {
  208267. setPosition (0.0);
  208268. }
  208269. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  208270. const RectanglePlacement& placement)
  208271. {
  208272. int normalWidth, normalHeight;
  208273. getMovieNormalSize (normalWidth, normalHeight);
  208274. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  208275. {
  208276. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  208277. placement.applyTo (x, y, w, h,
  208278. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  208279. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  208280. if (w > 0 && h > 0)
  208281. {
  208282. setBounds (roundToInt (x), roundToInt (y),
  208283. roundToInt (w), roundToInt (h));
  208284. }
  208285. }
  208286. else
  208287. {
  208288. setBounds (spaceToFitWithin);
  208289. }
  208290. }
  208291. #endif
  208292. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  208293. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  208294. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208295. // compiled on its own).
  208296. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  208297. class WebBrowserComponentInternal : public ActiveXControlComponent
  208298. {
  208299. public:
  208300. WebBrowserComponentInternal()
  208301. : browser (0),
  208302. connectionPoint (0),
  208303. adviseCookie (0)
  208304. {
  208305. }
  208306. ~WebBrowserComponentInternal()
  208307. {
  208308. if (connectionPoint != 0)
  208309. connectionPoint->Unadvise (adviseCookie);
  208310. if (browser != 0)
  208311. browser->Release();
  208312. }
  208313. void createBrowser()
  208314. {
  208315. createControl (&CLSID_WebBrowser);
  208316. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  208317. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  208318. if (connectionPointContainer != 0)
  208319. {
  208320. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  208321. &connectionPoint);
  208322. if (connectionPoint != 0)
  208323. {
  208324. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  208325. jassert (owner != 0);
  208326. EventHandler* handler = new EventHandler (owner);
  208327. connectionPoint->Advise (handler, &adviseCookie);
  208328. handler->Release();
  208329. }
  208330. }
  208331. }
  208332. void goToURL (const String& url,
  208333. const StringArray* headers,
  208334. const MemoryBlock* postData)
  208335. {
  208336. if (browser != 0)
  208337. {
  208338. LPSAFEARRAY sa = 0;
  208339. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  208340. VariantInit (&flags);
  208341. VariantInit (&frame);
  208342. VariantInit (&postDataVar);
  208343. VariantInit (&headersVar);
  208344. if (headers != 0)
  208345. {
  208346. V_VT (&headersVar) = VT_BSTR;
  208347. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  208348. }
  208349. if (postData != 0 && postData->getSize() > 0)
  208350. {
  208351. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  208352. if (sa != 0)
  208353. {
  208354. void* data = 0;
  208355. SafeArrayAccessData (sa, &data);
  208356. jassert (data != 0);
  208357. if (data != 0)
  208358. {
  208359. postData->copyTo (data, 0, postData->getSize());
  208360. SafeArrayUnaccessData (sa);
  208361. VARIANT postDataVar2;
  208362. VariantInit (&postDataVar2);
  208363. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  208364. V_ARRAY (&postDataVar2) = sa;
  208365. postDataVar = postDataVar2;
  208366. }
  208367. }
  208368. }
  208369. browser->Navigate ((BSTR) (const OLECHAR*) url,
  208370. &flags, &frame,
  208371. &postDataVar, &headersVar);
  208372. if (sa != 0)
  208373. SafeArrayDestroy (sa);
  208374. VariantClear (&flags);
  208375. VariantClear (&frame);
  208376. VariantClear (&postDataVar);
  208377. VariantClear (&headersVar);
  208378. }
  208379. }
  208380. IWebBrowser2* browser;
  208381. juce_UseDebuggingNewOperator
  208382. private:
  208383. IConnectionPoint* connectionPoint;
  208384. DWORD adviseCookie;
  208385. class EventHandler : public ComBaseClassHelper <IDispatch>,
  208386. public ComponentMovementWatcher
  208387. {
  208388. public:
  208389. EventHandler (WebBrowserComponent* owner_)
  208390. : ComponentMovementWatcher (owner_),
  208391. owner (owner_)
  208392. {
  208393. }
  208394. ~EventHandler()
  208395. {
  208396. }
  208397. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  208398. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  208399. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  208400. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  208401. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  208402. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  208403. UINT __RPC_FAR* /*puArgErr*/)
  208404. {
  208405. switch (dispIdMember)
  208406. {
  208407. case DISPID_BEFORENAVIGATE2:
  208408. {
  208409. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  208410. String url;
  208411. if ((vurl->vt & VT_BYREF) != 0)
  208412. url = *vurl->pbstrVal;
  208413. else
  208414. url = vurl->bstrVal;
  208415. *pDispParams->rgvarg->pboolVal
  208416. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  208417. : VARIANT_TRUE;
  208418. return S_OK;
  208419. }
  208420. default:
  208421. break;
  208422. }
  208423. return E_NOTIMPL;
  208424. }
  208425. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  208426. void componentPeerChanged() {}
  208427. void componentVisibilityChanged (Component&)
  208428. {
  208429. owner->visibilityChanged();
  208430. }
  208431. juce_UseDebuggingNewOperator
  208432. private:
  208433. WebBrowserComponent* const owner;
  208434. EventHandler (const EventHandler&);
  208435. EventHandler& operator= (const EventHandler&);
  208436. };
  208437. };
  208438. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  208439. : browser (0),
  208440. blankPageShown (false),
  208441. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  208442. {
  208443. setOpaque (true);
  208444. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  208445. }
  208446. WebBrowserComponent::~WebBrowserComponent()
  208447. {
  208448. delete browser;
  208449. }
  208450. void WebBrowserComponent::goToURL (const String& url,
  208451. const StringArray* headers,
  208452. const MemoryBlock* postData)
  208453. {
  208454. lastURL = url;
  208455. lastHeaders.clear();
  208456. if (headers != 0)
  208457. lastHeaders = *headers;
  208458. lastPostData.setSize (0);
  208459. if (postData != 0)
  208460. lastPostData = *postData;
  208461. blankPageShown = false;
  208462. browser->goToURL (url, headers, postData);
  208463. }
  208464. void WebBrowserComponent::stop()
  208465. {
  208466. if (browser->browser != 0)
  208467. browser->browser->Stop();
  208468. }
  208469. void WebBrowserComponent::goBack()
  208470. {
  208471. lastURL = String::empty;
  208472. blankPageShown = false;
  208473. if (browser->browser != 0)
  208474. browser->browser->GoBack();
  208475. }
  208476. void WebBrowserComponent::goForward()
  208477. {
  208478. lastURL = String::empty;
  208479. if (browser->browser != 0)
  208480. browser->browser->GoForward();
  208481. }
  208482. void WebBrowserComponent::refresh()
  208483. {
  208484. if (browser->browser != 0)
  208485. browser->browser->Refresh();
  208486. }
  208487. void WebBrowserComponent::paint (Graphics& g)
  208488. {
  208489. if (browser->browser == 0)
  208490. g.fillAll (Colours::white);
  208491. }
  208492. void WebBrowserComponent::checkWindowAssociation()
  208493. {
  208494. if (isShowing())
  208495. {
  208496. if (browser->browser == 0 && getPeer() != 0)
  208497. {
  208498. browser->createBrowser();
  208499. reloadLastURL();
  208500. }
  208501. else
  208502. {
  208503. if (blankPageShown)
  208504. goBack();
  208505. }
  208506. }
  208507. else
  208508. {
  208509. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  208510. {
  208511. // when the component becomes invisible, some stuff like flash
  208512. // carries on playing audio, so we need to force it onto a blank
  208513. // page to avoid this..
  208514. blankPageShown = true;
  208515. browser->goToURL ("about:blank", 0, 0);
  208516. }
  208517. }
  208518. }
  208519. void WebBrowserComponent::reloadLastURL()
  208520. {
  208521. if (lastURL.isNotEmpty())
  208522. {
  208523. goToURL (lastURL, &lastHeaders, &lastPostData);
  208524. lastURL = String::empty;
  208525. }
  208526. }
  208527. void WebBrowserComponent::parentHierarchyChanged()
  208528. {
  208529. checkWindowAssociation();
  208530. }
  208531. void WebBrowserComponent::resized()
  208532. {
  208533. browser->setSize (getWidth(), getHeight());
  208534. }
  208535. void WebBrowserComponent::visibilityChanged()
  208536. {
  208537. checkWindowAssociation();
  208538. }
  208539. bool WebBrowserComponent::pageAboutToLoad (const String&)
  208540. {
  208541. return true;
  208542. }
  208543. #endif
  208544. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  208545. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  208546. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208547. // compiled on its own).
  208548. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  208549. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  208550. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  208551. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  208552. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  208553. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  208554. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  208555. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  208556. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  208557. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  208558. #define WGL_ACCELERATION_ARB 0x2003
  208559. #define WGL_SWAP_METHOD_ARB 0x2007
  208560. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  208561. #define WGL_PIXEL_TYPE_ARB 0x2013
  208562. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  208563. #define WGL_COLOR_BITS_ARB 0x2014
  208564. #define WGL_RED_BITS_ARB 0x2015
  208565. #define WGL_GREEN_BITS_ARB 0x2017
  208566. #define WGL_BLUE_BITS_ARB 0x2019
  208567. #define WGL_ALPHA_BITS_ARB 0x201B
  208568. #define WGL_DEPTH_BITS_ARB 0x2022
  208569. #define WGL_STENCIL_BITS_ARB 0x2023
  208570. #define WGL_FULL_ACCELERATION_ARB 0x2027
  208571. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  208572. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  208573. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  208574. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  208575. #define WGL_STEREO_ARB 0x2012
  208576. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  208577. #define WGL_SAMPLES_ARB 0x2042
  208578. #define WGL_TYPE_RGBA_ARB 0x202B
  208579. static void getWglExtensions (HDC dc, StringArray& result) throw()
  208580. {
  208581. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  208582. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  208583. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  208584. else
  208585. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  208586. }
  208587. class WindowedGLContext : public OpenGLContext
  208588. {
  208589. public:
  208590. WindowedGLContext (Component* const component_,
  208591. HGLRC contextToShareWith,
  208592. const OpenGLPixelFormat& pixelFormat)
  208593. : renderContext (0),
  208594. nativeWindow (0),
  208595. dc (0),
  208596. component (component_)
  208597. {
  208598. jassert (component != 0);
  208599. createNativeWindow();
  208600. // Use a default pixel format that should be supported everywhere
  208601. PIXELFORMATDESCRIPTOR pfd;
  208602. zerostruct (pfd);
  208603. pfd.nSize = sizeof (pfd);
  208604. pfd.nVersion = 1;
  208605. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  208606. pfd.iPixelType = PFD_TYPE_RGBA;
  208607. pfd.cColorBits = 24;
  208608. pfd.cDepthBits = 16;
  208609. const int format = ChoosePixelFormat (dc, &pfd);
  208610. if (format != 0)
  208611. SetPixelFormat (dc, format, &pfd);
  208612. renderContext = wglCreateContext (dc);
  208613. makeActive();
  208614. setPixelFormat (pixelFormat);
  208615. if (contextToShareWith != 0 && renderContext != 0)
  208616. wglShareLists (contextToShareWith, renderContext);
  208617. }
  208618. ~WindowedGLContext()
  208619. {
  208620. deleteContext();
  208621. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  208622. delete nativeWindow;
  208623. }
  208624. void deleteContext()
  208625. {
  208626. makeInactive();
  208627. if (renderContext != 0)
  208628. {
  208629. wglDeleteContext (renderContext);
  208630. renderContext = 0;
  208631. }
  208632. }
  208633. bool makeActive() const throw()
  208634. {
  208635. jassert (renderContext != 0);
  208636. return wglMakeCurrent (dc, renderContext) != 0;
  208637. }
  208638. bool makeInactive() const throw()
  208639. {
  208640. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  208641. }
  208642. bool isActive() const throw()
  208643. {
  208644. return wglGetCurrentContext() == renderContext;
  208645. }
  208646. const OpenGLPixelFormat getPixelFormat() const
  208647. {
  208648. OpenGLPixelFormat pf;
  208649. makeActive();
  208650. StringArray availableExtensions;
  208651. getWglExtensions (dc, availableExtensions);
  208652. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  208653. return pf;
  208654. }
  208655. void* getRawContext() const throw()
  208656. {
  208657. return renderContext;
  208658. }
  208659. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  208660. {
  208661. makeActive();
  208662. PIXELFORMATDESCRIPTOR pfd;
  208663. zerostruct (pfd);
  208664. pfd.nSize = sizeof (pfd);
  208665. pfd.nVersion = 1;
  208666. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  208667. pfd.iPixelType = PFD_TYPE_RGBA;
  208668. pfd.iLayerType = PFD_MAIN_PLANE;
  208669. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  208670. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  208671. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  208672. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  208673. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  208674. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  208675. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  208676. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  208677. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  208678. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  208679. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  208680. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  208681. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  208682. int format = 0;
  208683. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  208684. StringArray availableExtensions;
  208685. getWglExtensions (dc, availableExtensions);
  208686. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  208687. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  208688. {
  208689. int attributes[64];
  208690. int n = 0;
  208691. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  208692. attributes[n++] = GL_TRUE;
  208693. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  208694. attributes[n++] = GL_TRUE;
  208695. attributes[n++] = WGL_ACCELERATION_ARB;
  208696. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  208697. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  208698. attributes[n++] = GL_TRUE;
  208699. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  208700. attributes[n++] = WGL_TYPE_RGBA_ARB;
  208701. attributes[n++] = WGL_COLOR_BITS_ARB;
  208702. attributes[n++] = pfd.cColorBits;
  208703. attributes[n++] = WGL_RED_BITS_ARB;
  208704. attributes[n++] = pixelFormat.redBits;
  208705. attributes[n++] = WGL_GREEN_BITS_ARB;
  208706. attributes[n++] = pixelFormat.greenBits;
  208707. attributes[n++] = WGL_BLUE_BITS_ARB;
  208708. attributes[n++] = pixelFormat.blueBits;
  208709. attributes[n++] = WGL_ALPHA_BITS_ARB;
  208710. attributes[n++] = pixelFormat.alphaBits;
  208711. attributes[n++] = WGL_DEPTH_BITS_ARB;
  208712. attributes[n++] = pixelFormat.depthBufferBits;
  208713. if (pixelFormat.stencilBufferBits > 0)
  208714. {
  208715. attributes[n++] = WGL_STENCIL_BITS_ARB;
  208716. attributes[n++] = pixelFormat.stencilBufferBits;
  208717. }
  208718. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  208719. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  208720. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  208721. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  208722. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  208723. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  208724. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208725. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  208726. if (availableExtensions.contains ("WGL_ARB_multisample")
  208727. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  208728. {
  208729. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  208730. attributes[n++] = 1;
  208731. attributes[n++] = WGL_SAMPLES_ARB;
  208732. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  208733. }
  208734. attributes[n++] = 0;
  208735. UINT formatsCount;
  208736. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  208737. (void) ok;
  208738. jassert (ok);
  208739. }
  208740. else
  208741. {
  208742. format = ChoosePixelFormat (dc, &pfd);
  208743. }
  208744. if (format != 0)
  208745. {
  208746. makeInactive();
  208747. // win32 can't change the pixel format of a window, so need to delete the
  208748. // old one and create a new one..
  208749. jassert (nativeWindow != 0);
  208750. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  208751. delete nativeWindow;
  208752. createNativeWindow();
  208753. if (SetPixelFormat (dc, format, &pfd))
  208754. {
  208755. wglDeleteContext (renderContext);
  208756. renderContext = wglCreateContext (dc);
  208757. jassert (renderContext != 0);
  208758. return renderContext != 0;
  208759. }
  208760. }
  208761. return false;
  208762. }
  208763. void updateWindowPosition (int x, int y, int w, int h, int)
  208764. {
  208765. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  208766. x, y, w, h,
  208767. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  208768. }
  208769. void repaint()
  208770. {
  208771. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  208772. }
  208773. void swapBuffers()
  208774. {
  208775. SwapBuffers (dc);
  208776. }
  208777. bool setSwapInterval (int numFramesPerSwap)
  208778. {
  208779. makeActive();
  208780. StringArray availableExtensions;
  208781. getWglExtensions (dc, availableExtensions);
  208782. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  208783. return availableExtensions.contains ("WGL_EXT_swap_control")
  208784. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  208785. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  208786. }
  208787. int getSwapInterval() const
  208788. {
  208789. makeActive();
  208790. StringArray availableExtensions;
  208791. getWglExtensions (dc, availableExtensions);
  208792. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  208793. if (availableExtensions.contains ("WGL_EXT_swap_control")
  208794. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  208795. return wglGetSwapIntervalEXT();
  208796. return 0;
  208797. }
  208798. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  208799. {
  208800. jassert (isActive());
  208801. StringArray availableExtensions;
  208802. getWglExtensions (dc, availableExtensions);
  208803. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208804. int numTypes = 0;
  208805. if (availableExtensions.contains("WGL_ARB_pixel_format")
  208806. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208807. {
  208808. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  208809. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  208810. jassertfalse;
  208811. }
  208812. else
  208813. {
  208814. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  208815. }
  208816. OpenGLPixelFormat pf;
  208817. for (int i = 0; i < numTypes; ++i)
  208818. {
  208819. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  208820. {
  208821. bool alreadyListed = false;
  208822. for (int j = results.size(); --j >= 0;)
  208823. if (pf == *results.getUnchecked(j))
  208824. alreadyListed = true;
  208825. if (! alreadyListed)
  208826. results.add (new OpenGLPixelFormat (pf));
  208827. }
  208828. }
  208829. }
  208830. void* getNativeWindowHandle() const
  208831. {
  208832. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  208833. }
  208834. juce_UseDebuggingNewOperator
  208835. HGLRC renderContext;
  208836. private:
  208837. Win32ComponentPeer* nativeWindow;
  208838. Component* const component;
  208839. HDC dc;
  208840. void createNativeWindow()
  208841. {
  208842. nativeWindow = new Win32ComponentPeer (component, 0);
  208843. nativeWindow->dontRepaint = true;
  208844. nativeWindow->setVisible (true);
  208845. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  208846. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  208847. if (peer != 0)
  208848. {
  208849. SetParent (hwnd, (HWND) peer->getNativeHandle());
  208850. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  208851. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  208852. }
  208853. dc = GetDC (hwnd);
  208854. }
  208855. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  208856. OpenGLPixelFormat& result,
  208857. const StringArray& availableExtensions) const throw()
  208858. {
  208859. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208860. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  208861. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208862. {
  208863. int attributes[32];
  208864. int numAttributes = 0;
  208865. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  208866. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  208867. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  208868. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  208869. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  208870. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  208871. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  208872. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  208873. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  208874. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  208875. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  208876. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  208877. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  208878. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  208879. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208880. if (availableExtensions.contains ("WGL_ARB_multisample"))
  208881. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  208882. int values[32];
  208883. zeromem (values, sizeof (values));
  208884. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  208885. {
  208886. int n = 0;
  208887. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  208888. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  208889. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  208890. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  208891. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  208892. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  208893. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  208894. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  208895. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  208896. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  208897. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  208898. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  208899. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  208900. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  208901. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  208902. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  208903. return isValidFormat;
  208904. }
  208905. else
  208906. {
  208907. jassertfalse;
  208908. }
  208909. }
  208910. else
  208911. {
  208912. PIXELFORMATDESCRIPTOR pfd;
  208913. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  208914. {
  208915. result.redBits = pfd.cRedBits;
  208916. result.greenBits = pfd.cGreenBits;
  208917. result.blueBits = pfd.cBlueBits;
  208918. result.alphaBits = pfd.cAlphaBits;
  208919. result.depthBufferBits = pfd.cDepthBits;
  208920. result.stencilBufferBits = pfd.cStencilBits;
  208921. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  208922. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  208923. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  208924. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  208925. result.fullSceneAntiAliasingNumSamples = 0;
  208926. return true;
  208927. }
  208928. else
  208929. {
  208930. jassertfalse;
  208931. }
  208932. }
  208933. return false;
  208934. }
  208935. WindowedGLContext (const WindowedGLContext&);
  208936. WindowedGLContext& operator= (const WindowedGLContext&);
  208937. };
  208938. OpenGLContext* OpenGLComponent::createContext()
  208939. {
  208940. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  208941. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  208942. preferredPixelFormat));
  208943. return (c->renderContext != 0) ? c.release() : 0;
  208944. }
  208945. void* OpenGLComponent::getNativeWindowHandle() const
  208946. {
  208947. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  208948. }
  208949. void juce_glViewport (const int w, const int h)
  208950. {
  208951. glViewport (0, 0, w, h);
  208952. }
  208953. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  208954. OwnedArray <OpenGLPixelFormat>& results)
  208955. {
  208956. Component tempComp;
  208957. {
  208958. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  208959. wc.makeActive();
  208960. wc.findAlternativeOpenGLPixelFormats (results);
  208961. }
  208962. }
  208963. #endif
  208964. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  208965. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  208966. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208967. // compiled on its own).
  208968. #if JUCE_INCLUDED_FILE
  208969. #if JUCE_USE_CDREADER
  208970. namespace CDReaderHelpers
  208971. {
  208972. //***************************************************************************
  208973. // %%% TARGET STATUS VALUES %%%
  208974. //***************************************************************************
  208975. #define STATUS_GOOD 0x00 // Status Good
  208976. #define STATUS_CHKCOND 0x02 // Check Condition
  208977. #define STATUS_CONDMET 0x04 // Condition Met
  208978. #define STATUS_BUSY 0x08 // Busy
  208979. #define STATUS_INTERM 0x10 // Intermediate
  208980. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  208981. #define STATUS_RESCONF 0x18 // Reservation conflict
  208982. #define STATUS_COMTERM 0x22 // Command Terminated
  208983. #define STATUS_QFULL 0x28 // Queue full
  208984. //***************************************************************************
  208985. // %%% SCSI MISCELLANEOUS EQUATES %%%
  208986. //***************************************************************************
  208987. #define MAXLUN 7 // Maximum Logical Unit Id
  208988. #define MAXTARG 7 // Maximum Target Id
  208989. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  208990. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  208991. //***************************************************************************
  208992. // %%% Commands for all Device Types %%%
  208993. //***************************************************************************
  208994. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  208995. #define SCSI_COMPARE 0x39 // Compare (O)
  208996. #define SCSI_COPY 0x18 // Copy (O)
  208997. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  208998. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  208999. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  209000. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  209001. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  209002. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  209003. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  209004. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  209005. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  209006. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  209007. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  209008. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  209009. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  209010. //***************************************************************************
  209011. // %%% Commands Unique to Direct Access Devices %%%
  209012. //***************************************************************************
  209013. #define SCSI_COMPARE 0x39 // Compare (O)
  209014. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  209015. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  209016. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  209017. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  209018. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  209019. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  209020. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  209021. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  209022. #define SCSI_READ_LONG 0x3E // Read Long (O)
  209023. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  209024. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  209025. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  209026. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  209027. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  209028. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  209029. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  209030. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  209031. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  209032. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  209033. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  209034. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  209035. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  209036. #define SCSI_VERIFY 0x2F // Verify (O)
  209037. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  209038. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  209039. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  209040. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  209041. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  209042. //***************************************************************************
  209043. // %%% Commands Unique to Sequential Access Devices %%%
  209044. //***************************************************************************
  209045. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  209046. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  209047. #define SCSI_LOCATE 0x2B // Locate (O)
  209048. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  209049. #define SCSI_READ_POS 0x34 // Read Position (O)
  209050. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  209051. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  209052. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  209053. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  209054. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  209055. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  209056. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  209057. //***************************************************************************
  209058. // %%% Commands Unique to Printer Devices %%%
  209059. //***************************************************************************
  209060. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  209061. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  209062. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  209063. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  209064. //***************************************************************************
  209065. // %%% Commands Unique to Processor Devices %%%
  209066. //***************************************************************************
  209067. #define SCSI_RECEIVE 0x08 // Receive (O)
  209068. #define SCSI_SEND 0x0A // Send (O)
  209069. //***************************************************************************
  209070. // %%% Commands Unique to Write-Once Devices %%%
  209071. //***************************************************************************
  209072. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  209073. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  209074. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  209075. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  209076. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  209077. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  209078. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  209079. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  209080. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  209081. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  209082. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  209083. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  209084. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  209085. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  209086. //***************************************************************************
  209087. // %%% Commands Unique to CD-ROM Devices %%%
  209088. //***************************************************************************
  209089. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  209090. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  209091. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  209092. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  209093. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  209094. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  209095. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  209096. #define SCSI_READHEADER 0x44 // Read Header (O)
  209097. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  209098. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  209099. //***************************************************************************
  209100. // %%% Commands Unique to Scanner Devices %%%
  209101. //***************************************************************************
  209102. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  209103. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  209104. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  209105. #define SCSI_SCAN 0x1B // Scan (O)
  209106. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  209107. //***************************************************************************
  209108. // %%% Commands Unique to Optical Memory Devices %%%
  209109. //***************************************************************************
  209110. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  209111. //***************************************************************************
  209112. // %%% Commands Unique to Medium Changer Devices %%%
  209113. //***************************************************************************
  209114. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  209115. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  209116. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  209117. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  209118. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  209119. //***************************************************************************
  209120. // %%% Commands Unique to Communication Devices %%%
  209121. //***************************************************************************
  209122. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  209123. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  209124. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  209125. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  209126. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  209127. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  209128. //***************************************************************************
  209129. // %%% Request Sense Data Format %%%
  209130. //***************************************************************************
  209131. typedef struct {
  209132. BYTE ErrorCode; // Error Code (70H or 71H)
  209133. BYTE SegmentNum; // Number of current segment descriptor
  209134. BYTE SenseKey; // Sense Key(See bit definitions too)
  209135. BYTE InfoByte0; // Information MSB
  209136. BYTE InfoByte1; // Information MID
  209137. BYTE InfoByte2; // Information MID
  209138. BYTE InfoByte3; // Information LSB
  209139. BYTE AddSenLen; // Additional Sense Length
  209140. BYTE ComSpecInf0; // Command Specific Information MSB
  209141. BYTE ComSpecInf1; // Command Specific Information MID
  209142. BYTE ComSpecInf2; // Command Specific Information MID
  209143. BYTE ComSpecInf3; // Command Specific Information LSB
  209144. BYTE AddSenseCode; // Additional Sense Code
  209145. BYTE AddSenQual; // Additional Sense Code Qualifier
  209146. BYTE FieldRepUCode; // Field Replaceable Unit Code
  209147. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  209148. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  209149. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  209150. BYTE AddSenseBytes; // Additional Sense Bytes
  209151. } SENSE_DATA_FMT;
  209152. //***************************************************************************
  209153. // %%% REQUEST SENSE ERROR CODE %%%
  209154. //***************************************************************************
  209155. #define SERROR_CURRENT 0x70 // Current Errors
  209156. #define SERROR_DEFERED 0x71 // Deferred Errors
  209157. //***************************************************************************
  209158. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  209159. //***************************************************************************
  209160. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  209161. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  209162. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  209163. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  209164. //***************************************************************************
  209165. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  209166. //***************************************************************************
  209167. #define KEY_NOSENSE 0x00 // No Sense
  209168. #define KEY_RECERROR 0x01 // Recovered Error
  209169. #define KEY_NOTREADY 0x02 // Not Ready
  209170. #define KEY_MEDIUMERR 0x03 // Medium Error
  209171. #define KEY_HARDERROR 0x04 // Hardware Error
  209172. #define KEY_ILLGLREQ 0x05 // Illegal Request
  209173. #define KEY_UNITATT 0x06 // Unit Attention
  209174. #define KEY_DATAPROT 0x07 // Data Protect
  209175. #define KEY_BLANKCHK 0x08 // Blank Check
  209176. #define KEY_VENDSPEC 0x09 // Vendor Specific
  209177. #define KEY_COPYABORT 0x0A // Copy Abort
  209178. #define KEY_EQUAL 0x0C // Equal (Search)
  209179. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  209180. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  209181. #define KEY_RESERVED 0x0F // Reserved
  209182. //***************************************************************************
  209183. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  209184. //***************************************************************************
  209185. #define DTYPE_DASD 0x00 // Disk Device
  209186. #define DTYPE_SEQD 0x01 // Tape Device
  209187. #define DTYPE_PRNT 0x02 // Printer
  209188. #define DTYPE_PROC 0x03 // Processor
  209189. #define DTYPE_WORM 0x04 // Write-once read-multiple
  209190. #define DTYPE_CROM 0x05 // CD-ROM device
  209191. #define DTYPE_SCAN 0x06 // Scanner device
  209192. #define DTYPE_OPTI 0x07 // Optical memory device
  209193. #define DTYPE_JUKE 0x08 // Medium Changer device
  209194. #define DTYPE_COMM 0x09 // Communications device
  209195. #define DTYPE_RESL 0x0A // Reserved (low)
  209196. #define DTYPE_RESH 0x1E // Reserved (high)
  209197. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  209198. //***************************************************************************
  209199. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  209200. //***************************************************************************
  209201. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  209202. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  209203. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  209204. #define ANSI_RESLO 0x3 // Reserved (low)
  209205. #define ANSI_RESHI 0x7 // Reserved (high)
  209206. typedef struct
  209207. {
  209208. USHORT Length;
  209209. UCHAR ScsiStatus;
  209210. UCHAR PathId;
  209211. UCHAR TargetId;
  209212. UCHAR Lun;
  209213. UCHAR CdbLength;
  209214. UCHAR SenseInfoLength;
  209215. UCHAR DataIn;
  209216. ULONG DataTransferLength;
  209217. ULONG TimeOutValue;
  209218. ULONG DataBufferOffset;
  209219. ULONG SenseInfoOffset;
  209220. UCHAR Cdb[16];
  209221. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  209222. typedef struct
  209223. {
  209224. USHORT Length;
  209225. UCHAR ScsiStatus;
  209226. UCHAR PathId;
  209227. UCHAR TargetId;
  209228. UCHAR Lun;
  209229. UCHAR CdbLength;
  209230. UCHAR SenseInfoLength;
  209231. UCHAR DataIn;
  209232. ULONG DataTransferLength;
  209233. ULONG TimeOutValue;
  209234. PVOID DataBuffer;
  209235. ULONG SenseInfoOffset;
  209236. UCHAR Cdb[16];
  209237. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  209238. typedef struct
  209239. {
  209240. SCSI_PASS_THROUGH_DIRECT spt;
  209241. ULONG Filler;
  209242. UCHAR ucSenseBuf[32];
  209243. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  209244. typedef struct
  209245. {
  209246. ULONG Length;
  209247. UCHAR PortNumber;
  209248. UCHAR PathId;
  209249. UCHAR TargetId;
  209250. UCHAR Lun;
  209251. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  209252. #define METHOD_BUFFERED 0
  209253. #define METHOD_IN_DIRECT 1
  209254. #define METHOD_OUT_DIRECT 2
  209255. #define METHOD_NEITHER 3
  209256. #define FILE_ANY_ACCESS 0
  209257. #ifndef FILE_READ_ACCESS
  209258. #define FILE_READ_ACCESS (0x0001)
  209259. #endif
  209260. #ifndef FILE_WRITE_ACCESS
  209261. #define FILE_WRITE_ACCESS (0x0002)
  209262. #endif
  209263. #define IOCTL_SCSI_BASE 0x00000004
  209264. #define SCSI_IOCTL_DATA_OUT 0
  209265. #define SCSI_IOCTL_DATA_IN 1
  209266. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  209267. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  209268. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  209269. )
  209270. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  209271. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  209272. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  209273. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  209274. #define SENSE_LEN 14
  209275. #define SRB_DIR_SCSI 0x00
  209276. #define SRB_POSTING 0x01
  209277. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  209278. #define SRB_DIR_IN 0x08
  209279. #define SRB_DIR_OUT 0x10
  209280. #define SRB_EVENT_NOTIFY 0x40
  209281. #define RESIDUAL_COUNT_SUPPORTED 0x02
  209282. #define MAX_SRB_TIMEOUT 1080001u
  209283. #define DEFAULT_SRB_TIMEOUT 1080001u
  209284. #define SC_HA_INQUIRY 0x00
  209285. #define SC_GET_DEV_TYPE 0x01
  209286. #define SC_EXEC_SCSI_CMD 0x02
  209287. #define SC_ABORT_SRB 0x03
  209288. #define SC_RESET_DEV 0x04
  209289. #define SC_SET_HA_PARMS 0x05
  209290. #define SC_GET_DISK_INFO 0x06
  209291. #define SC_RESCAN_SCSI_BUS 0x07
  209292. #define SC_GETSET_TIMEOUTS 0x08
  209293. #define SS_PENDING 0x00
  209294. #define SS_COMP 0x01
  209295. #define SS_ABORTED 0x02
  209296. #define SS_ABORT_FAIL 0x03
  209297. #define SS_ERR 0x04
  209298. #define SS_INVALID_CMD 0x80
  209299. #define SS_INVALID_HA 0x81
  209300. #define SS_NO_DEVICE 0x82
  209301. #define SS_INVALID_SRB 0xE0
  209302. #define SS_OLD_MANAGER 0xE1
  209303. #define SS_BUFFER_ALIGN 0xE1
  209304. #define SS_ILLEGAL_MODE 0xE2
  209305. #define SS_NO_ASPI 0xE3
  209306. #define SS_FAILED_INIT 0xE4
  209307. #define SS_ASPI_IS_BUSY 0xE5
  209308. #define SS_BUFFER_TO_BIG 0xE6
  209309. #define SS_BUFFER_TOO_BIG 0xE6
  209310. #define SS_MISMATCHED_COMPONENTS 0xE7
  209311. #define SS_NO_ADAPTERS 0xE8
  209312. #define SS_INSUFFICIENT_RESOURCES 0xE9
  209313. #define SS_ASPI_IS_SHUTDOWN 0xEA
  209314. #define SS_BAD_INSTALL 0xEB
  209315. #define HASTAT_OK 0x00
  209316. #define HASTAT_SEL_TO 0x11
  209317. #define HASTAT_DO_DU 0x12
  209318. #define HASTAT_BUS_FREE 0x13
  209319. #define HASTAT_PHASE_ERR 0x14
  209320. #define HASTAT_TIMEOUT 0x09
  209321. #define HASTAT_COMMAND_TIMEOUT 0x0B
  209322. #define HASTAT_MESSAGE_REJECT 0x0D
  209323. #define HASTAT_BUS_RESET 0x0E
  209324. #define HASTAT_PARITY_ERROR 0x0F
  209325. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  209326. #define PACKED
  209327. #pragma pack(1)
  209328. typedef struct
  209329. {
  209330. BYTE SRB_Cmd;
  209331. BYTE SRB_Status;
  209332. BYTE SRB_HaID;
  209333. BYTE SRB_Flags;
  209334. DWORD SRB_Hdr_Rsvd;
  209335. BYTE HA_Count;
  209336. BYTE HA_SCSI_ID;
  209337. BYTE HA_ManagerId[16];
  209338. BYTE HA_Identifier[16];
  209339. BYTE HA_Unique[16];
  209340. WORD HA_Rsvd1;
  209341. BYTE pad[20];
  209342. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  209343. typedef struct
  209344. {
  209345. BYTE SRB_Cmd;
  209346. BYTE SRB_Status;
  209347. BYTE SRB_HaID;
  209348. BYTE SRB_Flags;
  209349. DWORD SRB_Hdr_Rsvd;
  209350. BYTE SRB_Target;
  209351. BYTE SRB_Lun;
  209352. BYTE SRB_DeviceType;
  209353. BYTE SRB_Rsvd1;
  209354. BYTE pad[68];
  209355. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  209356. typedef struct
  209357. {
  209358. BYTE SRB_Cmd;
  209359. BYTE SRB_Status;
  209360. BYTE SRB_HaID;
  209361. BYTE SRB_Flags;
  209362. DWORD SRB_Hdr_Rsvd;
  209363. BYTE SRB_Target;
  209364. BYTE SRB_Lun;
  209365. WORD SRB_Rsvd1;
  209366. DWORD SRB_BufLen;
  209367. BYTE FAR *SRB_BufPointer;
  209368. BYTE SRB_SenseLen;
  209369. BYTE SRB_CDBLen;
  209370. BYTE SRB_HaStat;
  209371. BYTE SRB_TargStat;
  209372. VOID FAR *SRB_PostProc;
  209373. BYTE SRB_Rsvd2[20];
  209374. BYTE CDBByte[16];
  209375. BYTE SenseArea[SENSE_LEN+2];
  209376. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  209377. typedef struct
  209378. {
  209379. BYTE SRB_Cmd;
  209380. BYTE SRB_Status;
  209381. BYTE SRB_HaId;
  209382. BYTE SRB_Flags;
  209383. DWORD SRB_Hdr_Rsvd;
  209384. } PACKED SRB, *PSRB, FAR *LPSRB;
  209385. #pragma pack()
  209386. struct CDDeviceInfo
  209387. {
  209388. char vendor[9];
  209389. char productId[17];
  209390. char rev[5];
  209391. char vendorSpec[21];
  209392. BYTE ha;
  209393. BYTE tgt;
  209394. BYTE lun;
  209395. char scsiDriveLetter; // will be 0 if not using scsi
  209396. };
  209397. class CDReadBuffer
  209398. {
  209399. public:
  209400. int startFrame;
  209401. int numFrames;
  209402. int dataStartOffset;
  209403. int dataLength;
  209404. int bufferSize;
  209405. HeapBlock<BYTE> buffer;
  209406. int index;
  209407. bool wantsIndex;
  209408. CDReadBuffer (const int numberOfFrames)
  209409. : startFrame (0),
  209410. numFrames (0),
  209411. dataStartOffset (0),
  209412. dataLength (0),
  209413. bufferSize (2352 * numberOfFrames),
  209414. buffer (bufferSize),
  209415. index (0),
  209416. wantsIndex (false)
  209417. {
  209418. }
  209419. bool isZero() const throw()
  209420. {
  209421. BYTE* p = buffer + dataStartOffset;
  209422. for (int i = dataLength; --i >= 0;)
  209423. if (*p++ != 0)
  209424. return false;
  209425. return true;
  209426. }
  209427. };
  209428. class CDDeviceHandle;
  209429. class CDController
  209430. {
  209431. public:
  209432. CDController();
  209433. virtual ~CDController();
  209434. virtual bool read (CDReadBuffer* t) = 0;
  209435. virtual void shutDown();
  209436. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  209437. int getLastIndex();
  209438. public:
  209439. bool initialised;
  209440. CDDeviceHandle* deviceInfo;
  209441. int framesToCheck, framesOverlap;
  209442. void prepare (SRB_ExecSCSICmd& s);
  209443. void perform (SRB_ExecSCSICmd& s);
  209444. void setPaused (bool paused);
  209445. };
  209446. #pragma pack(1)
  209447. struct TOCTRACK
  209448. {
  209449. BYTE rsvd;
  209450. BYTE ADR;
  209451. BYTE trackNumber;
  209452. BYTE rsvd2;
  209453. BYTE addr[4];
  209454. };
  209455. struct TOC
  209456. {
  209457. WORD tocLen;
  209458. BYTE firstTrack;
  209459. BYTE lastTrack;
  209460. TOCTRACK tracks[100];
  209461. };
  209462. #pragma pack()
  209463. enum
  209464. {
  209465. READTYPE_ANY = 0,
  209466. READTYPE_ATAPI1 = 1,
  209467. READTYPE_ATAPI2 = 2,
  209468. READTYPE_READ6 = 3,
  209469. READTYPE_READ10 = 4,
  209470. READTYPE_READ_D8 = 5,
  209471. READTYPE_READ_D4 = 6,
  209472. READTYPE_READ_D4_1 = 7,
  209473. READTYPE_READ10_2 = 8
  209474. };
  209475. class CDDeviceHandle
  209476. {
  209477. public:
  209478. CDDeviceHandle (const CDDeviceInfo* const device)
  209479. : scsiHandle (0),
  209480. readType (READTYPE_ANY),
  209481. controller (0)
  209482. {
  209483. memcpy (&info, device, sizeof (info));
  209484. }
  209485. ~CDDeviceHandle()
  209486. {
  209487. if (controller != 0)
  209488. {
  209489. controller->shutDown();
  209490. controller = 0;
  209491. }
  209492. if (scsiHandle != 0)
  209493. CloseHandle (scsiHandle);
  209494. }
  209495. bool readTOC (TOC* lpToc, bool useMSF);
  209496. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  209497. void openDrawer (bool shouldBeOpen);
  209498. CDDeviceInfo info;
  209499. HANDLE scsiHandle;
  209500. BYTE readType;
  209501. private:
  209502. ScopedPointer<CDController> controller;
  209503. bool testController (const int readType,
  209504. CDController* const newController,
  209505. CDReadBuffer* const bufferToUse);
  209506. };
  209507. DWORD (*fGetASPI32SupportInfo)(void);
  209508. DWORD (*fSendASPI32Command)(LPSRB);
  209509. static HINSTANCE winAspiLib = 0;
  209510. static bool usingScsi = false;
  209511. static bool initialised = false;
  209512. static bool InitialiseCDRipper()
  209513. {
  209514. if (! initialised)
  209515. {
  209516. initialised = true;
  209517. OSVERSIONINFO info;
  209518. info.dwOSVersionInfoSize = sizeof (info);
  209519. GetVersionEx (&info);
  209520. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  209521. if (! usingScsi)
  209522. {
  209523. fGetASPI32SupportInfo = 0;
  209524. fSendASPI32Command = 0;
  209525. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  209526. if (winAspiLib != 0)
  209527. {
  209528. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  209529. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  209530. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  209531. return false;
  209532. }
  209533. else
  209534. {
  209535. usingScsi = true;
  209536. }
  209537. }
  209538. }
  209539. return true;
  209540. }
  209541. static void DeinitialiseCDRipper()
  209542. {
  209543. if (winAspiLib != 0)
  209544. {
  209545. fGetASPI32SupportInfo = 0;
  209546. fSendASPI32Command = 0;
  209547. FreeLibrary (winAspiLib);
  209548. winAspiLib = 0;
  209549. }
  209550. initialised = false;
  209551. }
  209552. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  209553. {
  209554. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  209555. OSVERSIONINFO info;
  209556. info.dwOSVersionInfoSize = sizeof (info);
  209557. GetVersionEx (&info);
  209558. DWORD flags = GENERIC_READ;
  209559. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  209560. flags = GENERIC_READ | GENERIC_WRITE;
  209561. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  209562. if (h == INVALID_HANDLE_VALUE)
  209563. {
  209564. flags ^= GENERIC_WRITE;
  209565. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  209566. }
  209567. return h;
  209568. }
  209569. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  209570. const char driveLetter,
  209571. HANDLE& deviceHandle,
  209572. const bool retryOnFailure = true)
  209573. {
  209574. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  209575. zerostruct (s);
  209576. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  209577. s.spt.CdbLength = srb->SRB_CDBLen;
  209578. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  209579. ? SCSI_IOCTL_DATA_IN
  209580. : ((srb->SRB_Flags & SRB_DIR_OUT)
  209581. ? SCSI_IOCTL_DATA_OUT
  209582. : SCSI_IOCTL_DATA_UNSPECIFIED));
  209583. s.spt.DataTransferLength = srb->SRB_BufLen;
  209584. s.spt.TimeOutValue = 5;
  209585. s.spt.DataBuffer = srb->SRB_BufPointer;
  209586. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  209587. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  209588. srb->SRB_Status = SS_ERR;
  209589. srb->SRB_TargStat = 0x0004;
  209590. DWORD bytesReturned = 0;
  209591. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  209592. &s, sizeof (s),
  209593. &s, sizeof (s),
  209594. &bytesReturned, 0) != 0)
  209595. {
  209596. srb->SRB_Status = SS_COMP;
  209597. }
  209598. else if (retryOnFailure)
  209599. {
  209600. const DWORD error = GetLastError();
  209601. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  209602. {
  209603. if (error != ERROR_INVALID_HANDLE)
  209604. CloseHandle (deviceHandle);
  209605. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  209606. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  209607. }
  209608. }
  209609. return srb->SRB_Status;
  209610. }
  209611. // Controller types..
  209612. class ControllerType1 : public CDController
  209613. {
  209614. public:
  209615. ControllerType1() {}
  209616. ~ControllerType1() {}
  209617. bool read (CDReadBuffer* rb)
  209618. {
  209619. if (rb->numFrames * 2352 > rb->bufferSize)
  209620. return false;
  209621. SRB_ExecSCSICmd s;
  209622. prepare (s);
  209623. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209624. s.SRB_BufLen = rb->bufferSize;
  209625. s.SRB_BufPointer = rb->buffer;
  209626. s.SRB_CDBLen = 12;
  209627. s.CDBByte[0] = 0xBE;
  209628. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209629. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209630. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209631. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209632. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  209633. perform (s);
  209634. if (s.SRB_Status != SS_COMP)
  209635. return false;
  209636. rb->dataLength = rb->numFrames * 2352;
  209637. rb->dataStartOffset = 0;
  209638. return true;
  209639. }
  209640. };
  209641. class ControllerType2 : public CDController
  209642. {
  209643. public:
  209644. ControllerType2() {}
  209645. ~ControllerType2() {}
  209646. void shutDown()
  209647. {
  209648. if (initialised)
  209649. {
  209650. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  209651. SRB_ExecSCSICmd s;
  209652. prepare (s);
  209653. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  209654. s.SRB_BufLen = 0x0C;
  209655. s.SRB_BufPointer = bufPointer;
  209656. s.SRB_CDBLen = 6;
  209657. s.CDBByte[0] = 0x15;
  209658. s.CDBByte[4] = 0x0C;
  209659. perform (s);
  209660. }
  209661. }
  209662. bool init()
  209663. {
  209664. SRB_ExecSCSICmd s;
  209665. s.SRB_Status = SS_ERR;
  209666. if (deviceInfo->readType == READTYPE_READ10_2)
  209667. {
  209668. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  209669. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  209670. for (int i = 0; i < 2; ++i)
  209671. {
  209672. prepare (s);
  209673. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209674. s.SRB_BufLen = 0x14;
  209675. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  209676. s.SRB_CDBLen = 6;
  209677. s.CDBByte[0] = 0x15;
  209678. s.CDBByte[1] = 0x10;
  209679. s.CDBByte[4] = 0x14;
  209680. perform (s);
  209681. if (s.SRB_Status != SS_COMP)
  209682. return false;
  209683. }
  209684. }
  209685. else
  209686. {
  209687. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  209688. prepare (s);
  209689. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209690. s.SRB_BufLen = 0x0C;
  209691. s.SRB_BufPointer = bufPointer;
  209692. s.SRB_CDBLen = 6;
  209693. s.CDBByte[0] = 0x15;
  209694. s.CDBByte[4] = 0x0C;
  209695. perform (s);
  209696. }
  209697. return s.SRB_Status == SS_COMP;
  209698. }
  209699. bool read (CDReadBuffer* rb)
  209700. {
  209701. if (rb->numFrames * 2352 > rb->bufferSize)
  209702. return false;
  209703. if (!initialised)
  209704. {
  209705. initialised = init();
  209706. if (!initialised)
  209707. return false;
  209708. }
  209709. SRB_ExecSCSICmd s;
  209710. prepare (s);
  209711. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209712. s.SRB_BufLen = rb->bufferSize;
  209713. s.SRB_BufPointer = rb->buffer;
  209714. s.SRB_CDBLen = 10;
  209715. s.CDBByte[0] = 0x28;
  209716. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  209717. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209718. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209719. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209720. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209721. perform (s);
  209722. if (s.SRB_Status != SS_COMP)
  209723. return false;
  209724. rb->dataLength = rb->numFrames * 2352;
  209725. rb->dataStartOffset = 0;
  209726. return true;
  209727. }
  209728. };
  209729. class ControllerType3 : public CDController
  209730. {
  209731. public:
  209732. ControllerType3() {}
  209733. ~ControllerType3() {}
  209734. bool read (CDReadBuffer* rb)
  209735. {
  209736. if (rb->numFrames * 2352 > rb->bufferSize)
  209737. return false;
  209738. if (!initialised)
  209739. {
  209740. setPaused (false);
  209741. initialised = true;
  209742. }
  209743. SRB_ExecSCSICmd s;
  209744. prepare (s);
  209745. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209746. s.SRB_BufLen = rb->numFrames * 2352;
  209747. s.SRB_BufPointer = rb->buffer;
  209748. s.SRB_CDBLen = 12;
  209749. s.CDBByte[0] = 0xD8;
  209750. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209751. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209752. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209753. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  209754. perform (s);
  209755. if (s.SRB_Status != SS_COMP)
  209756. return false;
  209757. rb->dataLength = rb->numFrames * 2352;
  209758. rb->dataStartOffset = 0;
  209759. return true;
  209760. }
  209761. };
  209762. class ControllerType4 : public CDController
  209763. {
  209764. public:
  209765. ControllerType4() {}
  209766. ~ControllerType4() {}
  209767. bool selectD4Mode()
  209768. {
  209769. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  209770. SRB_ExecSCSICmd s;
  209771. prepare (s);
  209772. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209773. s.SRB_CDBLen = 6;
  209774. s.SRB_BufLen = 12;
  209775. s.SRB_BufPointer = bufPointer;
  209776. s.CDBByte[0] = 0x15;
  209777. s.CDBByte[1] = 0x10;
  209778. s.CDBByte[4] = 0x08;
  209779. perform (s);
  209780. return s.SRB_Status == SS_COMP;
  209781. }
  209782. bool read (CDReadBuffer* rb)
  209783. {
  209784. if (rb->numFrames * 2352 > rb->bufferSize)
  209785. return false;
  209786. if (!initialised)
  209787. {
  209788. setPaused (true);
  209789. if (deviceInfo->readType == READTYPE_READ_D4_1)
  209790. selectD4Mode();
  209791. initialised = true;
  209792. }
  209793. SRB_ExecSCSICmd s;
  209794. prepare (s);
  209795. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209796. s.SRB_BufLen = rb->bufferSize;
  209797. s.SRB_BufPointer = rb->buffer;
  209798. s.SRB_CDBLen = 10;
  209799. s.CDBByte[0] = 0xD4;
  209800. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209801. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209802. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209803. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209804. perform (s);
  209805. if (s.SRB_Status != SS_COMP)
  209806. return false;
  209807. rb->dataLength = rb->numFrames * 2352;
  209808. rb->dataStartOffset = 0;
  209809. return true;
  209810. }
  209811. };
  209812. CDController::CDController() : initialised (false)
  209813. {
  209814. }
  209815. CDController::~CDController()
  209816. {
  209817. }
  209818. void CDController::prepare (SRB_ExecSCSICmd& s)
  209819. {
  209820. zerostruct (s);
  209821. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209822. s.SRB_HaID = deviceInfo->info.ha;
  209823. s.SRB_Target = deviceInfo->info.tgt;
  209824. s.SRB_Lun = deviceInfo->info.lun;
  209825. s.SRB_SenseLen = SENSE_LEN;
  209826. }
  209827. void CDController::perform (SRB_ExecSCSICmd& s)
  209828. {
  209829. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209830. s.SRB_PostProc = event;
  209831. ResetEvent (event);
  209832. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  209833. deviceInfo->info.scsiDriveLetter,
  209834. deviceInfo->scsiHandle)
  209835. : fSendASPI32Command ((LPSRB)&s);
  209836. if (status == SS_PENDING)
  209837. WaitForSingleObject (event, 4000);
  209838. CloseHandle (event);
  209839. }
  209840. void CDController::setPaused (bool paused)
  209841. {
  209842. SRB_ExecSCSICmd s;
  209843. prepare (s);
  209844. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209845. s.SRB_CDBLen = 10;
  209846. s.CDBByte[0] = 0x4B;
  209847. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  209848. perform (s);
  209849. }
  209850. void CDController::shutDown()
  209851. {
  209852. }
  209853. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  209854. {
  209855. if (overlapBuffer != 0)
  209856. {
  209857. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  209858. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  209859. if (doJitter
  209860. && overlapBuffer->startFrame > 0
  209861. && overlapBuffer->numFrames > 0
  209862. && overlapBuffer->dataLength > 0)
  209863. {
  209864. const int numFrames = rb->numFrames;
  209865. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  209866. {
  209867. rb->startFrame -= framesOverlap;
  209868. if (framesToCheck < framesOverlap
  209869. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  209870. rb->numFrames += framesOverlap;
  209871. }
  209872. else
  209873. {
  209874. overlapBuffer->dataLength = 0;
  209875. overlapBuffer->startFrame = 0;
  209876. overlapBuffer->numFrames = 0;
  209877. }
  209878. }
  209879. if (! read (rb))
  209880. return false;
  209881. if (doJitter)
  209882. {
  209883. const int checkLen = framesToCheck * 2352;
  209884. const int maxToCheck = rb->dataLength - checkLen;
  209885. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  209886. return true;
  209887. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  209888. bool found = false;
  209889. for (int i = 0; i < maxToCheck; ++i)
  209890. {
  209891. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  209892. {
  209893. i += checkLen;
  209894. rb->dataStartOffset = i;
  209895. rb->dataLength -= i;
  209896. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  209897. found = true;
  209898. break;
  209899. }
  209900. }
  209901. rb->numFrames = rb->dataLength / 2352;
  209902. rb->dataLength = 2352 * rb->numFrames;
  209903. if (!found)
  209904. return false;
  209905. }
  209906. if (canDoJitter)
  209907. {
  209908. memcpy (overlapBuffer->buffer,
  209909. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  209910. 2352 * framesToCheck);
  209911. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  209912. overlapBuffer->numFrames = framesToCheck;
  209913. overlapBuffer->dataLength = 2352 * framesToCheck;
  209914. overlapBuffer->dataStartOffset = 0;
  209915. }
  209916. else
  209917. {
  209918. overlapBuffer->startFrame = 0;
  209919. overlapBuffer->numFrames = 0;
  209920. overlapBuffer->dataLength = 0;
  209921. }
  209922. return true;
  209923. }
  209924. else
  209925. {
  209926. return read (rb);
  209927. }
  209928. }
  209929. int CDController::getLastIndex()
  209930. {
  209931. char qdata[100];
  209932. SRB_ExecSCSICmd s;
  209933. prepare (s);
  209934. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209935. s.SRB_BufLen = sizeof (qdata);
  209936. s.SRB_BufPointer = (BYTE*)qdata;
  209937. s.SRB_CDBLen = 12;
  209938. s.CDBByte[0] = 0x42;
  209939. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  209940. s.CDBByte[2] = 64;
  209941. s.CDBByte[3] = 1; // get current position
  209942. s.CDBByte[7] = 0;
  209943. s.CDBByte[8] = (BYTE)sizeof (qdata);
  209944. perform (s);
  209945. if (s.SRB_Status == SS_COMP)
  209946. return qdata[7];
  209947. return 0;
  209948. }
  209949. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  209950. {
  209951. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209952. SRB_ExecSCSICmd s;
  209953. zerostruct (s);
  209954. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209955. s.SRB_HaID = info.ha;
  209956. s.SRB_Target = info.tgt;
  209957. s.SRB_Lun = info.lun;
  209958. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209959. s.SRB_BufLen = 0x324;
  209960. s.SRB_BufPointer = (BYTE*)lpToc;
  209961. s.SRB_SenseLen = 0x0E;
  209962. s.SRB_CDBLen = 0x0A;
  209963. s.SRB_PostProc = event;
  209964. s.CDBByte[0] = 0x43;
  209965. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  209966. s.CDBByte[7] = 0x03;
  209967. s.CDBByte[8] = 0x24;
  209968. ResetEvent (event);
  209969. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  209970. : fSendASPI32Command ((LPSRB)&s);
  209971. if (status == SS_PENDING)
  209972. WaitForSingleObject (event, 4000);
  209973. CloseHandle (event);
  209974. return (s.SRB_Status == SS_COMP);
  209975. }
  209976. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  209977. CDReadBuffer* const overlapBuffer)
  209978. {
  209979. if (controller == 0)
  209980. {
  209981. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  209982. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  209983. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  209984. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  209985. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  209986. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  209987. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  209988. }
  209989. buffer->index = 0;
  209990. if ((controller != 0)
  209991. && controller->readAudio (buffer, overlapBuffer))
  209992. {
  209993. if (buffer->wantsIndex)
  209994. buffer->index = controller->getLastIndex();
  209995. return true;
  209996. }
  209997. return false;
  209998. }
  209999. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  210000. {
  210001. if (shouldBeOpen)
  210002. {
  210003. if (controller != 0)
  210004. {
  210005. controller->shutDown();
  210006. controller = 0;
  210007. }
  210008. if (scsiHandle != 0)
  210009. {
  210010. CloseHandle (scsiHandle);
  210011. scsiHandle = 0;
  210012. }
  210013. }
  210014. SRB_ExecSCSICmd s;
  210015. zerostruct (s);
  210016. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210017. s.SRB_HaID = info.ha;
  210018. s.SRB_Target = info.tgt;
  210019. s.SRB_Lun = info.lun;
  210020. s.SRB_SenseLen = SENSE_LEN;
  210021. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210022. s.SRB_BufLen = 0;
  210023. s.SRB_BufPointer = 0;
  210024. s.SRB_CDBLen = 12;
  210025. s.CDBByte[0] = 0x1b;
  210026. s.CDBByte[1] = (BYTE)(info.lun << 5);
  210027. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  210028. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  210029. s.SRB_PostProc = event;
  210030. ResetEvent (event);
  210031. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  210032. : fSendASPI32Command ((LPSRB)&s);
  210033. if (status == SS_PENDING)
  210034. WaitForSingleObject (event, 4000);
  210035. CloseHandle (event);
  210036. }
  210037. bool CDDeviceHandle::testController (const int type,
  210038. CDController* const newController,
  210039. CDReadBuffer* const rb)
  210040. {
  210041. controller = newController;
  210042. readType = (BYTE)type;
  210043. controller->deviceInfo = this;
  210044. controller->framesToCheck = 1;
  210045. controller->framesOverlap = 3;
  210046. bool passed = false;
  210047. memset (rb->buffer, 0xcd, rb->bufferSize);
  210048. if (controller->read (rb))
  210049. {
  210050. passed = true;
  210051. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  210052. int wrong = 0;
  210053. for (int i = rb->dataLength / 4; --i >= 0;)
  210054. {
  210055. if (*p++ == (int) 0xcdcdcdcd)
  210056. {
  210057. if (++wrong == 4)
  210058. {
  210059. passed = false;
  210060. break;
  210061. }
  210062. }
  210063. else
  210064. {
  210065. wrong = 0;
  210066. }
  210067. }
  210068. }
  210069. if (! passed)
  210070. {
  210071. controller->shutDown();
  210072. controller = 0;
  210073. }
  210074. return passed;
  210075. }
  210076. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  210077. {
  210078. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  210079. const int bufSize = 128;
  210080. BYTE buffer[bufSize];
  210081. zeromem (buffer, bufSize);
  210082. SRB_ExecSCSICmd s;
  210083. zerostruct (s);
  210084. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210085. s.SRB_HaID = ha;
  210086. s.SRB_Target = tgt;
  210087. s.SRB_Lun = lun;
  210088. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210089. s.SRB_BufLen = bufSize;
  210090. s.SRB_BufPointer = buffer;
  210091. s.SRB_SenseLen = SENSE_LEN;
  210092. s.SRB_CDBLen = 6;
  210093. s.SRB_PostProc = event;
  210094. s.CDBByte[0] = SCSI_INQUIRY;
  210095. s.CDBByte[4] = 100;
  210096. ResetEvent (event);
  210097. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  210098. WaitForSingleObject (event, 4000);
  210099. CloseHandle (event);
  210100. if (s.SRB_Status == SS_COMP)
  210101. {
  210102. memcpy (dev->vendor, &buffer[8], 8);
  210103. memcpy (dev->productId, &buffer[16], 16);
  210104. memcpy (dev->rev, &buffer[32], 4);
  210105. memcpy (dev->vendorSpec, &buffer[36], 20);
  210106. }
  210107. }
  210108. static int FindCDDevices (CDDeviceInfo* const list,
  210109. int maxItems)
  210110. {
  210111. int count = 0;
  210112. if (usingScsi)
  210113. {
  210114. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  210115. {
  210116. TCHAR drivePath[8];
  210117. drivePath[0] = driveLetter;
  210118. drivePath[1] = ':';
  210119. drivePath[2] = '\\';
  210120. drivePath[3] = 0;
  210121. if (GetDriveType (drivePath) == DRIVE_CDROM)
  210122. {
  210123. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  210124. if (h != INVALID_HANDLE_VALUE)
  210125. {
  210126. BYTE buffer[100], passThroughStruct[1024];
  210127. zeromem (buffer, sizeof (buffer));
  210128. zeromem (passThroughStruct, sizeof (passThroughStruct));
  210129. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  210130. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  210131. p->spt.CdbLength = 6;
  210132. p->spt.SenseInfoLength = 24;
  210133. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  210134. p->spt.DataTransferLength = 100;
  210135. p->spt.TimeOutValue = 2;
  210136. p->spt.DataBuffer = buffer;
  210137. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210138. p->spt.Cdb[0] = 0x12;
  210139. p->spt.Cdb[4] = 100;
  210140. DWORD bytesReturned = 0;
  210141. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210142. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  210143. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  210144. &bytesReturned, 0) != 0)
  210145. {
  210146. zeromem (&list[count], sizeof (CDDeviceInfo));
  210147. list[count].scsiDriveLetter = driveLetter;
  210148. memcpy (list[count].vendor, &buffer[8], 8);
  210149. memcpy (list[count].productId, &buffer[16], 16);
  210150. memcpy (list[count].rev, &buffer[32], 4);
  210151. memcpy (list[count].vendorSpec, &buffer[36], 20);
  210152. zeromem (passThroughStruct, sizeof (passThroughStruct));
  210153. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  210154. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  210155. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  210156. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  210157. &bytesReturned, 0) != 0)
  210158. {
  210159. list[count].ha = scsiAddr->PortNumber;
  210160. list[count].tgt = scsiAddr->TargetId;
  210161. list[count].lun = scsiAddr->Lun;
  210162. ++count;
  210163. }
  210164. }
  210165. CloseHandle (h);
  210166. }
  210167. }
  210168. }
  210169. }
  210170. else
  210171. {
  210172. const DWORD d = fGetASPI32SupportInfo();
  210173. BYTE status = HIBYTE (LOWORD (d));
  210174. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  210175. return 0;
  210176. const int numAdapters = LOBYTE (LOWORD (d));
  210177. for (BYTE ha = 0; ha < numAdapters; ++ha)
  210178. {
  210179. SRB_HAInquiry s;
  210180. zerostruct (s);
  210181. s.SRB_Cmd = SC_HA_INQUIRY;
  210182. s.SRB_HaID = ha;
  210183. fSendASPI32Command ((LPSRB)&s);
  210184. if (s.SRB_Status == SS_COMP)
  210185. {
  210186. maxItems = (int)s.HA_Unique[3];
  210187. if (maxItems == 0)
  210188. maxItems = 8;
  210189. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  210190. {
  210191. for (BYTE lun = 0; lun < 8; ++lun)
  210192. {
  210193. SRB_GDEVBlock sb;
  210194. zerostruct (sb);
  210195. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  210196. sb.SRB_HaID = ha;
  210197. sb.SRB_Target = tgt;
  210198. sb.SRB_Lun = lun;
  210199. fSendASPI32Command ((LPSRB) &sb);
  210200. if (sb.SRB_Status == SS_COMP
  210201. && sb.SRB_DeviceType == DTYPE_CROM)
  210202. {
  210203. zeromem (&list[count], sizeof (CDDeviceInfo));
  210204. list[count].ha = ha;
  210205. list[count].tgt = tgt;
  210206. list[count].lun = lun;
  210207. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  210208. ++count;
  210209. }
  210210. }
  210211. }
  210212. }
  210213. }
  210214. }
  210215. return count;
  210216. }
  210217. static int ripperUsers = 0;
  210218. static bool initialisedOk = false;
  210219. class DeinitialiseTimer : private Timer,
  210220. private DeletedAtShutdown
  210221. {
  210222. DeinitialiseTimer (const DeinitialiseTimer&);
  210223. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  210224. public:
  210225. DeinitialiseTimer()
  210226. {
  210227. startTimer (4000);
  210228. }
  210229. ~DeinitialiseTimer()
  210230. {
  210231. if (--ripperUsers == 0)
  210232. DeinitialiseCDRipper();
  210233. }
  210234. void timerCallback()
  210235. {
  210236. delete this;
  210237. }
  210238. juce_UseDebuggingNewOperator
  210239. };
  210240. static void incUserCount()
  210241. {
  210242. if (ripperUsers++ == 0)
  210243. initialisedOk = InitialiseCDRipper();
  210244. }
  210245. static void decUserCount()
  210246. {
  210247. new DeinitialiseTimer();
  210248. }
  210249. struct CDDeviceWrapper
  210250. {
  210251. ScopedPointer<CDDeviceHandle> cdH;
  210252. ScopedPointer<CDReadBuffer> overlapBuffer;
  210253. bool jitter;
  210254. };
  210255. static int getAddressOf (const TOCTRACK* const t)
  210256. {
  210257. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  210258. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  210259. }
  210260. static int getMSFAddressOf (const TOCTRACK* const t)
  210261. {
  210262. return 60 * t->addr[1] + t->addr[2];
  210263. }
  210264. static const int samplesPerFrame = 44100 / 75;
  210265. static const int bytesPerFrame = samplesPerFrame * 4;
  210266. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  210267. {
  210268. SRB_GDEVBlock s;
  210269. zerostruct (s);
  210270. s.SRB_Cmd = SC_GET_DEV_TYPE;
  210271. s.SRB_HaID = device->ha;
  210272. s.SRB_Target = device->tgt;
  210273. s.SRB_Lun = device->lun;
  210274. if (usingScsi)
  210275. {
  210276. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  210277. if (h != INVALID_HANDLE_VALUE)
  210278. {
  210279. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  210280. cdh->scsiHandle = h;
  210281. return cdh;
  210282. }
  210283. }
  210284. else
  210285. {
  210286. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  210287. && s.SRB_DeviceType == DTYPE_CROM)
  210288. {
  210289. return new CDDeviceHandle (device);
  210290. }
  210291. }
  210292. return 0;
  210293. }
  210294. }
  210295. const StringArray AudioCDReader::getAvailableCDNames()
  210296. {
  210297. using namespace CDReaderHelpers;
  210298. StringArray results;
  210299. incUserCount();
  210300. if (initialisedOk)
  210301. {
  210302. CDDeviceInfo list[8];
  210303. const int num = FindCDDevices (list, 8);
  210304. decUserCount();
  210305. for (int i = 0; i < num; ++i)
  210306. {
  210307. String s;
  210308. if (list[i].scsiDriveLetter > 0)
  210309. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  210310. s << String (list[i].vendor).trim()
  210311. << ' ' << String (list[i].productId).trim()
  210312. << ' ' << String (list[i].rev).trim();
  210313. results.add (s);
  210314. }
  210315. }
  210316. return results;
  210317. }
  210318. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  210319. {
  210320. using namespace CDReaderHelpers;
  210321. incUserCount();
  210322. if (initialisedOk)
  210323. {
  210324. CDDeviceInfo list[8];
  210325. const int num = FindCDDevices (list, 8);
  210326. if (((unsigned int) deviceIndex) < (unsigned int) num)
  210327. {
  210328. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  210329. if (handle != 0)
  210330. {
  210331. CDDeviceWrapper* const d = new CDDeviceWrapper();
  210332. d->cdH = handle;
  210333. d->overlapBuffer = new CDReadBuffer(3);
  210334. return new AudioCDReader (d);
  210335. }
  210336. }
  210337. }
  210338. decUserCount();
  210339. return 0;
  210340. }
  210341. AudioCDReader::AudioCDReader (void* handle_)
  210342. : AudioFormatReader (0, "CD Audio"),
  210343. handle (handle_),
  210344. indexingEnabled (false),
  210345. lastIndex (0),
  210346. firstFrameInBuffer (0),
  210347. samplesInBuffer (0)
  210348. {
  210349. using namespace CDReaderHelpers;
  210350. jassert (handle_ != 0);
  210351. refreshTrackLengths();
  210352. sampleRate = 44100.0;
  210353. bitsPerSample = 16;
  210354. lengthInSamples = getPositionOfTrackStart (numTracks);
  210355. numChannels = 2;
  210356. usesFloatingPointData = false;
  210357. buffer.setSize (4 * bytesPerFrame, true);
  210358. }
  210359. AudioCDReader::~AudioCDReader()
  210360. {
  210361. using namespace CDReaderHelpers;
  210362. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210363. delete device;
  210364. decUserCount();
  210365. }
  210366. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  210367. int64 startSampleInFile, int numSamples)
  210368. {
  210369. using namespace CDReaderHelpers;
  210370. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210371. bool ok = true;
  210372. while (numSamples > 0)
  210373. {
  210374. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  210375. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  210376. if (startSampleInFile >= bufferStartSample
  210377. && startSampleInFile < bufferEndSample)
  210378. {
  210379. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  210380. int* const l = destSamples[0] + startOffsetInDestBuffer;
  210381. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  210382. const short* src = (const short*) buffer.getData();
  210383. src += 2 * (startSampleInFile - bufferStartSample);
  210384. for (int i = 0; i < toDo; ++i)
  210385. {
  210386. l[i] = src [i << 1] << 16;
  210387. if (r != 0)
  210388. r[i] = src [(i << 1) + 1] << 16;
  210389. }
  210390. startOffsetInDestBuffer += toDo;
  210391. startSampleInFile += toDo;
  210392. numSamples -= toDo;
  210393. }
  210394. else
  210395. {
  210396. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  210397. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  210398. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  210399. {
  210400. device->overlapBuffer->dataLength = 0;
  210401. device->overlapBuffer->startFrame = 0;
  210402. device->overlapBuffer->numFrames = 0;
  210403. device->jitter = false;
  210404. }
  210405. firstFrameInBuffer = frameNeeded;
  210406. lastIndex = 0;
  210407. CDReadBuffer readBuffer (framesInBuffer + 4);
  210408. readBuffer.wantsIndex = indexingEnabled;
  210409. int i;
  210410. for (i = 5; --i >= 0;)
  210411. {
  210412. readBuffer.startFrame = frameNeeded;
  210413. readBuffer.numFrames = framesInBuffer;
  210414. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  210415. break;
  210416. else
  210417. device->overlapBuffer->dataLength = 0;
  210418. }
  210419. if (i >= 0)
  210420. {
  210421. memcpy ((char*) buffer.getData(),
  210422. readBuffer.buffer + readBuffer.dataStartOffset,
  210423. readBuffer.dataLength);
  210424. samplesInBuffer = readBuffer.dataLength >> 2;
  210425. lastIndex = readBuffer.index;
  210426. }
  210427. else
  210428. {
  210429. int* l = destSamples[0] + startOffsetInDestBuffer;
  210430. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  210431. while (--numSamples >= 0)
  210432. {
  210433. *l++ = 0;
  210434. if (r != 0)
  210435. *r++ = 0;
  210436. }
  210437. // sometimes the read fails for just the very last couple of blocks, so
  210438. // we'll ignore and errors in the last half-second of the disk..
  210439. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  210440. break;
  210441. }
  210442. }
  210443. }
  210444. return ok;
  210445. }
  210446. bool AudioCDReader::isCDStillPresent() const
  210447. {
  210448. using namespace CDReaderHelpers;
  210449. TOC toc;
  210450. zerostruct (toc);
  210451. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, false);
  210452. }
  210453. int AudioCDReader::getNumTracks() const
  210454. {
  210455. return numTracks;
  210456. }
  210457. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  210458. {
  210459. using namespace CDReaderHelpers;
  210460. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  210461. : 0;
  210462. }
  210463. void AudioCDReader::refreshTrackLengths()
  210464. {
  210465. using namespace CDReaderHelpers;
  210466. zeromem (trackStarts, sizeof (trackStarts));
  210467. zeromem (audioTracks, sizeof (audioTracks));
  210468. TOC toc;
  210469. zerostruct (toc);
  210470. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  210471. {
  210472. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  210473. for (int i = 0; i <= numTracks; ++i)
  210474. {
  210475. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  210476. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  210477. }
  210478. }
  210479. else
  210480. {
  210481. numTracks = 0;
  210482. }
  210483. }
  210484. bool AudioCDReader::isTrackAudio (int trackNum) const
  210485. {
  210486. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  210487. : false;
  210488. }
  210489. void AudioCDReader::enableIndexScanning (bool b)
  210490. {
  210491. indexingEnabled = b;
  210492. }
  210493. int AudioCDReader::getLastIndex() const
  210494. {
  210495. return lastIndex;
  210496. }
  210497. const int framesPerIndexRead = 4;
  210498. int AudioCDReader::getIndexAt (int samplePos)
  210499. {
  210500. using namespace CDReaderHelpers;
  210501. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210502. const int frameNeeded = samplePos / samplesPerFrame;
  210503. device->overlapBuffer->dataLength = 0;
  210504. device->overlapBuffer->startFrame = 0;
  210505. device->overlapBuffer->numFrames = 0;
  210506. device->jitter = false;
  210507. firstFrameInBuffer = 0;
  210508. lastIndex = 0;
  210509. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  210510. readBuffer.wantsIndex = true;
  210511. int i;
  210512. for (i = 5; --i >= 0;)
  210513. {
  210514. readBuffer.startFrame = frameNeeded;
  210515. readBuffer.numFrames = framesPerIndexRead;
  210516. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  210517. break;
  210518. }
  210519. if (i >= 0)
  210520. return readBuffer.index;
  210521. return -1;
  210522. }
  210523. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  210524. {
  210525. using namespace CDReaderHelpers;
  210526. Array <int> indexes;
  210527. const int trackStart = getPositionOfTrackStart (trackNumber);
  210528. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  210529. bool needToScan = true;
  210530. if (trackEnd - trackStart > 20 * 44100)
  210531. {
  210532. // check the end of the track for indexes before scanning the whole thing
  210533. needToScan = false;
  210534. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  210535. bool seenAnIndex = false;
  210536. while (pos <= trackEnd - samplesPerFrame)
  210537. {
  210538. const int index = getIndexAt (pos);
  210539. if (index == 0)
  210540. {
  210541. // lead-out, so skip back a bit if we've not found any indexes yet..
  210542. if (seenAnIndex)
  210543. break;
  210544. pos -= 44100 * 5;
  210545. if (pos < trackStart)
  210546. break;
  210547. }
  210548. else
  210549. {
  210550. if (index > 0)
  210551. seenAnIndex = true;
  210552. if (index > 1)
  210553. {
  210554. needToScan = true;
  210555. break;
  210556. }
  210557. pos += samplesPerFrame * framesPerIndexRead;
  210558. }
  210559. }
  210560. }
  210561. if (needToScan)
  210562. {
  210563. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210564. int pos = trackStart;
  210565. int last = -1;
  210566. while (pos < trackEnd - samplesPerFrame * 10)
  210567. {
  210568. const int frameNeeded = pos / samplesPerFrame;
  210569. device->overlapBuffer->dataLength = 0;
  210570. device->overlapBuffer->startFrame = 0;
  210571. device->overlapBuffer->numFrames = 0;
  210572. device->jitter = false;
  210573. firstFrameInBuffer = 0;
  210574. CDReadBuffer readBuffer (4);
  210575. readBuffer.wantsIndex = true;
  210576. int i;
  210577. for (i = 5; --i >= 0;)
  210578. {
  210579. readBuffer.startFrame = frameNeeded;
  210580. readBuffer.numFrames = framesPerIndexRead;
  210581. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  210582. break;
  210583. }
  210584. if (i < 0)
  210585. break;
  210586. if (readBuffer.index > last && readBuffer.index > 1)
  210587. {
  210588. last = readBuffer.index;
  210589. indexes.add (pos);
  210590. }
  210591. pos += samplesPerFrame * framesPerIndexRead;
  210592. }
  210593. indexes.removeValue (trackStart);
  210594. }
  210595. return indexes;
  210596. }
  210597. int AudioCDReader::getCDDBId()
  210598. {
  210599. using namespace CDReaderHelpers;
  210600. refreshTrackLengths();
  210601. if (numTracks > 0)
  210602. {
  210603. TOC toc;
  210604. zerostruct (toc);
  210605. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  210606. {
  210607. int n = 0;
  210608. for (int i = numTracks; --i >= 0;)
  210609. {
  210610. int j = getMSFAddressOf (&toc.tracks[i]);
  210611. while (j > 0)
  210612. {
  210613. n += (j % 10);
  210614. j /= 10;
  210615. }
  210616. }
  210617. if (n != 0)
  210618. {
  210619. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  210620. - getMSFAddressOf (&toc.tracks[0]);
  210621. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  210622. }
  210623. }
  210624. }
  210625. return 0;
  210626. }
  210627. void AudioCDReader::ejectDisk()
  210628. {
  210629. using namespace CDReaderHelpers;
  210630. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  210631. }
  210632. #endif
  210633. #if JUCE_USE_CDBURNER
  210634. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  210635. {
  210636. CoInitialize (0);
  210637. IDiscMaster* dm;
  210638. IDiscRecorder* result = 0;
  210639. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  210640. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  210641. IID_IDiscMaster,
  210642. (void**) &dm)))
  210643. {
  210644. if (SUCCEEDED (dm->Open()))
  210645. {
  210646. IEnumDiscRecorders* drEnum = 0;
  210647. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  210648. {
  210649. IDiscRecorder* dr = 0;
  210650. DWORD dummy;
  210651. int index = 0;
  210652. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  210653. {
  210654. if (indexToOpen == index)
  210655. {
  210656. result = dr;
  210657. break;
  210658. }
  210659. else if (list != 0)
  210660. {
  210661. BSTR path;
  210662. if (SUCCEEDED (dr->GetPath (&path)))
  210663. list->add ((const WCHAR*) path);
  210664. }
  210665. ++index;
  210666. dr->Release();
  210667. }
  210668. drEnum->Release();
  210669. }
  210670. if (master == 0)
  210671. dm->Close();
  210672. }
  210673. if (master != 0)
  210674. *master = dm;
  210675. else
  210676. dm->Release();
  210677. }
  210678. return result;
  210679. }
  210680. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  210681. public Timer
  210682. {
  210683. public:
  210684. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  210685. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  210686. listener (0), progress (0), shouldCancel (false)
  210687. {
  210688. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  210689. jassert (SUCCEEDED (hr));
  210690. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  210691. //jassert (SUCCEEDED (hr));
  210692. lastState = getDiskState();
  210693. startTimer (2000);
  210694. }
  210695. ~Pimpl() {}
  210696. void releaseObjects()
  210697. {
  210698. discRecorder->Close();
  210699. if (redbook != 0)
  210700. redbook->Release();
  210701. discRecorder->Release();
  210702. discMaster->Release();
  210703. Release();
  210704. }
  210705. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  210706. {
  210707. if (listener != 0 && ! shouldCancel)
  210708. shouldCancel = listener->audioCDBurnProgress (progress);
  210709. *pbCancel = shouldCancel;
  210710. return S_OK;
  210711. }
  210712. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  210713. {
  210714. progress = nCompleted / (float) nTotal;
  210715. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  210716. return E_NOTIMPL;
  210717. }
  210718. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  210719. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  210720. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  210721. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  210722. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  210723. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  210724. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  210725. class ScopedDiscOpener
  210726. {
  210727. public:
  210728. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  210729. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  210730. private:
  210731. Pimpl& pimpl;
  210732. ScopedDiscOpener (const ScopedDiscOpener&);
  210733. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  210734. };
  210735. DiskState getDiskState()
  210736. {
  210737. const ScopedDiscOpener opener (*this);
  210738. long type, flags;
  210739. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  210740. if (FAILED (hr))
  210741. return unknown;
  210742. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  210743. return writableDiskPresent;
  210744. if (type == 0)
  210745. return noDisc;
  210746. else
  210747. return readOnlyDiskPresent;
  210748. }
  210749. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  210750. {
  210751. ComSmartPtr<IPropertyStorage> prop;
  210752. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  210753. return defaultReturn;
  210754. PROPSPEC iPropSpec;
  210755. iPropSpec.ulKind = PRSPEC_LPWSTR;
  210756. iPropSpec.lpwstr = name;
  210757. PROPVARIANT iPropVariant;
  210758. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  210759. ? defaultReturn : (int) iPropVariant.lVal;
  210760. }
  210761. bool setIntProperty (const LPOLESTR name, const int value) const
  210762. {
  210763. ComSmartPtr<IPropertyStorage> prop;
  210764. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  210765. return false;
  210766. PROPSPEC iPropSpec;
  210767. iPropSpec.ulKind = PRSPEC_LPWSTR;
  210768. iPropSpec.lpwstr = name;
  210769. PROPVARIANT iPropVariant;
  210770. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  210771. return false;
  210772. iPropVariant.lVal = (long) value;
  210773. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  210774. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  210775. }
  210776. void timerCallback()
  210777. {
  210778. const DiskState state = getDiskState();
  210779. if (state != lastState)
  210780. {
  210781. lastState = state;
  210782. owner.sendChangeMessage (&owner);
  210783. }
  210784. }
  210785. AudioCDBurner& owner;
  210786. DiskState lastState;
  210787. IDiscMaster* discMaster;
  210788. IDiscRecorder* discRecorder;
  210789. IRedbookDiscMaster* redbook;
  210790. AudioCDBurner::BurnProgressListener* listener;
  210791. float progress;
  210792. bool shouldCancel;
  210793. };
  210794. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  210795. {
  210796. IDiscMaster* discMaster = 0;
  210797. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  210798. if (discRecorder != 0)
  210799. pimpl = new Pimpl (*this, discMaster, discRecorder);
  210800. }
  210801. AudioCDBurner::~AudioCDBurner()
  210802. {
  210803. if (pimpl != 0)
  210804. pimpl.release()->releaseObjects();
  210805. }
  210806. const StringArray AudioCDBurner::findAvailableDevices()
  210807. {
  210808. StringArray devs;
  210809. enumCDBurners (&devs, -1, 0);
  210810. return devs;
  210811. }
  210812. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  210813. {
  210814. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  210815. if (b->pimpl == 0)
  210816. b = 0;
  210817. return b.release();
  210818. }
  210819. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  210820. {
  210821. return pimpl->getDiskState();
  210822. }
  210823. bool AudioCDBurner::isDiskPresent() const
  210824. {
  210825. return getDiskState() == writableDiskPresent;
  210826. }
  210827. bool AudioCDBurner::openTray()
  210828. {
  210829. const Pimpl::ScopedDiscOpener opener (*pimpl);
  210830. return SUCCEEDED (pimpl->discRecorder->Eject());
  210831. }
  210832. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  210833. {
  210834. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  210835. DiskState oldState = getDiskState();
  210836. DiskState newState = oldState;
  210837. while (newState == oldState && Time::currentTimeMillis() < timeout)
  210838. {
  210839. newState = getDiskState();
  210840. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  210841. }
  210842. return newState;
  210843. }
  210844. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  210845. {
  210846. Array<int> results;
  210847. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  210848. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  210849. for (int i = 0; i < numElementsInArray (speeds); ++i)
  210850. if (speeds[i] <= maxSpeed)
  210851. results.add (speeds[i]);
  210852. results.addIfNotAlreadyThere (maxSpeed);
  210853. return results;
  210854. }
  210855. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  210856. {
  210857. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  210858. return false;
  210859. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  210860. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  210861. }
  210862. int AudioCDBurner::getNumAvailableAudioBlocks() const
  210863. {
  210864. long blocksFree = 0;
  210865. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  210866. return blocksFree;
  210867. }
  210868. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  210869. bool performFakeBurnForTesting, int writeSpeed)
  210870. {
  210871. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  210872. pimpl->listener = listener;
  210873. pimpl->progress = 0;
  210874. pimpl->shouldCancel = false;
  210875. UINT_PTR cookie;
  210876. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  210877. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  210878. ejectDiscAfterwards);
  210879. String error;
  210880. if (hr != S_OK)
  210881. {
  210882. const char* e = "Couldn't open or write to the CD device";
  210883. if (hr == IMAPI_E_USERABORT)
  210884. e = "User cancelled the write operation";
  210885. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  210886. e = "No Disk present";
  210887. error = e;
  210888. }
  210889. pimpl->discMaster->ProgressUnadvise (cookie);
  210890. pimpl->listener = 0;
  210891. return error;
  210892. }
  210893. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  210894. {
  210895. if (audioSource == 0)
  210896. return false;
  210897. ScopedPointer<AudioSource> source (audioSource);
  210898. long bytesPerBlock;
  210899. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  210900. const int samplesPerBlock = bytesPerBlock / 4;
  210901. bool ok = true;
  210902. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  210903. HeapBlock <byte> buffer (bytesPerBlock);
  210904. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  210905. int samplesDone = 0;
  210906. source->prepareToPlay (samplesPerBlock, 44100.0);
  210907. while (ok)
  210908. {
  210909. {
  210910. AudioSourceChannelInfo info;
  210911. info.buffer = &sourceBuffer;
  210912. info.numSamples = samplesPerBlock;
  210913. info.startSample = 0;
  210914. sourceBuffer.clear();
  210915. source->getNextAudioBlock (info);
  210916. }
  210917. zeromem (buffer, bytesPerBlock);
  210918. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  210919. buffer, samplesPerBlock, 4);
  210920. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  210921. buffer + 2, samplesPerBlock, 4);
  210922. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  210923. if (FAILED (hr))
  210924. ok = false;
  210925. samplesDone += samplesPerBlock;
  210926. if (samplesDone >= numSamples)
  210927. break;
  210928. }
  210929. hr = pimpl->redbook->CloseAudioTrack();
  210930. return ok && hr == S_OK;
  210931. }
  210932. #endif
  210933. #endif
  210934. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  210935. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  210936. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210937. // compiled on its own).
  210938. #if JUCE_INCLUDED_FILE
  210939. using ::free;
  210940. namespace MidiConstants
  210941. {
  210942. static const int midiBufferSize = 1024 * 10;
  210943. static const int numInHeaders = 32;
  210944. static const int inBufferSize = 256;
  210945. }
  210946. class MidiInThread : public Thread
  210947. {
  210948. public:
  210949. MidiInThread (MidiInput* const input_,
  210950. MidiInputCallback* const callback_)
  210951. : Thread ("Juce Midi"),
  210952. hIn (0),
  210953. input (input_),
  210954. callback (callback_),
  210955. isStarted (false),
  210956. startTime (0),
  210957. pendingLength(0)
  210958. {
  210959. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  210960. {
  210961. zeromem (&hdr[i], sizeof (MIDIHDR));
  210962. hdr[i].lpData = inData[i];
  210963. hdr[i].dwBufferLength = MidiConstants::inBufferSize;
  210964. }
  210965. };
  210966. ~MidiInThread()
  210967. {
  210968. stop();
  210969. if (hIn != 0)
  210970. {
  210971. int count = 5;
  210972. while (--count >= 0)
  210973. {
  210974. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  210975. break;
  210976. Sleep (20);
  210977. }
  210978. }
  210979. }
  210980. void handle (const uint32 message, const uint32 timeStamp)
  210981. {
  210982. const int byte = message & 0xff;
  210983. if (byte < 0x80)
  210984. return;
  210985. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  210986. const double time = timeStampToTime (timeStamp);
  210987. {
  210988. const ScopedLock sl (lock);
  210989. if (pendingLength < MidiConstants::midiBufferSize - 12)
  210990. {
  210991. char* const p = pending + pendingLength;
  210992. *(double*) p = time;
  210993. *(uint32*) (p + 8) = numBytes;
  210994. *(uint32*) (p + 12) = message;
  210995. pendingLength += 12 + numBytes;
  210996. }
  210997. else
  210998. {
  210999. jassertfalse; // midi buffer overflow! You might need to increase the size..
  211000. }
  211001. }
  211002. notify();
  211003. }
  211004. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  211005. {
  211006. const int num = hdr->dwBytesRecorded;
  211007. if (num > 0)
  211008. {
  211009. const double time = timeStampToTime (timeStamp);
  211010. {
  211011. const ScopedLock sl (lock);
  211012. if (pendingLength < MidiConstants::midiBufferSize - (8 + num))
  211013. {
  211014. char* const p = pending + pendingLength;
  211015. *(double*) p = time;
  211016. *(uint32*) (p + 8) = num;
  211017. memcpy (p + 12, hdr->lpData, num);
  211018. pendingLength += 12 + num;
  211019. }
  211020. else
  211021. {
  211022. jassertfalse; // midi buffer overflow! You might need to increase the size..
  211023. }
  211024. }
  211025. notify();
  211026. }
  211027. }
  211028. void writeBlock (const int i)
  211029. {
  211030. hdr[i].dwBytesRecorded = 0;
  211031. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  211032. jassert (res == MMSYSERR_NOERROR);
  211033. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  211034. jassert (res == MMSYSERR_NOERROR);
  211035. }
  211036. void run()
  211037. {
  211038. MemoryBlock pendingCopy (64);
  211039. while (! threadShouldExit())
  211040. {
  211041. for (int i = 0; i < MidiConstants::numInHeaders; ++i)
  211042. {
  211043. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  211044. {
  211045. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  211046. (void) res;
  211047. jassert (res == MMSYSERR_NOERROR);
  211048. writeBlock (i);
  211049. }
  211050. }
  211051. int len;
  211052. {
  211053. const ScopedLock sl (lock);
  211054. len = pendingLength;
  211055. if (len > 0)
  211056. {
  211057. pendingCopy.ensureSize (len);
  211058. pendingCopy.copyFrom (pending, 0, len);
  211059. pendingLength = 0;
  211060. }
  211061. }
  211062. //xxx needs to figure out if blocks are broken up or not
  211063. if (len == 0)
  211064. {
  211065. wait (500);
  211066. }
  211067. else
  211068. {
  211069. const char* p = (const char*) pendingCopy.getData();
  211070. while (len > 0)
  211071. {
  211072. const double time = *(const double*) p;
  211073. const int messageLen = *(const int*) (p + 8);
  211074. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  211075. callback->handleIncomingMidiMessage (input, message);
  211076. p += 12 + messageLen;
  211077. len -= 12 + messageLen;
  211078. }
  211079. }
  211080. }
  211081. }
  211082. void start()
  211083. {
  211084. jassert (hIn != 0);
  211085. if (hIn != 0 && ! isStarted)
  211086. {
  211087. stop();
  211088. activeMidiThreads.addIfNotAlreadyThere (this);
  211089. int i;
  211090. for (i = 0; i < MidiConstants::numInHeaders; ++i)
  211091. writeBlock (i);
  211092. startTime = Time::getMillisecondCounter();
  211093. MMRESULT res = midiInStart (hIn);
  211094. jassert (res == MMSYSERR_NOERROR);
  211095. if (res == MMSYSERR_NOERROR)
  211096. {
  211097. isStarted = true;
  211098. pendingLength = 0;
  211099. startThread (6);
  211100. }
  211101. }
  211102. }
  211103. void stop()
  211104. {
  211105. if (isStarted)
  211106. {
  211107. stopThread (5000);
  211108. midiInReset (hIn);
  211109. midiInStop (hIn);
  211110. activeMidiThreads.removeValue (this);
  211111. { const ScopedLock sl (lock); }
  211112. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  211113. {
  211114. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  211115. {
  211116. int c = 10;
  211117. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  211118. Sleep (20);
  211119. jassert (c >= 0);
  211120. }
  211121. }
  211122. isStarted = false;
  211123. pendingLength = 0;
  211124. }
  211125. }
  211126. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  211127. {
  211128. MidiInThread* const thread = reinterpret_cast <MidiInThread*> (dwInstance);
  211129. if (thread != 0 && activeMidiThreads.contains (thread))
  211130. {
  211131. if (uMsg == MIM_DATA)
  211132. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  211133. else if (uMsg == MIM_LONGDATA)
  211134. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  211135. }
  211136. }
  211137. juce_UseDebuggingNewOperator
  211138. HMIDIIN hIn;
  211139. private:
  211140. static Array <void*, CriticalSection> activeMidiThreads;
  211141. MidiInput* input;
  211142. MidiInputCallback* callback;
  211143. bool isStarted;
  211144. uint32 startTime;
  211145. CriticalSection lock;
  211146. MIDIHDR hdr [MidiConstants::numInHeaders];
  211147. char inData [MidiConstants::numInHeaders] [MidiConstants::inBufferSize];
  211148. int pendingLength;
  211149. char pending [MidiConstants::midiBufferSize];
  211150. double timeStampToTime (uint32 timeStamp)
  211151. {
  211152. timeStamp += startTime;
  211153. const uint32 now = Time::getMillisecondCounter();
  211154. if (timeStamp > now)
  211155. {
  211156. if (timeStamp > now + 2)
  211157. --startTime;
  211158. timeStamp = now;
  211159. }
  211160. return 0.001 * timeStamp;
  211161. }
  211162. MidiInThread (const MidiInThread&);
  211163. MidiInThread& operator= (const MidiInThread&);
  211164. };
  211165. Array <void*, CriticalSection> MidiInThread::activeMidiThreads;
  211166. const StringArray MidiInput::getDevices()
  211167. {
  211168. StringArray s;
  211169. const int num = midiInGetNumDevs();
  211170. for (int i = 0; i < num; ++i)
  211171. {
  211172. MIDIINCAPS mc;
  211173. zerostruct (mc);
  211174. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211175. s.add (String (mc.szPname, sizeof (mc.szPname)));
  211176. }
  211177. return s;
  211178. }
  211179. int MidiInput::getDefaultDeviceIndex()
  211180. {
  211181. return 0;
  211182. }
  211183. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  211184. {
  211185. if (callback == 0)
  211186. return 0;
  211187. UINT deviceId = MIDI_MAPPER;
  211188. int n = 0;
  211189. String name;
  211190. const int num = midiInGetNumDevs();
  211191. for (int i = 0; i < num; ++i)
  211192. {
  211193. MIDIINCAPS mc;
  211194. zerostruct (mc);
  211195. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211196. {
  211197. if (index == n)
  211198. {
  211199. deviceId = i;
  211200. name = String (mc.szPname, sizeof (mc.szPname));
  211201. break;
  211202. }
  211203. ++n;
  211204. }
  211205. }
  211206. ScopedPointer <MidiInput> in (new MidiInput (name));
  211207. ScopedPointer <MidiInThread> thread (new MidiInThread (in, callback));
  211208. HMIDIIN h;
  211209. HRESULT err = midiInOpen (&h, deviceId,
  211210. (DWORD_PTR) &MidiInThread::midiInCallback,
  211211. (DWORD_PTR) (MidiInThread*) thread,
  211212. CALLBACK_FUNCTION);
  211213. if (err == MMSYSERR_NOERROR)
  211214. {
  211215. thread->hIn = h;
  211216. in->internal = thread.release();
  211217. return in.release();
  211218. }
  211219. return 0;
  211220. }
  211221. MidiInput::MidiInput (const String& name_)
  211222. : name (name_),
  211223. internal (0)
  211224. {
  211225. }
  211226. MidiInput::~MidiInput()
  211227. {
  211228. delete static_cast <MidiInThread*> (internal);
  211229. }
  211230. void MidiInput::start()
  211231. {
  211232. static_cast <MidiInThread*> (internal)->start();
  211233. }
  211234. void MidiInput::stop()
  211235. {
  211236. static_cast <MidiInThread*> (internal)->stop();
  211237. }
  211238. struct MidiOutHandle
  211239. {
  211240. int refCount;
  211241. UINT deviceId;
  211242. HMIDIOUT handle;
  211243. static Array<MidiOutHandle*> activeHandles;
  211244. juce_UseDebuggingNewOperator
  211245. };
  211246. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  211247. const StringArray MidiOutput::getDevices()
  211248. {
  211249. StringArray s;
  211250. const int num = midiOutGetNumDevs();
  211251. for (int i = 0; i < num; ++i)
  211252. {
  211253. MIDIOUTCAPS mc;
  211254. zerostruct (mc);
  211255. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211256. s.add (String (mc.szPname, sizeof (mc.szPname)));
  211257. }
  211258. return s;
  211259. }
  211260. int MidiOutput::getDefaultDeviceIndex()
  211261. {
  211262. const int num = midiOutGetNumDevs();
  211263. int n = 0;
  211264. for (int i = 0; i < num; ++i)
  211265. {
  211266. MIDIOUTCAPS mc;
  211267. zerostruct (mc);
  211268. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211269. {
  211270. if ((mc.wTechnology & MOD_MAPPER) != 0)
  211271. return n;
  211272. ++n;
  211273. }
  211274. }
  211275. return 0;
  211276. }
  211277. MidiOutput* MidiOutput::openDevice (int index)
  211278. {
  211279. UINT deviceId = MIDI_MAPPER;
  211280. const int num = midiOutGetNumDevs();
  211281. int i, n = 0;
  211282. for (i = 0; i < num; ++i)
  211283. {
  211284. MIDIOUTCAPS mc;
  211285. zerostruct (mc);
  211286. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211287. {
  211288. // use the microsoft sw synth as a default - best not to allow deviceId
  211289. // to be MIDI_MAPPER, or else device sharing breaks
  211290. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  211291. deviceId = i;
  211292. if (index == n)
  211293. {
  211294. deviceId = i;
  211295. break;
  211296. }
  211297. ++n;
  211298. }
  211299. }
  211300. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  211301. {
  211302. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  211303. if (han != 0 && han->deviceId == deviceId)
  211304. {
  211305. han->refCount++;
  211306. MidiOutput* const out = new MidiOutput();
  211307. out->internal = han;
  211308. return out;
  211309. }
  211310. }
  211311. for (i = 4; --i >= 0;)
  211312. {
  211313. HMIDIOUT h = 0;
  211314. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  211315. if (res == MMSYSERR_NOERROR)
  211316. {
  211317. MidiOutHandle* const han = new MidiOutHandle();
  211318. han->deviceId = deviceId;
  211319. han->refCount = 1;
  211320. han->handle = h;
  211321. MidiOutHandle::activeHandles.add (han);
  211322. MidiOutput* const out = new MidiOutput();
  211323. out->internal = han;
  211324. return out;
  211325. }
  211326. else if (res == MMSYSERR_ALLOCATED)
  211327. {
  211328. Sleep (100);
  211329. }
  211330. else
  211331. {
  211332. break;
  211333. }
  211334. }
  211335. return 0;
  211336. }
  211337. MidiOutput::~MidiOutput()
  211338. {
  211339. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  211340. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  211341. {
  211342. midiOutClose (h->handle);
  211343. MidiOutHandle::activeHandles.removeValue (h);
  211344. delete h;
  211345. }
  211346. }
  211347. void MidiOutput::reset()
  211348. {
  211349. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  211350. midiOutReset (h->handle);
  211351. }
  211352. bool MidiOutput::getVolume (float& leftVol,
  211353. float& rightVol)
  211354. {
  211355. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211356. DWORD n;
  211357. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  211358. {
  211359. const unsigned short* const nn = (const unsigned short*) &n;
  211360. rightVol = nn[0] / (float) 0xffff;
  211361. leftVol = nn[1] / (float) 0xffff;
  211362. return true;
  211363. }
  211364. else
  211365. {
  211366. rightVol = leftVol = 1.0f;
  211367. return false;
  211368. }
  211369. }
  211370. void MidiOutput::setVolume (float leftVol,
  211371. float rightVol)
  211372. {
  211373. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  211374. DWORD n;
  211375. unsigned short* const nn = (unsigned short*) &n;
  211376. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  211377. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  211378. midiOutSetVolume (handle->handle, n);
  211379. }
  211380. void MidiOutput::sendMessageNow (const MidiMessage& message)
  211381. {
  211382. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211383. if (message.getRawDataSize() > 3
  211384. || message.isSysEx())
  211385. {
  211386. MIDIHDR h;
  211387. zerostruct (h);
  211388. h.lpData = (char*) message.getRawData();
  211389. h.dwBufferLength = message.getRawDataSize();
  211390. h.dwBytesRecorded = message.getRawDataSize();
  211391. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  211392. {
  211393. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  211394. if (res == MMSYSERR_NOERROR)
  211395. {
  211396. while ((h.dwFlags & MHDR_DONE) == 0)
  211397. Sleep (1);
  211398. int count = 500; // 1 sec timeout
  211399. while (--count >= 0)
  211400. {
  211401. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  211402. if (res == MIDIERR_STILLPLAYING)
  211403. Sleep (2);
  211404. else
  211405. break;
  211406. }
  211407. }
  211408. }
  211409. }
  211410. else
  211411. {
  211412. midiOutShortMsg (handle->handle,
  211413. *(unsigned int*) message.getRawData());
  211414. }
  211415. }
  211416. #endif
  211417. /*** End of inlined file: juce_win32_Midi.cpp ***/
  211418. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  211419. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211420. // compiled on its own).
  211421. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  211422. #undef WINDOWS
  211423. // #define ASIO_DEBUGGING
  211424. #ifdef ASIO_DEBUGGING
  211425. #define log(a) { Logger::writeToLog (a); DBG (a) }
  211426. #else
  211427. #define log(a) {}
  211428. #endif
  211429. #ifdef ASIO_DEBUGGING
  211430. static void logError (const String& context, long error)
  211431. {
  211432. String err ("unknown error");
  211433. if (error == ASE_NotPresent)
  211434. err = "Not Present";
  211435. else if (error == ASE_HWMalfunction)
  211436. err = "Hardware Malfunction";
  211437. else if (error == ASE_InvalidParameter)
  211438. err = "Invalid Parameter";
  211439. else if (error == ASE_InvalidMode)
  211440. err = "Invalid Mode";
  211441. else if (error == ASE_SPNotAdvancing)
  211442. err = "Sample position not advancing";
  211443. else if (error == ASE_NoClock)
  211444. err = "No Clock";
  211445. else if (error == ASE_NoMemory)
  211446. err = "Out of memory";
  211447. log ("!!error: " + context + " - " + err);
  211448. }
  211449. #else
  211450. #define logError(a, b) {}
  211451. #endif
  211452. class ASIOAudioIODevice;
  211453. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  211454. static const int maxASIOChannels = 160;
  211455. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  211456. private Timer
  211457. {
  211458. public:
  211459. Component ourWindow;
  211460. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  211461. const String& optionalDllForDirectLoading_)
  211462. : AudioIODevice (name_, "ASIO"),
  211463. asioObject (0),
  211464. classId (classId_),
  211465. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  211466. currentBitDepth (16),
  211467. currentSampleRate (0),
  211468. isOpen_ (false),
  211469. isStarted (false),
  211470. postOutput (true),
  211471. insideControlPanelModalLoop (false),
  211472. shouldUsePreferredSize (false)
  211473. {
  211474. name = name_;
  211475. ourWindow.addToDesktop (0);
  211476. windowHandle = ourWindow.getWindowHandle();
  211477. jassert (currentASIODev [slotNumber] == 0);
  211478. currentASIODev [slotNumber] = this;
  211479. openDevice();
  211480. }
  211481. ~ASIOAudioIODevice()
  211482. {
  211483. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  211484. if (currentASIODev[i] == this)
  211485. currentASIODev[i] = 0;
  211486. close();
  211487. log ("ASIO - exiting");
  211488. removeCurrentDriver();
  211489. }
  211490. void updateSampleRates()
  211491. {
  211492. // find a list of sample rates..
  211493. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  211494. sampleRates.clear();
  211495. if (asioObject != 0)
  211496. {
  211497. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  211498. {
  211499. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  211500. if (err == 0)
  211501. {
  211502. sampleRates.add ((int) possibleSampleRates[index]);
  211503. log ("rate: " + String ((int) possibleSampleRates[index]));
  211504. }
  211505. else if (err != ASE_NoClock)
  211506. {
  211507. logError ("CanSampleRate", err);
  211508. }
  211509. }
  211510. if (sampleRates.size() == 0)
  211511. {
  211512. double cr = 0;
  211513. const long err = asioObject->getSampleRate (&cr);
  211514. log ("No sample rates supported - current rate: " + String ((int) cr));
  211515. if (err == 0)
  211516. sampleRates.add ((int) cr);
  211517. }
  211518. }
  211519. }
  211520. const StringArray getOutputChannelNames()
  211521. {
  211522. return outputChannelNames;
  211523. }
  211524. const StringArray getInputChannelNames()
  211525. {
  211526. return inputChannelNames;
  211527. }
  211528. int getNumSampleRates()
  211529. {
  211530. return sampleRates.size();
  211531. }
  211532. double getSampleRate (int index)
  211533. {
  211534. return sampleRates [index];
  211535. }
  211536. int getNumBufferSizesAvailable()
  211537. {
  211538. return bufferSizes.size();
  211539. }
  211540. int getBufferSizeSamples (int index)
  211541. {
  211542. return bufferSizes [index];
  211543. }
  211544. int getDefaultBufferSize()
  211545. {
  211546. return preferredSize;
  211547. }
  211548. const String open (const BigInteger& inputChannels,
  211549. const BigInteger& outputChannels,
  211550. double sr,
  211551. int bufferSizeSamples)
  211552. {
  211553. close();
  211554. currentCallback = 0;
  211555. if (bufferSizeSamples <= 0)
  211556. shouldUsePreferredSize = true;
  211557. if (asioObject == 0 || ! isASIOOpen)
  211558. {
  211559. log ("Warning: device not open");
  211560. const String err (openDevice());
  211561. if (asioObject == 0 || ! isASIOOpen)
  211562. return err;
  211563. }
  211564. isStarted = false;
  211565. bufferIndex = -1;
  211566. long err = 0;
  211567. long newPreferredSize = 0;
  211568. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  211569. minSize = 0;
  211570. maxSize = 0;
  211571. newPreferredSize = 0;
  211572. granularity = 0;
  211573. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  211574. {
  211575. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  211576. shouldUsePreferredSize = true;
  211577. preferredSize = newPreferredSize;
  211578. }
  211579. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  211580. // dynamic changes to the buffer size...
  211581. shouldUsePreferredSize = shouldUsePreferredSize
  211582. || getName().containsIgnoreCase ("Digidesign");
  211583. if (shouldUsePreferredSize)
  211584. {
  211585. log ("Using preferred size for buffer..");
  211586. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  211587. {
  211588. bufferSizeSamples = preferredSize;
  211589. }
  211590. else
  211591. {
  211592. bufferSizeSamples = 1024;
  211593. logError ("GetBufferSize1", err);
  211594. }
  211595. shouldUsePreferredSize = false;
  211596. }
  211597. int sampleRate = roundDoubleToInt (sr);
  211598. currentSampleRate = sampleRate;
  211599. currentBlockSizeSamples = bufferSizeSamples;
  211600. currentChansOut.clear();
  211601. currentChansIn.clear();
  211602. zeromem (inBuffers, sizeof (inBuffers));
  211603. zeromem (outBuffers, sizeof (outBuffers));
  211604. updateSampleRates();
  211605. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  211606. sampleRate = sampleRates[0];
  211607. jassert (sampleRate != 0);
  211608. if (sampleRate == 0)
  211609. sampleRate = 44100;
  211610. long numSources = 32;
  211611. ASIOClockSource clocks[32];
  211612. zeromem (clocks, sizeof (clocks));
  211613. asioObject->getClockSources (clocks, &numSources);
  211614. bool isSourceSet = false;
  211615. // careful not to remove this loop because it does more than just logging!
  211616. int i;
  211617. for (i = 0; i < numSources; ++i)
  211618. {
  211619. String s ("clock: ");
  211620. s += clocks[i].name;
  211621. if (clocks[i].isCurrentSource)
  211622. {
  211623. isSourceSet = true;
  211624. s << " (cur)";
  211625. }
  211626. log (s);
  211627. }
  211628. if (numSources > 1 && ! isSourceSet)
  211629. {
  211630. log ("setting clock source");
  211631. asioObject->setClockSource (clocks[0].index);
  211632. Thread::sleep (20);
  211633. }
  211634. else
  211635. {
  211636. if (numSources == 0)
  211637. {
  211638. log ("ASIO - no clock sources!");
  211639. }
  211640. }
  211641. double cr = 0;
  211642. err = asioObject->getSampleRate (&cr);
  211643. if (err == 0)
  211644. {
  211645. currentSampleRate = cr;
  211646. }
  211647. else
  211648. {
  211649. logError ("GetSampleRate", err);
  211650. currentSampleRate = 0;
  211651. }
  211652. error = String::empty;
  211653. needToReset = false;
  211654. isReSync = false;
  211655. err = 0;
  211656. bool buffersCreated = false;
  211657. if (currentSampleRate != sampleRate)
  211658. {
  211659. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  211660. err = asioObject->setSampleRate (sampleRate);
  211661. if (err == ASE_NoClock && numSources > 0)
  211662. {
  211663. log ("trying to set a clock source..");
  211664. Thread::sleep (10);
  211665. err = asioObject->setClockSource (clocks[0].index);
  211666. if (err != 0)
  211667. {
  211668. logError ("SetClock", err);
  211669. }
  211670. Thread::sleep (10);
  211671. err = asioObject->setSampleRate (sampleRate);
  211672. }
  211673. }
  211674. if (err == 0)
  211675. {
  211676. currentSampleRate = sampleRate;
  211677. if (needToReset)
  211678. {
  211679. if (isReSync)
  211680. {
  211681. log ("Resync request");
  211682. }
  211683. log ("! Resetting ASIO after sample rate change");
  211684. removeCurrentDriver();
  211685. loadDriver();
  211686. const String error (initDriver());
  211687. if (error.isNotEmpty())
  211688. {
  211689. log ("ASIOInit: " + error);
  211690. }
  211691. needToReset = false;
  211692. isReSync = false;
  211693. }
  211694. numActiveInputChans = 0;
  211695. numActiveOutputChans = 0;
  211696. ASIOBufferInfo* info = bufferInfos;
  211697. int i;
  211698. for (i = 0; i < totalNumInputChans; ++i)
  211699. {
  211700. if (inputChannels[i])
  211701. {
  211702. currentChansIn.setBit (i);
  211703. info->isInput = 1;
  211704. info->channelNum = i;
  211705. info->buffers[0] = info->buffers[1] = 0;
  211706. ++info;
  211707. ++numActiveInputChans;
  211708. }
  211709. }
  211710. for (i = 0; i < totalNumOutputChans; ++i)
  211711. {
  211712. if (outputChannels[i])
  211713. {
  211714. currentChansOut.setBit (i);
  211715. info->isInput = 0;
  211716. info->channelNum = i;
  211717. info->buffers[0] = info->buffers[1] = 0;
  211718. ++info;
  211719. ++numActiveOutputChans;
  211720. }
  211721. }
  211722. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  211723. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  211724. if (currentASIODev[0] == this)
  211725. {
  211726. callbacks.bufferSwitch = &bufferSwitchCallback0;
  211727. callbacks.asioMessage = &asioMessagesCallback0;
  211728. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  211729. }
  211730. else if (currentASIODev[1] == this)
  211731. {
  211732. callbacks.bufferSwitch = &bufferSwitchCallback1;
  211733. callbacks.asioMessage = &asioMessagesCallback1;
  211734. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  211735. }
  211736. else if (currentASIODev[2] == this)
  211737. {
  211738. callbacks.bufferSwitch = &bufferSwitchCallback2;
  211739. callbacks.asioMessage = &asioMessagesCallback2;
  211740. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  211741. }
  211742. else
  211743. {
  211744. jassertfalse;
  211745. }
  211746. log ("disposing buffers");
  211747. err = asioObject->disposeBuffers();
  211748. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  211749. err = asioObject->createBuffers (bufferInfos,
  211750. totalBuffers,
  211751. currentBlockSizeSamples,
  211752. &callbacks);
  211753. if (err != 0)
  211754. {
  211755. currentBlockSizeSamples = preferredSize;
  211756. logError ("create buffers 2", err);
  211757. asioObject->disposeBuffers();
  211758. err = asioObject->createBuffers (bufferInfos,
  211759. totalBuffers,
  211760. currentBlockSizeSamples,
  211761. &callbacks);
  211762. }
  211763. if (err == 0)
  211764. {
  211765. buffersCreated = true;
  211766. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  211767. int n = 0;
  211768. Array <int> types;
  211769. currentBitDepth = 16;
  211770. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  211771. {
  211772. if (inputChannels[i])
  211773. {
  211774. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  211775. ASIOChannelInfo channelInfo;
  211776. zerostruct (channelInfo);
  211777. channelInfo.channel = i;
  211778. channelInfo.isInput = 1;
  211779. asioObject->getChannelInfo (&channelInfo);
  211780. types.addIfNotAlreadyThere (channelInfo.type);
  211781. typeToFormatParameters (channelInfo.type,
  211782. inputChannelBitDepths[n],
  211783. inputChannelBytesPerSample[n],
  211784. inputChannelIsFloat[n],
  211785. inputChannelLittleEndian[n]);
  211786. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  211787. ++n;
  211788. }
  211789. }
  211790. jassert (numActiveInputChans == n);
  211791. n = 0;
  211792. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  211793. {
  211794. if (outputChannels[i])
  211795. {
  211796. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  211797. ASIOChannelInfo channelInfo;
  211798. zerostruct (channelInfo);
  211799. channelInfo.channel = i;
  211800. channelInfo.isInput = 0;
  211801. asioObject->getChannelInfo (&channelInfo);
  211802. types.addIfNotAlreadyThere (channelInfo.type);
  211803. typeToFormatParameters (channelInfo.type,
  211804. outputChannelBitDepths[n],
  211805. outputChannelBytesPerSample[n],
  211806. outputChannelIsFloat[n],
  211807. outputChannelLittleEndian[n]);
  211808. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  211809. ++n;
  211810. }
  211811. }
  211812. jassert (numActiveOutputChans == n);
  211813. for (i = types.size(); --i >= 0;)
  211814. {
  211815. log ("channel format: " + String (types[i]));
  211816. }
  211817. jassert (n <= totalBuffers);
  211818. for (i = 0; i < numActiveOutputChans; ++i)
  211819. {
  211820. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  211821. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  211822. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  211823. {
  211824. log ("!! Null buffers");
  211825. }
  211826. else
  211827. {
  211828. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  211829. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  211830. }
  211831. }
  211832. inputLatency = outputLatency = 0;
  211833. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  211834. {
  211835. log ("ASIO - no latencies");
  211836. }
  211837. else
  211838. {
  211839. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  211840. }
  211841. isOpen_ = true;
  211842. log ("starting ASIO");
  211843. calledback = false;
  211844. err = asioObject->start();
  211845. if (err != 0)
  211846. {
  211847. isOpen_ = false;
  211848. log ("ASIO - stop on failure");
  211849. Thread::sleep (10);
  211850. asioObject->stop();
  211851. error = "Can't start device";
  211852. Thread::sleep (10);
  211853. }
  211854. else
  211855. {
  211856. int count = 300;
  211857. while (--count > 0 && ! calledback)
  211858. Thread::sleep (10);
  211859. isStarted = true;
  211860. if (! calledback)
  211861. {
  211862. error = "Device didn't start correctly";
  211863. log ("ASIO didn't callback - stopping..");
  211864. asioObject->stop();
  211865. }
  211866. }
  211867. }
  211868. else
  211869. {
  211870. error = "Can't create i/o buffers";
  211871. }
  211872. }
  211873. else
  211874. {
  211875. error = "Can't set sample rate: ";
  211876. error << sampleRate;
  211877. }
  211878. if (error.isNotEmpty())
  211879. {
  211880. logError (error, err);
  211881. if (asioObject != 0 && buffersCreated)
  211882. asioObject->disposeBuffers();
  211883. Thread::sleep (20);
  211884. isStarted = false;
  211885. isOpen_ = false;
  211886. const String errorCopy (error);
  211887. close(); // (this resets the error string)
  211888. error = errorCopy;
  211889. }
  211890. needToReset = false;
  211891. isReSync = false;
  211892. return error;
  211893. }
  211894. void close()
  211895. {
  211896. error = String::empty;
  211897. stopTimer();
  211898. stop();
  211899. if (isASIOOpen && isOpen_)
  211900. {
  211901. const ScopedLock sl (callbackLock);
  211902. isOpen_ = false;
  211903. isStarted = false;
  211904. needToReset = false;
  211905. isReSync = false;
  211906. log ("ASIO - stopping");
  211907. if (asioObject != 0)
  211908. {
  211909. Thread::sleep (20);
  211910. asioObject->stop();
  211911. Thread::sleep (10);
  211912. asioObject->disposeBuffers();
  211913. }
  211914. Thread::sleep (10);
  211915. }
  211916. }
  211917. bool isOpen()
  211918. {
  211919. return isOpen_ || insideControlPanelModalLoop;
  211920. }
  211921. int getCurrentBufferSizeSamples()
  211922. {
  211923. return currentBlockSizeSamples;
  211924. }
  211925. double getCurrentSampleRate()
  211926. {
  211927. return currentSampleRate;
  211928. }
  211929. const BigInteger getActiveOutputChannels() const
  211930. {
  211931. return currentChansOut;
  211932. }
  211933. const BigInteger getActiveInputChannels() const
  211934. {
  211935. return currentChansIn;
  211936. }
  211937. int getCurrentBitDepth()
  211938. {
  211939. return currentBitDepth;
  211940. }
  211941. int getOutputLatencyInSamples()
  211942. {
  211943. return outputLatency + currentBlockSizeSamples / 4;
  211944. }
  211945. int getInputLatencyInSamples()
  211946. {
  211947. return inputLatency + currentBlockSizeSamples / 4;
  211948. }
  211949. void start (AudioIODeviceCallback* callback)
  211950. {
  211951. if (callback != 0)
  211952. {
  211953. callback->audioDeviceAboutToStart (this);
  211954. const ScopedLock sl (callbackLock);
  211955. currentCallback = callback;
  211956. }
  211957. }
  211958. void stop()
  211959. {
  211960. AudioIODeviceCallback* const lastCallback = currentCallback;
  211961. {
  211962. const ScopedLock sl (callbackLock);
  211963. currentCallback = 0;
  211964. }
  211965. if (lastCallback != 0)
  211966. lastCallback->audioDeviceStopped();
  211967. }
  211968. bool isPlaying()
  211969. {
  211970. return isASIOOpen && (currentCallback != 0);
  211971. }
  211972. const String getLastError()
  211973. {
  211974. return error;
  211975. }
  211976. bool hasControlPanel() const
  211977. {
  211978. return true;
  211979. }
  211980. bool showControlPanel()
  211981. {
  211982. log ("ASIO - showing control panel");
  211983. Component modalWindow (String::empty);
  211984. modalWindow.setOpaque (true);
  211985. modalWindow.addToDesktop (0);
  211986. modalWindow.enterModalState();
  211987. bool done = false;
  211988. JUCE_TRY
  211989. {
  211990. // are there are devices that need to be closed before showing their control panel?
  211991. // close();
  211992. insideControlPanelModalLoop = true;
  211993. const uint32 started = Time::getMillisecondCounter();
  211994. if (asioObject != 0)
  211995. {
  211996. asioObject->controlPanel();
  211997. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  211998. log ("spent: " + String (spent));
  211999. if (spent > 300)
  212000. {
  212001. shouldUsePreferredSize = true;
  212002. done = true;
  212003. }
  212004. }
  212005. }
  212006. JUCE_CATCH_ALL
  212007. insideControlPanelModalLoop = false;
  212008. return done;
  212009. }
  212010. void resetRequest() throw()
  212011. {
  212012. needToReset = true;
  212013. }
  212014. void resyncRequest() throw()
  212015. {
  212016. needToReset = true;
  212017. isReSync = true;
  212018. }
  212019. void timerCallback()
  212020. {
  212021. if (! insideControlPanelModalLoop)
  212022. {
  212023. stopTimer();
  212024. // used to cause a reset
  212025. log ("! ASIO restart request!");
  212026. if (isOpen_)
  212027. {
  212028. AudioIODeviceCallback* const oldCallback = currentCallback;
  212029. close();
  212030. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  212031. currentSampleRate, currentBlockSizeSamples);
  212032. if (oldCallback != 0)
  212033. start (oldCallback);
  212034. }
  212035. }
  212036. else
  212037. {
  212038. startTimer (100);
  212039. }
  212040. }
  212041. juce_UseDebuggingNewOperator
  212042. private:
  212043. IASIO* volatile asioObject;
  212044. ASIOCallbacks callbacks;
  212045. void* windowHandle;
  212046. CLSID classId;
  212047. const String optionalDllForDirectLoading;
  212048. String error;
  212049. long totalNumInputChans, totalNumOutputChans;
  212050. StringArray inputChannelNames, outputChannelNames;
  212051. Array<int> sampleRates, bufferSizes;
  212052. long inputLatency, outputLatency;
  212053. long minSize, maxSize, preferredSize, granularity;
  212054. int volatile currentBlockSizeSamples;
  212055. int volatile currentBitDepth;
  212056. double volatile currentSampleRate;
  212057. BigInteger currentChansOut, currentChansIn;
  212058. AudioIODeviceCallback* volatile currentCallback;
  212059. CriticalSection callbackLock;
  212060. ASIOBufferInfo bufferInfos [maxASIOChannels];
  212061. float* inBuffers [maxASIOChannels];
  212062. float* outBuffers [maxASIOChannels];
  212063. int inputChannelBitDepths [maxASIOChannels];
  212064. int outputChannelBitDepths [maxASIOChannels];
  212065. int inputChannelBytesPerSample [maxASIOChannels];
  212066. int outputChannelBytesPerSample [maxASIOChannels];
  212067. bool inputChannelIsFloat [maxASIOChannels];
  212068. bool outputChannelIsFloat [maxASIOChannels];
  212069. bool inputChannelLittleEndian [maxASIOChannels];
  212070. bool outputChannelLittleEndian [maxASIOChannels];
  212071. WaitableEvent event1;
  212072. HeapBlock <float> tempBuffer;
  212073. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  212074. bool isOpen_, isStarted;
  212075. bool volatile isASIOOpen;
  212076. bool volatile calledback;
  212077. bool volatile littleEndian, postOutput, needToReset, isReSync;
  212078. bool volatile insideControlPanelModalLoop;
  212079. bool volatile shouldUsePreferredSize;
  212080. void removeCurrentDriver()
  212081. {
  212082. if (asioObject != 0)
  212083. {
  212084. asioObject->Release();
  212085. asioObject = 0;
  212086. }
  212087. }
  212088. bool loadDriver()
  212089. {
  212090. removeCurrentDriver();
  212091. JUCE_TRY
  212092. {
  212093. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  212094. classId, (void**) &asioObject) == S_OK)
  212095. {
  212096. return true;
  212097. }
  212098. // If a class isn't registered but we have a path for it, we can fallback to
  212099. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  212100. if (optionalDllForDirectLoading.isNotEmpty())
  212101. {
  212102. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  212103. if (h != 0)
  212104. {
  212105. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  212106. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  212107. if (dllGetClassObject != 0)
  212108. {
  212109. IClassFactory* classFactory = 0;
  212110. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  212111. if (classFactory != 0)
  212112. {
  212113. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  212114. classFactory->Release();
  212115. }
  212116. return asioObject != 0;
  212117. }
  212118. }
  212119. }
  212120. }
  212121. JUCE_CATCH_ALL
  212122. asioObject = 0;
  212123. return false;
  212124. }
  212125. const String initDriver()
  212126. {
  212127. if (asioObject != 0)
  212128. {
  212129. char buffer [256];
  212130. zeromem (buffer, sizeof (buffer));
  212131. if (! asioObject->init (windowHandle))
  212132. {
  212133. asioObject->getErrorMessage (buffer);
  212134. return String (buffer, sizeof (buffer) - 1);
  212135. }
  212136. // just in case any daft drivers expect this to be called..
  212137. asioObject->getDriverName (buffer);
  212138. return String::empty;
  212139. }
  212140. return "No Driver";
  212141. }
  212142. const String openDevice()
  212143. {
  212144. // use this in case the driver starts opening dialog boxes..
  212145. Component modalWindow (String::empty);
  212146. modalWindow.setOpaque (true);
  212147. modalWindow.addToDesktop (0);
  212148. modalWindow.enterModalState();
  212149. // open the device and get its info..
  212150. log ("opening ASIO device: " + getName());
  212151. needToReset = false;
  212152. isReSync = false;
  212153. outputChannelNames.clear();
  212154. inputChannelNames.clear();
  212155. bufferSizes.clear();
  212156. sampleRates.clear();
  212157. isASIOOpen = false;
  212158. isOpen_ = false;
  212159. totalNumInputChans = 0;
  212160. totalNumOutputChans = 0;
  212161. numActiveInputChans = 0;
  212162. numActiveOutputChans = 0;
  212163. currentCallback = 0;
  212164. error = String::empty;
  212165. if (getName().isEmpty())
  212166. return error;
  212167. long err = 0;
  212168. if (loadDriver())
  212169. {
  212170. if ((error = initDriver()).isEmpty())
  212171. {
  212172. numActiveInputChans = 0;
  212173. numActiveOutputChans = 0;
  212174. totalNumInputChans = 0;
  212175. totalNumOutputChans = 0;
  212176. if (asioObject != 0
  212177. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  212178. {
  212179. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  212180. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212181. {
  212182. // find a list of buffer sizes..
  212183. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  212184. if (granularity >= 0)
  212185. {
  212186. granularity = jmax (1, (int) granularity);
  212187. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  212188. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  212189. }
  212190. else if (granularity < 0)
  212191. {
  212192. for (int i = 0; i < 18; ++i)
  212193. {
  212194. const int s = (1 << i);
  212195. if (s >= minSize && s <= maxSize)
  212196. bufferSizes.add (s);
  212197. }
  212198. }
  212199. if (! bufferSizes.contains (preferredSize))
  212200. bufferSizes.insert (0, preferredSize);
  212201. double currentRate = 0;
  212202. asioObject->getSampleRate (&currentRate);
  212203. if (currentRate <= 0.0 || currentRate > 192001.0)
  212204. {
  212205. log ("setting sample rate");
  212206. err = asioObject->setSampleRate (44100.0);
  212207. if (err != 0)
  212208. {
  212209. logError ("setting sample rate", err);
  212210. }
  212211. asioObject->getSampleRate (&currentRate);
  212212. }
  212213. currentSampleRate = currentRate;
  212214. postOutput = (asioObject->outputReady() == 0);
  212215. if (postOutput)
  212216. {
  212217. log ("ASIO outputReady = ok");
  212218. }
  212219. updateSampleRates();
  212220. // ..because cubase does it at this point
  212221. inputLatency = outputLatency = 0;
  212222. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212223. {
  212224. log ("ASIO - no latencies");
  212225. }
  212226. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  212227. // create some dummy buffers now.. because cubase does..
  212228. numActiveInputChans = 0;
  212229. numActiveOutputChans = 0;
  212230. ASIOBufferInfo* info = bufferInfos;
  212231. int i, numChans = 0;
  212232. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  212233. {
  212234. info->isInput = 1;
  212235. info->channelNum = i;
  212236. info->buffers[0] = info->buffers[1] = 0;
  212237. ++info;
  212238. ++numChans;
  212239. }
  212240. const int outputBufferIndex = numChans;
  212241. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  212242. {
  212243. info->isInput = 0;
  212244. info->channelNum = i;
  212245. info->buffers[0] = info->buffers[1] = 0;
  212246. ++info;
  212247. ++numChans;
  212248. }
  212249. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212250. if (currentASIODev[0] == this)
  212251. {
  212252. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212253. callbacks.asioMessage = &asioMessagesCallback0;
  212254. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212255. }
  212256. else if (currentASIODev[1] == this)
  212257. {
  212258. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212259. callbacks.asioMessage = &asioMessagesCallback1;
  212260. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212261. }
  212262. else if (currentASIODev[2] == this)
  212263. {
  212264. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212265. callbacks.asioMessage = &asioMessagesCallback2;
  212266. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212267. }
  212268. else
  212269. {
  212270. jassertfalse;
  212271. }
  212272. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  212273. if (preferredSize > 0)
  212274. {
  212275. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  212276. if (err != 0)
  212277. {
  212278. logError ("dummy buffers", err);
  212279. }
  212280. }
  212281. long newInps = 0, newOuts = 0;
  212282. asioObject->getChannels (&newInps, &newOuts);
  212283. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  212284. {
  212285. totalNumInputChans = newInps;
  212286. totalNumOutputChans = newOuts;
  212287. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  212288. }
  212289. updateSampleRates();
  212290. ASIOChannelInfo channelInfo;
  212291. channelInfo.type = 0;
  212292. for (i = 0; i < totalNumInputChans; ++i)
  212293. {
  212294. zerostruct (channelInfo);
  212295. channelInfo.channel = i;
  212296. channelInfo.isInput = 1;
  212297. asioObject->getChannelInfo (&channelInfo);
  212298. inputChannelNames.add (String (channelInfo.name));
  212299. }
  212300. for (i = 0; i < totalNumOutputChans; ++i)
  212301. {
  212302. zerostruct (channelInfo);
  212303. channelInfo.channel = i;
  212304. channelInfo.isInput = 0;
  212305. asioObject->getChannelInfo (&channelInfo);
  212306. outputChannelNames.add (String (channelInfo.name));
  212307. typeToFormatParameters (channelInfo.type,
  212308. outputChannelBitDepths[i],
  212309. outputChannelBytesPerSample[i],
  212310. outputChannelIsFloat[i],
  212311. outputChannelLittleEndian[i]);
  212312. if (i < 2)
  212313. {
  212314. // clear the channels that are used with the dummy stuff
  212315. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  212316. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  212317. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  212318. }
  212319. }
  212320. outputChannelNames.trim();
  212321. inputChannelNames.trim();
  212322. outputChannelNames.appendNumbersToDuplicates (false, true);
  212323. inputChannelNames.appendNumbersToDuplicates (false, true);
  212324. // start and stop because cubase does it..
  212325. asioObject->getLatencies (&inputLatency, &outputLatency);
  212326. if ((err = asioObject->start()) != 0)
  212327. {
  212328. // ignore an error here, as it might start later after setting other stuff up
  212329. logError ("ASIO start", err);
  212330. }
  212331. Thread::sleep (100);
  212332. asioObject->stop();
  212333. }
  212334. else
  212335. {
  212336. error = "Can't detect buffer sizes";
  212337. }
  212338. }
  212339. else
  212340. {
  212341. error = "Can't detect asio channels";
  212342. }
  212343. }
  212344. }
  212345. else
  212346. {
  212347. error = "No such device";
  212348. }
  212349. if (error.isNotEmpty())
  212350. {
  212351. logError (error, err);
  212352. if (asioObject != 0)
  212353. asioObject->disposeBuffers();
  212354. removeCurrentDriver();
  212355. isASIOOpen = false;
  212356. }
  212357. else
  212358. {
  212359. isASIOOpen = true;
  212360. log ("ASIO device open");
  212361. }
  212362. isOpen_ = false;
  212363. needToReset = false;
  212364. isReSync = false;
  212365. return error;
  212366. }
  212367. void callback (const long index)
  212368. {
  212369. if (isStarted)
  212370. {
  212371. bufferIndex = index;
  212372. processBuffer();
  212373. }
  212374. else
  212375. {
  212376. if (postOutput && (asioObject != 0))
  212377. asioObject->outputReady();
  212378. }
  212379. calledback = true;
  212380. }
  212381. void processBuffer()
  212382. {
  212383. const ASIOBufferInfo* const infos = bufferInfos;
  212384. const int bi = bufferIndex;
  212385. const ScopedLock sl (callbackLock);
  212386. if (needToReset)
  212387. {
  212388. needToReset = false;
  212389. if (isReSync)
  212390. {
  212391. log ("! ASIO resync");
  212392. isReSync = false;
  212393. }
  212394. else
  212395. {
  212396. startTimer (20);
  212397. }
  212398. }
  212399. if (bi >= 0)
  212400. {
  212401. const int samps = currentBlockSizeSamples;
  212402. if (currentCallback != 0)
  212403. {
  212404. int i;
  212405. for (i = 0; i < numActiveInputChans; ++i)
  212406. {
  212407. float* const dst = inBuffers[i];
  212408. jassert (dst != 0);
  212409. const char* const src = (const char*) (infos[i].buffers[bi]);
  212410. if (inputChannelIsFloat[i])
  212411. {
  212412. memcpy (dst, src, samps * sizeof (float));
  212413. }
  212414. else
  212415. {
  212416. jassert (dst == tempBuffer + (samps * i));
  212417. switch (inputChannelBitDepths[i])
  212418. {
  212419. case 16:
  212420. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  212421. samps, inputChannelLittleEndian[i]);
  212422. break;
  212423. case 24:
  212424. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  212425. samps, inputChannelLittleEndian[i]);
  212426. break;
  212427. case 32:
  212428. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  212429. samps, inputChannelLittleEndian[i]);
  212430. break;
  212431. case 64:
  212432. jassertfalse;
  212433. break;
  212434. }
  212435. }
  212436. }
  212437. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  212438. numActiveInputChans,
  212439. outBuffers,
  212440. numActiveOutputChans,
  212441. samps);
  212442. for (i = 0; i < numActiveOutputChans; ++i)
  212443. {
  212444. float* const src = outBuffers[i];
  212445. jassert (src != 0);
  212446. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  212447. if (outputChannelIsFloat[i])
  212448. {
  212449. memcpy (dst, src, samps * sizeof (float));
  212450. }
  212451. else
  212452. {
  212453. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  212454. switch (outputChannelBitDepths[i])
  212455. {
  212456. case 16:
  212457. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  212458. samps, outputChannelLittleEndian[i]);
  212459. break;
  212460. case 24:
  212461. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  212462. samps, outputChannelLittleEndian[i]);
  212463. break;
  212464. case 32:
  212465. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  212466. samps, outputChannelLittleEndian[i]);
  212467. break;
  212468. case 64:
  212469. jassertfalse;
  212470. break;
  212471. }
  212472. }
  212473. }
  212474. }
  212475. else
  212476. {
  212477. for (int i = 0; i < numActiveOutputChans; ++i)
  212478. {
  212479. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  212480. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  212481. }
  212482. }
  212483. }
  212484. if (postOutput)
  212485. asioObject->outputReady();
  212486. }
  212487. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  212488. {
  212489. if (currentASIODev[0] != 0)
  212490. currentASIODev[0]->callback (index);
  212491. return 0;
  212492. }
  212493. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  212494. {
  212495. if (currentASIODev[1] != 0)
  212496. currentASIODev[1]->callback (index);
  212497. return 0;
  212498. }
  212499. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  212500. {
  212501. if (currentASIODev[2] != 0)
  212502. currentASIODev[2]->callback (index);
  212503. return 0;
  212504. }
  212505. static void bufferSwitchCallback0 (long index, long)
  212506. {
  212507. if (currentASIODev[0] != 0)
  212508. currentASIODev[0]->callback (index);
  212509. }
  212510. static void bufferSwitchCallback1 (long index, long)
  212511. {
  212512. if (currentASIODev[1] != 0)
  212513. currentASIODev[1]->callback (index);
  212514. }
  212515. static void bufferSwitchCallback2 (long index, long)
  212516. {
  212517. if (currentASIODev[2] != 0)
  212518. currentASIODev[2]->callback (index);
  212519. }
  212520. static long asioMessagesCallback0 (long selector, long value, void*, double*)
  212521. {
  212522. return asioMessagesCallback (selector, value, 0);
  212523. }
  212524. static long asioMessagesCallback1 (long selector, long value, void*, double*)
  212525. {
  212526. return asioMessagesCallback (selector, value, 1);
  212527. }
  212528. static long asioMessagesCallback2 (long selector, long value, void*, double*)
  212529. {
  212530. return asioMessagesCallback (selector, value, 2);
  212531. }
  212532. static long asioMessagesCallback (long selector, long value, const int deviceIndex)
  212533. {
  212534. switch (selector)
  212535. {
  212536. case kAsioSelectorSupported:
  212537. if (value == kAsioResetRequest
  212538. || value == kAsioEngineVersion
  212539. || value == kAsioResyncRequest
  212540. || value == kAsioLatenciesChanged
  212541. || value == kAsioSupportsInputMonitor)
  212542. return 1;
  212543. break;
  212544. case kAsioBufferSizeChange:
  212545. break;
  212546. case kAsioResetRequest:
  212547. if (currentASIODev[deviceIndex] != 0)
  212548. currentASIODev[deviceIndex]->resetRequest();
  212549. return 1;
  212550. case kAsioResyncRequest:
  212551. if (currentASIODev[deviceIndex] != 0)
  212552. currentASIODev[deviceIndex]->resyncRequest();
  212553. return 1;
  212554. case kAsioLatenciesChanged:
  212555. return 1;
  212556. case kAsioEngineVersion:
  212557. return 2;
  212558. case kAsioSupportsTimeInfo:
  212559. case kAsioSupportsTimeCode:
  212560. return 0;
  212561. }
  212562. return 0;
  212563. }
  212564. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  212565. {
  212566. }
  212567. static void convertInt16ToFloat (const char* src,
  212568. float* dest,
  212569. const int srcStrideBytes,
  212570. int numSamples,
  212571. const bool littleEndian) throw()
  212572. {
  212573. const double g = 1.0 / 32768.0;
  212574. if (littleEndian)
  212575. {
  212576. while (--numSamples >= 0)
  212577. {
  212578. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  212579. src += srcStrideBytes;
  212580. }
  212581. }
  212582. else
  212583. {
  212584. while (--numSamples >= 0)
  212585. {
  212586. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  212587. src += srcStrideBytes;
  212588. }
  212589. }
  212590. }
  212591. static void convertFloatToInt16 (const float* src,
  212592. char* dest,
  212593. const int dstStrideBytes,
  212594. int numSamples,
  212595. const bool littleEndian) throw()
  212596. {
  212597. const double maxVal = (double) 0x7fff;
  212598. if (littleEndian)
  212599. {
  212600. while (--numSamples >= 0)
  212601. {
  212602. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212603. dest += dstStrideBytes;
  212604. }
  212605. }
  212606. else
  212607. {
  212608. while (--numSamples >= 0)
  212609. {
  212610. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212611. dest += dstStrideBytes;
  212612. }
  212613. }
  212614. }
  212615. static void convertInt24ToFloat (const char* src,
  212616. float* dest,
  212617. const int srcStrideBytes,
  212618. int numSamples,
  212619. const bool littleEndian) throw()
  212620. {
  212621. const double g = 1.0 / 0x7fffff;
  212622. if (littleEndian)
  212623. {
  212624. while (--numSamples >= 0)
  212625. {
  212626. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  212627. src += srcStrideBytes;
  212628. }
  212629. }
  212630. else
  212631. {
  212632. while (--numSamples >= 0)
  212633. {
  212634. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  212635. src += srcStrideBytes;
  212636. }
  212637. }
  212638. }
  212639. static void convertFloatToInt24 (const float* src,
  212640. char* dest,
  212641. const int dstStrideBytes,
  212642. int numSamples,
  212643. const bool littleEndian) throw()
  212644. {
  212645. const double maxVal = (double) 0x7fffff;
  212646. if (littleEndian)
  212647. {
  212648. while (--numSamples >= 0)
  212649. {
  212650. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  212651. dest += dstStrideBytes;
  212652. }
  212653. }
  212654. else
  212655. {
  212656. while (--numSamples >= 0)
  212657. {
  212658. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  212659. dest += dstStrideBytes;
  212660. }
  212661. }
  212662. }
  212663. static void convertInt32ToFloat (const char* src,
  212664. float* dest,
  212665. const int srcStrideBytes,
  212666. int numSamples,
  212667. const bool littleEndian) throw()
  212668. {
  212669. const double g = 1.0 / 0x7fffffff;
  212670. if (littleEndian)
  212671. {
  212672. while (--numSamples >= 0)
  212673. {
  212674. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  212675. src += srcStrideBytes;
  212676. }
  212677. }
  212678. else
  212679. {
  212680. while (--numSamples >= 0)
  212681. {
  212682. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  212683. src += srcStrideBytes;
  212684. }
  212685. }
  212686. }
  212687. static void convertFloatToInt32 (const float* src,
  212688. char* dest,
  212689. const int dstStrideBytes,
  212690. int numSamples,
  212691. const bool littleEndian) throw()
  212692. {
  212693. const double maxVal = (double) 0x7fffffff;
  212694. if (littleEndian)
  212695. {
  212696. while (--numSamples >= 0)
  212697. {
  212698. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212699. dest += dstStrideBytes;
  212700. }
  212701. }
  212702. else
  212703. {
  212704. while (--numSamples >= 0)
  212705. {
  212706. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212707. dest += dstStrideBytes;
  212708. }
  212709. }
  212710. }
  212711. static void typeToFormatParameters (const long type,
  212712. int& bitDepth,
  212713. int& byteStride,
  212714. bool& formatIsFloat,
  212715. bool& littleEndian) throw()
  212716. {
  212717. bitDepth = 0;
  212718. littleEndian = false;
  212719. formatIsFloat = false;
  212720. switch (type)
  212721. {
  212722. case ASIOSTInt16MSB:
  212723. case ASIOSTInt16LSB:
  212724. case ASIOSTInt32MSB16:
  212725. case ASIOSTInt32LSB16:
  212726. bitDepth = 16; break;
  212727. case ASIOSTFloat32MSB:
  212728. case ASIOSTFloat32LSB:
  212729. formatIsFloat = true;
  212730. bitDepth = 32; break;
  212731. case ASIOSTInt32MSB:
  212732. case ASIOSTInt32LSB:
  212733. bitDepth = 32; break;
  212734. case ASIOSTInt24MSB:
  212735. case ASIOSTInt24LSB:
  212736. case ASIOSTInt32MSB24:
  212737. case ASIOSTInt32LSB24:
  212738. case ASIOSTInt32MSB18:
  212739. case ASIOSTInt32MSB20:
  212740. case ASIOSTInt32LSB18:
  212741. case ASIOSTInt32LSB20:
  212742. bitDepth = 24; break;
  212743. case ASIOSTFloat64MSB:
  212744. case ASIOSTFloat64LSB:
  212745. default:
  212746. bitDepth = 64;
  212747. break;
  212748. }
  212749. switch (type)
  212750. {
  212751. case ASIOSTInt16MSB:
  212752. case ASIOSTInt32MSB16:
  212753. case ASIOSTFloat32MSB:
  212754. case ASIOSTFloat64MSB:
  212755. case ASIOSTInt32MSB:
  212756. case ASIOSTInt32MSB18:
  212757. case ASIOSTInt32MSB20:
  212758. case ASIOSTInt32MSB24:
  212759. case ASIOSTInt24MSB:
  212760. littleEndian = false; break;
  212761. case ASIOSTInt16LSB:
  212762. case ASIOSTInt32LSB16:
  212763. case ASIOSTFloat32LSB:
  212764. case ASIOSTFloat64LSB:
  212765. case ASIOSTInt32LSB:
  212766. case ASIOSTInt32LSB18:
  212767. case ASIOSTInt32LSB20:
  212768. case ASIOSTInt32LSB24:
  212769. case ASIOSTInt24LSB:
  212770. littleEndian = true; break;
  212771. default:
  212772. break;
  212773. }
  212774. switch (type)
  212775. {
  212776. case ASIOSTInt16LSB:
  212777. case ASIOSTInt16MSB:
  212778. byteStride = 2; break;
  212779. case ASIOSTInt24LSB:
  212780. case ASIOSTInt24MSB:
  212781. byteStride = 3; break;
  212782. case ASIOSTInt32MSB16:
  212783. case ASIOSTInt32LSB16:
  212784. case ASIOSTInt32MSB:
  212785. case ASIOSTInt32MSB18:
  212786. case ASIOSTInt32MSB20:
  212787. case ASIOSTInt32MSB24:
  212788. case ASIOSTInt32LSB:
  212789. case ASIOSTInt32LSB18:
  212790. case ASIOSTInt32LSB20:
  212791. case ASIOSTInt32LSB24:
  212792. case ASIOSTFloat32LSB:
  212793. case ASIOSTFloat32MSB:
  212794. byteStride = 4; break;
  212795. case ASIOSTFloat64MSB:
  212796. case ASIOSTFloat64LSB:
  212797. byteStride = 8; break;
  212798. default:
  212799. break;
  212800. }
  212801. }
  212802. };
  212803. class ASIOAudioIODeviceType : public AudioIODeviceType
  212804. {
  212805. public:
  212806. ASIOAudioIODeviceType()
  212807. : AudioIODeviceType ("ASIO"),
  212808. hasScanned (false)
  212809. {
  212810. CoInitialize (0);
  212811. }
  212812. ~ASIOAudioIODeviceType()
  212813. {
  212814. }
  212815. void scanForDevices()
  212816. {
  212817. hasScanned = true;
  212818. deviceNames.clear();
  212819. classIds.clear();
  212820. HKEY hk = 0;
  212821. int index = 0;
  212822. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  212823. {
  212824. for (;;)
  212825. {
  212826. char name [256];
  212827. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  212828. {
  212829. addDriverInfo (name, hk);
  212830. }
  212831. else
  212832. {
  212833. break;
  212834. }
  212835. }
  212836. RegCloseKey (hk);
  212837. }
  212838. }
  212839. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  212840. {
  212841. jassert (hasScanned); // need to call scanForDevices() before doing this
  212842. return deviceNames;
  212843. }
  212844. int getDefaultDeviceIndex (bool) const
  212845. {
  212846. jassert (hasScanned); // need to call scanForDevices() before doing this
  212847. for (int i = deviceNames.size(); --i >= 0;)
  212848. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  212849. return i; // asio4all is a safe choice for a default..
  212850. #if JUCE_DEBUG
  212851. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  212852. return 1; // (the digi m-box driver crashes the app when you run
  212853. // it in the debugger, which can be a bit annoying)
  212854. #endif
  212855. return 0;
  212856. }
  212857. static int findFreeSlot()
  212858. {
  212859. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212860. if (currentASIODev[i] == 0)
  212861. return i;
  212862. jassertfalse; // unfortunately you can only have a finite number
  212863. // of ASIO devices open at the same time..
  212864. return -1;
  212865. }
  212866. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  212867. {
  212868. jassert (hasScanned); // need to call scanForDevices() before doing this
  212869. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  212870. }
  212871. bool hasSeparateInputsAndOutputs() const { return false; }
  212872. AudioIODevice* createDevice (const String& outputDeviceName,
  212873. const String& inputDeviceName)
  212874. {
  212875. // ASIO can't open two different devices for input and output - they must be the same one.
  212876. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  212877. jassert (hasScanned); // need to call scanForDevices() before doing this
  212878. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  212879. : inputDeviceName);
  212880. if (index >= 0)
  212881. {
  212882. const int freeSlot = findFreeSlot();
  212883. if (freeSlot >= 0)
  212884. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  212885. }
  212886. return 0;
  212887. }
  212888. juce_UseDebuggingNewOperator
  212889. private:
  212890. StringArray deviceNames;
  212891. OwnedArray <CLSID> classIds;
  212892. bool hasScanned;
  212893. static bool checkClassIsOk (const String& classId)
  212894. {
  212895. HKEY hk = 0;
  212896. bool ok = false;
  212897. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  212898. {
  212899. int index = 0;
  212900. for (;;)
  212901. {
  212902. WCHAR buf [512];
  212903. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  212904. {
  212905. if (classId.equalsIgnoreCase (buf))
  212906. {
  212907. HKEY subKey, pathKey;
  212908. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  212909. {
  212910. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  212911. {
  212912. WCHAR pathName [1024];
  212913. DWORD dtype = REG_SZ;
  212914. DWORD dsize = sizeof (pathName);
  212915. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  212916. ok = File (pathName).exists();
  212917. RegCloseKey (pathKey);
  212918. }
  212919. RegCloseKey (subKey);
  212920. }
  212921. break;
  212922. }
  212923. }
  212924. else
  212925. {
  212926. break;
  212927. }
  212928. }
  212929. RegCloseKey (hk);
  212930. }
  212931. return ok;
  212932. }
  212933. void addDriverInfo (const String& keyName, HKEY hk)
  212934. {
  212935. HKEY subKey;
  212936. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  212937. {
  212938. WCHAR buf [256];
  212939. zerostruct (buf);
  212940. DWORD dtype = REG_SZ;
  212941. DWORD dsize = sizeof (buf);
  212942. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  212943. {
  212944. if (dsize > 0 && checkClassIsOk (buf))
  212945. {
  212946. CLSID classId;
  212947. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  212948. {
  212949. dtype = REG_SZ;
  212950. dsize = sizeof (buf);
  212951. String deviceName;
  212952. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  212953. deviceName = buf;
  212954. else
  212955. deviceName = keyName;
  212956. log ("found " + deviceName);
  212957. deviceNames.add (deviceName);
  212958. classIds.add (new CLSID (classId));
  212959. }
  212960. }
  212961. RegCloseKey (subKey);
  212962. }
  212963. }
  212964. }
  212965. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  212966. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  212967. };
  212968. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  212969. {
  212970. return new ASIOAudioIODeviceType();
  212971. }
  212972. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  212973. void* guid,
  212974. const String& optionalDllForDirectLoading)
  212975. {
  212976. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  212977. if (freeSlot < 0)
  212978. return 0;
  212979. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  212980. }
  212981. #undef log
  212982. #endif
  212983. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  212984. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  212985. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212986. // compiled on its own).
  212987. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  212988. END_JUCE_NAMESPACE
  212989. extern "C"
  212990. {
  212991. // Declare just the minimum number of interfaces for the DSound objects that we need..
  212992. typedef struct typeDSBUFFERDESC
  212993. {
  212994. DWORD dwSize;
  212995. DWORD dwFlags;
  212996. DWORD dwBufferBytes;
  212997. DWORD dwReserved;
  212998. LPWAVEFORMATEX lpwfxFormat;
  212999. GUID guid3DAlgorithm;
  213000. } DSBUFFERDESC;
  213001. struct IDirectSoundBuffer;
  213002. #undef INTERFACE
  213003. #define INTERFACE IDirectSound
  213004. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  213005. {
  213006. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213007. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213008. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213009. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  213010. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213011. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  213012. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  213013. STDMETHOD(Compact) (THIS) PURE;
  213014. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  213015. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  213016. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213017. };
  213018. #undef INTERFACE
  213019. #define INTERFACE IDirectSoundBuffer
  213020. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  213021. {
  213022. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213023. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213024. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213025. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213026. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213027. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213028. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  213029. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  213030. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  213031. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213032. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  213033. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213034. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  213035. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  213036. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  213037. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  213038. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  213039. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  213040. STDMETHOD(Stop) (THIS) PURE;
  213041. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213042. STDMETHOD(Restore) (THIS) PURE;
  213043. };
  213044. typedef struct typeDSCBUFFERDESC
  213045. {
  213046. DWORD dwSize;
  213047. DWORD dwFlags;
  213048. DWORD dwBufferBytes;
  213049. DWORD dwReserved;
  213050. LPWAVEFORMATEX lpwfxFormat;
  213051. } DSCBUFFERDESC;
  213052. struct IDirectSoundCaptureBuffer;
  213053. #undef INTERFACE
  213054. #define INTERFACE IDirectSoundCapture
  213055. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  213056. {
  213057. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213058. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213059. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213060. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  213061. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213062. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213063. };
  213064. #undef INTERFACE
  213065. #define INTERFACE IDirectSoundCaptureBuffer
  213066. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  213067. {
  213068. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213069. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213070. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213071. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213072. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213073. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213074. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213075. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  213076. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213077. STDMETHOD(Start) (THIS_ DWORD) PURE;
  213078. STDMETHOD(Stop) (THIS) PURE;
  213079. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213080. };
  213081. };
  213082. BEGIN_JUCE_NAMESPACE
  213083. static const String getDSErrorMessage (HRESULT hr)
  213084. {
  213085. const char* result = 0;
  213086. switch (hr)
  213087. {
  213088. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  213089. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  213090. case E_INVALIDARG: result = "Invalid parameter"; break;
  213091. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  213092. case E_FAIL: result = "Generic error"; break;
  213093. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  213094. case E_OUTOFMEMORY: result = "Out of memory"; break;
  213095. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  213096. case E_NOTIMPL: result = "Unsupported function"; break;
  213097. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  213098. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  213099. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  213100. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  213101. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  213102. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  213103. case E_NOINTERFACE: result = "No interface"; break;
  213104. case S_OK: result = "No error"; break;
  213105. default: return "Unknown error: " + String ((int) hr);
  213106. }
  213107. return result;
  213108. }
  213109. #define DS_DEBUGGING 1
  213110. #ifdef DS_DEBUGGING
  213111. #define CATCH JUCE_CATCH_EXCEPTION
  213112. #undef log
  213113. #define log(a) Logger::writeToLog(a);
  213114. #undef logError
  213115. #define logError(a) logDSError(a, __LINE__);
  213116. static void logDSError (HRESULT hr, int lineNum)
  213117. {
  213118. if (hr != S_OK)
  213119. {
  213120. String error ("DS error at line ");
  213121. error << lineNum << " - " << getDSErrorMessage (hr);
  213122. log (error);
  213123. }
  213124. }
  213125. #else
  213126. #define CATCH JUCE_CATCH_ALL
  213127. #define log(a)
  213128. #define logError(a)
  213129. #endif
  213130. #define DSOUND_FUNCTION(functionName, params) \
  213131. typedef HRESULT (WINAPI *type##functionName) params; \
  213132. static type##functionName ds##functionName = 0;
  213133. #define DSOUND_FUNCTION_LOAD(functionName) \
  213134. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  213135. jassert (ds##functionName != 0);
  213136. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  213137. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  213138. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  213139. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  213140. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  213141. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  213142. static void initialiseDSoundFunctions()
  213143. {
  213144. if (dsDirectSoundCreate == 0)
  213145. {
  213146. HMODULE h = LoadLibraryA ("dsound.dll");
  213147. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  213148. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  213149. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  213150. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  213151. }
  213152. }
  213153. class DSoundInternalOutChannel
  213154. {
  213155. String name;
  213156. LPGUID guid;
  213157. int sampleRate, bufferSizeSamples;
  213158. float* leftBuffer;
  213159. float* rightBuffer;
  213160. IDirectSound* pDirectSound;
  213161. IDirectSoundBuffer* pOutputBuffer;
  213162. DWORD writeOffset;
  213163. int totalBytesPerBuffer;
  213164. int bytesPerBuffer;
  213165. unsigned int lastPlayCursor;
  213166. public:
  213167. int bitDepth;
  213168. bool doneFlag;
  213169. DSoundInternalOutChannel (const String& name_,
  213170. LPGUID guid_,
  213171. int rate,
  213172. int bufferSize,
  213173. float* left,
  213174. float* right)
  213175. : name (name_),
  213176. guid (guid_),
  213177. sampleRate (rate),
  213178. bufferSizeSamples (bufferSize),
  213179. leftBuffer (left),
  213180. rightBuffer (right),
  213181. pDirectSound (0),
  213182. pOutputBuffer (0),
  213183. bitDepth (16)
  213184. {
  213185. }
  213186. ~DSoundInternalOutChannel()
  213187. {
  213188. close();
  213189. }
  213190. void close()
  213191. {
  213192. HRESULT hr;
  213193. if (pOutputBuffer != 0)
  213194. {
  213195. JUCE_TRY
  213196. {
  213197. log ("closing dsound out: " + name);
  213198. hr = pOutputBuffer->Stop();
  213199. logError (hr);
  213200. }
  213201. CATCH
  213202. JUCE_TRY
  213203. {
  213204. hr = pOutputBuffer->Release();
  213205. logError (hr);
  213206. }
  213207. CATCH
  213208. pOutputBuffer = 0;
  213209. }
  213210. if (pDirectSound != 0)
  213211. {
  213212. JUCE_TRY
  213213. {
  213214. hr = pDirectSound->Release();
  213215. logError (hr);
  213216. }
  213217. CATCH
  213218. pDirectSound = 0;
  213219. }
  213220. }
  213221. const String open()
  213222. {
  213223. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  213224. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213225. pDirectSound = 0;
  213226. pOutputBuffer = 0;
  213227. writeOffset = 0;
  213228. String error;
  213229. HRESULT hr = E_NOINTERFACE;
  213230. if (dsDirectSoundCreate != 0)
  213231. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  213232. if (hr == S_OK)
  213233. {
  213234. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213235. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213236. const int numChannels = 2;
  213237. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  213238. logError (hr);
  213239. if (hr == S_OK)
  213240. {
  213241. IDirectSoundBuffer* pPrimaryBuffer;
  213242. DSBUFFERDESC primaryDesc;
  213243. zerostruct (primaryDesc);
  213244. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213245. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  213246. primaryDesc.dwBufferBytes = 0;
  213247. primaryDesc.lpwfxFormat = 0;
  213248. log ("opening dsound out step 2");
  213249. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  213250. logError (hr);
  213251. if (hr == S_OK)
  213252. {
  213253. WAVEFORMATEX wfFormat;
  213254. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213255. wfFormat.nChannels = (unsigned short) numChannels;
  213256. wfFormat.nSamplesPerSec = sampleRate;
  213257. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  213258. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  213259. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213260. wfFormat.cbSize = 0;
  213261. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  213262. logError (hr);
  213263. if (hr == S_OK)
  213264. {
  213265. DSBUFFERDESC secondaryDesc;
  213266. zerostruct (secondaryDesc);
  213267. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213268. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  213269. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  213270. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  213271. secondaryDesc.lpwfxFormat = &wfFormat;
  213272. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  213273. logError (hr);
  213274. if (hr == S_OK)
  213275. {
  213276. log ("opening dsound out step 3");
  213277. DWORD dwDataLen;
  213278. unsigned char* pDSBuffData;
  213279. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  213280. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  213281. logError (hr);
  213282. if (hr == S_OK)
  213283. {
  213284. zeromem (pDSBuffData, dwDataLen);
  213285. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  213286. if (hr == S_OK)
  213287. {
  213288. hr = pOutputBuffer->SetCurrentPosition (0);
  213289. if (hr == S_OK)
  213290. {
  213291. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  213292. if (hr == S_OK)
  213293. return String::empty;
  213294. }
  213295. }
  213296. }
  213297. }
  213298. }
  213299. }
  213300. }
  213301. }
  213302. error = getDSErrorMessage (hr);
  213303. close();
  213304. return error;
  213305. }
  213306. void synchronisePosition()
  213307. {
  213308. if (pOutputBuffer != 0)
  213309. {
  213310. DWORD playCursor;
  213311. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  213312. }
  213313. }
  213314. bool service()
  213315. {
  213316. if (pOutputBuffer == 0)
  213317. return true;
  213318. DWORD playCursor, writeCursor;
  213319. for (;;)
  213320. {
  213321. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  213322. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213323. {
  213324. pOutputBuffer->Restore();
  213325. continue;
  213326. }
  213327. if (hr == S_OK)
  213328. break;
  213329. logError (hr);
  213330. jassertfalse;
  213331. return true;
  213332. }
  213333. int playWriteGap = writeCursor - playCursor;
  213334. if (playWriteGap < 0)
  213335. playWriteGap += totalBytesPerBuffer;
  213336. int bytesEmpty = playCursor - writeOffset;
  213337. if (bytesEmpty < 0)
  213338. bytesEmpty += totalBytesPerBuffer;
  213339. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  213340. {
  213341. writeOffset = writeCursor;
  213342. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  213343. }
  213344. if (bytesEmpty >= bytesPerBuffer)
  213345. {
  213346. LPBYTE lpbuf1 = 0;
  213347. LPBYTE lpbuf2 = 0;
  213348. DWORD dwSize1 = 0;
  213349. DWORD dwSize2 = 0;
  213350. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  213351. bytesPerBuffer,
  213352. (void**) &lpbuf1, &dwSize1,
  213353. (void**) &lpbuf2, &dwSize2, 0);
  213354. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213355. {
  213356. pOutputBuffer->Restore();
  213357. hr = pOutputBuffer->Lock (writeOffset,
  213358. bytesPerBuffer,
  213359. (void**) &lpbuf1, &dwSize1,
  213360. (void**) &lpbuf2, &dwSize2, 0);
  213361. }
  213362. if (hr == S_OK)
  213363. {
  213364. if (bitDepth == 16)
  213365. {
  213366. const float gainL = 32767.0f;
  213367. const float gainR = 32767.0f;
  213368. int* dest = (int*)lpbuf1;
  213369. const float* left = leftBuffer;
  213370. const float* right = rightBuffer;
  213371. int samples1 = dwSize1 >> 2;
  213372. int samples2 = dwSize2 >> 2;
  213373. if (left == 0)
  213374. {
  213375. while (--samples1 >= 0)
  213376. {
  213377. int r = roundToInt (gainR * *right++);
  213378. if (r < -32768)
  213379. r = -32768;
  213380. else if (r > 32767)
  213381. r = 32767;
  213382. *dest++ = (r << 16);
  213383. }
  213384. dest = (int*)lpbuf2;
  213385. while (--samples2 >= 0)
  213386. {
  213387. int r = roundToInt (gainR * *right++);
  213388. if (r < -32768)
  213389. r = -32768;
  213390. else if (r > 32767)
  213391. r = 32767;
  213392. *dest++ = (r << 16);
  213393. }
  213394. }
  213395. else if (right == 0)
  213396. {
  213397. while (--samples1 >= 0)
  213398. {
  213399. int l = roundToInt (gainL * *left++);
  213400. if (l < -32768)
  213401. l = -32768;
  213402. else if (l > 32767)
  213403. l = 32767;
  213404. l &= 0xffff;
  213405. *dest++ = l;
  213406. }
  213407. dest = (int*)lpbuf2;
  213408. while (--samples2 >= 0)
  213409. {
  213410. int l = roundToInt (gainL * *left++);
  213411. if (l < -32768)
  213412. l = -32768;
  213413. else if (l > 32767)
  213414. l = 32767;
  213415. l &= 0xffff;
  213416. *dest++ = l;
  213417. }
  213418. }
  213419. else
  213420. {
  213421. while (--samples1 >= 0)
  213422. {
  213423. int l = roundToInt (gainL * *left++);
  213424. if (l < -32768)
  213425. l = -32768;
  213426. else if (l > 32767)
  213427. l = 32767;
  213428. l &= 0xffff;
  213429. int r = roundToInt (gainR * *right++);
  213430. if (r < -32768)
  213431. r = -32768;
  213432. else if (r > 32767)
  213433. r = 32767;
  213434. *dest++ = (r << 16) | l;
  213435. }
  213436. dest = (int*)lpbuf2;
  213437. while (--samples2 >= 0)
  213438. {
  213439. int l = roundToInt (gainL * *left++);
  213440. if (l < -32768)
  213441. l = -32768;
  213442. else if (l > 32767)
  213443. l = 32767;
  213444. l &= 0xffff;
  213445. int r = roundToInt (gainR * *right++);
  213446. if (r < -32768)
  213447. r = -32768;
  213448. else if (r > 32767)
  213449. r = 32767;
  213450. *dest++ = (r << 16) | l;
  213451. }
  213452. }
  213453. }
  213454. else
  213455. {
  213456. jassertfalse;
  213457. }
  213458. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  213459. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  213460. }
  213461. else
  213462. {
  213463. jassertfalse;
  213464. logError (hr);
  213465. }
  213466. bytesEmpty -= bytesPerBuffer;
  213467. return true;
  213468. }
  213469. else
  213470. {
  213471. return false;
  213472. }
  213473. }
  213474. };
  213475. struct DSoundInternalInChannel
  213476. {
  213477. String name;
  213478. LPGUID guid;
  213479. int sampleRate, bufferSizeSamples;
  213480. float* leftBuffer;
  213481. float* rightBuffer;
  213482. IDirectSound* pDirectSound;
  213483. IDirectSoundCapture* pDirectSoundCapture;
  213484. IDirectSoundCaptureBuffer* pInputBuffer;
  213485. public:
  213486. unsigned int readOffset;
  213487. int bytesPerBuffer, totalBytesPerBuffer;
  213488. int bitDepth;
  213489. bool doneFlag;
  213490. DSoundInternalInChannel (const String& name_,
  213491. LPGUID guid_,
  213492. int rate,
  213493. int bufferSize,
  213494. float* left,
  213495. float* right)
  213496. : name (name_),
  213497. guid (guid_),
  213498. sampleRate (rate),
  213499. bufferSizeSamples (bufferSize),
  213500. leftBuffer (left),
  213501. rightBuffer (right),
  213502. pDirectSound (0),
  213503. pDirectSoundCapture (0),
  213504. pInputBuffer (0),
  213505. bitDepth (16)
  213506. {
  213507. }
  213508. ~DSoundInternalInChannel()
  213509. {
  213510. close();
  213511. }
  213512. void close()
  213513. {
  213514. HRESULT hr;
  213515. if (pInputBuffer != 0)
  213516. {
  213517. JUCE_TRY
  213518. {
  213519. log ("closing dsound in: " + name);
  213520. hr = pInputBuffer->Stop();
  213521. logError (hr);
  213522. }
  213523. CATCH
  213524. JUCE_TRY
  213525. {
  213526. hr = pInputBuffer->Release();
  213527. logError (hr);
  213528. }
  213529. CATCH
  213530. pInputBuffer = 0;
  213531. }
  213532. if (pDirectSoundCapture != 0)
  213533. {
  213534. JUCE_TRY
  213535. {
  213536. hr = pDirectSoundCapture->Release();
  213537. logError (hr);
  213538. }
  213539. CATCH
  213540. pDirectSoundCapture = 0;
  213541. }
  213542. if (pDirectSound != 0)
  213543. {
  213544. JUCE_TRY
  213545. {
  213546. hr = pDirectSound->Release();
  213547. logError (hr);
  213548. }
  213549. CATCH
  213550. pDirectSound = 0;
  213551. }
  213552. }
  213553. const String open()
  213554. {
  213555. log ("opening dsound in device: " + name
  213556. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213557. pDirectSound = 0;
  213558. pDirectSoundCapture = 0;
  213559. pInputBuffer = 0;
  213560. readOffset = 0;
  213561. totalBytesPerBuffer = 0;
  213562. String error;
  213563. HRESULT hr = E_NOINTERFACE;
  213564. if (dsDirectSoundCaptureCreate != 0)
  213565. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  213566. logError (hr);
  213567. if (hr == S_OK)
  213568. {
  213569. const int numChannels = 2;
  213570. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213571. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213572. WAVEFORMATEX wfFormat;
  213573. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213574. wfFormat.nChannels = (unsigned short)numChannels;
  213575. wfFormat.nSamplesPerSec = sampleRate;
  213576. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  213577. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  213578. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213579. wfFormat.cbSize = 0;
  213580. DSCBUFFERDESC captureDesc;
  213581. zerostruct (captureDesc);
  213582. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  213583. captureDesc.dwFlags = 0;
  213584. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  213585. captureDesc.lpwfxFormat = &wfFormat;
  213586. log ("opening dsound in step 2");
  213587. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  213588. logError (hr);
  213589. if (hr == S_OK)
  213590. {
  213591. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  213592. logError (hr);
  213593. if (hr == S_OK)
  213594. return String::empty;
  213595. }
  213596. }
  213597. error = getDSErrorMessage (hr);
  213598. close();
  213599. return error;
  213600. }
  213601. void synchronisePosition()
  213602. {
  213603. if (pInputBuffer != 0)
  213604. {
  213605. DWORD capturePos;
  213606. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  213607. }
  213608. }
  213609. bool service()
  213610. {
  213611. if (pInputBuffer == 0)
  213612. return true;
  213613. DWORD capturePos, readPos;
  213614. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  213615. logError (hr);
  213616. if (hr != S_OK)
  213617. return true;
  213618. int bytesFilled = readPos - readOffset;
  213619. if (bytesFilled < 0)
  213620. bytesFilled += totalBytesPerBuffer;
  213621. if (bytesFilled >= bytesPerBuffer)
  213622. {
  213623. LPBYTE lpbuf1 = 0;
  213624. LPBYTE lpbuf2 = 0;
  213625. DWORD dwsize1 = 0;
  213626. DWORD dwsize2 = 0;
  213627. HRESULT hr = pInputBuffer->Lock (readOffset,
  213628. bytesPerBuffer,
  213629. (void**) &lpbuf1, &dwsize1,
  213630. (void**) &lpbuf2, &dwsize2, 0);
  213631. if (hr == S_OK)
  213632. {
  213633. if (bitDepth == 16)
  213634. {
  213635. const float g = 1.0f / 32768.0f;
  213636. float* destL = leftBuffer;
  213637. float* destR = rightBuffer;
  213638. int samples1 = dwsize1 >> 2;
  213639. int samples2 = dwsize2 >> 2;
  213640. const short* src = (const short*)lpbuf1;
  213641. if (destL == 0)
  213642. {
  213643. while (--samples1 >= 0)
  213644. {
  213645. ++src;
  213646. *destR++ = *src++ * g;
  213647. }
  213648. src = (const short*)lpbuf2;
  213649. while (--samples2 >= 0)
  213650. {
  213651. ++src;
  213652. *destR++ = *src++ * g;
  213653. }
  213654. }
  213655. else if (destR == 0)
  213656. {
  213657. while (--samples1 >= 0)
  213658. {
  213659. *destL++ = *src++ * g;
  213660. ++src;
  213661. }
  213662. src = (const short*)lpbuf2;
  213663. while (--samples2 >= 0)
  213664. {
  213665. *destL++ = *src++ * g;
  213666. ++src;
  213667. }
  213668. }
  213669. else
  213670. {
  213671. while (--samples1 >= 0)
  213672. {
  213673. *destL++ = *src++ * g;
  213674. *destR++ = *src++ * g;
  213675. }
  213676. src = (const short*)lpbuf2;
  213677. while (--samples2 >= 0)
  213678. {
  213679. *destL++ = *src++ * g;
  213680. *destR++ = *src++ * g;
  213681. }
  213682. }
  213683. }
  213684. else
  213685. {
  213686. jassertfalse;
  213687. }
  213688. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  213689. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  213690. }
  213691. else
  213692. {
  213693. logError (hr);
  213694. jassertfalse;
  213695. }
  213696. bytesFilled -= bytesPerBuffer;
  213697. return true;
  213698. }
  213699. else
  213700. {
  213701. return false;
  213702. }
  213703. }
  213704. };
  213705. class DSoundAudioIODevice : public AudioIODevice,
  213706. public Thread
  213707. {
  213708. public:
  213709. DSoundAudioIODevice (const String& deviceName,
  213710. const int outputDeviceIndex_,
  213711. const int inputDeviceIndex_)
  213712. : AudioIODevice (deviceName, "DirectSound"),
  213713. Thread ("Juce DSound"),
  213714. isOpen_ (false),
  213715. isStarted (false),
  213716. outputDeviceIndex (outputDeviceIndex_),
  213717. inputDeviceIndex (inputDeviceIndex_),
  213718. totalSamplesOut (0),
  213719. sampleRate (0.0),
  213720. inputBuffers (1, 1),
  213721. outputBuffers (1, 1),
  213722. callback (0),
  213723. bufferSizeSamples (0)
  213724. {
  213725. if (outputDeviceIndex_ >= 0)
  213726. {
  213727. outChannels.add (TRANS("Left"));
  213728. outChannels.add (TRANS("Right"));
  213729. }
  213730. if (inputDeviceIndex_ >= 0)
  213731. {
  213732. inChannels.add (TRANS("Left"));
  213733. inChannels.add (TRANS("Right"));
  213734. }
  213735. }
  213736. ~DSoundAudioIODevice()
  213737. {
  213738. close();
  213739. }
  213740. const StringArray getOutputChannelNames()
  213741. {
  213742. return outChannels;
  213743. }
  213744. const StringArray getInputChannelNames()
  213745. {
  213746. return inChannels;
  213747. }
  213748. int getNumSampleRates()
  213749. {
  213750. return 4;
  213751. }
  213752. double getSampleRate (int index)
  213753. {
  213754. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  213755. return samps [jlimit (0, 3, index)];
  213756. }
  213757. int getNumBufferSizesAvailable()
  213758. {
  213759. return 50;
  213760. }
  213761. int getBufferSizeSamples (int index)
  213762. {
  213763. int n = 64;
  213764. for (int i = 0; i < index; ++i)
  213765. n += (n < 512) ? 32
  213766. : ((n < 1024) ? 64
  213767. : ((n < 2048) ? 128 : 256));
  213768. return n;
  213769. }
  213770. int getDefaultBufferSize()
  213771. {
  213772. return 2560;
  213773. }
  213774. const String open (const BigInteger& inputChannels,
  213775. const BigInteger& outputChannels,
  213776. double sampleRate,
  213777. int bufferSizeSamples)
  213778. {
  213779. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  213780. isOpen_ = lastError.isEmpty();
  213781. return lastError;
  213782. }
  213783. void close()
  213784. {
  213785. stop();
  213786. if (isOpen_)
  213787. {
  213788. closeDevice();
  213789. isOpen_ = false;
  213790. }
  213791. }
  213792. bool isOpen()
  213793. {
  213794. return isOpen_ && isThreadRunning();
  213795. }
  213796. int getCurrentBufferSizeSamples()
  213797. {
  213798. return bufferSizeSamples;
  213799. }
  213800. double getCurrentSampleRate()
  213801. {
  213802. return sampleRate;
  213803. }
  213804. int getCurrentBitDepth()
  213805. {
  213806. int i, bits = 256;
  213807. for (i = inChans.size(); --i >= 0;)
  213808. bits = jmin (bits, inChans[i]->bitDepth);
  213809. for (i = outChans.size(); --i >= 0;)
  213810. bits = jmin (bits, outChans[i]->bitDepth);
  213811. if (bits > 32)
  213812. bits = 16;
  213813. return bits;
  213814. }
  213815. const BigInteger getActiveOutputChannels() const
  213816. {
  213817. return enabledOutputs;
  213818. }
  213819. const BigInteger getActiveInputChannels() const
  213820. {
  213821. return enabledInputs;
  213822. }
  213823. int getOutputLatencyInSamples()
  213824. {
  213825. return (int) (getCurrentBufferSizeSamples() * 1.5);
  213826. }
  213827. int getInputLatencyInSamples()
  213828. {
  213829. return getOutputLatencyInSamples();
  213830. }
  213831. void start (AudioIODeviceCallback* call)
  213832. {
  213833. if (isOpen_ && call != 0 && ! isStarted)
  213834. {
  213835. if (! isThreadRunning())
  213836. {
  213837. // something gone wrong and the thread's stopped..
  213838. isOpen_ = false;
  213839. return;
  213840. }
  213841. call->audioDeviceAboutToStart (this);
  213842. const ScopedLock sl (startStopLock);
  213843. callback = call;
  213844. isStarted = true;
  213845. }
  213846. }
  213847. void stop()
  213848. {
  213849. if (isStarted)
  213850. {
  213851. AudioIODeviceCallback* const callbackLocal = callback;
  213852. {
  213853. const ScopedLock sl (startStopLock);
  213854. isStarted = false;
  213855. }
  213856. if (callbackLocal != 0)
  213857. callbackLocal->audioDeviceStopped();
  213858. }
  213859. }
  213860. bool isPlaying()
  213861. {
  213862. return isStarted && isOpen_ && isThreadRunning();
  213863. }
  213864. const String getLastError()
  213865. {
  213866. return lastError;
  213867. }
  213868. juce_UseDebuggingNewOperator
  213869. StringArray inChannels, outChannels;
  213870. int outputDeviceIndex, inputDeviceIndex;
  213871. private:
  213872. bool isOpen_;
  213873. bool isStarted;
  213874. String lastError;
  213875. OwnedArray <DSoundInternalInChannel> inChans;
  213876. OwnedArray <DSoundInternalOutChannel> outChans;
  213877. WaitableEvent startEvent;
  213878. int bufferSizeSamples;
  213879. int volatile totalSamplesOut;
  213880. int64 volatile lastBlockTime;
  213881. double sampleRate;
  213882. BigInteger enabledInputs, enabledOutputs;
  213883. AudioSampleBuffer inputBuffers, outputBuffers;
  213884. AudioIODeviceCallback* callback;
  213885. CriticalSection startStopLock;
  213886. DSoundAudioIODevice (const DSoundAudioIODevice&);
  213887. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  213888. const String openDevice (const BigInteger& inputChannels,
  213889. const BigInteger& outputChannels,
  213890. double sampleRate_,
  213891. int bufferSizeSamples_);
  213892. void closeDevice()
  213893. {
  213894. isStarted = false;
  213895. stopThread (5000);
  213896. inChans.clear();
  213897. outChans.clear();
  213898. inputBuffers.setSize (1, 1);
  213899. outputBuffers.setSize (1, 1);
  213900. }
  213901. void resync()
  213902. {
  213903. if (! threadShouldExit())
  213904. {
  213905. sleep (5);
  213906. int i;
  213907. for (i = 0; i < outChans.size(); ++i)
  213908. outChans.getUnchecked(i)->synchronisePosition();
  213909. for (i = 0; i < inChans.size(); ++i)
  213910. inChans.getUnchecked(i)->synchronisePosition();
  213911. }
  213912. }
  213913. public:
  213914. void run()
  213915. {
  213916. while (! threadShouldExit())
  213917. {
  213918. if (wait (100))
  213919. break;
  213920. }
  213921. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  213922. const int maxTimeMS = jmax (5, 3 * latencyMs);
  213923. while (! threadShouldExit())
  213924. {
  213925. int numToDo = 0;
  213926. uint32 startTime = Time::getMillisecondCounter();
  213927. int i;
  213928. for (i = inChans.size(); --i >= 0;)
  213929. {
  213930. inChans.getUnchecked(i)->doneFlag = false;
  213931. ++numToDo;
  213932. }
  213933. for (i = outChans.size(); --i >= 0;)
  213934. {
  213935. outChans.getUnchecked(i)->doneFlag = false;
  213936. ++numToDo;
  213937. }
  213938. if (numToDo > 0)
  213939. {
  213940. const int maxCount = 3;
  213941. int count = maxCount;
  213942. for (;;)
  213943. {
  213944. for (i = inChans.size(); --i >= 0;)
  213945. {
  213946. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  213947. if ((! in->doneFlag) && in->service())
  213948. {
  213949. in->doneFlag = true;
  213950. --numToDo;
  213951. }
  213952. }
  213953. for (i = outChans.size(); --i >= 0;)
  213954. {
  213955. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  213956. if ((! out->doneFlag) && out->service())
  213957. {
  213958. out->doneFlag = true;
  213959. --numToDo;
  213960. }
  213961. }
  213962. if (numToDo <= 0)
  213963. break;
  213964. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  213965. {
  213966. resync();
  213967. break;
  213968. }
  213969. if (--count <= 0)
  213970. {
  213971. Sleep (1);
  213972. count = maxCount;
  213973. }
  213974. if (threadShouldExit())
  213975. return;
  213976. }
  213977. }
  213978. else
  213979. {
  213980. sleep (1);
  213981. }
  213982. const ScopedLock sl (startStopLock);
  213983. if (isStarted)
  213984. {
  213985. JUCE_TRY
  213986. {
  213987. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  213988. inputBuffers.getNumChannels(),
  213989. outputBuffers.getArrayOfChannels(),
  213990. outputBuffers.getNumChannels(),
  213991. bufferSizeSamples);
  213992. }
  213993. JUCE_CATCH_EXCEPTION
  213994. totalSamplesOut += bufferSizeSamples;
  213995. }
  213996. else
  213997. {
  213998. outputBuffers.clear();
  213999. totalSamplesOut = 0;
  214000. sleep (1);
  214001. }
  214002. }
  214003. }
  214004. };
  214005. class DSoundAudioIODeviceType : public AudioIODeviceType
  214006. {
  214007. public:
  214008. DSoundAudioIODeviceType()
  214009. : AudioIODeviceType ("DirectSound"),
  214010. hasScanned (false)
  214011. {
  214012. initialiseDSoundFunctions();
  214013. }
  214014. ~DSoundAudioIODeviceType()
  214015. {
  214016. }
  214017. void scanForDevices()
  214018. {
  214019. hasScanned = true;
  214020. outputDeviceNames.clear();
  214021. outputGuids.clear();
  214022. inputDeviceNames.clear();
  214023. inputGuids.clear();
  214024. if (dsDirectSoundEnumerateW != 0)
  214025. {
  214026. dsDirectSoundEnumerateW (outputEnumProcW, this);
  214027. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  214028. }
  214029. }
  214030. const StringArray getDeviceNames (bool wantInputNames) const
  214031. {
  214032. jassert (hasScanned); // need to call scanForDevices() before doing this
  214033. return wantInputNames ? inputDeviceNames
  214034. : outputDeviceNames;
  214035. }
  214036. int getDefaultDeviceIndex (bool /*forInput*/) const
  214037. {
  214038. jassert (hasScanned); // need to call scanForDevices() before doing this
  214039. return 0;
  214040. }
  214041. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  214042. {
  214043. jassert (hasScanned); // need to call scanForDevices() before doing this
  214044. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  214045. if (d == 0)
  214046. return -1;
  214047. return asInput ? d->inputDeviceIndex
  214048. : d->outputDeviceIndex;
  214049. }
  214050. bool hasSeparateInputsAndOutputs() const { return true; }
  214051. AudioIODevice* createDevice (const String& outputDeviceName,
  214052. const String& inputDeviceName)
  214053. {
  214054. jassert (hasScanned); // need to call scanForDevices() before doing this
  214055. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  214056. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  214057. if (outputIndex >= 0 || inputIndex >= 0)
  214058. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  214059. : inputDeviceName,
  214060. outputIndex, inputIndex);
  214061. return 0;
  214062. }
  214063. juce_UseDebuggingNewOperator
  214064. StringArray outputDeviceNames;
  214065. OwnedArray <GUID> outputGuids;
  214066. StringArray inputDeviceNames;
  214067. OwnedArray <GUID> inputGuids;
  214068. private:
  214069. bool hasScanned;
  214070. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  214071. {
  214072. desc = desc.trim();
  214073. if (desc.isNotEmpty())
  214074. {
  214075. const String origDesc (desc);
  214076. int n = 2;
  214077. while (outputDeviceNames.contains (desc))
  214078. desc = origDesc + " (" + String (n++) + ")";
  214079. outputDeviceNames.add (desc);
  214080. if (lpGUID != 0)
  214081. outputGuids.add (new GUID (*lpGUID));
  214082. else
  214083. outputGuids.add (0);
  214084. }
  214085. return TRUE;
  214086. }
  214087. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214088. {
  214089. return ((DSoundAudioIODeviceType*) object)
  214090. ->outputEnumProc (lpGUID, String (description));
  214091. }
  214092. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214093. {
  214094. return ((DSoundAudioIODeviceType*) object)
  214095. ->outputEnumProc (lpGUID, String (description));
  214096. }
  214097. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  214098. {
  214099. desc = desc.trim();
  214100. if (desc.isNotEmpty())
  214101. {
  214102. const String origDesc (desc);
  214103. int n = 2;
  214104. while (inputDeviceNames.contains (desc))
  214105. desc = origDesc + " (" + String (n++) + ")";
  214106. inputDeviceNames.add (desc);
  214107. if (lpGUID != 0)
  214108. inputGuids.add (new GUID (*lpGUID));
  214109. else
  214110. inputGuids.add (0);
  214111. }
  214112. return TRUE;
  214113. }
  214114. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214115. {
  214116. return ((DSoundAudioIODeviceType*) object)
  214117. ->inputEnumProc (lpGUID, String (description));
  214118. }
  214119. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214120. {
  214121. return ((DSoundAudioIODeviceType*) object)
  214122. ->inputEnumProc (lpGUID, String (description));
  214123. }
  214124. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  214125. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  214126. };
  214127. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  214128. const BigInteger& outputChannels,
  214129. double sampleRate_,
  214130. int bufferSizeSamples_)
  214131. {
  214132. closeDevice();
  214133. totalSamplesOut = 0;
  214134. sampleRate = sampleRate_;
  214135. if (bufferSizeSamples_ <= 0)
  214136. bufferSizeSamples_ = 960; // use as a default size if none is set.
  214137. bufferSizeSamples = bufferSizeSamples_ & ~7;
  214138. DSoundAudioIODeviceType dlh;
  214139. dlh.scanForDevices();
  214140. enabledInputs = inputChannels;
  214141. enabledInputs.setRange (inChannels.size(),
  214142. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  214143. false);
  214144. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  214145. inputBuffers.clear();
  214146. int i, numIns = 0;
  214147. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  214148. {
  214149. float* left = 0;
  214150. if (enabledInputs[i])
  214151. left = inputBuffers.getSampleData (numIns++);
  214152. float* right = 0;
  214153. if (enabledInputs[i + 1])
  214154. right = inputBuffers.getSampleData (numIns++);
  214155. if (left != 0 || right != 0)
  214156. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  214157. dlh.inputGuids [inputDeviceIndex],
  214158. (int) sampleRate, bufferSizeSamples,
  214159. left, right));
  214160. }
  214161. enabledOutputs = outputChannels;
  214162. enabledOutputs.setRange (outChannels.size(),
  214163. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  214164. false);
  214165. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  214166. outputBuffers.clear();
  214167. int numOuts = 0;
  214168. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  214169. {
  214170. float* left = 0;
  214171. if (enabledOutputs[i])
  214172. left = outputBuffers.getSampleData (numOuts++);
  214173. float* right = 0;
  214174. if (enabledOutputs[i + 1])
  214175. right = outputBuffers.getSampleData (numOuts++);
  214176. if (left != 0 || right != 0)
  214177. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  214178. dlh.outputGuids [outputDeviceIndex],
  214179. (int) sampleRate, bufferSizeSamples,
  214180. left, right));
  214181. }
  214182. String error;
  214183. // boost our priority while opening the devices to try to get better sync between them
  214184. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  214185. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  214186. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  214187. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  214188. for (i = 0; i < outChans.size(); ++i)
  214189. {
  214190. error = outChans[i]->open();
  214191. if (error.isNotEmpty())
  214192. {
  214193. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  214194. break;
  214195. }
  214196. }
  214197. if (error.isEmpty())
  214198. {
  214199. for (i = 0; i < inChans.size(); ++i)
  214200. {
  214201. error = inChans[i]->open();
  214202. if (error.isNotEmpty())
  214203. {
  214204. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  214205. break;
  214206. }
  214207. }
  214208. }
  214209. if (error.isEmpty())
  214210. {
  214211. totalSamplesOut = 0;
  214212. for (i = 0; i < outChans.size(); ++i)
  214213. outChans.getUnchecked(i)->synchronisePosition();
  214214. for (i = 0; i < inChans.size(); ++i)
  214215. inChans.getUnchecked(i)->synchronisePosition();
  214216. startThread (9);
  214217. sleep (10);
  214218. notify();
  214219. }
  214220. else
  214221. {
  214222. log (error);
  214223. }
  214224. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  214225. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  214226. return error;
  214227. }
  214228. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  214229. {
  214230. return new DSoundAudioIODeviceType();
  214231. }
  214232. #undef log
  214233. #endif
  214234. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  214235. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  214236. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214237. // compiled on its own).
  214238. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  214239. #if 1
  214240. const String getAudioErrorDesc (HRESULT hr)
  214241. {
  214242. const char* e = 0;
  214243. switch (hr)
  214244. {
  214245. case E_POINTER: e = "E_POINTER"; break;
  214246. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  214247. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  214248. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  214249. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  214250. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  214251. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  214252. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  214253. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  214254. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  214255. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  214256. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  214257. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  214258. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  214259. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  214260. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  214261. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  214262. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  214263. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  214264. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  214265. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  214266. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  214267. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  214268. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  214269. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  214270. default: return String::toHexString ((int) hr);
  214271. }
  214272. return e;
  214273. }
  214274. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse; } }
  214275. #define OK(a) wasapi_checkResult(a)
  214276. static bool wasapi_checkResult (HRESULT hr)
  214277. {
  214278. logFailure (hr);
  214279. return SUCCEEDED (hr);
  214280. }
  214281. #else
  214282. #define logFailure(hr) {}
  214283. #define OK(a) SUCCEEDED(a)
  214284. #endif
  214285. static const String wasapi_getDeviceID (IMMDevice* const device)
  214286. {
  214287. String s;
  214288. WCHAR* deviceId = 0;
  214289. if (OK (device->GetId (&deviceId)))
  214290. {
  214291. s = String (deviceId);
  214292. CoTaskMemFree (deviceId);
  214293. }
  214294. return s;
  214295. }
  214296. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  214297. {
  214298. EDataFlow flow = eRender;
  214299. ComSmartPtr <IMMEndpoint> endPoint;
  214300. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  214301. (void) OK (endPoint->GetDataFlow (&flow));
  214302. return flow;
  214303. }
  214304. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  214305. {
  214306. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  214307. }
  214308. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  214309. {
  214310. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  214311. : sizeof (WAVEFORMATEX));
  214312. }
  214313. class WASAPIDeviceBase
  214314. {
  214315. public:
  214316. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214317. : device (device_),
  214318. sampleRate (0),
  214319. numChannels (0),
  214320. actualNumChannels (0),
  214321. defaultSampleRate (0),
  214322. minBufferSize (0),
  214323. defaultBufferSize (0),
  214324. latencySamples (0),
  214325. useExclusiveMode (useExclusiveMode_)
  214326. {
  214327. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  214328. ComSmartPtr <IAudioClient> tempClient (createClient());
  214329. if (tempClient == 0)
  214330. return;
  214331. REFERENCE_TIME defaultPeriod, minPeriod;
  214332. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  214333. return;
  214334. WAVEFORMATEX* mixFormat = 0;
  214335. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  214336. return;
  214337. WAVEFORMATEXTENSIBLE format;
  214338. wasapi_copyWavFormat (format, mixFormat);
  214339. CoTaskMemFree (mixFormat);
  214340. actualNumChannels = numChannels = format.Format.nChannels;
  214341. defaultSampleRate = format.Format.nSamplesPerSec;
  214342. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  214343. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  214344. rates.addUsingDefaultSort (defaultSampleRate);
  214345. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214346. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  214347. {
  214348. if (ratesToTest[i] == defaultSampleRate)
  214349. continue;
  214350. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  214351. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214352. (WAVEFORMATEX*) &format, 0)))
  214353. if (! rates.contains (ratesToTest[i]))
  214354. rates.addUsingDefaultSort (ratesToTest[i]);
  214355. }
  214356. }
  214357. ~WASAPIDeviceBase()
  214358. {
  214359. device = 0;
  214360. CloseHandle (clientEvent);
  214361. }
  214362. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  214363. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  214364. {
  214365. sampleRate = newSampleRate;
  214366. channels = newChannels;
  214367. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  214368. numChannels = channels.getHighestBit() + 1;
  214369. if (numChannels == 0)
  214370. return true;
  214371. client = createClient();
  214372. if (client != 0
  214373. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  214374. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  214375. {
  214376. channelMaps.clear();
  214377. for (int i = 0; i <= channels.getHighestBit(); ++i)
  214378. if (channels[i])
  214379. channelMaps.add (i);
  214380. REFERENCE_TIME latency;
  214381. if (OK (client->GetStreamLatency (&latency)))
  214382. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  214383. (void) OK (client->GetBufferSize (&actualBufferSize));
  214384. return OK (client->SetEventHandle (clientEvent));
  214385. }
  214386. return false;
  214387. }
  214388. void closeClient()
  214389. {
  214390. if (client != 0)
  214391. client->Stop();
  214392. client = 0;
  214393. ResetEvent (clientEvent);
  214394. }
  214395. ComSmartPtr <IMMDevice> device;
  214396. ComSmartPtr <IAudioClient> client;
  214397. double sampleRate, defaultSampleRate;
  214398. int numChannels, actualNumChannels;
  214399. int minBufferSize, defaultBufferSize, latencySamples;
  214400. const bool useExclusiveMode;
  214401. Array <double> rates;
  214402. HANDLE clientEvent;
  214403. BigInteger channels;
  214404. AudioDataConverters::DataFormat dataFormat;
  214405. Array <int> channelMaps;
  214406. UINT32 actualBufferSize;
  214407. int bytesPerSample;
  214408. private:
  214409. const ComSmartPtr <IAudioClient> createClient()
  214410. {
  214411. ComSmartPtr <IAudioClient> client;
  214412. if (device != 0)
  214413. {
  214414. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  214415. logFailure (hr);
  214416. }
  214417. return client;
  214418. }
  214419. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  214420. {
  214421. WAVEFORMATEXTENSIBLE format;
  214422. zerostruct (format);
  214423. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  214424. {
  214425. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  214426. }
  214427. else
  214428. {
  214429. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  214430. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  214431. }
  214432. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  214433. format.Format.nChannels = (WORD) numChannels;
  214434. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  214435. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  214436. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  214437. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  214438. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  214439. switch (numChannels)
  214440. {
  214441. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  214442. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  214443. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214444. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214445. 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;
  214446. default: break;
  214447. }
  214448. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  214449. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214450. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  214451. logFailure (hr);
  214452. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  214453. {
  214454. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  214455. hr = S_OK;
  214456. }
  214457. CoTaskMemFree (nearestFormat);
  214458. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  214459. if (useExclusiveMode)
  214460. OK (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  214461. GUID session;
  214462. if (hr == S_OK
  214463. && OK (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214464. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  214465. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  214466. {
  214467. actualNumChannels = format.Format.nChannels;
  214468. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  214469. bytesPerSample = format.Format.wBitsPerSample / 8;
  214470. dataFormat = isFloat ? AudioDataConverters::float32LE
  214471. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  214472. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  214473. : AudioDataConverters::int16LE)));
  214474. return true;
  214475. }
  214476. return false;
  214477. }
  214478. WASAPIDeviceBase (const WASAPIDeviceBase&);
  214479. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  214480. };
  214481. class WASAPIInputDevice : public WASAPIDeviceBase
  214482. {
  214483. public:
  214484. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214485. : WASAPIDeviceBase (device_, useExclusiveMode_),
  214486. reservoir (1, 1)
  214487. {
  214488. }
  214489. ~WASAPIInputDevice()
  214490. {
  214491. close();
  214492. }
  214493. bool open (const double newSampleRate, const BigInteger& newChannels)
  214494. {
  214495. reservoirSize = 0;
  214496. reservoirCapacity = 16384;
  214497. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  214498. return openClient (newSampleRate, newChannels)
  214499. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  214500. }
  214501. void close()
  214502. {
  214503. closeClient();
  214504. captureClient = 0;
  214505. reservoir.setSize (0);
  214506. }
  214507. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  214508. {
  214509. if (numChannels <= 0)
  214510. return;
  214511. int offset = 0;
  214512. while (bufferSize > 0)
  214513. {
  214514. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  214515. {
  214516. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  214517. for (int i = 0; i < numDestBuffers; ++i)
  214518. {
  214519. float* const dest = destBuffers[i] + offset;
  214520. const int srcChan = channelMaps.getUnchecked(i);
  214521. switch (dataFormat)
  214522. {
  214523. case AudioDataConverters::float32LE:
  214524. AudioDataConverters::convertFloat32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214525. break;
  214526. case AudioDataConverters::int32LE:
  214527. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214528. break;
  214529. case AudioDataConverters::int24LE:
  214530. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  214531. break;
  214532. case AudioDataConverters::int16LE:
  214533. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  214534. break;
  214535. default: jassertfalse; break;
  214536. }
  214537. }
  214538. bufferSize -= samplesToDo;
  214539. offset += samplesToDo;
  214540. reservoirSize -= samplesToDo;
  214541. }
  214542. else
  214543. {
  214544. UINT32 packetLength = 0;
  214545. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  214546. break;
  214547. if (packetLength == 0)
  214548. {
  214549. if (thread.threadShouldExit())
  214550. break;
  214551. Thread::sleep (1);
  214552. continue;
  214553. }
  214554. uint8* inputData = 0;
  214555. UINT32 numSamplesAvailable;
  214556. DWORD flags;
  214557. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  214558. {
  214559. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  214560. for (int i = 0; i < numDestBuffers; ++i)
  214561. {
  214562. float* const dest = destBuffers[i] + offset;
  214563. const int srcChan = channelMaps.getUnchecked(i);
  214564. switch (dataFormat)
  214565. {
  214566. case AudioDataConverters::float32LE:
  214567. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214568. break;
  214569. case AudioDataConverters::int32LE:
  214570. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214571. break;
  214572. case AudioDataConverters::int24LE:
  214573. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  214574. break;
  214575. case AudioDataConverters::int16LE:
  214576. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  214577. break;
  214578. default: jassertfalse; break;
  214579. }
  214580. }
  214581. bufferSize -= samplesToDo;
  214582. offset += samplesToDo;
  214583. if (samplesToDo < (int) numSamplesAvailable)
  214584. {
  214585. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  214586. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  214587. bytesPerSample * actualNumChannels * reservoirSize);
  214588. }
  214589. captureClient->ReleaseBuffer (numSamplesAvailable);
  214590. }
  214591. }
  214592. }
  214593. }
  214594. ComSmartPtr <IAudioCaptureClient> captureClient;
  214595. MemoryBlock reservoir;
  214596. int reservoirSize, reservoirCapacity;
  214597. private:
  214598. WASAPIInputDevice (const WASAPIInputDevice&);
  214599. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  214600. };
  214601. class WASAPIOutputDevice : public WASAPIDeviceBase
  214602. {
  214603. public:
  214604. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214605. : WASAPIDeviceBase (device_, useExclusiveMode_)
  214606. {
  214607. }
  214608. ~WASAPIOutputDevice()
  214609. {
  214610. close();
  214611. }
  214612. bool open (const double newSampleRate, const BigInteger& newChannels)
  214613. {
  214614. return openClient (newSampleRate, newChannels)
  214615. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  214616. }
  214617. void close()
  214618. {
  214619. closeClient();
  214620. renderClient = 0;
  214621. }
  214622. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  214623. {
  214624. if (numChannels <= 0)
  214625. return;
  214626. int offset = 0;
  214627. while (bufferSize > 0)
  214628. {
  214629. UINT32 padding = 0;
  214630. if (! OK (client->GetCurrentPadding (&padding)))
  214631. return;
  214632. int samplesToDo = useExclusiveMode ? bufferSize
  214633. : jmin ((int) (actualBufferSize - padding), bufferSize);
  214634. if (samplesToDo <= 0)
  214635. {
  214636. if (thread.threadShouldExit())
  214637. break;
  214638. Thread::sleep (0);
  214639. continue;
  214640. }
  214641. uint8* outputData = 0;
  214642. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  214643. {
  214644. for (int i = 0; i < numSrcBuffers; ++i)
  214645. {
  214646. const float* const source = srcBuffers[i] + offset;
  214647. const int destChan = channelMaps.getUnchecked(i);
  214648. switch (dataFormat)
  214649. {
  214650. case AudioDataConverters::float32LE:
  214651. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  214652. break;
  214653. case AudioDataConverters::int32LE:
  214654. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  214655. break;
  214656. case AudioDataConverters::int24LE:
  214657. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  214658. break;
  214659. case AudioDataConverters::int16LE:
  214660. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  214661. break;
  214662. default: jassertfalse; break;
  214663. }
  214664. }
  214665. renderClient->ReleaseBuffer (samplesToDo, 0);
  214666. offset += samplesToDo;
  214667. bufferSize -= samplesToDo;
  214668. }
  214669. }
  214670. }
  214671. ComSmartPtr <IAudioRenderClient> renderClient;
  214672. private:
  214673. WASAPIOutputDevice (const WASAPIOutputDevice&);
  214674. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  214675. };
  214676. class WASAPIAudioIODevice : public AudioIODevice,
  214677. public Thread
  214678. {
  214679. public:
  214680. WASAPIAudioIODevice (const String& deviceName,
  214681. const String& outputDeviceId_,
  214682. const String& inputDeviceId_,
  214683. const bool useExclusiveMode_)
  214684. : AudioIODevice (deviceName, "Windows Audio"),
  214685. Thread ("Juce WASAPI"),
  214686. isOpen_ (false),
  214687. isStarted (false),
  214688. outputDevice (0),
  214689. outputDeviceId (outputDeviceId_),
  214690. inputDevice (0),
  214691. inputDeviceId (inputDeviceId_),
  214692. useExclusiveMode (useExclusiveMode_),
  214693. currentBufferSizeSamples (0),
  214694. currentSampleRate (0),
  214695. callback (0)
  214696. {
  214697. }
  214698. ~WASAPIAudioIODevice()
  214699. {
  214700. close();
  214701. deleteAndZero (inputDevice);
  214702. deleteAndZero (outputDevice);
  214703. }
  214704. bool initialise()
  214705. {
  214706. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  214707. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  214708. latencyIn = latencyOut = 0;
  214709. Array <double> ratesIn, ratesOut;
  214710. if (createDevices())
  214711. {
  214712. jassert (inputDevice != 0 || outputDevice != 0);
  214713. if (inputDevice != 0 && outputDevice != 0)
  214714. {
  214715. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  214716. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  214717. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  214718. sampleRates = inputDevice->rates;
  214719. sampleRates.removeValuesNotIn (outputDevice->rates);
  214720. }
  214721. else
  214722. {
  214723. WASAPIDeviceBase* const d = inputDevice != 0 ? (WASAPIDeviceBase*) inputDevice : (WASAPIDeviceBase*) outputDevice;
  214724. defaultSampleRate = d->defaultSampleRate;
  214725. minBufferSize = d->minBufferSize;
  214726. defaultBufferSize = d->defaultBufferSize;
  214727. sampleRates = d->rates;
  214728. }
  214729. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  214730. if (minBufferSize != defaultBufferSize)
  214731. bufferSizes.addUsingDefaultSort (minBufferSize);
  214732. int n = 64;
  214733. for (int i = 0; i < 40; ++i)
  214734. {
  214735. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  214736. bufferSizes.addUsingDefaultSort (n);
  214737. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  214738. }
  214739. return true;
  214740. }
  214741. return false;
  214742. }
  214743. const StringArray getOutputChannelNames()
  214744. {
  214745. StringArray outChannels;
  214746. if (outputDevice != 0)
  214747. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  214748. outChannels.add ("Output channel " + String (i));
  214749. return outChannels;
  214750. }
  214751. const StringArray getInputChannelNames()
  214752. {
  214753. StringArray inChannels;
  214754. if (inputDevice != 0)
  214755. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  214756. inChannels.add ("Input channel " + String (i));
  214757. return inChannels;
  214758. }
  214759. int getNumSampleRates() { return sampleRates.size(); }
  214760. double getSampleRate (int index) { return sampleRates [index]; }
  214761. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  214762. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  214763. int getDefaultBufferSize() { return defaultBufferSize; }
  214764. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  214765. double getCurrentSampleRate() { return currentSampleRate; }
  214766. int getCurrentBitDepth() { return 32; }
  214767. int getOutputLatencyInSamples() { return latencyOut; }
  214768. int getInputLatencyInSamples() { return latencyIn; }
  214769. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  214770. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  214771. const String getLastError() { return lastError; }
  214772. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  214773. double sampleRate, int bufferSizeSamples)
  214774. {
  214775. close();
  214776. lastError = String::empty;
  214777. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  214778. {
  214779. lastError = "The input and output devices don't share a common sample rate!";
  214780. return lastError;
  214781. }
  214782. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  214783. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  214784. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  214785. {
  214786. lastError = "Couldn't open the input device!";
  214787. return lastError;
  214788. }
  214789. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  214790. {
  214791. close();
  214792. lastError = "Couldn't open the output device!";
  214793. return lastError;
  214794. }
  214795. if (inputDevice != 0)
  214796. ResetEvent (inputDevice->clientEvent);
  214797. if (outputDevice != 0)
  214798. ResetEvent (outputDevice->clientEvent);
  214799. startThread (8);
  214800. Thread::sleep (5);
  214801. if (inputDevice != 0 && inputDevice->client != 0)
  214802. {
  214803. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  214804. HRESULT hr = inputDevice->client->Start();
  214805. logFailure (hr); //xxx handle this
  214806. }
  214807. if (outputDevice != 0 && outputDevice->client != 0)
  214808. {
  214809. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  214810. HRESULT hr = outputDevice->client->Start();
  214811. logFailure (hr); //xxx handle this
  214812. }
  214813. isOpen_ = true;
  214814. return lastError;
  214815. }
  214816. void close()
  214817. {
  214818. stop();
  214819. if (inputDevice != 0)
  214820. SetEvent (inputDevice->clientEvent);
  214821. if (outputDevice != 0)
  214822. SetEvent (outputDevice->clientEvent);
  214823. stopThread (5000);
  214824. if (inputDevice != 0)
  214825. inputDevice->close();
  214826. if (outputDevice != 0)
  214827. outputDevice->close();
  214828. isOpen_ = false;
  214829. }
  214830. bool isOpen() { return isOpen_ && isThreadRunning(); }
  214831. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  214832. void start (AudioIODeviceCallback* call)
  214833. {
  214834. if (isOpen_ && call != 0 && ! isStarted)
  214835. {
  214836. if (! isThreadRunning())
  214837. {
  214838. // something's gone wrong and the thread's stopped..
  214839. isOpen_ = false;
  214840. return;
  214841. }
  214842. call->audioDeviceAboutToStart (this);
  214843. const ScopedLock sl (startStopLock);
  214844. callback = call;
  214845. isStarted = true;
  214846. }
  214847. }
  214848. void stop()
  214849. {
  214850. if (isStarted)
  214851. {
  214852. AudioIODeviceCallback* const callbackLocal = callback;
  214853. {
  214854. const ScopedLock sl (startStopLock);
  214855. isStarted = false;
  214856. }
  214857. if (callbackLocal != 0)
  214858. callbackLocal->audioDeviceStopped();
  214859. }
  214860. }
  214861. void setMMThreadPriority()
  214862. {
  214863. DynamicLibraryLoader dll ("avrt.dll");
  214864. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  214865. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  214866. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  214867. {
  214868. DWORD dummy = 0;
  214869. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  214870. if (h != 0)
  214871. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  214872. }
  214873. }
  214874. void run()
  214875. {
  214876. setMMThreadPriority();
  214877. const int bufferSize = currentBufferSizeSamples;
  214878. HANDLE events[2];
  214879. int numEvents = 0;
  214880. if (inputDevice != 0)
  214881. events [numEvents++] = inputDevice->clientEvent;
  214882. if (outputDevice != 0)
  214883. events [numEvents++] = outputDevice->clientEvent;
  214884. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  214885. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  214886. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  214887. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  214888. float** const inputBuffers = ins.getArrayOfChannels();
  214889. float** const outputBuffers = outs.getArrayOfChannels();
  214890. ins.clear();
  214891. while (! threadShouldExit())
  214892. {
  214893. const DWORD result = useExclusiveMode ? WaitForSingleObject (inputDevice->clientEvent, 1000)
  214894. : WaitForMultipleObjects (numEvents, events, true, 1000);
  214895. if (result == WAIT_TIMEOUT)
  214896. continue;
  214897. if (threadShouldExit())
  214898. break;
  214899. if (inputDevice != 0)
  214900. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  214901. // Make the callback..
  214902. {
  214903. const ScopedLock sl (startStopLock);
  214904. if (isStarted)
  214905. {
  214906. JUCE_TRY
  214907. {
  214908. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  214909. numInputBuffers,
  214910. outputBuffers,
  214911. numOutputBuffers,
  214912. bufferSize);
  214913. }
  214914. JUCE_CATCH_EXCEPTION
  214915. }
  214916. else
  214917. {
  214918. outs.clear();
  214919. }
  214920. }
  214921. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  214922. continue;
  214923. if (outputDevice != 0)
  214924. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  214925. }
  214926. }
  214927. juce_UseDebuggingNewOperator
  214928. String outputDeviceId, inputDeviceId;
  214929. String lastError;
  214930. private:
  214931. // Device stats...
  214932. WASAPIInputDevice* inputDevice;
  214933. WASAPIOutputDevice* outputDevice;
  214934. const bool useExclusiveMode;
  214935. double defaultSampleRate;
  214936. int minBufferSize, defaultBufferSize;
  214937. int latencyIn, latencyOut;
  214938. Array <double> sampleRates;
  214939. Array <int> bufferSizes;
  214940. // Active state...
  214941. bool isOpen_, isStarted;
  214942. int currentBufferSizeSamples;
  214943. double currentSampleRate;
  214944. AudioIODeviceCallback* callback;
  214945. CriticalSection startStopLock;
  214946. bool createDevices()
  214947. {
  214948. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  214949. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  214950. return false;
  214951. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  214952. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  214953. return false;
  214954. UINT32 numDevices = 0;
  214955. if (! OK (deviceCollection->GetCount (&numDevices)))
  214956. return false;
  214957. for (UINT32 i = 0; i < numDevices; ++i)
  214958. {
  214959. ComSmartPtr <IMMDevice> device;
  214960. if (! OK (deviceCollection->Item (i, &device)))
  214961. continue;
  214962. const String deviceId (wasapi_getDeviceID (device));
  214963. if (deviceId.isEmpty())
  214964. continue;
  214965. const EDataFlow flow = wasapi_getDataFlow (device);
  214966. if (deviceId == inputDeviceId && flow == eCapture)
  214967. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  214968. else if (deviceId == outputDeviceId && flow == eRender)
  214969. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  214970. }
  214971. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  214972. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  214973. }
  214974. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  214975. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  214976. };
  214977. class WASAPIAudioIODeviceType : public AudioIODeviceType
  214978. {
  214979. public:
  214980. WASAPIAudioIODeviceType()
  214981. : AudioIODeviceType ("Windows Audio"),
  214982. hasScanned (false)
  214983. {
  214984. }
  214985. ~WASAPIAudioIODeviceType()
  214986. {
  214987. }
  214988. void scanForDevices()
  214989. {
  214990. hasScanned = true;
  214991. outputDeviceNames.clear();
  214992. inputDeviceNames.clear();
  214993. outputDeviceIds.clear();
  214994. inputDeviceIds.clear();
  214995. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  214996. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  214997. return;
  214998. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  214999. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  215000. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215001. UINT32 numDevices = 0;
  215002. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  215003. && OK (deviceCollection->GetCount (&numDevices))))
  215004. return;
  215005. for (UINT32 i = 0; i < numDevices; ++i)
  215006. {
  215007. ComSmartPtr <IMMDevice> device;
  215008. if (! OK (deviceCollection->Item (i, &device)))
  215009. continue;
  215010. const String deviceId (wasapi_getDeviceID (device));
  215011. DWORD state = 0;
  215012. if (! OK (device->GetState (&state)))
  215013. continue;
  215014. if (state != DEVICE_STATE_ACTIVE)
  215015. continue;
  215016. String name;
  215017. {
  215018. ComSmartPtr <IPropertyStore> properties;
  215019. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  215020. continue;
  215021. PROPVARIANT value;
  215022. PropVariantInit (&value);
  215023. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  215024. name = value.pwszVal;
  215025. PropVariantClear (&value);
  215026. }
  215027. const EDataFlow flow = wasapi_getDataFlow (device);
  215028. if (flow == eRender)
  215029. {
  215030. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  215031. outputDeviceIds.insert (index, deviceId);
  215032. outputDeviceNames.insert (index, name);
  215033. }
  215034. else if (flow == eCapture)
  215035. {
  215036. const int index = (deviceId == defaultCapture) ? 0 : -1;
  215037. inputDeviceIds.insert (index, deviceId);
  215038. inputDeviceNames.insert (index, name);
  215039. }
  215040. }
  215041. inputDeviceNames.appendNumbersToDuplicates (false, false);
  215042. outputDeviceNames.appendNumbersToDuplicates (false, false);
  215043. }
  215044. const StringArray getDeviceNames (bool wantInputNames) const
  215045. {
  215046. jassert (hasScanned); // need to call scanForDevices() before doing this
  215047. return wantInputNames ? inputDeviceNames
  215048. : outputDeviceNames;
  215049. }
  215050. int getDefaultDeviceIndex (bool /*forInput*/) const
  215051. {
  215052. jassert (hasScanned); // need to call scanForDevices() before doing this
  215053. return 0;
  215054. }
  215055. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215056. {
  215057. jassert (hasScanned); // need to call scanForDevices() before doing this
  215058. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  215059. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  215060. : outputDeviceIds.indexOf (d->outputDeviceId));
  215061. }
  215062. bool hasSeparateInputsAndOutputs() const { return true; }
  215063. AudioIODevice* createDevice (const String& outputDeviceName,
  215064. const String& inputDeviceName)
  215065. {
  215066. jassert (hasScanned); // need to call scanForDevices() before doing this
  215067. const bool useExclusiveMode = false;
  215068. ScopedPointer<WASAPIAudioIODevice> device;
  215069. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215070. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215071. if (outputIndex >= 0 || inputIndex >= 0)
  215072. {
  215073. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215074. : inputDeviceName,
  215075. outputDeviceIds [outputIndex],
  215076. inputDeviceIds [inputIndex],
  215077. useExclusiveMode);
  215078. if (! device->initialise())
  215079. device = 0;
  215080. }
  215081. return device.release();
  215082. }
  215083. juce_UseDebuggingNewOperator
  215084. StringArray outputDeviceNames, outputDeviceIds;
  215085. StringArray inputDeviceNames, inputDeviceIds;
  215086. private:
  215087. bool hasScanned;
  215088. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  215089. {
  215090. String s;
  215091. IMMDevice* dev = 0;
  215092. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  215093. eMultimedia, &dev)))
  215094. {
  215095. WCHAR* deviceId = 0;
  215096. if (OK (dev->GetId (&deviceId)))
  215097. {
  215098. s = String (deviceId);
  215099. CoTaskMemFree (deviceId);
  215100. }
  215101. dev->Release();
  215102. }
  215103. return s;
  215104. }
  215105. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  215106. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  215107. };
  215108. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  215109. {
  215110. return new WASAPIAudioIODeviceType();
  215111. }
  215112. #undef logFailure
  215113. #undef OK
  215114. #endif
  215115. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  215116. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  215117. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215118. // compiled on its own).
  215119. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  215120. class DShowCameraDeviceInteral : public ChangeBroadcaster
  215121. {
  215122. public:
  215123. DShowCameraDeviceInteral (CameraDevice* const owner_,
  215124. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  215125. const ComSmartPtr <IBaseFilter>& filter_,
  215126. int minWidth, int minHeight,
  215127. int maxWidth, int maxHeight)
  215128. : owner (owner_),
  215129. captureGraphBuilder (captureGraphBuilder_),
  215130. filter (filter_),
  215131. ok (false),
  215132. imageNeedsFlipping (false),
  215133. width (0),
  215134. height (0),
  215135. activeUsers (0),
  215136. recordNextFrameTime (false)
  215137. {
  215138. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  215139. if (FAILED (hr))
  215140. return;
  215141. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  215142. if (FAILED (hr))
  215143. return;
  215144. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  215145. if (FAILED (hr))
  215146. return;
  215147. {
  215148. ComSmartPtr <IAMStreamConfig> streamConfig;
  215149. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  215150. IID_IAMStreamConfig, (void**) &streamConfig);
  215151. if (streamConfig != 0)
  215152. {
  215153. getVideoSizes (streamConfig);
  215154. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  215155. return;
  215156. }
  215157. }
  215158. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  215159. if (FAILED (hr))
  215160. return;
  215161. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  215162. if (FAILED (hr))
  215163. return;
  215164. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  215165. if (FAILED (hr))
  215166. return;
  215167. if (! connectFilters (filter, smartTee))
  215168. return;
  215169. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  215170. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  215171. if (FAILED (hr))
  215172. return;
  215173. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  215174. if (FAILED (hr))
  215175. return;
  215176. AM_MEDIA_TYPE mt;
  215177. zerostruct (mt);
  215178. mt.majortype = MEDIATYPE_Video;
  215179. mt.subtype = MEDIASUBTYPE_RGB24;
  215180. mt.formattype = FORMAT_VideoInfo;
  215181. sampleGrabber->SetMediaType (&mt);
  215182. callback = new GrabberCallback (*this);
  215183. sampleGrabber->SetCallback (callback, 1);
  215184. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  215185. if (FAILED (hr))
  215186. return;
  215187. ComSmartPtr <IPin> grabberInputPin;
  215188. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  215189. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  215190. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  215191. return;
  215192. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  215193. if (FAILED (hr))
  215194. return;
  215195. zerostruct (mt);
  215196. hr = sampleGrabber->GetConnectedMediaType (&mt);
  215197. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  215198. width = pVih->bmiHeader.biWidth;
  215199. height = pVih->bmiHeader.biHeight;
  215200. ComSmartPtr <IBaseFilter> nullFilter;
  215201. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  215202. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  215203. if (connectFilters (sampleGrabberBase, nullFilter)
  215204. && addGraphToRot())
  215205. {
  215206. activeImage = Image (Image::RGB, width, height, true);
  215207. loadingImage = Image (Image::RGB, width, height, true);
  215208. ok = true;
  215209. }
  215210. }
  215211. ~DShowCameraDeviceInteral()
  215212. {
  215213. if (mediaControl != 0)
  215214. mediaControl->Stop();
  215215. removeGraphFromRot();
  215216. for (int i = viewerComps.size(); --i >= 0;)
  215217. viewerComps.getUnchecked(i)->ownerDeleted();
  215218. callback = 0;
  215219. graphBuilder = 0;
  215220. sampleGrabber = 0;
  215221. mediaControl = 0;
  215222. filter = 0;
  215223. captureGraphBuilder = 0;
  215224. smartTee = 0;
  215225. smartTeePreviewOutputPin = 0;
  215226. smartTeeCaptureOutputPin = 0;
  215227. asfWriter = 0;
  215228. }
  215229. void addUser()
  215230. {
  215231. if (ok && activeUsers++ == 0)
  215232. mediaControl->Run();
  215233. }
  215234. void removeUser()
  215235. {
  215236. if (ok && --activeUsers == 0)
  215237. mediaControl->Stop();
  215238. }
  215239. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  215240. {
  215241. if (recordNextFrameTime)
  215242. {
  215243. const double defaultCameraLatency = 0.1;
  215244. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  215245. recordNextFrameTime = false;
  215246. ComSmartPtr <IPin> pin;
  215247. if (getPin (filter, PINDIR_OUTPUT, &pin))
  215248. {
  215249. ComSmartPtr <IAMPushSource> pushSource;
  215250. HRESULT hr = pin->QueryInterface (IID_IAMPushSource, (void**) &pushSource);
  215251. if (pushSource != 0)
  215252. {
  215253. REFERENCE_TIME latency = 0;
  215254. hr = pushSource->GetLatency (&latency);
  215255. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  215256. }
  215257. }
  215258. }
  215259. {
  215260. const int lineStride = width * 3;
  215261. const ScopedLock sl (imageSwapLock);
  215262. {
  215263. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  215264. for (int i = 0; i < height; ++i)
  215265. memcpy (destData.getLinePointer ((height - 1) - i),
  215266. buffer + lineStride * i,
  215267. lineStride);
  215268. }
  215269. imageNeedsFlipping = true;
  215270. }
  215271. if (listeners.size() > 0)
  215272. callListeners (loadingImage);
  215273. sendChangeMessage (this);
  215274. }
  215275. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  215276. {
  215277. if (imageNeedsFlipping)
  215278. {
  215279. const ScopedLock sl (imageSwapLock);
  215280. swapVariables (loadingImage, activeImage);
  215281. imageNeedsFlipping = false;
  215282. }
  215283. RectanglePlacement rp (RectanglePlacement::centred);
  215284. double dx = 0, dy = 0, dw = width, dh = height;
  215285. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  215286. const int rx = roundToInt (dx), ry = roundToInt (dy);
  215287. const int rw = roundToInt (dw), rh = roundToInt (dh);
  215288. g.saveState();
  215289. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  215290. g.fillAll (Colours::black);
  215291. g.restoreState();
  215292. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  215293. }
  215294. bool createFileCaptureFilter (const File& file)
  215295. {
  215296. removeFileCaptureFilter();
  215297. file.deleteFile();
  215298. mediaControl->Stop();
  215299. firstRecordedTime = Time();
  215300. recordNextFrameTime = true;
  215301. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  215302. if (SUCCEEDED (hr))
  215303. {
  215304. ComSmartPtr <IFileSinkFilter> fileSink;
  215305. hr = asfWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  215306. if (SUCCEEDED (hr))
  215307. {
  215308. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  215309. if (SUCCEEDED (hr))
  215310. {
  215311. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  215312. if (SUCCEEDED (hr))
  215313. {
  215314. ComSmartPtr <IConfigAsfWriter> asfConfig;
  215315. hr = asfWriter->QueryInterface (IID_IConfigAsfWriter, (void**) &asfConfig);
  215316. asfConfig->SetIndexMode (true);
  215317. ComSmartPtr <IWMProfileManager> profileManager;
  215318. hr = WMCreateProfileManager (&profileManager);
  215319. // This gibberish is the DirectShow profile for a video-only wmv file.
  215320. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\"><streamconfig "
  215321. "majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  215322. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\"><videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  215323. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" btemporalcompression=\"1\" lsamplesize=\"0\"> <videoinfoheader "
  215324. "dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"100000\"><rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <rctarget "
  215325. "left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  215326. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" biclrused=\"0\" biclrimportant=\"0\"/> "
  215327. "</videoinfoheader></wmmediatype></streamconfig></profile>");
  215328. prof = prof.replace ("$WIDTH", String (width))
  215329. .replace ("$HEIGHT", String (height));
  215330. ComSmartPtr <IWMProfile> currentProfile;
  215331. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, &currentProfile);
  215332. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  215333. if (SUCCEEDED (hr))
  215334. {
  215335. ComSmartPtr <IPin> asfWriterInputPin;
  215336. if (getPin (asfWriter, PINDIR_INPUT, &asfWriterInputPin, "Video Input 01"))
  215337. {
  215338. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  215339. if (SUCCEEDED (hr)
  215340. && ok && activeUsers > 0
  215341. && SUCCEEDED (mediaControl->Run()))
  215342. {
  215343. return true;
  215344. }
  215345. }
  215346. }
  215347. }
  215348. }
  215349. }
  215350. }
  215351. removeFileCaptureFilter();
  215352. if (ok && activeUsers > 0)
  215353. mediaControl->Run();
  215354. return false;
  215355. }
  215356. void removeFileCaptureFilter()
  215357. {
  215358. mediaControl->Stop();
  215359. if (asfWriter != 0)
  215360. {
  215361. graphBuilder->RemoveFilter (asfWriter);
  215362. asfWriter = 0;
  215363. }
  215364. if (ok && activeUsers > 0)
  215365. mediaControl->Run();
  215366. }
  215367. void addListener (CameraDevice::Listener* listenerToAdd)
  215368. {
  215369. const ScopedLock sl (listenerLock);
  215370. if (listeners.size() == 0)
  215371. addUser();
  215372. listeners.addIfNotAlreadyThere (listenerToAdd);
  215373. }
  215374. void removeListener (CameraDevice::Listener* listenerToRemove)
  215375. {
  215376. const ScopedLock sl (listenerLock);
  215377. listeners.removeValue (listenerToRemove);
  215378. if (listeners.size() == 0)
  215379. removeUser();
  215380. }
  215381. void callListeners (const Image& image)
  215382. {
  215383. const ScopedLock sl (listenerLock);
  215384. for (int i = listeners.size(); --i >= 0;)
  215385. {
  215386. CameraDevice::Listener* const l = listeners[i];
  215387. if (l != 0)
  215388. l->imageReceived (image);
  215389. }
  215390. }
  215391. class DShowCaptureViewerComp : public Component,
  215392. public ChangeListener
  215393. {
  215394. public:
  215395. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  215396. : owner (owner_)
  215397. {
  215398. setOpaque (true);
  215399. owner->addChangeListener (this);
  215400. owner->addUser();
  215401. owner->viewerComps.add (this);
  215402. setSize (owner_->width, owner_->height);
  215403. }
  215404. ~DShowCaptureViewerComp()
  215405. {
  215406. if (owner != 0)
  215407. {
  215408. owner->viewerComps.removeValue (this);
  215409. owner->removeUser();
  215410. owner->removeChangeListener (this);
  215411. }
  215412. }
  215413. void ownerDeleted()
  215414. {
  215415. owner = 0;
  215416. }
  215417. void paint (Graphics& g)
  215418. {
  215419. g.setColour (Colours::black);
  215420. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  215421. if (owner != 0)
  215422. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  215423. else
  215424. g.fillAll (Colours::black);
  215425. }
  215426. void changeListenerCallback (void*)
  215427. {
  215428. repaint();
  215429. }
  215430. private:
  215431. DShowCameraDeviceInteral* owner;
  215432. };
  215433. bool ok;
  215434. int width, height;
  215435. Time firstRecordedTime;
  215436. Array <DShowCaptureViewerComp*> viewerComps;
  215437. private:
  215438. CameraDevice* const owner;
  215439. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215440. ComSmartPtr <IBaseFilter> filter;
  215441. ComSmartPtr <IBaseFilter> smartTee;
  215442. ComSmartPtr <IGraphBuilder> graphBuilder;
  215443. ComSmartPtr <ISampleGrabber> sampleGrabber;
  215444. ComSmartPtr <IMediaControl> mediaControl;
  215445. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  215446. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  215447. ComSmartPtr <IBaseFilter> asfWriter;
  215448. int activeUsers;
  215449. Array <int> widths, heights;
  215450. DWORD graphRegistrationID;
  215451. CriticalSection imageSwapLock;
  215452. bool imageNeedsFlipping;
  215453. Image loadingImage;
  215454. Image activeImage;
  215455. bool recordNextFrameTime;
  215456. void getVideoSizes (IAMStreamConfig* const streamConfig)
  215457. {
  215458. widths.clear();
  215459. heights.clear();
  215460. int count = 0, size = 0;
  215461. streamConfig->GetNumberOfCapabilities (&count, &size);
  215462. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215463. {
  215464. for (int i = 0; i < count; ++i)
  215465. {
  215466. VIDEO_STREAM_CONFIG_CAPS scc;
  215467. AM_MEDIA_TYPE* config;
  215468. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215469. if (SUCCEEDED (hr))
  215470. {
  215471. const int w = scc.InputSize.cx;
  215472. const int h = scc.InputSize.cy;
  215473. bool duplicate = false;
  215474. for (int j = widths.size(); --j >= 0;)
  215475. {
  215476. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  215477. {
  215478. duplicate = true;
  215479. break;
  215480. }
  215481. }
  215482. if (! duplicate)
  215483. {
  215484. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  215485. widths.add (w);
  215486. heights.add (h);
  215487. }
  215488. deleteMediaType (config);
  215489. }
  215490. }
  215491. }
  215492. }
  215493. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  215494. const int minWidth, const int minHeight,
  215495. const int maxWidth, const int maxHeight)
  215496. {
  215497. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  215498. streamConfig->GetNumberOfCapabilities (&count, &size);
  215499. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215500. {
  215501. AM_MEDIA_TYPE* config;
  215502. VIDEO_STREAM_CONFIG_CAPS scc;
  215503. for (int i = 0; i < count; ++i)
  215504. {
  215505. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215506. if (SUCCEEDED (hr))
  215507. {
  215508. if (scc.InputSize.cx >= minWidth
  215509. && scc.InputSize.cy >= minHeight
  215510. && scc.InputSize.cx <= maxWidth
  215511. && scc.InputSize.cy <= maxHeight)
  215512. {
  215513. int area = scc.InputSize.cx * scc.InputSize.cy;
  215514. if (area > bestArea)
  215515. {
  215516. bestIndex = i;
  215517. bestArea = area;
  215518. }
  215519. }
  215520. deleteMediaType (config);
  215521. }
  215522. }
  215523. if (bestIndex >= 0)
  215524. {
  215525. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  215526. hr = streamConfig->SetFormat (config);
  215527. deleteMediaType (config);
  215528. return SUCCEEDED (hr);
  215529. }
  215530. }
  215531. return false;
  215532. }
  215533. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  215534. {
  215535. ComSmartPtr <IEnumPins> enumerator;
  215536. ComSmartPtr <IPin> pin;
  215537. filter->EnumPins (&enumerator);
  215538. while (enumerator->Next (1, &pin, 0) == S_OK)
  215539. {
  215540. PIN_DIRECTION dir;
  215541. pin->QueryDirection (&dir);
  215542. if (wantedDirection == dir)
  215543. {
  215544. PIN_INFO info;
  215545. zerostruct (info);
  215546. pin->QueryPinInfo (&info);
  215547. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  215548. {
  215549. pin->AddRef();
  215550. *result = pin;
  215551. return true;
  215552. }
  215553. }
  215554. }
  215555. return false;
  215556. }
  215557. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  215558. {
  215559. ComSmartPtr <IPin> in, out;
  215560. return getPin (first, PINDIR_OUTPUT, &out)
  215561. && getPin (second, PINDIR_INPUT, &in)
  215562. && SUCCEEDED (graphBuilder->Connect (out, in));
  215563. }
  215564. bool addGraphToRot()
  215565. {
  215566. ComSmartPtr <IRunningObjectTable> rot;
  215567. if (FAILED (GetRunningObjectTable (0, &rot)))
  215568. return false;
  215569. ComSmartPtr <IMoniker> moniker;
  215570. WCHAR buffer[128];
  215571. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  215572. if (FAILED (hr))
  215573. return false;
  215574. graphRegistrationID = 0;
  215575. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  215576. }
  215577. void removeGraphFromRot()
  215578. {
  215579. ComSmartPtr <IRunningObjectTable> rot;
  215580. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  215581. rot->Revoke (graphRegistrationID);
  215582. }
  215583. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  215584. {
  215585. if (pmt->cbFormat != 0)
  215586. CoTaskMemFree ((PVOID) pmt->pbFormat);
  215587. if (pmt->pUnk != 0)
  215588. pmt->pUnk->Release();
  215589. CoTaskMemFree (pmt);
  215590. }
  215591. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  215592. {
  215593. public:
  215594. GrabberCallback (DShowCameraDeviceInteral& owner_)
  215595. : owner (owner_)
  215596. {
  215597. }
  215598. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  215599. {
  215600. return E_FAIL;
  215601. }
  215602. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  215603. {
  215604. owner.handleFrame (time, buffer, bufferSize);
  215605. return S_OK;
  215606. }
  215607. private:
  215608. DShowCameraDeviceInteral& owner;
  215609. GrabberCallback (const GrabberCallback&);
  215610. GrabberCallback& operator= (const GrabberCallback&);
  215611. };
  215612. ComSmartPtr <GrabberCallback> callback;
  215613. Array <CameraDevice::Listener*> listeners;
  215614. CriticalSection listenerLock;
  215615. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  215616. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  215617. };
  215618. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  215619. : name (name_)
  215620. {
  215621. isRecording = false;
  215622. }
  215623. CameraDevice::~CameraDevice()
  215624. {
  215625. stopRecording();
  215626. delete static_cast <DShowCameraDeviceInteral*> (internal);
  215627. internal = 0;
  215628. }
  215629. Component* CameraDevice::createViewerComponent()
  215630. {
  215631. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  215632. }
  215633. const String CameraDevice::getFileExtension()
  215634. {
  215635. return ".wmv";
  215636. }
  215637. void CameraDevice::startRecordingToFile (const File& file, int quality)
  215638. {
  215639. stopRecording();
  215640. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215641. d->addUser();
  215642. isRecording = d->createFileCaptureFilter (file);
  215643. }
  215644. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  215645. {
  215646. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215647. return d->firstRecordedTime;
  215648. }
  215649. void CameraDevice::stopRecording()
  215650. {
  215651. if (isRecording)
  215652. {
  215653. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215654. d->removeFileCaptureFilter();
  215655. d->removeUser();
  215656. isRecording = false;
  215657. }
  215658. }
  215659. void CameraDevice::addListener (Listener* listenerToAdd)
  215660. {
  215661. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215662. if (listenerToAdd != 0)
  215663. d->addListener (listenerToAdd);
  215664. }
  215665. void CameraDevice::removeListener (Listener* listenerToRemove)
  215666. {
  215667. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215668. if (listenerToRemove != 0)
  215669. d->removeListener (listenerToRemove);
  215670. }
  215671. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  215672. const int deviceIndexToOpen,
  215673. String& name)
  215674. {
  215675. int index = 0;
  215676. ComSmartPtr <IBaseFilter> result;
  215677. ComSmartPtr <ICreateDevEnum> pDevEnum;
  215678. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  215679. if (SUCCEEDED (hr))
  215680. {
  215681. ComSmartPtr <IEnumMoniker> enumerator;
  215682. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  215683. if (SUCCEEDED (hr) && enumerator != 0)
  215684. {
  215685. ComSmartPtr <IBaseFilter> captureFilter;
  215686. ComSmartPtr <IMoniker> moniker;
  215687. ULONG fetched;
  215688. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  215689. {
  215690. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  215691. if (SUCCEEDED (hr))
  215692. {
  215693. ComSmartPtr <IPropertyBag> propertyBag;
  215694. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  215695. if (SUCCEEDED (hr))
  215696. {
  215697. VARIANT var;
  215698. var.vt = VT_BSTR;
  215699. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  215700. propertyBag = 0;
  215701. if (SUCCEEDED (hr))
  215702. {
  215703. if (names != 0)
  215704. names->add (var.bstrVal);
  215705. if (index == deviceIndexToOpen)
  215706. {
  215707. name = var.bstrVal;
  215708. result = captureFilter;
  215709. captureFilter = 0;
  215710. break;
  215711. }
  215712. ++index;
  215713. }
  215714. moniker = 0;
  215715. }
  215716. captureFilter = 0;
  215717. }
  215718. }
  215719. }
  215720. }
  215721. return result;
  215722. }
  215723. const StringArray CameraDevice::getAvailableDevices()
  215724. {
  215725. StringArray devs;
  215726. String dummy;
  215727. enumerateCameras (&devs, -1, dummy);
  215728. return devs;
  215729. }
  215730. CameraDevice* CameraDevice::openDevice (int index,
  215731. int minWidth, int minHeight,
  215732. int maxWidth, int maxHeight)
  215733. {
  215734. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215735. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  215736. if (SUCCEEDED (hr))
  215737. {
  215738. String name;
  215739. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  215740. if (filter != 0)
  215741. {
  215742. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  215743. DShowCameraDeviceInteral* const intern
  215744. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  215745. minWidth, minHeight, maxWidth, maxHeight);
  215746. cam->internal = intern;
  215747. if (intern->ok)
  215748. return cam.release();
  215749. }
  215750. }
  215751. return 0;
  215752. }
  215753. #endif
  215754. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  215755. #endif
  215756. // Auto-link the other win32 libs that are needed by library calls..
  215757. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  215758. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  215759. // Auto-links to various win32 libs that are needed by library calls..
  215760. #pragma comment(lib, "kernel32.lib")
  215761. #pragma comment(lib, "user32.lib")
  215762. #pragma comment(lib, "shell32.lib")
  215763. #pragma comment(lib, "gdi32.lib")
  215764. #pragma comment(lib, "vfw32.lib")
  215765. #pragma comment(lib, "comdlg32.lib")
  215766. #pragma comment(lib, "winmm.lib")
  215767. #pragma comment(lib, "wininet.lib")
  215768. #pragma comment(lib, "ole32.lib")
  215769. #pragma comment(lib, "oleaut32.lib")
  215770. #pragma comment(lib, "advapi32.lib")
  215771. #pragma comment(lib, "ws2_32.lib")
  215772. #pragma comment(lib, "comsupp.lib")
  215773. #pragma comment(lib, "version.lib")
  215774. #if JUCE_OPENGL
  215775. #pragma comment(lib, "OpenGL32.Lib")
  215776. #pragma comment(lib, "GlU32.Lib")
  215777. #endif
  215778. #if JUCE_QUICKTIME
  215779. #pragma comment (lib, "QTMLClient.lib")
  215780. #endif
  215781. #if JUCE_USE_CAMERA
  215782. #pragma comment (lib, "Strmiids.lib")
  215783. #pragma comment (lib, "wmvcore.lib")
  215784. #endif
  215785. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  215786. #endif
  215787. END_JUCE_NAMESPACE
  215788. #endif
  215789. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  215790. #endif
  215791. #if JUCE_LINUX
  215792. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  215793. /*
  215794. This file wraps together all the mac-specific code, so that
  215795. we can include all the native headers just once, and compile all our
  215796. platform-specific stuff in one big lump, keeping it out of the way of
  215797. the rest of the codebase.
  215798. */
  215799. #if JUCE_LINUX
  215800. BEGIN_JUCE_NAMESPACE
  215801. #define JUCE_INCLUDED_FILE 1
  215802. // Now include the actual code files..
  215803. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  215804. /*
  215805. This file contains posix routines that are common to both the Linux and Mac builds.
  215806. It gets included directly in the cpp files for these platforms.
  215807. */
  215808. CriticalSection::CriticalSection() throw()
  215809. {
  215810. pthread_mutexattr_t atts;
  215811. pthread_mutexattr_init (&atts);
  215812. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  215813. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  215814. pthread_mutex_init (&internal, &atts);
  215815. }
  215816. CriticalSection::~CriticalSection() throw()
  215817. {
  215818. pthread_mutex_destroy (&internal);
  215819. }
  215820. void CriticalSection::enter() const throw()
  215821. {
  215822. pthread_mutex_lock (&internal);
  215823. }
  215824. bool CriticalSection::tryEnter() const throw()
  215825. {
  215826. return pthread_mutex_trylock (&internal) == 0;
  215827. }
  215828. void CriticalSection::exit() const throw()
  215829. {
  215830. pthread_mutex_unlock (&internal);
  215831. }
  215832. class WaitableEventImpl
  215833. {
  215834. public:
  215835. WaitableEventImpl (const bool manualReset_)
  215836. : triggered (false),
  215837. manualReset (manualReset_)
  215838. {
  215839. pthread_cond_init (&condition, 0);
  215840. pthread_mutexattr_t atts;
  215841. pthread_mutexattr_init (&atts);
  215842. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  215843. pthread_mutex_init (&mutex, &atts);
  215844. }
  215845. ~WaitableEventImpl()
  215846. {
  215847. pthread_cond_destroy (&condition);
  215848. pthread_mutex_destroy (&mutex);
  215849. }
  215850. bool wait (const int timeOutMillisecs) throw()
  215851. {
  215852. pthread_mutex_lock (&mutex);
  215853. if (! triggered)
  215854. {
  215855. if (timeOutMillisecs < 0)
  215856. {
  215857. do
  215858. {
  215859. pthread_cond_wait (&condition, &mutex);
  215860. }
  215861. while (! triggered);
  215862. }
  215863. else
  215864. {
  215865. struct timeval now;
  215866. gettimeofday (&now, 0);
  215867. struct timespec time;
  215868. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  215869. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  215870. if (time.tv_nsec >= 1000000000)
  215871. {
  215872. time.tv_nsec -= 1000000000;
  215873. time.tv_sec++;
  215874. }
  215875. do
  215876. {
  215877. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  215878. {
  215879. pthread_mutex_unlock (&mutex);
  215880. return false;
  215881. }
  215882. }
  215883. while (! triggered);
  215884. }
  215885. }
  215886. if (! manualReset)
  215887. triggered = false;
  215888. pthread_mutex_unlock (&mutex);
  215889. return true;
  215890. }
  215891. void signal() throw()
  215892. {
  215893. pthread_mutex_lock (&mutex);
  215894. triggered = true;
  215895. pthread_cond_broadcast (&condition);
  215896. pthread_mutex_unlock (&mutex);
  215897. }
  215898. void reset() throw()
  215899. {
  215900. pthread_mutex_lock (&mutex);
  215901. triggered = false;
  215902. pthread_mutex_unlock (&mutex);
  215903. }
  215904. private:
  215905. pthread_cond_t condition;
  215906. pthread_mutex_t mutex;
  215907. bool triggered;
  215908. const bool manualReset;
  215909. WaitableEventImpl (const WaitableEventImpl&);
  215910. WaitableEventImpl& operator= (const WaitableEventImpl&);
  215911. };
  215912. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  215913. : internal (new WaitableEventImpl (manualReset))
  215914. {
  215915. }
  215916. WaitableEvent::~WaitableEvent() throw()
  215917. {
  215918. delete static_cast <WaitableEventImpl*> (internal);
  215919. }
  215920. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  215921. {
  215922. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  215923. }
  215924. void WaitableEvent::signal() const throw()
  215925. {
  215926. static_cast <WaitableEventImpl*> (internal)->signal();
  215927. }
  215928. void WaitableEvent::reset() const throw()
  215929. {
  215930. static_cast <WaitableEventImpl*> (internal)->reset();
  215931. }
  215932. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  215933. {
  215934. struct timespec time;
  215935. time.tv_sec = millisecs / 1000;
  215936. time.tv_nsec = (millisecs % 1000) * 1000000;
  215937. nanosleep (&time, 0);
  215938. }
  215939. const juce_wchar File::separator = '/';
  215940. const String File::separatorString ("/");
  215941. const File File::getCurrentWorkingDirectory()
  215942. {
  215943. HeapBlock<char> heapBuffer;
  215944. char localBuffer [1024];
  215945. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  215946. int bufferSize = 4096;
  215947. while (cwd == 0 && errno == ERANGE)
  215948. {
  215949. heapBuffer.malloc (bufferSize);
  215950. cwd = getcwd (heapBuffer, bufferSize - 1);
  215951. bufferSize += 1024;
  215952. }
  215953. return File (String::fromUTF8 (cwd));
  215954. }
  215955. bool File::setAsCurrentWorkingDirectory() const
  215956. {
  215957. return chdir (getFullPathName().toUTF8()) == 0;
  215958. }
  215959. static bool juce_stat (const String& fileName, struct stat& info)
  215960. {
  215961. return fileName.isNotEmpty()
  215962. && (stat (fileName.toUTF8(), &info) == 0);
  215963. }
  215964. bool File::isDirectory() const
  215965. {
  215966. struct stat info;
  215967. return fullPath.isEmpty()
  215968. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  215969. }
  215970. bool File::exists() const
  215971. {
  215972. return fullPath.isNotEmpty()
  215973. && access (fullPath.toUTF8(), F_OK) == 0;
  215974. }
  215975. bool File::existsAsFile() const
  215976. {
  215977. return exists() && ! isDirectory();
  215978. }
  215979. int64 File::getSize() const
  215980. {
  215981. struct stat info;
  215982. return juce_stat (fullPath, info) ? info.st_size : 0;
  215983. }
  215984. bool File::hasWriteAccess() const
  215985. {
  215986. if (exists())
  215987. return access (fullPath.toUTF8(), W_OK) == 0;
  215988. if ((! isDirectory()) && fullPath.containsChar (separator))
  215989. return getParentDirectory().hasWriteAccess();
  215990. return false;
  215991. }
  215992. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  215993. {
  215994. struct stat info;
  215995. const int res = stat (fullPath.toUTF8(), &info);
  215996. if (res != 0)
  215997. return false;
  215998. info.st_mode &= 0777; // Just permissions
  215999. if (shouldBeReadOnly)
  216000. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  216001. else
  216002. // Give everybody write permission?
  216003. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  216004. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  216005. }
  216006. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  216007. {
  216008. modificationTime = 0;
  216009. accessTime = 0;
  216010. creationTime = 0;
  216011. struct stat info;
  216012. const int res = stat (fullPath.toUTF8(), &info);
  216013. if (res == 0)
  216014. {
  216015. modificationTime = (int64) info.st_mtime * 1000;
  216016. accessTime = (int64) info.st_atime * 1000;
  216017. creationTime = (int64) info.st_ctime * 1000;
  216018. }
  216019. }
  216020. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  216021. {
  216022. struct utimbuf times;
  216023. times.actime = (time_t) (accessTime / 1000);
  216024. times.modtime = (time_t) (modificationTime / 1000);
  216025. return utime (fullPath.toUTF8(), &times) == 0;
  216026. }
  216027. bool File::deleteFile() const
  216028. {
  216029. if (! exists())
  216030. return true;
  216031. else if (isDirectory())
  216032. return rmdir (fullPath.toUTF8()) == 0;
  216033. else
  216034. return remove (fullPath.toUTF8()) == 0;
  216035. }
  216036. bool File::moveInternal (const File& dest) const
  216037. {
  216038. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  216039. return true;
  216040. if (hasWriteAccess() && copyInternal (dest))
  216041. {
  216042. if (deleteFile())
  216043. return true;
  216044. dest.deleteFile();
  216045. }
  216046. return false;
  216047. }
  216048. void File::createDirectoryInternal (const String& fileName) const
  216049. {
  216050. mkdir (fileName.toUTF8(), 0777);
  216051. }
  216052. void* juce_fileOpen (const File& file, bool forWriting)
  216053. {
  216054. int flags = O_RDONLY;
  216055. if (forWriting)
  216056. {
  216057. if (file.exists())
  216058. {
  216059. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  216060. if (f != -1)
  216061. lseek (f, 0, SEEK_END);
  216062. return (void*) f;
  216063. }
  216064. else
  216065. {
  216066. flags = O_RDWR + O_CREAT;
  216067. }
  216068. }
  216069. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  216070. }
  216071. void juce_fileClose (void* handle)
  216072. {
  216073. if (handle != 0)
  216074. close ((int) (pointer_sized_int) handle);
  216075. }
  216076. int juce_fileRead (void* handle, void* buffer, int size)
  216077. {
  216078. if (handle != 0)
  216079. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  216080. return 0;
  216081. }
  216082. int juce_fileWrite (void* handle, const void* buffer, int size)
  216083. {
  216084. if (handle != 0)
  216085. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  216086. return 0;
  216087. }
  216088. int64 juce_fileSetPosition (void* handle, int64 pos)
  216089. {
  216090. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  216091. return pos;
  216092. return -1;
  216093. }
  216094. int64 FileOutputStream::getPositionInternal() const
  216095. {
  216096. if (fileHandle != 0)
  216097. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  216098. return -1;
  216099. }
  216100. void FileOutputStream::flushInternal()
  216101. {
  216102. if (fileHandle != 0)
  216103. fsync ((int) (pointer_sized_int) fileHandle);
  216104. }
  216105. const File juce_getExecutableFile()
  216106. {
  216107. Dl_info exeInfo;
  216108. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  216109. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  216110. }
  216111. // if this file doesn't exist, find a parent of it that does..
  216112. static bool juce_doStatFS (File f, struct statfs& result)
  216113. {
  216114. for (int i = 5; --i >= 0;)
  216115. {
  216116. if (f.exists())
  216117. break;
  216118. f = f.getParentDirectory();
  216119. }
  216120. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  216121. }
  216122. int64 File::getBytesFreeOnVolume() const
  216123. {
  216124. struct statfs buf;
  216125. if (juce_doStatFS (*this, buf))
  216126. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  216127. return 0;
  216128. }
  216129. int64 File::getVolumeTotalSize() const
  216130. {
  216131. struct statfs buf;
  216132. if (juce_doStatFS (*this, buf))
  216133. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  216134. return 0;
  216135. }
  216136. const String File::getVolumeLabel() const
  216137. {
  216138. #if JUCE_MAC
  216139. struct VolAttrBuf
  216140. {
  216141. u_int32_t length;
  216142. attrreference_t mountPointRef;
  216143. char mountPointSpace [MAXPATHLEN];
  216144. } attrBuf;
  216145. struct attrlist attrList;
  216146. zerostruct (attrList);
  216147. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  216148. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  216149. File f (*this);
  216150. for (;;)
  216151. {
  216152. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  216153. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  216154. (int) attrBuf.mountPointRef.attr_length);
  216155. const File parent (f.getParentDirectory());
  216156. if (f == parent)
  216157. break;
  216158. f = parent;
  216159. }
  216160. #endif
  216161. return String::empty;
  216162. }
  216163. int File::getVolumeSerialNumber() const
  216164. {
  216165. return 0; // xxx
  216166. }
  216167. void juce_runSystemCommand (const String& command)
  216168. {
  216169. int result = system (command.toUTF8());
  216170. (void) result;
  216171. }
  216172. const String juce_getOutputFromCommand (const String& command)
  216173. {
  216174. // slight bodge here, as we just pipe the output into a temp file and read it...
  216175. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  216176. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  216177. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  216178. String result (tempFile.loadFileAsString());
  216179. tempFile.deleteFile();
  216180. return result;
  216181. }
  216182. class InterProcessLock::Pimpl
  216183. {
  216184. public:
  216185. Pimpl (const String& name, const int timeOutMillisecs)
  216186. : handle (0), refCount (1)
  216187. {
  216188. #if JUCE_MAC
  216189. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  216190. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  216191. #else
  216192. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  216193. #endif
  216194. temp.create();
  216195. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  216196. if (handle != 0)
  216197. {
  216198. struct flock fl;
  216199. zerostruct (fl);
  216200. fl.l_whence = SEEK_SET;
  216201. fl.l_type = F_WRLCK;
  216202. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  216203. for (;;)
  216204. {
  216205. const int result = fcntl (handle, F_SETLK, &fl);
  216206. if (result >= 0)
  216207. return;
  216208. if (errno != EINTR)
  216209. {
  216210. if (timeOutMillisecs == 0
  216211. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  216212. break;
  216213. Thread::sleep (10);
  216214. }
  216215. }
  216216. }
  216217. closeFile();
  216218. }
  216219. ~Pimpl()
  216220. {
  216221. closeFile();
  216222. }
  216223. void closeFile()
  216224. {
  216225. if (handle != 0)
  216226. {
  216227. struct flock fl;
  216228. zerostruct (fl);
  216229. fl.l_whence = SEEK_SET;
  216230. fl.l_type = F_UNLCK;
  216231. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  216232. {}
  216233. close (handle);
  216234. handle = 0;
  216235. }
  216236. }
  216237. int handle, refCount;
  216238. };
  216239. InterProcessLock::InterProcessLock (const String& name_)
  216240. : name (name_)
  216241. {
  216242. }
  216243. InterProcessLock::~InterProcessLock()
  216244. {
  216245. }
  216246. bool InterProcessLock::enter (const int timeOutMillisecs)
  216247. {
  216248. const ScopedLock sl (lock);
  216249. if (pimpl == 0)
  216250. {
  216251. pimpl = new Pimpl (name, timeOutMillisecs);
  216252. if (pimpl->handle == 0)
  216253. pimpl = 0;
  216254. }
  216255. else
  216256. {
  216257. pimpl->refCount++;
  216258. }
  216259. return pimpl != 0;
  216260. }
  216261. void InterProcessLock::exit()
  216262. {
  216263. const ScopedLock sl (lock);
  216264. // Trying to release the lock too many times!
  216265. jassert (pimpl != 0);
  216266. if (pimpl != 0 && --(pimpl->refCount) == 0)
  216267. pimpl = 0;
  216268. }
  216269. /*** End of inlined file: juce_posix_SharedCode.h ***/
  216270. /*** Start of inlined file: juce_linux_Files.cpp ***/
  216271. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216272. // compiled on its own).
  216273. #if JUCE_INCLUDED_FILE
  216274. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  216275. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  216276. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  216277. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  216278. bool File::copyInternal (const File& dest) const
  216279. {
  216280. FileInputStream in (*this);
  216281. if (dest.deleteFile())
  216282. {
  216283. {
  216284. FileOutputStream out (dest);
  216285. if (out.failedToOpen())
  216286. return false;
  216287. if (out.writeFromInputStream (in, -1) == getSize())
  216288. return true;
  216289. }
  216290. dest.deleteFile();
  216291. }
  216292. return false;
  216293. }
  216294. void File::findFileSystemRoots (Array<File>& destArray)
  216295. {
  216296. destArray.add (File ("/"));
  216297. }
  216298. bool File::isOnCDRomDrive() const
  216299. {
  216300. struct statfs buf;
  216301. return statfs (getFullPathName().toUTF8(), &buf) == 0
  216302. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  216303. }
  216304. bool File::isOnHardDisk() const
  216305. {
  216306. struct statfs buf;
  216307. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  216308. {
  216309. switch (buf.f_type)
  216310. {
  216311. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  216312. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  216313. case U_NFS_SUPER_MAGIC: // Network NFS
  216314. case U_SMB_SUPER_MAGIC: // Network Samba
  216315. return false;
  216316. default:
  216317. // Assume anything else is a hard-disk (but note it could
  216318. // be a RAM disk. There isn't a good way of determining
  216319. // this for sure)
  216320. return true;
  216321. }
  216322. }
  216323. // Assume so if this fails for some reason
  216324. return true;
  216325. }
  216326. bool File::isOnRemovableDrive() const
  216327. {
  216328. jassertfalse; // xxx not implemented for linux!
  216329. return false;
  216330. }
  216331. bool File::isHidden() const
  216332. {
  216333. return getFileName().startsWithChar ('.');
  216334. }
  216335. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  216336. const File File::getSpecialLocation (const SpecialLocationType type)
  216337. {
  216338. switch (type)
  216339. {
  216340. case userHomeDirectory:
  216341. {
  216342. const char* homeDir = getenv ("HOME");
  216343. if (homeDir == 0)
  216344. {
  216345. struct passwd* const pw = getpwuid (getuid());
  216346. if (pw != 0)
  216347. homeDir = pw->pw_dir;
  216348. }
  216349. return File (String::fromUTF8 (homeDir));
  216350. }
  216351. case userDocumentsDirectory:
  216352. case userMusicDirectory:
  216353. case userMoviesDirectory:
  216354. case userApplicationDataDirectory:
  216355. return File ("~");
  216356. case userDesktopDirectory:
  216357. return File ("~/Desktop");
  216358. case commonApplicationDataDirectory:
  216359. return File ("/var");
  216360. case globalApplicationsDirectory:
  216361. return File ("/usr");
  216362. case tempDirectory:
  216363. {
  216364. File tmp ("/var/tmp");
  216365. if (! tmp.isDirectory())
  216366. {
  216367. tmp = "/tmp";
  216368. if (! tmp.isDirectory())
  216369. tmp = File::getCurrentWorkingDirectory();
  216370. }
  216371. return tmp;
  216372. }
  216373. case invokedExecutableFile:
  216374. if (juce_Argv0 != 0)
  216375. return File (String::fromUTF8 (juce_Argv0));
  216376. // deliberate fall-through...
  216377. case currentExecutableFile:
  216378. case currentApplicationFile:
  216379. return juce_getExecutableFile();
  216380. default:
  216381. jassertfalse; // unknown type?
  216382. break;
  216383. }
  216384. return File::nonexistent;
  216385. }
  216386. const String File::getVersion() const
  216387. {
  216388. return String::empty; // xxx not yet implemented
  216389. }
  216390. const File File::getLinkedTarget() const
  216391. {
  216392. char buffer [4096];
  216393. size_t numChars = readlink (getFullPathName().toUTF8(),
  216394. buffer, sizeof (buffer));
  216395. if (numChars > 0 && numChars <= sizeof (buffer))
  216396. return File (String::fromUTF8 (buffer, (int) numChars));
  216397. return *this;
  216398. }
  216399. bool File::moveToTrash() const
  216400. {
  216401. if (! exists())
  216402. return true;
  216403. File trashCan ("~/.Trash");
  216404. if (! trashCan.isDirectory())
  216405. trashCan = "~/.local/share/Trash/files";
  216406. if (! trashCan.isDirectory())
  216407. return false;
  216408. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  216409. getFileExtension()));
  216410. }
  216411. class DirectoryIterator::NativeIterator::Pimpl
  216412. {
  216413. public:
  216414. Pimpl (const File& directory, const String& wildCard_)
  216415. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  216416. wildCard (wildCard_),
  216417. dir (opendir (directory.getFullPathName().toUTF8()))
  216418. {
  216419. if (wildCard == "*.*")
  216420. wildCard = "*";
  216421. wildcardUTF8 = wildCard.toUTF8();
  216422. }
  216423. ~Pimpl()
  216424. {
  216425. if (dir != 0)
  216426. closedir (dir);
  216427. }
  216428. bool next (String& filenameFound,
  216429. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216430. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216431. {
  216432. if (dir == 0)
  216433. return false;
  216434. for (;;)
  216435. {
  216436. struct dirent* const de = readdir (dir);
  216437. if (de == 0)
  216438. return false;
  216439. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  216440. {
  216441. filenameFound = String::fromUTF8 (de->d_name);
  216442. const String path (parentDir + filenameFound);
  216443. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  216444. {
  216445. struct stat info;
  216446. const bool statOk = juce_stat (path, info);
  216447. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  216448. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  216449. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  216450. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  216451. }
  216452. if (isHidden != 0)
  216453. *isHidden = filenameFound.startsWithChar ('.');
  216454. if (isReadOnly != 0)
  216455. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  216456. return true;
  216457. }
  216458. }
  216459. }
  216460. private:
  216461. String parentDir, wildCard;
  216462. const char* wildcardUTF8;
  216463. DIR* dir;
  216464. Pimpl (const Pimpl&);
  216465. Pimpl& operator= (const Pimpl&);
  216466. };
  216467. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  216468. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  216469. {
  216470. }
  216471. DirectoryIterator::NativeIterator::~NativeIterator()
  216472. {
  216473. }
  216474. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  216475. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216476. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216477. {
  216478. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  216479. }
  216480. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  216481. {
  216482. String cmdString (fileName.replace (" ", "\\ ",false));
  216483. cmdString << " " << parameters;
  216484. if (URL::isProbablyAWebsiteURL (fileName)
  216485. || cmdString.startsWithIgnoreCase ("file:")
  216486. || URL::isProbablyAnEmailAddress (fileName))
  216487. {
  216488. // create a command that tries to launch a bunch of likely browsers
  216489. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  216490. StringArray cmdLines;
  216491. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  216492. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  216493. cmdString = cmdLines.joinIntoString (" || ");
  216494. }
  216495. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  216496. const int cpid = fork();
  216497. if (cpid == 0)
  216498. {
  216499. setsid();
  216500. // Child process
  216501. execve (argv[0], (char**) argv, environ);
  216502. exit (0);
  216503. }
  216504. return cpid >= 0;
  216505. }
  216506. void File::revealToUser() const
  216507. {
  216508. if (isDirectory())
  216509. startAsProcess();
  216510. else if (getParentDirectory().exists())
  216511. getParentDirectory().startAsProcess();
  216512. }
  216513. #endif
  216514. /*** End of inlined file: juce_linux_Files.cpp ***/
  216515. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  216516. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  216517. // compiled on its own).
  216518. #if JUCE_INCLUDED_FILE
  216519. struct NamedPipeInternal
  216520. {
  216521. String pipeInName, pipeOutName;
  216522. int pipeIn, pipeOut;
  216523. bool volatile createdPipe, blocked, stopReadOperation;
  216524. static void signalHandler (int) {}
  216525. };
  216526. void NamedPipe::cancelPendingReads()
  216527. {
  216528. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  216529. {
  216530. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216531. intern->stopReadOperation = true;
  216532. char buffer [1] = { 0 };
  216533. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  216534. (void) bytesWritten;
  216535. int timeout = 2000;
  216536. while (intern->blocked && --timeout >= 0)
  216537. Thread::sleep (2);
  216538. intern->stopReadOperation = false;
  216539. }
  216540. }
  216541. void NamedPipe::close()
  216542. {
  216543. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216544. if (intern != 0)
  216545. {
  216546. internal = 0;
  216547. if (intern->pipeIn != -1)
  216548. ::close (intern->pipeIn);
  216549. if (intern->pipeOut != -1)
  216550. ::close (intern->pipeOut);
  216551. if (intern->createdPipe)
  216552. {
  216553. unlink (intern->pipeInName.toUTF8());
  216554. unlink (intern->pipeOutName.toUTF8());
  216555. }
  216556. delete intern;
  216557. }
  216558. }
  216559. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  216560. {
  216561. close();
  216562. NamedPipeInternal* const intern = new NamedPipeInternal();
  216563. internal = intern;
  216564. intern->createdPipe = createPipe;
  216565. intern->blocked = false;
  216566. intern->stopReadOperation = false;
  216567. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  216568. siginterrupt (SIGPIPE, 1);
  216569. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  216570. intern->pipeInName = pipePath + "_in";
  216571. intern->pipeOutName = pipePath + "_out";
  216572. intern->pipeIn = -1;
  216573. intern->pipeOut = -1;
  216574. if (createPipe)
  216575. {
  216576. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  216577. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  216578. {
  216579. delete intern;
  216580. internal = 0;
  216581. return false;
  216582. }
  216583. }
  216584. return true;
  216585. }
  216586. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  216587. {
  216588. int bytesRead = -1;
  216589. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216590. if (intern != 0)
  216591. {
  216592. intern->blocked = true;
  216593. if (intern->pipeIn == -1)
  216594. {
  216595. if (intern->createdPipe)
  216596. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  216597. else
  216598. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  216599. if (intern->pipeIn == -1)
  216600. {
  216601. intern->blocked = false;
  216602. return -1;
  216603. }
  216604. }
  216605. bytesRead = 0;
  216606. char* p = (char*) destBuffer;
  216607. while (bytesRead < maxBytesToRead)
  216608. {
  216609. const int bytesThisTime = maxBytesToRead - bytesRead;
  216610. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  216611. if (numRead <= 0 || intern->stopReadOperation)
  216612. {
  216613. bytesRead = -1;
  216614. break;
  216615. }
  216616. bytesRead += numRead;
  216617. p += bytesRead;
  216618. }
  216619. intern->blocked = false;
  216620. }
  216621. return bytesRead;
  216622. }
  216623. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  216624. {
  216625. int bytesWritten = -1;
  216626. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216627. if (intern != 0)
  216628. {
  216629. if (intern->pipeOut == -1)
  216630. {
  216631. if (intern->createdPipe)
  216632. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  216633. else
  216634. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  216635. if (intern->pipeOut == -1)
  216636. {
  216637. return -1;
  216638. }
  216639. }
  216640. const char* p = (const char*) sourceBuffer;
  216641. bytesWritten = 0;
  216642. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  216643. while (bytesWritten < numBytesToWrite
  216644. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  216645. {
  216646. const int bytesThisTime = numBytesToWrite - bytesWritten;
  216647. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  216648. if (numWritten <= 0)
  216649. {
  216650. bytesWritten = -1;
  216651. break;
  216652. }
  216653. bytesWritten += numWritten;
  216654. p += bytesWritten;
  216655. }
  216656. }
  216657. return bytesWritten;
  216658. }
  216659. #endif
  216660. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  216661. /*** Start of inlined file: juce_linux_Network.cpp ***/
  216662. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216663. // compiled on its own).
  216664. #if JUCE_INCLUDED_FILE
  216665. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  216666. {
  216667. int numResults = 0;
  216668. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  216669. if (s != -1)
  216670. {
  216671. char buf [1024];
  216672. struct ifconf ifc;
  216673. ifc.ifc_len = sizeof (buf);
  216674. ifc.ifc_buf = buf;
  216675. ioctl (s, SIOCGIFCONF, &ifc);
  216676. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  216677. {
  216678. struct ifreq ifr;
  216679. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  216680. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  216681. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  216682. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  216683. && numResults < maxNum)
  216684. {
  216685. int64 a = 0;
  216686. for (int j = 6; --j >= 0;)
  216687. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  216688. *addresses++ = a;
  216689. ++numResults;
  216690. }
  216691. }
  216692. close (s);
  216693. }
  216694. return numResults;
  216695. }
  216696. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  216697. const String& emailSubject,
  216698. const String& bodyText,
  216699. const StringArray& filesToAttach)
  216700. {
  216701. jassertfalse; // xxx todo
  216702. return false;
  216703. }
  216704. /** A HTTP input stream that uses sockets.
  216705. */
  216706. class JUCE_HTTPSocketStream
  216707. {
  216708. public:
  216709. JUCE_HTTPSocketStream()
  216710. : readPosition (0),
  216711. socketHandle (-1),
  216712. levelsOfRedirection (0),
  216713. timeoutSeconds (15)
  216714. {
  216715. }
  216716. ~JUCE_HTTPSocketStream()
  216717. {
  216718. closeSocket();
  216719. }
  216720. bool open (const String& url,
  216721. const String& headers,
  216722. const MemoryBlock& postData,
  216723. const bool isPost,
  216724. URL::OpenStreamProgressCallback* callback,
  216725. void* callbackContext,
  216726. int timeOutMs)
  216727. {
  216728. closeSocket();
  216729. uint32 timeOutTime = Time::getMillisecondCounter();
  216730. if (timeOutMs == 0)
  216731. timeOutTime += 60000;
  216732. else if (timeOutMs < 0)
  216733. timeOutTime = 0xffffffff;
  216734. else
  216735. timeOutTime += timeOutMs;
  216736. String hostName, hostPath;
  216737. int hostPort;
  216738. if (! decomposeURL (url, hostName, hostPath, hostPort))
  216739. return false;
  216740. const struct hostent* host = 0;
  216741. int port = 0;
  216742. String proxyName, proxyPath;
  216743. int proxyPort = 0;
  216744. String proxyURL (getenv ("http_proxy"));
  216745. if (proxyURL.startsWithIgnoreCase ("http://"))
  216746. {
  216747. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  216748. return false;
  216749. host = gethostbyname (proxyName.toUTF8());
  216750. port = proxyPort;
  216751. }
  216752. else
  216753. {
  216754. host = gethostbyname (hostName.toUTF8());
  216755. port = hostPort;
  216756. }
  216757. if (host == 0)
  216758. return false;
  216759. struct sockaddr_in address;
  216760. zerostruct (address);
  216761. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  216762. address.sin_family = host->h_addrtype;
  216763. address.sin_port = htons (port);
  216764. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  216765. if (socketHandle == -1)
  216766. return false;
  216767. int receiveBufferSize = 16384;
  216768. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  216769. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  216770. #if JUCE_MAC
  216771. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  216772. #endif
  216773. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  216774. {
  216775. closeSocket();
  216776. return false;
  216777. }
  216778. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  216779. proxyName, proxyPort,
  216780. hostPath, url,
  216781. headers, postData,
  216782. isPost));
  216783. size_t totalHeaderSent = 0;
  216784. while (totalHeaderSent < requestHeader.getSize())
  216785. {
  216786. if (Time::getMillisecondCounter() > timeOutTime)
  216787. {
  216788. closeSocket();
  216789. return false;
  216790. }
  216791. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  216792. if (send (socketHandle,
  216793. ((const char*) requestHeader.getData()) + totalHeaderSent,
  216794. numToSend, 0)
  216795. != numToSend)
  216796. {
  216797. closeSocket();
  216798. return false;
  216799. }
  216800. totalHeaderSent += numToSend;
  216801. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  216802. {
  216803. closeSocket();
  216804. return false;
  216805. }
  216806. }
  216807. const String responseHeader (readResponse (timeOutTime));
  216808. if (responseHeader.isNotEmpty())
  216809. {
  216810. //DBG (responseHeader);
  216811. headerLines.clear();
  216812. headerLines.addLines (responseHeader);
  216813. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  216814. .substring (0, 3).getIntValue();
  216815. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  216816. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  216817. String location (findHeaderItem (headerLines, "Location:"));
  216818. if (statusCode >= 300 && statusCode < 400
  216819. && location.isNotEmpty())
  216820. {
  216821. if (! location.startsWithIgnoreCase ("http://"))
  216822. location = "http://" + location;
  216823. if (levelsOfRedirection++ < 3)
  216824. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  216825. }
  216826. else
  216827. {
  216828. levelsOfRedirection = 0;
  216829. return true;
  216830. }
  216831. }
  216832. closeSocket();
  216833. return false;
  216834. }
  216835. int read (void* buffer, int bytesToRead)
  216836. {
  216837. fd_set readbits;
  216838. FD_ZERO (&readbits);
  216839. FD_SET (socketHandle, &readbits);
  216840. struct timeval tv;
  216841. tv.tv_sec = timeoutSeconds;
  216842. tv.tv_usec = 0;
  216843. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216844. return 0; // (timeout)
  216845. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  216846. readPosition += bytesRead;
  216847. return bytesRead;
  216848. }
  216849. int readPosition;
  216850. StringArray headerLines;
  216851. juce_UseDebuggingNewOperator
  216852. private:
  216853. int socketHandle, levelsOfRedirection;
  216854. const int timeoutSeconds;
  216855. void closeSocket()
  216856. {
  216857. if (socketHandle >= 0)
  216858. close (socketHandle);
  216859. socketHandle = -1;
  216860. }
  216861. const MemoryBlock createRequestHeader (const String& hostName,
  216862. const int hostPort,
  216863. const String& proxyName,
  216864. const int proxyPort,
  216865. const String& hostPath,
  216866. const String& originalURL,
  216867. const String& headers,
  216868. const MemoryBlock& postData,
  216869. const bool isPost)
  216870. {
  216871. String header (isPost ? "POST " : "GET ");
  216872. if (proxyName.isEmpty())
  216873. {
  216874. header << hostPath << " HTTP/1.0\r\nHost: "
  216875. << hostName << ':' << hostPort;
  216876. }
  216877. else
  216878. {
  216879. header << originalURL << " HTTP/1.0\r\nHost: "
  216880. << proxyName << ':' << proxyPort;
  216881. }
  216882. header << "\r\nUser-Agent: JUCE/"
  216883. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  216884. << "\r\nConnection: Close\r\nContent-Length: "
  216885. << postData.getSize() << "\r\n"
  216886. << headers << "\r\n";
  216887. MemoryBlock mb;
  216888. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  216889. mb.append (postData.getData(), postData.getSize());
  216890. return mb;
  216891. }
  216892. const String readResponse (const uint32 timeOutTime)
  216893. {
  216894. int bytesRead = 0, numConsecutiveLFs = 0;
  216895. MemoryBlock buffer (1024, true);
  216896. while (numConsecutiveLFs < 2 && bytesRead < 32768
  216897. && Time::getMillisecondCounter() <= timeOutTime)
  216898. {
  216899. fd_set readbits;
  216900. FD_ZERO (&readbits);
  216901. FD_SET (socketHandle, &readbits);
  216902. struct timeval tv;
  216903. tv.tv_sec = timeoutSeconds;
  216904. tv.tv_usec = 0;
  216905. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216906. return String::empty; // (timeout)
  216907. buffer.ensureSize (bytesRead + 8, true);
  216908. char* const dest = (char*) buffer.getData() + bytesRead;
  216909. if (recv (socketHandle, dest, 1, 0) == -1)
  216910. return String::empty;
  216911. const char lastByte = *dest;
  216912. ++bytesRead;
  216913. if (lastByte == '\n')
  216914. ++numConsecutiveLFs;
  216915. else if (lastByte != '\r')
  216916. numConsecutiveLFs = 0;
  216917. }
  216918. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  216919. if (header.startsWithIgnoreCase ("HTTP/"))
  216920. return header.trimEnd();
  216921. return String::empty;
  216922. }
  216923. static bool decomposeURL (const String& url,
  216924. String& host, String& path, int& port)
  216925. {
  216926. if (! url.startsWithIgnoreCase ("http://"))
  216927. return false;
  216928. const int nextSlash = url.indexOfChar (7, '/');
  216929. int nextColon = url.indexOfChar (7, ':');
  216930. if (nextColon > nextSlash && nextSlash > 0)
  216931. nextColon = -1;
  216932. if (nextColon >= 0)
  216933. {
  216934. host = url.substring (7, nextColon);
  216935. if (nextSlash >= 0)
  216936. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  216937. else
  216938. port = url.substring (nextColon + 1).getIntValue();
  216939. }
  216940. else
  216941. {
  216942. port = 80;
  216943. if (nextSlash >= 0)
  216944. host = url.substring (7, nextSlash);
  216945. else
  216946. host = url.substring (7);
  216947. }
  216948. if (nextSlash >= 0)
  216949. path = url.substring (nextSlash);
  216950. else
  216951. path = "/";
  216952. return true;
  216953. }
  216954. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  216955. {
  216956. for (int i = 0; i < lines.size(); ++i)
  216957. if (lines[i].startsWithIgnoreCase (itemName))
  216958. return lines[i].substring (itemName.length()).trim();
  216959. return String::empty;
  216960. }
  216961. };
  216962. void* juce_openInternetFile (const String& url,
  216963. const String& headers,
  216964. const MemoryBlock& postData,
  216965. const bool isPost,
  216966. URL::OpenStreamProgressCallback* callback,
  216967. void* callbackContext,
  216968. int timeOutMs)
  216969. {
  216970. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  216971. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  216972. return s.release();
  216973. return 0;
  216974. }
  216975. void juce_closeInternetFile (void* handle)
  216976. {
  216977. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  216978. }
  216979. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  216980. {
  216981. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216982. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  216983. }
  216984. int64 juce_getInternetFileContentLength (void* handle)
  216985. {
  216986. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216987. if (s != 0)
  216988. {
  216989. //xxx todo
  216990. jassertfalse
  216991. }
  216992. return -1;
  216993. }
  216994. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  216995. {
  216996. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216997. if (s != 0)
  216998. {
  216999. for (int i = 0; i < s->headerLines.size(); ++i)
  217000. {
  217001. const String& headersEntry = s->headerLines[i];
  217002. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  217003. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  217004. const String previousValue (headers [key]);
  217005. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  217006. }
  217007. }
  217008. }
  217009. int juce_seekInInternetFile (void* handle, int newPosition)
  217010. {
  217011. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  217012. return s != 0 ? s->readPosition : 0;
  217013. }
  217014. #endif
  217015. /*** End of inlined file: juce_linux_Network.cpp ***/
  217016. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  217017. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217018. // compiled on its own).
  217019. #if JUCE_INCLUDED_FILE
  217020. void Logger::outputDebugString (const String& text)
  217021. {
  217022. std::cerr << text << std::endl;
  217023. }
  217024. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  217025. {
  217026. return Linux;
  217027. }
  217028. const String SystemStats::getOperatingSystemName()
  217029. {
  217030. return "Linux";
  217031. }
  217032. bool SystemStats::isOperatingSystem64Bit()
  217033. {
  217034. #if JUCE_64BIT
  217035. return true;
  217036. #else
  217037. //xxx not sure how to find this out?..
  217038. return false;
  217039. #endif
  217040. }
  217041. static const String juce_getCpuInfo (const char* const key)
  217042. {
  217043. StringArray lines;
  217044. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  217045. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  217046. if (lines[i].startsWithIgnoreCase (key))
  217047. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  217048. return String::empty;
  217049. }
  217050. const String SystemStats::getCpuVendor()
  217051. {
  217052. return juce_getCpuInfo ("vendor_id");
  217053. }
  217054. int SystemStats::getCpuSpeedInMegaherz()
  217055. {
  217056. return roundToInt (juce_getCpuInfo ("cpu MHz").getFloatValue());
  217057. }
  217058. int SystemStats::getMemorySizeInMegabytes()
  217059. {
  217060. struct sysinfo sysi;
  217061. if (sysinfo (&sysi) == 0)
  217062. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  217063. return 0;
  217064. }
  217065. int SystemStats::getPageSize()
  217066. {
  217067. return sysconf (_SC_PAGESIZE);
  217068. }
  217069. const String SystemStats::getLogonName()
  217070. {
  217071. const char* user = getenv ("USER");
  217072. if (user == 0)
  217073. {
  217074. struct passwd* const pw = getpwuid (getuid());
  217075. if (pw != 0)
  217076. user = pw->pw_name;
  217077. }
  217078. return String::fromUTF8 (user);
  217079. }
  217080. const String SystemStats::getFullUserName()
  217081. {
  217082. return getLogonName();
  217083. }
  217084. void SystemStats::initialiseStats()
  217085. {
  217086. const String flags (juce_getCpuInfo ("flags"));
  217087. cpuFlags.hasMMX = flags.contains ("mmx");
  217088. cpuFlags.hasSSE = flags.contains ("sse");
  217089. cpuFlags.hasSSE2 = flags.contains ("sse2");
  217090. cpuFlags.has3DNow = flags.contains ("3dnow");
  217091. cpuFlags.numCpus = juce_getCpuInfo ("processor").getIntValue() + 1;
  217092. }
  217093. void PlatformUtilities::fpuReset()
  217094. {
  217095. }
  217096. static bool juce_getTimeSinceStartup (timeval* const t) throw()
  217097. {
  217098. if (gettimeofday (t, 0) != 0)
  217099. return false;
  217100. static unsigned int calibrate = 0;
  217101. static bool calibrated = false;
  217102. if (! calibrated)
  217103. {
  217104. calibrated = true;
  217105. struct sysinfo sysi;
  217106. if (sysinfo (&sysi) == 0)
  217107. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  217108. }
  217109. t->tv_sec -= calibrate;
  217110. return true;
  217111. }
  217112. uint32 juce_millisecondsSinceStartup() throw()
  217113. {
  217114. timeval t;
  217115. if (juce_getTimeSinceStartup (&t))
  217116. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  217117. return 0;
  217118. }
  217119. int64 Time::getHighResolutionTicks() throw()
  217120. {
  217121. timeval t;
  217122. if (juce_getTimeSinceStartup (&t))
  217123. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  217124. return 0;
  217125. }
  217126. int64 Time::getHighResolutionTicksPerSecond() throw()
  217127. {
  217128. return 1000000; // (microseconds)
  217129. }
  217130. double Time::getMillisecondCounterHiRes() throw()
  217131. {
  217132. return getHighResolutionTicks() * 0.001;
  217133. }
  217134. bool Time::setSystemTimeToThisTime() const
  217135. {
  217136. timeval t;
  217137. t.tv_sec = millisSinceEpoch % 1000000;
  217138. t.tv_usec = millisSinceEpoch - t.tv_sec;
  217139. return settimeofday (&t, 0) ? false : true;
  217140. }
  217141. #endif
  217142. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  217143. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  217144. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217145. // compiled on its own).
  217146. #if JUCE_INCLUDED_FILE
  217147. /*
  217148. Note that a lot of methods that you'd expect to find in this file actually
  217149. live in juce_posix_SharedCode.h!
  217150. */
  217151. void JUCE_API juce_threadEntryPoint (void*);
  217152. void* threadEntryProc (void* value)
  217153. {
  217154. juce_threadEntryPoint (value);
  217155. return 0;
  217156. }
  217157. void* juce_createThread (void* userData)
  217158. {
  217159. pthread_t handle = 0;
  217160. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  217161. {
  217162. pthread_detach (handle);
  217163. return (void*) handle;
  217164. }
  217165. return 0;
  217166. }
  217167. void juce_killThread (void* handle)
  217168. {
  217169. if (handle != 0)
  217170. pthread_cancel ((pthread_t) handle);
  217171. }
  217172. void juce_setCurrentThreadName (const String& /*name*/)
  217173. {
  217174. }
  217175. Thread::ThreadID Thread::getCurrentThreadId()
  217176. {
  217177. return (ThreadID) pthread_self();
  217178. }
  217179. /* This is all a bit non-ideal... the trouble is that on Linux you
  217180. need to call setpriority to affect the dynamic priority for
  217181. non-realtime processes, but this requires the pid, which is not
  217182. accessible from the pthread_t. We could get it by calling getpid
  217183. once each thread has started, but then we would need a list of
  217184. running threads etc etc.
  217185. Also there is no such thing as IDLE priority on Linux.
  217186. For the moment, map idle, low and normal process priorities to
  217187. SCHED_OTHER, with the thread priority ignored for these classes.
  217188. Map high priority processes to the lower half of the SCHED_RR
  217189. range, and realtime to the upper half.
  217190. priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  217191. priority of the current thread
  217192. */
  217193. bool juce_setThreadPriority (void* handle, int priority)
  217194. {
  217195. struct sched_param param;
  217196. int policy;
  217197. if (handle == 0)
  217198. handle = (void*) pthread_self();
  217199. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  217200. && policy != SCHED_OTHER)
  217201. {
  217202. int minp = sched_get_priority_min (policy);
  217203. int maxp = sched_get_priority_max (policy);
  217204. int pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  217205. if (param.sched_priority >= (minp + (maxp - minp) / 2))
  217206. param.sched_priority = minp + ((maxp - minp) / 2) + pri; // (realtime)
  217207. else
  217208. param.sched_priority = minp + pri; // (high)
  217209. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  217210. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217211. }
  217212. return false;
  217213. }
  217214. /* Remove this macro if you're having problems compiling the cpu affinity
  217215. calls (the API for these has changed about quite a bit in various Linux
  217216. versions, and a lot of distros seem to ship with obsolete versions)
  217217. */
  217218. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217219. #define SUPPORT_AFFINITIES 1
  217220. #endif
  217221. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217222. {
  217223. #if SUPPORT_AFFINITIES
  217224. cpu_set_t affinity;
  217225. CPU_ZERO (&affinity);
  217226. for (int i = 0; i < 32; ++i)
  217227. if ((affinityMask & (1 << i)) != 0)
  217228. CPU_SET (i, &affinity);
  217229. /*
  217230. N.B. If this line causes a compile error, then you've probably not got the latest
  217231. version of glibc installed.
  217232. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217233. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217234. */
  217235. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217236. sched_yield();
  217237. #else
  217238. /* affinities aren't supported because either the appropriate header files weren't found,
  217239. or the SUPPORT_AFFINITIES macro was turned off
  217240. */
  217241. jassertfalse;
  217242. #endif
  217243. }
  217244. void Thread::yield()
  217245. {
  217246. sched_yield();
  217247. }
  217248. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  217249. void Process::setPriority (ProcessPriority prior)
  217250. {
  217251. struct sched_param param;
  217252. int policy, maxp, minp;
  217253. const int p = (int) prior;
  217254. if (p <= 1)
  217255. policy = SCHED_OTHER;
  217256. else
  217257. policy = SCHED_RR;
  217258. minp = sched_get_priority_min (policy);
  217259. maxp = sched_get_priority_max (policy);
  217260. if (p < 2)
  217261. param.sched_priority = 0;
  217262. else if (p == 2 )
  217263. // Set to middle of lower realtime priority range
  217264. param.sched_priority = minp + (maxp - minp) / 4;
  217265. else
  217266. // Set to middle of higher realtime priority range
  217267. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  217268. pthread_setschedparam (pthread_self(), policy, &param);
  217269. }
  217270. void Process::terminate()
  217271. {
  217272. exit (0);
  217273. }
  217274. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  217275. {
  217276. static char testResult = 0;
  217277. if (testResult == 0)
  217278. {
  217279. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  217280. if (testResult >= 0)
  217281. {
  217282. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  217283. testResult = 1;
  217284. }
  217285. }
  217286. return testResult < 0;
  217287. }
  217288. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  217289. {
  217290. return juce_isRunningUnderDebugger();
  217291. }
  217292. void Process::raisePrivilege()
  217293. {
  217294. // If running suid root, change effective user
  217295. // to root
  217296. if (geteuid() != 0 && getuid() == 0)
  217297. {
  217298. setreuid (geteuid(), getuid());
  217299. setregid (getegid(), getgid());
  217300. }
  217301. }
  217302. void Process::lowerPrivilege()
  217303. {
  217304. // If runing suid root, change effective user
  217305. // back to real user
  217306. if (geteuid() == 0 && getuid() != 0)
  217307. {
  217308. setreuid (geteuid(), getuid());
  217309. setregid (getegid(), getgid());
  217310. }
  217311. }
  217312. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217313. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  217314. {
  217315. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  217316. }
  217317. void PlatformUtilities::freeDynamicLibrary (void* handle)
  217318. {
  217319. dlclose(handle);
  217320. }
  217321. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  217322. {
  217323. return dlsym (libraryHandle, procedureName.toCString());
  217324. }
  217325. #endif
  217326. #endif
  217327. /*** End of inlined file: juce_linux_Threads.cpp ***/
  217328. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217329. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  217330. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217331. // compiled on its own).
  217332. #if JUCE_INCLUDED_FILE
  217333. #if JUCE_DEBUG
  217334. #define JUCE_DEBUG_XERRORS 1
  217335. #endif
  217336. extern Display* display;
  217337. extern Window juce_messageWindowHandle;
  217338. namespace ClipboardHelpers
  217339. {
  217340. static String localClipboardContent;
  217341. static Atom atom_UTF8_STRING;
  217342. static Atom atom_CLIPBOARD;
  217343. static Atom atom_TARGETS;
  217344. static void initSelectionAtoms()
  217345. {
  217346. static bool isInitialised = false;
  217347. if (! isInitialised)
  217348. {
  217349. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  217350. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  217351. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  217352. }
  217353. }
  217354. // Read the content of a window property as either a locale-dependent string or an utf8 string
  217355. // works only for strings shorter than 1000000 bytes
  217356. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  217357. {
  217358. String returnData;
  217359. char* clipData;
  217360. Atom actualType;
  217361. int actualFormat;
  217362. unsigned long numItems, bytesLeft;
  217363. if (XGetWindowProperty (display, window, prop,
  217364. 0L /* offset */, 1000000 /* length (max) */, False,
  217365. AnyPropertyType /* format */,
  217366. &actualType, &actualFormat, &numItems, &bytesLeft,
  217367. (unsigned char**) &clipData) == Success)
  217368. {
  217369. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  217370. returnData = String::fromUTF8 (clipData, numItems);
  217371. else if (actualType == XA_STRING && actualFormat == 8)
  217372. returnData = String (clipData, numItems);
  217373. if (clipData != 0)
  217374. XFree (clipData);
  217375. jassert (bytesLeft == 0 || numItems == 1000000);
  217376. }
  217377. XDeleteProperty (display, window, prop);
  217378. return returnData;
  217379. }
  217380. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  217381. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  217382. {
  217383. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  217384. // The selection owner will be asked to set the JUCE_SEL property on the
  217385. // juce_messageWindowHandle with the selection content
  217386. XConvertSelection (display, selection, requestedFormat, property_name,
  217387. juce_messageWindowHandle, CurrentTime);
  217388. int count = 50; // will wait at most for 200 ms
  217389. while (--count >= 0)
  217390. {
  217391. XEvent event;
  217392. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  217393. {
  217394. if (event.xselection.property == property_name)
  217395. {
  217396. jassert (event.xselection.requestor == juce_messageWindowHandle);
  217397. selectionContent = readWindowProperty (event.xselection.requestor,
  217398. event.xselection.property,
  217399. requestedFormat);
  217400. return true;
  217401. }
  217402. else
  217403. {
  217404. return false; // the format we asked for was denied.. (event.xselection.property == None)
  217405. }
  217406. }
  217407. // not very elegant.. we could do a select() or something like that...
  217408. // however clipboard content requesting is inherently slow on x11, it
  217409. // often takes 50ms or more so...
  217410. Thread::sleep (4);
  217411. }
  217412. return false;
  217413. }
  217414. }
  217415. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  217416. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  217417. {
  217418. ClipboardHelpers::initSelectionAtoms();
  217419. // the selection content is sent to the target window as a window property
  217420. XSelectionEvent reply;
  217421. reply.type = SelectionNotify;
  217422. reply.display = evt.display;
  217423. reply.requestor = evt.requestor;
  217424. reply.selection = evt.selection;
  217425. reply.target = evt.target;
  217426. reply.property = None; // == "fail"
  217427. reply.time = evt.time;
  217428. HeapBlock <char> data;
  217429. int propertyFormat = 0, numDataItems = 0;
  217430. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  217431. {
  217432. if (evt.target == XA_STRING)
  217433. {
  217434. // format data according to system locale
  217435. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  217436. data.calloc (numDataItems + 1);
  217437. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  217438. propertyFormat = 8; // bits/item
  217439. }
  217440. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  217441. {
  217442. // translate to utf8
  217443. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  217444. data.calloc (numDataItems + 1);
  217445. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  217446. propertyFormat = 8; // bits/item
  217447. }
  217448. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  217449. {
  217450. // another application wants to know what we are able to send
  217451. numDataItems = 2;
  217452. propertyFormat = 32; // atoms are 32-bit
  217453. data.calloc (numDataItems * 4);
  217454. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  217455. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  217456. atoms[1] = XA_STRING;
  217457. }
  217458. }
  217459. else
  217460. {
  217461. DBG ("requested unsupported clipboard");
  217462. }
  217463. if (data != 0)
  217464. {
  217465. const int maxReasonableSelectionSize = 1000000;
  217466. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  217467. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  217468. {
  217469. XChangeProperty (evt.display, evt.requestor,
  217470. evt.property, evt.target,
  217471. propertyFormat /* 8 or 32 */, PropModeReplace,
  217472. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  217473. reply.property = evt.property; // " == success"
  217474. }
  217475. }
  217476. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  217477. }
  217478. void SystemClipboard::copyTextToClipboard (const String& clipText)
  217479. {
  217480. ClipboardHelpers::initSelectionAtoms();
  217481. ClipboardHelpers::localClipboardContent = clipText;
  217482. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  217483. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  217484. }
  217485. const String SystemClipboard::getTextFromClipboard()
  217486. {
  217487. ClipboardHelpers::initSelectionAtoms();
  217488. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  217489. level" clipboard that is supposed to be filled by ctrl-C
  217490. etc). When a clipboard manager is running, the content of this
  217491. selection is preserved even when the original selection owner
  217492. exits.
  217493. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  217494. filled by good old x11 apps such as xterm)
  217495. */
  217496. String content;
  217497. Atom selection = XA_PRIMARY;
  217498. Window selectionOwner = None;
  217499. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  217500. {
  217501. selection = ClipboardHelpers::atom_CLIPBOARD;
  217502. selectionOwner = XGetSelectionOwner (display, selection);
  217503. }
  217504. if (selectionOwner != None)
  217505. {
  217506. if (selectionOwner == juce_messageWindowHandle)
  217507. {
  217508. content = ClipboardHelpers::localClipboardContent;
  217509. }
  217510. else
  217511. {
  217512. // first try: we want an utf8 string
  217513. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  217514. if (! ok)
  217515. {
  217516. // second chance, ask for a good old locale-dependent string ..
  217517. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  217518. }
  217519. }
  217520. }
  217521. return content;
  217522. }
  217523. #endif
  217524. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  217525. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  217526. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217527. // compiled on its own).
  217528. #if JUCE_INCLUDED_FILE
  217529. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  217530. #define JUCE_DEBUG_XERRORS 1
  217531. #endif
  217532. Display* display = 0;
  217533. Window juce_messageWindowHandle = None;
  217534. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  217535. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  217536. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  217537. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  217538. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  217539. class InternalMessageQueue
  217540. {
  217541. public:
  217542. InternalMessageQueue()
  217543. : bytesInSocket (0),
  217544. totalEventCount (0)
  217545. {
  217546. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  217547. (void) ret; jassert (ret == 0);
  217548. //setNonBlocking (fd[0]);
  217549. //setNonBlocking (fd[1]);
  217550. }
  217551. ~InternalMessageQueue()
  217552. {
  217553. close (fd[0]);
  217554. close (fd[1]);
  217555. clearSingletonInstance();
  217556. }
  217557. void postMessage (Message* msg)
  217558. {
  217559. const int maxBytesInSocketQueue = 128;
  217560. ScopedLock sl (lock);
  217561. queue.add (msg);
  217562. if (bytesInSocket < maxBytesInSocketQueue)
  217563. {
  217564. ++bytesInSocket;
  217565. ScopedUnlock ul (lock);
  217566. const unsigned char x = 0xff;
  217567. size_t bytesWritten = write (fd[0], &x, 1);
  217568. (void) bytesWritten;
  217569. }
  217570. }
  217571. bool isEmpty() const
  217572. {
  217573. ScopedLock sl (lock);
  217574. return queue.size() == 0;
  217575. }
  217576. bool dispatchNextEvent()
  217577. {
  217578. // This alternates between giving priority to XEvents or internal messages,
  217579. // to keep everything running smoothly..
  217580. if ((++totalEventCount & 1) != 0)
  217581. return dispatchNextXEvent() || dispatchNextInternalMessage();
  217582. else
  217583. return dispatchNextInternalMessage() || dispatchNextXEvent();
  217584. }
  217585. // Wait for an event (either XEvent, or an internal Message)
  217586. bool sleepUntilEvent (const int timeoutMs)
  217587. {
  217588. if (! isEmpty())
  217589. return true;
  217590. if (display != 0)
  217591. {
  217592. ScopedXLock xlock;
  217593. if (XPending (display))
  217594. return true;
  217595. }
  217596. struct timeval tv;
  217597. tv.tv_sec = 0;
  217598. tv.tv_usec = timeoutMs * 1000;
  217599. int fd0 = getWaitHandle();
  217600. int fdmax = fd0;
  217601. fd_set readset;
  217602. FD_ZERO (&readset);
  217603. FD_SET (fd0, &readset);
  217604. if (display != 0)
  217605. {
  217606. ScopedXLock xlock;
  217607. int fd1 = XConnectionNumber (display);
  217608. FD_SET (fd1, &readset);
  217609. fdmax = jmax (fd0, fd1);
  217610. }
  217611. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  217612. return (ret > 0); // ret <= 0 if error or timeout
  217613. }
  217614. struct MessageThreadFuncCall
  217615. {
  217616. enum { uniqueID = 0x73774623 };
  217617. MessageCallbackFunction* func;
  217618. void* parameter;
  217619. void* result;
  217620. CriticalSection lock;
  217621. WaitableEvent event;
  217622. };
  217623. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  217624. private:
  217625. CriticalSection lock;
  217626. OwnedArray <Message> queue;
  217627. int fd[2];
  217628. int bytesInSocket;
  217629. int totalEventCount;
  217630. int getWaitHandle() const throw() { return fd[1]; }
  217631. static bool setNonBlocking (int handle)
  217632. {
  217633. int socketFlags = fcntl (handle, F_GETFL, 0);
  217634. if (socketFlags == -1)
  217635. return false;
  217636. socketFlags |= O_NONBLOCK;
  217637. return fcntl (handle, F_SETFL, socketFlags) == 0;
  217638. }
  217639. static bool dispatchNextXEvent()
  217640. {
  217641. if (display == 0)
  217642. return false;
  217643. XEvent evt;
  217644. {
  217645. ScopedXLock xlock;
  217646. if (! XPending (display))
  217647. return false;
  217648. XNextEvent (display, &evt);
  217649. }
  217650. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  217651. juce_handleSelectionRequest (evt.xselectionrequest);
  217652. else if (evt.xany.window != juce_messageWindowHandle)
  217653. juce_windowMessageReceive (&evt);
  217654. return true;
  217655. }
  217656. Message* popNextMessage()
  217657. {
  217658. ScopedLock sl (lock);
  217659. if (bytesInSocket > 0)
  217660. {
  217661. --bytesInSocket;
  217662. ScopedUnlock ul (lock);
  217663. unsigned char x;
  217664. size_t numBytes = read (fd[1], &x, 1);
  217665. (void) numBytes;
  217666. }
  217667. return queue.removeAndReturn (0);
  217668. }
  217669. bool dispatchNextInternalMessage()
  217670. {
  217671. ScopedPointer <Message> msg (popNextMessage());
  217672. if (msg == 0)
  217673. return false;
  217674. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  217675. {
  217676. // Handle callback message
  217677. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  217678. call->result = (*(call->func)) (call->parameter);
  217679. call->event.signal();
  217680. }
  217681. else
  217682. {
  217683. // Handle "normal" messages
  217684. MessageManager::getInstance()->deliverMessage (msg.release());
  217685. }
  217686. return true;
  217687. }
  217688. };
  217689. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  217690. namespace LinuxErrorHandling
  217691. {
  217692. static bool errorOccurred = false;
  217693. static bool keyboardBreakOccurred = false;
  217694. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  217695. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  217696. // Usually happens when client-server connection is broken
  217697. static int ioErrorHandler (Display* display)
  217698. {
  217699. DBG ("ERROR: connection to X server broken.. terminating.");
  217700. if (JUCEApplication::isStandaloneApp)
  217701. MessageManager::getInstance()->stopDispatchLoop();
  217702. errorOccurred = true;
  217703. return 0;
  217704. }
  217705. // A protocol error has occurred
  217706. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  217707. {
  217708. #if JUCE_DEBUG_XERRORS
  217709. char errorStr[64] = { 0 };
  217710. char requestStr[64] = { 0 };
  217711. XGetErrorText (display, event->error_code, errorStr, 64);
  217712. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  217713. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  217714. #endif
  217715. return 0;
  217716. }
  217717. static void installXErrorHandlers()
  217718. {
  217719. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  217720. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  217721. }
  217722. static void removeXErrorHandlers()
  217723. {
  217724. XSetIOErrorHandler (oldIOErrorHandler);
  217725. oldIOErrorHandler = 0;
  217726. XSetErrorHandler (oldErrorHandler);
  217727. oldErrorHandler = 0;
  217728. }
  217729. static void keyboardBreakSignalHandler (int sig)
  217730. {
  217731. if (sig == SIGINT)
  217732. keyboardBreakOccurred = true;
  217733. }
  217734. static void installKeyboardBreakHandler()
  217735. {
  217736. struct sigaction saction;
  217737. sigset_t maskSet;
  217738. sigemptyset (&maskSet);
  217739. saction.sa_handler = keyboardBreakSignalHandler;
  217740. saction.sa_mask = maskSet;
  217741. saction.sa_flags = 0;
  217742. sigaction (SIGINT, &saction, 0);
  217743. }
  217744. }
  217745. void MessageManager::doPlatformSpecificInitialisation()
  217746. {
  217747. // Initialise xlib for multiple thread support
  217748. static bool initThreadCalled = false;
  217749. if (! initThreadCalled)
  217750. {
  217751. if (! XInitThreads())
  217752. {
  217753. // This is fatal! Print error and closedown
  217754. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  217755. if (JUCEApplication::isStandaloneApp)
  217756. Process::terminate();
  217757. return;
  217758. }
  217759. initThreadCalled = true;
  217760. }
  217761. LinuxErrorHandling::installXErrorHandlers();
  217762. LinuxErrorHandling::installKeyboardBreakHandler();
  217763. // Create the internal message queue
  217764. InternalMessageQueue::getInstance();
  217765. // Try to connect to a display
  217766. String displayName (getenv ("DISPLAY"));
  217767. if (displayName.isEmpty())
  217768. displayName = ":0.0";
  217769. display = XOpenDisplay (displayName.toCString());
  217770. if (display != 0) // This is not fatal! we can run headless.
  217771. {
  217772. // Create a context to store user data associated with Windows we create in WindowDriver
  217773. windowHandleXContext = XUniqueContext();
  217774. // We're only interested in client messages for this window, which are always sent
  217775. XSetWindowAttributes swa;
  217776. swa.event_mask = NoEventMask;
  217777. // Create our message window (this will never be mapped)
  217778. const int screen = DefaultScreen (display);
  217779. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  217780. 0, 0, 1, 1, 0, 0, InputOnly,
  217781. DefaultVisual (display, screen),
  217782. CWEventMask, &swa);
  217783. }
  217784. }
  217785. void MessageManager::doPlatformSpecificShutdown()
  217786. {
  217787. InternalMessageQueue::deleteInstance();
  217788. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  217789. {
  217790. XDestroyWindow (display, juce_messageWindowHandle);
  217791. XCloseDisplay (display);
  217792. juce_messageWindowHandle = 0;
  217793. display = 0;
  217794. LinuxErrorHandling::removeXErrorHandlers();
  217795. }
  217796. }
  217797. bool juce_postMessageToSystemQueue (Message* message)
  217798. {
  217799. if (LinuxErrorHandling::errorOccurred)
  217800. return false;
  217801. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  217802. return true;
  217803. }
  217804. void MessageManager::broadcastMessage (const String& value) throw()
  217805. {
  217806. /* TODO */
  217807. }
  217808. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  217809. void* parameter)
  217810. {
  217811. if (LinuxErrorHandling::errorOccurred)
  217812. return 0;
  217813. if (isThisTheMessageThread())
  217814. return func (parameter);
  217815. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  217816. messageCallContext.func = func;
  217817. messageCallContext.parameter = parameter;
  217818. InternalMessageQueue::getInstanceWithoutCreating()
  217819. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  217820. 0, 0, &messageCallContext));
  217821. // Wait for it to complete before continuing
  217822. messageCallContext.event.wait();
  217823. return messageCallContext.result;
  217824. }
  217825. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  217826. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  217827. {
  217828. while (! LinuxErrorHandling::errorOccurred)
  217829. {
  217830. if (LinuxErrorHandling::keyboardBreakOccurred)
  217831. {
  217832. LinuxErrorHandling::errorOccurred = true;
  217833. if (JUCEApplication::isStandaloneApp)
  217834. Process::terminate();
  217835. break;
  217836. }
  217837. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  217838. return true;
  217839. if (returnIfNoPendingMessages)
  217840. break;
  217841. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  217842. }
  217843. return false;
  217844. }
  217845. #endif
  217846. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  217847. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  217848. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217849. // compiled on its own).
  217850. #if JUCE_INCLUDED_FILE
  217851. class FreeTypeFontFace
  217852. {
  217853. public:
  217854. enum FontStyle
  217855. {
  217856. Plain = 0,
  217857. Bold = 1,
  217858. Italic = 2
  217859. };
  217860. FreeTypeFontFace (const String& familyName)
  217861. : hasSerif (false),
  217862. monospaced (false)
  217863. {
  217864. family = familyName;
  217865. }
  217866. void setFileName (const String& name, const int faceIndex, FontStyle style)
  217867. {
  217868. if (names [(int) style].fileName.isEmpty())
  217869. {
  217870. names [(int) style].fileName = name;
  217871. names [(int) style].faceIndex = faceIndex;
  217872. }
  217873. }
  217874. const String& getFamilyName() const throw() { return family; }
  217875. const String& getFileName (const int style, int& faceIndex) const throw()
  217876. {
  217877. faceIndex = names[style].faceIndex;
  217878. return names[style].fileName;
  217879. }
  217880. void setMonospaced (bool mono) throw() { monospaced = mono; }
  217881. bool getMonospaced() const throw() { return monospaced; }
  217882. void setSerif (const bool serif) throw() { hasSerif = serif; }
  217883. bool getSerif() const throw() { return hasSerif; }
  217884. private:
  217885. String family;
  217886. struct FontNameIndex
  217887. {
  217888. String fileName;
  217889. int faceIndex;
  217890. };
  217891. FontNameIndex names[4];
  217892. bool hasSerif, monospaced;
  217893. };
  217894. class FreeTypeInterface : public DeletedAtShutdown
  217895. {
  217896. public:
  217897. FreeTypeInterface()
  217898. : ftLib (0),
  217899. lastFace (0),
  217900. lastBold (false),
  217901. lastItalic (false)
  217902. {
  217903. if (FT_Init_FreeType (&ftLib) != 0)
  217904. {
  217905. ftLib = 0;
  217906. DBG ("Failed to initialize FreeType");
  217907. }
  217908. StringArray fontDirs;
  217909. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  217910. fontDirs.removeEmptyStrings (true);
  217911. if (fontDirs.size() == 0)
  217912. {
  217913. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  217914. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  217915. if (fontsInfo != 0)
  217916. {
  217917. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  217918. {
  217919. fontDirs.add (e->getAllSubText().trim());
  217920. }
  217921. }
  217922. }
  217923. if (fontDirs.size() == 0)
  217924. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  217925. for (int i = 0; i < fontDirs.size(); ++i)
  217926. enumerateFaces (fontDirs[i]);
  217927. }
  217928. ~FreeTypeInterface()
  217929. {
  217930. if (lastFace != 0)
  217931. FT_Done_Face (lastFace);
  217932. if (ftLib != 0)
  217933. FT_Done_FreeType (ftLib);
  217934. clearSingletonInstance();
  217935. }
  217936. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  217937. {
  217938. for (int i = 0; i < faces.size(); i++)
  217939. if (faces[i]->getFamilyName() == familyName)
  217940. return faces[i];
  217941. if (! create)
  217942. return 0;
  217943. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  217944. faces.add (newFace);
  217945. return newFace;
  217946. }
  217947. // Enumerate all font faces available in a given directory
  217948. void enumerateFaces (const String& path)
  217949. {
  217950. File dirPath (path);
  217951. if (path.isEmpty() || ! dirPath.isDirectory())
  217952. return;
  217953. DirectoryIterator di (dirPath, true);
  217954. while (di.next())
  217955. {
  217956. File possible (di.getFile());
  217957. if (possible.hasFileExtension ("ttf")
  217958. || possible.hasFileExtension ("pfb")
  217959. || possible.hasFileExtension ("pcf"))
  217960. {
  217961. FT_Face face;
  217962. int faceIndex = 0;
  217963. int numFaces = 0;
  217964. do
  217965. {
  217966. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  217967. faceIndex, &face) == 0)
  217968. {
  217969. if (faceIndex == 0)
  217970. numFaces = face->num_faces;
  217971. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  217972. {
  217973. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  217974. int style = (int) FreeTypeFontFace::Plain;
  217975. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  217976. style |= (int) FreeTypeFontFace::Bold;
  217977. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  217978. style |= (int) FreeTypeFontFace::Italic;
  217979. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  217980. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  217981. // Surely there must be a better way to do this?
  217982. const String name (face->family_name);
  217983. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  217984. || name.containsIgnoreCase ("Verdana")
  217985. || name.containsIgnoreCase ("Arial")));
  217986. }
  217987. FT_Done_Face (face);
  217988. }
  217989. ++faceIndex;
  217990. }
  217991. while (faceIndex < numFaces);
  217992. }
  217993. }
  217994. }
  217995. // Create a FreeType face object for a given font
  217996. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  217997. {
  217998. FT_Face face = 0;
  217999. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  218000. {
  218001. face = lastFace;
  218002. }
  218003. else
  218004. {
  218005. if (lastFace != 0)
  218006. {
  218007. FT_Done_Face (lastFace);
  218008. lastFace = 0;
  218009. }
  218010. lastFontName = fontName;
  218011. lastBold = bold;
  218012. lastItalic = italic;
  218013. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  218014. if (ftFace != 0)
  218015. {
  218016. int style = (int) FreeTypeFontFace::Plain;
  218017. if (bold)
  218018. style |= (int) FreeTypeFontFace::Bold;
  218019. if (italic)
  218020. style |= (int) FreeTypeFontFace::Italic;
  218021. int faceIndex;
  218022. String fileName (ftFace->getFileName (style, faceIndex));
  218023. if (fileName.isEmpty())
  218024. {
  218025. style ^= (int) FreeTypeFontFace::Bold;
  218026. fileName = ftFace->getFileName (style, faceIndex);
  218027. if (fileName.isEmpty())
  218028. {
  218029. style ^= (int) FreeTypeFontFace::Bold;
  218030. style ^= (int) FreeTypeFontFace::Italic;
  218031. fileName = ftFace->getFileName (style, faceIndex);
  218032. if (! fileName.length())
  218033. {
  218034. style ^= (int) FreeTypeFontFace::Bold;
  218035. fileName = ftFace->getFileName (style, faceIndex);
  218036. }
  218037. }
  218038. }
  218039. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  218040. {
  218041. face = lastFace;
  218042. // If there isn't a unicode charmap then select the first one.
  218043. if (FT_Select_Charmap (face, ft_encoding_unicode))
  218044. FT_Set_Charmap (face, face->charmaps[0]);
  218045. }
  218046. }
  218047. }
  218048. return face;
  218049. }
  218050. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  218051. {
  218052. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  218053. const float height = (float) (face->ascender - face->descender);
  218054. const float scaleX = 1.0f / height;
  218055. const float scaleY = -1.0f / height;
  218056. Path destShape;
  218057. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  218058. || face->glyph->format != ft_glyph_format_outline)
  218059. {
  218060. return false;
  218061. }
  218062. const FT_Outline* const outline = &face->glyph->outline;
  218063. const short* const contours = outline->contours;
  218064. const char* const tags = outline->tags;
  218065. FT_Vector* const points = outline->points;
  218066. for (int c = 0; c < outline->n_contours; c++)
  218067. {
  218068. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  218069. const int endPoint = contours[c];
  218070. for (int p = startPoint; p <= endPoint; p++)
  218071. {
  218072. const float x = scaleX * points[p].x;
  218073. const float y = scaleY * points[p].y;
  218074. if (p == startPoint)
  218075. {
  218076. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218077. {
  218078. float x2 = scaleX * points [endPoint].x;
  218079. float y2 = scaleY * points [endPoint].y;
  218080. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  218081. {
  218082. x2 = (x + x2) * 0.5f;
  218083. y2 = (y + y2) * 0.5f;
  218084. }
  218085. destShape.startNewSubPath (x2, y2);
  218086. }
  218087. else
  218088. {
  218089. destShape.startNewSubPath (x, y);
  218090. }
  218091. }
  218092. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  218093. {
  218094. if (p != startPoint)
  218095. destShape.lineTo (x, y);
  218096. }
  218097. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218098. {
  218099. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  218100. float x2 = scaleX * points [nextIndex].x;
  218101. float y2 = scaleY * points [nextIndex].y;
  218102. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  218103. {
  218104. x2 = (x + x2) * 0.5f;
  218105. y2 = (y + y2) * 0.5f;
  218106. }
  218107. else
  218108. {
  218109. ++p;
  218110. }
  218111. destShape.quadraticTo (x, y, x2, y2);
  218112. }
  218113. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  218114. {
  218115. if (p >= endPoint)
  218116. return false;
  218117. const int next1 = p + 1;
  218118. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  218119. const float x2 = scaleX * points [next1].x;
  218120. const float y2 = scaleY * points [next1].y;
  218121. const float x3 = scaleX * points [next2].x;
  218122. const float y3 = scaleY * points [next2].y;
  218123. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  218124. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  218125. return false;
  218126. destShape.cubicTo (x, y, x2, y2, x3, y3);
  218127. p += 2;
  218128. }
  218129. }
  218130. destShape.closeSubPath();
  218131. }
  218132. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  218133. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  218134. addKerning (face, dest, character, glyphIndex);
  218135. return true;
  218136. }
  218137. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  218138. {
  218139. const float height = (float) (face->ascender - face->descender);
  218140. uint32 rightGlyphIndex;
  218141. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  218142. while (rightGlyphIndex != 0)
  218143. {
  218144. FT_Vector kerning;
  218145. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  218146. {
  218147. if (kerning.x != 0)
  218148. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  218149. }
  218150. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  218151. }
  218152. }
  218153. // Add a glyph to a font
  218154. bool addGlyphToFont (const uint32 character, const String& fontName,
  218155. bool bold, bool italic, CustomTypeface& dest)
  218156. {
  218157. FT_Face face = createFT_Face (fontName, bold, italic);
  218158. return face != 0 && addGlyph (face, dest, character);
  218159. }
  218160. void getFamilyNames (StringArray& familyNames) const
  218161. {
  218162. for (int i = 0; i < faces.size(); i++)
  218163. familyNames.add (faces[i]->getFamilyName());
  218164. }
  218165. void getMonospacedNames (StringArray& monoSpaced) const
  218166. {
  218167. for (int i = 0; i < faces.size(); i++)
  218168. if (faces[i]->getMonospaced())
  218169. monoSpaced.add (faces[i]->getFamilyName());
  218170. }
  218171. void getSerifNames (StringArray& serif) const
  218172. {
  218173. for (int i = 0; i < faces.size(); i++)
  218174. if (faces[i]->getSerif())
  218175. serif.add (faces[i]->getFamilyName());
  218176. }
  218177. void getSansSerifNames (StringArray& sansSerif) const
  218178. {
  218179. for (int i = 0; i < faces.size(); i++)
  218180. if (! faces[i]->getSerif())
  218181. sansSerif.add (faces[i]->getFamilyName());
  218182. }
  218183. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  218184. private:
  218185. FT_Library ftLib;
  218186. FT_Face lastFace;
  218187. String lastFontName;
  218188. bool lastBold, lastItalic;
  218189. OwnedArray<FreeTypeFontFace> faces;
  218190. };
  218191. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  218192. class FreetypeTypeface : public CustomTypeface
  218193. {
  218194. public:
  218195. FreetypeTypeface (const Font& font)
  218196. {
  218197. FT_Face face = FreeTypeInterface::getInstance()
  218198. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  218199. if (face == 0)
  218200. {
  218201. #if JUCE_DEBUG
  218202. String msg ("Failed to create typeface: ");
  218203. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  218204. DBG (msg);
  218205. #endif
  218206. }
  218207. else
  218208. {
  218209. setCharacteristics (font.getTypefaceName(),
  218210. face->ascender / (float) (face->ascender - face->descender),
  218211. font.isBold(), font.isItalic(),
  218212. L' ');
  218213. }
  218214. }
  218215. bool loadGlyphIfPossible (juce_wchar character)
  218216. {
  218217. return FreeTypeInterface::getInstance()
  218218. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  218219. }
  218220. };
  218221. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  218222. {
  218223. return new FreetypeTypeface (font);
  218224. }
  218225. const StringArray Font::findAllTypefaceNames()
  218226. {
  218227. StringArray s;
  218228. FreeTypeInterface::getInstance()->getFamilyNames (s);
  218229. s.sort (true);
  218230. return s;
  218231. }
  218232. static const String pickBestFont (const StringArray& names,
  218233. const char* const choicesString)
  218234. {
  218235. StringArray choices;
  218236. choices.addTokens (String (choicesString), ",", String::empty);
  218237. choices.trim();
  218238. choices.removeEmptyStrings();
  218239. int i, j;
  218240. for (j = 0; j < choices.size(); ++j)
  218241. if (names.contains (choices[j], true))
  218242. return choices[j];
  218243. for (j = 0; j < choices.size(); ++j)
  218244. for (i = 0; i < names.size(); i++)
  218245. if (names[i].startsWithIgnoreCase (choices[j]))
  218246. return names[i];
  218247. for (j = 0; j < choices.size(); ++j)
  218248. for (i = 0; i < names.size(); i++)
  218249. if (names[i].containsIgnoreCase (choices[j]))
  218250. return names[i];
  218251. return names[0];
  218252. }
  218253. static const String linux_getDefaultSansSerifFontName()
  218254. {
  218255. StringArray allFonts;
  218256. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  218257. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  218258. }
  218259. static const String linux_getDefaultSerifFontName()
  218260. {
  218261. StringArray allFonts;
  218262. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  218263. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  218264. }
  218265. static const String linux_getDefaultMonospacedFontName()
  218266. {
  218267. StringArray allFonts;
  218268. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  218269. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  218270. }
  218271. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  218272. {
  218273. defaultSans = linux_getDefaultSansSerifFontName();
  218274. defaultSerif = linux_getDefaultSerifFontName();
  218275. defaultFixed = linux_getDefaultMonospacedFontName();
  218276. }
  218277. #endif
  218278. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  218279. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  218280. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218281. // compiled on its own).
  218282. #if JUCE_INCLUDED_FILE
  218283. // These are defined in juce_linux_Messaging.cpp
  218284. extern Display* display;
  218285. extern XContext windowHandleXContext;
  218286. namespace Atoms
  218287. {
  218288. enum ProtocolItems
  218289. {
  218290. TAKE_FOCUS = 0,
  218291. DELETE_WINDOW = 1,
  218292. PING = 2
  218293. };
  218294. static Atom Protocols, ProtocolList[3], ChangeState, State,
  218295. ActiveWin, Pid, WindowType, WindowState,
  218296. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  218297. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  218298. XdndActionDescription, XdndActionCopy,
  218299. allowedActions[5],
  218300. allowedMimeTypes[2];
  218301. const unsigned long DndVersion = 3;
  218302. static void initialiseAtoms()
  218303. {
  218304. static bool atomsInitialised = false;
  218305. if (! atomsInitialised)
  218306. {
  218307. atomsInitialised = true;
  218308. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  218309. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  218310. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  218311. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  218312. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  218313. State = XInternAtom (display, "WM_STATE", True);
  218314. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  218315. Pid = XInternAtom (display, "_NET_WM_PID", False);
  218316. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  218317. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  218318. XdndAware = XInternAtom (display, "XdndAware", False);
  218319. XdndEnter = XInternAtom (display, "XdndEnter", False);
  218320. XdndLeave = XInternAtom (display, "XdndLeave", False);
  218321. XdndPosition = XInternAtom (display, "XdndPosition", False);
  218322. XdndStatus = XInternAtom (display, "XdndStatus", False);
  218323. XdndDrop = XInternAtom (display, "XdndDrop", False);
  218324. XdndFinished = XInternAtom (display, "XdndFinished", False);
  218325. XdndSelection = XInternAtom (display, "XdndSelection", False);
  218326. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  218327. XdndActionList = XInternAtom (display, "XdndActionList", False);
  218328. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  218329. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  218330. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  218331. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  218332. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  218333. allowedActions[1] = XdndActionCopy;
  218334. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  218335. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  218336. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  218337. }
  218338. }
  218339. }
  218340. namespace Keys
  218341. {
  218342. enum MouseButtons
  218343. {
  218344. NoButton = 0,
  218345. LeftButton = 1,
  218346. MiddleButton = 2,
  218347. RightButton = 3,
  218348. WheelUp = 4,
  218349. WheelDown = 5
  218350. };
  218351. static int AltMask = 0;
  218352. static int NumLockMask = 0;
  218353. static bool numLock = false;
  218354. static bool capsLock = false;
  218355. static char keyStates [32];
  218356. static const int extendedKeyModifier = 0x10000000;
  218357. }
  218358. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  218359. {
  218360. int keysym;
  218361. if (keyCode & Keys::extendedKeyModifier)
  218362. {
  218363. keysym = 0xff00 | (keyCode & 0xff);
  218364. }
  218365. else
  218366. {
  218367. keysym = keyCode;
  218368. if (keysym == (XK_Tab & 0xff)
  218369. || keysym == (XK_Return & 0xff)
  218370. || keysym == (XK_Escape & 0xff)
  218371. || keysym == (XK_BackSpace & 0xff))
  218372. {
  218373. keysym |= 0xff00;
  218374. }
  218375. }
  218376. ScopedXLock xlock;
  218377. const int keycode = XKeysymToKeycode (display, keysym);
  218378. const int keybyte = keycode >> 3;
  218379. const int keybit = (1 << (keycode & 7));
  218380. return (Keys::keyStates [keybyte] & keybit) != 0;
  218381. }
  218382. #if JUCE_USE_XSHM
  218383. namespace XSHMHelpers
  218384. {
  218385. static int trappedErrorCode = 0;
  218386. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  218387. {
  218388. trappedErrorCode = err->error_code;
  218389. return 0;
  218390. }
  218391. static bool isShmAvailable() throw()
  218392. {
  218393. static bool isChecked = false;
  218394. static bool isAvailable = false;
  218395. if (! isChecked)
  218396. {
  218397. isChecked = true;
  218398. int major, minor;
  218399. Bool pixmaps;
  218400. ScopedXLock xlock;
  218401. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  218402. {
  218403. trappedErrorCode = 0;
  218404. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  218405. XShmSegmentInfo segmentInfo;
  218406. zerostruct (segmentInfo);
  218407. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  218408. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  218409. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218410. xImage->bytes_per_line * xImage->height,
  218411. IPC_CREAT | 0777)) >= 0)
  218412. {
  218413. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218414. if (segmentInfo.shmaddr != (void*) -1)
  218415. {
  218416. segmentInfo.readOnly = False;
  218417. xImage->data = segmentInfo.shmaddr;
  218418. XSync (display, False);
  218419. if (XShmAttach (display, &segmentInfo) != 0)
  218420. {
  218421. XSync (display, False);
  218422. XShmDetach (display, &segmentInfo);
  218423. isAvailable = true;
  218424. }
  218425. }
  218426. XFlush (display);
  218427. XDestroyImage (xImage);
  218428. shmdt (segmentInfo.shmaddr);
  218429. }
  218430. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218431. XSetErrorHandler (oldHandler);
  218432. if (trappedErrorCode != 0)
  218433. isAvailable = false;
  218434. }
  218435. }
  218436. return isAvailable;
  218437. }
  218438. }
  218439. #endif
  218440. #if JUCE_USE_XRENDER
  218441. namespace XRender
  218442. {
  218443. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  218444. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  218445. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  218446. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  218447. static tXRenderQueryVersion xRenderQueryVersion = 0;
  218448. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  218449. static tXRenderFindFormat xRenderFindFormat = 0;
  218450. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  218451. static bool isAvailable()
  218452. {
  218453. static bool hasLoaded = false;
  218454. if (! hasLoaded)
  218455. {
  218456. ScopedXLock xlock;
  218457. hasLoaded = true;
  218458. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  218459. if (h != 0)
  218460. {
  218461. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  218462. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  218463. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  218464. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  218465. }
  218466. if (xRenderQueryVersion != 0
  218467. && xRenderFindStandardFormat != 0
  218468. && xRenderFindFormat != 0
  218469. && xRenderFindVisualFormat != 0)
  218470. {
  218471. int major, minor;
  218472. if (xRenderQueryVersion (display, &major, &minor))
  218473. return true;
  218474. }
  218475. xRenderQueryVersion = 0;
  218476. }
  218477. return xRenderQueryVersion != 0;
  218478. }
  218479. static XRenderPictFormat* findPictureFormat()
  218480. {
  218481. ScopedXLock xlock;
  218482. XRenderPictFormat* pictFormat = 0;
  218483. if (isAvailable())
  218484. {
  218485. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  218486. if (pictFormat == 0)
  218487. {
  218488. XRenderPictFormat desiredFormat;
  218489. desiredFormat.type = PictTypeDirect;
  218490. desiredFormat.depth = 32;
  218491. desiredFormat.direct.alphaMask = 0xff;
  218492. desiredFormat.direct.redMask = 0xff;
  218493. desiredFormat.direct.greenMask = 0xff;
  218494. desiredFormat.direct.blueMask = 0xff;
  218495. desiredFormat.direct.alpha = 24;
  218496. desiredFormat.direct.red = 16;
  218497. desiredFormat.direct.green = 8;
  218498. desiredFormat.direct.blue = 0;
  218499. pictFormat = xRenderFindFormat (display,
  218500. PictFormatType | PictFormatDepth
  218501. | PictFormatRedMask | PictFormatRed
  218502. | PictFormatGreenMask | PictFormatGreen
  218503. | PictFormatBlueMask | PictFormatBlue
  218504. | PictFormatAlphaMask | PictFormatAlpha,
  218505. &desiredFormat,
  218506. 0);
  218507. }
  218508. }
  218509. return pictFormat;
  218510. }
  218511. }
  218512. #endif
  218513. namespace Visuals
  218514. {
  218515. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  218516. {
  218517. ScopedXLock xlock;
  218518. Visual* visual = 0;
  218519. int numVisuals = 0;
  218520. long desiredMask = VisualNoMask;
  218521. XVisualInfo desiredVisual;
  218522. desiredVisual.screen = DefaultScreen (display);
  218523. desiredVisual.depth = desiredDepth;
  218524. desiredMask = VisualScreenMask | VisualDepthMask;
  218525. if (desiredDepth == 32)
  218526. {
  218527. desiredVisual.c_class = TrueColor;
  218528. desiredVisual.red_mask = 0x00FF0000;
  218529. desiredVisual.green_mask = 0x0000FF00;
  218530. desiredVisual.blue_mask = 0x000000FF;
  218531. desiredVisual.bits_per_rgb = 8;
  218532. desiredMask |= VisualClassMask;
  218533. desiredMask |= VisualRedMaskMask;
  218534. desiredMask |= VisualGreenMaskMask;
  218535. desiredMask |= VisualBlueMaskMask;
  218536. desiredMask |= VisualBitsPerRGBMask;
  218537. }
  218538. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218539. desiredMask,
  218540. &desiredVisual,
  218541. &numVisuals);
  218542. if (xvinfos != 0)
  218543. {
  218544. for (int i = 0; i < numVisuals; i++)
  218545. {
  218546. if (xvinfos[i].depth == desiredDepth)
  218547. {
  218548. visual = xvinfos[i].visual;
  218549. break;
  218550. }
  218551. }
  218552. XFree (xvinfos);
  218553. }
  218554. return visual;
  218555. }
  218556. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  218557. {
  218558. Visual* visual = 0;
  218559. if (desiredDepth == 32)
  218560. {
  218561. #if JUCE_USE_XSHM
  218562. if (XSHMHelpers::isShmAvailable())
  218563. {
  218564. #if JUCE_USE_XRENDER
  218565. if (XRender::isAvailable())
  218566. {
  218567. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  218568. if (pictFormat != 0)
  218569. {
  218570. int numVisuals = 0;
  218571. XVisualInfo desiredVisual;
  218572. desiredVisual.screen = DefaultScreen (display);
  218573. desiredVisual.depth = 32;
  218574. desiredVisual.bits_per_rgb = 8;
  218575. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218576. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  218577. &desiredVisual, &numVisuals);
  218578. if (xvinfos != 0)
  218579. {
  218580. for (int i = 0; i < numVisuals; ++i)
  218581. {
  218582. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  218583. if (pictVisualFormat != 0
  218584. && pictVisualFormat->type == PictTypeDirect
  218585. && pictVisualFormat->direct.alphaMask)
  218586. {
  218587. visual = xvinfos[i].visual;
  218588. matchedDepth = 32;
  218589. break;
  218590. }
  218591. }
  218592. XFree (xvinfos);
  218593. }
  218594. }
  218595. }
  218596. #endif
  218597. if (visual == 0)
  218598. {
  218599. visual = findVisualWithDepth (32);
  218600. if (visual != 0)
  218601. matchedDepth = 32;
  218602. }
  218603. }
  218604. #endif
  218605. }
  218606. if (visual == 0 && desiredDepth >= 24)
  218607. {
  218608. visual = findVisualWithDepth (24);
  218609. if (visual != 0)
  218610. matchedDepth = 24;
  218611. }
  218612. if (visual == 0 && desiredDepth >= 16)
  218613. {
  218614. visual = findVisualWithDepth (16);
  218615. if (visual != 0)
  218616. matchedDepth = 16;
  218617. }
  218618. return visual;
  218619. }
  218620. }
  218621. class XBitmapImage : public Image::SharedImage
  218622. {
  218623. public:
  218624. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  218625. const bool clearImage, const int imageDepth_, Visual* visual)
  218626. : Image::SharedImage (format_, w, h),
  218627. imageDepth (imageDepth_),
  218628. gc (None)
  218629. {
  218630. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  218631. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  218632. lineStride = ((w * pixelStride + 3) & ~3);
  218633. ScopedXLock xlock;
  218634. #if JUCE_USE_XSHM
  218635. usingXShm = false;
  218636. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  218637. {
  218638. zerostruct (segmentInfo);
  218639. segmentInfo.shmid = -1;
  218640. segmentInfo.shmaddr = (char *) -1;
  218641. segmentInfo.readOnly = False;
  218642. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  218643. if (xImage != 0)
  218644. {
  218645. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218646. xImage->bytes_per_line * xImage->height,
  218647. IPC_CREAT | 0777)) >= 0)
  218648. {
  218649. if (segmentInfo.shmid != -1)
  218650. {
  218651. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218652. if (segmentInfo.shmaddr != (void*) -1)
  218653. {
  218654. segmentInfo.readOnly = False;
  218655. xImage->data = segmentInfo.shmaddr;
  218656. imageData = (uint8*) segmentInfo.shmaddr;
  218657. if (XShmAttach (display, &segmentInfo) != 0)
  218658. usingXShm = true;
  218659. else
  218660. jassertfalse;
  218661. }
  218662. else
  218663. {
  218664. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218665. }
  218666. }
  218667. }
  218668. }
  218669. }
  218670. if (! usingXShm)
  218671. #endif
  218672. {
  218673. imageDataAllocated.malloc (lineStride * h);
  218674. imageData = imageDataAllocated;
  218675. if (format_ == Image::ARGB && clearImage)
  218676. zeromem (imageData, h * lineStride);
  218677. xImage = (XImage*) juce_calloc (sizeof (XImage));
  218678. xImage->width = w;
  218679. xImage->height = h;
  218680. xImage->xoffset = 0;
  218681. xImage->format = ZPixmap;
  218682. xImage->data = (char*) imageData;
  218683. xImage->byte_order = ImageByteOrder (display);
  218684. xImage->bitmap_unit = BitmapUnit (display);
  218685. xImage->bitmap_bit_order = BitmapBitOrder (display);
  218686. xImage->bitmap_pad = 32;
  218687. xImage->depth = pixelStride * 8;
  218688. xImage->bytes_per_line = lineStride;
  218689. xImage->bits_per_pixel = pixelStride * 8;
  218690. xImage->red_mask = 0x00FF0000;
  218691. xImage->green_mask = 0x0000FF00;
  218692. xImage->blue_mask = 0x000000FF;
  218693. if (imageDepth == 16)
  218694. {
  218695. const int pixelStride = 2;
  218696. const int lineStride = ((w * pixelStride + 3) & ~3);
  218697. imageData16Bit.malloc (lineStride * h);
  218698. xImage->data = imageData16Bit;
  218699. xImage->bitmap_pad = 16;
  218700. xImage->depth = pixelStride * 8;
  218701. xImage->bytes_per_line = lineStride;
  218702. xImage->bits_per_pixel = pixelStride * 8;
  218703. xImage->red_mask = visual->red_mask;
  218704. xImage->green_mask = visual->green_mask;
  218705. xImage->blue_mask = visual->blue_mask;
  218706. }
  218707. if (! XInitImage (xImage))
  218708. jassertfalse;
  218709. }
  218710. }
  218711. ~XBitmapImage()
  218712. {
  218713. ScopedXLock xlock;
  218714. if (gc != None)
  218715. XFreeGC (display, gc);
  218716. #if JUCE_USE_XSHM
  218717. if (usingXShm)
  218718. {
  218719. XShmDetach (display, &segmentInfo);
  218720. XFlush (display);
  218721. XDestroyImage (xImage);
  218722. shmdt (segmentInfo.shmaddr);
  218723. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218724. }
  218725. else
  218726. #endif
  218727. {
  218728. xImage->data = 0;
  218729. XDestroyImage (xImage);
  218730. }
  218731. }
  218732. Image::ImageType getType() const { return Image::NativeImage; }
  218733. LowLevelGraphicsContext* createLowLevelContext()
  218734. {
  218735. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  218736. }
  218737. SharedImage* clone()
  218738. {
  218739. jassertfalse;
  218740. return 0;
  218741. }
  218742. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  218743. {
  218744. ScopedXLock xlock;
  218745. if (gc == None)
  218746. {
  218747. XGCValues gcvalues;
  218748. gcvalues.foreground = None;
  218749. gcvalues.background = None;
  218750. gcvalues.function = GXcopy;
  218751. gcvalues.plane_mask = AllPlanes;
  218752. gcvalues.clip_mask = None;
  218753. gcvalues.graphics_exposures = False;
  218754. gc = XCreateGC (display, window,
  218755. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  218756. &gcvalues);
  218757. }
  218758. if (imageDepth == 16)
  218759. {
  218760. const uint32 rMask = xImage->red_mask;
  218761. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  218762. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  218763. const uint32 gMask = xImage->green_mask;
  218764. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  218765. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  218766. const uint32 bMask = xImage->blue_mask;
  218767. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  218768. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  218769. const Image::BitmapData srcData (Image (this), false);
  218770. for (int y = sy; y < sy + dh; ++y)
  218771. {
  218772. const uint8* p = srcData.getPixelPointer (sx, y);
  218773. for (int x = sx; x < sx + dw; ++x)
  218774. {
  218775. const PixelRGB* const pixel = (const PixelRGB*) p;
  218776. p += srcData.pixelStride;
  218777. XPutPixel (xImage, x, y,
  218778. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  218779. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  218780. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  218781. }
  218782. }
  218783. }
  218784. // blit results to screen.
  218785. #if JUCE_USE_XSHM
  218786. if (usingXShm)
  218787. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  218788. else
  218789. #endif
  218790. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  218791. }
  218792. juce_UseDebuggingNewOperator
  218793. private:
  218794. XImage* xImage;
  218795. const int imageDepth;
  218796. HeapBlock <uint8> imageDataAllocated;
  218797. HeapBlock <char> imageData16Bit;
  218798. GC gc;
  218799. #if JUCE_USE_XSHM
  218800. XShmSegmentInfo segmentInfo;
  218801. bool usingXShm;
  218802. #endif
  218803. static int getShiftNeeded (const uint32 mask) throw()
  218804. {
  218805. for (int i = 32; --i >= 0;)
  218806. if (((mask >> i) & 1) != 0)
  218807. return i - 7;
  218808. jassertfalse;
  218809. return 0;
  218810. }
  218811. };
  218812. class LinuxComponentPeer : public ComponentPeer
  218813. {
  218814. public:
  218815. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  218816. : ComponentPeer (component, windowStyleFlags),
  218817. windowH (0),
  218818. parentWindow (0),
  218819. wx (0),
  218820. wy (0),
  218821. ww (0),
  218822. wh (0),
  218823. fullScreen (false),
  218824. mapped (false),
  218825. visual (0),
  218826. depth (0)
  218827. {
  218828. // it's dangerous to create a window on a thread other than the message thread..
  218829. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  218830. repainter = new LinuxRepaintManager (this);
  218831. createWindow();
  218832. setTitle (component->getName());
  218833. }
  218834. ~LinuxComponentPeer()
  218835. {
  218836. // it's dangerous to delete a window on a thread other than the message thread..
  218837. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  218838. deleteIconPixmaps();
  218839. destroyWindow();
  218840. windowH = 0;
  218841. }
  218842. void* getNativeHandle() const
  218843. {
  218844. return (void*) windowH;
  218845. }
  218846. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  218847. {
  218848. XPointer peer = 0;
  218849. ScopedXLock xlock;
  218850. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  218851. {
  218852. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  218853. peer = 0;
  218854. }
  218855. return (LinuxComponentPeer*) peer;
  218856. }
  218857. void setVisible (bool shouldBeVisible)
  218858. {
  218859. ScopedXLock xlock;
  218860. if (shouldBeVisible)
  218861. XMapWindow (display, windowH);
  218862. else
  218863. XUnmapWindow (display, windowH);
  218864. }
  218865. void setTitle (const String& title)
  218866. {
  218867. setWindowTitle (windowH, title);
  218868. }
  218869. void setPosition (int x, int y)
  218870. {
  218871. setBounds (x, y, ww, wh, false);
  218872. }
  218873. void setSize (int w, int h)
  218874. {
  218875. setBounds (wx, wy, w, h, false);
  218876. }
  218877. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  218878. {
  218879. fullScreen = isNowFullScreen;
  218880. if (windowH != 0)
  218881. {
  218882. Component::SafePointer<Component> deletionChecker (component);
  218883. wx = x;
  218884. wy = y;
  218885. ww = jmax (1, w);
  218886. wh = jmax (1, h);
  218887. ScopedXLock xlock;
  218888. // Make sure the Window manager does what we want
  218889. XSizeHints* hints = XAllocSizeHints();
  218890. hints->flags = USSize | USPosition;
  218891. hints->width = ww;
  218892. hints->height = wh;
  218893. hints->x = wx;
  218894. hints->y = wy;
  218895. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  218896. {
  218897. hints->min_width = hints->max_width = hints->width;
  218898. hints->min_height = hints->max_height = hints->height;
  218899. hints->flags |= PMinSize | PMaxSize;
  218900. }
  218901. XSetWMNormalHints (display, windowH, hints);
  218902. XFree (hints);
  218903. XMoveResizeWindow (display, windowH,
  218904. wx - windowBorder.getLeft(),
  218905. wy - windowBorder.getTop(), ww, wh);
  218906. if (deletionChecker != 0)
  218907. {
  218908. updateBorderSize();
  218909. handleMovedOrResized();
  218910. }
  218911. }
  218912. }
  218913. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  218914. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  218915. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  218916. {
  218917. return relativePosition + getScreenPosition();
  218918. }
  218919. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  218920. {
  218921. return screenPosition - getScreenPosition();
  218922. }
  218923. void setMinimised (bool shouldBeMinimised)
  218924. {
  218925. if (shouldBeMinimised)
  218926. {
  218927. Window root = RootWindow (display, DefaultScreen (display));
  218928. XClientMessageEvent clientMsg;
  218929. clientMsg.display = display;
  218930. clientMsg.window = windowH;
  218931. clientMsg.type = ClientMessage;
  218932. clientMsg.format = 32;
  218933. clientMsg.message_type = Atoms::ChangeState;
  218934. clientMsg.data.l[0] = IconicState;
  218935. ScopedXLock xlock;
  218936. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  218937. }
  218938. else
  218939. {
  218940. setVisible (true);
  218941. }
  218942. }
  218943. bool isMinimised() const
  218944. {
  218945. bool minimised = false;
  218946. unsigned char* stateProp;
  218947. unsigned long nitems, bytesLeft;
  218948. Atom actualType;
  218949. int actualFormat;
  218950. ScopedXLock xlock;
  218951. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  218952. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  218953. &stateProp) == Success
  218954. && actualType == Atoms::State
  218955. && actualFormat == 32
  218956. && nitems > 0)
  218957. {
  218958. if (((unsigned long*) stateProp)[0] == IconicState)
  218959. minimised = true;
  218960. XFree (stateProp);
  218961. }
  218962. return minimised;
  218963. }
  218964. void setFullScreen (const bool shouldBeFullScreen)
  218965. {
  218966. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  218967. setMinimised (false);
  218968. if (fullScreen != shouldBeFullScreen)
  218969. {
  218970. if (shouldBeFullScreen)
  218971. r = Desktop::getInstance().getMainMonitorArea();
  218972. if (! r.isEmpty())
  218973. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  218974. getComponent()->repaint();
  218975. }
  218976. }
  218977. bool isFullScreen() const
  218978. {
  218979. return fullScreen;
  218980. }
  218981. bool isChildWindowOf (Window possibleParent) const
  218982. {
  218983. Window* windowList = 0;
  218984. uint32 windowListSize = 0;
  218985. Window parent, root;
  218986. ScopedXLock xlock;
  218987. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  218988. {
  218989. if (windowList != 0)
  218990. XFree (windowList);
  218991. return parent == possibleParent;
  218992. }
  218993. return false;
  218994. }
  218995. bool isFrontWindow() const
  218996. {
  218997. Window* windowList = 0;
  218998. uint32 windowListSize = 0;
  218999. bool result = false;
  219000. ScopedXLock xlock;
  219001. Window parent, root = RootWindow (display, DefaultScreen (display));
  219002. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  219003. {
  219004. for (int i = windowListSize; --i >= 0;)
  219005. {
  219006. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  219007. if (peer != 0)
  219008. {
  219009. result = (peer == this);
  219010. break;
  219011. }
  219012. }
  219013. }
  219014. if (windowList != 0)
  219015. XFree (windowList);
  219016. return result;
  219017. }
  219018. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  219019. {
  219020. int x = position.getX();
  219021. int y = position.getY();
  219022. if (((unsigned int) x) >= (unsigned int) ww
  219023. || ((unsigned int) y) >= (unsigned int) wh)
  219024. return false;
  219025. bool inFront = false;
  219026. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  219027. {
  219028. Component* const c = Desktop::getInstance().getComponent (i);
  219029. if (inFront)
  219030. {
  219031. if (c->contains (x + wx - c->getScreenX(),
  219032. y + wy - c->getScreenY()))
  219033. {
  219034. return false;
  219035. }
  219036. }
  219037. else if (c == getComponent())
  219038. {
  219039. inFront = true;
  219040. }
  219041. }
  219042. if (trueIfInAChildWindow)
  219043. return true;
  219044. ::Window root, child;
  219045. unsigned int bw, depth;
  219046. int wx, wy, w, h;
  219047. ScopedXLock xlock;
  219048. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  219049. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  219050. &bw, &depth))
  219051. {
  219052. return false;
  219053. }
  219054. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  219055. return false;
  219056. return child == None;
  219057. }
  219058. const BorderSize getFrameSize() const
  219059. {
  219060. return BorderSize();
  219061. }
  219062. bool setAlwaysOnTop (bool alwaysOnTop)
  219063. {
  219064. return false;
  219065. }
  219066. void toFront (bool makeActive)
  219067. {
  219068. if (makeActive)
  219069. {
  219070. setVisible (true);
  219071. grabFocus();
  219072. }
  219073. XEvent ev;
  219074. ev.xclient.type = ClientMessage;
  219075. ev.xclient.serial = 0;
  219076. ev.xclient.send_event = True;
  219077. ev.xclient.message_type = Atoms::ActiveWin;
  219078. ev.xclient.window = windowH;
  219079. ev.xclient.format = 32;
  219080. ev.xclient.data.l[0] = 2;
  219081. ev.xclient.data.l[1] = CurrentTime;
  219082. ev.xclient.data.l[2] = 0;
  219083. ev.xclient.data.l[3] = 0;
  219084. ev.xclient.data.l[4] = 0;
  219085. {
  219086. ScopedXLock xlock;
  219087. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  219088. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  219089. XWindowAttributes attr;
  219090. XGetWindowAttributes (display, windowH, &attr);
  219091. if (component->isAlwaysOnTop())
  219092. XRaiseWindow (display, windowH);
  219093. XSync (display, False);
  219094. }
  219095. handleBroughtToFront();
  219096. }
  219097. void toBehind (ComponentPeer* other)
  219098. {
  219099. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  219100. jassert (otherPeer != 0); // wrong type of window?
  219101. if (otherPeer != 0)
  219102. {
  219103. setMinimised (false);
  219104. Window newStack[] = { otherPeer->windowH, windowH };
  219105. ScopedXLock xlock;
  219106. XRestackWindows (display, newStack, 2);
  219107. }
  219108. }
  219109. bool isFocused() const
  219110. {
  219111. int revert = 0;
  219112. Window focusedWindow = 0;
  219113. ScopedXLock xlock;
  219114. XGetInputFocus (display, &focusedWindow, &revert);
  219115. return focusedWindow == windowH;
  219116. }
  219117. void grabFocus()
  219118. {
  219119. XWindowAttributes atts;
  219120. ScopedXLock xlock;
  219121. if (windowH != 0
  219122. && XGetWindowAttributes (display, windowH, &atts)
  219123. && atts.map_state == IsViewable
  219124. && ! isFocused())
  219125. {
  219126. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  219127. isActiveApplication = true;
  219128. }
  219129. }
  219130. void textInputRequired (const Point<int>&)
  219131. {
  219132. }
  219133. void repaint (const Rectangle<int>& area)
  219134. {
  219135. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  219136. }
  219137. void performAnyPendingRepaintsNow()
  219138. {
  219139. repainter->performAnyPendingRepaintsNow();
  219140. }
  219141. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  219142. {
  219143. ScopedXLock xlock;
  219144. const int width = image.getWidth();
  219145. const int height = image.getHeight();
  219146. HeapBlock <char> colour (width * height);
  219147. int index = 0;
  219148. for (int y = 0; y < height; ++y)
  219149. for (int x = 0; x < width; ++x)
  219150. colour[index++] = static_cast<char> (image.getPixelAt (x, y).getARGB());
  219151. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  219152. 0, colour.getData(),
  219153. width, height, 32, 0);
  219154. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  219155. width, height, 24);
  219156. GC gc = XCreateGC (display, pixmap, 0, 0);
  219157. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  219158. XFreeGC (display, gc);
  219159. return pixmap;
  219160. }
  219161. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  219162. {
  219163. ScopedXLock xlock;
  219164. const int width = image.getWidth();
  219165. const int height = image.getHeight();
  219166. const int stride = (width + 7) >> 3;
  219167. HeapBlock <char> mask;
  219168. mask.calloc (stride * height);
  219169. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  219170. for (int y = 0; y < height; ++y)
  219171. {
  219172. for (int x = 0; x < width; ++x)
  219173. {
  219174. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  219175. const int offset = y * stride + (x >> 3);
  219176. if (image.getPixelAt (x, y).getAlpha() >= 128)
  219177. mask[offset] |= bit;
  219178. }
  219179. }
  219180. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  219181. mask.getData(), width, height, 1, 0, 1);
  219182. }
  219183. void setIcon (const Image& newIcon)
  219184. {
  219185. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  219186. HeapBlock <unsigned long> data (dataSize);
  219187. int index = 0;
  219188. data[index++] = newIcon.getWidth();
  219189. data[index++] = newIcon.getHeight();
  219190. for (int y = 0; y < newIcon.getHeight(); ++y)
  219191. for (int x = 0; x < newIcon.getWidth(); ++x)
  219192. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  219193. ScopedXLock xlock;
  219194. XChangeProperty (display, windowH,
  219195. XInternAtom (display, "_NET_WM_ICON", False),
  219196. XA_CARDINAL, 32, PropModeReplace,
  219197. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  219198. deleteIconPixmaps();
  219199. XWMHints* wmHints = XGetWMHints (display, windowH);
  219200. if (wmHints == 0)
  219201. wmHints = XAllocWMHints();
  219202. wmHints->flags |= IconPixmapHint | IconMaskHint;
  219203. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  219204. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  219205. XSetWMHints (display, windowH, wmHints);
  219206. XFree (wmHints);
  219207. XSync (display, False);
  219208. }
  219209. void deleteIconPixmaps()
  219210. {
  219211. ScopedXLock xlock;
  219212. XWMHints* wmHints = XGetWMHints (display, windowH);
  219213. if (wmHints != 0)
  219214. {
  219215. if ((wmHints->flags & IconPixmapHint) != 0)
  219216. {
  219217. wmHints->flags &= ~IconPixmapHint;
  219218. XFreePixmap (display, wmHints->icon_pixmap);
  219219. }
  219220. if ((wmHints->flags & IconMaskHint) != 0)
  219221. {
  219222. wmHints->flags &= ~IconMaskHint;
  219223. XFreePixmap (display, wmHints->icon_mask);
  219224. }
  219225. XSetWMHints (display, windowH, wmHints);
  219226. XFree (wmHints);
  219227. }
  219228. }
  219229. void handleWindowMessage (XEvent* event)
  219230. {
  219231. switch (event->xany.type)
  219232. {
  219233. case 2: // 'KeyPress'
  219234. {
  219235. ScopedXLock xlock;
  219236. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  219237. updateKeyStates (keyEvent->keycode, true);
  219238. char utf8 [64];
  219239. zeromem (utf8, sizeof (utf8));
  219240. KeySym sym;
  219241. {
  219242. const char* oldLocale = ::setlocale (LC_ALL, 0);
  219243. ::setlocale (LC_ALL, "");
  219244. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  219245. ::setlocale (LC_ALL, oldLocale);
  219246. }
  219247. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  219248. int keyCode = (int) unicodeChar;
  219249. if (keyCode < 0x20)
  219250. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  219251. const ModifierKeys oldMods (currentModifiers);
  219252. bool keyPressed = false;
  219253. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  219254. if ((sym & 0xff00) == 0xff00)
  219255. {
  219256. // Translate keypad
  219257. if (sym == XK_KP_Divide)
  219258. keyCode = XK_slash;
  219259. else if (sym == XK_KP_Multiply)
  219260. keyCode = XK_asterisk;
  219261. else if (sym == XK_KP_Subtract)
  219262. keyCode = XK_hyphen;
  219263. else if (sym == XK_KP_Add)
  219264. keyCode = XK_plus;
  219265. else if (sym == XK_KP_Enter)
  219266. keyCode = XK_Return;
  219267. else if (sym == XK_KP_Decimal)
  219268. keyCode = Keys::numLock ? XK_period : XK_Delete;
  219269. else if (sym == XK_KP_0)
  219270. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  219271. else if (sym == XK_KP_1)
  219272. keyCode = Keys::numLock ? XK_1 : XK_End;
  219273. else if (sym == XK_KP_2)
  219274. keyCode = Keys::numLock ? XK_2 : XK_Down;
  219275. else if (sym == XK_KP_3)
  219276. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  219277. else if (sym == XK_KP_4)
  219278. keyCode = Keys::numLock ? XK_4 : XK_Left;
  219279. else if (sym == XK_KP_5)
  219280. keyCode = XK_5;
  219281. else if (sym == XK_KP_6)
  219282. keyCode = Keys::numLock ? XK_6 : XK_Right;
  219283. else if (sym == XK_KP_7)
  219284. keyCode = Keys::numLock ? XK_7 : XK_Home;
  219285. else if (sym == XK_KP_8)
  219286. keyCode = Keys::numLock ? XK_8 : XK_Up;
  219287. else if (sym == XK_KP_9)
  219288. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  219289. switch (sym)
  219290. {
  219291. case XK_Left:
  219292. case XK_Right:
  219293. case XK_Up:
  219294. case XK_Down:
  219295. case XK_Page_Up:
  219296. case XK_Page_Down:
  219297. case XK_End:
  219298. case XK_Home:
  219299. case XK_Delete:
  219300. case XK_Insert:
  219301. keyPressed = true;
  219302. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219303. break;
  219304. case XK_Tab:
  219305. case XK_Return:
  219306. case XK_Escape:
  219307. case XK_BackSpace:
  219308. keyPressed = true;
  219309. keyCode &= 0xff;
  219310. break;
  219311. default:
  219312. {
  219313. if (sym >= XK_F1 && sym <= XK_F16)
  219314. {
  219315. keyPressed = true;
  219316. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219317. }
  219318. break;
  219319. }
  219320. }
  219321. }
  219322. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  219323. keyPressed = true;
  219324. if (oldMods != currentModifiers)
  219325. handleModifierKeysChange();
  219326. if (keyDownChange)
  219327. handleKeyUpOrDown (true);
  219328. if (keyPressed)
  219329. handleKeyPress (keyCode, unicodeChar);
  219330. break;
  219331. }
  219332. case KeyRelease:
  219333. {
  219334. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  219335. updateKeyStates (keyEvent->keycode, false);
  219336. ScopedXLock xlock;
  219337. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  219338. const ModifierKeys oldMods (currentModifiers);
  219339. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  219340. if (oldMods != currentModifiers)
  219341. handleModifierKeysChange();
  219342. if (keyDownChange)
  219343. handleKeyUpOrDown (false);
  219344. break;
  219345. }
  219346. case ButtonPress:
  219347. {
  219348. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  219349. updateKeyModifiers (buttonPressEvent->state);
  219350. bool buttonMsg = false;
  219351. const int map = pointerMap [buttonPressEvent->button - Button1];
  219352. if (map == Keys::WheelUp || map == Keys::WheelDown)
  219353. {
  219354. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  219355. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  219356. }
  219357. if (map == Keys::LeftButton)
  219358. {
  219359. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  219360. buttonMsg = true;
  219361. }
  219362. else if (map == Keys::RightButton)
  219363. {
  219364. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  219365. buttonMsg = true;
  219366. }
  219367. else if (map == Keys::MiddleButton)
  219368. {
  219369. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  219370. buttonMsg = true;
  219371. }
  219372. if (buttonMsg)
  219373. {
  219374. toFront (true);
  219375. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  219376. getEventTime (buttonPressEvent->time));
  219377. }
  219378. clearLastMousePos();
  219379. break;
  219380. }
  219381. case ButtonRelease:
  219382. {
  219383. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  219384. updateKeyModifiers (buttonRelEvent->state);
  219385. const int map = pointerMap [buttonRelEvent->button - Button1];
  219386. if (map == Keys::LeftButton)
  219387. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  219388. else if (map == Keys::RightButton)
  219389. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  219390. else if (map == Keys::MiddleButton)
  219391. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  219392. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  219393. getEventTime (buttonRelEvent->time));
  219394. clearLastMousePos();
  219395. break;
  219396. }
  219397. case MotionNotify:
  219398. {
  219399. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  219400. updateKeyModifiers (movedEvent->state);
  219401. const Point<int> mousePos (Desktop::getMousePosition());
  219402. if (lastMousePos != mousePos)
  219403. {
  219404. lastMousePos = mousePos;
  219405. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  219406. {
  219407. Window wRoot = 0, wParent = 0;
  219408. {
  219409. ScopedXLock xlock;
  219410. unsigned int numChildren;
  219411. Window* wChild = 0;
  219412. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  219413. }
  219414. if (wParent != 0
  219415. && wParent != windowH
  219416. && wParent != wRoot)
  219417. {
  219418. parentWindow = wParent;
  219419. updateBounds();
  219420. }
  219421. else
  219422. {
  219423. parentWindow = 0;
  219424. }
  219425. }
  219426. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  219427. }
  219428. break;
  219429. }
  219430. case EnterNotify:
  219431. {
  219432. clearLastMousePos();
  219433. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  219434. if (! currentModifiers.isAnyMouseButtonDown())
  219435. {
  219436. updateKeyModifiers (enterEvent->state);
  219437. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  219438. }
  219439. break;
  219440. }
  219441. case LeaveNotify:
  219442. {
  219443. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  219444. // Suppress the normal leave if we've got a pointer grab, or if
  219445. // it's a bogus one caused by clicking a mouse button when running
  219446. // in a Window manager
  219447. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  219448. || leaveEvent->mode == NotifyUngrab)
  219449. {
  219450. updateKeyModifiers (leaveEvent->state);
  219451. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  219452. }
  219453. break;
  219454. }
  219455. case FocusIn:
  219456. {
  219457. isActiveApplication = true;
  219458. if (isFocused())
  219459. handleFocusGain();
  219460. break;
  219461. }
  219462. case FocusOut:
  219463. {
  219464. isActiveApplication = false;
  219465. if (! isFocused())
  219466. handleFocusLoss();
  219467. break;
  219468. }
  219469. case Expose:
  219470. {
  219471. // Batch together all pending expose events
  219472. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  219473. XEvent nextEvent;
  219474. ScopedXLock xlock;
  219475. if (exposeEvent->window != windowH)
  219476. {
  219477. Window child;
  219478. XTranslateCoordinates (display, exposeEvent->window, windowH,
  219479. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  219480. &child);
  219481. }
  219482. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  219483. exposeEvent->width, exposeEvent->height));
  219484. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  219485. {
  219486. XPeekEvent (display, (XEvent*) &nextEvent);
  219487. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  219488. break;
  219489. XNextEvent (display, (XEvent*) &nextEvent);
  219490. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  219491. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  219492. nextExposeEvent->width, nextExposeEvent->height));
  219493. }
  219494. break;
  219495. }
  219496. case CirculateNotify:
  219497. case CreateNotify:
  219498. case DestroyNotify:
  219499. // Think we can ignore these
  219500. break;
  219501. case ConfigureNotify:
  219502. {
  219503. updateBounds();
  219504. updateBorderSize();
  219505. handleMovedOrResized();
  219506. // if the native title bar is dragged, need to tell any active menus, etc.
  219507. if ((styleFlags & windowHasTitleBar) != 0
  219508. && component->isCurrentlyBlockedByAnotherModalComponent())
  219509. {
  219510. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  219511. if (currentModalComp != 0)
  219512. currentModalComp->inputAttemptWhenModal();
  219513. }
  219514. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  219515. if (confEvent->window == windowH
  219516. && confEvent->above != 0
  219517. && isFrontWindow())
  219518. {
  219519. handleBroughtToFront();
  219520. }
  219521. break;
  219522. }
  219523. case ReparentNotify:
  219524. {
  219525. parentWindow = 0;
  219526. Window wRoot = 0;
  219527. Window* wChild = 0;
  219528. unsigned int numChildren;
  219529. {
  219530. ScopedXLock xlock;
  219531. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  219532. }
  219533. if (parentWindow == windowH || parentWindow == wRoot)
  219534. parentWindow = 0;
  219535. updateBounds();
  219536. updateBorderSize();
  219537. handleMovedOrResized();
  219538. break;
  219539. }
  219540. case GravityNotify:
  219541. {
  219542. updateBounds();
  219543. updateBorderSize();
  219544. handleMovedOrResized();
  219545. break;
  219546. }
  219547. case MapNotify:
  219548. mapped = true;
  219549. handleBroughtToFront();
  219550. break;
  219551. case UnmapNotify:
  219552. mapped = false;
  219553. break;
  219554. case MappingNotify:
  219555. {
  219556. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  219557. if (mappingEvent->request != MappingPointer)
  219558. {
  219559. // Deal with modifier/keyboard mapping
  219560. ScopedXLock xlock;
  219561. XRefreshKeyboardMapping (mappingEvent);
  219562. updateModifierMappings();
  219563. }
  219564. break;
  219565. }
  219566. case ClientMessage:
  219567. {
  219568. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  219569. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  219570. {
  219571. const Atom atom = (Atom) clientMsg->data.l[0];
  219572. if (atom == Atoms::ProtocolList [Atoms::PING])
  219573. {
  219574. Window root = RootWindow (display, DefaultScreen (display));
  219575. event->xclient.window = root;
  219576. XSendEvent (display, root, False, NoEventMask, event);
  219577. XFlush (display);
  219578. }
  219579. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  219580. {
  219581. XWindowAttributes atts;
  219582. ScopedXLock xlock;
  219583. if (clientMsg->window != 0
  219584. && XGetWindowAttributes (display, clientMsg->window, &atts))
  219585. {
  219586. if (atts.map_state == IsViewable)
  219587. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  219588. }
  219589. }
  219590. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  219591. {
  219592. handleUserClosingWindow();
  219593. }
  219594. }
  219595. else if (clientMsg->message_type == Atoms::XdndEnter)
  219596. {
  219597. handleDragAndDropEnter (clientMsg);
  219598. }
  219599. else if (clientMsg->message_type == Atoms::XdndLeave)
  219600. {
  219601. resetDragAndDrop();
  219602. }
  219603. else if (clientMsg->message_type == Atoms::XdndPosition)
  219604. {
  219605. handleDragAndDropPosition (clientMsg);
  219606. }
  219607. else if (clientMsg->message_type == Atoms::XdndDrop)
  219608. {
  219609. handleDragAndDropDrop (clientMsg);
  219610. }
  219611. else if (clientMsg->message_type == Atoms::XdndStatus)
  219612. {
  219613. handleDragAndDropStatus (clientMsg);
  219614. }
  219615. else if (clientMsg->message_type == Atoms::XdndFinished)
  219616. {
  219617. resetDragAndDrop();
  219618. }
  219619. break;
  219620. }
  219621. case SelectionNotify:
  219622. handleDragAndDropSelection (event);
  219623. break;
  219624. case SelectionClear:
  219625. case SelectionRequest:
  219626. break;
  219627. default:
  219628. #if JUCE_USE_XSHM
  219629. {
  219630. ScopedXLock xlock;
  219631. if (event->xany.type == XShmGetEventBase (display))
  219632. repainter->notifyPaintCompleted();
  219633. }
  219634. #endif
  219635. break;
  219636. }
  219637. }
  219638. void showMouseCursor (Cursor cursor) throw()
  219639. {
  219640. ScopedXLock xlock;
  219641. XDefineCursor (display, windowH, cursor);
  219642. }
  219643. void setTaskBarIcon (const Image& image)
  219644. {
  219645. ScopedXLock xlock;
  219646. taskbarImage = image;
  219647. Screen* const screen = XDefaultScreenOfDisplay (display);
  219648. const int screenNumber = XScreenNumberOfScreen (screen);
  219649. String screenAtom ("_NET_SYSTEM_TRAY_S");
  219650. screenAtom << screenNumber;
  219651. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  219652. XGrabServer (display);
  219653. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  219654. if (managerWin != None)
  219655. XSelectInput (display, managerWin, StructureNotifyMask);
  219656. XUngrabServer (display);
  219657. XFlush (display);
  219658. if (managerWin != None)
  219659. {
  219660. XEvent ev;
  219661. zerostruct (ev);
  219662. ev.xclient.type = ClientMessage;
  219663. ev.xclient.window = managerWin;
  219664. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  219665. ev.xclient.format = 32;
  219666. ev.xclient.data.l[0] = CurrentTime;
  219667. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  219668. ev.xclient.data.l[2] = windowH;
  219669. ev.xclient.data.l[3] = 0;
  219670. ev.xclient.data.l[4] = 0;
  219671. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  219672. XSync (display, False);
  219673. }
  219674. // For older KDE's ...
  219675. long atomData = 1;
  219676. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  219677. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  219678. // For more recent KDE's...
  219679. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  219680. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  219681. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  219682. XSizeHints* hints = XAllocSizeHints();
  219683. hints->flags = PMinSize;
  219684. hints->min_width = 22;
  219685. hints->min_height = 22;
  219686. XSetWMNormalHints (display, windowH, hints);
  219687. XFree (hints);
  219688. }
  219689. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  219690. juce_UseDebuggingNewOperator
  219691. bool dontRepaint;
  219692. static ModifierKeys currentModifiers;
  219693. static bool isActiveApplication;
  219694. private:
  219695. class LinuxRepaintManager : public Timer
  219696. {
  219697. public:
  219698. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  219699. : peer (peer_),
  219700. lastTimeImageUsed (0)
  219701. {
  219702. #if JUCE_USE_XSHM
  219703. shmCompletedDrawing = true;
  219704. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  219705. if (useARGBImagesForRendering)
  219706. {
  219707. ScopedXLock xlock;
  219708. XShmSegmentInfo segmentinfo;
  219709. XImage* const testImage
  219710. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219711. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  219712. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  219713. XDestroyImage (testImage);
  219714. }
  219715. #endif
  219716. }
  219717. ~LinuxRepaintManager()
  219718. {
  219719. }
  219720. void timerCallback()
  219721. {
  219722. #if JUCE_USE_XSHM
  219723. if (! shmCompletedDrawing)
  219724. return;
  219725. #endif
  219726. if (! regionsNeedingRepaint.isEmpty())
  219727. {
  219728. stopTimer();
  219729. performAnyPendingRepaintsNow();
  219730. }
  219731. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  219732. {
  219733. stopTimer();
  219734. image = Image::null;
  219735. }
  219736. }
  219737. void repaint (const Rectangle<int>& area)
  219738. {
  219739. if (! isTimerRunning())
  219740. startTimer (repaintTimerPeriod);
  219741. regionsNeedingRepaint.add (area);
  219742. }
  219743. void performAnyPendingRepaintsNow()
  219744. {
  219745. #if JUCE_USE_XSHM
  219746. if (! shmCompletedDrawing)
  219747. {
  219748. startTimer (repaintTimerPeriod);
  219749. return;
  219750. }
  219751. #endif
  219752. peer->clearMaskedRegion();
  219753. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  219754. regionsNeedingRepaint.clear();
  219755. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  219756. if (! totalArea.isEmpty())
  219757. {
  219758. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  219759. || image.getHeight() < totalArea.getHeight())
  219760. {
  219761. #if JUCE_USE_XSHM
  219762. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  219763. : Image::RGB,
  219764. #else
  219765. image = Image (new XBitmapImage (Image::RGB,
  219766. #endif
  219767. (totalArea.getWidth() + 31) & ~31,
  219768. (totalArea.getHeight() + 31) & ~31,
  219769. false, peer->depth, peer->visual));
  219770. }
  219771. startTimer (repaintTimerPeriod);
  219772. RectangleList adjustedList (originalRepaintRegion);
  219773. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  219774. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  219775. if (peer->depth == 32)
  219776. {
  219777. RectangleList::Iterator i (originalRepaintRegion);
  219778. while (i.next())
  219779. image.clear (*i.getRectangle() - totalArea.getPosition());
  219780. }
  219781. peer->handlePaint (context);
  219782. if (! peer->maskedRegion.isEmpty())
  219783. originalRepaintRegion.subtract (peer->maskedRegion);
  219784. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  219785. {
  219786. #if JUCE_USE_XSHM
  219787. shmCompletedDrawing = false;
  219788. #endif
  219789. const Rectangle<int>& r = *i.getRectangle();
  219790. static_cast<XBitmapImage*> (image.getSharedImage())
  219791. ->blitToWindow (peer->windowH,
  219792. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  219793. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  219794. }
  219795. }
  219796. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  219797. startTimer (repaintTimerPeriod);
  219798. }
  219799. #if JUCE_USE_XSHM
  219800. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  219801. #endif
  219802. private:
  219803. enum { repaintTimerPeriod = 1000 / 100 };
  219804. LinuxComponentPeer* const peer;
  219805. Image image;
  219806. uint32 lastTimeImageUsed;
  219807. RectangleList regionsNeedingRepaint;
  219808. #if JUCE_USE_XSHM
  219809. bool useARGBImagesForRendering, shmCompletedDrawing;
  219810. #endif
  219811. LinuxRepaintManager (const LinuxRepaintManager&);
  219812. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  219813. };
  219814. ScopedPointer <LinuxRepaintManager> repainter;
  219815. friend class LinuxRepaintManager;
  219816. Window windowH, parentWindow;
  219817. int wx, wy, ww, wh;
  219818. Image taskbarImage;
  219819. bool fullScreen, mapped;
  219820. Visual* visual;
  219821. int depth;
  219822. BorderSize windowBorder;
  219823. struct MotifWmHints
  219824. {
  219825. unsigned long flags;
  219826. unsigned long functions;
  219827. unsigned long decorations;
  219828. long input_mode;
  219829. unsigned long status;
  219830. };
  219831. static void updateKeyStates (const int keycode, const bool press) throw()
  219832. {
  219833. const int keybyte = keycode >> 3;
  219834. const int keybit = (1 << (keycode & 7));
  219835. if (press)
  219836. Keys::keyStates [keybyte] |= keybit;
  219837. else
  219838. Keys::keyStates [keybyte] &= ~keybit;
  219839. }
  219840. static void updateKeyModifiers (const int status) throw()
  219841. {
  219842. int keyMods = 0;
  219843. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  219844. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  219845. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  219846. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  219847. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  219848. Keys::capsLock = ((status & LockMask) != 0);
  219849. }
  219850. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  219851. {
  219852. int modifier = 0;
  219853. bool isModifier = true;
  219854. switch (sym)
  219855. {
  219856. case XK_Shift_L:
  219857. case XK_Shift_R:
  219858. modifier = ModifierKeys::shiftModifier;
  219859. break;
  219860. case XK_Control_L:
  219861. case XK_Control_R:
  219862. modifier = ModifierKeys::ctrlModifier;
  219863. break;
  219864. case XK_Alt_L:
  219865. case XK_Alt_R:
  219866. modifier = ModifierKeys::altModifier;
  219867. break;
  219868. case XK_Num_Lock:
  219869. if (press)
  219870. Keys::numLock = ! Keys::numLock;
  219871. break;
  219872. case XK_Caps_Lock:
  219873. if (press)
  219874. Keys::capsLock = ! Keys::capsLock;
  219875. break;
  219876. case XK_Scroll_Lock:
  219877. break;
  219878. default:
  219879. isModifier = false;
  219880. break;
  219881. }
  219882. if (modifier != 0)
  219883. {
  219884. if (press)
  219885. currentModifiers = currentModifiers.withFlags (modifier);
  219886. else
  219887. currentModifiers = currentModifiers.withoutFlags (modifier);
  219888. }
  219889. return isModifier;
  219890. }
  219891. // Alt and Num lock are not defined by standard X
  219892. // modifier constants: check what they're mapped to
  219893. static void updateModifierMappings() throw()
  219894. {
  219895. ScopedXLock xlock;
  219896. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  219897. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  219898. Keys::AltMask = 0;
  219899. Keys::NumLockMask = 0;
  219900. XModifierKeymap* mapping = XGetModifierMapping (display);
  219901. if (mapping)
  219902. {
  219903. for (int i = 0; i < 8; i++)
  219904. {
  219905. if (mapping->modifiermap [i << 1] == altLeftCode)
  219906. Keys::AltMask = 1 << i;
  219907. else if (mapping->modifiermap [i << 1] == numLockCode)
  219908. Keys::NumLockMask = 1 << i;
  219909. }
  219910. XFreeModifiermap (mapping);
  219911. }
  219912. }
  219913. void removeWindowDecorations (Window wndH)
  219914. {
  219915. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  219916. if (hints != None)
  219917. {
  219918. MotifWmHints motifHints;
  219919. zerostruct (motifHints);
  219920. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  219921. motifHints.decorations = 0;
  219922. ScopedXLock xlock;
  219923. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219924. (unsigned char*) &motifHints, 4);
  219925. }
  219926. hints = XInternAtom (display, "_WIN_HINTS", True);
  219927. if (hints != None)
  219928. {
  219929. long gnomeHints = 0;
  219930. ScopedXLock xlock;
  219931. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219932. (unsigned char*) &gnomeHints, 1);
  219933. }
  219934. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  219935. if (hints != None)
  219936. {
  219937. long kwmHints = 2; /*KDE_tinyDecoration*/
  219938. ScopedXLock xlock;
  219939. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219940. (unsigned char*) &kwmHints, 1);
  219941. }
  219942. }
  219943. void addWindowButtons (Window wndH)
  219944. {
  219945. ScopedXLock xlock;
  219946. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  219947. if (hints != None)
  219948. {
  219949. MotifWmHints motifHints;
  219950. zerostruct (motifHints);
  219951. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  219952. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  219953. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  219954. if ((styleFlags & windowHasCloseButton) != 0)
  219955. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  219956. if ((styleFlags & windowHasMinimiseButton) != 0)
  219957. {
  219958. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  219959. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  219960. }
  219961. if ((styleFlags & windowHasMaximiseButton) != 0)
  219962. {
  219963. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  219964. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  219965. }
  219966. if ((styleFlags & windowIsResizable) != 0)
  219967. {
  219968. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  219969. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  219970. }
  219971. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  219972. }
  219973. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  219974. if (hints != None)
  219975. {
  219976. int netHints [6];
  219977. int num = 0;
  219978. if ((styleFlags & windowIsResizable) != 0)
  219979. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  219980. if ((styleFlags & windowHasMaximiseButton) != 0)
  219981. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  219982. if ((styleFlags & windowHasMinimiseButton) != 0)
  219983. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  219984. if ((styleFlags & windowHasCloseButton) != 0)
  219985. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  219986. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  219987. }
  219988. }
  219989. void setWindowType()
  219990. {
  219991. int netHints [2];
  219992. int numHints = 0;
  219993. if ((styleFlags & windowIsTemporary) != 0
  219994. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  219995. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  219996. else
  219997. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  219998. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  219999. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  220000. (unsigned char*) &netHints, numHints);
  220001. numHints = 0;
  220002. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  220003. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  220004. if (component->isAlwaysOnTop())
  220005. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  220006. if (numHints > 0)
  220007. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  220008. (unsigned char*) &netHints, numHints);
  220009. }
  220010. void createWindow()
  220011. {
  220012. ScopedXLock xlock;
  220013. Atoms::initialiseAtoms();
  220014. resetDragAndDrop();
  220015. // Get defaults for various properties
  220016. const int screen = DefaultScreen (display);
  220017. Window root = RootWindow (display, screen);
  220018. // Try to obtain a 32-bit visual or fallback to 24 or 16
  220019. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  220020. if (visual == 0)
  220021. {
  220022. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  220023. Process::terminate();
  220024. }
  220025. // Create and install a colormap suitable fr our visual
  220026. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  220027. XInstallColormap (display, colormap);
  220028. // Set up the window attributes
  220029. XSetWindowAttributes swa;
  220030. swa.border_pixel = 0;
  220031. swa.background_pixmap = None;
  220032. swa.colormap = colormap;
  220033. swa.event_mask = getAllEventsMask();
  220034. windowH = XCreateWindow (display, root,
  220035. 0, 0, 1, 1,
  220036. 0, depth, InputOutput, visual,
  220037. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  220038. &swa);
  220039. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  220040. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  220041. GrabModeAsync, GrabModeAsync, None, None);
  220042. // Set the window context to identify the window handle object
  220043. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  220044. {
  220045. // Failed
  220046. jassertfalse;
  220047. Logger::outputDebugString ("Failed to create context information for window.\n");
  220048. XDestroyWindow (display, windowH);
  220049. windowH = 0;
  220050. return;
  220051. }
  220052. // Set window manager hints
  220053. XWMHints* wmHints = XAllocWMHints();
  220054. wmHints->flags = InputHint | StateHint;
  220055. wmHints->input = True; // Locally active input model
  220056. wmHints->initial_state = NormalState;
  220057. XSetWMHints (display, windowH, wmHints);
  220058. XFree (wmHints);
  220059. // Set the window type
  220060. setWindowType();
  220061. // Define decoration
  220062. if ((styleFlags & windowHasTitleBar) == 0)
  220063. removeWindowDecorations (windowH);
  220064. else
  220065. addWindowButtons (windowH);
  220066. // Set window name
  220067. setWindowTitle (windowH, getComponent()->getName());
  220068. // Associate the PID, allowing to be shut down when something goes wrong
  220069. unsigned long pid = getpid();
  220070. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  220071. (unsigned char*) &pid, 1);
  220072. // Set window manager protocols
  220073. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  220074. (unsigned char*) Atoms::ProtocolList, 2);
  220075. // Set drag and drop flags
  220076. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  220077. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  220078. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  220079. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  220080. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  220081. (const unsigned char*) "", 0);
  220082. unsigned long dndVersion = Atoms::DndVersion;
  220083. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  220084. (const unsigned char*) &dndVersion, 1);
  220085. // Initialise the pointer and keyboard mapping
  220086. // This is not the same as the logical pointer mapping the X server uses:
  220087. // we don't mess with this.
  220088. static bool mappingInitialised = false;
  220089. if (! mappingInitialised)
  220090. {
  220091. mappingInitialised = true;
  220092. const int numButtons = XGetPointerMapping (display, 0, 0);
  220093. if (numButtons == 2)
  220094. {
  220095. pointerMap[0] = Keys::LeftButton;
  220096. pointerMap[1] = Keys::RightButton;
  220097. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  220098. }
  220099. else if (numButtons >= 3)
  220100. {
  220101. pointerMap[0] = Keys::LeftButton;
  220102. pointerMap[1] = Keys::MiddleButton;
  220103. pointerMap[2] = Keys::RightButton;
  220104. if (numButtons >= 5)
  220105. {
  220106. pointerMap[3] = Keys::WheelUp;
  220107. pointerMap[4] = Keys::WheelDown;
  220108. }
  220109. }
  220110. updateModifierMappings();
  220111. }
  220112. }
  220113. void destroyWindow()
  220114. {
  220115. ScopedXLock xlock;
  220116. XPointer handlePointer;
  220117. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  220118. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  220119. XDestroyWindow (display, windowH);
  220120. // Wait for it to complete and then remove any events for this
  220121. // window from the event queue.
  220122. XSync (display, false);
  220123. XEvent event;
  220124. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  220125. {}
  220126. }
  220127. static int getAllEventsMask() throw()
  220128. {
  220129. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  220130. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  220131. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  220132. }
  220133. static int64 getEventTime (::Time t)
  220134. {
  220135. static int64 eventTimeOffset = 0x12345678;
  220136. const int64 thisMessageTime = t;
  220137. if (eventTimeOffset == 0x12345678)
  220138. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  220139. return eventTimeOffset + thisMessageTime;
  220140. }
  220141. static void setWindowTitle (Window xwin, const String& title)
  220142. {
  220143. XTextProperty nameProperty;
  220144. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  220145. ScopedXLock xlock;
  220146. if (XStringListToTextProperty (strings, 1, &nameProperty))
  220147. {
  220148. XSetWMName (display, xwin, &nameProperty);
  220149. XSetWMIconName (display, xwin, &nameProperty);
  220150. XFree (nameProperty.value);
  220151. }
  220152. }
  220153. void updateBorderSize()
  220154. {
  220155. if ((styleFlags & windowHasTitleBar) == 0)
  220156. {
  220157. windowBorder = BorderSize (0);
  220158. }
  220159. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  220160. {
  220161. ScopedXLock xlock;
  220162. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  220163. if (hints != None)
  220164. {
  220165. unsigned char* data = 0;
  220166. unsigned long nitems, bytesLeft;
  220167. Atom actualType;
  220168. int actualFormat;
  220169. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  220170. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220171. &data) == Success)
  220172. {
  220173. const unsigned long* const sizes = (const unsigned long*) data;
  220174. if (actualFormat == 32)
  220175. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  220176. (int) sizes[3], (int) sizes[1]);
  220177. XFree (data);
  220178. }
  220179. }
  220180. }
  220181. }
  220182. void updateBounds()
  220183. {
  220184. jassert (windowH != 0);
  220185. if (windowH != 0)
  220186. {
  220187. Window root, child;
  220188. unsigned int bw, depth;
  220189. ScopedXLock xlock;
  220190. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220191. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  220192. &bw, &depth))
  220193. {
  220194. wx = wy = ww = wh = 0;
  220195. }
  220196. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  220197. {
  220198. wx = wy = 0;
  220199. }
  220200. }
  220201. }
  220202. void resetDragAndDrop()
  220203. {
  220204. dragAndDropFiles.clear();
  220205. lastDropPos = Point<int> (-1, -1);
  220206. dragAndDropCurrentMimeType = 0;
  220207. dragAndDropSourceWindow = 0;
  220208. srcMimeTypeAtomList.clear();
  220209. }
  220210. void sendDragAndDropMessage (XClientMessageEvent& msg)
  220211. {
  220212. msg.type = ClientMessage;
  220213. msg.display = display;
  220214. msg.window = dragAndDropSourceWindow;
  220215. msg.format = 32;
  220216. msg.data.l[0] = windowH;
  220217. ScopedXLock xlock;
  220218. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  220219. }
  220220. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  220221. {
  220222. XClientMessageEvent msg;
  220223. zerostruct (msg);
  220224. msg.message_type = Atoms::XdndStatus;
  220225. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  220226. msg.data.l[4] = dropAction;
  220227. sendDragAndDropMessage (msg);
  220228. }
  220229. void sendDragAndDropLeave()
  220230. {
  220231. XClientMessageEvent msg;
  220232. zerostruct (msg);
  220233. msg.message_type = Atoms::XdndLeave;
  220234. sendDragAndDropMessage (msg);
  220235. }
  220236. void sendDragAndDropFinish()
  220237. {
  220238. XClientMessageEvent msg;
  220239. zerostruct (msg);
  220240. msg.message_type = Atoms::XdndFinished;
  220241. sendDragAndDropMessage (msg);
  220242. }
  220243. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  220244. {
  220245. if ((clientMsg->data.l[1] & 1) == 0)
  220246. {
  220247. sendDragAndDropLeave();
  220248. if (dragAndDropFiles.size() > 0)
  220249. handleFileDragExit (dragAndDropFiles);
  220250. dragAndDropFiles.clear();
  220251. }
  220252. }
  220253. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  220254. {
  220255. if (dragAndDropSourceWindow == 0)
  220256. return;
  220257. dragAndDropSourceWindow = clientMsg->data.l[0];
  220258. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  220259. (int) clientMsg->data.l[2] & 0xffff);
  220260. dropPos -= getScreenPosition();
  220261. if (lastDropPos != dropPos)
  220262. {
  220263. lastDropPos = dropPos;
  220264. dragAndDropTimestamp = clientMsg->data.l[3];
  220265. Atom targetAction = Atoms::XdndActionCopy;
  220266. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  220267. {
  220268. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  220269. {
  220270. targetAction = Atoms::allowedActions[i];
  220271. break;
  220272. }
  220273. }
  220274. sendDragAndDropStatus (true, targetAction);
  220275. if (dragAndDropFiles.size() == 0)
  220276. updateDraggedFileList (clientMsg);
  220277. if (dragAndDropFiles.size() > 0)
  220278. handleFileDragMove (dragAndDropFiles, dropPos);
  220279. }
  220280. }
  220281. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  220282. {
  220283. if (dragAndDropFiles.size() == 0)
  220284. updateDraggedFileList (clientMsg);
  220285. const StringArray files (dragAndDropFiles);
  220286. const Point<int> lastPos (lastDropPos);
  220287. sendDragAndDropFinish();
  220288. resetDragAndDrop();
  220289. if (files.size() > 0)
  220290. handleFileDragDrop (files, lastPos);
  220291. }
  220292. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  220293. {
  220294. dragAndDropFiles.clear();
  220295. srcMimeTypeAtomList.clear();
  220296. dragAndDropCurrentMimeType = 0;
  220297. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  220298. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  220299. {
  220300. dragAndDropSourceWindow = 0;
  220301. return;
  220302. }
  220303. dragAndDropSourceWindow = clientMsg->data.l[0];
  220304. if ((clientMsg->data.l[1] & 1) != 0)
  220305. {
  220306. Atom actual;
  220307. int format;
  220308. unsigned long count = 0, remaining = 0;
  220309. unsigned char* data = 0;
  220310. ScopedXLock xlock;
  220311. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  220312. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  220313. &count, &remaining, &data);
  220314. if (data != 0)
  220315. {
  220316. if (actual == XA_ATOM && format == 32 && count != 0)
  220317. {
  220318. const unsigned long* const types = (const unsigned long*) data;
  220319. for (unsigned int i = 0; i < count; ++i)
  220320. if (types[i] != None)
  220321. srcMimeTypeAtomList.add (types[i]);
  220322. }
  220323. XFree (data);
  220324. }
  220325. }
  220326. if (srcMimeTypeAtomList.size() == 0)
  220327. {
  220328. for (int i = 2; i < 5; ++i)
  220329. if (clientMsg->data.l[i] != None)
  220330. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  220331. if (srcMimeTypeAtomList.size() == 0)
  220332. {
  220333. dragAndDropSourceWindow = 0;
  220334. return;
  220335. }
  220336. }
  220337. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  220338. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  220339. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  220340. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  220341. handleDragAndDropPosition (clientMsg);
  220342. }
  220343. void handleDragAndDropSelection (const XEvent* const evt)
  220344. {
  220345. dragAndDropFiles.clear();
  220346. if (evt->xselection.property != 0)
  220347. {
  220348. StringArray lines;
  220349. {
  220350. MemoryBlock dropData;
  220351. for (;;)
  220352. {
  220353. Atom actual;
  220354. uint8* data = 0;
  220355. unsigned long count = 0, remaining = 0;
  220356. int format = 0;
  220357. ScopedXLock xlock;
  220358. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  220359. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  220360. &format, &count, &remaining, &data) == Success)
  220361. {
  220362. dropData.append (data, count * format / 8);
  220363. XFree (data);
  220364. if (remaining == 0)
  220365. break;
  220366. }
  220367. else
  220368. {
  220369. XFree (data);
  220370. break;
  220371. }
  220372. }
  220373. lines.addLines (dropData.toString());
  220374. }
  220375. for (int i = 0; i < lines.size(); ++i)
  220376. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  220377. dragAndDropFiles.trim();
  220378. dragAndDropFiles.removeEmptyStrings();
  220379. }
  220380. }
  220381. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  220382. {
  220383. dragAndDropFiles.clear();
  220384. if (dragAndDropSourceWindow != None
  220385. && dragAndDropCurrentMimeType != 0)
  220386. {
  220387. dragAndDropTimestamp = clientMsg->data.l[2];
  220388. ScopedXLock xlock;
  220389. XConvertSelection (display,
  220390. Atoms::XdndSelection,
  220391. dragAndDropCurrentMimeType,
  220392. XInternAtom (display, "JXSelectionWindowProperty", 0),
  220393. windowH,
  220394. dragAndDropTimestamp);
  220395. }
  220396. }
  220397. StringArray dragAndDropFiles;
  220398. int dragAndDropTimestamp;
  220399. Point<int> lastDropPos;
  220400. Atom dragAndDropCurrentMimeType;
  220401. Window dragAndDropSourceWindow;
  220402. Array <Atom> srcMimeTypeAtomList;
  220403. static int pointerMap[5];
  220404. static Point<int> lastMousePos;
  220405. static void clearLastMousePos() throw()
  220406. {
  220407. lastMousePos = Point<int> (0x100000, 0x100000);
  220408. }
  220409. };
  220410. ModifierKeys LinuxComponentPeer::currentModifiers;
  220411. bool LinuxComponentPeer::isActiveApplication = false;
  220412. int LinuxComponentPeer::pointerMap[5];
  220413. Point<int> LinuxComponentPeer::lastMousePos;
  220414. bool Process::isForegroundProcess()
  220415. {
  220416. return LinuxComponentPeer::isActiveApplication;
  220417. }
  220418. void ModifierKeys::updateCurrentModifiers() throw()
  220419. {
  220420. currentModifiers = LinuxComponentPeer::currentModifiers;
  220421. }
  220422. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220423. {
  220424. Window root, child;
  220425. int x, y, winx, winy;
  220426. unsigned int mask;
  220427. int mouseMods = 0;
  220428. ScopedXLock xlock;
  220429. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  220430. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  220431. {
  220432. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  220433. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  220434. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  220435. }
  220436. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  220437. return LinuxComponentPeer::currentModifiers;
  220438. }
  220439. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  220440. {
  220441. if (enableOrDisable)
  220442. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  220443. }
  220444. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  220445. {
  220446. return new LinuxComponentPeer (this, styleFlags);
  220447. }
  220448. // (this callback is hooked up in the messaging code)
  220449. void juce_windowMessageReceive (XEvent* event)
  220450. {
  220451. if (event->xany.window != None)
  220452. {
  220453. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  220454. if (ComponentPeer::isValidPeer (peer))
  220455. peer->handleWindowMessage (event);
  220456. }
  220457. else
  220458. {
  220459. switch (event->xany.type)
  220460. {
  220461. case KeymapNotify:
  220462. {
  220463. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  220464. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  220465. break;
  220466. }
  220467. default:
  220468. break;
  220469. }
  220470. }
  220471. }
  220472. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  220473. {
  220474. if (display == 0)
  220475. return;
  220476. #if JUCE_USE_XINERAMA
  220477. int major_opcode, first_event, first_error;
  220478. ScopedXLock xlock;
  220479. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  220480. {
  220481. typedef Bool (*tXineramaIsActive) (Display*);
  220482. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  220483. static tXineramaIsActive xXineramaIsActive = 0;
  220484. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  220485. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  220486. {
  220487. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  220488. if (h == 0)
  220489. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  220490. if (h != 0)
  220491. {
  220492. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  220493. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  220494. }
  220495. }
  220496. if (xXineramaIsActive != 0
  220497. && xXineramaQueryScreens != 0
  220498. && xXineramaIsActive (display))
  220499. {
  220500. int numMonitors = 0;
  220501. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  220502. if (screens != 0)
  220503. {
  220504. for (int i = numMonitors; --i >= 0;)
  220505. {
  220506. int index = screens[i].screen_number;
  220507. if (index >= 0)
  220508. {
  220509. while (monitorCoords.size() < index)
  220510. monitorCoords.add (Rectangle<int>());
  220511. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  220512. screens[i].y_org,
  220513. screens[i].width,
  220514. screens[i].height));
  220515. }
  220516. }
  220517. XFree (screens);
  220518. }
  220519. }
  220520. }
  220521. if (monitorCoords.size() == 0)
  220522. #endif
  220523. {
  220524. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  220525. if (hints != None)
  220526. {
  220527. const int numMonitors = ScreenCount (display);
  220528. for (int i = 0; i < numMonitors; ++i)
  220529. {
  220530. Window root = RootWindow (display, i);
  220531. unsigned long nitems, bytesLeft;
  220532. Atom actualType;
  220533. int actualFormat;
  220534. unsigned char* data = 0;
  220535. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  220536. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220537. &data) == Success)
  220538. {
  220539. const long* const position = (const long*) data;
  220540. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  220541. monitorCoords.add (Rectangle<int> (position[0], position[1],
  220542. position[2], position[3]));
  220543. XFree (data);
  220544. }
  220545. }
  220546. }
  220547. if (monitorCoords.size() == 0)
  220548. {
  220549. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  220550. DisplayHeight (display, DefaultScreen (display))));
  220551. }
  220552. }
  220553. }
  220554. void Desktop::createMouseInputSources()
  220555. {
  220556. mouseSources.add (new MouseInputSource (0, true));
  220557. }
  220558. bool Desktop::canUseSemiTransparentWindows() throw()
  220559. {
  220560. int matchedDepth = 0;
  220561. const int desiredDepth = 32;
  220562. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  220563. && (matchedDepth == desiredDepth);
  220564. }
  220565. const Point<int> Desktop::getMousePosition()
  220566. {
  220567. Window root, child;
  220568. int x, y, winx, winy;
  220569. unsigned int mask;
  220570. ScopedXLock xlock;
  220571. if (XQueryPointer (display,
  220572. RootWindow (display, DefaultScreen (display)),
  220573. &root, &child,
  220574. &x, &y, &winx, &winy, &mask) == False)
  220575. {
  220576. // Pointer not on the default screen
  220577. x = y = -1;
  220578. }
  220579. return Point<int> (x, y);
  220580. }
  220581. void Desktop::setMousePosition (const Point<int>& newPosition)
  220582. {
  220583. ScopedXLock xlock;
  220584. Window root = RootWindow (display, DefaultScreen (display));
  220585. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  220586. }
  220587. static bool screenSaverAllowed = true;
  220588. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  220589. {
  220590. if (screenSaverAllowed != isEnabled)
  220591. {
  220592. screenSaverAllowed = isEnabled;
  220593. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  220594. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  220595. if (xScreenSaverSuspend == 0)
  220596. {
  220597. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  220598. if (h != 0)
  220599. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  220600. }
  220601. ScopedXLock xlock;
  220602. if (xScreenSaverSuspend != 0)
  220603. xScreenSaverSuspend (display, ! isEnabled);
  220604. }
  220605. }
  220606. bool Desktop::isScreenSaverEnabled()
  220607. {
  220608. return screenSaverAllowed;
  220609. }
  220610. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  220611. {
  220612. ScopedXLock xlock;
  220613. const unsigned int imageW = image.getWidth();
  220614. const unsigned int imageH = image.getHeight();
  220615. #if JUCE_USE_XCURSOR
  220616. {
  220617. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  220618. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  220619. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  220620. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  220621. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  220622. static tXcursorImageCreate xXcursorImageCreate = 0;
  220623. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  220624. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  220625. static bool hasBeenLoaded = false;
  220626. if (! hasBeenLoaded)
  220627. {
  220628. hasBeenLoaded = true;
  220629. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  220630. if (h != 0)
  220631. {
  220632. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  220633. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  220634. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  220635. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  220636. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  220637. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  220638. || ! xXcursorSupportsARGB (display))
  220639. xXcursorSupportsARGB = 0;
  220640. }
  220641. }
  220642. if (xXcursorSupportsARGB != 0)
  220643. {
  220644. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  220645. if (xcImage != 0)
  220646. {
  220647. xcImage->xhot = hotspotX;
  220648. xcImage->yhot = hotspotY;
  220649. XcursorPixel* dest = xcImage->pixels;
  220650. for (int y = 0; y < (int) imageH; ++y)
  220651. for (int x = 0; x < (int) imageW; ++x)
  220652. *dest++ = image.getPixelAt (x, y).getARGB();
  220653. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  220654. xXcursorImageDestroy (xcImage);
  220655. if (result != 0)
  220656. return result;
  220657. }
  220658. }
  220659. }
  220660. #endif
  220661. Window root = RootWindow (display, DefaultScreen (display));
  220662. unsigned int cursorW, cursorH;
  220663. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  220664. return 0;
  220665. Image im (Image::ARGB, cursorW, cursorH, true);
  220666. {
  220667. Graphics g (im);
  220668. if (imageW > cursorW || imageH > cursorH)
  220669. {
  220670. hotspotX = (hotspotX * cursorW) / imageW;
  220671. hotspotY = (hotspotY * cursorH) / imageH;
  220672. g.drawImageWithin (image, 0, 0, imageW, imageH,
  220673. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  220674. false);
  220675. }
  220676. else
  220677. {
  220678. g.drawImageAt (image, 0, 0);
  220679. }
  220680. }
  220681. const int stride = (cursorW + 7) >> 3;
  220682. HeapBlock <char> maskPlane, sourcePlane;
  220683. maskPlane.calloc (stride * cursorH);
  220684. sourcePlane.calloc (stride * cursorH);
  220685. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220686. for (int y = cursorH; --y >= 0;)
  220687. {
  220688. for (int x = cursorW; --x >= 0;)
  220689. {
  220690. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220691. const int offset = y * stride + (x >> 3);
  220692. const Colour c (im.getPixelAt (x, y));
  220693. if (c.getAlpha() >= 128)
  220694. maskPlane[offset] |= mask;
  220695. if (c.getBrightness() >= 0.5f)
  220696. sourcePlane[offset] |= mask;
  220697. }
  220698. }
  220699. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220700. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220701. XColor white, black;
  220702. black.red = black.green = black.blue = 0;
  220703. white.red = white.green = white.blue = 0xffff;
  220704. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  220705. XFreePixmap (display, sourcePixmap);
  220706. XFreePixmap (display, maskPixmap);
  220707. return result;
  220708. }
  220709. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  220710. {
  220711. ScopedXLock xlock;
  220712. if (cursorHandle != 0)
  220713. XFreeCursor (display, (Cursor) cursorHandle);
  220714. }
  220715. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  220716. {
  220717. unsigned int shape;
  220718. switch (type)
  220719. {
  220720. case NormalCursor: return None; // Use parent cursor
  220721. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  220722. case WaitCursor: shape = XC_watch; break;
  220723. case IBeamCursor: shape = XC_xterm; break;
  220724. case PointingHandCursor: shape = XC_hand2; break;
  220725. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  220726. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  220727. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  220728. case TopEdgeResizeCursor: shape = XC_top_side; break;
  220729. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  220730. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  220731. case RightEdgeResizeCursor: shape = XC_right_side; break;
  220732. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  220733. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  220734. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  220735. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  220736. case CrosshairCursor: shape = XC_crosshair; break;
  220737. case DraggingHandCursor:
  220738. {
  220739. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  220740. 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,
  220741. 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 };
  220742. const int dragHandDataSize = 99;
  220743. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  220744. }
  220745. case CopyingCursor:
  220746. {
  220747. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  220748. 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,
  220749. 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,
  220750. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  220751. const int copyCursorSize = 119;
  220752. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  220753. }
  220754. default:
  220755. jassertfalse;
  220756. return None;
  220757. }
  220758. ScopedXLock xlock;
  220759. return (void*) XCreateFontCursor (display, shape);
  220760. }
  220761. void MouseCursor::showInWindow (ComponentPeer* peer) const
  220762. {
  220763. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  220764. if (lp != 0)
  220765. lp->showMouseCursor ((Cursor) getHandle());
  220766. }
  220767. void MouseCursor::showInAllWindows() const
  220768. {
  220769. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  220770. showInWindow (ComponentPeer::getPeer (i));
  220771. }
  220772. const Image juce_createIconForFile (const File& file)
  220773. {
  220774. return Image::null;
  220775. }
  220776. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  220777. {
  220778. return createSoftwareImage (format, width, height, clearImage);
  220779. }
  220780. #if JUCE_OPENGL
  220781. class WindowedGLContext : public OpenGLContext
  220782. {
  220783. public:
  220784. WindowedGLContext (Component* const component,
  220785. const OpenGLPixelFormat& pixelFormat_,
  220786. GLXContext sharedContext)
  220787. : renderContext (0),
  220788. embeddedWindow (0),
  220789. pixelFormat (pixelFormat_),
  220790. swapInterval (0)
  220791. {
  220792. jassert (component != 0);
  220793. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  220794. if (peer == 0)
  220795. return;
  220796. ScopedXLock xlock;
  220797. XSync (display, False);
  220798. GLint attribs [64];
  220799. int n = 0;
  220800. attribs[n++] = GLX_RGBA;
  220801. attribs[n++] = GLX_DOUBLEBUFFER;
  220802. attribs[n++] = GLX_RED_SIZE;
  220803. attribs[n++] = pixelFormat.redBits;
  220804. attribs[n++] = GLX_GREEN_SIZE;
  220805. attribs[n++] = pixelFormat.greenBits;
  220806. attribs[n++] = GLX_BLUE_SIZE;
  220807. attribs[n++] = pixelFormat.blueBits;
  220808. attribs[n++] = GLX_ALPHA_SIZE;
  220809. attribs[n++] = pixelFormat.alphaBits;
  220810. attribs[n++] = GLX_DEPTH_SIZE;
  220811. attribs[n++] = pixelFormat.depthBufferBits;
  220812. attribs[n++] = GLX_STENCIL_SIZE;
  220813. attribs[n++] = pixelFormat.stencilBufferBits;
  220814. attribs[n++] = GLX_ACCUM_RED_SIZE;
  220815. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  220816. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  220817. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  220818. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  220819. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  220820. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  220821. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  220822. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  220823. attribs[n++] = None;
  220824. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  220825. if (bestVisual == 0)
  220826. return;
  220827. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  220828. Window windowH = (Window) peer->getNativeHandle();
  220829. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  220830. XSetWindowAttributes swa;
  220831. swa.colormap = colourMap;
  220832. swa.border_pixel = 0;
  220833. swa.event_mask = ExposureMask | StructureNotifyMask;
  220834. embeddedWindow = XCreateWindow (display, windowH,
  220835. 0, 0, 1, 1, 0,
  220836. bestVisual->depth,
  220837. InputOutput,
  220838. bestVisual->visual,
  220839. CWBorderPixel | CWColormap | CWEventMask,
  220840. &swa);
  220841. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  220842. XMapWindow (display, embeddedWindow);
  220843. XFreeColormap (display, colourMap);
  220844. XFree (bestVisual);
  220845. XSync (display, False);
  220846. }
  220847. ~WindowedGLContext()
  220848. {
  220849. ScopedXLock xlock;
  220850. deleteContext();
  220851. XUnmapWindow (display, embeddedWindow);
  220852. XDestroyWindow (display, embeddedWindow);
  220853. }
  220854. void deleteContext()
  220855. {
  220856. makeInactive();
  220857. if (renderContext != 0)
  220858. {
  220859. ScopedXLock xlock;
  220860. glXDestroyContext (display, renderContext);
  220861. renderContext = 0;
  220862. }
  220863. }
  220864. bool makeActive() const throw()
  220865. {
  220866. jassert (renderContext != 0);
  220867. ScopedXLock xlock;
  220868. return glXMakeCurrent (display, embeddedWindow, renderContext)
  220869. && XSync (display, False);
  220870. }
  220871. bool makeInactive() const throw()
  220872. {
  220873. ScopedXLock xlock;
  220874. return (! isActive()) || glXMakeCurrent (display, None, 0);
  220875. }
  220876. bool isActive() const throw()
  220877. {
  220878. ScopedXLock xlock;
  220879. return glXGetCurrentContext() == renderContext;
  220880. }
  220881. const OpenGLPixelFormat getPixelFormat() const
  220882. {
  220883. return pixelFormat;
  220884. }
  220885. void* getRawContext() const throw()
  220886. {
  220887. return renderContext;
  220888. }
  220889. void updateWindowPosition (int x, int y, int w, int h, int)
  220890. {
  220891. ScopedXLock xlock;
  220892. XMoveResizeWindow (display, embeddedWindow,
  220893. x, y, jmax (1, w), jmax (1, h));
  220894. }
  220895. void swapBuffers()
  220896. {
  220897. ScopedXLock xlock;
  220898. glXSwapBuffers (display, embeddedWindow);
  220899. }
  220900. bool setSwapInterval (const int numFramesPerSwap)
  220901. {
  220902. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  220903. if (GLXSwapIntervalSGI != 0)
  220904. {
  220905. swapInterval = numFramesPerSwap;
  220906. GLXSwapIntervalSGI (numFramesPerSwap);
  220907. return true;
  220908. }
  220909. return false;
  220910. }
  220911. int getSwapInterval() const
  220912. {
  220913. return swapInterval;
  220914. }
  220915. void repaint()
  220916. {
  220917. }
  220918. juce_UseDebuggingNewOperator
  220919. GLXContext renderContext;
  220920. private:
  220921. Window embeddedWindow;
  220922. OpenGLPixelFormat pixelFormat;
  220923. int swapInterval;
  220924. WindowedGLContext (const WindowedGLContext&);
  220925. WindowedGLContext& operator= (const WindowedGLContext&);
  220926. };
  220927. OpenGLContext* OpenGLComponent::createContext()
  220928. {
  220929. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  220930. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  220931. return (c->renderContext != 0) ? c.release() : 0;
  220932. }
  220933. void juce_glViewport (const int w, const int h)
  220934. {
  220935. glViewport (0, 0, w, h);
  220936. }
  220937. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  220938. OwnedArray <OpenGLPixelFormat>& results)
  220939. {
  220940. results.add (new OpenGLPixelFormat()); // xxx
  220941. }
  220942. #endif
  220943. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  220944. {
  220945. jassertfalse; // not implemented!
  220946. return false;
  220947. }
  220948. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  220949. {
  220950. jassertfalse; // not implemented!
  220951. return false;
  220952. }
  220953. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  220954. {
  220955. if (! isOnDesktop ())
  220956. addToDesktop (0);
  220957. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  220958. if (wp != 0)
  220959. {
  220960. wp->setTaskBarIcon (newImage);
  220961. setVisible (true);
  220962. toFront (false);
  220963. repaint();
  220964. }
  220965. }
  220966. void SystemTrayIconComponent::paint (Graphics& g)
  220967. {
  220968. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  220969. if (wp != 0)
  220970. {
  220971. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  220972. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  220973. false);
  220974. }
  220975. }
  220976. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  220977. {
  220978. // xxx not yet implemented!
  220979. }
  220980. void PlatformUtilities::beep()
  220981. {
  220982. std::cout << "\a" << std::flush;
  220983. }
  220984. bool AlertWindow::showNativeDialogBox (const String& title,
  220985. const String& bodyText,
  220986. bool isOkCancel)
  220987. {
  220988. // use a non-native one for the time being..
  220989. if (isOkCancel)
  220990. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  220991. else
  220992. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  220993. return true;
  220994. }
  220995. const int KeyPress::spaceKey = XK_space & 0xff;
  220996. const int KeyPress::returnKey = XK_Return & 0xff;
  220997. const int KeyPress::escapeKey = XK_Escape & 0xff;
  220998. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  220999. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  221000. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  221001. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  221002. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  221003. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  221004. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  221005. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  221006. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  221007. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  221008. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  221009. const int KeyPress::tabKey = XK_Tab & 0xff;
  221010. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  221011. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  221012. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  221013. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  221014. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  221015. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  221016. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  221017. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  221018. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  221019. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  221020. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  221021. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  221022. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  221023. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  221024. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  221025. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  221026. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  221027. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  221028. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  221029. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  221030. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  221031. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  221032. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  221033. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  221034. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  221035. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  221036. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  221037. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  221038. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  221039. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  221040. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  221041. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  221042. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  221043. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  221044. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  221045. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  221046. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  221047. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  221048. #endif
  221049. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  221050. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  221051. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221052. // compiled on its own).
  221053. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  221054. static const int maxNumChans = 64;
  221055. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  221056. {
  221057. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  221058. snd_pcm_hw_params_t* hwParams;
  221059. snd_pcm_hw_params_alloca (&hwParams);
  221060. for (int i = 0; ratesToTry[i] != 0; ++i)
  221061. {
  221062. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  221063. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  221064. {
  221065. rates.addIfNotAlreadyThere (ratesToTry[i]);
  221066. }
  221067. }
  221068. }
  221069. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  221070. {
  221071. snd_pcm_hw_params_t *params;
  221072. snd_pcm_hw_params_alloca (&params);
  221073. if (snd_pcm_hw_params_any (handle, params) >= 0)
  221074. {
  221075. snd_pcm_hw_params_get_channels_min (params, minChans);
  221076. snd_pcm_hw_params_get_channels_max (params, maxChans);
  221077. }
  221078. }
  221079. static void getDeviceProperties (const String& deviceID,
  221080. unsigned int& minChansOut,
  221081. unsigned int& maxChansOut,
  221082. unsigned int& minChansIn,
  221083. unsigned int& maxChansIn,
  221084. Array <int>& rates)
  221085. {
  221086. if (deviceID.isEmpty())
  221087. return;
  221088. snd_ctl_t* handle;
  221089. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221090. {
  221091. snd_pcm_info_t* info;
  221092. snd_pcm_info_alloca (&info);
  221093. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  221094. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  221095. snd_pcm_info_set_subdevice (info, 0);
  221096. if (snd_ctl_pcm_info (handle, info) >= 0)
  221097. {
  221098. snd_pcm_t* pcmHandle;
  221099. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  221100. {
  221101. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  221102. getDeviceSampleRates (pcmHandle, rates);
  221103. snd_pcm_close (pcmHandle);
  221104. }
  221105. }
  221106. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  221107. if (snd_ctl_pcm_info (handle, info) >= 0)
  221108. {
  221109. snd_pcm_t* pcmHandle;
  221110. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  221111. {
  221112. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  221113. if (rates.size() == 0)
  221114. getDeviceSampleRates (pcmHandle, rates);
  221115. snd_pcm_close (pcmHandle);
  221116. }
  221117. }
  221118. snd_ctl_close (handle);
  221119. }
  221120. }
  221121. class ALSADevice
  221122. {
  221123. public:
  221124. ALSADevice (const String& deviceID,
  221125. const bool forInput)
  221126. : handle (0),
  221127. bitDepth (16),
  221128. numChannelsRunning (0),
  221129. isInput (forInput),
  221130. sampleFormat (AudioDataConverters::int16LE)
  221131. {
  221132. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  221133. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  221134. SND_PCM_ASYNC));
  221135. }
  221136. ~ALSADevice()
  221137. {
  221138. if (handle != 0)
  221139. snd_pcm_close (handle);
  221140. }
  221141. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  221142. {
  221143. if (handle == 0)
  221144. return false;
  221145. snd_pcm_hw_params_t* hwParams;
  221146. snd_pcm_hw_params_alloca (&hwParams);
  221147. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  221148. return false;
  221149. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  221150. isInterleaved = false;
  221151. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  221152. isInterleaved = true;
  221153. else
  221154. {
  221155. jassertfalse;
  221156. return false;
  221157. }
  221158. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  221159. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  221160. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  221161. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  221162. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  221163. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  221164. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  221165. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  221166. bitDepth = 0;
  221167. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  221168. {
  221169. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  221170. {
  221171. bitDepth = formatsToTry [i + 1];
  221172. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  221173. break;
  221174. }
  221175. }
  221176. if (bitDepth == 0)
  221177. {
  221178. error = "device doesn't support a compatible PCM format";
  221179. DBG ("ALSA error: " + error + "\n");
  221180. return false;
  221181. }
  221182. int dir = 0;
  221183. unsigned int periods = 4;
  221184. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  221185. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  221186. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  221187. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  221188. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  221189. || failed (snd_pcm_hw_params (handle, hwParams)))
  221190. {
  221191. return false;
  221192. }
  221193. snd_pcm_sw_params_t* swParams;
  221194. snd_pcm_sw_params_alloca (&swParams);
  221195. snd_pcm_uframes_t boundary;
  221196. if (failed (snd_pcm_sw_params_current (handle, swParams))
  221197. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  221198. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  221199. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  221200. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  221201. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  221202. || failed (snd_pcm_sw_params (handle, swParams)))
  221203. {
  221204. return false;
  221205. }
  221206. /*
  221207. #if JUCE_DEBUG
  221208. // enable this to dump the config of the devices that get opened
  221209. snd_output_t* out;
  221210. snd_output_stdio_attach (&out, stderr, 0);
  221211. snd_pcm_hw_params_dump (hwParams, out);
  221212. snd_pcm_sw_params_dump (swParams, out);
  221213. #endif
  221214. */
  221215. numChannelsRunning = numChannels;
  221216. return true;
  221217. }
  221218. bool write (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  221219. {
  221220. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  221221. float** const data = outputChannelBuffer.getArrayOfChannels();
  221222. if (isInterleaved)
  221223. {
  221224. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221225. float* interleaved = static_cast <float*> (scratch.getData());
  221226. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  221227. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  221228. snd_pcm_sframes_t num = snd_pcm_writei (handle, interleaved, numSamples);
  221229. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  221230. return false;
  221231. }
  221232. else
  221233. {
  221234. for (int i = 0; i < numChannelsRunning; ++i)
  221235. if (data[i] != 0)
  221236. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  221237. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  221238. if (failed (num))
  221239. {
  221240. if (num == -EPIPE)
  221241. {
  221242. if (failed (snd_pcm_prepare (handle)))
  221243. return false;
  221244. }
  221245. else if (num != -ESTRPIPE)
  221246. return false;
  221247. }
  221248. }
  221249. return true;
  221250. }
  221251. bool read (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  221252. {
  221253. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  221254. float** const data = inputChannelBuffer.getArrayOfChannels();
  221255. if (isInterleaved)
  221256. {
  221257. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221258. float* interleaved = static_cast <float*> (scratch.getData());
  221259. snd_pcm_sframes_t num = snd_pcm_readi (handle, interleaved, numSamples);
  221260. if (failed (num))
  221261. {
  221262. if (num == -EPIPE)
  221263. {
  221264. if (failed (snd_pcm_prepare (handle)))
  221265. return false;
  221266. }
  221267. else if (num != -ESTRPIPE)
  221268. return false;
  221269. }
  221270. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  221271. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  221272. }
  221273. else
  221274. {
  221275. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  221276. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  221277. return false;
  221278. for (int i = 0; i < numChannelsRunning; ++i)
  221279. if (data[i] != 0)
  221280. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  221281. }
  221282. return true;
  221283. }
  221284. juce_UseDebuggingNewOperator
  221285. snd_pcm_t* handle;
  221286. String error;
  221287. int bitDepth, numChannelsRunning;
  221288. private:
  221289. const bool isInput;
  221290. bool isInterleaved;
  221291. MemoryBlock scratch;
  221292. AudioDataConverters::DataFormat sampleFormat;
  221293. bool failed (const int errorNum)
  221294. {
  221295. if (errorNum >= 0)
  221296. return false;
  221297. error = snd_strerror (errorNum);
  221298. DBG ("ALSA error: " + error + "\n");
  221299. return true;
  221300. }
  221301. };
  221302. class ALSAThread : public Thread
  221303. {
  221304. public:
  221305. ALSAThread (const String& inputId_,
  221306. const String& outputId_)
  221307. : Thread ("Juce ALSA"),
  221308. sampleRate (0),
  221309. bufferSize (0),
  221310. callback (0),
  221311. inputId (inputId_),
  221312. outputId (outputId_),
  221313. numCallbacks (0),
  221314. inputChannelBuffer (1, 1),
  221315. outputChannelBuffer (1, 1)
  221316. {
  221317. initialiseRatesAndChannels();
  221318. }
  221319. ~ALSAThread()
  221320. {
  221321. close();
  221322. }
  221323. void open (BigInteger inputChannels,
  221324. BigInteger outputChannels,
  221325. const double sampleRate_,
  221326. const int bufferSize_)
  221327. {
  221328. close();
  221329. error = String::empty;
  221330. sampleRate = sampleRate_;
  221331. bufferSize = bufferSize_;
  221332. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  221333. inputChannelBuffer.clear();
  221334. inputChannelDataForCallback.clear();
  221335. currentInputChans.clear();
  221336. if (inputChannels.getHighestBit() >= 0)
  221337. {
  221338. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  221339. {
  221340. if (inputChannels[i])
  221341. {
  221342. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  221343. currentInputChans.setBit (i);
  221344. }
  221345. }
  221346. }
  221347. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  221348. outputChannelBuffer.clear();
  221349. outputChannelDataForCallback.clear();
  221350. currentOutputChans.clear();
  221351. if (outputChannels.getHighestBit() >= 0)
  221352. {
  221353. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  221354. {
  221355. if (outputChannels[i])
  221356. {
  221357. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  221358. currentOutputChans.setBit (i);
  221359. }
  221360. }
  221361. }
  221362. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  221363. {
  221364. outputDevice = new ALSADevice (outputId, false);
  221365. if (outputDevice->error.isNotEmpty())
  221366. {
  221367. error = outputDevice->error;
  221368. outputDevice = 0;
  221369. return;
  221370. }
  221371. currentOutputChans.setRange (0, minChansOut, true);
  221372. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  221373. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  221374. bufferSize))
  221375. {
  221376. error = outputDevice->error;
  221377. outputDevice = 0;
  221378. return;
  221379. }
  221380. }
  221381. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  221382. {
  221383. inputDevice = new ALSADevice (inputId, true);
  221384. if (inputDevice->error.isNotEmpty())
  221385. {
  221386. error = inputDevice->error;
  221387. inputDevice = 0;
  221388. return;
  221389. }
  221390. currentInputChans.setRange (0, minChansIn, true);
  221391. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  221392. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  221393. bufferSize))
  221394. {
  221395. error = inputDevice->error;
  221396. inputDevice = 0;
  221397. return;
  221398. }
  221399. }
  221400. if (outputDevice == 0 && inputDevice == 0)
  221401. {
  221402. error = "no channels";
  221403. return;
  221404. }
  221405. if (outputDevice != 0 && inputDevice != 0)
  221406. {
  221407. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  221408. }
  221409. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  221410. return;
  221411. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  221412. return;
  221413. startThread (9);
  221414. int count = 1000;
  221415. while (numCallbacks == 0)
  221416. {
  221417. sleep (5);
  221418. if (--count < 0 || ! isThreadRunning())
  221419. {
  221420. error = "device didn't start";
  221421. break;
  221422. }
  221423. }
  221424. }
  221425. void close()
  221426. {
  221427. stopThread (6000);
  221428. inputDevice = 0;
  221429. outputDevice = 0;
  221430. inputChannelBuffer.setSize (1, 1);
  221431. outputChannelBuffer.setSize (1, 1);
  221432. numCallbacks = 0;
  221433. }
  221434. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  221435. {
  221436. const ScopedLock sl (callbackLock);
  221437. callback = newCallback;
  221438. }
  221439. void run()
  221440. {
  221441. while (! threadShouldExit())
  221442. {
  221443. if (inputDevice != 0)
  221444. {
  221445. if (! inputDevice->read (inputChannelBuffer, bufferSize))
  221446. {
  221447. DBG ("ALSA: read failure");
  221448. break;
  221449. }
  221450. }
  221451. if (threadShouldExit())
  221452. break;
  221453. {
  221454. const ScopedLock sl (callbackLock);
  221455. ++numCallbacks;
  221456. if (callback != 0)
  221457. {
  221458. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  221459. inputChannelDataForCallback.size(),
  221460. outputChannelDataForCallback.getRawDataPointer(),
  221461. outputChannelDataForCallback.size(),
  221462. bufferSize);
  221463. }
  221464. else
  221465. {
  221466. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  221467. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  221468. }
  221469. }
  221470. if (outputDevice != 0)
  221471. {
  221472. failed (snd_pcm_wait (outputDevice->handle, 2000));
  221473. if (threadShouldExit())
  221474. break;
  221475. failed (snd_pcm_avail_update (outputDevice->handle));
  221476. if (! outputDevice->write (outputChannelBuffer, bufferSize))
  221477. {
  221478. DBG ("ALSA: write failure");
  221479. break;
  221480. }
  221481. }
  221482. }
  221483. }
  221484. int getBitDepth() const throw()
  221485. {
  221486. if (outputDevice != 0)
  221487. return outputDevice->bitDepth;
  221488. if (inputDevice != 0)
  221489. return inputDevice->bitDepth;
  221490. return 16;
  221491. }
  221492. juce_UseDebuggingNewOperator
  221493. String error;
  221494. double sampleRate;
  221495. int bufferSize;
  221496. BigInteger currentInputChans, currentOutputChans;
  221497. Array <int> sampleRates;
  221498. StringArray channelNamesOut, channelNamesIn;
  221499. AudioIODeviceCallback* callback;
  221500. private:
  221501. const String inputId, outputId;
  221502. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  221503. int numCallbacks;
  221504. CriticalSection callbackLock;
  221505. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  221506. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  221507. unsigned int minChansOut, maxChansOut;
  221508. unsigned int minChansIn, maxChansIn;
  221509. bool failed (const int errorNum)
  221510. {
  221511. if (errorNum >= 0)
  221512. return false;
  221513. error = snd_strerror (errorNum);
  221514. DBG ("ALSA error: " + error + "\n");
  221515. return true;
  221516. }
  221517. void initialiseRatesAndChannels()
  221518. {
  221519. sampleRates.clear();
  221520. channelNamesOut.clear();
  221521. channelNamesIn.clear();
  221522. minChansOut = 0;
  221523. maxChansOut = 0;
  221524. minChansIn = 0;
  221525. maxChansIn = 0;
  221526. unsigned int dummy = 0;
  221527. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  221528. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  221529. unsigned int i;
  221530. for (i = 0; i < maxChansOut; ++i)
  221531. channelNamesOut.add ("channel " + String ((int) i + 1));
  221532. for (i = 0; i < maxChansIn; ++i)
  221533. channelNamesIn.add ("channel " + String ((int) i + 1));
  221534. }
  221535. };
  221536. class ALSAAudioIODevice : public AudioIODevice
  221537. {
  221538. public:
  221539. ALSAAudioIODevice (const String& deviceName,
  221540. const String& inputId_,
  221541. const String& outputId_)
  221542. : AudioIODevice (deviceName, "ALSA"),
  221543. inputId (inputId_),
  221544. outputId (outputId_),
  221545. isOpen_ (false),
  221546. isStarted (false),
  221547. internal (inputId_, outputId_)
  221548. {
  221549. }
  221550. ~ALSAAudioIODevice()
  221551. {
  221552. }
  221553. const StringArray getOutputChannelNames()
  221554. {
  221555. return internal.channelNamesOut;
  221556. }
  221557. const StringArray getInputChannelNames()
  221558. {
  221559. return internal.channelNamesIn;
  221560. }
  221561. int getNumSampleRates()
  221562. {
  221563. return internal.sampleRates.size();
  221564. }
  221565. double getSampleRate (int index)
  221566. {
  221567. return internal.sampleRates [index];
  221568. }
  221569. int getNumBufferSizesAvailable()
  221570. {
  221571. return 50;
  221572. }
  221573. int getBufferSizeSamples (int index)
  221574. {
  221575. int n = 16;
  221576. for (int i = 0; i < index; ++i)
  221577. n += n < 64 ? 16
  221578. : (n < 512 ? 32
  221579. : (n < 1024 ? 64
  221580. : (n < 2048 ? 128 : 256)));
  221581. return n;
  221582. }
  221583. int getDefaultBufferSize()
  221584. {
  221585. return 512;
  221586. }
  221587. const String open (const BigInteger& inputChannels,
  221588. const BigInteger& outputChannels,
  221589. double sampleRate,
  221590. int bufferSizeSamples)
  221591. {
  221592. close();
  221593. if (bufferSizeSamples <= 0)
  221594. bufferSizeSamples = getDefaultBufferSize();
  221595. if (sampleRate <= 0)
  221596. {
  221597. for (int i = 0; i < getNumSampleRates(); ++i)
  221598. {
  221599. if (getSampleRate (i) >= 44100)
  221600. {
  221601. sampleRate = getSampleRate (i);
  221602. break;
  221603. }
  221604. }
  221605. }
  221606. internal.open (inputChannels, outputChannels,
  221607. sampleRate, bufferSizeSamples);
  221608. isOpen_ = internal.error.isEmpty();
  221609. return internal.error;
  221610. }
  221611. void close()
  221612. {
  221613. stop();
  221614. internal.close();
  221615. isOpen_ = false;
  221616. }
  221617. bool isOpen()
  221618. {
  221619. return isOpen_;
  221620. }
  221621. int getCurrentBufferSizeSamples()
  221622. {
  221623. return internal.bufferSize;
  221624. }
  221625. double getCurrentSampleRate()
  221626. {
  221627. return internal.sampleRate;
  221628. }
  221629. int getCurrentBitDepth()
  221630. {
  221631. return internal.getBitDepth();
  221632. }
  221633. const BigInteger getActiveOutputChannels() const
  221634. {
  221635. return internal.currentOutputChans;
  221636. }
  221637. const BigInteger getActiveInputChannels() const
  221638. {
  221639. return internal.currentInputChans;
  221640. }
  221641. int getOutputLatencyInSamples()
  221642. {
  221643. return 0;
  221644. }
  221645. int getInputLatencyInSamples()
  221646. {
  221647. return 0;
  221648. }
  221649. void start (AudioIODeviceCallback* callback)
  221650. {
  221651. if (! isOpen_)
  221652. callback = 0;
  221653. if (callback != 0)
  221654. callback->audioDeviceAboutToStart (this);
  221655. internal.setCallback (callback);
  221656. isStarted = (callback != 0);
  221657. }
  221658. void stop()
  221659. {
  221660. AudioIODeviceCallback* const oldCallback = internal.callback;
  221661. start (0);
  221662. if (oldCallback != 0)
  221663. oldCallback->audioDeviceStopped();
  221664. }
  221665. bool isPlaying()
  221666. {
  221667. return isStarted && internal.error.isEmpty();
  221668. }
  221669. const String getLastError()
  221670. {
  221671. return internal.error;
  221672. }
  221673. String inputId, outputId;
  221674. private:
  221675. bool isOpen_, isStarted;
  221676. ALSAThread internal;
  221677. };
  221678. class ALSAAudioIODeviceType : public AudioIODeviceType
  221679. {
  221680. public:
  221681. ALSAAudioIODeviceType()
  221682. : AudioIODeviceType ("ALSA"),
  221683. hasScanned (false)
  221684. {
  221685. }
  221686. ~ALSAAudioIODeviceType()
  221687. {
  221688. }
  221689. void scanForDevices()
  221690. {
  221691. if (hasScanned)
  221692. return;
  221693. hasScanned = true;
  221694. inputNames.clear();
  221695. inputIds.clear();
  221696. outputNames.clear();
  221697. outputIds.clear();
  221698. snd_ctl_t* handle;
  221699. snd_ctl_card_info_t* info;
  221700. snd_ctl_card_info_alloca (&info);
  221701. int cardNum = -1;
  221702. while (outputIds.size() + inputIds.size() <= 32)
  221703. {
  221704. snd_card_next (&cardNum);
  221705. if (cardNum < 0)
  221706. break;
  221707. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221708. {
  221709. if (snd_ctl_card_info (handle, info) >= 0)
  221710. {
  221711. String cardId (snd_ctl_card_info_get_id (info));
  221712. if (cardId.removeCharacters ("0123456789").isEmpty())
  221713. cardId = String (cardNum);
  221714. int device = -1;
  221715. for (;;)
  221716. {
  221717. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  221718. break;
  221719. String id, name;
  221720. id << "hw:" << cardId << ',' << device;
  221721. bool isInput, isOutput;
  221722. if (testDevice (id, isInput, isOutput))
  221723. {
  221724. name << snd_ctl_card_info_get_name (info);
  221725. if (name.isEmpty())
  221726. name = id;
  221727. if (isInput)
  221728. {
  221729. inputNames.add (name);
  221730. inputIds.add (id);
  221731. }
  221732. if (isOutput)
  221733. {
  221734. outputNames.add (name);
  221735. outputIds.add (id);
  221736. }
  221737. }
  221738. }
  221739. }
  221740. snd_ctl_close (handle);
  221741. }
  221742. }
  221743. inputNames.appendNumbersToDuplicates (false, true);
  221744. outputNames.appendNumbersToDuplicates (false, true);
  221745. }
  221746. const StringArray getDeviceNames (bool wantInputNames) const
  221747. {
  221748. jassert (hasScanned); // need to call scanForDevices() before doing this
  221749. return wantInputNames ? inputNames : outputNames;
  221750. }
  221751. int getDefaultDeviceIndex (bool forInput) const
  221752. {
  221753. jassert (hasScanned); // need to call scanForDevices() before doing this
  221754. return 0;
  221755. }
  221756. bool hasSeparateInputsAndOutputs() const { return true; }
  221757. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  221758. {
  221759. jassert (hasScanned); // need to call scanForDevices() before doing this
  221760. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  221761. if (d == 0)
  221762. return -1;
  221763. return asInput ? inputIds.indexOf (d->inputId)
  221764. : outputIds.indexOf (d->outputId);
  221765. }
  221766. AudioIODevice* createDevice (const String& outputDeviceName,
  221767. const String& inputDeviceName)
  221768. {
  221769. jassert (hasScanned); // need to call scanForDevices() before doing this
  221770. const int inputIndex = inputNames.indexOf (inputDeviceName);
  221771. const int outputIndex = outputNames.indexOf (outputDeviceName);
  221772. String deviceName (outputIndex >= 0 ? outputDeviceName
  221773. : inputDeviceName);
  221774. if (inputIndex >= 0 || outputIndex >= 0)
  221775. return new ALSAAudioIODevice (deviceName,
  221776. inputIds [inputIndex],
  221777. outputIds [outputIndex]);
  221778. return 0;
  221779. }
  221780. juce_UseDebuggingNewOperator
  221781. private:
  221782. StringArray inputNames, outputNames, inputIds, outputIds;
  221783. bool hasScanned;
  221784. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  221785. {
  221786. unsigned int minChansOut = 0, maxChansOut = 0;
  221787. unsigned int minChansIn = 0, maxChansIn = 0;
  221788. Array <int> rates;
  221789. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  221790. DBG ("ALSA device: " + id
  221791. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  221792. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  221793. + " rates=" + String (rates.size()));
  221794. isInput = maxChansIn > 0;
  221795. isOutput = maxChansOut > 0;
  221796. return (isInput || isOutput) && rates.size() > 0;
  221797. }
  221798. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  221799. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  221800. };
  221801. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  221802. {
  221803. return new ALSAAudioIODeviceType();
  221804. }
  221805. #endif
  221806. /*** End of inlined file: juce_linux_Audio.cpp ***/
  221807. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  221808. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221809. // compiled on its own).
  221810. #ifdef JUCE_INCLUDED_FILE
  221811. #if JUCE_JACK
  221812. static void* juce_libjack_handle = 0;
  221813. void* juce_load_jack_function (const char* const name)
  221814. {
  221815. if (juce_libjack_handle == 0)
  221816. return 0;
  221817. return dlsym (juce_libjack_handle, name);
  221818. }
  221819. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  221820. typedef return_type (*fn_name##_ptr_t)argument_types; \
  221821. return_type fn_name argument_types { \
  221822. static fn_name##_ptr_t fn = 0; \
  221823. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  221824. if (fn) return (*fn)arguments; \
  221825. else return 0; \
  221826. }
  221827. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  221828. typedef void (*fn_name##_ptr_t)argument_types; \
  221829. void fn_name argument_types { \
  221830. static fn_name##_ptr_t fn = 0; \
  221831. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  221832. if (fn) (*fn)arguments; \
  221833. }
  221834. 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));
  221835. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  221836. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  221837. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  221838. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  221839. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  221840. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  221841. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  221842. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  221843. 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));
  221844. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  221845. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  221846. 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));
  221847. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  221848. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  221849. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  221850. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  221851. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  221852. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  221853. #if JUCE_DEBUG
  221854. #define JACK_LOGGING_ENABLED 1
  221855. #endif
  221856. #if JACK_LOGGING_ENABLED
  221857. static void jack_Log (const String& s)
  221858. {
  221859. std::cerr << s << std::endl;
  221860. }
  221861. static void dumpJackErrorMessage (const jack_status_t status)
  221862. {
  221863. if (status & JackServerFailed || status & JackServerError)
  221864. jack_Log ("Unable to connect to JACK server");
  221865. if (status & JackVersionError)
  221866. jack_Log ("Client's protocol version does not match");
  221867. if (status & JackInvalidOption)
  221868. jack_Log ("The operation contained an invalid or unsupported option");
  221869. if (status & JackNameNotUnique)
  221870. jack_Log ("The desired client name was not unique");
  221871. if (status & JackNoSuchClient)
  221872. jack_Log ("Requested client does not exist");
  221873. if (status & JackInitFailure)
  221874. jack_Log ("Unable to initialize client");
  221875. }
  221876. #else
  221877. #define dumpJackErrorMessage(a) {}
  221878. #define jack_Log(...) {}
  221879. #endif
  221880. #ifndef JUCE_JACK_CLIENT_NAME
  221881. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  221882. #endif
  221883. class JackAudioIODevice : public AudioIODevice
  221884. {
  221885. public:
  221886. JackAudioIODevice (const String& deviceName,
  221887. const String& inputId_,
  221888. const String& outputId_)
  221889. : AudioIODevice (deviceName, "JACK"),
  221890. inputId (inputId_),
  221891. outputId (outputId_),
  221892. isOpen_ (false),
  221893. callback (0),
  221894. totalNumberOfInputChannels (0),
  221895. totalNumberOfOutputChannels (0)
  221896. {
  221897. jassert (deviceName.isNotEmpty());
  221898. jack_status_t status;
  221899. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  221900. if (client == 0)
  221901. {
  221902. dumpJackErrorMessage (status);
  221903. }
  221904. else
  221905. {
  221906. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  221907. // open input ports
  221908. const StringArray inputChannels (getInputChannelNames());
  221909. for (int i = 0; i < inputChannels.size(); i++)
  221910. {
  221911. String inputName;
  221912. inputName << "in_" << ++totalNumberOfInputChannels;
  221913. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  221914. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  221915. }
  221916. // open output ports
  221917. const StringArray outputChannels (getOutputChannelNames());
  221918. for (int i = 0; i < outputChannels.size (); i++)
  221919. {
  221920. String outputName;
  221921. outputName << "out_" << ++totalNumberOfOutputChannels;
  221922. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  221923. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  221924. }
  221925. inChans.calloc (totalNumberOfInputChannels + 2);
  221926. outChans.calloc (totalNumberOfOutputChannels + 2);
  221927. }
  221928. }
  221929. ~JackAudioIODevice()
  221930. {
  221931. close();
  221932. if (client != 0)
  221933. {
  221934. JUCE_NAMESPACE::jack_client_close (client);
  221935. client = 0;
  221936. }
  221937. }
  221938. const StringArray getChannelNames (bool forInput) const
  221939. {
  221940. StringArray names;
  221941. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  221942. forInput ? JackPortIsInput : JackPortIsOutput);
  221943. if (ports != 0)
  221944. {
  221945. int j = 0;
  221946. while (ports[j] != 0)
  221947. {
  221948. const String portName (ports [j++]);
  221949. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221950. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  221951. }
  221952. free (ports);
  221953. }
  221954. return names;
  221955. }
  221956. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  221957. const StringArray getInputChannelNames() { return getChannelNames (true); }
  221958. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  221959. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  221960. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  221961. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  221962. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  221963. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  221964. double sampleRate, int bufferSizeSamples)
  221965. {
  221966. if (client == 0)
  221967. {
  221968. lastError = "No JACK client running";
  221969. return lastError;
  221970. }
  221971. lastError = String::empty;
  221972. close();
  221973. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  221974. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  221975. JUCE_NAMESPACE::jack_activate (client);
  221976. isOpen_ = true;
  221977. if (! inputChannels.isZero())
  221978. {
  221979. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  221980. if (ports != 0)
  221981. {
  221982. const int numInputChannels = inputChannels.getHighestBit() + 1;
  221983. for (int i = 0; i < numInputChannels; ++i)
  221984. {
  221985. const String portName (ports[i]);
  221986. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221987. {
  221988. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  221989. if (error != 0)
  221990. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  221991. }
  221992. }
  221993. free (ports);
  221994. }
  221995. }
  221996. if (! outputChannels.isZero())
  221997. {
  221998. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  221999. if (ports != 0)
  222000. {
  222001. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  222002. for (int i = 0; i < numOutputChannels; ++i)
  222003. {
  222004. const String portName (ports[i]);
  222005. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222006. {
  222007. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  222008. if (error != 0)
  222009. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222010. }
  222011. }
  222012. free (ports);
  222013. }
  222014. }
  222015. return lastError;
  222016. }
  222017. void close()
  222018. {
  222019. stop();
  222020. if (client != 0)
  222021. {
  222022. JUCE_NAMESPACE::jack_deactivate (client);
  222023. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  222024. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  222025. }
  222026. isOpen_ = false;
  222027. }
  222028. void start (AudioIODeviceCallback* newCallback)
  222029. {
  222030. if (isOpen_ && newCallback != callback)
  222031. {
  222032. if (newCallback != 0)
  222033. newCallback->audioDeviceAboutToStart (this);
  222034. AudioIODeviceCallback* const oldCallback = callback;
  222035. {
  222036. const ScopedLock sl (callbackLock);
  222037. callback = newCallback;
  222038. }
  222039. if (oldCallback != 0)
  222040. oldCallback->audioDeviceStopped();
  222041. }
  222042. }
  222043. void stop()
  222044. {
  222045. start (0);
  222046. }
  222047. bool isOpen() { return isOpen_; }
  222048. bool isPlaying() { return callback != 0; }
  222049. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  222050. double getCurrentSampleRate() { return getSampleRate (0); }
  222051. int getCurrentBitDepth() { return 32; }
  222052. const String getLastError() { return lastError; }
  222053. const BigInteger getActiveOutputChannels() const
  222054. {
  222055. BigInteger outputBits;
  222056. for (int i = 0; i < outputPorts.size(); i++)
  222057. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  222058. outputBits.setBit (i);
  222059. return outputBits;
  222060. }
  222061. const BigInteger getActiveInputChannels() const
  222062. {
  222063. BigInteger inputBits;
  222064. for (int i = 0; i < inputPorts.size(); i++)
  222065. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  222066. inputBits.setBit (i);
  222067. return inputBits;
  222068. }
  222069. int getOutputLatencyInSamples()
  222070. {
  222071. int latency = 0;
  222072. for (int i = 0; i < outputPorts.size(); i++)
  222073. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  222074. return latency;
  222075. }
  222076. int getInputLatencyInSamples()
  222077. {
  222078. int latency = 0;
  222079. for (int i = 0; i < inputPorts.size(); i++)
  222080. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  222081. return latency;
  222082. }
  222083. String inputId, outputId;
  222084. private:
  222085. void process (const int numSamples)
  222086. {
  222087. int i, numActiveInChans = 0, numActiveOutChans = 0;
  222088. for (i = 0; i < totalNumberOfInputChannels; ++i)
  222089. {
  222090. jack_default_audio_sample_t* in
  222091. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  222092. if (in != 0)
  222093. inChans [numActiveInChans++] = (float*) in;
  222094. }
  222095. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  222096. {
  222097. jack_default_audio_sample_t* out
  222098. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  222099. if (out != 0)
  222100. outChans [numActiveOutChans++] = (float*) out;
  222101. }
  222102. const ScopedLock sl (callbackLock);
  222103. if (callback != 0)
  222104. {
  222105. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  222106. outChans, numActiveOutChans, numSamples);
  222107. }
  222108. else
  222109. {
  222110. for (i = 0; i < numActiveOutChans; ++i)
  222111. zeromem (outChans[i], sizeof (float) * numSamples);
  222112. }
  222113. }
  222114. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  222115. {
  222116. if (callbackArgument != 0)
  222117. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  222118. return 0;
  222119. }
  222120. static void threadInitCallback (void* callbackArgument)
  222121. {
  222122. jack_Log ("JackAudioIODevice::initialise");
  222123. }
  222124. static void shutdownCallback (void* callbackArgument)
  222125. {
  222126. jack_Log ("JackAudioIODevice::shutdown");
  222127. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  222128. if (device != 0)
  222129. {
  222130. device->client = 0;
  222131. device->close();
  222132. }
  222133. }
  222134. static void errorCallback (const char* msg)
  222135. {
  222136. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  222137. }
  222138. bool isOpen_;
  222139. jack_client_t* client;
  222140. String lastError;
  222141. AudioIODeviceCallback* callback;
  222142. CriticalSection callbackLock;
  222143. HeapBlock <float*> inChans, outChans;
  222144. int totalNumberOfInputChannels;
  222145. int totalNumberOfOutputChannels;
  222146. Array<void*> inputPorts, outputPorts;
  222147. };
  222148. class JackAudioIODeviceType : public AudioIODeviceType
  222149. {
  222150. public:
  222151. JackAudioIODeviceType()
  222152. : AudioIODeviceType ("JACK"),
  222153. hasScanned (false)
  222154. {
  222155. }
  222156. ~JackAudioIODeviceType()
  222157. {
  222158. }
  222159. void scanForDevices()
  222160. {
  222161. hasScanned = true;
  222162. inputNames.clear();
  222163. inputIds.clear();
  222164. outputNames.clear();
  222165. outputIds.clear();
  222166. if (juce_libjack_handle == 0)
  222167. {
  222168. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  222169. if (juce_libjack_handle == 0)
  222170. return;
  222171. }
  222172. // open a dummy client
  222173. jack_status_t status;
  222174. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  222175. if (client == 0)
  222176. {
  222177. dumpJackErrorMessage (status);
  222178. }
  222179. else
  222180. {
  222181. // scan for output devices
  222182. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222183. if (ports != 0)
  222184. {
  222185. int j = 0;
  222186. while (ports[j] != 0)
  222187. {
  222188. String clientName (ports[j]);
  222189. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222190. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222191. && ! inputNames.contains (clientName))
  222192. {
  222193. inputNames.add (clientName);
  222194. inputIds.add (ports [j]);
  222195. }
  222196. ++j;
  222197. }
  222198. free (ports);
  222199. }
  222200. // scan for input devices
  222201. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222202. if (ports != 0)
  222203. {
  222204. int j = 0;
  222205. while (ports[j] != 0)
  222206. {
  222207. String clientName (ports[j]);
  222208. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222209. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222210. && ! outputNames.contains (clientName))
  222211. {
  222212. outputNames.add (clientName);
  222213. outputIds.add (ports [j]);
  222214. }
  222215. ++j;
  222216. }
  222217. free (ports);
  222218. }
  222219. JUCE_NAMESPACE::jack_client_close (client);
  222220. }
  222221. }
  222222. const StringArray getDeviceNames (bool wantInputNames) const
  222223. {
  222224. jassert (hasScanned); // need to call scanForDevices() before doing this
  222225. return wantInputNames ? inputNames : outputNames;
  222226. }
  222227. int getDefaultDeviceIndex (bool forInput) const
  222228. {
  222229. jassert (hasScanned); // need to call scanForDevices() before doing this
  222230. return 0;
  222231. }
  222232. bool hasSeparateInputsAndOutputs() const { return true; }
  222233. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222234. {
  222235. jassert (hasScanned); // need to call scanForDevices() before doing this
  222236. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  222237. if (d == 0)
  222238. return -1;
  222239. return asInput ? inputIds.indexOf (d->inputId)
  222240. : outputIds.indexOf (d->outputId);
  222241. }
  222242. AudioIODevice* createDevice (const String& outputDeviceName,
  222243. const String& inputDeviceName)
  222244. {
  222245. jassert (hasScanned); // need to call scanForDevices() before doing this
  222246. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222247. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222248. if (inputIndex >= 0 || outputIndex >= 0)
  222249. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  222250. : inputDeviceName,
  222251. inputIds [inputIndex],
  222252. outputIds [outputIndex]);
  222253. return 0;
  222254. }
  222255. juce_UseDebuggingNewOperator
  222256. private:
  222257. StringArray inputNames, outputNames, inputIds, outputIds;
  222258. bool hasScanned;
  222259. JackAudioIODeviceType (const JackAudioIODeviceType&);
  222260. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  222261. };
  222262. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  222263. {
  222264. return new JackAudioIODeviceType();
  222265. }
  222266. #else // if JACK is turned off..
  222267. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  222268. #endif
  222269. #endif
  222270. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  222271. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  222272. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222273. // compiled on its own).
  222274. #if JUCE_INCLUDED_FILE
  222275. #if JUCE_ALSA
  222276. static snd_seq_t* iterateDevices (const bool forInput,
  222277. StringArray& deviceNamesFound,
  222278. const int deviceIndexToOpen)
  222279. {
  222280. snd_seq_t* returnedHandle = 0;
  222281. snd_seq_t* seqHandle;
  222282. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222283. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222284. {
  222285. snd_seq_system_info_t* systemInfo;
  222286. snd_seq_client_info_t* clientInfo;
  222287. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  222288. {
  222289. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  222290. && snd_seq_client_info_malloc (&clientInfo) == 0)
  222291. {
  222292. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  222293. while (--numClients >= 0 && returnedHandle == 0)
  222294. {
  222295. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  222296. {
  222297. snd_seq_port_info_t* portInfo;
  222298. if (snd_seq_port_info_malloc (&portInfo) == 0)
  222299. {
  222300. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  222301. const int client = snd_seq_client_info_get_client (clientInfo);
  222302. snd_seq_port_info_set_client (portInfo, client);
  222303. snd_seq_port_info_set_port (portInfo, -1);
  222304. while (--numPorts >= 0)
  222305. {
  222306. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  222307. && (snd_seq_port_info_get_capability (portInfo)
  222308. & (forInput ? SND_SEQ_PORT_CAP_READ
  222309. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  222310. {
  222311. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  222312. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  222313. {
  222314. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  222315. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  222316. if (sourcePort != -1)
  222317. {
  222318. snd_seq_set_client_name (seqHandle,
  222319. forInput ? "Juce Midi Input"
  222320. : "Juce Midi Output");
  222321. const int portId
  222322. = snd_seq_create_simple_port (seqHandle,
  222323. forInput ? "Juce Midi In Port"
  222324. : "Juce Midi Out Port",
  222325. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222326. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222327. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222328. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  222329. returnedHandle = seqHandle;
  222330. }
  222331. }
  222332. }
  222333. }
  222334. snd_seq_port_info_free (portInfo);
  222335. }
  222336. }
  222337. }
  222338. snd_seq_client_info_free (clientInfo);
  222339. }
  222340. snd_seq_system_info_free (systemInfo);
  222341. }
  222342. if (returnedHandle == 0)
  222343. snd_seq_close (seqHandle);
  222344. }
  222345. deviceNamesFound.appendNumbersToDuplicates (true, true);
  222346. return returnedHandle;
  222347. }
  222348. static snd_seq_t* createDevice (const bool forInput,
  222349. const String& deviceNameToOpen)
  222350. {
  222351. snd_seq_t* seqHandle = 0;
  222352. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222353. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222354. {
  222355. snd_seq_set_client_name (seqHandle,
  222356. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  222357. const int portId
  222358. = snd_seq_create_simple_port (seqHandle,
  222359. forInput ? "in"
  222360. : "out",
  222361. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222362. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222363. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  222364. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222365. if (portId < 0)
  222366. {
  222367. snd_seq_close (seqHandle);
  222368. seqHandle = 0;
  222369. }
  222370. }
  222371. return seqHandle;
  222372. }
  222373. class MidiOutputDevice
  222374. {
  222375. public:
  222376. MidiOutputDevice (MidiOutput* const midiOutput_,
  222377. snd_seq_t* const seqHandle_)
  222378. :
  222379. midiOutput (midiOutput_),
  222380. seqHandle (seqHandle_),
  222381. maxEventSize (16 * 1024)
  222382. {
  222383. jassert (seqHandle != 0 && midiOutput != 0);
  222384. snd_midi_event_new (maxEventSize, &midiParser);
  222385. }
  222386. ~MidiOutputDevice()
  222387. {
  222388. snd_midi_event_free (midiParser);
  222389. snd_seq_close (seqHandle);
  222390. }
  222391. void sendMessageNow (const MidiMessage& message)
  222392. {
  222393. if (message.getRawDataSize() > maxEventSize)
  222394. {
  222395. maxEventSize = message.getRawDataSize();
  222396. snd_midi_event_free (midiParser);
  222397. snd_midi_event_new (maxEventSize, &midiParser);
  222398. }
  222399. snd_seq_event_t event;
  222400. snd_seq_ev_clear (&event);
  222401. snd_midi_event_encode (midiParser,
  222402. message.getRawData(),
  222403. message.getRawDataSize(),
  222404. &event);
  222405. snd_midi_event_reset_encode (midiParser);
  222406. snd_seq_ev_set_source (&event, 0);
  222407. snd_seq_ev_set_subs (&event);
  222408. snd_seq_ev_set_direct (&event);
  222409. snd_seq_event_output (seqHandle, &event);
  222410. snd_seq_drain_output (seqHandle);
  222411. }
  222412. juce_UseDebuggingNewOperator
  222413. private:
  222414. MidiOutput* const midiOutput;
  222415. snd_seq_t* const seqHandle;
  222416. snd_midi_event_t* midiParser;
  222417. int maxEventSize;
  222418. };
  222419. const StringArray MidiOutput::getDevices()
  222420. {
  222421. StringArray devices;
  222422. iterateDevices (false, devices, -1);
  222423. return devices;
  222424. }
  222425. int MidiOutput::getDefaultDeviceIndex()
  222426. {
  222427. return 0;
  222428. }
  222429. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  222430. {
  222431. MidiOutput* newDevice = 0;
  222432. StringArray devices;
  222433. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  222434. if (handle != 0)
  222435. {
  222436. newDevice = new MidiOutput();
  222437. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222438. }
  222439. return newDevice;
  222440. }
  222441. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  222442. {
  222443. MidiOutput* newDevice = 0;
  222444. snd_seq_t* const handle = createDevice (false, deviceName);
  222445. if (handle != 0)
  222446. {
  222447. newDevice = new MidiOutput();
  222448. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222449. }
  222450. return newDevice;
  222451. }
  222452. MidiOutput::~MidiOutput()
  222453. {
  222454. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  222455. delete device;
  222456. }
  222457. void MidiOutput::reset()
  222458. {
  222459. }
  222460. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  222461. {
  222462. return false;
  222463. }
  222464. void MidiOutput::setVolume (float leftVol, float rightVol)
  222465. {
  222466. }
  222467. void MidiOutput::sendMessageNow (const MidiMessage& message)
  222468. {
  222469. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  222470. }
  222471. class MidiInputThread : public Thread
  222472. {
  222473. public:
  222474. MidiInputThread (MidiInput* const midiInput_,
  222475. snd_seq_t* const seqHandle_,
  222476. MidiInputCallback* const callback_)
  222477. : Thread ("Juce MIDI Input"),
  222478. midiInput (midiInput_),
  222479. seqHandle (seqHandle_),
  222480. callback (callback_)
  222481. {
  222482. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  222483. }
  222484. ~MidiInputThread()
  222485. {
  222486. snd_seq_close (seqHandle);
  222487. }
  222488. void run()
  222489. {
  222490. const int maxEventSize = 16 * 1024;
  222491. snd_midi_event_t* midiParser;
  222492. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  222493. {
  222494. HeapBlock <uint8> buffer (maxEventSize);
  222495. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  222496. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  222497. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  222498. while (! threadShouldExit())
  222499. {
  222500. if (poll (pfd, numPfds, 500) > 0)
  222501. {
  222502. snd_seq_event_t* inputEvent = 0;
  222503. snd_seq_nonblock (seqHandle, 1);
  222504. do
  222505. {
  222506. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  222507. {
  222508. // xxx what about SYSEXes that are too big for the buffer?
  222509. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  222510. snd_midi_event_reset_decode (midiParser);
  222511. if (numBytes > 0)
  222512. {
  222513. const MidiMessage message ((const uint8*) buffer,
  222514. numBytes,
  222515. Time::getMillisecondCounter() * 0.001);
  222516. callback->handleIncomingMidiMessage (midiInput, message);
  222517. }
  222518. snd_seq_free_event (inputEvent);
  222519. }
  222520. }
  222521. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  222522. snd_seq_free_event (inputEvent);
  222523. }
  222524. }
  222525. snd_midi_event_free (midiParser);
  222526. }
  222527. };
  222528. juce_UseDebuggingNewOperator
  222529. private:
  222530. MidiInput* const midiInput;
  222531. snd_seq_t* const seqHandle;
  222532. MidiInputCallback* const callback;
  222533. };
  222534. MidiInput::MidiInput (const String& name_)
  222535. : name (name_),
  222536. internal (0)
  222537. {
  222538. }
  222539. MidiInput::~MidiInput()
  222540. {
  222541. stop();
  222542. MidiInputThread* const thread = (MidiInputThread*) internal;
  222543. delete thread;
  222544. }
  222545. void MidiInput::start()
  222546. {
  222547. ((MidiInputThread*) internal)->startThread();
  222548. }
  222549. void MidiInput::stop()
  222550. {
  222551. ((MidiInputThread*) internal)->stopThread (3000);
  222552. }
  222553. int MidiInput::getDefaultDeviceIndex()
  222554. {
  222555. return 0;
  222556. }
  222557. const StringArray MidiInput::getDevices()
  222558. {
  222559. StringArray devices;
  222560. iterateDevices (true, devices, -1);
  222561. return devices;
  222562. }
  222563. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  222564. {
  222565. MidiInput* newDevice = 0;
  222566. StringArray devices;
  222567. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  222568. if (handle != 0)
  222569. {
  222570. newDevice = new MidiInput (devices [deviceIndex]);
  222571. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222572. }
  222573. return newDevice;
  222574. }
  222575. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  222576. {
  222577. MidiInput* newDevice = 0;
  222578. snd_seq_t* const handle = createDevice (true, deviceName);
  222579. if (handle != 0)
  222580. {
  222581. newDevice = new MidiInput (deviceName);
  222582. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222583. }
  222584. return newDevice;
  222585. }
  222586. #else
  222587. // (These are just stub functions if ALSA is unavailable...)
  222588. const StringArray MidiOutput::getDevices() { return StringArray(); }
  222589. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  222590. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  222591. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  222592. MidiOutput::~MidiOutput() {}
  222593. void MidiOutput::reset() {}
  222594. bool MidiOutput::getVolume (float&, float&) { return false; }
  222595. void MidiOutput::setVolume (float, float) {}
  222596. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  222597. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  222598. MidiInput::~MidiInput() {}
  222599. void MidiInput::start() {}
  222600. void MidiInput::stop() {}
  222601. int MidiInput::getDefaultDeviceIndex() { return 0; }
  222602. const StringArray MidiInput::getDevices() { return StringArray(); }
  222603. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  222604. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  222605. #endif
  222606. #endif
  222607. /*** End of inlined file: juce_linux_Midi.cpp ***/
  222608. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  222609. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222610. // compiled on its own).
  222611. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  222612. AudioCDReader::AudioCDReader()
  222613. : AudioFormatReader (0, "CD Audio")
  222614. {
  222615. }
  222616. const StringArray AudioCDReader::getAvailableCDNames()
  222617. {
  222618. StringArray names;
  222619. return names;
  222620. }
  222621. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  222622. {
  222623. return 0;
  222624. }
  222625. AudioCDReader::~AudioCDReader()
  222626. {
  222627. }
  222628. void AudioCDReader::refreshTrackLengths()
  222629. {
  222630. }
  222631. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  222632. int64 startSampleInFile, int numSamples)
  222633. {
  222634. return false;
  222635. }
  222636. bool AudioCDReader::isCDStillPresent() const
  222637. {
  222638. return false;
  222639. }
  222640. int AudioCDReader::getNumTracks() const
  222641. {
  222642. return 0;
  222643. }
  222644. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  222645. {
  222646. return 0;
  222647. }
  222648. bool AudioCDReader::isTrackAudio (int trackNum) const
  222649. {
  222650. return false;
  222651. }
  222652. void AudioCDReader::enableIndexScanning (bool b)
  222653. {
  222654. }
  222655. int AudioCDReader::getLastIndex() const
  222656. {
  222657. return 0;
  222658. }
  222659. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  222660. {
  222661. return Array<int>();
  222662. }
  222663. int AudioCDReader::getCDDBId()
  222664. {
  222665. return 0;
  222666. }
  222667. #endif
  222668. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  222669. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  222670. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222671. // compiled on its own).
  222672. #if JUCE_INCLUDED_FILE
  222673. void FileChooser::showPlatformDialog (Array<File>& results,
  222674. const String& title,
  222675. const File& file,
  222676. const String& filters,
  222677. bool isDirectory,
  222678. bool selectsFiles,
  222679. bool isSave,
  222680. bool warnAboutOverwritingExistingFiles,
  222681. bool selectMultipleFiles,
  222682. FilePreviewComponent* previewComponent)
  222683. {
  222684. const String separator (":");
  222685. String command ("zenity --file-selection");
  222686. if (title.isNotEmpty())
  222687. command << " --title=\"" << title << "\"";
  222688. if (file != File::nonexistent)
  222689. command << " --filename=\"" << file.getFullPathName () << "\"";
  222690. if (isDirectory)
  222691. command << " --directory";
  222692. if (isSave)
  222693. command << " --save";
  222694. if (selectMultipleFiles)
  222695. command << " --multiple --separator=\"" << separator << "\"";
  222696. command << " 2>&1";
  222697. MemoryOutputStream result;
  222698. int status = -1;
  222699. FILE* stream = popen (command.toUTF8(), "r");
  222700. if (stream != 0)
  222701. {
  222702. for (;;)
  222703. {
  222704. char buffer [1024];
  222705. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  222706. if (bytesRead <= 0)
  222707. break;
  222708. result.write (buffer, bytesRead);
  222709. }
  222710. status = pclose (stream);
  222711. }
  222712. if (status == 0)
  222713. {
  222714. StringArray tokens;
  222715. if (selectMultipleFiles)
  222716. tokens.addTokens (result.toUTF8(), separator, String::empty);
  222717. else
  222718. tokens.add (result.toUTF8());
  222719. for (int i = 0; i < tokens.size(); i++)
  222720. results.add (File (tokens[i]));
  222721. return;
  222722. }
  222723. //xxx ain't got one!
  222724. jassertfalse;
  222725. }
  222726. #endif
  222727. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  222728. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  222729. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222730. // compiled on its own).
  222731. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  222732. /*
  222733. Sorry.. This class isn't implemented on Linux!
  222734. */
  222735. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  222736. : browser (0),
  222737. blankPageShown (false),
  222738. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  222739. {
  222740. setOpaque (true);
  222741. }
  222742. WebBrowserComponent::~WebBrowserComponent()
  222743. {
  222744. }
  222745. void WebBrowserComponent::goToURL (const String& url,
  222746. const StringArray* headers,
  222747. const MemoryBlock* postData)
  222748. {
  222749. lastURL = url;
  222750. lastHeaders.clear();
  222751. if (headers != 0)
  222752. lastHeaders = *headers;
  222753. lastPostData.setSize (0);
  222754. if (postData != 0)
  222755. lastPostData = *postData;
  222756. blankPageShown = false;
  222757. }
  222758. void WebBrowserComponent::stop()
  222759. {
  222760. }
  222761. void WebBrowserComponent::goBack()
  222762. {
  222763. lastURL = String::empty;
  222764. blankPageShown = false;
  222765. }
  222766. void WebBrowserComponent::goForward()
  222767. {
  222768. lastURL = String::empty;
  222769. }
  222770. void WebBrowserComponent::refresh()
  222771. {
  222772. }
  222773. void WebBrowserComponent::paint (Graphics& g)
  222774. {
  222775. g.fillAll (Colours::white);
  222776. }
  222777. void WebBrowserComponent::checkWindowAssociation()
  222778. {
  222779. }
  222780. void WebBrowserComponent::reloadLastURL()
  222781. {
  222782. if (lastURL.isNotEmpty())
  222783. {
  222784. goToURL (lastURL, &lastHeaders, &lastPostData);
  222785. lastURL = String::empty;
  222786. }
  222787. }
  222788. void WebBrowserComponent::parentHierarchyChanged()
  222789. {
  222790. checkWindowAssociation();
  222791. }
  222792. void WebBrowserComponent::resized()
  222793. {
  222794. }
  222795. void WebBrowserComponent::visibilityChanged()
  222796. {
  222797. checkWindowAssociation();
  222798. }
  222799. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  222800. {
  222801. return true;
  222802. }
  222803. #endif
  222804. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  222805. #endif
  222806. END_JUCE_NAMESPACE
  222807. #endif
  222808. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  222809. #endif
  222810. #if JUCE_MAC || JUCE_IPHONE
  222811. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  222812. /*
  222813. This file wraps together all the mac-specific code, so that
  222814. we can include all the native headers just once, and compile all our
  222815. platform-specific stuff in one big lump, keeping it out of the way of
  222816. the rest of the codebase.
  222817. */
  222818. #if JUCE_MAC || JUCE_IOS
  222819. BEGIN_JUCE_NAMESPACE
  222820. #undef Point
  222821. #define JUCE_INCLUDED_FILE 1
  222822. // Now include the actual code files..
  222823. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  222824. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  222825. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  222826. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  222827. cross-linked so that when you make a call to a class that you thought was private, it ends up
  222828. actually calling into a similarly named class in the other module's address space.
  222829. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  222830. have unique names, and should avoid this problem.
  222831. If you're using the amalgamated version, you can just set this macro to something unique before
  222832. you include juce_amalgamated.cpp.
  222833. */
  222834. #ifndef JUCE_ObjCExtraSuffix
  222835. #define JUCE_ObjCExtraSuffix 3
  222836. #endif
  222837. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  222838. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  222839. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  222840. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  222841. /*** Start of inlined file: juce_mac_Strings.mm ***/
  222842. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222843. // compiled on its own).
  222844. #if JUCE_INCLUDED_FILE
  222845. static const String nsStringToJuce (NSString* s)
  222846. {
  222847. return String::fromUTF8 ([s UTF8String]);
  222848. }
  222849. static NSString* juceStringToNS (const String& s)
  222850. {
  222851. return [NSString stringWithUTF8String: s.toUTF8()];
  222852. }
  222853. static const String convertUTF16ToString (const UniChar* utf16)
  222854. {
  222855. String s;
  222856. while (*utf16 != 0)
  222857. s += (juce_wchar) *utf16++;
  222858. return s;
  222859. }
  222860. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  222861. {
  222862. String result;
  222863. if (cfString != 0)
  222864. {
  222865. CFRange range = { 0, CFStringGetLength (cfString) };
  222866. HeapBlock <UniChar> u (range.length + 1);
  222867. CFStringGetCharacters (cfString, range, u);
  222868. u[range.length] = 0;
  222869. result = convertUTF16ToString (u);
  222870. }
  222871. return result;
  222872. }
  222873. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  222874. {
  222875. const int len = s.length();
  222876. HeapBlock <UniChar> temp (len + 2);
  222877. for (int i = 0; i <= len; ++i)
  222878. temp[i] = s[i];
  222879. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  222880. }
  222881. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  222882. {
  222883. #if JUCE_IOS
  222884. const ScopedAutoReleasePool pool;
  222885. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  222886. #else
  222887. UnicodeMapping map;
  222888. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  222889. kUnicodeNoSubset,
  222890. kTextEncodingDefaultFormat);
  222891. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  222892. kUnicodeCanonicalCompVariant,
  222893. kTextEncodingDefaultFormat);
  222894. map.mappingVersion = kUnicodeUseLatestMapping;
  222895. UnicodeToTextInfo conversionInfo = 0;
  222896. String result;
  222897. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  222898. {
  222899. const int len = s.length();
  222900. HeapBlock <UniChar> tempIn, tempOut;
  222901. tempIn.calloc (len + 2);
  222902. tempOut.calloc (len + 2);
  222903. for (int i = 0; i <= len; ++i)
  222904. tempIn[i] = s[i];
  222905. ByteCount bytesRead = 0;
  222906. ByteCount outputBufferSize = 0;
  222907. if (ConvertFromUnicodeToText (conversionInfo,
  222908. len * sizeof (UniChar), tempIn,
  222909. kUnicodeDefaultDirectionMask,
  222910. 0, 0, 0, 0,
  222911. len * sizeof (UniChar), &bytesRead,
  222912. &outputBufferSize, tempOut) == noErr)
  222913. {
  222914. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  222915. juce_wchar* t = result;
  222916. unsigned int i;
  222917. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  222918. t[i] = (juce_wchar) tempOut[i];
  222919. t[i] = 0;
  222920. }
  222921. DisposeUnicodeToTextInfo (&conversionInfo);
  222922. }
  222923. return result;
  222924. #endif
  222925. }
  222926. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  222927. void SystemClipboard::copyTextToClipboard (const String& text)
  222928. {
  222929. #if JUCE_IOS
  222930. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  222931. forPasteboardType: @"public.text"];
  222932. #else
  222933. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  222934. owner: nil];
  222935. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  222936. forType: NSStringPboardType];
  222937. #endif
  222938. }
  222939. const String SystemClipboard::getTextFromClipboard()
  222940. {
  222941. #if JUCE_IOS
  222942. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  222943. #else
  222944. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  222945. #endif
  222946. return text == 0 ? String::empty
  222947. : nsStringToJuce (text);
  222948. }
  222949. #endif
  222950. #endif
  222951. /*** End of inlined file: juce_mac_Strings.mm ***/
  222952. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  222953. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222954. // compiled on its own).
  222955. #if JUCE_INCLUDED_FILE
  222956. namespace SystemStatsHelpers
  222957. {
  222958. static int64 highResTimerFrequency = 0;
  222959. static double highResTimerToMillisecRatio = 0;
  222960. #if JUCE_INTEL
  222961. static void juce_getCpuVendor (char* const v) throw()
  222962. {
  222963. int vendor[4];
  222964. zerostruct (vendor);
  222965. int dummy = 0;
  222966. asm ("mov %%ebx, %%esi \n\t"
  222967. "cpuid \n\t"
  222968. "xchg %%esi, %%ebx"
  222969. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  222970. memcpy (v, vendor, 16);
  222971. }
  222972. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  222973. {
  222974. unsigned int cpu = 0;
  222975. unsigned int ext = 0;
  222976. unsigned int family = 0;
  222977. unsigned int dummy = 0;
  222978. asm ("mov %%ebx, %%esi \n\t"
  222979. "cpuid \n\t"
  222980. "xchg %%esi, %%ebx"
  222981. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  222982. familyModel = family;
  222983. extFeatures = ext;
  222984. return cpu;
  222985. }
  222986. #endif
  222987. }
  222988. void SystemStats::initialiseStats()
  222989. {
  222990. using namespace SystemStatsHelpers;
  222991. static bool initialised = false;
  222992. if (! initialised)
  222993. {
  222994. initialised = true;
  222995. #if JUCE_MAC
  222996. // extremely annoying: adding this line stops the apple menu items from working. Of
  222997. // course, not adding it means that carbon windows (e.g. in plugins) won't get
  222998. // any events.
  222999. //NSApplicationLoad();
  223000. [NSApplication sharedApplication];
  223001. #endif
  223002. #if JUCE_INTEL
  223003. unsigned int familyModel, extFeatures;
  223004. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  223005. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  223006. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  223007. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  223008. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  223009. #else
  223010. cpuFlags.hasMMX = false;
  223011. cpuFlags.hasSSE = false;
  223012. cpuFlags.hasSSE2 = false;
  223013. cpuFlags.has3DNow = false;
  223014. #endif
  223015. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  223016. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  223017. #else
  223018. cpuFlags.numCpus = (int) MPProcessors();
  223019. #endif
  223020. mach_timebase_info_data_t timebase;
  223021. (void) mach_timebase_info (&timebase);
  223022. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  223023. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  223024. String s (SystemStats::getJUCEVersion());
  223025. rlimit lim;
  223026. getrlimit (RLIMIT_NOFILE, &lim);
  223027. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  223028. setrlimit (RLIMIT_NOFILE, &lim);
  223029. }
  223030. }
  223031. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  223032. {
  223033. return MacOSX;
  223034. }
  223035. const String SystemStats::getOperatingSystemName()
  223036. {
  223037. return "Mac OS X";
  223038. }
  223039. bool SystemStats::isOperatingSystem64Bit()
  223040. {
  223041. #if JUCE_64BIT
  223042. return true;
  223043. #else
  223044. //xxx not sure how to find this out?..
  223045. return false;
  223046. #endif
  223047. }
  223048. int SystemStats::getMemorySizeInMegabytes()
  223049. {
  223050. uint64 mem = 0;
  223051. size_t memSize = sizeof (mem);
  223052. int mib[] = { CTL_HW, HW_MEMSIZE };
  223053. sysctl (mib, 2, &mem, &memSize, 0, 0);
  223054. return (int) (mem / (1024 * 1024));
  223055. }
  223056. const String SystemStats::getCpuVendor()
  223057. {
  223058. #if JUCE_INTEL
  223059. char v [16];
  223060. SystemStatsHelpers::juce_getCpuVendor (v);
  223061. return String (v, 16);
  223062. #else
  223063. return String::empty;
  223064. #endif
  223065. }
  223066. int SystemStats::getCpuSpeedInMegaherz()
  223067. {
  223068. uint64 speedHz = 0;
  223069. size_t speedSize = sizeof (speedHz);
  223070. int mib[] = { CTL_HW, HW_CPU_FREQ };
  223071. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  223072. #if JUCE_BIG_ENDIAN
  223073. if (speedSize == 4)
  223074. speedHz >>= 32;
  223075. #endif
  223076. return (int) (speedHz / 1000000);
  223077. }
  223078. const String SystemStats::getLogonName()
  223079. {
  223080. return nsStringToJuce (NSUserName());
  223081. }
  223082. const String SystemStats::getFullUserName()
  223083. {
  223084. return nsStringToJuce (NSFullUserName());
  223085. }
  223086. uint32 juce_millisecondsSinceStartup() throw()
  223087. {
  223088. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  223089. }
  223090. double Time::getMillisecondCounterHiRes() throw()
  223091. {
  223092. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  223093. }
  223094. int64 Time::getHighResolutionTicks() throw()
  223095. {
  223096. return (int64) mach_absolute_time();
  223097. }
  223098. int64 Time::getHighResolutionTicksPerSecond() throw()
  223099. {
  223100. return SystemStatsHelpers::highResTimerFrequency;
  223101. }
  223102. bool Time::setSystemTimeToThisTime() const
  223103. {
  223104. jassertfalse;
  223105. return false;
  223106. }
  223107. int SystemStats::getPageSize()
  223108. {
  223109. return (int) NSPageSize();
  223110. }
  223111. void PlatformUtilities::fpuReset()
  223112. {
  223113. }
  223114. #endif
  223115. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  223116. /*** Start of inlined file: juce_mac_Network.mm ***/
  223117. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223118. // compiled on its own).
  223119. #if JUCE_INCLUDED_FILE
  223120. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  223121. {
  223122. #ifndef IFT_ETHER
  223123. #define IFT_ETHER 6
  223124. #endif
  223125. ifaddrs* addrs = 0;
  223126. int numResults = 0;
  223127. if (getifaddrs (&addrs) == 0)
  223128. {
  223129. const ifaddrs* cursor = addrs;
  223130. while (cursor != 0 && numResults < maxNum)
  223131. {
  223132. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  223133. if (sto->ss_family == AF_LINK)
  223134. {
  223135. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  223136. if (sadd->sdl_type == IFT_ETHER)
  223137. {
  223138. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  223139. uint64 a = 0;
  223140. for (int i = 6; --i >= 0;)
  223141. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  223142. *addresses++ = (int64) a;
  223143. ++numResults;
  223144. }
  223145. }
  223146. cursor = cursor->ifa_next;
  223147. }
  223148. freeifaddrs (addrs);
  223149. }
  223150. return numResults;
  223151. }
  223152. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  223153. const String& emailSubject,
  223154. const String& bodyText,
  223155. const StringArray& filesToAttach)
  223156. {
  223157. #if JUCE_IOS
  223158. //xxx probably need to use MFMailComposeViewController
  223159. jassertfalse;
  223160. return false;
  223161. #else
  223162. const ScopedAutoReleasePool pool;
  223163. String script;
  223164. script << "tell application \"Mail\"\r\n"
  223165. "set newMessage to make new outgoing message with properties {subject:\""
  223166. << emailSubject.replace ("\"", "\\\"")
  223167. << "\", content:\""
  223168. << bodyText.replace ("\"", "\\\"")
  223169. << "\" & return & return}\r\n"
  223170. "tell newMessage\r\n"
  223171. "set visible to true\r\n"
  223172. "set sender to \"sdfsdfsdfewf\"\r\n"
  223173. "make new to recipient at end of to recipients with properties {address:\""
  223174. << targetEmailAddress
  223175. << "\"}\r\n";
  223176. for (int i = 0; i < filesToAttach.size(); ++i)
  223177. {
  223178. script << "tell content\r\n"
  223179. "make new attachment with properties {file name:\""
  223180. << filesToAttach[i].replace ("\"", "\\\"")
  223181. << "\"} at after the last paragraph\r\n"
  223182. "end tell\r\n";
  223183. }
  223184. script << "end tell\r\n"
  223185. "end tell\r\n";
  223186. NSAppleScript* s = [[NSAppleScript alloc]
  223187. initWithSource: juceStringToNS (script)];
  223188. NSDictionary* error = 0;
  223189. const bool ok = [s executeAndReturnError: &error] != nil;
  223190. [s release];
  223191. return ok;
  223192. #endif
  223193. }
  223194. END_JUCE_NAMESPACE
  223195. using namespace JUCE_NAMESPACE;
  223196. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  223197. @interface JuceURLConnection : NSObject
  223198. {
  223199. @public
  223200. NSURLRequest* request;
  223201. NSURLConnection* connection;
  223202. NSMutableData* data;
  223203. Thread* runLoopThread;
  223204. bool initialised, hasFailed, hasFinished;
  223205. int position;
  223206. int64 contentLength;
  223207. NSDictionary* headers;
  223208. NSLock* dataLock;
  223209. }
  223210. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  223211. - (void) dealloc;
  223212. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  223213. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  223214. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  223215. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  223216. - (BOOL) isOpen;
  223217. - (int) read: (char*) dest numBytes: (int) num;
  223218. - (int) readPosition;
  223219. - (void) stop;
  223220. - (void) createConnection;
  223221. @end
  223222. class JuceURLConnectionMessageThread : public Thread
  223223. {
  223224. JuceURLConnection* owner;
  223225. public:
  223226. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  223227. : Thread ("http connection"),
  223228. owner (owner_)
  223229. {
  223230. }
  223231. ~JuceURLConnectionMessageThread()
  223232. {
  223233. stopThread (10000);
  223234. }
  223235. void run()
  223236. {
  223237. [owner createConnection];
  223238. while (! threadShouldExit())
  223239. {
  223240. const ScopedAutoReleasePool pool;
  223241. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  223242. }
  223243. }
  223244. };
  223245. @implementation JuceURLConnection
  223246. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  223247. withCallback: (URL::OpenStreamProgressCallback*) callback
  223248. withContext: (void*) context;
  223249. {
  223250. [super init];
  223251. request = req;
  223252. [request retain];
  223253. data = [[NSMutableData data] retain];
  223254. dataLock = [[NSLock alloc] init];
  223255. connection = 0;
  223256. initialised = false;
  223257. hasFailed = false;
  223258. hasFinished = false;
  223259. contentLength = -1;
  223260. headers = 0;
  223261. runLoopThread = new JuceURLConnectionMessageThread (self);
  223262. runLoopThread->startThread();
  223263. while (runLoopThread->isThreadRunning() && ! initialised)
  223264. {
  223265. if (callback != 0)
  223266. callback (context, -1, (int) [[request HTTPBody] length]);
  223267. Thread::sleep (1);
  223268. }
  223269. return self;
  223270. }
  223271. - (void) dealloc
  223272. {
  223273. [self stop];
  223274. deleteAndZero (runLoopThread);
  223275. [connection release];
  223276. [data release];
  223277. [dataLock release];
  223278. [request release];
  223279. [headers release];
  223280. [super dealloc];
  223281. }
  223282. - (void) createConnection
  223283. {
  223284. NSUInteger oldRetainCount = [self retainCount];
  223285. connection = [[NSURLConnection alloc] initWithRequest: request
  223286. delegate: self];
  223287. if (oldRetainCount == [self retainCount])
  223288. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  223289. if (connection == nil)
  223290. runLoopThread->signalThreadShouldExit();
  223291. }
  223292. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  223293. {
  223294. (void) conn;
  223295. [dataLock lock];
  223296. [data setLength: 0];
  223297. [dataLock unlock];
  223298. initialised = true;
  223299. contentLength = [response expectedContentLength];
  223300. [headers release];
  223301. headers = 0;
  223302. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  223303. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  223304. }
  223305. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  223306. {
  223307. (void) conn;
  223308. DBG (nsStringToJuce ([error description]));
  223309. hasFailed = true;
  223310. initialised = true;
  223311. if (runLoopThread != 0)
  223312. runLoopThread->signalThreadShouldExit();
  223313. }
  223314. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  223315. {
  223316. (void) conn;
  223317. [dataLock lock];
  223318. [data appendData: newData];
  223319. [dataLock unlock];
  223320. initialised = true;
  223321. }
  223322. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  223323. {
  223324. (void) conn;
  223325. hasFinished = true;
  223326. initialised = true;
  223327. if (runLoopThread != 0)
  223328. runLoopThread->signalThreadShouldExit();
  223329. }
  223330. - (BOOL) isOpen
  223331. {
  223332. return connection != 0 && ! hasFailed;
  223333. }
  223334. - (int) readPosition
  223335. {
  223336. return position;
  223337. }
  223338. - (int) read: (char*) dest numBytes: (int) numNeeded
  223339. {
  223340. int numDone = 0;
  223341. while (numNeeded > 0)
  223342. {
  223343. int available = jmin (numNeeded, (int) [data length]);
  223344. if (available > 0)
  223345. {
  223346. [dataLock lock];
  223347. [data getBytes: dest length: available];
  223348. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  223349. [dataLock unlock];
  223350. numDone += available;
  223351. numNeeded -= available;
  223352. dest += available;
  223353. }
  223354. else
  223355. {
  223356. if (hasFailed || hasFinished)
  223357. break;
  223358. Thread::sleep (1);
  223359. }
  223360. }
  223361. position += numDone;
  223362. return numDone;
  223363. }
  223364. - (void) stop
  223365. {
  223366. [connection cancel];
  223367. if (runLoopThread != 0)
  223368. runLoopThread->stopThread (10000);
  223369. }
  223370. @end
  223371. BEGIN_JUCE_NAMESPACE
  223372. void* juce_openInternetFile (const String& url,
  223373. const String& headers,
  223374. const MemoryBlock& postData,
  223375. const bool isPost,
  223376. URL::OpenStreamProgressCallback* callback,
  223377. void* callbackContext,
  223378. int timeOutMs)
  223379. {
  223380. const ScopedAutoReleasePool pool;
  223381. NSMutableURLRequest* req = [NSMutableURLRequest
  223382. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  223383. cachePolicy: NSURLRequestUseProtocolCachePolicy
  223384. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  223385. if (req == nil)
  223386. return 0;
  223387. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  223388. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  223389. StringArray headerLines;
  223390. headerLines.addLines (headers);
  223391. headerLines.removeEmptyStrings (true);
  223392. for (int i = 0; i < headerLines.size(); ++i)
  223393. {
  223394. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  223395. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  223396. if (key.isNotEmpty() && value.isNotEmpty())
  223397. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  223398. }
  223399. if (isPost && postData.getSize() > 0)
  223400. {
  223401. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  223402. length: postData.getSize()]];
  223403. }
  223404. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  223405. withCallback: callback
  223406. withContext: callbackContext];
  223407. if ([s isOpen])
  223408. return s;
  223409. [s release];
  223410. return 0;
  223411. }
  223412. void juce_closeInternetFile (void* handle)
  223413. {
  223414. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223415. if (s != 0)
  223416. {
  223417. const ScopedAutoReleasePool pool;
  223418. [s stop];
  223419. [s release];
  223420. }
  223421. }
  223422. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  223423. {
  223424. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223425. if (s != 0)
  223426. {
  223427. const ScopedAutoReleasePool pool;
  223428. return [s read: (char*) buffer numBytes: bytesToRead];
  223429. }
  223430. return 0;
  223431. }
  223432. int64 juce_getInternetFileContentLength (void* handle)
  223433. {
  223434. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223435. if (s != 0)
  223436. return s->contentLength;
  223437. return -1;
  223438. }
  223439. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  223440. {
  223441. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223442. if (s != 0 && s->headers != 0)
  223443. {
  223444. NSEnumerator* enumerator = [s->headers keyEnumerator];
  223445. NSString* key;
  223446. while ((key = [enumerator nextObject]) != nil)
  223447. headers.set (nsStringToJuce (key),
  223448. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  223449. }
  223450. }
  223451. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  223452. {
  223453. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223454. if (s != 0)
  223455. return [s readPosition];
  223456. return 0;
  223457. }
  223458. #endif
  223459. /*** End of inlined file: juce_mac_Network.mm ***/
  223460. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  223461. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223462. // compiled on its own).
  223463. #if JUCE_INCLUDED_FILE
  223464. struct NamedPipeInternal
  223465. {
  223466. String pipeInName, pipeOutName;
  223467. int pipeIn, pipeOut;
  223468. bool volatile createdPipe, blocked, stopReadOperation;
  223469. static void signalHandler (int) {}
  223470. };
  223471. void NamedPipe::cancelPendingReads()
  223472. {
  223473. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  223474. {
  223475. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223476. intern->stopReadOperation = true;
  223477. char buffer [1] = { 0 };
  223478. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  223479. (void) bytesWritten;
  223480. int timeout = 2000;
  223481. while (intern->blocked && --timeout >= 0)
  223482. Thread::sleep (2);
  223483. intern->stopReadOperation = false;
  223484. }
  223485. }
  223486. void NamedPipe::close()
  223487. {
  223488. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223489. if (intern != 0)
  223490. {
  223491. internal = 0;
  223492. if (intern->pipeIn != -1)
  223493. ::close (intern->pipeIn);
  223494. if (intern->pipeOut != -1)
  223495. ::close (intern->pipeOut);
  223496. if (intern->createdPipe)
  223497. {
  223498. unlink (intern->pipeInName.toUTF8());
  223499. unlink (intern->pipeOutName.toUTF8());
  223500. }
  223501. delete intern;
  223502. }
  223503. }
  223504. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  223505. {
  223506. close();
  223507. NamedPipeInternal* const intern = new NamedPipeInternal();
  223508. internal = intern;
  223509. intern->createdPipe = createPipe;
  223510. intern->blocked = false;
  223511. intern->stopReadOperation = false;
  223512. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  223513. siginterrupt (SIGPIPE, 1);
  223514. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  223515. intern->pipeInName = pipePath + "_in";
  223516. intern->pipeOutName = pipePath + "_out";
  223517. intern->pipeIn = -1;
  223518. intern->pipeOut = -1;
  223519. if (createPipe)
  223520. {
  223521. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  223522. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  223523. {
  223524. delete intern;
  223525. internal = 0;
  223526. return false;
  223527. }
  223528. }
  223529. return true;
  223530. }
  223531. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  223532. {
  223533. int bytesRead = -1;
  223534. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223535. if (intern != 0)
  223536. {
  223537. intern->blocked = true;
  223538. if (intern->pipeIn == -1)
  223539. {
  223540. if (intern->createdPipe)
  223541. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  223542. else
  223543. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  223544. if (intern->pipeIn == -1)
  223545. {
  223546. intern->blocked = false;
  223547. return -1;
  223548. }
  223549. }
  223550. bytesRead = 0;
  223551. char* p = (char*) destBuffer;
  223552. while (bytesRead < maxBytesToRead)
  223553. {
  223554. const int bytesThisTime = maxBytesToRead - bytesRead;
  223555. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  223556. if (numRead <= 0 || intern->stopReadOperation)
  223557. {
  223558. bytesRead = -1;
  223559. break;
  223560. }
  223561. bytesRead += numRead;
  223562. p += bytesRead;
  223563. }
  223564. intern->blocked = false;
  223565. }
  223566. return bytesRead;
  223567. }
  223568. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  223569. {
  223570. int bytesWritten = -1;
  223571. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223572. if (intern != 0)
  223573. {
  223574. if (intern->pipeOut == -1)
  223575. {
  223576. if (intern->createdPipe)
  223577. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  223578. else
  223579. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  223580. if (intern->pipeOut == -1)
  223581. {
  223582. return -1;
  223583. }
  223584. }
  223585. const char* p = (const char*) sourceBuffer;
  223586. bytesWritten = 0;
  223587. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  223588. while (bytesWritten < numBytesToWrite
  223589. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  223590. {
  223591. const int bytesThisTime = numBytesToWrite - bytesWritten;
  223592. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  223593. if (numWritten <= 0)
  223594. {
  223595. bytesWritten = -1;
  223596. break;
  223597. }
  223598. bytesWritten += numWritten;
  223599. p += bytesWritten;
  223600. }
  223601. }
  223602. return bytesWritten;
  223603. }
  223604. #endif
  223605. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  223606. /*** Start of inlined file: juce_mac_Threads.mm ***/
  223607. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223608. // compiled on its own).
  223609. #if JUCE_INCLUDED_FILE
  223610. /*
  223611. Note that a lot of methods that you'd expect to find in this file actually
  223612. live in juce_posix_SharedCode.h!
  223613. */
  223614. void JUCE_API juce_threadEntryPoint (void*);
  223615. void* threadEntryProc (void* userData)
  223616. {
  223617. const ScopedAutoReleasePool pool;
  223618. juce_threadEntryPoint (userData);
  223619. return 0;
  223620. }
  223621. void* juce_createThread (void* userData)
  223622. {
  223623. pthread_t handle = 0;
  223624. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  223625. {
  223626. pthread_detach (handle);
  223627. return (void*) handle;
  223628. }
  223629. return 0;
  223630. }
  223631. void juce_killThread (void* handle)
  223632. {
  223633. if (handle != 0)
  223634. pthread_cancel ((pthread_t) handle);
  223635. }
  223636. void juce_setCurrentThreadName (const String& /*name*/)
  223637. {
  223638. }
  223639. bool juce_setThreadPriority (void* handle, int priority)
  223640. {
  223641. if (handle == 0)
  223642. handle = (void*) pthread_self();
  223643. struct sched_param param;
  223644. int policy;
  223645. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  223646. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  223647. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  223648. }
  223649. Thread::ThreadID Thread::getCurrentThreadId()
  223650. {
  223651. return static_cast <ThreadID> (pthread_self());
  223652. }
  223653. void Thread::yield()
  223654. {
  223655. sched_yield();
  223656. }
  223657. void Thread::setCurrentThreadAffinityMask (const uint32 /*affinityMask*/)
  223658. {
  223659. // xxx
  223660. jassertfalse;
  223661. }
  223662. bool Process::isForegroundProcess()
  223663. {
  223664. #if JUCE_MAC
  223665. return [NSApp isActive];
  223666. #else
  223667. return true; // xxx change this if more than one app is ever possible on the iPhone!
  223668. #endif
  223669. }
  223670. void Process::raisePrivilege()
  223671. {
  223672. jassertfalse;
  223673. }
  223674. void Process::lowerPrivilege()
  223675. {
  223676. jassertfalse;
  223677. }
  223678. void Process::terminate()
  223679. {
  223680. exit (0);
  223681. }
  223682. void Process::setPriority (ProcessPriority)
  223683. {
  223684. // xxx
  223685. }
  223686. #endif
  223687. /*** End of inlined file: juce_mac_Threads.mm ***/
  223688. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  223689. /*
  223690. This file contains posix routines that are common to both the Linux and Mac builds.
  223691. It gets included directly in the cpp files for these platforms.
  223692. */
  223693. CriticalSection::CriticalSection() throw()
  223694. {
  223695. pthread_mutexattr_t atts;
  223696. pthread_mutexattr_init (&atts);
  223697. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  223698. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  223699. pthread_mutex_init (&internal, &atts);
  223700. }
  223701. CriticalSection::~CriticalSection() throw()
  223702. {
  223703. pthread_mutex_destroy (&internal);
  223704. }
  223705. void CriticalSection::enter() const throw()
  223706. {
  223707. pthread_mutex_lock (&internal);
  223708. }
  223709. bool CriticalSection::tryEnter() const throw()
  223710. {
  223711. return pthread_mutex_trylock (&internal) == 0;
  223712. }
  223713. void CriticalSection::exit() const throw()
  223714. {
  223715. pthread_mutex_unlock (&internal);
  223716. }
  223717. class WaitableEventImpl
  223718. {
  223719. public:
  223720. WaitableEventImpl (const bool manualReset_)
  223721. : triggered (false),
  223722. manualReset (manualReset_)
  223723. {
  223724. pthread_cond_init (&condition, 0);
  223725. pthread_mutexattr_t atts;
  223726. pthread_mutexattr_init (&atts);
  223727. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  223728. pthread_mutex_init (&mutex, &atts);
  223729. }
  223730. ~WaitableEventImpl()
  223731. {
  223732. pthread_cond_destroy (&condition);
  223733. pthread_mutex_destroy (&mutex);
  223734. }
  223735. bool wait (const int timeOutMillisecs) throw()
  223736. {
  223737. pthread_mutex_lock (&mutex);
  223738. if (! triggered)
  223739. {
  223740. if (timeOutMillisecs < 0)
  223741. {
  223742. do
  223743. {
  223744. pthread_cond_wait (&condition, &mutex);
  223745. }
  223746. while (! triggered);
  223747. }
  223748. else
  223749. {
  223750. struct timeval now;
  223751. gettimeofday (&now, 0);
  223752. struct timespec time;
  223753. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  223754. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  223755. if (time.tv_nsec >= 1000000000)
  223756. {
  223757. time.tv_nsec -= 1000000000;
  223758. time.tv_sec++;
  223759. }
  223760. do
  223761. {
  223762. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  223763. {
  223764. pthread_mutex_unlock (&mutex);
  223765. return false;
  223766. }
  223767. }
  223768. while (! triggered);
  223769. }
  223770. }
  223771. if (! manualReset)
  223772. triggered = false;
  223773. pthread_mutex_unlock (&mutex);
  223774. return true;
  223775. }
  223776. void signal() throw()
  223777. {
  223778. pthread_mutex_lock (&mutex);
  223779. triggered = true;
  223780. pthread_cond_broadcast (&condition);
  223781. pthread_mutex_unlock (&mutex);
  223782. }
  223783. void reset() throw()
  223784. {
  223785. pthread_mutex_lock (&mutex);
  223786. triggered = false;
  223787. pthread_mutex_unlock (&mutex);
  223788. }
  223789. private:
  223790. pthread_cond_t condition;
  223791. pthread_mutex_t mutex;
  223792. bool triggered;
  223793. const bool manualReset;
  223794. WaitableEventImpl (const WaitableEventImpl&);
  223795. WaitableEventImpl& operator= (const WaitableEventImpl&);
  223796. };
  223797. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  223798. : internal (new WaitableEventImpl (manualReset))
  223799. {
  223800. }
  223801. WaitableEvent::~WaitableEvent() throw()
  223802. {
  223803. delete static_cast <WaitableEventImpl*> (internal);
  223804. }
  223805. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  223806. {
  223807. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  223808. }
  223809. void WaitableEvent::signal() const throw()
  223810. {
  223811. static_cast <WaitableEventImpl*> (internal)->signal();
  223812. }
  223813. void WaitableEvent::reset() const throw()
  223814. {
  223815. static_cast <WaitableEventImpl*> (internal)->reset();
  223816. }
  223817. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  223818. {
  223819. struct timespec time;
  223820. time.tv_sec = millisecs / 1000;
  223821. time.tv_nsec = (millisecs % 1000) * 1000000;
  223822. nanosleep (&time, 0);
  223823. }
  223824. const juce_wchar File::separator = '/';
  223825. const String File::separatorString ("/");
  223826. const File File::getCurrentWorkingDirectory()
  223827. {
  223828. HeapBlock<char> heapBuffer;
  223829. char localBuffer [1024];
  223830. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  223831. int bufferSize = 4096;
  223832. while (cwd == 0 && errno == ERANGE)
  223833. {
  223834. heapBuffer.malloc (bufferSize);
  223835. cwd = getcwd (heapBuffer, bufferSize - 1);
  223836. bufferSize += 1024;
  223837. }
  223838. return File (String::fromUTF8 (cwd));
  223839. }
  223840. bool File::setAsCurrentWorkingDirectory() const
  223841. {
  223842. return chdir (getFullPathName().toUTF8()) == 0;
  223843. }
  223844. static bool juce_stat (const String& fileName, struct stat& info)
  223845. {
  223846. return fileName.isNotEmpty()
  223847. && (stat (fileName.toUTF8(), &info) == 0);
  223848. }
  223849. bool File::isDirectory() const
  223850. {
  223851. struct stat info;
  223852. return fullPath.isEmpty()
  223853. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  223854. }
  223855. bool File::exists() const
  223856. {
  223857. return fullPath.isNotEmpty()
  223858. && access (fullPath.toUTF8(), F_OK) == 0;
  223859. }
  223860. bool File::existsAsFile() const
  223861. {
  223862. return exists() && ! isDirectory();
  223863. }
  223864. int64 File::getSize() const
  223865. {
  223866. struct stat info;
  223867. return juce_stat (fullPath, info) ? info.st_size : 0;
  223868. }
  223869. bool File::hasWriteAccess() const
  223870. {
  223871. if (exists())
  223872. return access (fullPath.toUTF8(), W_OK) == 0;
  223873. if ((! isDirectory()) && fullPath.containsChar (separator))
  223874. return getParentDirectory().hasWriteAccess();
  223875. return false;
  223876. }
  223877. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  223878. {
  223879. struct stat info;
  223880. const int res = stat (fullPath.toUTF8(), &info);
  223881. if (res != 0)
  223882. return false;
  223883. info.st_mode &= 0777; // Just permissions
  223884. if (shouldBeReadOnly)
  223885. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  223886. else
  223887. // Give everybody write permission?
  223888. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  223889. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  223890. }
  223891. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  223892. {
  223893. modificationTime = 0;
  223894. accessTime = 0;
  223895. creationTime = 0;
  223896. struct stat info;
  223897. const int res = stat (fullPath.toUTF8(), &info);
  223898. if (res == 0)
  223899. {
  223900. modificationTime = (int64) info.st_mtime * 1000;
  223901. accessTime = (int64) info.st_atime * 1000;
  223902. creationTime = (int64) info.st_ctime * 1000;
  223903. }
  223904. }
  223905. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  223906. {
  223907. struct utimbuf times;
  223908. times.actime = (time_t) (accessTime / 1000);
  223909. times.modtime = (time_t) (modificationTime / 1000);
  223910. return utime (fullPath.toUTF8(), &times) == 0;
  223911. }
  223912. bool File::deleteFile() const
  223913. {
  223914. if (! exists())
  223915. return true;
  223916. else if (isDirectory())
  223917. return rmdir (fullPath.toUTF8()) == 0;
  223918. else
  223919. return remove (fullPath.toUTF8()) == 0;
  223920. }
  223921. bool File::moveInternal (const File& dest) const
  223922. {
  223923. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  223924. return true;
  223925. if (hasWriteAccess() && copyInternal (dest))
  223926. {
  223927. if (deleteFile())
  223928. return true;
  223929. dest.deleteFile();
  223930. }
  223931. return false;
  223932. }
  223933. void File::createDirectoryInternal (const String& fileName) const
  223934. {
  223935. mkdir (fileName.toUTF8(), 0777);
  223936. }
  223937. void* juce_fileOpen (const File& file, bool forWriting)
  223938. {
  223939. int flags = O_RDONLY;
  223940. if (forWriting)
  223941. {
  223942. if (file.exists())
  223943. {
  223944. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  223945. if (f != -1)
  223946. lseek (f, 0, SEEK_END);
  223947. return (void*) f;
  223948. }
  223949. else
  223950. {
  223951. flags = O_RDWR + O_CREAT;
  223952. }
  223953. }
  223954. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  223955. }
  223956. void juce_fileClose (void* handle)
  223957. {
  223958. if (handle != 0)
  223959. close ((int) (pointer_sized_int) handle);
  223960. }
  223961. int juce_fileRead (void* handle, void* buffer, int size)
  223962. {
  223963. if (handle != 0)
  223964. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  223965. return 0;
  223966. }
  223967. int juce_fileWrite (void* handle, const void* buffer, int size)
  223968. {
  223969. if (handle != 0)
  223970. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  223971. return 0;
  223972. }
  223973. int64 juce_fileSetPosition (void* handle, int64 pos)
  223974. {
  223975. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  223976. return pos;
  223977. return -1;
  223978. }
  223979. int64 FileOutputStream::getPositionInternal() const
  223980. {
  223981. if (fileHandle != 0)
  223982. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  223983. return -1;
  223984. }
  223985. void FileOutputStream::flushInternal()
  223986. {
  223987. if (fileHandle != 0)
  223988. fsync ((int) (pointer_sized_int) fileHandle);
  223989. }
  223990. const File juce_getExecutableFile()
  223991. {
  223992. Dl_info exeInfo;
  223993. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  223994. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  223995. }
  223996. // if this file doesn't exist, find a parent of it that does..
  223997. static bool juce_doStatFS (File f, struct statfs& result)
  223998. {
  223999. for (int i = 5; --i >= 0;)
  224000. {
  224001. if (f.exists())
  224002. break;
  224003. f = f.getParentDirectory();
  224004. }
  224005. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  224006. }
  224007. int64 File::getBytesFreeOnVolume() const
  224008. {
  224009. struct statfs buf;
  224010. if (juce_doStatFS (*this, buf))
  224011. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  224012. return 0;
  224013. }
  224014. int64 File::getVolumeTotalSize() const
  224015. {
  224016. struct statfs buf;
  224017. if (juce_doStatFS (*this, buf))
  224018. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  224019. return 0;
  224020. }
  224021. const String File::getVolumeLabel() const
  224022. {
  224023. #if JUCE_MAC
  224024. struct VolAttrBuf
  224025. {
  224026. u_int32_t length;
  224027. attrreference_t mountPointRef;
  224028. char mountPointSpace [MAXPATHLEN];
  224029. } attrBuf;
  224030. struct attrlist attrList;
  224031. zerostruct (attrList);
  224032. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  224033. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  224034. File f (*this);
  224035. for (;;)
  224036. {
  224037. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  224038. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  224039. (int) attrBuf.mountPointRef.attr_length);
  224040. const File parent (f.getParentDirectory());
  224041. if (f == parent)
  224042. break;
  224043. f = parent;
  224044. }
  224045. #endif
  224046. return String::empty;
  224047. }
  224048. int File::getVolumeSerialNumber() const
  224049. {
  224050. return 0; // xxx
  224051. }
  224052. void juce_runSystemCommand (const String& command)
  224053. {
  224054. int result = system (command.toUTF8());
  224055. (void) result;
  224056. }
  224057. const String juce_getOutputFromCommand (const String& command)
  224058. {
  224059. // slight bodge here, as we just pipe the output into a temp file and read it...
  224060. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  224061. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  224062. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  224063. String result (tempFile.loadFileAsString());
  224064. tempFile.deleteFile();
  224065. return result;
  224066. }
  224067. class InterProcessLock::Pimpl
  224068. {
  224069. public:
  224070. Pimpl (const String& name, const int timeOutMillisecs)
  224071. : handle (0), refCount (1)
  224072. {
  224073. #if JUCE_MAC
  224074. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  224075. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  224076. #else
  224077. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  224078. #endif
  224079. temp.create();
  224080. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  224081. if (handle != 0)
  224082. {
  224083. struct flock fl;
  224084. zerostruct (fl);
  224085. fl.l_whence = SEEK_SET;
  224086. fl.l_type = F_WRLCK;
  224087. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  224088. for (;;)
  224089. {
  224090. const int result = fcntl (handle, F_SETLK, &fl);
  224091. if (result >= 0)
  224092. return;
  224093. if (errno != EINTR)
  224094. {
  224095. if (timeOutMillisecs == 0
  224096. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  224097. break;
  224098. Thread::sleep (10);
  224099. }
  224100. }
  224101. }
  224102. closeFile();
  224103. }
  224104. ~Pimpl()
  224105. {
  224106. closeFile();
  224107. }
  224108. void closeFile()
  224109. {
  224110. if (handle != 0)
  224111. {
  224112. struct flock fl;
  224113. zerostruct (fl);
  224114. fl.l_whence = SEEK_SET;
  224115. fl.l_type = F_UNLCK;
  224116. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  224117. {}
  224118. close (handle);
  224119. handle = 0;
  224120. }
  224121. }
  224122. int handle, refCount;
  224123. };
  224124. InterProcessLock::InterProcessLock (const String& name_)
  224125. : name (name_)
  224126. {
  224127. }
  224128. InterProcessLock::~InterProcessLock()
  224129. {
  224130. }
  224131. bool InterProcessLock::enter (const int timeOutMillisecs)
  224132. {
  224133. const ScopedLock sl (lock);
  224134. if (pimpl == 0)
  224135. {
  224136. pimpl = new Pimpl (name, timeOutMillisecs);
  224137. if (pimpl->handle == 0)
  224138. pimpl = 0;
  224139. }
  224140. else
  224141. {
  224142. pimpl->refCount++;
  224143. }
  224144. return pimpl != 0;
  224145. }
  224146. void InterProcessLock::exit()
  224147. {
  224148. const ScopedLock sl (lock);
  224149. // Trying to release the lock too many times!
  224150. jassert (pimpl != 0);
  224151. if (pimpl != 0 && --(pimpl->refCount) == 0)
  224152. pimpl = 0;
  224153. }
  224154. /*** End of inlined file: juce_posix_SharedCode.h ***/
  224155. /*** Start of inlined file: juce_mac_Files.mm ***/
  224156. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224157. // compiled on its own).
  224158. #if JUCE_INCLUDED_FILE
  224159. /*
  224160. Note that a lot of methods that you'd expect to find in this file actually
  224161. live in juce_posix_SharedCode.h!
  224162. */
  224163. bool File::copyInternal (const File& dest) const
  224164. {
  224165. const ScopedAutoReleasePool pool;
  224166. NSFileManager* fm = [NSFileManager defaultManager];
  224167. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  224168. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  224169. && [fm copyItemAtPath: juceStringToNS (fullPath)
  224170. toPath: juceStringToNS (dest.getFullPathName())
  224171. error: nil];
  224172. #else
  224173. && [fm copyPath: juceStringToNS (fullPath)
  224174. toPath: juceStringToNS (dest.getFullPathName())
  224175. handler: nil];
  224176. #endif
  224177. }
  224178. void File::findFileSystemRoots (Array<File>& destArray)
  224179. {
  224180. destArray.add (File ("/"));
  224181. }
  224182. static bool isFileOnDriveType (const File& f, const char* const* types)
  224183. {
  224184. struct statfs buf;
  224185. if (juce_doStatFS (f, buf))
  224186. {
  224187. const String type (buf.f_fstypename);
  224188. while (*types != 0)
  224189. if (type.equalsIgnoreCase (*types++))
  224190. return true;
  224191. }
  224192. return false;
  224193. }
  224194. bool File::isOnCDRomDrive() const
  224195. {
  224196. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  224197. return isFileOnDriveType (*this, cdTypes);
  224198. }
  224199. bool File::isOnHardDisk() const
  224200. {
  224201. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  224202. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  224203. }
  224204. bool File::isOnRemovableDrive() const
  224205. {
  224206. #if JUCE_IOS
  224207. return false; // xxx is this possible?
  224208. #else
  224209. const ScopedAutoReleasePool pool;
  224210. BOOL removable = false;
  224211. [[NSWorkspace sharedWorkspace]
  224212. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  224213. isRemovable: &removable
  224214. isWritable: nil
  224215. isUnmountable: nil
  224216. description: nil
  224217. type: nil];
  224218. return removable;
  224219. #endif
  224220. }
  224221. static bool juce_isHiddenFile (const String& path)
  224222. {
  224223. #if JUCE_IOS
  224224. return File (path).getFileName().startsWithChar ('.');
  224225. #else
  224226. FSRef ref;
  224227. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  224228. return false;
  224229. FSCatalogInfo info;
  224230. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  224231. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  224232. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  224233. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  224234. #endif
  224235. }
  224236. bool File::isHidden() const
  224237. {
  224238. return juce_isHiddenFile (getFullPathName());
  224239. }
  224240. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  224241. const File File::getSpecialLocation (const SpecialLocationType type)
  224242. {
  224243. const ScopedAutoReleasePool pool;
  224244. String resultPath;
  224245. switch (type)
  224246. {
  224247. case userHomeDirectory:
  224248. resultPath = nsStringToJuce (NSHomeDirectory());
  224249. break;
  224250. case userDocumentsDirectory:
  224251. resultPath = "~/Documents";
  224252. break;
  224253. case userDesktopDirectory:
  224254. resultPath = "~/Desktop";
  224255. break;
  224256. case userApplicationDataDirectory:
  224257. resultPath = "~/Library";
  224258. break;
  224259. case commonApplicationDataDirectory:
  224260. resultPath = "/Library";
  224261. break;
  224262. case globalApplicationsDirectory:
  224263. resultPath = "/Applications";
  224264. break;
  224265. case userMusicDirectory:
  224266. resultPath = "~/Music";
  224267. break;
  224268. case userMoviesDirectory:
  224269. resultPath = "~/Movies";
  224270. break;
  224271. case tempDirectory:
  224272. {
  224273. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  224274. tmp.createDirectory();
  224275. return tmp.getFullPathName();
  224276. }
  224277. case invokedExecutableFile:
  224278. if (juce_Argv0 != 0)
  224279. return File (String::fromUTF8 (juce_Argv0));
  224280. // deliberate fall-through...
  224281. case currentExecutableFile:
  224282. return juce_getExecutableFile();
  224283. case currentApplicationFile:
  224284. {
  224285. const File exe (juce_getExecutableFile());
  224286. const File parent (exe.getParentDirectory());
  224287. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  224288. ? parent.getParentDirectory().getParentDirectory()
  224289. : exe;
  224290. }
  224291. default:
  224292. jassertfalse; // unknown type?
  224293. break;
  224294. }
  224295. if (resultPath.isNotEmpty())
  224296. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  224297. return File::nonexistent;
  224298. }
  224299. const String File::getVersion() const
  224300. {
  224301. const ScopedAutoReleasePool pool;
  224302. String result;
  224303. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  224304. if (bundle != 0)
  224305. {
  224306. NSDictionary* info = [bundle infoDictionary];
  224307. if (info != 0)
  224308. {
  224309. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  224310. if (name != nil)
  224311. result = nsStringToJuce (name);
  224312. }
  224313. }
  224314. return result;
  224315. }
  224316. const File File::getLinkedTarget() const
  224317. {
  224318. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  224319. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  224320. #else
  224321. NSString* dest = [[NSFileManager defaultManager] pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  224322. #endif
  224323. if (dest != nil)
  224324. return File (nsStringToJuce (dest));
  224325. return *this;
  224326. }
  224327. bool File::moveToTrash() const
  224328. {
  224329. if (! exists())
  224330. return true;
  224331. #if JUCE_IOS
  224332. return deleteFile(); //xxx is there a trashcan on the iPhone?
  224333. #else
  224334. const ScopedAutoReleasePool pool;
  224335. NSString* p = juceStringToNS (getFullPathName());
  224336. return [[NSWorkspace sharedWorkspace]
  224337. performFileOperation: NSWorkspaceRecycleOperation
  224338. source: [p stringByDeletingLastPathComponent]
  224339. destination: @""
  224340. files: [NSArray arrayWithObject: [p lastPathComponent]]
  224341. tag: nil ];
  224342. #endif
  224343. }
  224344. class DirectoryIterator::NativeIterator::Pimpl
  224345. {
  224346. public:
  224347. Pimpl (const File& directory, const String& wildCard_)
  224348. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  224349. wildCard (wildCard_),
  224350. enumerator (0)
  224351. {
  224352. ScopedAutoReleasePool pool;
  224353. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  224354. wildcardUTF8 = wildCard.toUTF8();
  224355. }
  224356. ~Pimpl()
  224357. {
  224358. [enumerator release];
  224359. }
  224360. bool next (String& filenameFound,
  224361. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224362. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224363. {
  224364. ScopedAutoReleasePool pool;
  224365. for (;;)
  224366. {
  224367. NSString* file;
  224368. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  224369. return false;
  224370. [enumerator skipDescendents];
  224371. filenameFound = nsStringToJuce (file);
  224372. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  224373. continue;
  224374. const String path (parentDir + filenameFound);
  224375. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  224376. {
  224377. struct stat info;
  224378. const bool statOk = juce_stat (path, info);
  224379. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  224380. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  224381. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  224382. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  224383. }
  224384. if (isHidden != 0)
  224385. *isHidden = juce_isHiddenFile (path);
  224386. if (isReadOnly != 0)
  224387. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  224388. return true;
  224389. }
  224390. }
  224391. private:
  224392. String parentDir, wildCard;
  224393. const char* wildcardUTF8;
  224394. NSDirectoryEnumerator* enumerator;
  224395. Pimpl (const Pimpl&);
  224396. Pimpl& operator= (const Pimpl&);
  224397. };
  224398. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  224399. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  224400. {
  224401. }
  224402. DirectoryIterator::NativeIterator::~NativeIterator()
  224403. {
  224404. }
  224405. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  224406. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224407. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224408. {
  224409. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  224410. }
  224411. bool juce_launchExecutable (const String& pathAndArguments)
  224412. {
  224413. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  224414. const int cpid = fork();
  224415. if (cpid == 0)
  224416. {
  224417. // Child process
  224418. if (execve (argv[0], (char**) argv, 0) < 0)
  224419. exit (0);
  224420. }
  224421. else
  224422. {
  224423. if (cpid < 0)
  224424. return false;
  224425. }
  224426. return true;
  224427. }
  224428. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  224429. {
  224430. #if JUCE_IOS
  224431. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  224432. #else
  224433. const ScopedAutoReleasePool pool;
  224434. if (parameters.isEmpty())
  224435. {
  224436. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  224437. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  224438. }
  224439. bool ok = false;
  224440. FSRef ref;
  224441. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  224442. {
  224443. if (PlatformUtilities::isBundle (fileName))
  224444. {
  224445. NSMutableArray* urls = [NSMutableArray array];
  224446. StringArray docs;
  224447. docs.addTokens (parameters, true);
  224448. for (int i = 0; i < docs.size(); ++i)
  224449. [urls addObject: juceStringToNS (docs[i])];
  224450. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  224451. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  224452. options: 0
  224453. additionalEventParamDescriptor: nil
  224454. launchIdentifiers: nil];
  224455. }
  224456. else
  224457. {
  224458. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  224459. }
  224460. }
  224461. return ok;
  224462. #endif
  224463. }
  224464. void File::revealToUser() const
  224465. {
  224466. #if ! JUCE_IOS
  224467. if (exists())
  224468. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  224469. else if (getParentDirectory().exists())
  224470. getParentDirectory().revealToUser();
  224471. #endif
  224472. }
  224473. #if ! JUCE_IOS
  224474. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  224475. {
  224476. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  224477. }
  224478. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  224479. {
  224480. char path [2048];
  224481. zerostruct (path);
  224482. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  224483. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  224484. return String::empty;
  224485. }
  224486. #endif
  224487. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  224488. {
  224489. const ScopedAutoReleasePool pool;
  224490. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  224491. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  224492. #else
  224493. NSDictionary* fileDict = [[NSFileManager defaultManager] fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  224494. #endif
  224495. //return (OSType) [fileDict objectForKey: NSFileHFSTypeCode];
  224496. return [fileDict fileHFSTypeCode];
  224497. }
  224498. bool PlatformUtilities::isBundle (const String& filename)
  224499. {
  224500. #if JUCE_IOS
  224501. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  224502. #else
  224503. const ScopedAutoReleasePool pool;
  224504. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  224505. #endif
  224506. }
  224507. #endif
  224508. /*** End of inlined file: juce_mac_Files.mm ***/
  224509. #if JUCE_IOS
  224510. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  224511. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224512. // compiled on its own).
  224513. #if JUCE_INCLUDED_FILE
  224514. END_JUCE_NAMESPACE
  224515. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  224516. {
  224517. }
  224518. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  224519. - (void) applicationWillTerminate: (UIApplication*) application;
  224520. @end
  224521. @implementation JuceAppStartupDelegate
  224522. - (void) applicationDidFinishLaunching: (UIApplication*) application
  224523. {
  224524. String dummy;
  224525. if (! JUCEApplication::getInstance()->initialiseApp (dummy))
  224526. exit (0);
  224527. }
  224528. - (void) applicationWillTerminate: (UIApplication*) application
  224529. {
  224530. JUCEApplication::getInstance()->shutdownApp();
  224531. // need to do this stuff because the OS kills the process before our scope-based cleanup code gets executed..
  224532. delete JUCEApplication::getInstance();
  224533. shutdownJuce_GUI();
  224534. }
  224535. @end
  224536. BEGIN_JUCE_NAMESPACE
  224537. int juce_iOSMain (int argc, const char* argv[])
  224538. {
  224539. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  224540. }
  224541. ScopedAutoReleasePool::ScopedAutoReleasePool()
  224542. {
  224543. pool = [[NSAutoreleasePool alloc] init];
  224544. }
  224545. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  224546. {
  224547. [((NSAutoreleasePool*) pool) release];
  224548. }
  224549. void PlatformUtilities::beep()
  224550. {
  224551. //xxx
  224552. //AudioServicesPlaySystemSound ();
  224553. }
  224554. void PlatformUtilities::addItemToDock (const File& file)
  224555. {
  224556. }
  224557. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224558. END_JUCE_NAMESPACE
  224559. @interface JuceAlertBoxDelegate : NSObject
  224560. {
  224561. @public
  224562. bool clickedOk;
  224563. }
  224564. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  224565. @end
  224566. @implementation JuceAlertBoxDelegate
  224567. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  224568. {
  224569. clickedOk = (buttonIndex == 0);
  224570. alertView.hidden = true;
  224571. }
  224572. @end
  224573. BEGIN_JUCE_NAMESPACE
  224574. // (This function is used directly by other bits of code)
  224575. bool juce_iPhoneShowModalAlert (const String& title,
  224576. const String& bodyText,
  224577. NSString* okButtonText,
  224578. NSString* cancelButtonText)
  224579. {
  224580. const ScopedAutoReleasePool pool;
  224581. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  224582. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  224583. message: juceStringToNS (bodyText)
  224584. delegate: callback
  224585. cancelButtonTitle: okButtonText
  224586. otherButtonTitles: cancelButtonText, nil];
  224587. [alert retain];
  224588. [alert show];
  224589. while (! alert.hidden && alert.superview != nil)
  224590. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224591. const bool result = callback->clickedOk;
  224592. [alert release];
  224593. [callback release];
  224594. return result;
  224595. }
  224596. bool AlertWindow::showNativeDialogBox (const String& title,
  224597. const String& bodyText,
  224598. bool isOkCancel)
  224599. {
  224600. return juce_iPhoneShowModalAlert (title, bodyText,
  224601. @"OK",
  224602. isOkCancel ? @"Cancel" : nil);
  224603. }
  224604. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  224605. {
  224606. jassertfalse; // no such thing on the iphone!
  224607. return false;
  224608. }
  224609. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  224610. {
  224611. jassertfalse; // no such thing on the iphone!
  224612. return false;
  224613. }
  224614. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224615. {
  224616. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  224617. }
  224618. bool Desktop::isScreenSaverEnabled()
  224619. {
  224620. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  224621. }
  224622. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  224623. {
  224624. const ScopedAutoReleasePool pool;
  224625. monitorCoords.clear();
  224626. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  224627. : [[UIScreen mainScreen] bounds];
  224628. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  224629. (int) r.origin.y,
  224630. (int) r.size.width,
  224631. (int) r.size.height));
  224632. }
  224633. #endif
  224634. #endif
  224635. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  224636. #else
  224637. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  224638. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224639. // compiled on its own).
  224640. #if JUCE_INCLUDED_FILE
  224641. ScopedAutoReleasePool::ScopedAutoReleasePool()
  224642. {
  224643. pool = [[NSAutoreleasePool alloc] init];
  224644. }
  224645. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  224646. {
  224647. [((NSAutoreleasePool*) pool) release];
  224648. }
  224649. void PlatformUtilities::beep()
  224650. {
  224651. NSBeep();
  224652. }
  224653. void PlatformUtilities::addItemToDock (const File& file)
  224654. {
  224655. // check that it's not already there...
  224656. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  224657. .containsIgnoreCase (file.getFullPathName()))
  224658. {
  224659. 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>"
  224660. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  224661. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  224662. }
  224663. }
  224664. int PlatformUtilities::getOSXMinorVersionNumber()
  224665. {
  224666. SInt32 versionMinor = 0;
  224667. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  224668. (void) err;
  224669. jassert (err == noErr);
  224670. return (int) versionMinor;
  224671. }
  224672. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224673. bool AlertWindow::showNativeDialogBox (const String& title,
  224674. const String& bodyText,
  224675. bool isOkCancel)
  224676. {
  224677. const ScopedAutoReleasePool pool;
  224678. return NSRunAlertPanel (juceStringToNS (title),
  224679. juceStringToNS (bodyText),
  224680. @"Ok",
  224681. isOkCancel ? @"Cancel" : nil,
  224682. nil) == NSAlertDefaultReturn;
  224683. }
  224684. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  224685. {
  224686. if (files.size() == 0)
  224687. return false;
  224688. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  224689. if (draggingSource == 0)
  224690. {
  224691. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  224692. return false;
  224693. }
  224694. Component* sourceComp = draggingSource->getComponentUnderMouse();
  224695. if (sourceComp == 0)
  224696. {
  224697. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  224698. return false;
  224699. }
  224700. const ScopedAutoReleasePool pool;
  224701. NSView* view = (NSView*) sourceComp->getWindowHandle();
  224702. if (view == 0)
  224703. return false;
  224704. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  224705. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  224706. owner: nil];
  224707. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  224708. for (int i = 0; i < files.size(); ++i)
  224709. [filesArray addObject: juceStringToNS (files[i])];
  224710. [pboard setPropertyList: filesArray
  224711. forType: NSFilenamesPboardType];
  224712. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  224713. fromView: nil];
  224714. dragPosition.x -= 16;
  224715. dragPosition.y -= 16;
  224716. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  224717. at: dragPosition
  224718. offset: NSMakeSize (0, 0)
  224719. event: [[view window] currentEvent]
  224720. pasteboard: pboard
  224721. source: view
  224722. slideBack: YES];
  224723. return true;
  224724. }
  224725. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  224726. {
  224727. jassertfalse; // not implemented!
  224728. return false;
  224729. }
  224730. bool Desktop::canUseSemiTransparentWindows() throw()
  224731. {
  224732. return true;
  224733. }
  224734. const Point<int> Desktop::getMousePosition()
  224735. {
  224736. const ScopedAutoReleasePool pool;
  224737. const NSPoint p ([NSEvent mouseLocation]);
  224738. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  224739. }
  224740. void Desktop::setMousePosition (const Point<int>& newPosition)
  224741. {
  224742. // this rubbish needs to be done around the warp call, to avoid causing a
  224743. // bizarre glitch..
  224744. CGAssociateMouseAndMouseCursorPosition (false);
  224745. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  224746. CGAssociateMouseAndMouseCursorPosition (true);
  224747. }
  224748. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  224749. class ScreenSaverDefeater : public Timer,
  224750. public DeletedAtShutdown
  224751. {
  224752. public:
  224753. ScreenSaverDefeater()
  224754. {
  224755. startTimer (10000);
  224756. timerCallback();
  224757. }
  224758. ~ScreenSaverDefeater() {}
  224759. void timerCallback()
  224760. {
  224761. if (Process::isForegroundProcess())
  224762. UpdateSystemActivity (UsrActivity);
  224763. }
  224764. };
  224765. static ScreenSaverDefeater* screenSaverDefeater = 0;
  224766. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224767. {
  224768. if (isEnabled)
  224769. deleteAndZero (screenSaverDefeater);
  224770. else if (screenSaverDefeater == 0)
  224771. screenSaverDefeater = new ScreenSaverDefeater();
  224772. }
  224773. bool Desktop::isScreenSaverEnabled()
  224774. {
  224775. return screenSaverDefeater == 0;
  224776. }
  224777. #else
  224778. static IOPMAssertionID screenSaverDisablerID = 0;
  224779. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224780. {
  224781. if (isEnabled)
  224782. {
  224783. if (screenSaverDisablerID != 0)
  224784. {
  224785. IOPMAssertionRelease (screenSaverDisablerID);
  224786. screenSaverDisablerID = 0;
  224787. }
  224788. }
  224789. else
  224790. {
  224791. if (screenSaverDisablerID == 0)
  224792. {
  224793. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  224794. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  224795. CFSTR ("Juce"), &screenSaverDisablerID);
  224796. #else
  224797. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  224798. &screenSaverDisablerID);
  224799. #endif
  224800. }
  224801. }
  224802. }
  224803. bool Desktop::isScreenSaverEnabled()
  224804. {
  224805. return screenSaverDisablerID == 0;
  224806. }
  224807. #endif
  224808. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  224809. {
  224810. const ScopedAutoReleasePool pool;
  224811. monitorCoords.clear();
  224812. NSArray* screens = [NSScreen screens];
  224813. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  224814. for (unsigned int i = 0; i < [screens count]; ++i)
  224815. {
  224816. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  224817. NSRect r = clipToWorkArea ? [s visibleFrame]
  224818. : [s frame];
  224819. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  224820. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  224821. (int) r.size.width,
  224822. (int) r.size.height));
  224823. }
  224824. jassert (monitorCoords.size() > 0);
  224825. }
  224826. #endif
  224827. #endif
  224828. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  224829. #endif
  224830. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  224831. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224832. // compiled on its own).
  224833. #if JUCE_INCLUDED_FILE
  224834. void Logger::outputDebugString (const String& text)
  224835. {
  224836. std::cerr << text << std::endl;
  224837. }
  224838. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  224839. {
  224840. static char testResult = 0;
  224841. if (testResult == 0)
  224842. {
  224843. struct kinfo_proc info;
  224844. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  224845. size_t sz = sizeof (info);
  224846. sysctl (m, 4, &info, &sz, 0, 0);
  224847. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  224848. }
  224849. return testResult > 0;
  224850. }
  224851. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  224852. {
  224853. return juce_isRunningUnderDebugger();
  224854. }
  224855. #endif
  224856. /*** End of inlined file: juce_mac_Debugging.mm ***/
  224857. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224858. #if JUCE_IOS
  224859. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  224860. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224861. // compiled on its own).
  224862. #if JUCE_INCLUDED_FILE
  224863. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  224864. #define SUPPORT_10_4_FONTS 1
  224865. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  224866. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  224867. #define SUPPORT_ONLY_10_4_FONTS 1
  224868. #endif
  224869. END_JUCE_NAMESPACE
  224870. @interface NSFont (PrivateHack)
  224871. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  224872. @end
  224873. BEGIN_JUCE_NAMESPACE
  224874. #endif
  224875. class MacTypeface : public Typeface
  224876. {
  224877. public:
  224878. MacTypeface (const Font& font)
  224879. : Typeface (font.getTypefaceName())
  224880. {
  224881. const ScopedAutoReleasePool pool;
  224882. renderingTransform = CGAffineTransformIdentity;
  224883. bool needsItalicTransform = false;
  224884. #if JUCE_IOS
  224885. NSString* fontName = juceStringToNS (font.getTypefaceName());
  224886. if (font.isItalic() || font.isBold())
  224887. {
  224888. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  224889. for (NSString* i in familyFonts)
  224890. {
  224891. const String fn (nsStringToJuce (i));
  224892. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  224893. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  224894. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  224895. || afterDash.containsIgnoreCase ("italic")
  224896. || fn.endsWithIgnoreCase ("oblique")
  224897. || fn.endsWithIgnoreCase ("italic");
  224898. if (probablyBold == font.isBold()
  224899. && probablyItalic == font.isItalic())
  224900. {
  224901. fontName = i;
  224902. needsItalicTransform = false;
  224903. break;
  224904. }
  224905. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  224906. {
  224907. fontName = i;
  224908. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  224909. }
  224910. }
  224911. if (needsItalicTransform)
  224912. renderingTransform.c = 0.15f;
  224913. }
  224914. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  224915. const int ascender = abs (CGFontGetAscent (fontRef));
  224916. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  224917. ascent = ascender / totalHeight;
  224918. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224919. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  224920. #else
  224921. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  224922. if (font.isItalic())
  224923. {
  224924. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  224925. toHaveTrait: NSItalicFontMask];
  224926. if (newFont == nsFont)
  224927. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  224928. nsFont = newFont;
  224929. }
  224930. if (font.isBold())
  224931. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  224932. [nsFont retain];
  224933. ascent = std::abs ((float) [nsFont ascender]);
  224934. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  224935. ascent /= totalSize;
  224936. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  224937. if (needsItalicTransform)
  224938. {
  224939. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  224940. renderingTransform.c = 0.15f;
  224941. }
  224942. #if SUPPORT_ONLY_10_4_FONTS
  224943. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224944. if (atsFont == 0)
  224945. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224946. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  224947. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  224948. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224949. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  224950. #else
  224951. #if SUPPORT_10_4_FONTS
  224952. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224953. {
  224954. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224955. if (atsFont == 0)
  224956. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224957. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  224958. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  224959. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224960. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  224961. }
  224962. else
  224963. #endif
  224964. {
  224965. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  224966. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  224967. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224968. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  224969. }
  224970. #endif
  224971. #endif
  224972. }
  224973. ~MacTypeface()
  224974. {
  224975. #if ! JUCE_IOS
  224976. [nsFont release];
  224977. #endif
  224978. if (fontRef != 0)
  224979. CGFontRelease (fontRef);
  224980. }
  224981. float getAscent() const
  224982. {
  224983. return ascent;
  224984. }
  224985. float getDescent() const
  224986. {
  224987. return 1.0f - ascent;
  224988. }
  224989. float getStringWidth (const String& text)
  224990. {
  224991. if (fontRef == 0 || text.isEmpty())
  224992. return 0;
  224993. const int length = text.length();
  224994. HeapBlock <CGGlyph> glyphs;
  224995. createGlyphsForString (text, length, glyphs);
  224996. float x = 0;
  224997. #if SUPPORT_ONLY_10_4_FONTS
  224998. HeapBlock <NSSize> advances (length);
  224999. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225000. for (int i = 0; i < length; ++i)
  225001. x += advances[i].width;
  225002. #else
  225003. #if SUPPORT_10_4_FONTS
  225004. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225005. {
  225006. HeapBlock <NSSize> advances (length);
  225007. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  225008. for (int i = 0; i < length; ++i)
  225009. x += advances[i].width;
  225010. }
  225011. else
  225012. #endif
  225013. {
  225014. HeapBlock <int> advances (length);
  225015. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225016. for (int i = 0; i < length; ++i)
  225017. x += advances[i];
  225018. }
  225019. #endif
  225020. return x * unitsToHeightScaleFactor;
  225021. }
  225022. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  225023. {
  225024. xOffsets.add (0);
  225025. if (fontRef == 0 || text.isEmpty())
  225026. return;
  225027. const int length = text.length();
  225028. HeapBlock <CGGlyph> glyphs;
  225029. createGlyphsForString (text, length, glyphs);
  225030. #if SUPPORT_ONLY_10_4_FONTS
  225031. HeapBlock <NSSize> advances (length);
  225032. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225033. int x = 0;
  225034. for (int i = 0; i < length; ++i)
  225035. {
  225036. x += advances[i].width;
  225037. xOffsets.add (x * unitsToHeightScaleFactor);
  225038. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  225039. }
  225040. #else
  225041. #if SUPPORT_10_4_FONTS
  225042. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225043. {
  225044. HeapBlock <NSSize> advances (length);
  225045. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225046. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  225047. float x = 0;
  225048. for (int i = 0; i < length; ++i)
  225049. {
  225050. x += advances[i].width;
  225051. xOffsets.add (x * unitsToHeightScaleFactor);
  225052. resultGlyphs.add (nsGlyphs[i]);
  225053. }
  225054. }
  225055. else
  225056. #endif
  225057. {
  225058. HeapBlock <int> advances (length);
  225059. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225060. {
  225061. int x = 0;
  225062. for (int i = 0; i < length; ++i)
  225063. {
  225064. x += advances [i];
  225065. xOffsets.add (x * unitsToHeightScaleFactor);
  225066. resultGlyphs.add (glyphs[i]);
  225067. }
  225068. }
  225069. }
  225070. #endif
  225071. }
  225072. bool getOutlineForGlyph (int glyphNumber, Path& path)
  225073. {
  225074. #if JUCE_IOS
  225075. return false;
  225076. #else
  225077. if (nsFont == 0)
  225078. return false;
  225079. // we might need to apply a transform to the path, so it mustn't have anything else in it
  225080. jassert (path.isEmpty());
  225081. const ScopedAutoReleasePool pool;
  225082. NSBezierPath* bez = [NSBezierPath bezierPath];
  225083. [bez moveToPoint: NSMakePoint (0, 0)];
  225084. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  225085. inFont: nsFont];
  225086. for (int i = 0; i < [bez elementCount]; ++i)
  225087. {
  225088. NSPoint p[3];
  225089. switch ([bez elementAtIndex: i associatedPoints: p])
  225090. {
  225091. case NSMoveToBezierPathElement:
  225092. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  225093. break;
  225094. case NSLineToBezierPathElement:
  225095. path.lineTo ((float) p[0].x, (float) -p[0].y);
  225096. break;
  225097. case NSCurveToBezierPathElement:
  225098. 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);
  225099. break;
  225100. case NSClosePathBezierPathElement:
  225101. path.closeSubPath();
  225102. break;
  225103. default:
  225104. jassertfalse;
  225105. break;
  225106. }
  225107. }
  225108. path.applyTransform (pathTransform);
  225109. return true;
  225110. #endif
  225111. }
  225112. juce_UseDebuggingNewOperator
  225113. CGFontRef fontRef;
  225114. float fontHeightToCGSizeFactor;
  225115. CGAffineTransform renderingTransform;
  225116. private:
  225117. float ascent, unitsToHeightScaleFactor;
  225118. #if JUCE_IOS
  225119. #else
  225120. NSFont* nsFont;
  225121. AffineTransform pathTransform;
  225122. #endif
  225123. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  225124. {
  225125. #if SUPPORT_10_4_FONTS
  225126. #if ! SUPPORT_ONLY_10_4_FONTS
  225127. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225128. #endif
  225129. {
  225130. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  225131. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225132. for (int i = 0; i < length; ++i)
  225133. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  225134. return;
  225135. }
  225136. #endif
  225137. #if ! SUPPORT_ONLY_10_4_FONTS
  225138. if (charToGlyphMapper == 0)
  225139. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  225140. glyphs.malloc (length);
  225141. for (int i = 0; i < length; ++i)
  225142. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  225143. #endif
  225144. }
  225145. #if ! SUPPORT_ONLY_10_4_FONTS
  225146. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  225147. class CharToGlyphMapper
  225148. {
  225149. public:
  225150. CharToGlyphMapper (CGFontRef fontRef)
  225151. : segCount (0), endCode (0), startCode (0), idDelta (0),
  225152. idRangeOffset (0), glyphIndexes (0)
  225153. {
  225154. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  225155. if (cmapTable != 0)
  225156. {
  225157. const int numSubtables = getValue16 (cmapTable, 2);
  225158. for (int i = 0; i < numSubtables; ++i)
  225159. {
  225160. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  225161. {
  225162. const int offset = getValue32 (cmapTable, i * 8 + 8);
  225163. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  225164. {
  225165. const int length = getValue16 (cmapTable, offset + 2);
  225166. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  225167. segCount = segCountX2 / 2;
  225168. const int endCodeOffset = offset + 14;
  225169. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  225170. const int idDeltaOffset = startCodeOffset + segCountX2;
  225171. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  225172. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  225173. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  225174. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  225175. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  225176. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  225177. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  225178. }
  225179. break;
  225180. }
  225181. }
  225182. CFRelease (cmapTable);
  225183. }
  225184. }
  225185. ~CharToGlyphMapper()
  225186. {
  225187. if (endCode != 0)
  225188. {
  225189. CFRelease (endCode);
  225190. CFRelease (startCode);
  225191. CFRelease (idDelta);
  225192. CFRelease (idRangeOffset);
  225193. CFRelease (glyphIndexes);
  225194. }
  225195. }
  225196. int getGlyphForCharacter (const juce_wchar c) const
  225197. {
  225198. for (int i = 0; i < segCount; ++i)
  225199. {
  225200. if (getValue16 (endCode, i * 2) >= c)
  225201. {
  225202. const int start = getValue16 (startCode, i * 2);
  225203. if (start > c)
  225204. break;
  225205. const int delta = getValue16 (idDelta, i * 2);
  225206. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  225207. if (rangeOffset == 0)
  225208. return delta + c;
  225209. else
  225210. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  225211. }
  225212. }
  225213. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  225214. return jmax (-1, c - 29);
  225215. }
  225216. private:
  225217. int segCount;
  225218. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  225219. static uint16 getValue16 (CFDataRef data, const int index)
  225220. {
  225221. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  225222. }
  225223. static uint32 getValue32 (CFDataRef data, const int index)
  225224. {
  225225. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  225226. }
  225227. };
  225228. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  225229. #endif
  225230. MacTypeface (const MacTypeface&);
  225231. MacTypeface& operator= (const MacTypeface&);
  225232. };
  225233. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  225234. {
  225235. return new MacTypeface (font);
  225236. }
  225237. const StringArray Font::findAllTypefaceNames()
  225238. {
  225239. StringArray names;
  225240. const ScopedAutoReleasePool pool;
  225241. #if JUCE_IOS
  225242. NSArray* fonts = [UIFont familyNames];
  225243. #else
  225244. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  225245. #endif
  225246. for (unsigned int i = 0; i < [fonts count]; ++i)
  225247. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  225248. names.sort (true);
  225249. return names;
  225250. }
  225251. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  225252. {
  225253. #if JUCE_IOS
  225254. defaultSans = "Helvetica";
  225255. defaultSerif = "Times New Roman";
  225256. defaultFixed = "Courier New";
  225257. #else
  225258. defaultSans = "Lucida Grande";
  225259. defaultSerif = "Times New Roman";
  225260. defaultFixed = "Monaco";
  225261. #endif
  225262. }
  225263. #endif
  225264. /*** End of inlined file: juce_mac_Fonts.mm ***/
  225265. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  225266. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225267. // compiled on its own).
  225268. #if JUCE_INCLUDED_FILE
  225269. class CoreGraphicsImage : public Image::SharedImage
  225270. {
  225271. public:
  225272. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  225273. : Image::SharedImage (format_, width_, height_)
  225274. {
  225275. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  225276. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  225277. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  225278. imageData = imageDataAllocated;
  225279. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  225280. : CGColorSpaceCreateDeviceRGB();
  225281. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  225282. colourSpace, getCGImageFlags (format_));
  225283. CGColorSpaceRelease (colourSpace);
  225284. }
  225285. ~CoreGraphicsImage()
  225286. {
  225287. CGContextRelease (context);
  225288. }
  225289. Image::ImageType getType() const { return Image::NativeImage; }
  225290. LowLevelGraphicsContext* createLowLevelContext();
  225291. SharedImage* clone()
  225292. {
  225293. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  225294. memcpy (im->imageData, imageData, lineStride * height);
  225295. return im;
  225296. }
  225297. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  225298. {
  225299. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  225300. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  225301. {
  225302. return CGBitmapContextCreateImage (nativeImage->context);
  225303. }
  225304. else
  225305. {
  225306. const Image::BitmapData srcData (juceImage, false);
  225307. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  225308. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  225309. 8, srcData.pixelStride * 8, srcData.lineStride,
  225310. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  225311. 0, true, kCGRenderingIntentDefault);
  225312. CGDataProviderRelease (provider);
  225313. return imageRef;
  225314. }
  225315. }
  225316. #if JUCE_MAC
  225317. static NSImage* createNSImage (const Image& image)
  225318. {
  225319. const ScopedAutoReleasePool pool;
  225320. NSImage* im = [[NSImage alloc] init];
  225321. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  225322. [im lockFocus];
  225323. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  225324. CGImageRef imageRef = createImage (image, false, colourSpace);
  225325. CGColorSpaceRelease (colourSpace);
  225326. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  225327. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  225328. CGImageRelease (imageRef);
  225329. [im unlockFocus];
  225330. return im;
  225331. }
  225332. #endif
  225333. CGContextRef context;
  225334. HeapBlock<uint8> imageDataAllocated;
  225335. private:
  225336. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  225337. {
  225338. #if JUCE_BIG_ENDIAN
  225339. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  225340. #else
  225341. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  225342. #endif
  225343. }
  225344. };
  225345. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  225346. {
  225347. #if USE_COREGRAPHICS_RENDERING
  225348. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  225349. #else
  225350. return createSoftwareImage (format, width, height, clearImage);
  225351. #endif
  225352. }
  225353. class CoreGraphicsContext : public LowLevelGraphicsContext
  225354. {
  225355. public:
  225356. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  225357. : context (context_),
  225358. flipHeight (flipHeight_),
  225359. state (new SavedState()),
  225360. numGradientLookupEntries (0),
  225361. lastClipRectIsValid (false)
  225362. {
  225363. CGContextRetain (context);
  225364. CGContextSaveGState(context);
  225365. CGContextSetShouldSmoothFonts (context, true);
  225366. CGContextSetShouldAntialias (context, true);
  225367. CGContextSetBlendMode (context, kCGBlendModeNormal);
  225368. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  225369. greyColourSpace = CGColorSpaceCreateDeviceGray();
  225370. gradientCallbacks.version = 0;
  225371. gradientCallbacks.evaluate = gradientCallback;
  225372. gradientCallbacks.releaseInfo = 0;
  225373. setFont (Font());
  225374. }
  225375. ~CoreGraphicsContext()
  225376. {
  225377. CGContextRestoreGState (context);
  225378. CGContextRelease (context);
  225379. CGColorSpaceRelease (rgbColourSpace);
  225380. CGColorSpaceRelease (greyColourSpace);
  225381. }
  225382. bool isVectorDevice() const { return false; }
  225383. void setOrigin (int x, int y)
  225384. {
  225385. CGContextTranslateCTM (context, x, -y);
  225386. if (lastClipRectIsValid)
  225387. lastClipRect.translate (-x, -y);
  225388. }
  225389. bool clipToRectangle (const Rectangle<int>& r)
  225390. {
  225391. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  225392. if (lastClipRectIsValid)
  225393. {
  225394. lastClipRect = lastClipRect.getIntersection (r);
  225395. return ! lastClipRect.isEmpty();
  225396. }
  225397. return ! isClipEmpty();
  225398. }
  225399. bool clipToRectangleList (const RectangleList& clipRegion)
  225400. {
  225401. if (clipRegion.isEmpty())
  225402. {
  225403. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  225404. lastClipRectIsValid = true;
  225405. lastClipRect = Rectangle<int>();
  225406. return false;
  225407. }
  225408. else
  225409. {
  225410. const int numRects = clipRegion.getNumRectangles();
  225411. HeapBlock <CGRect> rects (numRects);
  225412. for (int i = 0; i < numRects; ++i)
  225413. {
  225414. const Rectangle<int>& r = clipRegion.getRectangle(i);
  225415. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  225416. }
  225417. CGContextClipToRects (context, rects, numRects);
  225418. lastClipRectIsValid = false;
  225419. return ! isClipEmpty();
  225420. }
  225421. }
  225422. void excludeClipRectangle (const Rectangle<int>& r)
  225423. {
  225424. RectangleList remaining (getClipBounds());
  225425. remaining.subtract (r);
  225426. clipToRectangleList (remaining);
  225427. lastClipRectIsValid = false;
  225428. }
  225429. void clipToPath (const Path& path, const AffineTransform& transform)
  225430. {
  225431. createPath (path, transform);
  225432. CGContextClip (context);
  225433. lastClipRectIsValid = false;
  225434. }
  225435. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  225436. {
  225437. if (! transform.isSingularity())
  225438. {
  225439. Image singleChannelImage (sourceImage);
  225440. if (sourceImage.getFormat() != Image::SingleChannel)
  225441. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  225442. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  225443. flip();
  225444. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  225445. applyTransform (t);
  225446. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  225447. CGContextClipToMask (context, r, image);
  225448. applyTransform (t.inverted());
  225449. flip();
  225450. CGImageRelease (image);
  225451. lastClipRectIsValid = false;
  225452. }
  225453. }
  225454. bool clipRegionIntersects (const Rectangle<int>& r)
  225455. {
  225456. return getClipBounds().intersects (r);
  225457. }
  225458. const Rectangle<int> getClipBounds() const
  225459. {
  225460. if (! lastClipRectIsValid)
  225461. {
  225462. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  225463. lastClipRectIsValid = true;
  225464. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  225465. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  225466. roundToInt (bounds.size.width),
  225467. roundToInt (bounds.size.height));
  225468. }
  225469. return lastClipRect;
  225470. }
  225471. bool isClipEmpty() const
  225472. {
  225473. return getClipBounds().isEmpty();
  225474. }
  225475. void saveState()
  225476. {
  225477. CGContextSaveGState (context);
  225478. stateStack.add (new SavedState (*state));
  225479. }
  225480. void restoreState()
  225481. {
  225482. CGContextRestoreGState (context);
  225483. SavedState* const top = stateStack.getLast();
  225484. if (top != 0)
  225485. {
  225486. state = top;
  225487. stateStack.removeLast (1, false);
  225488. lastClipRectIsValid = false;
  225489. }
  225490. else
  225491. {
  225492. jassertfalse; // trying to pop with an empty stack!
  225493. }
  225494. }
  225495. void setFill (const FillType& fillType)
  225496. {
  225497. state->fillType = fillType;
  225498. if (fillType.isColour())
  225499. {
  225500. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  225501. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  225502. CGContextSetAlpha (context, 1.0f);
  225503. }
  225504. }
  225505. void setOpacity (float newOpacity)
  225506. {
  225507. state->fillType.setOpacity (newOpacity);
  225508. setFill (state->fillType);
  225509. }
  225510. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  225511. {
  225512. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  225513. ? kCGInterpolationLow
  225514. : kCGInterpolationHigh);
  225515. }
  225516. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  225517. {
  225518. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  225519. if (replaceExistingContents)
  225520. {
  225521. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225522. CGContextClearRect (context, cgRect);
  225523. #else
  225524. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225525. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  225526. CGContextClearRect (context, cgRect);
  225527. else
  225528. #endif
  225529. CGContextSetBlendMode (context, kCGBlendModeCopy);
  225530. #endif
  225531. fillRect (r, false);
  225532. CGContextSetBlendMode (context, kCGBlendModeNormal);
  225533. }
  225534. else
  225535. {
  225536. if (state->fillType.isColour())
  225537. {
  225538. CGContextFillRect (context, cgRect);
  225539. }
  225540. else if (state->fillType.isGradient())
  225541. {
  225542. CGContextSaveGState (context);
  225543. CGContextClipToRect (context, cgRect);
  225544. drawGradient();
  225545. CGContextRestoreGState (context);
  225546. }
  225547. else
  225548. {
  225549. CGContextSaveGState (context);
  225550. CGContextClipToRect (context, cgRect);
  225551. drawImage (state->fillType.image, state->fillType.transform, true);
  225552. CGContextRestoreGState (context);
  225553. }
  225554. }
  225555. }
  225556. void fillPath (const Path& path, const AffineTransform& transform)
  225557. {
  225558. CGContextSaveGState (context);
  225559. if (state->fillType.isColour())
  225560. {
  225561. flip();
  225562. applyTransform (transform);
  225563. createPath (path);
  225564. if (path.isUsingNonZeroWinding())
  225565. CGContextFillPath (context);
  225566. else
  225567. CGContextEOFillPath (context);
  225568. }
  225569. else
  225570. {
  225571. createPath (path, transform);
  225572. if (path.isUsingNonZeroWinding())
  225573. CGContextClip (context);
  225574. else
  225575. CGContextEOClip (context);
  225576. if (state->fillType.isGradient())
  225577. drawGradient();
  225578. else
  225579. drawImage (state->fillType.image, state->fillType.transform, true);
  225580. }
  225581. CGContextRestoreGState (context);
  225582. }
  225583. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  225584. {
  225585. const int iw = sourceImage.getWidth();
  225586. const int ih = sourceImage.getHeight();
  225587. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  225588. CGContextSaveGState (context);
  225589. CGContextSetAlpha (context, state->fillType.getOpacity());
  225590. flip();
  225591. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  225592. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  225593. if (fillEntireClipAsTiles)
  225594. {
  225595. #if JUCE_IOS
  225596. CGContextDrawTiledImage (context, imageRect, image);
  225597. #else
  225598. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  225599. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  225600. // if it's doing a transformation - it's quicker to just draw lots of images manually
  225601. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  225602. CGContextDrawTiledImage (context, imageRect, image);
  225603. else
  225604. #endif
  225605. {
  225606. // Fallback to manually doing a tiled fill on 10.4
  225607. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  225608. int x = 0, y = 0;
  225609. while (x > clip.origin.x) x -= iw;
  225610. while (y > clip.origin.y) y -= ih;
  225611. const int right = (int) (clip.origin.x + clip.size.width);
  225612. const int bottom = (int) (clip.origin.y + clip.size.height);
  225613. while (y < bottom)
  225614. {
  225615. for (int x2 = x; x2 < right; x2 += iw)
  225616. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  225617. y += ih;
  225618. }
  225619. }
  225620. #endif
  225621. }
  225622. else
  225623. {
  225624. CGContextDrawImage (context, imageRect, image);
  225625. }
  225626. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  225627. CGContextRestoreGState (context);
  225628. }
  225629. void drawLine (const Line<float>& line)
  225630. {
  225631. CGContextSetLineCap (context, kCGLineCapSquare);
  225632. CGContextSetLineWidth (context, 1.0f);
  225633. CGContextSetRGBStrokeColor (context,
  225634. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  225635. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  225636. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  225637. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  225638. CGContextStrokeLineSegments (context, cgLine, 1);
  225639. }
  225640. void drawVerticalLine (const int x, float top, float bottom)
  225641. {
  225642. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  225643. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  225644. #else
  225645. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  225646. // the x co-ord slightly to trick it..
  225647. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  225648. #endif
  225649. }
  225650. void drawHorizontalLine (const int y, float left, float right)
  225651. {
  225652. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  225653. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  225654. #else
  225655. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  225656. // the x co-ord slightly to trick it..
  225657. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  225658. #endif
  225659. }
  225660. void setFont (const Font& newFont)
  225661. {
  225662. if (state->font != newFont)
  225663. {
  225664. state->fontRef = 0;
  225665. state->font = newFont;
  225666. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  225667. if (mf != 0)
  225668. {
  225669. state->fontRef = mf->fontRef;
  225670. CGContextSetFont (context, state->fontRef);
  225671. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  225672. state->fontTransform = mf->renderingTransform;
  225673. state->fontTransform.a *= state->font.getHorizontalScale();
  225674. CGContextSetTextMatrix (context, state->fontTransform);
  225675. }
  225676. }
  225677. }
  225678. const Font getFont()
  225679. {
  225680. return state->font;
  225681. }
  225682. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  225683. {
  225684. if (state->fontRef != 0 && state->fillType.isColour())
  225685. {
  225686. if (transform.isOnlyTranslation())
  225687. {
  225688. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  225689. CGGlyph g = glyphNumber;
  225690. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  225691. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  225692. }
  225693. else
  225694. {
  225695. CGContextSaveGState (context);
  225696. flip();
  225697. applyTransform (transform);
  225698. CGAffineTransform t = state->fontTransform;
  225699. t.d = -t.d;
  225700. CGContextSetTextMatrix (context, t);
  225701. CGGlyph g = glyphNumber;
  225702. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  225703. CGContextRestoreGState (context);
  225704. }
  225705. }
  225706. else
  225707. {
  225708. Path p;
  225709. Font& f = state->font;
  225710. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  225711. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  225712. .followedBy (transform));
  225713. }
  225714. }
  225715. private:
  225716. CGContextRef context;
  225717. const CGFloat flipHeight;
  225718. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  225719. CGFunctionCallbacks gradientCallbacks;
  225720. mutable Rectangle<int> lastClipRect;
  225721. mutable bool lastClipRectIsValid;
  225722. struct SavedState
  225723. {
  225724. SavedState()
  225725. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  225726. {
  225727. }
  225728. SavedState (const SavedState& other)
  225729. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  225730. fontTransform (other.fontTransform)
  225731. {
  225732. }
  225733. ~SavedState()
  225734. {
  225735. }
  225736. FillType fillType;
  225737. Font font;
  225738. CGFontRef fontRef;
  225739. CGAffineTransform fontTransform;
  225740. };
  225741. ScopedPointer <SavedState> state;
  225742. OwnedArray <SavedState> stateStack;
  225743. HeapBlock <PixelARGB> gradientLookupTable;
  225744. int numGradientLookupEntries;
  225745. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  225746. {
  225747. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  225748. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  225749. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  225750. colour.unpremultiply();
  225751. outData[0] = colour.getRed() / 255.0f;
  225752. outData[1] = colour.getGreen() / 255.0f;
  225753. outData[2] = colour.getBlue() / 255.0f;
  225754. outData[3] = colour.getAlpha() / 255.0f;
  225755. }
  225756. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  225757. {
  225758. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  225759. --numGradientLookupEntries;
  225760. CGShadingRef result = 0;
  225761. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  225762. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  225763. if (gradient.isRadial)
  225764. {
  225765. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  225766. p1, gradient.point1.getDistanceFrom (gradient.point2),
  225767. function, true, true);
  225768. }
  225769. else
  225770. {
  225771. result = CGShadingCreateAxial (rgbColourSpace, p1,
  225772. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  225773. function, true, true);
  225774. }
  225775. CGFunctionRelease (function);
  225776. return result;
  225777. }
  225778. void drawGradient()
  225779. {
  225780. flip();
  225781. applyTransform (state->fillType.transform);
  225782. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  225783. // you draw a gradient with high quality interp enabled).
  225784. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  225785. CGContextSetAlpha (context, state->fillType.getOpacity());
  225786. CGContextDrawShading (context, shading);
  225787. CGShadingRelease (shading);
  225788. }
  225789. void createPath (const Path& path) const
  225790. {
  225791. CGContextBeginPath (context);
  225792. Path::Iterator i (path);
  225793. while (i.next())
  225794. {
  225795. switch (i.elementType)
  225796. {
  225797. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  225798. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  225799. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  225800. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  225801. case Path::Iterator::closePath: CGContextClosePath (context); break;
  225802. default: jassertfalse; break;
  225803. }
  225804. }
  225805. }
  225806. void createPath (const Path& path, const AffineTransform& transform) const
  225807. {
  225808. CGContextBeginPath (context);
  225809. Path::Iterator i (path);
  225810. while (i.next())
  225811. {
  225812. switch (i.elementType)
  225813. {
  225814. case Path::Iterator::startNewSubPath:
  225815. transform.transformPoint (i.x1, i.y1);
  225816. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  225817. break;
  225818. case Path::Iterator::lineTo:
  225819. transform.transformPoint (i.x1, i.y1);
  225820. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  225821. break;
  225822. case Path::Iterator::quadraticTo:
  225823. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  225824. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  225825. break;
  225826. case Path::Iterator::cubicTo:
  225827. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  225828. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  225829. break;
  225830. case Path::Iterator::closePath:
  225831. CGContextClosePath (context); break;
  225832. default:
  225833. jassertfalse;
  225834. break;
  225835. }
  225836. }
  225837. }
  225838. void flip() const
  225839. {
  225840. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  225841. }
  225842. void applyTransform (const AffineTransform& transform) const
  225843. {
  225844. CGAffineTransform t;
  225845. t.a = transform.mat00;
  225846. t.b = transform.mat10;
  225847. t.c = transform.mat01;
  225848. t.d = transform.mat11;
  225849. t.tx = transform.mat02;
  225850. t.ty = transform.mat12;
  225851. CGContextConcatCTM (context, t);
  225852. }
  225853. CoreGraphicsContext (const CoreGraphicsContext&);
  225854. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  225855. };
  225856. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  225857. {
  225858. return new CoreGraphicsContext (context, height);
  225859. }
  225860. #endif
  225861. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  225862. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  225863. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225864. // compiled on its own).
  225865. #if JUCE_INCLUDED_FILE
  225866. class UIViewComponentPeer;
  225867. END_JUCE_NAMESPACE
  225868. #define JuceUIView MakeObjCClassName(JuceUIView)
  225869. @interface JuceUIView : UIView <UITextFieldDelegate>
  225870. {
  225871. @public
  225872. UIViewComponentPeer* owner;
  225873. UITextField *hiddenTextField;
  225874. }
  225875. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  225876. - (void) dealloc;
  225877. - (void) drawRect: (CGRect) r;
  225878. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  225879. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  225880. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  225881. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  225882. - (BOOL) becomeFirstResponder;
  225883. - (BOOL) resignFirstResponder;
  225884. - (BOOL) canBecomeFirstResponder;
  225885. - (void) asyncRepaint: (id) rect;
  225886. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) string;
  225887. - (BOOL) textFieldShouldClear: (UITextField*) textField;
  225888. - (BOOL) textFieldShouldReturn: (UITextField*) textField;
  225889. @end
  225890. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  225891. @interface JuceUIWindow : UIWindow
  225892. {
  225893. @private
  225894. UIViewComponentPeer* owner;
  225895. bool isZooming;
  225896. }
  225897. - (void) setOwner: (UIViewComponentPeer*) owner;
  225898. - (void) becomeKeyWindow;
  225899. @end
  225900. BEGIN_JUCE_NAMESPACE
  225901. class UIViewComponentPeer : public ComponentPeer,
  225902. public FocusChangeListener
  225903. {
  225904. public:
  225905. UIViewComponentPeer (Component* const component,
  225906. const int windowStyleFlags,
  225907. UIView* viewToAttachTo);
  225908. ~UIViewComponentPeer();
  225909. void* getNativeHandle() const;
  225910. void setVisible (bool shouldBeVisible);
  225911. void setTitle (const String& title);
  225912. void setPosition (int x, int y);
  225913. void setSize (int w, int h);
  225914. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  225915. const Rectangle<int> getBounds() const;
  225916. const Rectangle<int> getBounds (const bool global) const;
  225917. const Point<int> getScreenPosition() const;
  225918. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  225919. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  225920. void setMinimised (bool shouldBeMinimised);
  225921. bool isMinimised() const;
  225922. void setFullScreen (bool shouldBeFullScreen);
  225923. bool isFullScreen() const;
  225924. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  225925. const BorderSize getFrameSize() const;
  225926. bool setAlwaysOnTop (bool alwaysOnTop);
  225927. void toFront (bool makeActiveWindow);
  225928. void toBehind (ComponentPeer* other);
  225929. void setIcon (const Image& newIcon);
  225930. virtual void drawRect (CGRect r);
  225931. virtual bool canBecomeKeyWindow();
  225932. virtual bool windowShouldClose();
  225933. virtual void redirectMovedOrResized();
  225934. virtual CGRect constrainRect (CGRect r);
  225935. virtual void viewFocusGain();
  225936. virtual void viewFocusLoss();
  225937. bool isFocused() const;
  225938. void grabFocus();
  225939. void textInputRequired (const Point<int>& position);
  225940. virtual BOOL textFieldReplaceCharacters (const Range<int>& range, const String& text);
  225941. virtual BOOL textFieldShouldClear();
  225942. virtual BOOL textFieldShouldReturn();
  225943. void updateHiddenTextContent (TextInputTarget* target);
  225944. void globalFocusChanged (Component*);
  225945. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  225946. void repaint (const Rectangle<int>& area);
  225947. void performAnyPendingRepaintsNow();
  225948. juce_UseDebuggingNewOperator
  225949. UIWindow* window;
  225950. JuceUIView* view;
  225951. bool isSharedWindow, fullScreen, insideDrawRect;
  225952. static ModifierKeys currentModifiers;
  225953. static int64 getMouseTime (UIEvent* e)
  225954. {
  225955. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  225956. + (int64) ([e timestamp] * 1000.0);
  225957. }
  225958. Array <UITouch*> currentTouches;
  225959. };
  225960. END_JUCE_NAMESPACE
  225961. @implementation JuceUIView
  225962. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  225963. withFrame: (CGRect) frame
  225964. {
  225965. [super initWithFrame: frame];
  225966. owner = owner_;
  225967. hiddenTextField = [[UITextField alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  225968. [self addSubview: hiddenTextField];
  225969. hiddenTextField.delegate = self;
  225970. return self;
  225971. }
  225972. - (void) dealloc
  225973. {
  225974. [hiddenTextField removeFromSuperview];
  225975. [hiddenTextField release];
  225976. [super dealloc];
  225977. }
  225978. - (void) drawRect: (CGRect) r
  225979. {
  225980. if (owner != 0)
  225981. owner->drawRect (r);
  225982. }
  225983. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  225984. {
  225985. return false;
  225986. }
  225987. ModifierKeys UIViewComponentPeer::currentModifiers;
  225988. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  225989. {
  225990. return UIViewComponentPeer::currentModifiers;
  225991. }
  225992. void ModifierKeys::updateCurrentModifiers() throw()
  225993. {
  225994. currentModifiers = UIViewComponentPeer::currentModifiers;
  225995. }
  225996. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  225997. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  225998. {
  225999. if (owner != 0)
  226000. owner->handleTouches (event, true, false, false);
  226001. }
  226002. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  226003. {
  226004. if (owner != 0)
  226005. owner->handleTouches (event, false, false, false);
  226006. }
  226007. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  226008. {
  226009. if (owner != 0)
  226010. owner->handleTouches (event, false, true, false);
  226011. }
  226012. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  226013. {
  226014. if (owner != 0)
  226015. owner->handleTouches (event, false, true, true);
  226016. [self touchesEnded: touches withEvent: event];
  226017. }
  226018. - (BOOL) becomeFirstResponder
  226019. {
  226020. if (owner != 0)
  226021. owner->viewFocusGain();
  226022. return true;
  226023. }
  226024. - (BOOL) resignFirstResponder
  226025. {
  226026. if (owner != 0)
  226027. owner->viewFocusLoss();
  226028. return true;
  226029. }
  226030. - (BOOL) canBecomeFirstResponder
  226031. {
  226032. return owner != 0 && owner->canBecomeKeyWindow();
  226033. }
  226034. - (void) asyncRepaint: (id) rect
  226035. {
  226036. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  226037. [self setNeedsDisplayInRect: *r];
  226038. }
  226039. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) text
  226040. {
  226041. return owner->textFieldReplaceCharacters (Range<int> (range.location, range.location + range.length),
  226042. nsStringToJuce (text));
  226043. }
  226044. - (BOOL) textFieldShouldClear: (UITextField*) textField
  226045. {
  226046. return owner->textFieldShouldClear();
  226047. }
  226048. - (BOOL) textFieldShouldReturn: (UITextField*) textField
  226049. {
  226050. return owner->textFieldShouldReturn();
  226051. }
  226052. @end
  226053. @implementation JuceUIWindow
  226054. - (void) setOwner: (UIViewComponentPeer*) owner_
  226055. {
  226056. owner = owner_;
  226057. isZooming = false;
  226058. }
  226059. - (void) becomeKeyWindow
  226060. {
  226061. [super becomeKeyWindow];
  226062. if (owner != 0)
  226063. owner->grabFocus();
  226064. }
  226065. @end
  226066. BEGIN_JUCE_NAMESPACE
  226067. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  226068. const int windowStyleFlags,
  226069. UIView* viewToAttachTo)
  226070. : ComponentPeer (component, windowStyleFlags),
  226071. window (0),
  226072. view (0),
  226073. isSharedWindow (viewToAttachTo != 0),
  226074. fullScreen (false),
  226075. insideDrawRect (false)
  226076. {
  226077. CGRect r = CGRectMake (0, 0, (float) component->getWidth(), (float) component->getHeight());
  226078. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  226079. if (isSharedWindow)
  226080. {
  226081. window = [viewToAttachTo window];
  226082. [viewToAttachTo addSubview: view];
  226083. setVisible (component->isVisible());
  226084. }
  226085. else
  226086. {
  226087. r.origin.x = (float) component->getX();
  226088. r.origin.y = (float) component->getY();
  226089. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  226090. window = [[JuceUIWindow alloc] init];
  226091. window.frame = r;
  226092. window.opaque = component->isOpaque();
  226093. view.opaque = component->isOpaque();
  226094. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  226095. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  226096. [((JuceUIWindow*) window) setOwner: this];
  226097. if (component->isAlwaysOnTop())
  226098. window.windowLevel = UIWindowLevelAlert;
  226099. [window addSubview: view];
  226100. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  226101. view.hidden = ! component->isVisible();
  226102. window.hidden = ! component->isVisible();
  226103. view.multipleTouchEnabled = YES;
  226104. }
  226105. setTitle (component->getName());
  226106. Desktop::getInstance().addFocusChangeListener (this);
  226107. }
  226108. UIViewComponentPeer::~UIViewComponentPeer()
  226109. {
  226110. Desktop::getInstance().removeFocusChangeListener (this);
  226111. view->owner = 0;
  226112. [view removeFromSuperview];
  226113. [view release];
  226114. if (! isSharedWindow)
  226115. {
  226116. [((JuceUIWindow*) window) setOwner: 0];
  226117. [window release];
  226118. }
  226119. }
  226120. void* UIViewComponentPeer::getNativeHandle() const
  226121. {
  226122. return view;
  226123. }
  226124. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  226125. {
  226126. view.hidden = ! shouldBeVisible;
  226127. if (! isSharedWindow)
  226128. window.hidden = ! shouldBeVisible;
  226129. }
  226130. void UIViewComponentPeer::setTitle (const String& title)
  226131. {
  226132. // xxx is this possible?
  226133. }
  226134. void UIViewComponentPeer::setPosition (int x, int y)
  226135. {
  226136. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  226137. }
  226138. void UIViewComponentPeer::setSize (int w, int h)
  226139. {
  226140. setBounds (component->getX(), component->getY(), w, h, false);
  226141. }
  226142. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  226143. {
  226144. fullScreen = isNowFullScreen;
  226145. w = jmax (0, w);
  226146. h = jmax (0, h);
  226147. CGRect r;
  226148. r.origin.x = (float) x;
  226149. r.origin.y = (float) y;
  226150. r.size.width = (float) w;
  226151. r.size.height = (float) h;
  226152. if (isSharedWindow)
  226153. {
  226154. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  226155. if ([view frame].size.width != r.size.width
  226156. || [view frame].size.height != r.size.height)
  226157. [view setNeedsDisplay];
  226158. view.frame = r;
  226159. }
  226160. else
  226161. {
  226162. window.frame = r;
  226163. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  226164. }
  226165. }
  226166. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  226167. {
  226168. CGRect r = [view frame];
  226169. if (global && [view window] != 0)
  226170. {
  226171. r = [view convertRect: r toView: nil];
  226172. CGRect wr = [[view window] frame];
  226173. r.origin.x += wr.origin.x;
  226174. r.origin.y += wr.origin.y;
  226175. }
  226176. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y,
  226177. (int) r.size.width, (int) r.size.height);
  226178. }
  226179. const Rectangle<int> UIViewComponentPeer::getBounds() const
  226180. {
  226181. return getBounds (! isSharedWindow);
  226182. }
  226183. const Point<int> UIViewComponentPeer::getScreenPosition() const
  226184. {
  226185. return getBounds (true).getPosition();
  226186. }
  226187. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  226188. {
  226189. return relativePosition + getScreenPosition();
  226190. }
  226191. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  226192. {
  226193. return screenPosition - getScreenPosition();
  226194. }
  226195. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  226196. {
  226197. if (constrainer != 0)
  226198. {
  226199. CGRect current = [window frame];
  226200. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  226201. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  226202. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  226203. (int) r.size.width, (int) r.size.height);
  226204. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  226205. (int) current.size.width, (int) current.size.height);
  226206. constrainer->checkBounds (pos, original,
  226207. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  226208. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  226209. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  226210. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  226211. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  226212. r.origin.x = pos.getX();
  226213. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  226214. r.size.width = pos.getWidth();
  226215. r.size.height = pos.getHeight();
  226216. }
  226217. return r;
  226218. }
  226219. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  226220. {
  226221. // xxx
  226222. }
  226223. bool UIViewComponentPeer::isMinimised() const
  226224. {
  226225. return false;
  226226. }
  226227. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  226228. {
  226229. if (! isSharedWindow)
  226230. {
  226231. Rectangle<int> r (lastNonFullscreenBounds);
  226232. setMinimised (false);
  226233. if (fullScreen != shouldBeFullScreen)
  226234. {
  226235. if (shouldBeFullScreen)
  226236. r = Desktop::getInstance().getMainMonitorArea();
  226237. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  226238. if (r != getComponent()->getBounds() && ! r.isEmpty())
  226239. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  226240. }
  226241. }
  226242. }
  226243. bool UIViewComponentPeer::isFullScreen() const
  226244. {
  226245. return fullScreen;
  226246. }
  226247. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  226248. {
  226249. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  226250. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  226251. return false;
  226252. CGPoint p;
  226253. p.x = (float) position.getX();
  226254. p.y = (float) position.getY();
  226255. UIView* v = [view hitTest: p withEvent: nil];
  226256. if (trueIfInAChildWindow)
  226257. return v != nil;
  226258. return v == view;
  226259. }
  226260. const BorderSize UIViewComponentPeer::getFrameSize() const
  226261. {
  226262. BorderSize b;
  226263. if (! isSharedWindow)
  226264. {
  226265. CGRect v = [view convertRect: [view frame] toView: nil];
  226266. CGRect w = [window frame];
  226267. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  226268. b.setBottom ((int) v.origin.y);
  226269. b.setLeft ((int) v.origin.x);
  226270. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  226271. }
  226272. return b;
  226273. }
  226274. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  226275. {
  226276. if (! isSharedWindow)
  226277. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  226278. return true;
  226279. }
  226280. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  226281. {
  226282. if (isSharedWindow)
  226283. [[view superview] bringSubviewToFront: view];
  226284. if (window != 0 && component->isVisible())
  226285. [window makeKeyAndVisible];
  226286. }
  226287. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  226288. {
  226289. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  226290. jassert (otherPeer != 0); // wrong type of window?
  226291. if (otherPeer != 0)
  226292. {
  226293. if (isSharedWindow)
  226294. {
  226295. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  226296. }
  226297. else
  226298. {
  226299. jassertfalse; // don't know how to do this
  226300. }
  226301. }
  226302. }
  226303. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  226304. {
  226305. // to do..
  226306. }
  226307. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  226308. {
  226309. NSArray* touches = [[event touchesForView: view] allObjects];
  226310. for (unsigned int i = 0; i < [touches count]; ++i)
  226311. {
  226312. UITouch* touch = [touches objectAtIndex: i];
  226313. CGPoint p = [touch locationInView: view];
  226314. const Point<int> pos ((int) p.x, (int) p.y);
  226315. juce_lastMousePos = pos + getScreenPosition();
  226316. const int64 time = getMouseTime (event);
  226317. int touchIndex = currentTouches.indexOf (touch);
  226318. if (touchIndex < 0)
  226319. {
  226320. touchIndex = currentTouches.size();
  226321. currentTouches.add (touch);
  226322. }
  226323. if (isDown)
  226324. {
  226325. currentModifiers = currentModifiers.withoutMouseButtons();
  226326. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  226327. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  226328. }
  226329. else if (isUp)
  226330. {
  226331. currentModifiers = currentModifiers.withoutMouseButtons();
  226332. currentTouches.remove (touchIndex);
  226333. }
  226334. if (isCancel)
  226335. currentTouches.clear();
  226336. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  226337. }
  226338. }
  226339. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  226340. void UIViewComponentPeer::viewFocusGain()
  226341. {
  226342. if (currentlyFocusedPeer != this)
  226343. {
  226344. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  226345. currentlyFocusedPeer->handleFocusLoss();
  226346. currentlyFocusedPeer = this;
  226347. handleFocusGain();
  226348. }
  226349. }
  226350. void UIViewComponentPeer::viewFocusLoss()
  226351. {
  226352. if (currentlyFocusedPeer == this)
  226353. {
  226354. currentlyFocusedPeer = 0;
  226355. handleFocusLoss();
  226356. }
  226357. }
  226358. void juce_HandleProcessFocusChange()
  226359. {
  226360. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  226361. {
  226362. if (Process::isForegroundProcess())
  226363. {
  226364. currentlyFocusedPeer->handleFocusGain();
  226365. ComponentPeer::bringModalComponentToFront();
  226366. }
  226367. else
  226368. {
  226369. currentlyFocusedPeer->handleFocusLoss();
  226370. // turn kiosk mode off if we lose focus..
  226371. Desktop::getInstance().setKioskModeComponent (0);
  226372. }
  226373. }
  226374. }
  226375. bool UIViewComponentPeer::isFocused() const
  226376. {
  226377. return isSharedWindow ? this == currentlyFocusedPeer
  226378. : (window != 0 && [window isKeyWindow]);
  226379. }
  226380. void UIViewComponentPeer::grabFocus()
  226381. {
  226382. if (window != 0)
  226383. {
  226384. [window makeKeyWindow];
  226385. viewFocusGain();
  226386. }
  226387. }
  226388. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  226389. {
  226390. }
  226391. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  226392. {
  226393. view->hiddenTextField.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  226394. }
  226395. BOOL UIViewComponentPeer::textFieldReplaceCharacters (const Range<int>& range, const String& text)
  226396. {
  226397. TextInputTarget* const target = findCurrentTextInputTarget();
  226398. if (target != 0)
  226399. {
  226400. const Range<int> currentSelection (target->getHighlightedRegion());
  226401. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  226402. if (currentSelection.isEmpty())
  226403. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  226404. target->insertTextAtCaret (text);
  226405. updateHiddenTextContent (target);
  226406. }
  226407. return NO;
  226408. }
  226409. BOOL UIViewComponentPeer::textFieldShouldClear()
  226410. {
  226411. TextInputTarget* const target = findCurrentTextInputTarget();
  226412. if (target != 0)
  226413. {
  226414. target->setHighlightedRegion (Range<int> (0, std::numeric_limits<int>::max()));
  226415. target->insertTextAtCaret (String::empty);
  226416. updateHiddenTextContent (target);
  226417. }
  226418. return YES;
  226419. }
  226420. BOOL UIViewComponentPeer::textFieldShouldReturn()
  226421. {
  226422. TextInputTarget* const target = findCurrentTextInputTarget();
  226423. if (target != 0)
  226424. {
  226425. target->insertTextAtCaret ("\n");
  226426. updateHiddenTextContent (target);
  226427. }
  226428. return YES;
  226429. }
  226430. void UIViewComponentPeer::globalFocusChanged (Component*)
  226431. {
  226432. TextInputTarget* const target = findCurrentTextInputTarget();
  226433. if (target != 0)
  226434. {
  226435. Component* comp = dynamic_cast<Component*> (target);
  226436. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  226437. view->hiddenTextField.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  226438. updateHiddenTextContent (target);
  226439. [view->hiddenTextField becomeFirstResponder];
  226440. }
  226441. else
  226442. {
  226443. [view->hiddenTextField resignFirstResponder];
  226444. }
  226445. }
  226446. void UIViewComponentPeer::drawRect (CGRect r)
  226447. {
  226448. if (r.size.width < 1.0f || r.size.height < 1.0f)
  226449. return;
  226450. CGContextRef cg = UIGraphicsGetCurrentContext();
  226451. if (! component->isOpaque())
  226452. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  226453. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  226454. CoreGraphicsContext g (cg, view.bounds.size.height);
  226455. insideDrawRect = true;
  226456. handlePaint (g);
  226457. insideDrawRect = false;
  226458. }
  226459. bool UIViewComponentPeer::canBecomeKeyWindow()
  226460. {
  226461. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  226462. }
  226463. bool UIViewComponentPeer::windowShouldClose()
  226464. {
  226465. if (! isValidPeer (this))
  226466. return YES;
  226467. handleUserClosingWindow();
  226468. return NO;
  226469. }
  226470. void UIViewComponentPeer::redirectMovedOrResized()
  226471. {
  226472. handleMovedOrResized();
  226473. }
  226474. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  226475. {
  226476. }
  226477. class AsyncRepaintMessage : public CallbackMessage
  226478. {
  226479. public:
  226480. UIViewComponentPeer* const peer;
  226481. const Rectangle<int> rect;
  226482. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  226483. : peer (peer_), rect (rect_)
  226484. {
  226485. }
  226486. void messageCallback()
  226487. {
  226488. if (ComponentPeer::isValidPeer (peer))
  226489. peer->repaint (rect);
  226490. }
  226491. };
  226492. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  226493. {
  226494. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  226495. {
  226496. (new AsyncRepaintMessage (this, area))->post();
  226497. }
  226498. else
  226499. {
  226500. [view setNeedsDisplayInRect: CGRectMake ((float) area.getX(), (float) area.getY(),
  226501. (float) area.getWidth(), (float) area.getHeight())];
  226502. }
  226503. }
  226504. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  226505. {
  226506. }
  226507. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  226508. {
  226509. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  226510. }
  226511. const Image juce_createIconForFile (const File& file)
  226512. {
  226513. return Image::null;
  226514. }
  226515. void Desktop::createMouseInputSources()
  226516. {
  226517. for (int i = 0; i < 10; ++i)
  226518. mouseSources.add (new MouseInputSource (i, false));
  226519. }
  226520. bool Desktop::canUseSemiTransparentWindows() throw()
  226521. {
  226522. return true;
  226523. }
  226524. const Point<int> Desktop::getMousePosition()
  226525. {
  226526. return juce_lastMousePos;
  226527. }
  226528. void Desktop::setMousePosition (const Point<int>&)
  226529. {
  226530. }
  226531. const int KeyPress::spaceKey = ' ';
  226532. const int KeyPress::returnKey = 0x0d;
  226533. const int KeyPress::escapeKey = 0x1b;
  226534. const int KeyPress::backspaceKey = 0x7f;
  226535. const int KeyPress::leftKey = 0x1000;
  226536. const int KeyPress::rightKey = 0x1001;
  226537. const int KeyPress::upKey = 0x1002;
  226538. const int KeyPress::downKey = 0x1003;
  226539. const int KeyPress::pageUpKey = 0x1004;
  226540. const int KeyPress::pageDownKey = 0x1005;
  226541. const int KeyPress::endKey = 0x1006;
  226542. const int KeyPress::homeKey = 0x1007;
  226543. const int KeyPress::deleteKey = 0x1008;
  226544. const int KeyPress::insertKey = -1;
  226545. const int KeyPress::tabKey = 9;
  226546. const int KeyPress::F1Key = 0x2001;
  226547. const int KeyPress::F2Key = 0x2002;
  226548. const int KeyPress::F3Key = 0x2003;
  226549. const int KeyPress::F4Key = 0x2004;
  226550. const int KeyPress::F5Key = 0x2005;
  226551. const int KeyPress::F6Key = 0x2006;
  226552. const int KeyPress::F7Key = 0x2007;
  226553. const int KeyPress::F8Key = 0x2008;
  226554. const int KeyPress::F9Key = 0x2009;
  226555. const int KeyPress::F10Key = 0x200a;
  226556. const int KeyPress::F11Key = 0x200b;
  226557. const int KeyPress::F12Key = 0x200c;
  226558. const int KeyPress::F13Key = 0x200d;
  226559. const int KeyPress::F14Key = 0x200e;
  226560. const int KeyPress::F15Key = 0x200f;
  226561. const int KeyPress::F16Key = 0x2010;
  226562. const int KeyPress::numberPad0 = 0x30020;
  226563. const int KeyPress::numberPad1 = 0x30021;
  226564. const int KeyPress::numberPad2 = 0x30022;
  226565. const int KeyPress::numberPad3 = 0x30023;
  226566. const int KeyPress::numberPad4 = 0x30024;
  226567. const int KeyPress::numberPad5 = 0x30025;
  226568. const int KeyPress::numberPad6 = 0x30026;
  226569. const int KeyPress::numberPad7 = 0x30027;
  226570. const int KeyPress::numberPad8 = 0x30028;
  226571. const int KeyPress::numberPad9 = 0x30029;
  226572. const int KeyPress::numberPadAdd = 0x3002a;
  226573. const int KeyPress::numberPadSubtract = 0x3002b;
  226574. const int KeyPress::numberPadMultiply = 0x3002c;
  226575. const int KeyPress::numberPadDivide = 0x3002d;
  226576. const int KeyPress::numberPadSeparator = 0x3002e;
  226577. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  226578. const int KeyPress::numberPadEquals = 0x30030;
  226579. const int KeyPress::numberPadDelete = 0x30031;
  226580. const int KeyPress::playKey = 0x30000;
  226581. const int KeyPress::stopKey = 0x30001;
  226582. const int KeyPress::fastForwardKey = 0x30002;
  226583. const int KeyPress::rewindKey = 0x30003;
  226584. #endif
  226585. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  226586. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  226587. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226588. // compiled on its own).
  226589. #if JUCE_INCLUDED_FILE
  226590. struct CallbackMessagePayload
  226591. {
  226592. MessageCallbackFunction* function;
  226593. void* parameter;
  226594. void* volatile result;
  226595. bool volatile hasBeenExecuted;
  226596. };
  226597. END_JUCE_NAMESPACE
  226598. @interface JuceCustomMessageHandler : NSObject
  226599. {
  226600. }
  226601. - (void) performCallback: (id) info;
  226602. @end
  226603. @implementation JuceCustomMessageHandler
  226604. - (void) performCallback: (id) info
  226605. {
  226606. if ([info isKindOfClass: [NSData class]])
  226607. {
  226608. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  226609. if (pl != 0)
  226610. {
  226611. pl->result = (*pl->function) (pl->parameter);
  226612. pl->hasBeenExecuted = true;
  226613. }
  226614. }
  226615. else
  226616. {
  226617. jassertfalse; // should never get here!
  226618. }
  226619. }
  226620. @end
  226621. BEGIN_JUCE_NAMESPACE
  226622. void MessageManager::runDispatchLoop()
  226623. {
  226624. jassert (isThisTheMessageThread()); // must only be called by the message thread
  226625. runDispatchLoopUntil (-1);
  226626. }
  226627. void MessageManager::stopDispatchLoop()
  226628. {
  226629. exit (0); // iPhone apps get no mercy..
  226630. }
  226631. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  226632. {
  226633. const ScopedAutoReleasePool pool;
  226634. jassert (isThisTheMessageThread()); // must only be called by the message thread
  226635. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  226636. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  226637. while (! quitMessagePosted)
  226638. {
  226639. const ScopedAutoReleasePool pool;
  226640. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  226641. beforeDate: endDate];
  226642. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  226643. break;
  226644. }
  226645. return ! quitMessagePosted;
  226646. }
  226647. static CFRunLoopRef runLoop = 0;
  226648. static CFRunLoopSourceRef runLoopSource = 0;
  226649. static OwnedArray <Message, CriticalSection>* pendingMessages = 0;
  226650. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  226651. static void runLoopSourceCallback (void*)
  226652. {
  226653. if (pendingMessages != 0)
  226654. {
  226655. int numDispatched = 0;
  226656. do
  226657. {
  226658. Message* const nextMessage = pendingMessages->removeAndReturn (0);
  226659. if (nextMessage == 0)
  226660. return;
  226661. const ScopedAutoReleasePool pool;
  226662. MessageManager::getInstance()->deliverMessage (nextMessage);
  226663. } while (++numDispatched <= 4);
  226664. CFRunLoopSourceSignal (runLoopSource);
  226665. CFRunLoopWakeUp (runLoop);
  226666. }
  226667. }
  226668. void MessageManager::doPlatformSpecificInitialisation()
  226669. {
  226670. pendingMessages = new OwnedArray <Message, CriticalSection>();
  226671. runLoop = CFRunLoopGetCurrent();
  226672. CFRunLoopSourceContext sourceContext;
  226673. zerostruct (sourceContext);
  226674. sourceContext.perform = runLoopSourceCallback;
  226675. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  226676. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  226677. if (juceCustomMessageHandler == 0)
  226678. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  226679. }
  226680. void MessageManager::doPlatformSpecificShutdown()
  226681. {
  226682. CFRunLoopSourceInvalidate (runLoopSource);
  226683. CFRelease (runLoopSource);
  226684. runLoopSource = 0;
  226685. deleteAndZero (pendingMessages);
  226686. if (juceCustomMessageHandler != 0)
  226687. {
  226688. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  226689. [juceCustomMessageHandler release];
  226690. juceCustomMessageHandler = 0;
  226691. }
  226692. }
  226693. bool juce_postMessageToSystemQueue (Message* message)
  226694. {
  226695. if (pendingMessages != 0)
  226696. {
  226697. pendingMessages->add (message);
  226698. CFRunLoopSourceSignal (runLoopSource);
  226699. CFRunLoopWakeUp (runLoop);
  226700. }
  226701. return true;
  226702. }
  226703. void MessageManager::broadcastMessage (const String& value) throw()
  226704. {
  226705. }
  226706. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  226707. void* data)
  226708. {
  226709. if (isThisTheMessageThread())
  226710. {
  226711. return (*callback) (data);
  226712. }
  226713. else
  226714. {
  226715. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  226716. // deadlock because the message manager is blocked from running, so can never
  226717. // call your function..
  226718. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  226719. const ScopedAutoReleasePool pool;
  226720. CallbackMessagePayload cmp;
  226721. cmp.function = callback;
  226722. cmp.parameter = data;
  226723. cmp.result = 0;
  226724. cmp.hasBeenExecuted = false;
  226725. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  226726. withObject: [NSData dataWithBytesNoCopy: &cmp
  226727. length: sizeof (cmp)
  226728. freeWhenDone: NO]
  226729. waitUntilDone: YES];
  226730. return cmp.result;
  226731. }
  226732. }
  226733. #endif
  226734. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  226735. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  226736. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226737. // compiled on its own).
  226738. #if JUCE_INCLUDED_FILE
  226739. #if JUCE_MAC
  226740. END_JUCE_NAMESPACE
  226741. using namespace JUCE_NAMESPACE;
  226742. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  226743. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226744. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  226745. #else
  226746. @interface JuceFileChooserDelegate : NSObject
  226747. #endif
  226748. {
  226749. StringArray* filters;
  226750. }
  226751. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  226752. - (void) dealloc;
  226753. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  226754. @end
  226755. @implementation JuceFileChooserDelegate
  226756. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  226757. {
  226758. [super init];
  226759. filters = filters_;
  226760. return self;
  226761. }
  226762. - (void) dealloc
  226763. {
  226764. delete filters;
  226765. [super dealloc];
  226766. }
  226767. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  226768. {
  226769. (void) sender;
  226770. const File f (nsStringToJuce (filename));
  226771. for (int i = filters->size(); --i >= 0;)
  226772. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  226773. return true;
  226774. return f.isDirectory();
  226775. }
  226776. @end
  226777. BEGIN_JUCE_NAMESPACE
  226778. void FileChooser::showPlatformDialog (Array<File>& results,
  226779. const String& title,
  226780. const File& currentFileOrDirectory,
  226781. const String& filter,
  226782. bool selectsDirectory,
  226783. bool selectsFiles,
  226784. bool isSaveDialogue,
  226785. bool warnAboutOverwritingExistingFiles,
  226786. bool selectMultipleFiles,
  226787. FilePreviewComponent* extraInfoComponent)
  226788. {
  226789. const ScopedAutoReleasePool pool;
  226790. StringArray* filters = new StringArray();
  226791. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  226792. filters->trim();
  226793. filters->removeEmptyStrings();
  226794. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  226795. [delegate autorelease];
  226796. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  226797. : [NSOpenPanel openPanel];
  226798. [panel setTitle: juceStringToNS (title)];
  226799. if (! isSaveDialogue)
  226800. {
  226801. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  226802. [openPanel setCanChooseDirectories: selectsDirectory];
  226803. [openPanel setCanChooseFiles: selectsFiles];
  226804. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  226805. }
  226806. [panel setDelegate: delegate];
  226807. if (isSaveDialogue || selectsDirectory)
  226808. [panel setCanCreateDirectories: YES];
  226809. String directory, filename;
  226810. if (currentFileOrDirectory.isDirectory())
  226811. {
  226812. directory = currentFileOrDirectory.getFullPathName();
  226813. }
  226814. else
  226815. {
  226816. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  226817. filename = currentFileOrDirectory.getFileName();
  226818. }
  226819. if ([panel runModalForDirectory: juceStringToNS (directory)
  226820. file: juceStringToNS (filename)]
  226821. == NSOKButton)
  226822. {
  226823. if (isSaveDialogue)
  226824. {
  226825. results.add (File (nsStringToJuce ([panel filename])));
  226826. }
  226827. else
  226828. {
  226829. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  226830. NSArray* urls = [openPanel filenames];
  226831. for (unsigned int i = 0; i < [urls count]; ++i)
  226832. {
  226833. NSString* f = [urls objectAtIndex: i];
  226834. results.add (File (nsStringToJuce (f)));
  226835. }
  226836. }
  226837. }
  226838. [panel setDelegate: nil];
  226839. }
  226840. #else
  226841. void FileChooser::showPlatformDialog (Array<File>& results,
  226842. const String& title,
  226843. const File& currentFileOrDirectory,
  226844. const String& filter,
  226845. bool selectsDirectory,
  226846. bool selectsFiles,
  226847. bool isSaveDialogue,
  226848. bool warnAboutOverwritingExistingFiles,
  226849. bool selectMultipleFiles,
  226850. FilePreviewComponent* extraInfoComponent)
  226851. {
  226852. const ScopedAutoReleasePool pool;
  226853. jassertfalse; //xxx to do
  226854. }
  226855. #endif
  226856. #endif
  226857. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  226858. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  226859. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226860. // compiled on its own).
  226861. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  226862. #if JUCE_MAC
  226863. END_JUCE_NAMESPACE
  226864. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  226865. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  226866. {
  226867. CriticalSection* contextLock;
  226868. bool needsUpdate;
  226869. }
  226870. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  226871. - (bool) makeActive;
  226872. - (void) makeInactive;
  226873. - (void) reshape;
  226874. @end
  226875. @implementation ThreadSafeNSOpenGLView
  226876. - (id) initWithFrame: (NSRect) frameRect
  226877. pixelFormat: (NSOpenGLPixelFormat*) format
  226878. {
  226879. contextLock = new CriticalSection();
  226880. self = [super initWithFrame: frameRect pixelFormat: format];
  226881. if (self != nil)
  226882. [[NSNotificationCenter defaultCenter] addObserver: self
  226883. selector: @selector (_surfaceNeedsUpdate:)
  226884. name: NSViewGlobalFrameDidChangeNotification
  226885. object: self];
  226886. return self;
  226887. }
  226888. - (void) dealloc
  226889. {
  226890. [[NSNotificationCenter defaultCenter] removeObserver: self];
  226891. delete contextLock;
  226892. [super dealloc];
  226893. }
  226894. - (bool) makeActive
  226895. {
  226896. const ScopedLock sl (*contextLock);
  226897. if ([self openGLContext] == 0)
  226898. return false;
  226899. [[self openGLContext] makeCurrentContext];
  226900. if (needsUpdate)
  226901. {
  226902. [super update];
  226903. needsUpdate = false;
  226904. }
  226905. return true;
  226906. }
  226907. - (void) makeInactive
  226908. {
  226909. const ScopedLock sl (*contextLock);
  226910. [NSOpenGLContext clearCurrentContext];
  226911. }
  226912. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  226913. {
  226914. const ScopedLock sl (*contextLock);
  226915. needsUpdate = true;
  226916. }
  226917. - (void) update
  226918. {
  226919. const ScopedLock sl (*contextLock);
  226920. needsUpdate = true;
  226921. }
  226922. - (void) reshape
  226923. {
  226924. const ScopedLock sl (*contextLock);
  226925. needsUpdate = true;
  226926. }
  226927. @end
  226928. BEGIN_JUCE_NAMESPACE
  226929. class WindowedGLContext : public OpenGLContext
  226930. {
  226931. public:
  226932. WindowedGLContext (Component* const component,
  226933. const OpenGLPixelFormat& pixelFormat_,
  226934. NSOpenGLContext* sharedContext)
  226935. : renderContext (0),
  226936. pixelFormat (pixelFormat_)
  226937. {
  226938. jassert (component != 0);
  226939. NSOpenGLPixelFormatAttribute attribs [64];
  226940. int n = 0;
  226941. attribs[n++] = NSOpenGLPFADoubleBuffer;
  226942. attribs[n++] = NSOpenGLPFAAccelerated;
  226943. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  226944. attribs[n++] = NSOpenGLPFAColorSize;
  226945. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  226946. pixelFormat.greenBits,
  226947. pixelFormat.blueBits);
  226948. attribs[n++] = NSOpenGLPFAAlphaSize;
  226949. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  226950. attribs[n++] = NSOpenGLPFADepthSize;
  226951. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  226952. attribs[n++] = NSOpenGLPFAStencilSize;
  226953. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  226954. attribs[n++] = NSOpenGLPFAAccumSize;
  226955. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  226956. pixelFormat.accumulationBufferGreenBits,
  226957. pixelFormat.accumulationBufferBlueBits,
  226958. pixelFormat.accumulationBufferAlphaBits);
  226959. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  226960. attribs[n++] = NSOpenGLPFASampleBuffers;
  226961. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  226962. attribs[n++] = NSOpenGLPFAClosestPolicy;
  226963. attribs[n++] = NSOpenGLPFANoRecovery;
  226964. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  226965. NSOpenGLPixelFormat* format
  226966. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  226967. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  226968. pixelFormat: format];
  226969. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  226970. shareContext: sharedContext] autorelease];
  226971. const GLint swapInterval = 1;
  226972. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  226973. [view setOpenGLContext: renderContext];
  226974. [renderContext setView: view];
  226975. [format release];
  226976. viewHolder = new NSViewComponentInternal (view, component);
  226977. }
  226978. ~WindowedGLContext()
  226979. {
  226980. deleteContext();
  226981. viewHolder = 0;
  226982. }
  226983. void deleteContext()
  226984. {
  226985. makeInactive();
  226986. [renderContext clearDrawable];
  226987. [renderContext setView: nil];
  226988. [view setOpenGLContext: nil];
  226989. renderContext = nil;
  226990. }
  226991. bool makeActive() const throw()
  226992. {
  226993. jassert (renderContext != 0);
  226994. [view makeActive];
  226995. return isActive();
  226996. }
  226997. bool makeInactive() const throw()
  226998. {
  226999. [view makeInactive];
  227000. return true;
  227001. }
  227002. bool isActive() const throw()
  227003. {
  227004. return [NSOpenGLContext currentContext] == renderContext;
  227005. }
  227006. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  227007. void* getRawContext() const throw() { return renderContext; }
  227008. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  227009. {
  227010. }
  227011. void swapBuffers()
  227012. {
  227013. [renderContext flushBuffer];
  227014. }
  227015. bool setSwapInterval (const int numFramesPerSwap)
  227016. {
  227017. [renderContext setValues: (const GLint*) &numFramesPerSwap
  227018. forParameter: NSOpenGLCPSwapInterval];
  227019. return true;
  227020. }
  227021. int getSwapInterval() const
  227022. {
  227023. GLint numFrames = 0;
  227024. [renderContext getValues: &numFrames
  227025. forParameter: NSOpenGLCPSwapInterval];
  227026. return numFrames;
  227027. }
  227028. void repaint()
  227029. {
  227030. // we need to invalidate the juce view that holds this gl view, to make it
  227031. // cause a repaint callback
  227032. NSView* v = (NSView*) viewHolder->view;
  227033. NSRect r = [v frame];
  227034. // bit of a bodge here.. if we only invalidate the area of the gl component,
  227035. // it's completely covered by the NSOpenGLView, so the OS throws away the
  227036. // repaint message, thus never causing our paint() callback, and never repainting
  227037. // the comp. So invalidating just a little bit around the edge helps..
  227038. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  227039. }
  227040. void* getNativeWindowHandle() const { return viewHolder->view; }
  227041. juce_UseDebuggingNewOperator
  227042. NSOpenGLContext* renderContext;
  227043. ThreadSafeNSOpenGLView* view;
  227044. private:
  227045. OpenGLPixelFormat pixelFormat;
  227046. ScopedPointer <NSViewComponentInternal> viewHolder;
  227047. WindowedGLContext (const WindowedGLContext&);
  227048. WindowedGLContext& operator= (const WindowedGLContext&);
  227049. };
  227050. OpenGLContext* OpenGLComponent::createContext()
  227051. {
  227052. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  227053. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  227054. return (c->renderContext != 0) ? c.release() : 0;
  227055. }
  227056. void* OpenGLComponent::getNativeWindowHandle() const
  227057. {
  227058. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  227059. : 0;
  227060. }
  227061. void juce_glViewport (const int w, const int h)
  227062. {
  227063. glViewport (0, 0, w, h);
  227064. }
  227065. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  227066. OwnedArray <OpenGLPixelFormat>& results)
  227067. {
  227068. /* GLint attribs [64];
  227069. int n = 0;
  227070. attribs[n++] = AGL_RGBA;
  227071. attribs[n++] = AGL_DOUBLEBUFFER;
  227072. attribs[n++] = AGL_ACCELERATED;
  227073. attribs[n++] = AGL_NO_RECOVERY;
  227074. attribs[n++] = AGL_NONE;
  227075. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  227076. while (p != 0)
  227077. {
  227078. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  227079. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  227080. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  227081. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  227082. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  227083. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  227084. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  227085. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  227086. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  227087. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  227088. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  227089. results.add (pf);
  227090. p = aglNextPixelFormat (p);
  227091. }*/
  227092. //jassertfalse //xxx can't see how you do this in cocoa!
  227093. }
  227094. #else
  227095. END_JUCE_NAMESPACE
  227096. @interface JuceGLView : UIView
  227097. {
  227098. }
  227099. + (Class) layerClass;
  227100. @end
  227101. @implementation JuceGLView
  227102. + (Class) layerClass
  227103. {
  227104. return [CAEAGLLayer class];
  227105. }
  227106. @end
  227107. BEGIN_JUCE_NAMESPACE
  227108. class GLESContext : public OpenGLContext
  227109. {
  227110. public:
  227111. GLESContext (UIViewComponentPeer* peer,
  227112. Component* const component_,
  227113. const OpenGLPixelFormat& pixelFormat_,
  227114. const GLESContext* const sharedContext,
  227115. NSUInteger apiType)
  227116. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  227117. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  227118. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  227119. {
  227120. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  227121. view.opaque = YES;
  227122. view.hidden = NO;
  227123. view.backgroundColor = [UIColor blackColor];
  227124. view.userInteractionEnabled = NO;
  227125. glLayer = (CAEAGLLayer*) [view layer];
  227126. [peer->view addSubview: view];
  227127. if (sharedContext != 0)
  227128. context = [[EAGLContext alloc] initWithAPI: apiType
  227129. sharegroup: [sharedContext->context sharegroup]];
  227130. else
  227131. context = [[EAGLContext alloc] initWithAPI: apiType];
  227132. createGLBuffers();
  227133. }
  227134. ~GLESContext()
  227135. {
  227136. deleteContext();
  227137. [view removeFromSuperview];
  227138. [view release];
  227139. freeGLBuffers();
  227140. }
  227141. void deleteContext()
  227142. {
  227143. makeInactive();
  227144. [context release];
  227145. context = nil;
  227146. }
  227147. bool makeActive() const throw()
  227148. {
  227149. jassert (context != 0);
  227150. [EAGLContext setCurrentContext: context];
  227151. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  227152. return true;
  227153. }
  227154. void swapBuffers()
  227155. {
  227156. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227157. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  227158. }
  227159. bool makeInactive() const throw()
  227160. {
  227161. return [EAGLContext setCurrentContext: nil];
  227162. }
  227163. bool isActive() const throw()
  227164. {
  227165. return [EAGLContext currentContext] == context;
  227166. }
  227167. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  227168. void* getRawContext() const throw() { return glLayer; }
  227169. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  227170. {
  227171. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  227172. if (lastWidth != w || lastHeight != h)
  227173. {
  227174. lastWidth = w;
  227175. lastHeight = h;
  227176. freeGLBuffers();
  227177. createGLBuffers();
  227178. }
  227179. }
  227180. bool setSwapInterval (const int numFramesPerSwap)
  227181. {
  227182. numFrames = numFramesPerSwap;
  227183. return true;
  227184. }
  227185. int getSwapInterval() const
  227186. {
  227187. return numFrames;
  227188. }
  227189. void repaint()
  227190. {
  227191. }
  227192. void createGLBuffers()
  227193. {
  227194. makeActive();
  227195. glGenFramebuffersOES (1, &frameBufferHandle);
  227196. glGenRenderbuffersOES (1, &colorBufferHandle);
  227197. glGenRenderbuffersOES (1, &depthBufferHandle);
  227198. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227199. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  227200. GLint width, height;
  227201. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  227202. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  227203. if (useDepthBuffer)
  227204. {
  227205. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  227206. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  227207. }
  227208. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227209. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  227210. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  227211. if (useDepthBuffer)
  227212. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  227213. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  227214. }
  227215. void freeGLBuffers()
  227216. {
  227217. if (frameBufferHandle != 0)
  227218. {
  227219. glDeleteFramebuffersOES (1, &frameBufferHandle);
  227220. frameBufferHandle = 0;
  227221. }
  227222. if (colorBufferHandle != 0)
  227223. {
  227224. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  227225. colorBufferHandle = 0;
  227226. }
  227227. if (depthBufferHandle != 0)
  227228. {
  227229. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  227230. depthBufferHandle = 0;
  227231. }
  227232. }
  227233. juce_UseDebuggingNewOperator
  227234. private:
  227235. Component::SafePointer<Component> component;
  227236. OpenGLPixelFormat pixelFormat;
  227237. JuceGLView* view;
  227238. CAEAGLLayer* glLayer;
  227239. EAGLContext* context;
  227240. bool useDepthBuffer;
  227241. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  227242. int numFrames;
  227243. int lastWidth, lastHeight;
  227244. GLESContext (const GLESContext&);
  227245. GLESContext& operator= (const GLESContext&);
  227246. };
  227247. OpenGLContext* OpenGLComponent::createContext()
  227248. {
  227249. ScopedAutoReleasePool pool;
  227250. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  227251. if (peer != 0)
  227252. return new GLESContext (peer, this, preferredPixelFormat,
  227253. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  227254. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  227255. return 0;
  227256. }
  227257. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  227258. OwnedArray <OpenGLPixelFormat>& /*results*/)
  227259. {
  227260. }
  227261. void juce_glViewport (const int w, const int h)
  227262. {
  227263. glViewport (0, 0, w, h);
  227264. }
  227265. #endif
  227266. #endif
  227267. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  227268. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  227269. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227270. // compiled on its own).
  227271. #if JUCE_INCLUDED_FILE
  227272. #if JUCE_MAC
  227273. namespace MouseCursorHelpers
  227274. {
  227275. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  227276. {
  227277. NSImage* im = CoreGraphicsImage::createNSImage (image);
  227278. NSCursor* c = [[NSCursor alloc] initWithImage: im
  227279. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  227280. [im release];
  227281. return c;
  227282. }
  227283. static void* fromWebKitFile (const char* filename, float hx, float hy)
  227284. {
  227285. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  227286. BufferedInputStream buf (&fileStream, 4096, false);
  227287. PNGImageFormat pngFormat;
  227288. Image im (pngFormat.decodeImage (buf));
  227289. if (im.isValid())
  227290. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  227291. jassertfalse;
  227292. return 0;
  227293. }
  227294. }
  227295. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  227296. {
  227297. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  227298. }
  227299. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  227300. {
  227301. const ScopedAutoReleasePool pool;
  227302. NSCursor* c = 0;
  227303. switch (type)
  227304. {
  227305. case NormalCursor: c = [NSCursor arrowCursor]; break;
  227306. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  227307. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  227308. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  227309. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  227310. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  227311. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  227312. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  227313. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  227314. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  227315. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  227316. case UpDownResizeCursor:
  227317. case TopEdgeResizeCursor:
  227318. case BottomEdgeResizeCursor:
  227319. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  227320. case TopLeftCornerResizeCursor:
  227321. case BottomRightCornerResizeCursor:
  227322. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  227323. case TopRightCornerResizeCursor:
  227324. case BottomLeftCornerResizeCursor:
  227325. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  227326. case UpDownLeftRightResizeCursor:
  227327. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  227328. default:
  227329. jassertfalse;
  227330. break;
  227331. }
  227332. [c retain];
  227333. return c;
  227334. }
  227335. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  227336. {
  227337. [((NSCursor*) cursorHandle) release];
  227338. }
  227339. void MouseCursor::showInAllWindows() const
  227340. {
  227341. showInWindow (0);
  227342. }
  227343. void MouseCursor::showInWindow (ComponentPeer*) const
  227344. {
  227345. [((NSCursor*) getHandle()) set];
  227346. }
  227347. #else
  227348. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  227349. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  227350. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  227351. void MouseCursor::showInAllWindows() const {}
  227352. void MouseCursor::showInWindow (ComponentPeer*) const {}
  227353. #endif
  227354. #endif
  227355. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  227356. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  227357. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227358. // compiled on its own).
  227359. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  227360. #if JUCE_MAC
  227361. END_JUCE_NAMESPACE
  227362. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  227363. @interface DownloadClickDetector : NSObject
  227364. {
  227365. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  227366. }
  227367. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  227368. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  227369. request: (NSURLRequest*) request
  227370. frame: (WebFrame*) frame
  227371. decisionListener: (id<WebPolicyDecisionListener>) listener;
  227372. @end
  227373. @implementation DownloadClickDetector
  227374. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  227375. {
  227376. [super init];
  227377. ownerComponent = ownerComponent_;
  227378. return self;
  227379. }
  227380. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  227381. request: (NSURLRequest*) request
  227382. frame: (WebFrame*) frame
  227383. decisionListener: (id <WebPolicyDecisionListener>) listener
  227384. {
  227385. (void) sender;
  227386. (void) request;
  227387. (void) frame;
  227388. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  227389. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  227390. [listener use];
  227391. else
  227392. [listener ignore];
  227393. }
  227394. @end
  227395. BEGIN_JUCE_NAMESPACE
  227396. class WebBrowserComponentInternal : public NSViewComponent
  227397. {
  227398. public:
  227399. WebBrowserComponentInternal (WebBrowserComponent* owner)
  227400. {
  227401. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  227402. frameName: @""
  227403. groupName: @""];
  227404. setView (webView);
  227405. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  227406. [webView setPolicyDelegate: clickListener];
  227407. }
  227408. ~WebBrowserComponentInternal()
  227409. {
  227410. [webView setPolicyDelegate: nil];
  227411. [clickListener release];
  227412. setView (0);
  227413. }
  227414. void goToURL (const String& url,
  227415. const StringArray* headers,
  227416. const MemoryBlock* postData)
  227417. {
  227418. NSMutableURLRequest* r
  227419. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  227420. cachePolicy: NSURLRequestUseProtocolCachePolicy
  227421. timeoutInterval: 30.0];
  227422. if (postData != 0 && postData->getSize() > 0)
  227423. {
  227424. [r setHTTPMethod: @"POST"];
  227425. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  227426. length: postData->getSize()]];
  227427. }
  227428. if (headers != 0)
  227429. {
  227430. for (int i = 0; i < headers->size(); ++i)
  227431. {
  227432. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  227433. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  227434. [r setValue: juceStringToNS (headerValue)
  227435. forHTTPHeaderField: juceStringToNS (headerName)];
  227436. }
  227437. }
  227438. stop();
  227439. [[webView mainFrame] loadRequest: r];
  227440. }
  227441. void goBack()
  227442. {
  227443. [webView goBack];
  227444. }
  227445. void goForward()
  227446. {
  227447. [webView goForward];
  227448. }
  227449. void stop()
  227450. {
  227451. [webView stopLoading: nil];
  227452. }
  227453. void refresh()
  227454. {
  227455. [webView reload: nil];
  227456. }
  227457. private:
  227458. WebView* webView;
  227459. DownloadClickDetector* clickListener;
  227460. };
  227461. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  227462. : browser (0),
  227463. blankPageShown (false),
  227464. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  227465. {
  227466. setOpaque (true);
  227467. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  227468. }
  227469. WebBrowserComponent::~WebBrowserComponent()
  227470. {
  227471. deleteAndZero (browser);
  227472. }
  227473. void WebBrowserComponent::goToURL (const String& url,
  227474. const StringArray* headers,
  227475. const MemoryBlock* postData)
  227476. {
  227477. lastURL = url;
  227478. lastHeaders.clear();
  227479. if (headers != 0)
  227480. lastHeaders = *headers;
  227481. lastPostData.setSize (0);
  227482. if (postData != 0)
  227483. lastPostData = *postData;
  227484. blankPageShown = false;
  227485. browser->goToURL (url, headers, postData);
  227486. }
  227487. void WebBrowserComponent::stop()
  227488. {
  227489. browser->stop();
  227490. }
  227491. void WebBrowserComponent::goBack()
  227492. {
  227493. lastURL = String::empty;
  227494. blankPageShown = false;
  227495. browser->goBack();
  227496. }
  227497. void WebBrowserComponent::goForward()
  227498. {
  227499. lastURL = String::empty;
  227500. browser->goForward();
  227501. }
  227502. void WebBrowserComponent::refresh()
  227503. {
  227504. browser->refresh();
  227505. }
  227506. void WebBrowserComponent::paint (Graphics&)
  227507. {
  227508. }
  227509. void WebBrowserComponent::checkWindowAssociation()
  227510. {
  227511. if (isShowing())
  227512. {
  227513. if (blankPageShown)
  227514. goBack();
  227515. }
  227516. else
  227517. {
  227518. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  227519. {
  227520. // when the component becomes invisible, some stuff like flash
  227521. // carries on playing audio, so we need to force it onto a blank
  227522. // page to avoid this, (and send it back when it's made visible again).
  227523. blankPageShown = true;
  227524. browser->goToURL ("about:blank", 0, 0);
  227525. }
  227526. }
  227527. }
  227528. void WebBrowserComponent::reloadLastURL()
  227529. {
  227530. if (lastURL.isNotEmpty())
  227531. {
  227532. goToURL (lastURL, &lastHeaders, &lastPostData);
  227533. lastURL = String::empty;
  227534. }
  227535. }
  227536. void WebBrowserComponent::parentHierarchyChanged()
  227537. {
  227538. checkWindowAssociation();
  227539. }
  227540. void WebBrowserComponent::resized()
  227541. {
  227542. browser->setSize (getWidth(), getHeight());
  227543. }
  227544. void WebBrowserComponent::visibilityChanged()
  227545. {
  227546. checkWindowAssociation();
  227547. }
  227548. bool WebBrowserComponent::pageAboutToLoad (const String&)
  227549. {
  227550. return true;
  227551. }
  227552. #else
  227553. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  227554. {
  227555. }
  227556. WebBrowserComponent::~WebBrowserComponent()
  227557. {
  227558. }
  227559. void WebBrowserComponent::goToURL (const String& url,
  227560. const StringArray* headers,
  227561. const MemoryBlock* postData)
  227562. {
  227563. }
  227564. void WebBrowserComponent::stop()
  227565. {
  227566. }
  227567. void WebBrowserComponent::goBack()
  227568. {
  227569. }
  227570. void WebBrowserComponent::goForward()
  227571. {
  227572. }
  227573. void WebBrowserComponent::refresh()
  227574. {
  227575. }
  227576. void WebBrowserComponent::paint (Graphics& g)
  227577. {
  227578. }
  227579. void WebBrowserComponent::checkWindowAssociation()
  227580. {
  227581. }
  227582. void WebBrowserComponent::reloadLastURL()
  227583. {
  227584. }
  227585. void WebBrowserComponent::parentHierarchyChanged()
  227586. {
  227587. }
  227588. void WebBrowserComponent::resized()
  227589. {
  227590. }
  227591. void WebBrowserComponent::visibilityChanged()
  227592. {
  227593. }
  227594. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  227595. {
  227596. return true;
  227597. }
  227598. #endif
  227599. #endif
  227600. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  227601. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  227602. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227603. // compiled on its own).
  227604. #if JUCE_INCLUDED_FILE
  227605. class IPhoneAudioIODevice : public AudioIODevice
  227606. {
  227607. public:
  227608. IPhoneAudioIODevice (const String& deviceName)
  227609. : AudioIODevice (deviceName, "Audio"),
  227610. audioUnit (0),
  227611. isRunning (false),
  227612. callback (0),
  227613. actualBufferSize (0),
  227614. floatData (1, 2)
  227615. {
  227616. numInputChannels = 2;
  227617. numOutputChannels = 2;
  227618. preferredBufferSize = 0;
  227619. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  227620. updateDeviceInfo();
  227621. }
  227622. ~IPhoneAudioIODevice()
  227623. {
  227624. close();
  227625. }
  227626. const StringArray getOutputChannelNames()
  227627. {
  227628. StringArray s;
  227629. s.add ("Left");
  227630. s.add ("Right");
  227631. return s;
  227632. }
  227633. const StringArray getInputChannelNames()
  227634. {
  227635. StringArray s;
  227636. if (audioInputIsAvailable)
  227637. {
  227638. s.add ("Left");
  227639. s.add ("Right");
  227640. }
  227641. return s;
  227642. }
  227643. int getNumSampleRates()
  227644. {
  227645. return 1;
  227646. }
  227647. double getSampleRate (int index)
  227648. {
  227649. return sampleRate;
  227650. }
  227651. int getNumBufferSizesAvailable()
  227652. {
  227653. return 1;
  227654. }
  227655. int getBufferSizeSamples (int index)
  227656. {
  227657. return getDefaultBufferSize();
  227658. }
  227659. int getDefaultBufferSize()
  227660. {
  227661. return 1024;
  227662. }
  227663. const String open (const BigInteger& inputChannels,
  227664. const BigInteger& outputChannels,
  227665. double sampleRate,
  227666. int bufferSize)
  227667. {
  227668. close();
  227669. lastError = String::empty;
  227670. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  227671. // xxx set up channel mapping
  227672. activeOutputChans = outputChannels;
  227673. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  227674. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  227675. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  227676. activeInputChans = inputChannels;
  227677. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  227678. numInputChannels = activeInputChans.countNumberOfSetBits();
  227679. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  227680. AudioSessionSetActive (true);
  227681. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  227682. : kAudioSessionCategory_MediaPlayback;
  227683. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  227684. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  227685. fixAudioRouteIfSetToReceiver();
  227686. updateDeviceInfo();
  227687. Float32 bufferDuration = preferredBufferSize / sampleRate;
  227688. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  227689. actualBufferSize = preferredBufferSize;
  227690. prepareFloatBuffers();
  227691. isRunning = true;
  227692. propertyChanged (0, 0, 0); // creates and starts the AU
  227693. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  227694. return lastError;
  227695. }
  227696. void close()
  227697. {
  227698. if (isRunning)
  227699. {
  227700. isRunning = false;
  227701. AudioSessionSetActive (false);
  227702. if (audioUnit != 0)
  227703. {
  227704. AudioComponentInstanceDispose (audioUnit);
  227705. audioUnit = 0;
  227706. }
  227707. }
  227708. }
  227709. bool isOpen()
  227710. {
  227711. return isRunning;
  227712. }
  227713. int getCurrentBufferSizeSamples()
  227714. {
  227715. return actualBufferSize;
  227716. }
  227717. double getCurrentSampleRate()
  227718. {
  227719. return sampleRate;
  227720. }
  227721. int getCurrentBitDepth()
  227722. {
  227723. return 16;
  227724. }
  227725. const BigInteger getActiveOutputChannels() const
  227726. {
  227727. return activeOutputChans;
  227728. }
  227729. const BigInteger getActiveInputChannels() const
  227730. {
  227731. return activeInputChans;
  227732. }
  227733. int getOutputLatencyInSamples()
  227734. {
  227735. return 0; //xxx
  227736. }
  227737. int getInputLatencyInSamples()
  227738. {
  227739. return 0; //xxx
  227740. }
  227741. void start (AudioIODeviceCallback* callback_)
  227742. {
  227743. if (isRunning && callback != callback_)
  227744. {
  227745. if (callback_ != 0)
  227746. callback_->audioDeviceAboutToStart (this);
  227747. const ScopedLock sl (callbackLock);
  227748. callback = callback_;
  227749. }
  227750. }
  227751. void stop()
  227752. {
  227753. if (isRunning)
  227754. {
  227755. AudioIODeviceCallback* lastCallback;
  227756. {
  227757. const ScopedLock sl (callbackLock);
  227758. lastCallback = callback;
  227759. callback = 0;
  227760. }
  227761. if (lastCallback != 0)
  227762. lastCallback->audioDeviceStopped();
  227763. }
  227764. }
  227765. bool isPlaying()
  227766. {
  227767. return isRunning && callback != 0;
  227768. }
  227769. const String getLastError()
  227770. {
  227771. return lastError;
  227772. }
  227773. private:
  227774. CriticalSection callbackLock;
  227775. Float64 sampleRate;
  227776. int numInputChannels, numOutputChannels;
  227777. int preferredBufferSize;
  227778. int actualBufferSize;
  227779. bool isRunning;
  227780. String lastError;
  227781. AudioStreamBasicDescription format;
  227782. AudioUnit audioUnit;
  227783. UInt32 audioInputIsAvailable;
  227784. AudioIODeviceCallback* callback;
  227785. BigInteger activeOutputChans, activeInputChans;
  227786. AudioSampleBuffer floatData;
  227787. float* inputChannels[3];
  227788. float* outputChannels[3];
  227789. bool monoInputChannelNumber, monoOutputChannelNumber;
  227790. void prepareFloatBuffers()
  227791. {
  227792. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  227793. zerostruct (inputChannels);
  227794. zerostruct (outputChannels);
  227795. for (int i = 0; i < numInputChannels; ++i)
  227796. inputChannels[i] = floatData.getSampleData (i);
  227797. for (int i = 0; i < numOutputChannels; ++i)
  227798. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  227799. }
  227800. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  227801. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  227802. {
  227803. OSStatus err = noErr;
  227804. if (audioInputIsAvailable)
  227805. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  227806. const ScopedLock sl (callbackLock);
  227807. if (callback != 0)
  227808. {
  227809. if (audioInputIsAvailable && numInputChannels > 0)
  227810. {
  227811. short* shortData = (short*) ioData->mBuffers[0].mData;
  227812. if (numInputChannels >= 2)
  227813. {
  227814. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227815. {
  227816. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  227817. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  227818. }
  227819. }
  227820. else
  227821. {
  227822. if (monoInputChannelNumber > 0)
  227823. ++shortData;
  227824. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227825. {
  227826. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  227827. ++shortData;
  227828. }
  227829. }
  227830. }
  227831. else
  227832. {
  227833. for (int i = numInputChannels; --i >= 0;)
  227834. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  227835. }
  227836. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  227837. outputChannels, numOutputChannels,
  227838. (int) inNumberFrames);
  227839. short* shortData = (short*) ioData->mBuffers[0].mData;
  227840. int n = 0;
  227841. if (numOutputChannels >= 2)
  227842. {
  227843. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227844. {
  227845. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  227846. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  227847. }
  227848. }
  227849. else if (numOutputChannels == 1)
  227850. {
  227851. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227852. {
  227853. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  227854. shortData [n++] = s;
  227855. shortData [n++] = s;
  227856. }
  227857. }
  227858. else
  227859. {
  227860. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  227861. }
  227862. }
  227863. else
  227864. {
  227865. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  227866. }
  227867. return err;
  227868. }
  227869. void updateDeviceInfo()
  227870. {
  227871. UInt32 size = sizeof (sampleRate);
  227872. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  227873. size = sizeof (audioInputIsAvailable);
  227874. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  227875. }
  227876. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  227877. {
  227878. if (! isRunning)
  227879. return;
  227880. if (inPropertyValue != 0)
  227881. {
  227882. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  227883. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  227884. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  227885. SInt32 routeChangeReason;
  227886. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  227887. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  227888. fixAudioRouteIfSetToReceiver();
  227889. }
  227890. updateDeviceInfo();
  227891. createAudioUnit();
  227892. AudioSessionSetActive (true);
  227893. if (audioUnit != 0)
  227894. {
  227895. UInt32 formatSize = sizeof (format);
  227896. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  227897. Float32 bufferDuration = preferredBufferSize / sampleRate;
  227898. UInt32 bufferDurationSize = sizeof (bufferDuration);
  227899. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  227900. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  227901. AudioOutputUnitStart (audioUnit);
  227902. }
  227903. }
  227904. void interruptionListener (UInt32 inInterruption)
  227905. {
  227906. /*if (inInterruption == kAudioSessionBeginInterruption)
  227907. {
  227908. isRunning = false;
  227909. AudioOutputUnitStop (audioUnit);
  227910. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  227911. "This could have been interrupted by another application or by unplugging a headset",
  227912. @"Resume",
  227913. @"Cancel"))
  227914. {
  227915. isRunning = true;
  227916. propertyChanged (0, 0, 0);
  227917. }
  227918. }*/
  227919. if (inInterruption == kAudioSessionEndInterruption)
  227920. {
  227921. isRunning = true;
  227922. AudioSessionSetActive (true);
  227923. AudioOutputUnitStart (audioUnit);
  227924. }
  227925. }
  227926. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  227927. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  227928. {
  227929. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  227930. }
  227931. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  227932. {
  227933. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  227934. }
  227935. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  227936. {
  227937. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  227938. }
  227939. void resetFormat (const int numChannels)
  227940. {
  227941. memset (&format, 0, sizeof (format));
  227942. format.mFormatID = kAudioFormatLinearPCM;
  227943. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  227944. format.mBitsPerChannel = 8 * sizeof (short);
  227945. format.mChannelsPerFrame = 2;
  227946. format.mFramesPerPacket = 1;
  227947. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  227948. }
  227949. bool createAudioUnit()
  227950. {
  227951. if (audioUnit != 0)
  227952. {
  227953. AudioComponentInstanceDispose (audioUnit);
  227954. audioUnit = 0;
  227955. }
  227956. resetFormat (2);
  227957. AudioComponentDescription desc;
  227958. desc.componentType = kAudioUnitType_Output;
  227959. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  227960. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  227961. desc.componentFlags = 0;
  227962. desc.componentFlagsMask = 0;
  227963. AudioComponent comp = AudioComponentFindNext (0, &desc);
  227964. AudioComponentInstanceNew (comp, &audioUnit);
  227965. if (audioUnit == 0)
  227966. return false;
  227967. const UInt32 one = 1;
  227968. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  227969. AudioChannelLayout layout;
  227970. layout.mChannelBitmap = 0;
  227971. layout.mNumberChannelDescriptions = 0;
  227972. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  227973. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  227974. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  227975. AURenderCallbackStruct inputProc;
  227976. inputProc.inputProc = processStatic;
  227977. inputProc.inputProcRefCon = this;
  227978. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  227979. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  227980. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  227981. AudioUnitInitialize (audioUnit);
  227982. return true;
  227983. }
  227984. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  227985. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  227986. static void fixAudioRouteIfSetToReceiver()
  227987. {
  227988. CFStringRef audioRoute = 0;
  227989. UInt32 propertySize = sizeof (audioRoute);
  227990. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  227991. {
  227992. NSString* route = (NSString*) audioRoute;
  227993. //DBG ("audio route: " + nsStringToJuce (route));
  227994. if ([route hasPrefix: @"Receiver"])
  227995. {
  227996. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  227997. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  227998. }
  227999. CFRelease (audioRoute);
  228000. }
  228001. }
  228002. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  228003. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  228004. };
  228005. class IPhoneAudioIODeviceType : public AudioIODeviceType
  228006. {
  228007. public:
  228008. IPhoneAudioIODeviceType()
  228009. : AudioIODeviceType ("iPhone Audio")
  228010. {
  228011. }
  228012. ~IPhoneAudioIODeviceType()
  228013. {
  228014. }
  228015. void scanForDevices()
  228016. {
  228017. }
  228018. const StringArray getDeviceNames (bool wantInputNames) const
  228019. {
  228020. StringArray s;
  228021. s.add ("iPhone Audio");
  228022. return s;
  228023. }
  228024. int getDefaultDeviceIndex (bool forInput) const
  228025. {
  228026. return 0;
  228027. }
  228028. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  228029. {
  228030. return device != 0 ? 0 : -1;
  228031. }
  228032. bool hasSeparateInputsAndOutputs() const { return false; }
  228033. AudioIODevice* createDevice (const String& outputDeviceName,
  228034. const String& inputDeviceName)
  228035. {
  228036. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  228037. {
  228038. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  228039. : inputDeviceName);
  228040. }
  228041. return 0;
  228042. }
  228043. juce_UseDebuggingNewOperator
  228044. private:
  228045. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  228046. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  228047. };
  228048. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  228049. {
  228050. return new IPhoneAudioIODeviceType();
  228051. }
  228052. #endif
  228053. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  228054. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  228055. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228056. // compiled on its own).
  228057. #if JUCE_INCLUDED_FILE
  228058. #if JUCE_MAC
  228059. #undef log
  228060. #define log(a) Logger::writeToLog(a)
  228061. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  228062. {
  228063. if (err == noErr)
  228064. return true;
  228065. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  228066. jassertfalse;
  228067. return false;
  228068. }
  228069. #undef OK
  228070. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  228071. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  228072. {
  228073. String result;
  228074. CFStringRef str = 0;
  228075. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  228076. if (str != 0)
  228077. {
  228078. result = PlatformUtilities::cfStringToJuceString (str);
  228079. CFRelease (str);
  228080. str = 0;
  228081. }
  228082. MIDIEntityRef entity = 0;
  228083. MIDIEndpointGetEntity (endpoint, &entity);
  228084. if (entity == 0)
  228085. return result; // probably virtual
  228086. if (result.isEmpty())
  228087. {
  228088. // endpoint name has zero length - try the entity
  228089. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  228090. if (str != 0)
  228091. {
  228092. result += PlatformUtilities::cfStringToJuceString (str);
  228093. CFRelease (str);
  228094. str = 0;
  228095. }
  228096. }
  228097. // now consider the device's name
  228098. MIDIDeviceRef device = 0;
  228099. MIDIEntityGetDevice (entity, &device);
  228100. if (device == 0)
  228101. return result;
  228102. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  228103. if (str != 0)
  228104. {
  228105. const String s (PlatformUtilities::cfStringToJuceString (str));
  228106. CFRelease (str);
  228107. // if an external device has only one entity, throw away
  228108. // the endpoint name and just use the device name
  228109. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  228110. {
  228111. result = s;
  228112. }
  228113. else if (! result.startsWithIgnoreCase (s))
  228114. {
  228115. // prepend the device name to the entity name
  228116. result = (s + " " + result).trimEnd();
  228117. }
  228118. }
  228119. return result;
  228120. }
  228121. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  228122. {
  228123. String result;
  228124. // Does the endpoint have connections?
  228125. CFDataRef connections = 0;
  228126. int numConnections = 0;
  228127. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  228128. if (connections != 0)
  228129. {
  228130. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  228131. if (numConnections > 0)
  228132. {
  228133. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  228134. for (int i = 0; i < numConnections; ++i, ++pid)
  228135. {
  228136. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  228137. MIDIObjectRef connObject;
  228138. MIDIObjectType connObjectType;
  228139. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  228140. if (err == noErr)
  228141. {
  228142. String s;
  228143. if (connObjectType == kMIDIObjectType_ExternalSource
  228144. || connObjectType == kMIDIObjectType_ExternalDestination)
  228145. {
  228146. // Connected to an external device's endpoint (10.3 and later).
  228147. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  228148. }
  228149. else
  228150. {
  228151. // Connected to an external device (10.2) (or something else, catch-all)
  228152. CFStringRef str = 0;
  228153. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  228154. if (str != 0)
  228155. {
  228156. s = PlatformUtilities::cfStringToJuceString (str);
  228157. CFRelease (str);
  228158. }
  228159. }
  228160. if (s.isNotEmpty())
  228161. {
  228162. if (result.isNotEmpty())
  228163. result += ", ";
  228164. result += s;
  228165. }
  228166. }
  228167. }
  228168. }
  228169. CFRelease (connections);
  228170. }
  228171. if (result.isNotEmpty())
  228172. return result;
  228173. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  228174. return getEndpointName (endpoint, false);
  228175. }
  228176. const StringArray MidiOutput::getDevices()
  228177. {
  228178. StringArray s;
  228179. const ItemCount num = MIDIGetNumberOfDestinations();
  228180. for (ItemCount i = 0; i < num; ++i)
  228181. {
  228182. MIDIEndpointRef dest = MIDIGetDestination (i);
  228183. if (dest != 0)
  228184. {
  228185. String name (getConnectedEndpointName (dest));
  228186. if (name.isEmpty())
  228187. name = "<error>";
  228188. s.add (name);
  228189. }
  228190. else
  228191. {
  228192. s.add ("<error>");
  228193. }
  228194. }
  228195. return s;
  228196. }
  228197. int MidiOutput::getDefaultDeviceIndex()
  228198. {
  228199. return 0;
  228200. }
  228201. static MIDIClientRef globalMidiClient;
  228202. static bool hasGlobalClientBeenCreated = false;
  228203. static bool makeSureClientExists()
  228204. {
  228205. if (! hasGlobalClientBeenCreated)
  228206. {
  228207. String name ("JUCE");
  228208. if (JUCEApplication::getInstance() != 0)
  228209. name = JUCEApplication::getInstance()->getApplicationName();
  228210. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  228211. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  228212. CFRelease (appName);
  228213. }
  228214. return hasGlobalClientBeenCreated;
  228215. }
  228216. class MidiPortAndEndpoint
  228217. {
  228218. public:
  228219. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  228220. : port (port_), endPoint (endPoint_)
  228221. {
  228222. }
  228223. ~MidiPortAndEndpoint()
  228224. {
  228225. if (port != 0)
  228226. MIDIPortDispose (port);
  228227. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  228228. MIDIEndpointDispose (endPoint);
  228229. }
  228230. MIDIPortRef port;
  228231. MIDIEndpointRef endPoint;
  228232. };
  228233. MidiOutput* MidiOutput::openDevice (int index)
  228234. {
  228235. MidiOutput* mo = 0;
  228236. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  228237. {
  228238. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  228239. CFStringRef pname;
  228240. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  228241. {
  228242. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  228243. if (makeSureClientExists())
  228244. {
  228245. MIDIPortRef port;
  228246. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  228247. {
  228248. mo = new MidiOutput();
  228249. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  228250. }
  228251. }
  228252. CFRelease (pname);
  228253. }
  228254. }
  228255. return mo;
  228256. }
  228257. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  228258. {
  228259. MidiOutput* mo = 0;
  228260. if (makeSureClientExists())
  228261. {
  228262. MIDIEndpointRef endPoint;
  228263. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  228264. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  228265. {
  228266. mo = new MidiOutput();
  228267. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  228268. }
  228269. CFRelease (name);
  228270. }
  228271. return mo;
  228272. }
  228273. MidiOutput::~MidiOutput()
  228274. {
  228275. delete (MidiPortAndEndpoint*) internal;
  228276. }
  228277. void MidiOutput::reset()
  228278. {
  228279. }
  228280. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  228281. {
  228282. return false;
  228283. }
  228284. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  228285. {
  228286. }
  228287. void MidiOutput::sendMessageNow (const MidiMessage& message)
  228288. {
  228289. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  228290. if (message.isSysEx())
  228291. {
  228292. const int maxPacketSize = 256;
  228293. int pos = 0, bytesLeft = message.getRawDataSize();
  228294. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  228295. HeapBlock <MIDIPacketList> packets;
  228296. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  228297. packets->numPackets = numPackets;
  228298. MIDIPacket* p = packets->packet;
  228299. for (int i = 0; i < numPackets; ++i)
  228300. {
  228301. p->timeStamp = 0;
  228302. p->length = jmin (maxPacketSize, bytesLeft);
  228303. memcpy (p->data, message.getRawData() + pos, p->length);
  228304. pos += p->length;
  228305. bytesLeft -= p->length;
  228306. p = MIDIPacketNext (p);
  228307. }
  228308. if (mpe->port != 0)
  228309. MIDISend (mpe->port, mpe->endPoint, packets);
  228310. else
  228311. MIDIReceived (mpe->endPoint, packets);
  228312. }
  228313. else
  228314. {
  228315. MIDIPacketList packets;
  228316. packets.numPackets = 1;
  228317. packets.packet[0].timeStamp = 0;
  228318. packets.packet[0].length = message.getRawDataSize();
  228319. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  228320. if (mpe->port != 0)
  228321. MIDISend (mpe->port, mpe->endPoint, &packets);
  228322. else
  228323. MIDIReceived (mpe->endPoint, &packets);
  228324. }
  228325. }
  228326. const StringArray MidiInput::getDevices()
  228327. {
  228328. StringArray s;
  228329. const ItemCount num = MIDIGetNumberOfSources();
  228330. for (ItemCount i = 0; i < num; ++i)
  228331. {
  228332. MIDIEndpointRef source = MIDIGetSource (i);
  228333. if (source != 0)
  228334. {
  228335. String name (getConnectedEndpointName (source));
  228336. if (name.isEmpty())
  228337. name = "<error>";
  228338. s.add (name);
  228339. }
  228340. else
  228341. {
  228342. s.add ("<error>");
  228343. }
  228344. }
  228345. return s;
  228346. }
  228347. int MidiInput::getDefaultDeviceIndex()
  228348. {
  228349. return 0;
  228350. }
  228351. struct MidiPortAndCallback
  228352. {
  228353. MidiInput* input;
  228354. MidiPortAndEndpoint* portAndEndpoint;
  228355. MidiInputCallback* callback;
  228356. MemoryBlock pendingData;
  228357. int pendingBytes;
  228358. double pendingDataTime;
  228359. bool active;
  228360. void processSysex (const uint8*& d, int& size, const double time)
  228361. {
  228362. if (*d == 0xf0)
  228363. {
  228364. pendingBytes = 0;
  228365. pendingDataTime = time;
  228366. }
  228367. pendingData.ensureSize (pendingBytes + size, false);
  228368. uint8* totalMessage = (uint8*) pendingData.getData();
  228369. uint8* dest = totalMessage + pendingBytes;
  228370. while (size > 0)
  228371. {
  228372. if (pendingBytes > 0 && *d >= 0x80)
  228373. {
  228374. if (*d >= 0xfa || *d == 0xf8)
  228375. {
  228376. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  228377. ++d;
  228378. --size;
  228379. }
  228380. else
  228381. {
  228382. if (*d == 0xf7)
  228383. {
  228384. *dest++ = *d++;
  228385. pendingBytes++;
  228386. --size;
  228387. }
  228388. break;
  228389. }
  228390. }
  228391. else
  228392. {
  228393. *dest++ = *d++;
  228394. pendingBytes++;
  228395. --size;
  228396. }
  228397. }
  228398. if (totalMessage [pendingBytes - 1] == 0xf7)
  228399. {
  228400. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  228401. pendingBytes = 0;
  228402. }
  228403. else
  228404. {
  228405. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  228406. }
  228407. }
  228408. };
  228409. namespace CoreMidiCallbacks
  228410. {
  228411. static CriticalSection callbackLock;
  228412. static Array<void*> activeCallbacks;
  228413. }
  228414. static void midiInputProc (const MIDIPacketList* pktlist,
  228415. void* readProcRefCon,
  228416. void* /*srcConnRefCon*/)
  228417. {
  228418. double time = Time::getMillisecondCounterHiRes() * 0.001;
  228419. const double originalTime = time;
  228420. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  228421. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228422. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  228423. {
  228424. const MIDIPacket* packet = &pktlist->packet[0];
  228425. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  228426. {
  228427. const uint8* d = (const uint8*) (packet->data);
  228428. int size = packet->length;
  228429. while (size > 0)
  228430. {
  228431. time = originalTime;
  228432. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  228433. {
  228434. mpc->processSysex (d, size, time);
  228435. }
  228436. else
  228437. {
  228438. int used = 0;
  228439. const MidiMessage m (d, size, used, 0, time);
  228440. if (used <= 0)
  228441. {
  228442. jassertfalse; // malformed midi message
  228443. break;
  228444. }
  228445. else
  228446. {
  228447. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  228448. }
  228449. size -= used;
  228450. d += used;
  228451. }
  228452. }
  228453. packet = MIDIPacketNext (packet);
  228454. }
  228455. }
  228456. }
  228457. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  228458. {
  228459. MidiInput* mi = 0;
  228460. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  228461. {
  228462. MIDIEndpointRef endPoint = MIDIGetSource (index);
  228463. if (endPoint != 0)
  228464. {
  228465. CFStringRef pname;
  228466. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  228467. {
  228468. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  228469. if (makeSureClientExists())
  228470. {
  228471. MIDIPortRef port;
  228472. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  228473. mpc->active = false;
  228474. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  228475. {
  228476. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  228477. {
  228478. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  228479. mpc->callback = callback;
  228480. mpc->pendingBytes = 0;
  228481. mpc->pendingData.ensureSize (128);
  228482. mi = new MidiInput (getDevices() [index]);
  228483. mpc->input = mi;
  228484. mi->internal = mpc;
  228485. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228486. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  228487. }
  228488. else
  228489. {
  228490. OK (MIDIPortDispose (port));
  228491. }
  228492. }
  228493. }
  228494. }
  228495. CFRelease (pname);
  228496. }
  228497. }
  228498. return mi;
  228499. }
  228500. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  228501. {
  228502. MidiInput* mi = 0;
  228503. if (makeSureClientExists())
  228504. {
  228505. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  228506. mpc->active = false;
  228507. MIDIEndpointRef endPoint;
  228508. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  228509. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  228510. {
  228511. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  228512. mpc->callback = callback;
  228513. mpc->pendingBytes = 0;
  228514. mpc->pendingData.ensureSize (128);
  228515. mi = new MidiInput (deviceName);
  228516. mpc->input = mi;
  228517. mi->internal = mpc;
  228518. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228519. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  228520. }
  228521. CFRelease (name);
  228522. }
  228523. return mi;
  228524. }
  228525. MidiInput::MidiInput (const String& name_)
  228526. : name (name_)
  228527. {
  228528. }
  228529. MidiInput::~MidiInput()
  228530. {
  228531. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  228532. mpc->active = false;
  228533. {
  228534. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228535. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  228536. }
  228537. if (mpc->portAndEndpoint->port != 0)
  228538. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  228539. delete mpc->portAndEndpoint;
  228540. delete mpc;
  228541. }
  228542. void MidiInput::start()
  228543. {
  228544. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228545. ((MidiPortAndCallback*) internal)->active = true;
  228546. }
  228547. void MidiInput::stop()
  228548. {
  228549. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228550. ((MidiPortAndCallback*) internal)->active = false;
  228551. }
  228552. #undef log
  228553. #else
  228554. MidiOutput::~MidiOutput()
  228555. {
  228556. }
  228557. void MidiOutput::reset()
  228558. {
  228559. }
  228560. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  228561. {
  228562. return false;
  228563. }
  228564. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  228565. {
  228566. }
  228567. void MidiOutput::sendMessageNow (const MidiMessage& message)
  228568. {
  228569. }
  228570. const StringArray MidiOutput::getDevices()
  228571. {
  228572. return StringArray();
  228573. }
  228574. MidiOutput* MidiOutput::openDevice (int index)
  228575. {
  228576. return 0;
  228577. }
  228578. const StringArray MidiInput::getDevices()
  228579. {
  228580. return StringArray();
  228581. }
  228582. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  228583. {
  228584. return 0;
  228585. }
  228586. #endif
  228587. #endif
  228588. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  228589. #else
  228590. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  228591. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228592. // compiled on its own).
  228593. #if JUCE_INCLUDED_FILE
  228594. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  228595. #define SUPPORT_10_4_FONTS 1
  228596. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  228597. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  228598. #define SUPPORT_ONLY_10_4_FONTS 1
  228599. #endif
  228600. END_JUCE_NAMESPACE
  228601. @interface NSFont (PrivateHack)
  228602. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  228603. @end
  228604. BEGIN_JUCE_NAMESPACE
  228605. #endif
  228606. class MacTypeface : public Typeface
  228607. {
  228608. public:
  228609. MacTypeface (const Font& font)
  228610. : Typeface (font.getTypefaceName())
  228611. {
  228612. const ScopedAutoReleasePool pool;
  228613. renderingTransform = CGAffineTransformIdentity;
  228614. bool needsItalicTransform = false;
  228615. #if JUCE_IOS
  228616. NSString* fontName = juceStringToNS (font.getTypefaceName());
  228617. if (font.isItalic() || font.isBold())
  228618. {
  228619. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  228620. for (NSString* i in familyFonts)
  228621. {
  228622. const String fn (nsStringToJuce (i));
  228623. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  228624. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  228625. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  228626. || afterDash.containsIgnoreCase ("italic")
  228627. || fn.endsWithIgnoreCase ("oblique")
  228628. || fn.endsWithIgnoreCase ("italic");
  228629. if (probablyBold == font.isBold()
  228630. && probablyItalic == font.isItalic())
  228631. {
  228632. fontName = i;
  228633. needsItalicTransform = false;
  228634. break;
  228635. }
  228636. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  228637. {
  228638. fontName = i;
  228639. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  228640. }
  228641. }
  228642. if (needsItalicTransform)
  228643. renderingTransform.c = 0.15f;
  228644. }
  228645. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  228646. const int ascender = abs (CGFontGetAscent (fontRef));
  228647. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  228648. ascent = ascender / totalHeight;
  228649. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228650. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  228651. #else
  228652. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  228653. if (font.isItalic())
  228654. {
  228655. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  228656. toHaveTrait: NSItalicFontMask];
  228657. if (newFont == nsFont)
  228658. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  228659. nsFont = newFont;
  228660. }
  228661. if (font.isBold())
  228662. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  228663. [nsFont retain];
  228664. ascent = std::abs ((float) [nsFont ascender]);
  228665. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  228666. ascent /= totalSize;
  228667. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  228668. if (needsItalicTransform)
  228669. {
  228670. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  228671. renderingTransform.c = 0.15f;
  228672. }
  228673. #if SUPPORT_ONLY_10_4_FONTS
  228674. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228675. if (atsFont == 0)
  228676. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228677. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  228678. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  228679. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228680. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  228681. #else
  228682. #if SUPPORT_10_4_FONTS
  228683. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228684. {
  228685. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228686. if (atsFont == 0)
  228687. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228688. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  228689. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  228690. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228691. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  228692. }
  228693. else
  228694. #endif
  228695. {
  228696. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  228697. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  228698. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228699. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  228700. }
  228701. #endif
  228702. #endif
  228703. }
  228704. ~MacTypeface()
  228705. {
  228706. #if ! JUCE_IOS
  228707. [nsFont release];
  228708. #endif
  228709. if (fontRef != 0)
  228710. CGFontRelease (fontRef);
  228711. }
  228712. float getAscent() const
  228713. {
  228714. return ascent;
  228715. }
  228716. float getDescent() const
  228717. {
  228718. return 1.0f - ascent;
  228719. }
  228720. float getStringWidth (const String& text)
  228721. {
  228722. if (fontRef == 0 || text.isEmpty())
  228723. return 0;
  228724. const int length = text.length();
  228725. HeapBlock <CGGlyph> glyphs;
  228726. createGlyphsForString (text, length, glyphs);
  228727. float x = 0;
  228728. #if SUPPORT_ONLY_10_4_FONTS
  228729. HeapBlock <NSSize> advances (length);
  228730. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  228731. for (int i = 0; i < length; ++i)
  228732. x += advances[i].width;
  228733. #else
  228734. #if SUPPORT_10_4_FONTS
  228735. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228736. {
  228737. HeapBlock <NSSize> advances (length);
  228738. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  228739. for (int i = 0; i < length; ++i)
  228740. x += advances[i].width;
  228741. }
  228742. else
  228743. #endif
  228744. {
  228745. HeapBlock <int> advances (length);
  228746. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  228747. for (int i = 0; i < length; ++i)
  228748. x += advances[i];
  228749. }
  228750. #endif
  228751. return x * unitsToHeightScaleFactor;
  228752. }
  228753. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  228754. {
  228755. xOffsets.add (0);
  228756. if (fontRef == 0 || text.isEmpty())
  228757. return;
  228758. const int length = text.length();
  228759. HeapBlock <CGGlyph> glyphs;
  228760. createGlyphsForString (text, length, glyphs);
  228761. #if SUPPORT_ONLY_10_4_FONTS
  228762. HeapBlock <NSSize> advances (length);
  228763. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  228764. int x = 0;
  228765. for (int i = 0; i < length; ++i)
  228766. {
  228767. x += advances[i].width;
  228768. xOffsets.add (x * unitsToHeightScaleFactor);
  228769. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  228770. }
  228771. #else
  228772. #if SUPPORT_10_4_FONTS
  228773. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228774. {
  228775. HeapBlock <NSSize> advances (length);
  228776. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  228777. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  228778. float x = 0;
  228779. for (int i = 0; i < length; ++i)
  228780. {
  228781. x += advances[i].width;
  228782. xOffsets.add (x * unitsToHeightScaleFactor);
  228783. resultGlyphs.add (nsGlyphs[i]);
  228784. }
  228785. }
  228786. else
  228787. #endif
  228788. {
  228789. HeapBlock <int> advances (length);
  228790. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  228791. {
  228792. int x = 0;
  228793. for (int i = 0; i < length; ++i)
  228794. {
  228795. x += advances [i];
  228796. xOffsets.add (x * unitsToHeightScaleFactor);
  228797. resultGlyphs.add (glyphs[i]);
  228798. }
  228799. }
  228800. }
  228801. #endif
  228802. }
  228803. bool getOutlineForGlyph (int glyphNumber, Path& path)
  228804. {
  228805. #if JUCE_IOS
  228806. return false;
  228807. #else
  228808. if (nsFont == 0)
  228809. return false;
  228810. // we might need to apply a transform to the path, so it mustn't have anything else in it
  228811. jassert (path.isEmpty());
  228812. const ScopedAutoReleasePool pool;
  228813. NSBezierPath* bez = [NSBezierPath bezierPath];
  228814. [bez moveToPoint: NSMakePoint (0, 0)];
  228815. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  228816. inFont: nsFont];
  228817. for (int i = 0; i < [bez elementCount]; ++i)
  228818. {
  228819. NSPoint p[3];
  228820. switch ([bez elementAtIndex: i associatedPoints: p])
  228821. {
  228822. case NSMoveToBezierPathElement:
  228823. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  228824. break;
  228825. case NSLineToBezierPathElement:
  228826. path.lineTo ((float) p[0].x, (float) -p[0].y);
  228827. break;
  228828. case NSCurveToBezierPathElement:
  228829. 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);
  228830. break;
  228831. case NSClosePathBezierPathElement:
  228832. path.closeSubPath();
  228833. break;
  228834. default:
  228835. jassertfalse;
  228836. break;
  228837. }
  228838. }
  228839. path.applyTransform (pathTransform);
  228840. return true;
  228841. #endif
  228842. }
  228843. juce_UseDebuggingNewOperator
  228844. CGFontRef fontRef;
  228845. float fontHeightToCGSizeFactor;
  228846. CGAffineTransform renderingTransform;
  228847. private:
  228848. float ascent, unitsToHeightScaleFactor;
  228849. #if JUCE_IOS
  228850. #else
  228851. NSFont* nsFont;
  228852. AffineTransform pathTransform;
  228853. #endif
  228854. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  228855. {
  228856. #if SUPPORT_10_4_FONTS
  228857. #if ! SUPPORT_ONLY_10_4_FONTS
  228858. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228859. #endif
  228860. {
  228861. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  228862. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  228863. for (int i = 0; i < length; ++i)
  228864. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  228865. return;
  228866. }
  228867. #endif
  228868. #if ! SUPPORT_ONLY_10_4_FONTS
  228869. if (charToGlyphMapper == 0)
  228870. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  228871. glyphs.malloc (length);
  228872. for (int i = 0; i < length; ++i)
  228873. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  228874. #endif
  228875. }
  228876. #if ! SUPPORT_ONLY_10_4_FONTS
  228877. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  228878. class CharToGlyphMapper
  228879. {
  228880. public:
  228881. CharToGlyphMapper (CGFontRef fontRef)
  228882. : segCount (0), endCode (0), startCode (0), idDelta (0),
  228883. idRangeOffset (0), glyphIndexes (0)
  228884. {
  228885. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  228886. if (cmapTable != 0)
  228887. {
  228888. const int numSubtables = getValue16 (cmapTable, 2);
  228889. for (int i = 0; i < numSubtables; ++i)
  228890. {
  228891. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  228892. {
  228893. const int offset = getValue32 (cmapTable, i * 8 + 8);
  228894. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  228895. {
  228896. const int length = getValue16 (cmapTable, offset + 2);
  228897. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  228898. segCount = segCountX2 / 2;
  228899. const int endCodeOffset = offset + 14;
  228900. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  228901. const int idDeltaOffset = startCodeOffset + segCountX2;
  228902. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  228903. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  228904. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  228905. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  228906. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  228907. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  228908. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  228909. }
  228910. break;
  228911. }
  228912. }
  228913. CFRelease (cmapTable);
  228914. }
  228915. }
  228916. ~CharToGlyphMapper()
  228917. {
  228918. if (endCode != 0)
  228919. {
  228920. CFRelease (endCode);
  228921. CFRelease (startCode);
  228922. CFRelease (idDelta);
  228923. CFRelease (idRangeOffset);
  228924. CFRelease (glyphIndexes);
  228925. }
  228926. }
  228927. int getGlyphForCharacter (const juce_wchar c) const
  228928. {
  228929. for (int i = 0; i < segCount; ++i)
  228930. {
  228931. if (getValue16 (endCode, i * 2) >= c)
  228932. {
  228933. const int start = getValue16 (startCode, i * 2);
  228934. if (start > c)
  228935. break;
  228936. const int delta = getValue16 (idDelta, i * 2);
  228937. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  228938. if (rangeOffset == 0)
  228939. return delta + c;
  228940. else
  228941. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  228942. }
  228943. }
  228944. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  228945. return jmax (-1, c - 29);
  228946. }
  228947. private:
  228948. int segCount;
  228949. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  228950. static uint16 getValue16 (CFDataRef data, const int index)
  228951. {
  228952. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  228953. }
  228954. static uint32 getValue32 (CFDataRef data, const int index)
  228955. {
  228956. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  228957. }
  228958. };
  228959. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  228960. #endif
  228961. MacTypeface (const MacTypeface&);
  228962. MacTypeface& operator= (const MacTypeface&);
  228963. };
  228964. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  228965. {
  228966. return new MacTypeface (font);
  228967. }
  228968. const StringArray Font::findAllTypefaceNames()
  228969. {
  228970. StringArray names;
  228971. const ScopedAutoReleasePool pool;
  228972. #if JUCE_IOS
  228973. NSArray* fonts = [UIFont familyNames];
  228974. #else
  228975. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  228976. #endif
  228977. for (unsigned int i = 0; i < [fonts count]; ++i)
  228978. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  228979. names.sort (true);
  228980. return names;
  228981. }
  228982. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  228983. {
  228984. #if JUCE_IOS
  228985. defaultSans = "Helvetica";
  228986. defaultSerif = "Times New Roman";
  228987. defaultFixed = "Courier New";
  228988. #else
  228989. defaultSans = "Lucida Grande";
  228990. defaultSerif = "Times New Roman";
  228991. defaultFixed = "Monaco";
  228992. #endif
  228993. }
  228994. #endif
  228995. /*** End of inlined file: juce_mac_Fonts.mm ***/
  228996. // (must go before juce_mac_CoreGraphicsContext.mm)
  228997. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  228998. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228999. // compiled on its own).
  229000. #if JUCE_INCLUDED_FILE
  229001. class CoreGraphicsImage : public Image::SharedImage
  229002. {
  229003. public:
  229004. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  229005. : Image::SharedImage (format_, width_, height_)
  229006. {
  229007. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  229008. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  229009. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  229010. imageData = imageDataAllocated;
  229011. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  229012. : CGColorSpaceCreateDeviceRGB();
  229013. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  229014. colourSpace, getCGImageFlags (format_));
  229015. CGColorSpaceRelease (colourSpace);
  229016. }
  229017. ~CoreGraphicsImage()
  229018. {
  229019. CGContextRelease (context);
  229020. }
  229021. Image::ImageType getType() const { return Image::NativeImage; }
  229022. LowLevelGraphicsContext* createLowLevelContext();
  229023. SharedImage* clone()
  229024. {
  229025. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  229026. memcpy (im->imageData, imageData, lineStride * height);
  229027. return im;
  229028. }
  229029. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  229030. {
  229031. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  229032. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  229033. {
  229034. return CGBitmapContextCreateImage (nativeImage->context);
  229035. }
  229036. else
  229037. {
  229038. const Image::BitmapData srcData (juceImage, false);
  229039. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  229040. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  229041. 8, srcData.pixelStride * 8, srcData.lineStride,
  229042. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  229043. 0, true, kCGRenderingIntentDefault);
  229044. CGDataProviderRelease (provider);
  229045. return imageRef;
  229046. }
  229047. }
  229048. #if JUCE_MAC
  229049. static NSImage* createNSImage (const Image& image)
  229050. {
  229051. const ScopedAutoReleasePool pool;
  229052. NSImage* im = [[NSImage alloc] init];
  229053. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  229054. [im lockFocus];
  229055. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  229056. CGImageRef imageRef = createImage (image, false, colourSpace);
  229057. CGColorSpaceRelease (colourSpace);
  229058. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  229059. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  229060. CGImageRelease (imageRef);
  229061. [im unlockFocus];
  229062. return im;
  229063. }
  229064. #endif
  229065. CGContextRef context;
  229066. HeapBlock<uint8> imageDataAllocated;
  229067. private:
  229068. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  229069. {
  229070. #if JUCE_BIG_ENDIAN
  229071. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  229072. #else
  229073. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  229074. #endif
  229075. }
  229076. };
  229077. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  229078. {
  229079. #if USE_COREGRAPHICS_RENDERING
  229080. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  229081. #else
  229082. return createSoftwareImage (format, width, height, clearImage);
  229083. #endif
  229084. }
  229085. class CoreGraphicsContext : public LowLevelGraphicsContext
  229086. {
  229087. public:
  229088. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  229089. : context (context_),
  229090. flipHeight (flipHeight_),
  229091. state (new SavedState()),
  229092. numGradientLookupEntries (0),
  229093. lastClipRectIsValid (false)
  229094. {
  229095. CGContextRetain (context);
  229096. CGContextSaveGState(context);
  229097. CGContextSetShouldSmoothFonts (context, true);
  229098. CGContextSetShouldAntialias (context, true);
  229099. CGContextSetBlendMode (context, kCGBlendModeNormal);
  229100. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  229101. greyColourSpace = CGColorSpaceCreateDeviceGray();
  229102. gradientCallbacks.version = 0;
  229103. gradientCallbacks.evaluate = gradientCallback;
  229104. gradientCallbacks.releaseInfo = 0;
  229105. setFont (Font());
  229106. }
  229107. ~CoreGraphicsContext()
  229108. {
  229109. CGContextRestoreGState (context);
  229110. CGContextRelease (context);
  229111. CGColorSpaceRelease (rgbColourSpace);
  229112. CGColorSpaceRelease (greyColourSpace);
  229113. }
  229114. bool isVectorDevice() const { return false; }
  229115. void setOrigin (int x, int y)
  229116. {
  229117. CGContextTranslateCTM (context, x, -y);
  229118. if (lastClipRectIsValid)
  229119. lastClipRect.translate (-x, -y);
  229120. }
  229121. bool clipToRectangle (const Rectangle<int>& r)
  229122. {
  229123. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  229124. if (lastClipRectIsValid)
  229125. {
  229126. lastClipRect = lastClipRect.getIntersection (r);
  229127. return ! lastClipRect.isEmpty();
  229128. }
  229129. return ! isClipEmpty();
  229130. }
  229131. bool clipToRectangleList (const RectangleList& clipRegion)
  229132. {
  229133. if (clipRegion.isEmpty())
  229134. {
  229135. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  229136. lastClipRectIsValid = true;
  229137. lastClipRect = Rectangle<int>();
  229138. return false;
  229139. }
  229140. else
  229141. {
  229142. const int numRects = clipRegion.getNumRectangles();
  229143. HeapBlock <CGRect> rects (numRects);
  229144. for (int i = 0; i < numRects; ++i)
  229145. {
  229146. const Rectangle<int>& r = clipRegion.getRectangle(i);
  229147. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  229148. }
  229149. CGContextClipToRects (context, rects, numRects);
  229150. lastClipRectIsValid = false;
  229151. return ! isClipEmpty();
  229152. }
  229153. }
  229154. void excludeClipRectangle (const Rectangle<int>& r)
  229155. {
  229156. RectangleList remaining (getClipBounds());
  229157. remaining.subtract (r);
  229158. clipToRectangleList (remaining);
  229159. lastClipRectIsValid = false;
  229160. }
  229161. void clipToPath (const Path& path, const AffineTransform& transform)
  229162. {
  229163. createPath (path, transform);
  229164. CGContextClip (context);
  229165. lastClipRectIsValid = false;
  229166. }
  229167. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  229168. {
  229169. if (! transform.isSingularity())
  229170. {
  229171. Image singleChannelImage (sourceImage);
  229172. if (sourceImage.getFormat() != Image::SingleChannel)
  229173. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  229174. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  229175. flip();
  229176. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  229177. applyTransform (t);
  229178. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  229179. CGContextClipToMask (context, r, image);
  229180. applyTransform (t.inverted());
  229181. flip();
  229182. CGImageRelease (image);
  229183. lastClipRectIsValid = false;
  229184. }
  229185. }
  229186. bool clipRegionIntersects (const Rectangle<int>& r)
  229187. {
  229188. return getClipBounds().intersects (r);
  229189. }
  229190. const Rectangle<int> getClipBounds() const
  229191. {
  229192. if (! lastClipRectIsValid)
  229193. {
  229194. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229195. lastClipRectIsValid = true;
  229196. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  229197. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  229198. roundToInt (bounds.size.width),
  229199. roundToInt (bounds.size.height));
  229200. }
  229201. return lastClipRect;
  229202. }
  229203. bool isClipEmpty() const
  229204. {
  229205. return getClipBounds().isEmpty();
  229206. }
  229207. void saveState()
  229208. {
  229209. CGContextSaveGState (context);
  229210. stateStack.add (new SavedState (*state));
  229211. }
  229212. void restoreState()
  229213. {
  229214. CGContextRestoreGState (context);
  229215. SavedState* const top = stateStack.getLast();
  229216. if (top != 0)
  229217. {
  229218. state = top;
  229219. stateStack.removeLast (1, false);
  229220. lastClipRectIsValid = false;
  229221. }
  229222. else
  229223. {
  229224. jassertfalse; // trying to pop with an empty stack!
  229225. }
  229226. }
  229227. void setFill (const FillType& fillType)
  229228. {
  229229. state->fillType = fillType;
  229230. if (fillType.isColour())
  229231. {
  229232. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  229233. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  229234. CGContextSetAlpha (context, 1.0f);
  229235. }
  229236. }
  229237. void setOpacity (float newOpacity)
  229238. {
  229239. state->fillType.setOpacity (newOpacity);
  229240. setFill (state->fillType);
  229241. }
  229242. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  229243. {
  229244. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  229245. ? kCGInterpolationLow
  229246. : kCGInterpolationHigh);
  229247. }
  229248. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  229249. {
  229250. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  229251. if (replaceExistingContents)
  229252. {
  229253. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229254. CGContextClearRect (context, cgRect);
  229255. #else
  229256. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229257. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  229258. CGContextClearRect (context, cgRect);
  229259. else
  229260. #endif
  229261. CGContextSetBlendMode (context, kCGBlendModeCopy);
  229262. #endif
  229263. fillRect (r, false);
  229264. CGContextSetBlendMode (context, kCGBlendModeNormal);
  229265. }
  229266. else
  229267. {
  229268. if (state->fillType.isColour())
  229269. {
  229270. CGContextFillRect (context, cgRect);
  229271. }
  229272. else if (state->fillType.isGradient())
  229273. {
  229274. CGContextSaveGState (context);
  229275. CGContextClipToRect (context, cgRect);
  229276. drawGradient();
  229277. CGContextRestoreGState (context);
  229278. }
  229279. else
  229280. {
  229281. CGContextSaveGState (context);
  229282. CGContextClipToRect (context, cgRect);
  229283. drawImage (state->fillType.image, state->fillType.transform, true);
  229284. CGContextRestoreGState (context);
  229285. }
  229286. }
  229287. }
  229288. void fillPath (const Path& path, const AffineTransform& transform)
  229289. {
  229290. CGContextSaveGState (context);
  229291. if (state->fillType.isColour())
  229292. {
  229293. flip();
  229294. applyTransform (transform);
  229295. createPath (path);
  229296. if (path.isUsingNonZeroWinding())
  229297. CGContextFillPath (context);
  229298. else
  229299. CGContextEOFillPath (context);
  229300. }
  229301. else
  229302. {
  229303. createPath (path, transform);
  229304. if (path.isUsingNonZeroWinding())
  229305. CGContextClip (context);
  229306. else
  229307. CGContextEOClip (context);
  229308. if (state->fillType.isGradient())
  229309. drawGradient();
  229310. else
  229311. drawImage (state->fillType.image, state->fillType.transform, true);
  229312. }
  229313. CGContextRestoreGState (context);
  229314. }
  229315. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  229316. {
  229317. const int iw = sourceImage.getWidth();
  229318. const int ih = sourceImage.getHeight();
  229319. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  229320. CGContextSaveGState (context);
  229321. CGContextSetAlpha (context, state->fillType.getOpacity());
  229322. flip();
  229323. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  229324. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  229325. if (fillEntireClipAsTiles)
  229326. {
  229327. #if JUCE_IOS
  229328. CGContextDrawTiledImage (context, imageRect, image);
  229329. #else
  229330. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  229331. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  229332. // if it's doing a transformation - it's quicker to just draw lots of images manually
  229333. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  229334. CGContextDrawTiledImage (context, imageRect, image);
  229335. else
  229336. #endif
  229337. {
  229338. // Fallback to manually doing a tiled fill on 10.4
  229339. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229340. int x = 0, y = 0;
  229341. while (x > clip.origin.x) x -= iw;
  229342. while (y > clip.origin.y) y -= ih;
  229343. const int right = (int) (clip.origin.x + clip.size.width);
  229344. const int bottom = (int) (clip.origin.y + clip.size.height);
  229345. while (y < bottom)
  229346. {
  229347. for (int x2 = x; x2 < right; x2 += iw)
  229348. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  229349. y += ih;
  229350. }
  229351. }
  229352. #endif
  229353. }
  229354. else
  229355. {
  229356. CGContextDrawImage (context, imageRect, image);
  229357. }
  229358. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  229359. CGContextRestoreGState (context);
  229360. }
  229361. void drawLine (const Line<float>& line)
  229362. {
  229363. CGContextSetLineCap (context, kCGLineCapSquare);
  229364. CGContextSetLineWidth (context, 1.0f);
  229365. CGContextSetRGBStrokeColor (context,
  229366. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  229367. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  229368. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  229369. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  229370. CGContextStrokeLineSegments (context, cgLine, 1);
  229371. }
  229372. void drawVerticalLine (const int x, float top, float bottom)
  229373. {
  229374. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  229375. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  229376. #else
  229377. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  229378. // the x co-ord slightly to trick it..
  229379. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  229380. #endif
  229381. }
  229382. void drawHorizontalLine (const int y, float left, float right)
  229383. {
  229384. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  229385. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  229386. #else
  229387. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  229388. // the x co-ord slightly to trick it..
  229389. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  229390. #endif
  229391. }
  229392. void setFont (const Font& newFont)
  229393. {
  229394. if (state->font != newFont)
  229395. {
  229396. state->fontRef = 0;
  229397. state->font = newFont;
  229398. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  229399. if (mf != 0)
  229400. {
  229401. state->fontRef = mf->fontRef;
  229402. CGContextSetFont (context, state->fontRef);
  229403. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  229404. state->fontTransform = mf->renderingTransform;
  229405. state->fontTransform.a *= state->font.getHorizontalScale();
  229406. CGContextSetTextMatrix (context, state->fontTransform);
  229407. }
  229408. }
  229409. }
  229410. const Font getFont()
  229411. {
  229412. return state->font;
  229413. }
  229414. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  229415. {
  229416. if (state->fontRef != 0 && state->fillType.isColour())
  229417. {
  229418. if (transform.isOnlyTranslation())
  229419. {
  229420. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  229421. CGGlyph g = glyphNumber;
  229422. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  229423. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  229424. }
  229425. else
  229426. {
  229427. CGContextSaveGState (context);
  229428. flip();
  229429. applyTransform (transform);
  229430. CGAffineTransform t = state->fontTransform;
  229431. t.d = -t.d;
  229432. CGContextSetTextMatrix (context, t);
  229433. CGGlyph g = glyphNumber;
  229434. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  229435. CGContextRestoreGState (context);
  229436. }
  229437. }
  229438. else
  229439. {
  229440. Path p;
  229441. Font& f = state->font;
  229442. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  229443. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  229444. .followedBy (transform));
  229445. }
  229446. }
  229447. private:
  229448. CGContextRef context;
  229449. const CGFloat flipHeight;
  229450. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  229451. CGFunctionCallbacks gradientCallbacks;
  229452. mutable Rectangle<int> lastClipRect;
  229453. mutable bool lastClipRectIsValid;
  229454. struct SavedState
  229455. {
  229456. SavedState()
  229457. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  229458. {
  229459. }
  229460. SavedState (const SavedState& other)
  229461. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  229462. fontTransform (other.fontTransform)
  229463. {
  229464. }
  229465. ~SavedState()
  229466. {
  229467. }
  229468. FillType fillType;
  229469. Font font;
  229470. CGFontRef fontRef;
  229471. CGAffineTransform fontTransform;
  229472. };
  229473. ScopedPointer <SavedState> state;
  229474. OwnedArray <SavedState> stateStack;
  229475. HeapBlock <PixelARGB> gradientLookupTable;
  229476. int numGradientLookupEntries;
  229477. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  229478. {
  229479. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  229480. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  229481. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  229482. colour.unpremultiply();
  229483. outData[0] = colour.getRed() / 255.0f;
  229484. outData[1] = colour.getGreen() / 255.0f;
  229485. outData[2] = colour.getBlue() / 255.0f;
  229486. outData[3] = colour.getAlpha() / 255.0f;
  229487. }
  229488. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  229489. {
  229490. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  229491. --numGradientLookupEntries;
  229492. CGShadingRef result = 0;
  229493. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  229494. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  229495. if (gradient.isRadial)
  229496. {
  229497. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  229498. p1, gradient.point1.getDistanceFrom (gradient.point2),
  229499. function, true, true);
  229500. }
  229501. else
  229502. {
  229503. result = CGShadingCreateAxial (rgbColourSpace, p1,
  229504. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  229505. function, true, true);
  229506. }
  229507. CGFunctionRelease (function);
  229508. return result;
  229509. }
  229510. void drawGradient()
  229511. {
  229512. flip();
  229513. applyTransform (state->fillType.transform);
  229514. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  229515. // you draw a gradient with high quality interp enabled).
  229516. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  229517. CGContextSetAlpha (context, state->fillType.getOpacity());
  229518. CGContextDrawShading (context, shading);
  229519. CGShadingRelease (shading);
  229520. }
  229521. void createPath (const Path& path) const
  229522. {
  229523. CGContextBeginPath (context);
  229524. Path::Iterator i (path);
  229525. while (i.next())
  229526. {
  229527. switch (i.elementType)
  229528. {
  229529. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  229530. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  229531. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  229532. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  229533. case Path::Iterator::closePath: CGContextClosePath (context); break;
  229534. default: jassertfalse; break;
  229535. }
  229536. }
  229537. }
  229538. void createPath (const Path& path, const AffineTransform& transform) const
  229539. {
  229540. CGContextBeginPath (context);
  229541. Path::Iterator i (path);
  229542. while (i.next())
  229543. {
  229544. switch (i.elementType)
  229545. {
  229546. case Path::Iterator::startNewSubPath:
  229547. transform.transformPoint (i.x1, i.y1);
  229548. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  229549. break;
  229550. case Path::Iterator::lineTo:
  229551. transform.transformPoint (i.x1, i.y1);
  229552. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  229553. break;
  229554. case Path::Iterator::quadraticTo:
  229555. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  229556. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  229557. break;
  229558. case Path::Iterator::cubicTo:
  229559. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  229560. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  229561. break;
  229562. case Path::Iterator::closePath:
  229563. CGContextClosePath (context); break;
  229564. default:
  229565. jassertfalse;
  229566. break;
  229567. }
  229568. }
  229569. }
  229570. void flip() const
  229571. {
  229572. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  229573. }
  229574. void applyTransform (const AffineTransform& transform) const
  229575. {
  229576. CGAffineTransform t;
  229577. t.a = transform.mat00;
  229578. t.b = transform.mat10;
  229579. t.c = transform.mat01;
  229580. t.d = transform.mat11;
  229581. t.tx = transform.mat02;
  229582. t.ty = transform.mat12;
  229583. CGContextConcatCTM (context, t);
  229584. }
  229585. CoreGraphicsContext (const CoreGraphicsContext&);
  229586. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  229587. };
  229588. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  229589. {
  229590. return new CoreGraphicsContext (context, height);
  229591. }
  229592. #endif
  229593. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  229594. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  229595. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229596. // compiled on its own).
  229597. #if JUCE_INCLUDED_FILE
  229598. class NSViewComponentPeer;
  229599. END_JUCE_NAMESPACE
  229600. @interface NSEvent (JuceDeviceDelta)
  229601. - (float) deviceDeltaX;
  229602. - (float) deviceDeltaY;
  229603. @end
  229604. #define JuceNSView MakeObjCClassName(JuceNSView)
  229605. @interface JuceNSView : NSView<NSTextInput>
  229606. {
  229607. @public
  229608. NSViewComponentPeer* owner;
  229609. NSNotificationCenter* notificationCenter;
  229610. String* stringBeingComposed;
  229611. bool textWasInserted;
  229612. }
  229613. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  229614. - (void) dealloc;
  229615. - (BOOL) isOpaque;
  229616. - (void) drawRect: (NSRect) r;
  229617. - (void) mouseDown: (NSEvent*) ev;
  229618. - (void) asyncMouseDown: (NSEvent*) ev;
  229619. - (void) mouseUp: (NSEvent*) ev;
  229620. - (void) asyncMouseUp: (NSEvent*) ev;
  229621. - (void) mouseDragged: (NSEvent*) ev;
  229622. - (void) mouseMoved: (NSEvent*) ev;
  229623. - (void) mouseEntered: (NSEvent*) ev;
  229624. - (void) mouseExited: (NSEvent*) ev;
  229625. - (void) rightMouseDown: (NSEvent*) ev;
  229626. - (void) rightMouseDragged: (NSEvent*) ev;
  229627. - (void) rightMouseUp: (NSEvent*) ev;
  229628. - (void) otherMouseDown: (NSEvent*) ev;
  229629. - (void) otherMouseDragged: (NSEvent*) ev;
  229630. - (void) otherMouseUp: (NSEvent*) ev;
  229631. - (void) scrollWheel: (NSEvent*) ev;
  229632. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  229633. - (void) frameChanged: (NSNotification*) n;
  229634. - (void) viewDidMoveToWindow;
  229635. - (void) keyDown: (NSEvent*) ev;
  229636. - (void) keyUp: (NSEvent*) ev;
  229637. // NSTextInput Methods
  229638. - (void) insertText: (id) aString;
  229639. - (void) doCommandBySelector: (SEL) aSelector;
  229640. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  229641. - (void) unmarkText;
  229642. - (BOOL) hasMarkedText;
  229643. - (long) conversationIdentifier;
  229644. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  229645. - (NSRange) markedRange;
  229646. - (NSRange) selectedRange;
  229647. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  229648. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  229649. - (NSArray*) validAttributesForMarkedText;
  229650. - (void) flagsChanged: (NSEvent*) ev;
  229651. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229652. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  229653. #endif
  229654. - (BOOL) becomeFirstResponder;
  229655. - (BOOL) resignFirstResponder;
  229656. - (BOOL) acceptsFirstResponder;
  229657. - (void) asyncRepaint: (id) rect;
  229658. - (NSArray*) getSupportedDragTypes;
  229659. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  229660. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  229661. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  229662. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  229663. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  229664. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  229665. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  229666. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  229667. @end
  229668. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  229669. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  229670. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  229671. #else
  229672. @interface JuceNSWindow : NSWindow
  229673. #endif
  229674. {
  229675. @private
  229676. NSViewComponentPeer* owner;
  229677. bool isZooming;
  229678. }
  229679. - (void) setOwner: (NSViewComponentPeer*) owner;
  229680. - (BOOL) canBecomeKeyWindow;
  229681. - (void) becomeKeyWindow;
  229682. - (BOOL) windowShouldClose: (id) window;
  229683. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  229684. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  229685. - (void) zoom: (id) sender;
  229686. @end
  229687. BEGIN_JUCE_NAMESPACE
  229688. class NSViewComponentPeer : public ComponentPeer
  229689. {
  229690. public:
  229691. NSViewComponentPeer (Component* const component,
  229692. const int windowStyleFlags,
  229693. NSView* viewToAttachTo);
  229694. ~NSViewComponentPeer();
  229695. void* getNativeHandle() const;
  229696. void setVisible (bool shouldBeVisible);
  229697. void setTitle (const String& title);
  229698. void setPosition (int x, int y);
  229699. void setSize (int w, int h);
  229700. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  229701. const Rectangle<int> getBounds (const bool global) const;
  229702. const Rectangle<int> getBounds() const;
  229703. const Point<int> getScreenPosition() const;
  229704. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  229705. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  229706. void setMinimised (bool shouldBeMinimised);
  229707. bool isMinimised() const;
  229708. void setFullScreen (bool shouldBeFullScreen);
  229709. bool isFullScreen() const;
  229710. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  229711. const BorderSize getFrameSize() const;
  229712. bool setAlwaysOnTop (bool alwaysOnTop);
  229713. void toFront (bool makeActiveWindow);
  229714. void toBehind (ComponentPeer* other);
  229715. void setIcon (const Image& newIcon);
  229716. const StringArray getAvailableRenderingEngines() throw();
  229717. int getCurrentRenderingEngine() throw();
  229718. void setCurrentRenderingEngine (int index) throw();
  229719. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  229720. for example having more than one juce plugin loaded into a host, then when a
  229721. method is called, the actual code that runs might actually be in a different module
  229722. than the one you expect... So any calls to library functions or statics that are
  229723. made inside obj-c methods will probably end up getting executed in a different DLL's
  229724. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  229725. To work around this insanity, I'm only allowing obj-c methods to make calls to
  229726. virtual methods of an object that's known to live inside the right module's space.
  229727. */
  229728. virtual void redirectMouseDown (NSEvent* ev);
  229729. virtual void redirectMouseUp (NSEvent* ev);
  229730. virtual void redirectMouseDrag (NSEvent* ev);
  229731. virtual void redirectMouseMove (NSEvent* ev);
  229732. virtual void redirectMouseEnter (NSEvent* ev);
  229733. virtual void redirectMouseExit (NSEvent* ev);
  229734. virtual void redirectMouseWheel (NSEvent* ev);
  229735. void sendMouseEvent (NSEvent* ev);
  229736. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  229737. virtual bool redirectKeyDown (NSEvent* ev);
  229738. virtual bool redirectKeyUp (NSEvent* ev);
  229739. virtual void redirectModKeyChange (NSEvent* ev);
  229740. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229741. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  229742. #endif
  229743. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  229744. virtual bool isOpaque();
  229745. virtual void drawRect (NSRect r);
  229746. virtual bool canBecomeKeyWindow();
  229747. virtual bool windowShouldClose();
  229748. virtual void redirectMovedOrResized();
  229749. virtual void viewMovedToWindow();
  229750. virtual NSRect constrainRect (NSRect r);
  229751. static void showArrowCursorIfNeeded();
  229752. static void updateModifiers (NSEvent* e);
  229753. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  229754. static int getKeyCodeFromEvent (NSEvent* ev)
  229755. {
  229756. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  229757. int keyCode = unmodified[0];
  229758. if (keyCode == 0x19) // (backwards-tab)
  229759. keyCode = '\t';
  229760. else if (keyCode == 0x03) // (enter)
  229761. keyCode = '\r';
  229762. return keyCode;
  229763. }
  229764. static int64 getMouseTime (NSEvent* e)
  229765. {
  229766. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  229767. + (int64) ([e timestamp] * 1000.0);
  229768. }
  229769. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  229770. {
  229771. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  229772. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  229773. }
  229774. static int getModifierForButtonNumber (const NSInteger num)
  229775. {
  229776. return num == 0 ? ModifierKeys::leftButtonModifier
  229777. : (num == 1 ? ModifierKeys::rightButtonModifier
  229778. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  229779. }
  229780. virtual void viewFocusGain();
  229781. virtual void viewFocusLoss();
  229782. bool isFocused() const;
  229783. void grabFocus();
  229784. void textInputRequired (const Point<int>& position);
  229785. void repaint (const Rectangle<int>& area);
  229786. void performAnyPendingRepaintsNow();
  229787. juce_UseDebuggingNewOperator
  229788. NSWindow* window;
  229789. JuceNSView* view;
  229790. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  229791. static ModifierKeys currentModifiers;
  229792. static ComponentPeer* currentlyFocusedPeer;
  229793. static Array<int> keysCurrentlyDown;
  229794. };
  229795. END_JUCE_NAMESPACE
  229796. @implementation JuceNSView
  229797. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  229798. withFrame: (NSRect) frame
  229799. {
  229800. [super initWithFrame: frame];
  229801. owner = owner_;
  229802. stringBeingComposed = 0;
  229803. textWasInserted = false;
  229804. notificationCenter = [NSNotificationCenter defaultCenter];
  229805. [notificationCenter addObserver: self
  229806. selector: @selector (frameChanged:)
  229807. name: NSViewFrameDidChangeNotification
  229808. object: self];
  229809. if (! owner_->isSharedWindow)
  229810. {
  229811. [notificationCenter addObserver: self
  229812. selector: @selector (frameChanged:)
  229813. name: NSWindowDidMoveNotification
  229814. object: owner_->window];
  229815. }
  229816. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  229817. return self;
  229818. }
  229819. - (void) dealloc
  229820. {
  229821. [notificationCenter removeObserver: self];
  229822. delete stringBeingComposed;
  229823. [super dealloc];
  229824. }
  229825. - (void) drawRect: (NSRect) r
  229826. {
  229827. if (owner != 0)
  229828. owner->drawRect (r);
  229829. }
  229830. - (BOOL) isOpaque
  229831. {
  229832. return owner == 0 || owner->isOpaque();
  229833. }
  229834. - (void) mouseDown: (NSEvent*) ev
  229835. {
  229836. if (JUCEApplication::isStandaloneApp)
  229837. [self asyncMouseDown: ev];
  229838. else
  229839. // In some host situations, the host will stop modal loops from working
  229840. // correctly if they're called from a mouse event, so we'll trigger
  229841. // the event asynchronously..
  229842. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  229843. withObject: ev
  229844. waitUntilDone: NO];
  229845. }
  229846. - (void) asyncMouseDown: (NSEvent*) ev
  229847. {
  229848. if (owner != 0)
  229849. owner->redirectMouseDown (ev);
  229850. }
  229851. - (void) mouseUp: (NSEvent*) ev
  229852. {
  229853. if (! JUCEApplication::isStandaloneApp)
  229854. [self asyncMouseUp: ev];
  229855. else
  229856. // In some host situations, the host will stop modal loops from working
  229857. // correctly if they're called from a mouse event, so we'll trigger
  229858. // the event asynchronously..
  229859. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  229860. withObject: ev
  229861. waitUntilDone: NO];
  229862. }
  229863. - (void) asyncMouseUp: (NSEvent*) ev
  229864. {
  229865. if (owner != 0)
  229866. owner->redirectMouseUp (ev);
  229867. }
  229868. - (void) mouseDragged: (NSEvent*) ev
  229869. {
  229870. if (owner != 0)
  229871. owner->redirectMouseDrag (ev);
  229872. }
  229873. - (void) mouseMoved: (NSEvent*) ev
  229874. {
  229875. if (owner != 0)
  229876. owner->redirectMouseMove (ev);
  229877. }
  229878. - (void) mouseEntered: (NSEvent*) ev
  229879. {
  229880. if (owner != 0)
  229881. owner->redirectMouseEnter (ev);
  229882. }
  229883. - (void) mouseExited: (NSEvent*) ev
  229884. {
  229885. if (owner != 0)
  229886. owner->redirectMouseExit (ev);
  229887. }
  229888. - (void) rightMouseDown: (NSEvent*) ev
  229889. {
  229890. [self mouseDown: ev];
  229891. }
  229892. - (void) rightMouseDragged: (NSEvent*) ev
  229893. {
  229894. [self mouseDragged: ev];
  229895. }
  229896. - (void) rightMouseUp: (NSEvent*) ev
  229897. {
  229898. [self mouseUp: ev];
  229899. }
  229900. - (void) otherMouseDown: (NSEvent*) ev
  229901. {
  229902. [self mouseDown: ev];
  229903. }
  229904. - (void) otherMouseDragged: (NSEvent*) ev
  229905. {
  229906. [self mouseDragged: ev];
  229907. }
  229908. - (void) otherMouseUp: (NSEvent*) ev
  229909. {
  229910. [self mouseUp: ev];
  229911. }
  229912. - (void) scrollWheel: (NSEvent*) ev
  229913. {
  229914. if (owner != 0)
  229915. owner->redirectMouseWheel (ev);
  229916. }
  229917. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  229918. {
  229919. (void) ev;
  229920. return YES;
  229921. }
  229922. - (void) frameChanged: (NSNotification*) n
  229923. {
  229924. (void) n;
  229925. if (owner != 0)
  229926. owner->redirectMovedOrResized();
  229927. }
  229928. - (void) viewDidMoveToWindow
  229929. {
  229930. if (owner != 0)
  229931. owner->viewMovedToWindow();
  229932. }
  229933. - (void) asyncRepaint: (id) rect
  229934. {
  229935. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  229936. [self setNeedsDisplayInRect: *r];
  229937. }
  229938. - (void) keyDown: (NSEvent*) ev
  229939. {
  229940. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229941. textWasInserted = false;
  229942. if (target != 0)
  229943. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  229944. else
  229945. deleteAndZero (stringBeingComposed);
  229946. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  229947. [super keyDown: ev];
  229948. }
  229949. - (void) keyUp: (NSEvent*) ev
  229950. {
  229951. if (owner == 0 || ! owner->redirectKeyUp (ev))
  229952. [super keyUp: ev];
  229953. }
  229954. - (void) insertText: (id) aString
  229955. {
  229956. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  229957. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  229958. if ([newText length] > 0)
  229959. {
  229960. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229961. if (target != 0)
  229962. {
  229963. target->insertTextAtCaret (nsStringToJuce (newText));
  229964. textWasInserted = true;
  229965. }
  229966. }
  229967. deleteAndZero (stringBeingComposed);
  229968. }
  229969. - (void) doCommandBySelector: (SEL) aSelector
  229970. {
  229971. (void) aSelector;
  229972. }
  229973. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  229974. {
  229975. (void) selectionRange;
  229976. if (stringBeingComposed == 0)
  229977. stringBeingComposed = new String();
  229978. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  229979. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229980. if (target != 0)
  229981. {
  229982. const Range<int> currentHighlight (target->getHighlightedRegion());
  229983. target->insertTextAtCaret (*stringBeingComposed);
  229984. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  229985. textWasInserted = true;
  229986. }
  229987. }
  229988. - (void) unmarkText
  229989. {
  229990. if (stringBeingComposed != 0)
  229991. {
  229992. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229993. if (target != 0)
  229994. {
  229995. target->insertTextAtCaret (*stringBeingComposed);
  229996. textWasInserted = true;
  229997. }
  229998. }
  229999. deleteAndZero (stringBeingComposed);
  230000. }
  230001. - (BOOL) hasMarkedText
  230002. {
  230003. return stringBeingComposed != 0;
  230004. }
  230005. - (long) conversationIdentifier
  230006. {
  230007. return (long) (pointer_sized_int) self;
  230008. }
  230009. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  230010. {
  230011. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230012. if (target != 0)
  230013. {
  230014. const Range<int> r ((int) theRange.location,
  230015. (int) (theRange.location + theRange.length));
  230016. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  230017. }
  230018. return nil;
  230019. }
  230020. - (NSRange) markedRange
  230021. {
  230022. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  230023. : NSMakeRange (NSNotFound, 0);
  230024. }
  230025. - (NSRange) selectedRange
  230026. {
  230027. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230028. if (target != 0)
  230029. {
  230030. const Range<int> highlight (target->getHighlightedRegion());
  230031. if (! highlight.isEmpty())
  230032. return NSMakeRange (highlight.getStart(), highlight.getLength());
  230033. }
  230034. return NSMakeRange (NSNotFound, 0);
  230035. }
  230036. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  230037. {
  230038. (void) theRange;
  230039. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  230040. if (comp == 0)
  230041. return NSMakeRect (0, 0, 0, 0);
  230042. const Rectangle<int> bounds (comp->getScreenBounds());
  230043. return NSMakeRect (bounds.getX(),
  230044. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  230045. bounds.getWidth(),
  230046. bounds.getHeight());
  230047. }
  230048. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  230049. {
  230050. (void) thePoint;
  230051. return NSNotFound;
  230052. }
  230053. - (NSArray*) validAttributesForMarkedText
  230054. {
  230055. return [NSArray array];
  230056. }
  230057. - (void) flagsChanged: (NSEvent*) ev
  230058. {
  230059. if (owner != 0)
  230060. owner->redirectModKeyChange (ev);
  230061. }
  230062. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230063. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  230064. {
  230065. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  230066. return true;
  230067. return [super performKeyEquivalent: ev];
  230068. }
  230069. #endif
  230070. - (BOOL) becomeFirstResponder
  230071. {
  230072. if (owner != 0)
  230073. owner->viewFocusGain();
  230074. return true;
  230075. }
  230076. - (BOOL) resignFirstResponder
  230077. {
  230078. if (owner != 0)
  230079. owner->viewFocusLoss();
  230080. return true;
  230081. }
  230082. - (BOOL) acceptsFirstResponder
  230083. {
  230084. return owner != 0 && owner->canBecomeKeyWindow();
  230085. }
  230086. - (NSArray*) getSupportedDragTypes
  230087. {
  230088. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  230089. }
  230090. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  230091. {
  230092. return owner != 0 && owner->sendDragCallback (type, sender);
  230093. }
  230094. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  230095. {
  230096. if ([self sendDragCallback: 0 sender: sender])
  230097. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  230098. else
  230099. return NSDragOperationNone;
  230100. }
  230101. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  230102. {
  230103. if ([self sendDragCallback: 0 sender: sender])
  230104. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  230105. else
  230106. return NSDragOperationNone;
  230107. }
  230108. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  230109. {
  230110. [self sendDragCallback: 1 sender: sender];
  230111. }
  230112. - (void) draggingExited: (id <NSDraggingInfo>) sender
  230113. {
  230114. [self sendDragCallback: 1 sender: sender];
  230115. }
  230116. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  230117. {
  230118. (void) sender;
  230119. return YES;
  230120. }
  230121. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  230122. {
  230123. return [self sendDragCallback: 2 sender: sender];
  230124. }
  230125. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  230126. {
  230127. (void) sender;
  230128. }
  230129. @end
  230130. @implementation JuceNSWindow
  230131. - (void) setOwner: (NSViewComponentPeer*) owner_
  230132. {
  230133. owner = owner_;
  230134. isZooming = false;
  230135. }
  230136. - (BOOL) canBecomeKeyWindow
  230137. {
  230138. return owner != 0 && owner->canBecomeKeyWindow();
  230139. }
  230140. - (void) becomeKeyWindow
  230141. {
  230142. [super becomeKeyWindow];
  230143. if (owner != 0)
  230144. owner->grabFocus();
  230145. }
  230146. - (BOOL) windowShouldClose: (id) window
  230147. {
  230148. (void) window;
  230149. return owner == 0 || owner->windowShouldClose();
  230150. }
  230151. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  230152. {
  230153. (void) screen;
  230154. if (owner != 0)
  230155. frameRect = owner->constrainRect (frameRect);
  230156. return frameRect;
  230157. }
  230158. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  230159. {
  230160. (void) window;
  230161. if (isZooming)
  230162. return proposedFrameSize;
  230163. NSRect frameRect = [self frame];
  230164. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  230165. frameRect.size = proposedFrameSize;
  230166. if (owner != 0)
  230167. frameRect = owner->constrainRect (frameRect);
  230168. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  230169. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  230170. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  230171. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  230172. return frameRect.size;
  230173. }
  230174. - (void) zoom: (id) sender
  230175. {
  230176. isZooming = true;
  230177. [super zoom: sender];
  230178. isZooming = false;
  230179. }
  230180. - (void) windowWillMove: (NSNotification*) notification
  230181. {
  230182. (void) notification;
  230183. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  230184. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  230185. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  230186. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  230187. }
  230188. @end
  230189. BEGIN_JUCE_NAMESPACE
  230190. ModifierKeys NSViewComponentPeer::currentModifiers;
  230191. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  230192. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  230193. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  230194. {
  230195. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  230196. return true;
  230197. if (keyCode >= 'A' && keyCode <= 'Z'
  230198. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  230199. return true;
  230200. if (keyCode >= 'a' && keyCode <= 'z'
  230201. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  230202. return true;
  230203. return false;
  230204. }
  230205. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  230206. {
  230207. int m = 0;
  230208. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  230209. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  230210. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  230211. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  230212. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  230213. }
  230214. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  230215. {
  230216. updateModifiers (ev);
  230217. int keyCode = getKeyCodeFromEvent (ev);
  230218. if (keyCode != 0)
  230219. {
  230220. if (isKeyDown)
  230221. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  230222. else
  230223. keysCurrentlyDown.removeValue (keyCode);
  230224. }
  230225. }
  230226. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  230227. {
  230228. return NSViewComponentPeer::currentModifiers;
  230229. }
  230230. void ModifierKeys::updateCurrentModifiers() throw()
  230231. {
  230232. currentModifiers = NSViewComponentPeer::currentModifiers;
  230233. }
  230234. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  230235. const int windowStyleFlags,
  230236. NSView* viewToAttachTo)
  230237. : ComponentPeer (component_, windowStyleFlags),
  230238. window (0),
  230239. view (0),
  230240. isSharedWindow (viewToAttachTo != 0),
  230241. fullScreen (false),
  230242. insideDrawRect (false),
  230243. #if USE_COREGRAPHICS_RENDERING
  230244. usingCoreGraphics (true),
  230245. #else
  230246. usingCoreGraphics (false),
  230247. #endif
  230248. recursiveToFrontCall (false)
  230249. {
  230250. NSRect r;
  230251. r.origin.x = 0;
  230252. r.origin.y = 0;
  230253. r.size.width = (float) component->getWidth();
  230254. r.size.height = (float) component->getHeight();
  230255. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  230256. [view setPostsFrameChangedNotifications: YES];
  230257. if (isSharedWindow)
  230258. {
  230259. window = [viewToAttachTo window];
  230260. [viewToAttachTo addSubview: view];
  230261. setVisible (component->isVisible());
  230262. }
  230263. else
  230264. {
  230265. r.origin.x = (float) component->getX();
  230266. r.origin.y = (float) component->getY();
  230267. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  230268. unsigned int style = 0;
  230269. if ((windowStyleFlags & windowHasTitleBar) == 0)
  230270. style = NSBorderlessWindowMask;
  230271. else
  230272. style = NSTitledWindowMask;
  230273. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  230274. style |= NSMiniaturizableWindowMask;
  230275. if ((windowStyleFlags & windowHasCloseButton) != 0)
  230276. style |= NSClosableWindowMask;
  230277. if ((windowStyleFlags & windowIsResizable) != 0)
  230278. style |= NSResizableWindowMask;
  230279. window = [[JuceNSWindow alloc] initWithContentRect: r
  230280. styleMask: style
  230281. backing: NSBackingStoreBuffered
  230282. defer: YES];
  230283. [((JuceNSWindow*) window) setOwner: this];
  230284. [window orderOut: nil];
  230285. [window setDelegate: (JuceNSWindow*) window];
  230286. [window setOpaque: component->isOpaque()];
  230287. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  230288. if (component->isAlwaysOnTop())
  230289. [window setLevel: NSFloatingWindowLevel];
  230290. [window setContentView: view];
  230291. [window setAutodisplay: YES];
  230292. [window setAcceptsMouseMovedEvents: YES];
  230293. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  230294. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  230295. [window setReleasedWhenClosed: YES];
  230296. [window retain];
  230297. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  230298. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  230299. }
  230300. setTitle (component->getName());
  230301. }
  230302. NSViewComponentPeer::~NSViewComponentPeer()
  230303. {
  230304. view->owner = 0;
  230305. [view removeFromSuperview];
  230306. [view release];
  230307. if (! isSharedWindow)
  230308. {
  230309. [((JuceNSWindow*) window) setOwner: 0];
  230310. [window close];
  230311. [window release];
  230312. }
  230313. }
  230314. void* NSViewComponentPeer::getNativeHandle() const
  230315. {
  230316. return view;
  230317. }
  230318. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  230319. {
  230320. if (isSharedWindow)
  230321. {
  230322. [view setHidden: ! shouldBeVisible];
  230323. }
  230324. else
  230325. {
  230326. if (shouldBeVisible)
  230327. {
  230328. [window orderFront: nil];
  230329. handleBroughtToFront();
  230330. }
  230331. else
  230332. {
  230333. [window orderOut: nil];
  230334. }
  230335. }
  230336. }
  230337. void NSViewComponentPeer::setTitle (const String& title)
  230338. {
  230339. const ScopedAutoReleasePool pool;
  230340. if (! isSharedWindow)
  230341. [window setTitle: juceStringToNS (title)];
  230342. }
  230343. void NSViewComponentPeer::setPosition (int x, int y)
  230344. {
  230345. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  230346. }
  230347. void NSViewComponentPeer::setSize (int w, int h)
  230348. {
  230349. setBounds (component->getX(), component->getY(), w, h, false);
  230350. }
  230351. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  230352. {
  230353. fullScreen = isNowFullScreen;
  230354. w = jmax (0, w);
  230355. h = jmax (0, h);
  230356. NSRect r;
  230357. r.origin.x = (float) x;
  230358. r.origin.y = (float) y;
  230359. r.size.width = (float) w;
  230360. r.size.height = (float) h;
  230361. if (isSharedWindow)
  230362. {
  230363. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  230364. if ([view frame].size.width != r.size.width
  230365. || [view frame].size.height != r.size.height)
  230366. [view setNeedsDisplay: true];
  230367. [view setFrame: r];
  230368. }
  230369. else
  230370. {
  230371. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  230372. [window setFrame: [window frameRectForContentRect: r]
  230373. display: true];
  230374. }
  230375. }
  230376. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  230377. {
  230378. NSRect r = [view frame];
  230379. if (global && [view window] != 0)
  230380. {
  230381. r = [view convertRect: r toView: nil];
  230382. NSRect wr = [[view window] frame];
  230383. r.origin.x += wr.origin.x;
  230384. r.origin.y += wr.origin.y;
  230385. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  230386. }
  230387. else
  230388. {
  230389. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  230390. }
  230391. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  230392. }
  230393. const Rectangle<int> NSViewComponentPeer::getBounds() const
  230394. {
  230395. return getBounds (! isSharedWindow);
  230396. }
  230397. const Point<int> NSViewComponentPeer::getScreenPosition() const
  230398. {
  230399. return getBounds (true).getPosition();
  230400. }
  230401. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  230402. {
  230403. return relativePosition + getScreenPosition();
  230404. }
  230405. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  230406. {
  230407. return screenPosition - getScreenPosition();
  230408. }
  230409. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  230410. {
  230411. if (constrainer != 0)
  230412. {
  230413. NSRect current = [window frame];
  230414. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  230415. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  230416. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  230417. (int) r.size.width, (int) r.size.height);
  230418. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  230419. (int) current.size.width, (int) current.size.height);
  230420. constrainer->checkBounds (pos, original,
  230421. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  230422. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  230423. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  230424. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  230425. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  230426. r.origin.x = pos.getX();
  230427. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  230428. r.size.width = pos.getWidth();
  230429. r.size.height = pos.getHeight();
  230430. }
  230431. return r;
  230432. }
  230433. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  230434. {
  230435. if (! isSharedWindow)
  230436. {
  230437. if (shouldBeMinimised)
  230438. [window miniaturize: nil];
  230439. else
  230440. [window deminiaturize: nil];
  230441. }
  230442. }
  230443. bool NSViewComponentPeer::isMinimised() const
  230444. {
  230445. return window != 0 && [window isMiniaturized];
  230446. }
  230447. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  230448. {
  230449. if (! isSharedWindow)
  230450. {
  230451. Rectangle<int> r (lastNonFullscreenBounds);
  230452. setMinimised (false);
  230453. if (fullScreen != shouldBeFullScreen)
  230454. {
  230455. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  230456. {
  230457. fullScreen = true;
  230458. [window performZoom: nil];
  230459. }
  230460. else
  230461. {
  230462. if (shouldBeFullScreen)
  230463. r = Desktop::getInstance().getMainMonitorArea();
  230464. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  230465. if (r != getComponent()->getBounds() && ! r.isEmpty())
  230466. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  230467. }
  230468. }
  230469. }
  230470. }
  230471. bool NSViewComponentPeer::isFullScreen() const
  230472. {
  230473. return fullScreen;
  230474. }
  230475. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  230476. {
  230477. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  230478. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  230479. return false;
  230480. NSPoint p;
  230481. p.x = (float) position.getX();
  230482. p.y = (float) position.getY();
  230483. NSView* v = [view hitTest: p];
  230484. if (trueIfInAChildWindow)
  230485. return v != nil;
  230486. return v == view;
  230487. }
  230488. const BorderSize NSViewComponentPeer::getFrameSize() const
  230489. {
  230490. BorderSize b;
  230491. if (! isSharedWindow)
  230492. {
  230493. NSRect v = [view convertRect: [view frame] toView: nil];
  230494. NSRect w = [window frame];
  230495. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  230496. b.setBottom ((int) v.origin.y);
  230497. b.setLeft ((int) v.origin.x);
  230498. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  230499. }
  230500. return b;
  230501. }
  230502. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  230503. {
  230504. if (! isSharedWindow)
  230505. {
  230506. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  230507. : NSNormalWindowLevel];
  230508. }
  230509. return true;
  230510. }
  230511. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  230512. {
  230513. if (isSharedWindow)
  230514. {
  230515. [[view superview] addSubview: view
  230516. positioned: NSWindowAbove
  230517. relativeTo: nil];
  230518. }
  230519. if (window != 0 && component->isVisible())
  230520. {
  230521. if (makeActiveWindow)
  230522. [window makeKeyAndOrderFront: nil];
  230523. else
  230524. [window orderFront: nil];
  230525. if (! recursiveToFrontCall)
  230526. {
  230527. recursiveToFrontCall = true;
  230528. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  230529. handleBroughtToFront();
  230530. recursiveToFrontCall = false;
  230531. }
  230532. }
  230533. }
  230534. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  230535. {
  230536. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  230537. jassert (otherPeer != 0); // wrong type of window?
  230538. if (otherPeer != 0)
  230539. {
  230540. if (isSharedWindow)
  230541. {
  230542. [[view superview] addSubview: view
  230543. positioned: NSWindowBelow
  230544. relativeTo: otherPeer->view];
  230545. }
  230546. else
  230547. {
  230548. [window orderWindow: NSWindowBelow
  230549. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  230550. : nil ];
  230551. }
  230552. }
  230553. }
  230554. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  230555. {
  230556. // to do..
  230557. }
  230558. void NSViewComponentPeer::viewFocusGain()
  230559. {
  230560. if (currentlyFocusedPeer != this)
  230561. {
  230562. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  230563. currentlyFocusedPeer->handleFocusLoss();
  230564. currentlyFocusedPeer = this;
  230565. handleFocusGain();
  230566. }
  230567. }
  230568. void NSViewComponentPeer::viewFocusLoss()
  230569. {
  230570. if (currentlyFocusedPeer == this)
  230571. {
  230572. currentlyFocusedPeer = 0;
  230573. handleFocusLoss();
  230574. }
  230575. }
  230576. void juce_HandleProcessFocusChange()
  230577. {
  230578. NSViewComponentPeer::keysCurrentlyDown.clear();
  230579. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  230580. {
  230581. if (Process::isForegroundProcess())
  230582. {
  230583. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  230584. ComponentPeer::bringModalComponentToFront();
  230585. }
  230586. else
  230587. {
  230588. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  230589. // turn kiosk mode off if we lose focus..
  230590. Desktop::getInstance().setKioskModeComponent (0);
  230591. }
  230592. }
  230593. }
  230594. bool NSViewComponentPeer::isFocused() const
  230595. {
  230596. return isSharedWindow ? this == currentlyFocusedPeer
  230597. : (window != 0 && [window isKeyWindow]);
  230598. }
  230599. void NSViewComponentPeer::grabFocus()
  230600. {
  230601. if (window != 0)
  230602. {
  230603. [window makeKeyWindow];
  230604. [window makeFirstResponder: view];
  230605. viewFocusGain();
  230606. }
  230607. }
  230608. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  230609. {
  230610. }
  230611. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  230612. {
  230613. String unicode (nsStringToJuce ([ev characters]));
  230614. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  230615. int keyCode = getKeyCodeFromEvent (ev);
  230616. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  230617. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  230618. if (unicode.isNotEmpty() || keyCode != 0)
  230619. {
  230620. if (isKeyDown)
  230621. {
  230622. bool used = false;
  230623. while (unicode.length() > 0)
  230624. {
  230625. juce_wchar textCharacter = unicode[0];
  230626. unicode = unicode.substring (1);
  230627. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  230628. textCharacter = 0;
  230629. used = handleKeyUpOrDown (true) || used;
  230630. used = handleKeyPress (keyCode, textCharacter) || used;
  230631. }
  230632. return used;
  230633. }
  230634. else
  230635. {
  230636. if (handleKeyUpOrDown (false))
  230637. return true;
  230638. }
  230639. }
  230640. return false;
  230641. }
  230642. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  230643. {
  230644. updateKeysDown (ev, true);
  230645. bool used = handleKeyEvent (ev, true);
  230646. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  230647. {
  230648. // for command keys, the key-up event is thrown away, so simulate one..
  230649. updateKeysDown (ev, false);
  230650. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  230651. }
  230652. // (If we're running modally, don't allow unused keystrokes to be passed
  230653. // along to other blocked views..)
  230654. if (Component::getCurrentlyModalComponent() != 0)
  230655. used = true;
  230656. return used;
  230657. }
  230658. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  230659. {
  230660. updateKeysDown (ev, false);
  230661. return handleKeyEvent (ev, false)
  230662. || Component::getCurrentlyModalComponent() != 0;
  230663. }
  230664. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  230665. {
  230666. keysCurrentlyDown.clear();
  230667. handleKeyUpOrDown (true);
  230668. updateModifiers (ev);
  230669. handleModifierKeysChange();
  230670. }
  230671. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230672. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  230673. {
  230674. if ([ev type] == NSKeyDown)
  230675. return redirectKeyDown (ev);
  230676. else if ([ev type] == NSKeyUp)
  230677. return redirectKeyUp (ev);
  230678. return false;
  230679. }
  230680. #endif
  230681. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  230682. {
  230683. updateModifiers (ev);
  230684. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  230685. }
  230686. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  230687. {
  230688. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230689. sendMouseEvent (ev);
  230690. }
  230691. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  230692. {
  230693. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230694. sendMouseEvent (ev);
  230695. showArrowCursorIfNeeded();
  230696. }
  230697. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  230698. {
  230699. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230700. sendMouseEvent (ev);
  230701. }
  230702. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  230703. {
  230704. currentModifiers = currentModifiers.withoutMouseButtons();
  230705. sendMouseEvent (ev);
  230706. showArrowCursorIfNeeded();
  230707. }
  230708. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  230709. {
  230710. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  230711. currentModifiers = currentModifiers.withoutMouseButtons();
  230712. sendMouseEvent (ev);
  230713. }
  230714. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  230715. {
  230716. currentModifiers = currentModifiers.withoutMouseButtons();
  230717. sendMouseEvent (ev);
  230718. }
  230719. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  230720. {
  230721. updateModifiers (ev);
  230722. float x = 0, y = 0;
  230723. @try
  230724. {
  230725. x = [ev deviceDeltaX] * 0.5f;
  230726. y = [ev deviceDeltaY] * 0.5f;
  230727. }
  230728. @catch (...)
  230729. {}
  230730. if (x == 0 && y == 0)
  230731. {
  230732. x = [ev deltaX] * 10.0f;
  230733. y = [ev deltaY] * 10.0f;
  230734. }
  230735. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  230736. }
  230737. void NSViewComponentPeer::showArrowCursorIfNeeded()
  230738. {
  230739. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  230740. if (mouse.getComponentUnderMouse() == 0
  230741. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  230742. {
  230743. [[NSCursor arrowCursor] set];
  230744. }
  230745. }
  230746. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  230747. {
  230748. NSString* bestType
  230749. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  230750. if (bestType == nil)
  230751. return false;
  230752. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  230753. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  230754. StringArray files;
  230755. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  230756. if (list == nil)
  230757. return false;
  230758. if ([list isKindOfClass: [NSArray class]])
  230759. {
  230760. NSArray* items = (NSArray*) list;
  230761. for (unsigned int i = 0; i < [items count]; ++i)
  230762. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  230763. }
  230764. if (files.size() == 0)
  230765. return false;
  230766. if (type == 0)
  230767. handleFileDragMove (files, pos);
  230768. else if (type == 1)
  230769. handleFileDragExit (files);
  230770. else if (type == 2)
  230771. handleFileDragDrop (files, pos);
  230772. return true;
  230773. }
  230774. bool NSViewComponentPeer::isOpaque()
  230775. {
  230776. return component == 0 || component->isOpaque();
  230777. }
  230778. void NSViewComponentPeer::drawRect (NSRect r)
  230779. {
  230780. if (r.size.width < 1.0f || r.size.height < 1.0f)
  230781. return;
  230782. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230783. if (! component->isOpaque())
  230784. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  230785. #if USE_COREGRAPHICS_RENDERING
  230786. if (usingCoreGraphics)
  230787. {
  230788. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  230789. insideDrawRect = true;
  230790. handlePaint (context);
  230791. insideDrawRect = false;
  230792. }
  230793. else
  230794. #endif
  230795. {
  230796. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  230797. (int) (r.size.width + 0.5f),
  230798. (int) (r.size.height + 0.5f),
  230799. ! getComponent()->isOpaque());
  230800. const int xOffset = -roundToInt (r.origin.x);
  230801. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  230802. const NSRect* rects = 0;
  230803. NSInteger numRects = 0;
  230804. [view getRectsBeingDrawn: &rects count: &numRects];
  230805. const Rectangle<int> clipBounds (temp.getBounds());
  230806. RectangleList clip;
  230807. for (int i = 0; i < numRects; ++i)
  230808. {
  230809. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  230810. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  230811. roundToInt (rects[i].size.width),
  230812. roundToInt (rects[i].size.height))));
  230813. }
  230814. if (! clip.isEmpty())
  230815. {
  230816. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  230817. insideDrawRect = true;
  230818. handlePaint (context);
  230819. insideDrawRect = false;
  230820. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230821. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  230822. CGColorSpaceRelease (colourSpace);
  230823. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  230824. CGImageRelease (image);
  230825. }
  230826. }
  230827. }
  230828. const StringArray NSViewComponentPeer::getAvailableRenderingEngines() throw()
  230829. {
  230830. StringArray s;
  230831. s.add ("Software Renderer");
  230832. #if USE_COREGRAPHICS_RENDERING
  230833. s.add ("CoreGraphics Renderer");
  230834. #endif
  230835. return s;
  230836. }
  230837. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  230838. {
  230839. return usingCoreGraphics ? 1 : 0;
  230840. }
  230841. void NSViewComponentPeer::setCurrentRenderingEngine (int index) throw()
  230842. {
  230843. #if USE_COREGRAPHICS_RENDERING
  230844. if (usingCoreGraphics != (index > 0))
  230845. {
  230846. usingCoreGraphics = index > 0;
  230847. [view setNeedsDisplay: true];
  230848. }
  230849. #endif
  230850. }
  230851. bool NSViewComponentPeer::canBecomeKeyWindow()
  230852. {
  230853. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  230854. }
  230855. bool NSViewComponentPeer::windowShouldClose()
  230856. {
  230857. if (! isValidPeer (this))
  230858. return YES;
  230859. handleUserClosingWindow();
  230860. return NO;
  230861. }
  230862. void NSViewComponentPeer::redirectMovedOrResized()
  230863. {
  230864. handleMovedOrResized();
  230865. }
  230866. void NSViewComponentPeer::viewMovedToWindow()
  230867. {
  230868. if (isSharedWindow)
  230869. window = [view window];
  230870. }
  230871. void Desktop::createMouseInputSources()
  230872. {
  230873. mouseSources.add (new MouseInputSource (0, true));
  230874. }
  230875. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  230876. {
  230877. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  230878. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  230879. // is apparently still available in 64-bit apps..
  230880. if (enableOrDisable)
  230881. {
  230882. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  230883. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  230884. }
  230885. else
  230886. {
  230887. SetSystemUIMode (kUIModeNormal, 0);
  230888. }
  230889. }
  230890. class AsyncRepaintMessage : public CallbackMessage
  230891. {
  230892. public:
  230893. NSViewComponentPeer* const peer;
  230894. const Rectangle<int> rect;
  230895. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  230896. : peer (peer_), rect (rect_)
  230897. {
  230898. }
  230899. void messageCallback()
  230900. {
  230901. if (ComponentPeer::isValidPeer (peer))
  230902. peer->repaint (rect);
  230903. }
  230904. };
  230905. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  230906. {
  230907. if (insideDrawRect)
  230908. {
  230909. (new AsyncRepaintMessage (this, area))->post();
  230910. }
  230911. else
  230912. {
  230913. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  230914. (float) area.getWidth(), (float) area.getHeight())];
  230915. }
  230916. }
  230917. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  230918. {
  230919. [view displayIfNeeded];
  230920. }
  230921. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  230922. {
  230923. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  230924. }
  230925. const Image juce_createIconForFile (const File& file)
  230926. {
  230927. const ScopedAutoReleasePool pool;
  230928. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  230929. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  230930. [NSGraphicsContext saveGraphicsState];
  230931. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  230932. [image drawAtPoint: NSMakePoint (0, 0)
  230933. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  230934. operation: NSCompositeSourceOver fraction: 1.0f];
  230935. [[NSGraphicsContext currentContext] flushGraphics];
  230936. [NSGraphicsContext restoreGraphicsState];
  230937. return Image (result);
  230938. }
  230939. const int KeyPress::spaceKey = ' ';
  230940. const int KeyPress::returnKey = 0x0d;
  230941. const int KeyPress::escapeKey = 0x1b;
  230942. const int KeyPress::backspaceKey = 0x7f;
  230943. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  230944. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  230945. const int KeyPress::upKey = NSUpArrowFunctionKey;
  230946. const int KeyPress::downKey = NSDownArrowFunctionKey;
  230947. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  230948. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  230949. const int KeyPress::endKey = NSEndFunctionKey;
  230950. const int KeyPress::homeKey = NSHomeFunctionKey;
  230951. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  230952. const int KeyPress::insertKey = -1;
  230953. const int KeyPress::tabKey = 9;
  230954. const int KeyPress::F1Key = NSF1FunctionKey;
  230955. const int KeyPress::F2Key = NSF2FunctionKey;
  230956. const int KeyPress::F3Key = NSF3FunctionKey;
  230957. const int KeyPress::F4Key = NSF4FunctionKey;
  230958. const int KeyPress::F5Key = NSF5FunctionKey;
  230959. const int KeyPress::F6Key = NSF6FunctionKey;
  230960. const int KeyPress::F7Key = NSF7FunctionKey;
  230961. const int KeyPress::F8Key = NSF8FunctionKey;
  230962. const int KeyPress::F9Key = NSF9FunctionKey;
  230963. const int KeyPress::F10Key = NSF10FunctionKey;
  230964. const int KeyPress::F11Key = NSF1FunctionKey;
  230965. const int KeyPress::F12Key = NSF12FunctionKey;
  230966. const int KeyPress::F13Key = NSF13FunctionKey;
  230967. const int KeyPress::F14Key = NSF14FunctionKey;
  230968. const int KeyPress::F15Key = NSF15FunctionKey;
  230969. const int KeyPress::F16Key = NSF16FunctionKey;
  230970. const int KeyPress::numberPad0 = 0x30020;
  230971. const int KeyPress::numberPad1 = 0x30021;
  230972. const int KeyPress::numberPad2 = 0x30022;
  230973. const int KeyPress::numberPad3 = 0x30023;
  230974. const int KeyPress::numberPad4 = 0x30024;
  230975. const int KeyPress::numberPad5 = 0x30025;
  230976. const int KeyPress::numberPad6 = 0x30026;
  230977. const int KeyPress::numberPad7 = 0x30027;
  230978. const int KeyPress::numberPad8 = 0x30028;
  230979. const int KeyPress::numberPad9 = 0x30029;
  230980. const int KeyPress::numberPadAdd = 0x3002a;
  230981. const int KeyPress::numberPadSubtract = 0x3002b;
  230982. const int KeyPress::numberPadMultiply = 0x3002c;
  230983. const int KeyPress::numberPadDivide = 0x3002d;
  230984. const int KeyPress::numberPadSeparator = 0x3002e;
  230985. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  230986. const int KeyPress::numberPadEquals = 0x30030;
  230987. const int KeyPress::numberPadDelete = 0x30031;
  230988. const int KeyPress::playKey = 0x30000;
  230989. const int KeyPress::stopKey = 0x30001;
  230990. const int KeyPress::fastForwardKey = 0x30002;
  230991. const int KeyPress::rewindKey = 0x30003;
  230992. #endif
  230993. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230994. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  230995. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230996. // compiled on its own).
  230997. #if JUCE_INCLUDED_FILE
  230998. #if JUCE_MAC
  230999. namespace MouseCursorHelpers
  231000. {
  231001. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  231002. {
  231003. NSImage* im = CoreGraphicsImage::createNSImage (image);
  231004. NSCursor* c = [[NSCursor alloc] initWithImage: im
  231005. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  231006. [im release];
  231007. return c;
  231008. }
  231009. static void* fromWebKitFile (const char* filename, float hx, float hy)
  231010. {
  231011. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  231012. BufferedInputStream buf (&fileStream, 4096, false);
  231013. PNGImageFormat pngFormat;
  231014. Image im (pngFormat.decodeImage (buf));
  231015. if (im.isValid())
  231016. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  231017. jassertfalse;
  231018. return 0;
  231019. }
  231020. }
  231021. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  231022. {
  231023. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  231024. }
  231025. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  231026. {
  231027. const ScopedAutoReleasePool pool;
  231028. NSCursor* c = 0;
  231029. switch (type)
  231030. {
  231031. case NormalCursor: c = [NSCursor arrowCursor]; break;
  231032. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  231033. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  231034. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  231035. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  231036. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  231037. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  231038. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  231039. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  231040. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  231041. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  231042. case UpDownResizeCursor:
  231043. case TopEdgeResizeCursor:
  231044. case BottomEdgeResizeCursor:
  231045. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  231046. case TopLeftCornerResizeCursor:
  231047. case BottomRightCornerResizeCursor:
  231048. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  231049. case TopRightCornerResizeCursor:
  231050. case BottomLeftCornerResizeCursor:
  231051. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  231052. case UpDownLeftRightResizeCursor:
  231053. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  231054. default:
  231055. jassertfalse;
  231056. break;
  231057. }
  231058. [c retain];
  231059. return c;
  231060. }
  231061. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  231062. {
  231063. [((NSCursor*) cursorHandle) release];
  231064. }
  231065. void MouseCursor::showInAllWindows() const
  231066. {
  231067. showInWindow (0);
  231068. }
  231069. void MouseCursor::showInWindow (ComponentPeer*) const
  231070. {
  231071. [((NSCursor*) getHandle()) set];
  231072. }
  231073. #else
  231074. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  231075. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  231076. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  231077. void MouseCursor::showInAllWindows() const {}
  231078. void MouseCursor::showInWindow (ComponentPeer*) const {}
  231079. #endif
  231080. #endif
  231081. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  231082. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  231083. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231084. // compiled on its own).
  231085. #if JUCE_INCLUDED_FILE
  231086. class NSViewComponentInternal : public ComponentMovementWatcher
  231087. {
  231088. Component* const owner;
  231089. NSViewComponentPeer* currentPeer;
  231090. bool wasShowing;
  231091. public:
  231092. NSView* const view;
  231093. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  231094. : ComponentMovementWatcher (owner_),
  231095. owner (owner_),
  231096. currentPeer (0),
  231097. wasShowing (false),
  231098. view (view_)
  231099. {
  231100. [view_ retain];
  231101. if (owner_->isShowing())
  231102. componentPeerChanged();
  231103. }
  231104. ~NSViewComponentInternal()
  231105. {
  231106. [view removeFromSuperview];
  231107. [view release];
  231108. }
  231109. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  231110. {
  231111. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  231112. // The ComponentMovementWatcher version of this method avoids calling
  231113. // us when the top-level comp is resized, but for an NSView we need to know this
  231114. // because with inverted co-ords, we need to update the position even if the
  231115. // top-left pos hasn't changed
  231116. if (comp.isOnDesktop() && wasResized)
  231117. componentMovedOrResized (wasMoved, wasResized);
  231118. }
  231119. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  231120. {
  231121. Component* const topComp = owner->getTopLevelComponent();
  231122. if (topComp->getPeer() != 0)
  231123. {
  231124. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  231125. NSRect r;
  231126. r.origin.x = (float) pos.getX();
  231127. r.origin.y = (float) pos.getY();
  231128. r.size.width = (float) owner->getWidth();
  231129. r.size.height = (float) owner->getHeight();
  231130. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231131. [view setFrame: r];
  231132. }
  231133. }
  231134. void componentPeerChanged()
  231135. {
  231136. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  231137. if (currentPeer != peer)
  231138. {
  231139. [view removeFromSuperview];
  231140. currentPeer = peer;
  231141. if (peer != 0)
  231142. {
  231143. [peer->view addSubview: view];
  231144. componentMovedOrResized (false, false);
  231145. }
  231146. }
  231147. [view setHidden: ! owner->isShowing()];
  231148. }
  231149. void componentVisibilityChanged (Component&)
  231150. {
  231151. componentPeerChanged();
  231152. }
  231153. juce_UseDebuggingNewOperator
  231154. private:
  231155. NSViewComponentInternal (const NSViewComponentInternal&);
  231156. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  231157. };
  231158. NSViewComponent::NSViewComponent()
  231159. {
  231160. }
  231161. NSViewComponent::~NSViewComponent()
  231162. {
  231163. }
  231164. void NSViewComponent::setView (void* view)
  231165. {
  231166. if (view != getView())
  231167. {
  231168. if (view != 0)
  231169. info = new NSViewComponentInternal ((NSView*) view, this);
  231170. else
  231171. info = 0;
  231172. }
  231173. }
  231174. void* NSViewComponent::getView() const
  231175. {
  231176. return info == 0 ? 0 : info->view;
  231177. }
  231178. void NSViewComponent::paint (Graphics&)
  231179. {
  231180. }
  231181. #endif
  231182. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  231183. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  231184. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231185. // compiled on its own).
  231186. #if JUCE_INCLUDED_FILE
  231187. AppleRemoteDevice::AppleRemoteDevice()
  231188. : device (0),
  231189. queue (0),
  231190. remoteId (0)
  231191. {
  231192. }
  231193. AppleRemoteDevice::~AppleRemoteDevice()
  231194. {
  231195. stop();
  231196. }
  231197. static io_object_t getAppleRemoteDevice()
  231198. {
  231199. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  231200. io_iterator_t iter = 0;
  231201. io_object_t iod = 0;
  231202. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  231203. && iter != 0)
  231204. {
  231205. iod = IOIteratorNext (iter);
  231206. }
  231207. IOObjectRelease (iter);
  231208. return iod;
  231209. }
  231210. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  231211. {
  231212. jassert (*device == 0);
  231213. io_name_t classname;
  231214. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  231215. {
  231216. IOCFPlugInInterface** cfPlugInInterface = 0;
  231217. SInt32 score = 0;
  231218. if (IOCreatePlugInInterfaceForService (iod,
  231219. kIOHIDDeviceUserClientTypeID,
  231220. kIOCFPlugInInterfaceID,
  231221. &cfPlugInInterface,
  231222. &score) == kIOReturnSuccess)
  231223. {
  231224. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  231225. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  231226. device);
  231227. (void) hr;
  231228. (*cfPlugInInterface)->Release (cfPlugInInterface);
  231229. }
  231230. }
  231231. return *device != 0;
  231232. }
  231233. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  231234. {
  231235. if (queue != 0)
  231236. return true;
  231237. stop();
  231238. bool result = false;
  231239. io_object_t iod = getAppleRemoteDevice();
  231240. if (iod != 0)
  231241. {
  231242. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  231243. result = true;
  231244. else
  231245. stop();
  231246. IOObjectRelease (iod);
  231247. }
  231248. return result;
  231249. }
  231250. void AppleRemoteDevice::stop()
  231251. {
  231252. if (queue != 0)
  231253. {
  231254. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  231255. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  231256. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  231257. queue = 0;
  231258. }
  231259. if (device != 0)
  231260. {
  231261. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  231262. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  231263. device = 0;
  231264. }
  231265. }
  231266. bool AppleRemoteDevice::isActive() const
  231267. {
  231268. return queue != 0;
  231269. }
  231270. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  231271. {
  231272. if (result == kIOReturnSuccess)
  231273. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  231274. }
  231275. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  231276. {
  231277. Array <int> cookies;
  231278. CFArrayRef elements;
  231279. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  231280. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  231281. return false;
  231282. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  231283. {
  231284. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  231285. // get the cookie
  231286. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  231287. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  231288. continue;
  231289. long number;
  231290. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  231291. continue;
  231292. cookies.add ((int) number);
  231293. }
  231294. CFRelease (elements);
  231295. if ((*(IOHIDDeviceInterface**) device)
  231296. ->open ((IOHIDDeviceInterface**) device,
  231297. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  231298. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  231299. {
  231300. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  231301. if (queue != 0)
  231302. {
  231303. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  231304. for (int i = 0; i < cookies.size(); ++i)
  231305. {
  231306. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  231307. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  231308. }
  231309. CFRunLoopSourceRef eventSource;
  231310. if ((*(IOHIDQueueInterface**) queue)
  231311. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  231312. {
  231313. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  231314. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  231315. {
  231316. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  231317. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  231318. return true;
  231319. }
  231320. }
  231321. }
  231322. }
  231323. return false;
  231324. }
  231325. void AppleRemoteDevice::handleCallbackInternal()
  231326. {
  231327. int totalValues = 0;
  231328. AbsoluteTime nullTime = { 0, 0 };
  231329. char cookies [12];
  231330. int numCookies = 0;
  231331. while (numCookies < numElementsInArray (cookies))
  231332. {
  231333. IOHIDEventStruct e;
  231334. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  231335. break;
  231336. if ((int) e.elementCookie == 19)
  231337. {
  231338. remoteId = e.value;
  231339. buttonPressed (switched, false);
  231340. }
  231341. else
  231342. {
  231343. totalValues += e.value;
  231344. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  231345. }
  231346. }
  231347. cookies [numCookies++] = 0;
  231348. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  231349. static const char buttonPatterns[] =
  231350. {
  231351. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  231352. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  231353. 0x1f, 0x1d, 0x1c, 0x12, 0,
  231354. 0x1f, 0x1e, 0x1c, 0x12, 0,
  231355. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  231356. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  231357. 0x1f, 0x12, 0x04, 0x02, 0,
  231358. 0x1f, 0x12, 0x03, 0x02, 0,
  231359. 0x1f, 0x12, 0x1f, 0x12, 0,
  231360. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  231361. 19, 0
  231362. };
  231363. int buttonNum = (int) menuButton;
  231364. int i = 0;
  231365. while (i < numElementsInArray (buttonPatterns))
  231366. {
  231367. if (strcmp (cookies, buttonPatterns + i) == 0)
  231368. {
  231369. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  231370. break;
  231371. }
  231372. i += (int) strlen (buttonPatterns + i) + 1;
  231373. ++buttonNum;
  231374. }
  231375. }
  231376. #endif
  231377. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  231378. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  231379. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231380. // compiled on its own).
  231381. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  231382. #if JUCE_MAC
  231383. END_JUCE_NAMESPACE
  231384. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  231385. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  231386. {
  231387. CriticalSection* contextLock;
  231388. bool needsUpdate;
  231389. }
  231390. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  231391. - (bool) makeActive;
  231392. - (void) makeInactive;
  231393. - (void) reshape;
  231394. @end
  231395. @implementation ThreadSafeNSOpenGLView
  231396. - (id) initWithFrame: (NSRect) frameRect
  231397. pixelFormat: (NSOpenGLPixelFormat*) format
  231398. {
  231399. contextLock = new CriticalSection();
  231400. self = [super initWithFrame: frameRect pixelFormat: format];
  231401. if (self != nil)
  231402. [[NSNotificationCenter defaultCenter] addObserver: self
  231403. selector: @selector (_surfaceNeedsUpdate:)
  231404. name: NSViewGlobalFrameDidChangeNotification
  231405. object: self];
  231406. return self;
  231407. }
  231408. - (void) dealloc
  231409. {
  231410. [[NSNotificationCenter defaultCenter] removeObserver: self];
  231411. delete contextLock;
  231412. [super dealloc];
  231413. }
  231414. - (bool) makeActive
  231415. {
  231416. const ScopedLock sl (*contextLock);
  231417. if ([self openGLContext] == 0)
  231418. return false;
  231419. [[self openGLContext] makeCurrentContext];
  231420. if (needsUpdate)
  231421. {
  231422. [super update];
  231423. needsUpdate = false;
  231424. }
  231425. return true;
  231426. }
  231427. - (void) makeInactive
  231428. {
  231429. const ScopedLock sl (*contextLock);
  231430. [NSOpenGLContext clearCurrentContext];
  231431. }
  231432. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  231433. {
  231434. const ScopedLock sl (*contextLock);
  231435. needsUpdate = true;
  231436. }
  231437. - (void) update
  231438. {
  231439. const ScopedLock sl (*contextLock);
  231440. needsUpdate = true;
  231441. }
  231442. - (void) reshape
  231443. {
  231444. const ScopedLock sl (*contextLock);
  231445. needsUpdate = true;
  231446. }
  231447. @end
  231448. BEGIN_JUCE_NAMESPACE
  231449. class WindowedGLContext : public OpenGLContext
  231450. {
  231451. public:
  231452. WindowedGLContext (Component* const component,
  231453. const OpenGLPixelFormat& pixelFormat_,
  231454. NSOpenGLContext* sharedContext)
  231455. : renderContext (0),
  231456. pixelFormat (pixelFormat_)
  231457. {
  231458. jassert (component != 0);
  231459. NSOpenGLPixelFormatAttribute attribs [64];
  231460. int n = 0;
  231461. attribs[n++] = NSOpenGLPFADoubleBuffer;
  231462. attribs[n++] = NSOpenGLPFAAccelerated;
  231463. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  231464. attribs[n++] = NSOpenGLPFAColorSize;
  231465. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  231466. pixelFormat.greenBits,
  231467. pixelFormat.blueBits);
  231468. attribs[n++] = NSOpenGLPFAAlphaSize;
  231469. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  231470. attribs[n++] = NSOpenGLPFADepthSize;
  231471. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  231472. attribs[n++] = NSOpenGLPFAStencilSize;
  231473. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  231474. attribs[n++] = NSOpenGLPFAAccumSize;
  231475. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  231476. pixelFormat.accumulationBufferGreenBits,
  231477. pixelFormat.accumulationBufferBlueBits,
  231478. pixelFormat.accumulationBufferAlphaBits);
  231479. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  231480. attribs[n++] = NSOpenGLPFASampleBuffers;
  231481. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  231482. attribs[n++] = NSOpenGLPFAClosestPolicy;
  231483. attribs[n++] = NSOpenGLPFANoRecovery;
  231484. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  231485. NSOpenGLPixelFormat* format
  231486. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  231487. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  231488. pixelFormat: format];
  231489. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  231490. shareContext: sharedContext] autorelease];
  231491. const GLint swapInterval = 1;
  231492. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  231493. [view setOpenGLContext: renderContext];
  231494. [renderContext setView: view];
  231495. [format release];
  231496. viewHolder = new NSViewComponentInternal (view, component);
  231497. }
  231498. ~WindowedGLContext()
  231499. {
  231500. deleteContext();
  231501. viewHolder = 0;
  231502. }
  231503. void deleteContext()
  231504. {
  231505. makeInactive();
  231506. [renderContext clearDrawable];
  231507. [renderContext setView: nil];
  231508. [view setOpenGLContext: nil];
  231509. renderContext = nil;
  231510. }
  231511. bool makeActive() const throw()
  231512. {
  231513. jassert (renderContext != 0);
  231514. [view makeActive];
  231515. return isActive();
  231516. }
  231517. bool makeInactive() const throw()
  231518. {
  231519. [view makeInactive];
  231520. return true;
  231521. }
  231522. bool isActive() const throw()
  231523. {
  231524. return [NSOpenGLContext currentContext] == renderContext;
  231525. }
  231526. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  231527. void* getRawContext() const throw() { return renderContext; }
  231528. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  231529. {
  231530. }
  231531. void swapBuffers()
  231532. {
  231533. [renderContext flushBuffer];
  231534. }
  231535. bool setSwapInterval (const int numFramesPerSwap)
  231536. {
  231537. [renderContext setValues: (const GLint*) &numFramesPerSwap
  231538. forParameter: NSOpenGLCPSwapInterval];
  231539. return true;
  231540. }
  231541. int getSwapInterval() const
  231542. {
  231543. GLint numFrames = 0;
  231544. [renderContext getValues: &numFrames
  231545. forParameter: NSOpenGLCPSwapInterval];
  231546. return numFrames;
  231547. }
  231548. void repaint()
  231549. {
  231550. // we need to invalidate the juce view that holds this gl view, to make it
  231551. // cause a repaint callback
  231552. NSView* v = (NSView*) viewHolder->view;
  231553. NSRect r = [v frame];
  231554. // bit of a bodge here.. if we only invalidate the area of the gl component,
  231555. // it's completely covered by the NSOpenGLView, so the OS throws away the
  231556. // repaint message, thus never causing our paint() callback, and never repainting
  231557. // the comp. So invalidating just a little bit around the edge helps..
  231558. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  231559. }
  231560. void* getNativeWindowHandle() const { return viewHolder->view; }
  231561. juce_UseDebuggingNewOperator
  231562. NSOpenGLContext* renderContext;
  231563. ThreadSafeNSOpenGLView* view;
  231564. private:
  231565. OpenGLPixelFormat pixelFormat;
  231566. ScopedPointer <NSViewComponentInternal> viewHolder;
  231567. WindowedGLContext (const WindowedGLContext&);
  231568. WindowedGLContext& operator= (const WindowedGLContext&);
  231569. };
  231570. OpenGLContext* OpenGLComponent::createContext()
  231571. {
  231572. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  231573. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  231574. return (c->renderContext != 0) ? c.release() : 0;
  231575. }
  231576. void* OpenGLComponent::getNativeWindowHandle() const
  231577. {
  231578. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  231579. : 0;
  231580. }
  231581. void juce_glViewport (const int w, const int h)
  231582. {
  231583. glViewport (0, 0, w, h);
  231584. }
  231585. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  231586. OwnedArray <OpenGLPixelFormat>& results)
  231587. {
  231588. /* GLint attribs [64];
  231589. int n = 0;
  231590. attribs[n++] = AGL_RGBA;
  231591. attribs[n++] = AGL_DOUBLEBUFFER;
  231592. attribs[n++] = AGL_ACCELERATED;
  231593. attribs[n++] = AGL_NO_RECOVERY;
  231594. attribs[n++] = AGL_NONE;
  231595. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  231596. while (p != 0)
  231597. {
  231598. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  231599. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  231600. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  231601. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  231602. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  231603. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  231604. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  231605. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  231606. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  231607. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  231608. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  231609. results.add (pf);
  231610. p = aglNextPixelFormat (p);
  231611. }*/
  231612. //jassertfalse //xxx can't see how you do this in cocoa!
  231613. }
  231614. #else
  231615. END_JUCE_NAMESPACE
  231616. @interface JuceGLView : UIView
  231617. {
  231618. }
  231619. + (Class) layerClass;
  231620. @end
  231621. @implementation JuceGLView
  231622. + (Class) layerClass
  231623. {
  231624. return [CAEAGLLayer class];
  231625. }
  231626. @end
  231627. BEGIN_JUCE_NAMESPACE
  231628. class GLESContext : public OpenGLContext
  231629. {
  231630. public:
  231631. GLESContext (UIViewComponentPeer* peer,
  231632. Component* const component_,
  231633. const OpenGLPixelFormat& pixelFormat_,
  231634. const GLESContext* const sharedContext,
  231635. NSUInteger apiType)
  231636. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  231637. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  231638. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  231639. {
  231640. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  231641. view.opaque = YES;
  231642. view.hidden = NO;
  231643. view.backgroundColor = [UIColor blackColor];
  231644. view.userInteractionEnabled = NO;
  231645. glLayer = (CAEAGLLayer*) [view layer];
  231646. [peer->view addSubview: view];
  231647. if (sharedContext != 0)
  231648. context = [[EAGLContext alloc] initWithAPI: apiType
  231649. sharegroup: [sharedContext->context sharegroup]];
  231650. else
  231651. context = [[EAGLContext alloc] initWithAPI: apiType];
  231652. createGLBuffers();
  231653. }
  231654. ~GLESContext()
  231655. {
  231656. deleteContext();
  231657. [view removeFromSuperview];
  231658. [view release];
  231659. freeGLBuffers();
  231660. }
  231661. void deleteContext()
  231662. {
  231663. makeInactive();
  231664. [context release];
  231665. context = nil;
  231666. }
  231667. bool makeActive() const throw()
  231668. {
  231669. jassert (context != 0);
  231670. [EAGLContext setCurrentContext: context];
  231671. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  231672. return true;
  231673. }
  231674. void swapBuffers()
  231675. {
  231676. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231677. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  231678. }
  231679. bool makeInactive() const throw()
  231680. {
  231681. return [EAGLContext setCurrentContext: nil];
  231682. }
  231683. bool isActive() const throw()
  231684. {
  231685. return [EAGLContext currentContext] == context;
  231686. }
  231687. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  231688. void* getRawContext() const throw() { return glLayer; }
  231689. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  231690. {
  231691. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  231692. if (lastWidth != w || lastHeight != h)
  231693. {
  231694. lastWidth = w;
  231695. lastHeight = h;
  231696. freeGLBuffers();
  231697. createGLBuffers();
  231698. }
  231699. }
  231700. bool setSwapInterval (const int numFramesPerSwap)
  231701. {
  231702. numFrames = numFramesPerSwap;
  231703. return true;
  231704. }
  231705. int getSwapInterval() const
  231706. {
  231707. return numFrames;
  231708. }
  231709. void repaint()
  231710. {
  231711. }
  231712. void createGLBuffers()
  231713. {
  231714. makeActive();
  231715. glGenFramebuffersOES (1, &frameBufferHandle);
  231716. glGenRenderbuffersOES (1, &colorBufferHandle);
  231717. glGenRenderbuffersOES (1, &depthBufferHandle);
  231718. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231719. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  231720. GLint width, height;
  231721. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  231722. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  231723. if (useDepthBuffer)
  231724. {
  231725. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  231726. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  231727. }
  231728. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231729. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  231730. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  231731. if (useDepthBuffer)
  231732. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  231733. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  231734. }
  231735. void freeGLBuffers()
  231736. {
  231737. if (frameBufferHandle != 0)
  231738. {
  231739. glDeleteFramebuffersOES (1, &frameBufferHandle);
  231740. frameBufferHandle = 0;
  231741. }
  231742. if (colorBufferHandle != 0)
  231743. {
  231744. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  231745. colorBufferHandle = 0;
  231746. }
  231747. if (depthBufferHandle != 0)
  231748. {
  231749. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  231750. depthBufferHandle = 0;
  231751. }
  231752. }
  231753. juce_UseDebuggingNewOperator
  231754. private:
  231755. Component::SafePointer<Component> component;
  231756. OpenGLPixelFormat pixelFormat;
  231757. JuceGLView* view;
  231758. CAEAGLLayer* glLayer;
  231759. EAGLContext* context;
  231760. bool useDepthBuffer;
  231761. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  231762. int numFrames;
  231763. int lastWidth, lastHeight;
  231764. GLESContext (const GLESContext&);
  231765. GLESContext& operator= (const GLESContext&);
  231766. };
  231767. OpenGLContext* OpenGLComponent::createContext()
  231768. {
  231769. ScopedAutoReleasePool pool;
  231770. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  231771. if (peer != 0)
  231772. return new GLESContext (peer, this, preferredPixelFormat,
  231773. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  231774. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  231775. return 0;
  231776. }
  231777. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  231778. OwnedArray <OpenGLPixelFormat>& /*results*/)
  231779. {
  231780. }
  231781. void juce_glViewport (const int w, const int h)
  231782. {
  231783. glViewport (0, 0, w, h);
  231784. }
  231785. #endif
  231786. #endif
  231787. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  231788. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  231789. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231790. // compiled on its own).
  231791. #if JUCE_INCLUDED_FILE
  231792. class JuceMainMenuHandler;
  231793. END_JUCE_NAMESPACE
  231794. using namespace JUCE_NAMESPACE;
  231795. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  231796. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231797. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  231798. #else
  231799. @interface JuceMenuCallback : NSObject
  231800. #endif
  231801. {
  231802. JuceMainMenuHandler* owner;
  231803. }
  231804. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  231805. - (void) dealloc;
  231806. - (void) menuItemInvoked: (id) menu;
  231807. - (void) menuNeedsUpdate: (NSMenu*) menu;
  231808. @end
  231809. BEGIN_JUCE_NAMESPACE
  231810. class JuceMainMenuHandler : private MenuBarModel::Listener,
  231811. private DeletedAtShutdown
  231812. {
  231813. public:
  231814. static JuceMainMenuHandler* instance;
  231815. JuceMainMenuHandler()
  231816. : currentModel (0),
  231817. lastUpdateTime (0)
  231818. {
  231819. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  231820. }
  231821. ~JuceMainMenuHandler()
  231822. {
  231823. setMenu (0);
  231824. jassert (instance == this);
  231825. instance = 0;
  231826. [callback release];
  231827. }
  231828. void setMenu (MenuBarModel* const newMenuBarModel)
  231829. {
  231830. if (currentModel != newMenuBarModel)
  231831. {
  231832. if (currentModel != 0)
  231833. currentModel->removeListener (this);
  231834. currentModel = newMenuBarModel;
  231835. if (currentModel != 0)
  231836. currentModel->addListener (this);
  231837. menuBarItemsChanged (0);
  231838. }
  231839. }
  231840. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  231841. const String& name, const int menuId, const int tag)
  231842. {
  231843. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  231844. action: nil
  231845. keyEquivalent: @""];
  231846. [item setTag: tag];
  231847. NSMenu* sub = createMenu (child, name, menuId, tag);
  231848. [parent setSubmenu: sub forItem: item];
  231849. [sub setAutoenablesItems: false];
  231850. [sub release];
  231851. }
  231852. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  231853. const String& name, const int menuId, const int tag)
  231854. {
  231855. [parentItem setTag: tag];
  231856. NSMenu* menu = [parentItem submenu];
  231857. [menu setTitle: juceStringToNS (name)];
  231858. while ([menu numberOfItems] > 0)
  231859. [menu removeItemAtIndex: 0];
  231860. PopupMenu::MenuItemIterator iter (menuToCopy);
  231861. while (iter.next())
  231862. addMenuItem (iter, menu, menuId, tag);
  231863. [menu setAutoenablesItems: false];
  231864. [menu update];
  231865. }
  231866. void menuBarItemsChanged (MenuBarModel*)
  231867. {
  231868. lastUpdateTime = Time::getMillisecondCounter();
  231869. StringArray menuNames;
  231870. if (currentModel != 0)
  231871. menuNames = currentModel->getMenuBarNames();
  231872. NSMenu* menuBar = [NSApp mainMenu];
  231873. while ([menuBar numberOfItems] > 1 + menuNames.size())
  231874. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  231875. int menuId = 1;
  231876. for (int i = 0; i < menuNames.size(); ++i)
  231877. {
  231878. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  231879. if (i >= [menuBar numberOfItems] - 1)
  231880. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  231881. else
  231882. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  231883. }
  231884. }
  231885. static void flashMenuBar (NSMenu* menu)
  231886. {
  231887. if ([[menu title] isEqualToString: @"Apple"])
  231888. return;
  231889. [menu retain];
  231890. const unichar f35Key = NSF35FunctionKey;
  231891. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  231892. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  231893. action: nil
  231894. keyEquivalent: f35String];
  231895. [item setTarget: nil];
  231896. [menu insertItem: item atIndex: [menu numberOfItems]];
  231897. [item release];
  231898. if ([menu indexOfItem: item] >= 0)
  231899. {
  231900. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  231901. location: NSZeroPoint
  231902. modifierFlags: NSCommandKeyMask
  231903. timestamp: 0
  231904. windowNumber: 0
  231905. context: [NSGraphicsContext currentContext]
  231906. characters: f35String
  231907. charactersIgnoringModifiers: f35String
  231908. isARepeat: NO
  231909. keyCode: 0];
  231910. [menu performKeyEquivalent: f35Event];
  231911. if ([menu indexOfItem: item] >= 0)
  231912. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  231913. }
  231914. [menu release];
  231915. }
  231916. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  231917. {
  231918. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  231919. {
  231920. NSMenuItem* m = [menu itemAtIndex: i];
  231921. if ([m tag] == info.commandID)
  231922. return m;
  231923. if ([m submenu] != 0)
  231924. {
  231925. NSMenuItem* found = findMenuItem ([m submenu], info);
  231926. if (found != 0)
  231927. return found;
  231928. }
  231929. }
  231930. return 0;
  231931. }
  231932. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  231933. {
  231934. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  231935. if (item != 0)
  231936. flashMenuBar ([item menu]);
  231937. }
  231938. void updateMenus()
  231939. {
  231940. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  231941. menuBarItemsChanged (0);
  231942. }
  231943. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  231944. {
  231945. if (currentModel != 0)
  231946. {
  231947. if (commandManager != 0)
  231948. {
  231949. ApplicationCommandTarget::InvocationInfo info (commandId);
  231950. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  231951. commandManager->invoke (info, true);
  231952. }
  231953. currentModel->menuItemSelected (commandId, topLevelIndex);
  231954. }
  231955. }
  231956. MenuBarModel* currentModel;
  231957. uint32 lastUpdateTime;
  231958. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  231959. const int topLevelMenuId, const int topLevelIndex)
  231960. {
  231961. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  231962. if (text == 0)
  231963. text = @"";
  231964. if (iter.isSeparator)
  231965. {
  231966. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  231967. }
  231968. else if (iter.isSectionHeader)
  231969. {
  231970. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231971. action: nil
  231972. keyEquivalent: @""];
  231973. [item setEnabled: false];
  231974. }
  231975. else if (iter.subMenu != 0)
  231976. {
  231977. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231978. action: nil
  231979. keyEquivalent: @""];
  231980. [item setTag: iter.itemId];
  231981. [item setEnabled: iter.isEnabled];
  231982. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  231983. [sub setDelegate: nil];
  231984. [menuToAddTo setSubmenu: sub forItem: item];
  231985. [sub release];
  231986. }
  231987. else
  231988. {
  231989. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231990. action: @selector (menuItemInvoked:)
  231991. keyEquivalent: @""];
  231992. [item setTag: iter.itemId];
  231993. [item setEnabled: iter.isEnabled];
  231994. [item setState: iter.isTicked ? NSOnState : NSOffState];
  231995. [item setTarget: (id) callback];
  231996. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  231997. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  231998. [item setRepresentedObject: info];
  231999. if (iter.commandManager != 0)
  232000. {
  232001. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  232002. ->getKeyPressesAssignedToCommand (iter.itemId));
  232003. if (keyPresses.size() > 0)
  232004. {
  232005. const KeyPress& kp = keyPresses.getReference(0);
  232006. if (kp.getKeyCode() != KeyPress::backspaceKey
  232007. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  232008. // every time you press the key while editing text)
  232009. {
  232010. juce_wchar key = kp.getTextCharacter();
  232011. if (kp.getKeyCode() == KeyPress::backspaceKey)
  232012. key = NSBackspaceCharacter;
  232013. else if (kp.getKeyCode() == KeyPress::deleteKey)
  232014. key = NSDeleteCharacter;
  232015. else if (key == 0)
  232016. key = (juce_wchar) kp.getKeyCode();
  232017. unsigned int mods = 0;
  232018. if (kp.getModifiers().isShiftDown())
  232019. mods |= NSShiftKeyMask;
  232020. if (kp.getModifiers().isCtrlDown())
  232021. mods |= NSControlKeyMask;
  232022. if (kp.getModifiers().isAltDown())
  232023. mods |= NSAlternateKeyMask;
  232024. if (kp.getModifiers().isCommandDown())
  232025. mods |= NSCommandKeyMask;
  232026. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  232027. [item setKeyEquivalentModifierMask: mods];
  232028. }
  232029. }
  232030. }
  232031. }
  232032. }
  232033. JuceMenuCallback* callback;
  232034. private:
  232035. NSMenu* createMenu (const PopupMenu menu,
  232036. const String& menuName,
  232037. const int topLevelMenuId,
  232038. const int topLevelIndex)
  232039. {
  232040. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  232041. [m setAutoenablesItems: false];
  232042. [m setDelegate: callback];
  232043. PopupMenu::MenuItemIterator iter (menu);
  232044. while (iter.next())
  232045. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  232046. [m update];
  232047. return m;
  232048. }
  232049. };
  232050. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  232051. END_JUCE_NAMESPACE
  232052. @implementation JuceMenuCallback
  232053. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  232054. {
  232055. [super init];
  232056. owner = owner_;
  232057. return self;
  232058. }
  232059. - (void) dealloc
  232060. {
  232061. [super dealloc];
  232062. }
  232063. - (void) menuItemInvoked: (id) menu
  232064. {
  232065. NSMenuItem* item = (NSMenuItem*) menu;
  232066. if ([[item representedObject] isKindOfClass: [NSArray class]])
  232067. {
  232068. // 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
  232069. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  232070. // into the focused component and let it trigger the menu item indirectly.
  232071. NSEvent* e = [NSApp currentEvent];
  232072. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  232073. {
  232074. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  232075. {
  232076. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  232077. if (peer != 0)
  232078. {
  232079. if ([e type] == NSKeyDown)
  232080. peer->redirectKeyDown (e);
  232081. else
  232082. peer->redirectKeyUp (e);
  232083. return;
  232084. }
  232085. }
  232086. }
  232087. NSArray* info = (NSArray*) [item representedObject];
  232088. owner->invoke ((int) [item tag],
  232089. (ApplicationCommandManager*) (pointer_sized_int)
  232090. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  232091. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  232092. }
  232093. }
  232094. - (void) menuNeedsUpdate: (NSMenu*) menu;
  232095. {
  232096. (void) menu;
  232097. if (JuceMainMenuHandler::instance != 0)
  232098. JuceMainMenuHandler::instance->updateMenus();
  232099. }
  232100. @end
  232101. BEGIN_JUCE_NAMESPACE
  232102. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  232103. const PopupMenu* extraItems)
  232104. {
  232105. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  232106. {
  232107. PopupMenu::MenuItemIterator iter (*extraItems);
  232108. while (iter.next())
  232109. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  232110. [menu addItem: [NSMenuItem separatorItem]];
  232111. }
  232112. NSMenuItem* item;
  232113. // Services...
  232114. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  232115. action: nil keyEquivalent: @""];
  232116. [menu addItem: item];
  232117. [item release];
  232118. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  232119. [menu setSubmenu: servicesMenu forItem: item];
  232120. [NSApp setServicesMenu: servicesMenu];
  232121. [servicesMenu release];
  232122. [menu addItem: [NSMenuItem separatorItem]];
  232123. // Hide + Show stuff...
  232124. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  232125. action: @selector (hide:) keyEquivalent: @"h"];
  232126. [item setTarget: NSApp];
  232127. [menu addItem: item];
  232128. [item release];
  232129. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  232130. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  232131. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  232132. [item setTarget: NSApp];
  232133. [menu addItem: item];
  232134. [item release];
  232135. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  232136. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  232137. [item setTarget: NSApp];
  232138. [menu addItem: item];
  232139. [item release];
  232140. [menu addItem: [NSMenuItem separatorItem]];
  232141. // Quit item....
  232142. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  232143. action: @selector (terminate:) keyEquivalent: @"q"];
  232144. [item setTarget: NSApp];
  232145. [menu addItem: item];
  232146. [item release];
  232147. return menu;
  232148. }
  232149. // Since our app has no NIB, this initialises a standard app menu...
  232150. static void rebuildMainMenu (const PopupMenu* extraItems)
  232151. {
  232152. // this can't be used in a plugin!
  232153. jassert (JUCEApplication::isStandaloneApp);
  232154. if (JUCEApplication::getInstance() != 0)
  232155. {
  232156. const ScopedAutoReleasePool pool;
  232157. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  232158. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  232159. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  232160. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  232161. [mainMenu setSubmenu: appMenu forItem: item];
  232162. [NSApp setMainMenu: mainMenu];
  232163. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  232164. [appMenu release];
  232165. [mainMenu release];
  232166. }
  232167. }
  232168. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  232169. const PopupMenu* extraAppleMenuItems)
  232170. {
  232171. if (getMacMainMenu() != newMenuBarModel)
  232172. {
  232173. const ScopedAutoReleasePool pool;
  232174. if (newMenuBarModel == 0)
  232175. {
  232176. delete JuceMainMenuHandler::instance;
  232177. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  232178. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  232179. extraAppleMenuItems = 0;
  232180. }
  232181. else
  232182. {
  232183. if (JuceMainMenuHandler::instance == 0)
  232184. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  232185. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  232186. }
  232187. }
  232188. rebuildMainMenu (extraAppleMenuItems);
  232189. if (newMenuBarModel != 0)
  232190. newMenuBarModel->menuItemsChanged();
  232191. }
  232192. MenuBarModel* MenuBarModel::getMacMainMenu()
  232193. {
  232194. return JuceMainMenuHandler::instance != 0
  232195. ? JuceMainMenuHandler::instance->currentModel : 0;
  232196. }
  232197. void juce_initialiseMacMainMenu()
  232198. {
  232199. if (JuceMainMenuHandler::instance == 0)
  232200. rebuildMainMenu (0);
  232201. }
  232202. #endif
  232203. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  232204. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  232205. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232206. // compiled on its own).
  232207. #if JUCE_INCLUDED_FILE
  232208. #if JUCE_MAC
  232209. END_JUCE_NAMESPACE
  232210. using namespace JUCE_NAMESPACE;
  232211. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  232212. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  232213. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  232214. #else
  232215. @interface JuceFileChooserDelegate : NSObject
  232216. #endif
  232217. {
  232218. StringArray* filters;
  232219. }
  232220. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  232221. - (void) dealloc;
  232222. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  232223. @end
  232224. @implementation JuceFileChooserDelegate
  232225. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  232226. {
  232227. [super init];
  232228. filters = filters_;
  232229. return self;
  232230. }
  232231. - (void) dealloc
  232232. {
  232233. delete filters;
  232234. [super dealloc];
  232235. }
  232236. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  232237. {
  232238. (void) sender;
  232239. const File f (nsStringToJuce (filename));
  232240. for (int i = filters->size(); --i >= 0;)
  232241. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  232242. return true;
  232243. return f.isDirectory();
  232244. }
  232245. @end
  232246. BEGIN_JUCE_NAMESPACE
  232247. void FileChooser::showPlatformDialog (Array<File>& results,
  232248. const String& title,
  232249. const File& currentFileOrDirectory,
  232250. const String& filter,
  232251. bool selectsDirectory,
  232252. bool selectsFiles,
  232253. bool isSaveDialogue,
  232254. bool warnAboutOverwritingExistingFiles,
  232255. bool selectMultipleFiles,
  232256. FilePreviewComponent* extraInfoComponent)
  232257. {
  232258. const ScopedAutoReleasePool pool;
  232259. StringArray* filters = new StringArray();
  232260. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  232261. filters->trim();
  232262. filters->removeEmptyStrings();
  232263. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  232264. [delegate autorelease];
  232265. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  232266. : [NSOpenPanel openPanel];
  232267. [panel setTitle: juceStringToNS (title)];
  232268. if (! isSaveDialogue)
  232269. {
  232270. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  232271. [openPanel setCanChooseDirectories: selectsDirectory];
  232272. [openPanel setCanChooseFiles: selectsFiles];
  232273. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  232274. }
  232275. [panel setDelegate: delegate];
  232276. if (isSaveDialogue || selectsDirectory)
  232277. [panel setCanCreateDirectories: YES];
  232278. String directory, filename;
  232279. if (currentFileOrDirectory.isDirectory())
  232280. {
  232281. directory = currentFileOrDirectory.getFullPathName();
  232282. }
  232283. else
  232284. {
  232285. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  232286. filename = currentFileOrDirectory.getFileName();
  232287. }
  232288. if ([panel runModalForDirectory: juceStringToNS (directory)
  232289. file: juceStringToNS (filename)]
  232290. == NSOKButton)
  232291. {
  232292. if (isSaveDialogue)
  232293. {
  232294. results.add (File (nsStringToJuce ([panel filename])));
  232295. }
  232296. else
  232297. {
  232298. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  232299. NSArray* urls = [openPanel filenames];
  232300. for (unsigned int i = 0; i < [urls count]; ++i)
  232301. {
  232302. NSString* f = [urls objectAtIndex: i];
  232303. results.add (File (nsStringToJuce (f)));
  232304. }
  232305. }
  232306. }
  232307. [panel setDelegate: nil];
  232308. }
  232309. #else
  232310. void FileChooser::showPlatformDialog (Array<File>& results,
  232311. const String& title,
  232312. const File& currentFileOrDirectory,
  232313. const String& filter,
  232314. bool selectsDirectory,
  232315. bool selectsFiles,
  232316. bool isSaveDialogue,
  232317. bool warnAboutOverwritingExistingFiles,
  232318. bool selectMultipleFiles,
  232319. FilePreviewComponent* extraInfoComponent)
  232320. {
  232321. const ScopedAutoReleasePool pool;
  232322. jassertfalse; //xxx to do
  232323. }
  232324. #endif
  232325. #endif
  232326. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  232327. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  232328. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232329. // compiled on its own).
  232330. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  232331. END_JUCE_NAMESPACE
  232332. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  232333. @interface NonInterceptingQTMovieView : QTMovieView
  232334. {
  232335. }
  232336. - (id) initWithFrame: (NSRect) frame;
  232337. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  232338. - (NSView*) hitTest: (NSPoint) p;
  232339. @end
  232340. @implementation NonInterceptingQTMovieView
  232341. - (id) initWithFrame: (NSRect) frame
  232342. {
  232343. self = [super initWithFrame: frame];
  232344. [self setNextResponder: [self superview]];
  232345. return self;
  232346. }
  232347. - (void) dealloc
  232348. {
  232349. [super dealloc];
  232350. }
  232351. - (NSView*) hitTest: (NSPoint) point
  232352. {
  232353. return [self isControllerVisible] ? [super hitTest: point] : nil;
  232354. }
  232355. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  232356. {
  232357. return YES;
  232358. }
  232359. @end
  232360. BEGIN_JUCE_NAMESPACE
  232361. #define theMovie (static_cast <QTMovie*> (movie))
  232362. QuickTimeMovieComponent::QuickTimeMovieComponent()
  232363. : movie (0)
  232364. {
  232365. setOpaque (true);
  232366. setVisible (true);
  232367. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  232368. setView (view);
  232369. [view release];
  232370. }
  232371. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  232372. {
  232373. closeMovie();
  232374. setView (0);
  232375. }
  232376. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  232377. {
  232378. return true;
  232379. }
  232380. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  232381. {
  232382. // unfortunately, QTMovie objects can only be created on the main thread..
  232383. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  232384. QTMovie* movie = 0;
  232385. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  232386. if (fin != 0)
  232387. {
  232388. movieFile = fin->getFile();
  232389. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  232390. error: nil];
  232391. }
  232392. else
  232393. {
  232394. MemoryBlock temp;
  232395. movieStream->readIntoMemoryBlock (temp);
  232396. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  232397. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  232398. {
  232399. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  232400. length: temp.getSize()]
  232401. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  232402. MIMEType: @""]
  232403. error: nil];
  232404. if (movie != 0)
  232405. break;
  232406. }
  232407. }
  232408. return movie;
  232409. }
  232410. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  232411. const bool isControllerVisible_)
  232412. {
  232413. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  232414. }
  232415. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  232416. const bool controllerVisible_)
  232417. {
  232418. closeMovie();
  232419. if (getPeer() == 0)
  232420. {
  232421. // To open a movie, this component must be visible inside a functioning window, so that
  232422. // the QT control can be assigned to the window.
  232423. jassertfalse;
  232424. return false;
  232425. }
  232426. movie = openMovieFromStream (movieStream, movieFile);
  232427. [theMovie retain];
  232428. QTMovieView* view = (QTMovieView*) getView();
  232429. [view setMovie: theMovie];
  232430. [view setControllerVisible: controllerVisible_];
  232431. setLooping (looping);
  232432. return movie != nil;
  232433. }
  232434. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  232435. const bool isControllerVisible_)
  232436. {
  232437. // unfortunately, QTMovie objects can only be created on the main thread..
  232438. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  232439. closeMovie();
  232440. if (getPeer() == 0)
  232441. {
  232442. // To open a movie, this component must be visible inside a functioning window, so that
  232443. // the QT control can be assigned to the window.
  232444. jassertfalse;
  232445. return false;
  232446. }
  232447. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  232448. NSError* err;
  232449. if ([QTMovie canInitWithURL: url])
  232450. movie = [QTMovie movieWithURL: url error: &err];
  232451. [theMovie retain];
  232452. QTMovieView* view = (QTMovieView*) getView();
  232453. [view setMovie: theMovie];
  232454. [view setControllerVisible: controllerVisible];
  232455. setLooping (looping);
  232456. return movie != nil;
  232457. }
  232458. void QuickTimeMovieComponent::closeMovie()
  232459. {
  232460. stop();
  232461. QTMovieView* view = (QTMovieView*) getView();
  232462. [view setMovie: nil];
  232463. [theMovie release];
  232464. movie = 0;
  232465. movieFile = File::nonexistent;
  232466. }
  232467. bool QuickTimeMovieComponent::isMovieOpen() const
  232468. {
  232469. return movie != nil;
  232470. }
  232471. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  232472. {
  232473. return movieFile;
  232474. }
  232475. void QuickTimeMovieComponent::play()
  232476. {
  232477. [theMovie play];
  232478. }
  232479. void QuickTimeMovieComponent::stop()
  232480. {
  232481. [theMovie stop];
  232482. }
  232483. bool QuickTimeMovieComponent::isPlaying() const
  232484. {
  232485. return movie != 0 && [theMovie rate] != 0;
  232486. }
  232487. void QuickTimeMovieComponent::setPosition (const double seconds)
  232488. {
  232489. if (movie != 0)
  232490. {
  232491. QTTime t;
  232492. t.timeValue = (uint64) (100000.0 * seconds);
  232493. t.timeScale = 100000;
  232494. t.flags = 0;
  232495. [theMovie setCurrentTime: t];
  232496. }
  232497. }
  232498. double QuickTimeMovieComponent::getPosition() const
  232499. {
  232500. if (movie == 0)
  232501. return 0.0;
  232502. QTTime t = [theMovie currentTime];
  232503. return t.timeValue / (double) t.timeScale;
  232504. }
  232505. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  232506. {
  232507. [theMovie setRate: newSpeed];
  232508. }
  232509. double QuickTimeMovieComponent::getMovieDuration() const
  232510. {
  232511. if (movie == 0)
  232512. return 0.0;
  232513. QTTime t = [theMovie duration];
  232514. return t.timeValue / (double) t.timeScale;
  232515. }
  232516. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  232517. {
  232518. looping = shouldLoop;
  232519. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  232520. forKey: QTMovieLoopsAttribute];
  232521. }
  232522. bool QuickTimeMovieComponent::isLooping() const
  232523. {
  232524. return looping;
  232525. }
  232526. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  232527. {
  232528. [theMovie setVolume: newVolume];
  232529. }
  232530. float QuickTimeMovieComponent::getMovieVolume() const
  232531. {
  232532. return movie != 0 ? [theMovie volume] : 0.0f;
  232533. }
  232534. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  232535. {
  232536. width = 0;
  232537. height = 0;
  232538. if (movie != 0)
  232539. {
  232540. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  232541. width = (int) s.width;
  232542. height = (int) s.height;
  232543. }
  232544. }
  232545. void QuickTimeMovieComponent::paint (Graphics& g)
  232546. {
  232547. if (movie == 0)
  232548. g.fillAll (Colours::black);
  232549. }
  232550. bool QuickTimeMovieComponent::isControllerVisible() const
  232551. {
  232552. return controllerVisible;
  232553. }
  232554. void QuickTimeMovieComponent::goToStart()
  232555. {
  232556. setPosition (0.0);
  232557. }
  232558. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  232559. const RectanglePlacement& placement)
  232560. {
  232561. int normalWidth, normalHeight;
  232562. getMovieNormalSize (normalWidth, normalHeight);
  232563. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  232564. {
  232565. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  232566. placement.applyTo (x, y, w, h,
  232567. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  232568. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  232569. if (w > 0 && h > 0)
  232570. {
  232571. setBounds (roundToInt (x), roundToInt (y),
  232572. roundToInt (w), roundToInt (h));
  232573. }
  232574. }
  232575. else
  232576. {
  232577. setBounds (spaceToFitWithin);
  232578. }
  232579. }
  232580. #if ! (JUCE_MAC && JUCE_64BIT)
  232581. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  232582. {
  232583. if (movieStream == 0)
  232584. return false;
  232585. File file;
  232586. QTMovie* movie = openMovieFromStream (movieStream, file);
  232587. if (movie != nil)
  232588. result = [movie quickTimeMovie];
  232589. return movie != nil;
  232590. }
  232591. #endif
  232592. #endif
  232593. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  232594. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  232595. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232596. // compiled on its own).
  232597. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  232598. const int kilobytesPerSecond1x = 176;
  232599. END_JUCE_NAMESPACE
  232600. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  232601. @interface OpenDiskDevice : NSObject
  232602. {
  232603. @public
  232604. DRDevice* device;
  232605. NSMutableArray* tracks;
  232606. bool underrunProtection;
  232607. }
  232608. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  232609. - (void) dealloc;
  232610. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  232611. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  232612. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  232613. @end
  232614. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  232615. @interface AudioTrackProducer : NSObject
  232616. {
  232617. JUCE_NAMESPACE::AudioSource* source;
  232618. int readPosition, lengthInFrames;
  232619. }
  232620. - (AudioTrackProducer*) init: (int) lengthInFrames;
  232621. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  232622. - (void) dealloc;
  232623. - (void) setupTrackProperties: (DRTrack*) track;
  232624. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  232625. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  232626. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  232627. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  232628. toMedia:(NSDictionary*)mediaInfo;
  232629. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  232630. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  232631. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  232632. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  232633. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  232634. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  232635. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  232636. ioFlags:(uint32_t*)flags;
  232637. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  232638. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  232639. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  232640. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  232641. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  232642. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  232643. ioFlags:(uint32_t*)flags;
  232644. @end
  232645. @implementation OpenDiskDevice
  232646. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  232647. {
  232648. [super init];
  232649. device = device_;
  232650. tracks = [[NSMutableArray alloc] init];
  232651. underrunProtection = true;
  232652. return self;
  232653. }
  232654. - (void) dealloc
  232655. {
  232656. [tracks release];
  232657. [super dealloc];
  232658. }
  232659. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  232660. {
  232661. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  232662. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  232663. [p setupTrackProperties: t];
  232664. [tracks addObject: t];
  232665. [t release];
  232666. [p release];
  232667. }
  232668. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  232669. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  232670. {
  232671. DRBurn* burn = [DRBurn burnForDevice: device];
  232672. if (! [device acquireExclusiveAccess])
  232673. {
  232674. *error = "Couldn't open or write to the CD device";
  232675. return;
  232676. }
  232677. [device acquireMediaReservation];
  232678. NSMutableDictionary* d = [[burn properties] mutableCopy];
  232679. [d autorelease];
  232680. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  232681. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  232682. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  232683. if (burnSpeed > 0)
  232684. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  232685. if (! underrunProtection)
  232686. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  232687. [burn setProperties: d];
  232688. [burn writeLayout: tracks];
  232689. for (;;)
  232690. {
  232691. JUCE_NAMESPACE::Thread::sleep (300);
  232692. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  232693. if (listener != 0 && listener->audioCDBurnProgress (progress))
  232694. {
  232695. [burn abort];
  232696. *error = "User cancelled the write operation";
  232697. break;
  232698. }
  232699. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  232700. {
  232701. *error = "Write operation failed";
  232702. break;
  232703. }
  232704. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  232705. {
  232706. break;
  232707. }
  232708. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  232709. objectForKey: DRErrorStatusErrorStringKey];
  232710. if ([err length] > 0)
  232711. {
  232712. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  232713. break;
  232714. }
  232715. }
  232716. [device releaseMediaReservation];
  232717. [device releaseExclusiveAccess];
  232718. }
  232719. @end
  232720. @implementation AudioTrackProducer
  232721. - (AudioTrackProducer*) init: (int) lengthInFrames_
  232722. {
  232723. lengthInFrames = lengthInFrames_;
  232724. readPosition = 0;
  232725. return self;
  232726. }
  232727. - (void) setupTrackProperties: (DRTrack*) track
  232728. {
  232729. NSMutableDictionary* p = [[track properties] mutableCopy];
  232730. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  232731. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  232732. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  232733. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  232734. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  232735. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  232736. [track setProperties: p];
  232737. [p release];
  232738. }
  232739. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  232740. {
  232741. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  232742. if (s != nil)
  232743. s->source = source_;
  232744. return s;
  232745. }
  232746. - (void) dealloc
  232747. {
  232748. if (source != 0)
  232749. {
  232750. source->releaseResources();
  232751. delete source;
  232752. }
  232753. [super dealloc];
  232754. }
  232755. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  232756. {
  232757. }
  232758. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  232759. {
  232760. return true;
  232761. }
  232762. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  232763. {
  232764. return lengthInFrames;
  232765. }
  232766. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  232767. toMedia: (NSDictionary*) mediaInfo
  232768. {
  232769. if (source != 0)
  232770. source->prepareToPlay (44100 / 75, 44100);
  232771. readPosition = 0;
  232772. return true;
  232773. }
  232774. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  232775. {
  232776. if (source != 0)
  232777. source->prepareToPlay (44100 / 75, 44100);
  232778. return true;
  232779. }
  232780. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  232781. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  232782. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  232783. {
  232784. if (source != 0)
  232785. {
  232786. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  232787. if (numSamples > 0)
  232788. {
  232789. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  232790. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  232791. info.buffer = &tempBuffer;
  232792. info.startSample = 0;
  232793. info.numSamples = numSamples;
  232794. source->getNextAudioBlock (info);
  232795. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  232796. buffer, numSamples, 4);
  232797. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  232798. buffer + 2, numSamples, 4);
  232799. readPosition += numSamples;
  232800. }
  232801. return numSamples * 4;
  232802. }
  232803. return 0;
  232804. }
  232805. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  232806. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  232807. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  232808. ioFlags: (uint32_t*) flags
  232809. {
  232810. zeromem (buffer, bufferLength);
  232811. return bufferLength;
  232812. }
  232813. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  232814. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  232815. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  232816. {
  232817. return true;
  232818. }
  232819. @end
  232820. BEGIN_JUCE_NAMESPACE
  232821. class AudioCDBurner::Pimpl : public Timer
  232822. {
  232823. public:
  232824. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  232825. : device (0), owner (owner_)
  232826. {
  232827. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  232828. if (dev != 0)
  232829. {
  232830. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  232831. lastState = getDiskState();
  232832. startTimer (1000);
  232833. }
  232834. }
  232835. ~Pimpl()
  232836. {
  232837. stopTimer();
  232838. [device release];
  232839. }
  232840. void timerCallback()
  232841. {
  232842. const DiskState state = getDiskState();
  232843. if (state != lastState)
  232844. {
  232845. lastState = state;
  232846. owner.sendChangeMessage (&owner);
  232847. }
  232848. }
  232849. DiskState getDiskState() const
  232850. {
  232851. if ([device->device isValid])
  232852. {
  232853. NSDictionary* status = [device->device status];
  232854. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  232855. if ([state isEqualTo: DRDeviceMediaStateNone])
  232856. {
  232857. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  232858. return trayOpen;
  232859. return noDisc;
  232860. }
  232861. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  232862. {
  232863. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  232864. return writableDiskPresent;
  232865. else
  232866. return readOnlyDiskPresent;
  232867. }
  232868. }
  232869. return unknown;
  232870. }
  232871. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  232872. const Array<int> getAvailableWriteSpeeds() const
  232873. {
  232874. Array<int> results;
  232875. if ([device->device isValid])
  232876. {
  232877. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  232878. for (unsigned int i = 0; i < [speeds count]; ++i)
  232879. {
  232880. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  232881. results.add (kbPerSec / kilobytesPerSecond1x);
  232882. }
  232883. }
  232884. return results;
  232885. }
  232886. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  232887. {
  232888. if ([device->device isValid])
  232889. {
  232890. device->underrunProtection = shouldBeEnabled;
  232891. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  232892. }
  232893. return false;
  232894. }
  232895. int getNumAvailableAudioBlocks() const
  232896. {
  232897. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  232898. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  232899. }
  232900. OpenDiskDevice* device;
  232901. private:
  232902. DiskState lastState;
  232903. AudioCDBurner& owner;
  232904. };
  232905. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  232906. {
  232907. pimpl = new Pimpl (*this, deviceIndex);
  232908. }
  232909. AudioCDBurner::~AudioCDBurner()
  232910. {
  232911. }
  232912. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  232913. {
  232914. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  232915. if (b->pimpl->device == 0)
  232916. b = 0;
  232917. return b.release();
  232918. }
  232919. static NSArray* findDiskBurnerDevices()
  232920. {
  232921. NSMutableArray* results = [NSMutableArray array];
  232922. NSArray* devs = [DRDevice devices];
  232923. if (devs != 0)
  232924. {
  232925. int num = [devs count];
  232926. int i;
  232927. for (i = 0; i < num; ++i)
  232928. {
  232929. NSDictionary* dic = [[devs objectAtIndex: i] info];
  232930. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  232931. if (name != nil)
  232932. [results addObject: name];
  232933. }
  232934. }
  232935. return results;
  232936. }
  232937. const StringArray AudioCDBurner::findAvailableDevices()
  232938. {
  232939. NSArray* names = findDiskBurnerDevices();
  232940. StringArray s;
  232941. for (unsigned int i = 0; i < [names count]; ++i)
  232942. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  232943. return s;
  232944. }
  232945. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  232946. {
  232947. return pimpl->getDiskState();
  232948. }
  232949. bool AudioCDBurner::isDiskPresent() const
  232950. {
  232951. return getDiskState() == writableDiskPresent;
  232952. }
  232953. bool AudioCDBurner::openTray()
  232954. {
  232955. return pimpl->openTray();
  232956. }
  232957. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  232958. {
  232959. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  232960. DiskState oldState = getDiskState();
  232961. DiskState newState = oldState;
  232962. while (newState == oldState && Time::currentTimeMillis() < timeout)
  232963. {
  232964. newState = getDiskState();
  232965. Thread::sleep (100);
  232966. }
  232967. return newState;
  232968. }
  232969. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  232970. {
  232971. return pimpl->getAvailableWriteSpeeds();
  232972. }
  232973. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  232974. {
  232975. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  232976. }
  232977. int AudioCDBurner::getNumAvailableAudioBlocks() const
  232978. {
  232979. return pimpl->getNumAvailableAudioBlocks();
  232980. }
  232981. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  232982. {
  232983. if ([pimpl->device->device isValid])
  232984. {
  232985. [pimpl->device addSourceTrack: source numSamples: numSamps];
  232986. return true;
  232987. }
  232988. return false;
  232989. }
  232990. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  232991. bool ejectDiscAfterwards,
  232992. bool performFakeBurnForTesting,
  232993. int writeSpeed)
  232994. {
  232995. String error ("Couldn't open or write to the CD device");
  232996. if ([pimpl->device->device isValid])
  232997. {
  232998. error = String::empty;
  232999. [pimpl->device burn: listener
  233000. errorString: &error
  233001. ejectAfterwards: ejectDiscAfterwards
  233002. isFake: performFakeBurnForTesting
  233003. speed: writeSpeed];
  233004. }
  233005. return error;
  233006. }
  233007. #endif
  233008. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  233009. void AudioCDReader::ejectDisk()
  233010. {
  233011. const ScopedAutoReleasePool p;
  233012. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  233013. }
  233014. #endif
  233015. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  233016. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  233017. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233018. // compiled on its own).
  233019. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  233020. static void juce_findCDs (Array<File>& cds)
  233021. {
  233022. File volumes ("/Volumes");
  233023. volumes.findChildFiles (cds, File::findDirectories, false);
  233024. for (int i = cds.size(); --i >= 0;)
  233025. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  233026. cds.remove (i);
  233027. }
  233028. const StringArray AudioCDReader::getAvailableCDNames()
  233029. {
  233030. Array<File> cds;
  233031. juce_findCDs (cds);
  233032. StringArray names;
  233033. for (int i = 0; i < cds.size(); ++i)
  233034. names.add (cds.getReference(i).getFileName());
  233035. return names;
  233036. }
  233037. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  233038. {
  233039. Array<File> cds;
  233040. juce_findCDs (cds);
  233041. if (cds[index].exists())
  233042. return new AudioCDReader (cds[index]);
  233043. return 0;
  233044. }
  233045. AudioCDReader::AudioCDReader (const File& volume)
  233046. : AudioFormatReader (0, "CD Audio"),
  233047. volumeDir (volume),
  233048. currentReaderTrack (-1),
  233049. reader (0)
  233050. {
  233051. sampleRate = 44100.0;
  233052. bitsPerSample = 16;
  233053. numChannels = 2;
  233054. usesFloatingPointData = false;
  233055. refreshTrackLengths();
  233056. }
  233057. AudioCDReader::~AudioCDReader()
  233058. {
  233059. }
  233060. static int juce_getCDTrackNumber (const File& file)
  233061. {
  233062. return file.getFileName()
  233063. .initialSectionContainingOnly ("0123456789")
  233064. .getIntValue();
  233065. }
  233066. int AudioCDReader::compareElements (const File& first, const File& second)
  233067. {
  233068. const int firstTrack = juce_getCDTrackNumber (first);
  233069. const int secondTrack = juce_getCDTrackNumber (second);
  233070. jassert (firstTrack > 0 && secondTrack > 0);
  233071. return firstTrack - secondTrack;
  233072. }
  233073. void AudioCDReader::refreshTrackLengths()
  233074. {
  233075. tracks.clear();
  233076. trackStartSamples.clear();
  233077. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  233078. tracks.sort (*this);
  233079. AiffAudioFormat format;
  233080. int sample = 0;
  233081. for (int i = 0; i < tracks.size(); ++i)
  233082. {
  233083. trackStartSamples.add (sample);
  233084. FileInputStream* const in = tracks.getReference(i).createInputStream();
  233085. if (in != 0)
  233086. {
  233087. ScopedPointer <AudioFormatReader> r (format.createReaderFor (in, true));
  233088. if (r != 0)
  233089. sample += (int) r->lengthInSamples;
  233090. }
  233091. }
  233092. trackStartSamples.add (sample);
  233093. lengthInSamples = sample;
  233094. }
  233095. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  233096. int64 startSampleInFile, int numSamples)
  233097. {
  233098. while (numSamples > 0)
  233099. {
  233100. int track = -1;
  233101. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  233102. {
  233103. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  233104. {
  233105. track = i;
  233106. break;
  233107. }
  233108. }
  233109. if (track < 0)
  233110. return false;
  233111. if (track != currentReaderTrack)
  233112. {
  233113. reader = 0;
  233114. FileInputStream* const in = tracks [track].createInputStream();
  233115. if (in != 0)
  233116. {
  233117. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  233118. AiffAudioFormat format;
  233119. reader = format.createReaderFor (bin, true);
  233120. if (reader == 0)
  233121. currentReaderTrack = -1;
  233122. else
  233123. currentReaderTrack = track;
  233124. }
  233125. }
  233126. if (reader == 0)
  233127. return false;
  233128. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  233129. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  233130. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  233131. numSamples -= numAvailable;
  233132. startSampleInFile += numAvailable;
  233133. }
  233134. return true;
  233135. }
  233136. bool AudioCDReader::isCDStillPresent() const
  233137. {
  233138. return volumeDir.exists();
  233139. }
  233140. int AudioCDReader::getNumTracks() const
  233141. {
  233142. return tracks.size();
  233143. }
  233144. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  233145. {
  233146. return trackStartSamples [trackNum];
  233147. }
  233148. bool AudioCDReader::isTrackAudio (int trackNum) const
  233149. {
  233150. return tracks [trackNum] != File::nonexistent;
  233151. }
  233152. void AudioCDReader::enableIndexScanning (bool b)
  233153. {
  233154. // any way to do this on a Mac??
  233155. }
  233156. int AudioCDReader::getLastIndex() const
  233157. {
  233158. return 0;
  233159. }
  233160. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  233161. {
  233162. return Array <int>();
  233163. }
  233164. int AudioCDReader::getCDDBId()
  233165. {
  233166. return 0; //xxx
  233167. }
  233168. #endif
  233169. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  233170. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  233171. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233172. // compiled on its own).
  233173. #if JUCE_INCLUDED_FILE
  233174. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  233175. for example having more than one juce plugin loaded into a host, then when a
  233176. method is called, the actual code that runs might actually be in a different module
  233177. than the one you expect... So any calls to library functions or statics that are
  233178. made inside obj-c methods will probably end up getting executed in a different DLL's
  233179. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  233180. To work around this insanity, I'm only allowing obj-c methods to make calls to
  233181. virtual methods of an object that's known to live inside the right module's space.
  233182. */
  233183. class AppDelegateRedirector
  233184. {
  233185. public:
  233186. AppDelegateRedirector()
  233187. {
  233188. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  233189. runLoop = CFRunLoopGetMain();
  233190. #else
  233191. runLoop = CFRunLoopGetCurrent();
  233192. #endif
  233193. CFRunLoopSourceContext sourceContext;
  233194. zerostruct (sourceContext);
  233195. sourceContext.info = this;
  233196. sourceContext.perform = runLoopSourceCallback;
  233197. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  233198. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  233199. }
  233200. virtual ~AppDelegateRedirector()
  233201. {
  233202. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  233203. CFRunLoopSourceInvalidate (runLoopSource);
  233204. CFRelease (runLoopSource);
  233205. }
  233206. virtual NSApplicationTerminateReply shouldTerminate()
  233207. {
  233208. if (JUCEApplication::getInstance() != 0)
  233209. {
  233210. JUCEApplication::getInstance()->systemRequestedQuit();
  233211. return NSTerminateCancel;
  233212. }
  233213. return NSTerminateNow;
  233214. }
  233215. virtual BOOL openFile (const NSString* filename)
  233216. {
  233217. if (JUCEApplication::getInstance() != 0)
  233218. {
  233219. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  233220. return YES;
  233221. }
  233222. return NO;
  233223. }
  233224. virtual void openFiles (NSArray* filenames)
  233225. {
  233226. StringArray files;
  233227. for (unsigned int i = 0; i < [filenames count]; ++i)
  233228. {
  233229. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  233230. if (filename.containsChar (' '))
  233231. filename = filename.quoted('"');
  233232. files.add (filename);
  233233. }
  233234. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  233235. {
  233236. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  233237. }
  233238. }
  233239. virtual void focusChanged()
  233240. {
  233241. juce_HandleProcessFocusChange();
  233242. }
  233243. struct CallbackMessagePayload
  233244. {
  233245. MessageCallbackFunction* function;
  233246. void* parameter;
  233247. void* volatile result;
  233248. bool volatile hasBeenExecuted;
  233249. };
  233250. virtual void performCallback (CallbackMessagePayload* pl)
  233251. {
  233252. pl->result = (*pl->function) (pl->parameter);
  233253. pl->hasBeenExecuted = true;
  233254. }
  233255. virtual void deleteSelf()
  233256. {
  233257. delete this;
  233258. }
  233259. void postMessage (Message* const m)
  233260. {
  233261. messages.add (m);
  233262. CFRunLoopSourceSignal (runLoopSource);
  233263. CFRunLoopWakeUp (runLoop);
  233264. }
  233265. private:
  233266. CFRunLoopRef runLoop;
  233267. CFRunLoopSourceRef runLoopSource;
  233268. OwnedArray <Message, CriticalSection> messages;
  233269. void runLoopCallback()
  233270. {
  233271. int numDispatched = 0;
  233272. do
  233273. {
  233274. Message* const nextMessage = messages.removeAndReturn (0);
  233275. if (nextMessage == 0)
  233276. return;
  233277. const ScopedAutoReleasePool pool;
  233278. MessageManager::getInstance()->deliverMessage (nextMessage);
  233279. } while (++numDispatched <= 4);
  233280. CFRunLoopSourceSignal (runLoopSource);
  233281. CFRunLoopWakeUp (runLoop);
  233282. }
  233283. static void runLoopSourceCallback (void* info)
  233284. {
  233285. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  233286. }
  233287. };
  233288. END_JUCE_NAMESPACE
  233289. using namespace JUCE_NAMESPACE;
  233290. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  233291. @interface JuceAppDelegate : NSObject
  233292. {
  233293. @private
  233294. id oldDelegate;
  233295. @public
  233296. AppDelegateRedirector* redirector;
  233297. }
  233298. - (JuceAppDelegate*) init;
  233299. - (void) dealloc;
  233300. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  233301. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  233302. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  233303. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  233304. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  233305. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  233306. - (void) performCallback: (id) info;
  233307. - (void) dummyMethod;
  233308. @end
  233309. @implementation JuceAppDelegate
  233310. - (JuceAppDelegate*) init
  233311. {
  233312. [super init];
  233313. redirector = new AppDelegateRedirector();
  233314. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  233315. if (JUCEApplication::isStandaloneApp)
  233316. {
  233317. oldDelegate = [NSApp delegate];
  233318. [NSApp setDelegate: self];
  233319. }
  233320. else
  233321. {
  233322. oldDelegate = 0;
  233323. [center addObserver: self selector: @selector (applicationDidResignActive:)
  233324. name: NSApplicationDidResignActiveNotification object: NSApp];
  233325. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  233326. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  233327. [center addObserver: self selector: @selector (applicationWillUnhide:)
  233328. name: NSApplicationWillUnhideNotification object: NSApp];
  233329. }
  233330. return self;
  233331. }
  233332. - (void) dealloc
  233333. {
  233334. if (oldDelegate != 0)
  233335. [NSApp setDelegate: oldDelegate];
  233336. redirector->deleteSelf();
  233337. [super dealloc];
  233338. }
  233339. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  233340. {
  233341. (void) app;
  233342. return redirector->shouldTerminate();
  233343. }
  233344. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  233345. {
  233346. (void) app;
  233347. return redirector->openFile (filename);
  233348. }
  233349. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  233350. {
  233351. (void) sender;
  233352. return redirector->openFiles (filenames);
  233353. }
  233354. - (void) applicationDidBecomeActive: (NSNotification*) notification
  233355. {
  233356. (void) notification;
  233357. redirector->focusChanged();
  233358. }
  233359. - (void) applicationDidResignActive: (NSNotification*) notification
  233360. {
  233361. (void) notification;
  233362. redirector->focusChanged();
  233363. }
  233364. - (void) applicationWillUnhide: (NSNotification*) notification
  233365. {
  233366. (void) notification;
  233367. redirector->focusChanged();
  233368. }
  233369. - (void) performCallback: (id) info
  233370. {
  233371. if ([info isKindOfClass: [NSData class]])
  233372. {
  233373. AppDelegateRedirector::CallbackMessagePayload* pl
  233374. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  233375. if (pl != 0)
  233376. redirector->performCallback (pl);
  233377. }
  233378. else
  233379. {
  233380. jassertfalse; // should never get here!
  233381. }
  233382. }
  233383. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  233384. @end
  233385. BEGIN_JUCE_NAMESPACE
  233386. static JuceAppDelegate* juceAppDelegate = 0;
  233387. void MessageManager::runDispatchLoop()
  233388. {
  233389. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  233390. {
  233391. const ScopedAutoReleasePool pool;
  233392. // must only be called by the message thread!
  233393. jassert (isThisTheMessageThread());
  233394. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  233395. @try
  233396. {
  233397. [NSApp run];
  233398. }
  233399. @catch (NSException* e)
  233400. {
  233401. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  233402. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  233403. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  233404. }
  233405. @finally
  233406. {
  233407. }
  233408. #else
  233409. [NSApp run];
  233410. #endif
  233411. }
  233412. }
  233413. void MessageManager::stopDispatchLoop()
  233414. {
  233415. quitMessagePosted = true;
  233416. [NSApp stop: nil];
  233417. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  233418. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  233419. }
  233420. static bool isEventBlockedByModalComps (NSEvent* e)
  233421. {
  233422. if (Component::getNumCurrentlyModalComponents() == 0)
  233423. return false;
  233424. NSWindow* const w = [e window];
  233425. if (w == 0 || [w worksWhenModal])
  233426. return false;
  233427. bool isKey = false, isInputAttempt = false;
  233428. switch ([e type])
  233429. {
  233430. case NSKeyDown:
  233431. case NSKeyUp:
  233432. isKey = isInputAttempt = true;
  233433. break;
  233434. case NSLeftMouseDown:
  233435. case NSRightMouseDown:
  233436. case NSOtherMouseDown:
  233437. isInputAttempt = true;
  233438. break;
  233439. case NSLeftMouseDragged:
  233440. case NSRightMouseDragged:
  233441. case NSLeftMouseUp:
  233442. case NSRightMouseUp:
  233443. case NSOtherMouseUp:
  233444. case NSOtherMouseDragged:
  233445. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  233446. return false;
  233447. break;
  233448. case NSMouseMoved:
  233449. case NSMouseEntered:
  233450. case NSMouseExited:
  233451. case NSCursorUpdate:
  233452. case NSScrollWheel:
  233453. case NSTabletPoint:
  233454. case NSTabletProximity:
  233455. break;
  233456. default:
  233457. return false;
  233458. }
  233459. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  233460. {
  233461. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  233462. NSView* const compView = (NSView*) peer->getNativeHandle();
  233463. if ([compView window] == w)
  233464. {
  233465. if (isKey)
  233466. {
  233467. if (compView == [w firstResponder])
  233468. return false;
  233469. }
  233470. else
  233471. {
  233472. if (NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil],
  233473. [compView bounds]))
  233474. return false;
  233475. }
  233476. }
  233477. }
  233478. if (isInputAttempt)
  233479. {
  233480. if (! [NSApp isActive])
  233481. [NSApp activateIgnoringOtherApps: YES];
  233482. Component* const modal = Component::getCurrentlyModalComponent (0);
  233483. if (modal != 0)
  233484. modal->inputAttemptWhenModal();
  233485. }
  233486. return true;
  233487. }
  233488. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  233489. {
  233490. jassert (isThisTheMessageThread()); // must only be called by the message thread
  233491. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  233492. while (! quitMessagePosted)
  233493. {
  233494. const ScopedAutoReleasePool pool;
  233495. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  233496. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  233497. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  233498. inMode: NSDefaultRunLoopMode
  233499. dequeue: YES];
  233500. if (e != 0 && ! isEventBlockedByModalComps (e))
  233501. [NSApp sendEvent: e];
  233502. if (Time::getMillisecondCounter() >= endTime)
  233503. break;
  233504. }
  233505. return ! quitMessagePosted;
  233506. }
  233507. void MessageManager::doPlatformSpecificInitialisation()
  233508. {
  233509. if (juceAppDelegate == 0)
  233510. juceAppDelegate = [[JuceAppDelegate alloc] init];
  233511. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  233512. // correctly (needed prior to 10.5)
  233513. if (! [NSThread isMultiThreaded])
  233514. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  233515. toTarget: juceAppDelegate
  233516. withObject: nil];
  233517. }
  233518. void MessageManager::doPlatformSpecificShutdown()
  233519. {
  233520. if (juceAppDelegate != 0)
  233521. {
  233522. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  233523. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  233524. [juceAppDelegate release];
  233525. juceAppDelegate = 0;
  233526. }
  233527. }
  233528. bool juce_postMessageToSystemQueue (Message* message)
  233529. {
  233530. juceAppDelegate->redirector->postMessage (message);
  233531. return true;
  233532. }
  233533. void MessageManager::broadcastMessage (const String& value) throw()
  233534. {
  233535. }
  233536. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  233537. {
  233538. if (isThisTheMessageThread())
  233539. {
  233540. return (*callback) (data);
  233541. }
  233542. else
  233543. {
  233544. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  233545. // deadlock because the message manager is blocked from running, so can never
  233546. // call your function..
  233547. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  233548. const ScopedAutoReleasePool pool;
  233549. AppDelegateRedirector::CallbackMessagePayload cmp;
  233550. cmp.function = callback;
  233551. cmp.parameter = data;
  233552. cmp.result = 0;
  233553. cmp.hasBeenExecuted = false;
  233554. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  233555. withObject: [NSData dataWithBytesNoCopy: &cmp
  233556. length: sizeof (cmp)
  233557. freeWhenDone: NO]
  233558. waitUntilDone: YES];
  233559. return cmp.result;
  233560. }
  233561. }
  233562. #endif
  233563. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  233564. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  233565. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233566. // compiled on its own).
  233567. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  233568. #if JUCE_MAC
  233569. END_JUCE_NAMESPACE
  233570. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  233571. @interface DownloadClickDetector : NSObject
  233572. {
  233573. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  233574. }
  233575. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  233576. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  233577. request: (NSURLRequest*) request
  233578. frame: (WebFrame*) frame
  233579. decisionListener: (id<WebPolicyDecisionListener>) listener;
  233580. @end
  233581. @implementation DownloadClickDetector
  233582. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  233583. {
  233584. [super init];
  233585. ownerComponent = ownerComponent_;
  233586. return self;
  233587. }
  233588. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  233589. request: (NSURLRequest*) request
  233590. frame: (WebFrame*) frame
  233591. decisionListener: (id <WebPolicyDecisionListener>) listener
  233592. {
  233593. (void) sender;
  233594. (void) request;
  233595. (void) frame;
  233596. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  233597. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  233598. [listener use];
  233599. else
  233600. [listener ignore];
  233601. }
  233602. @end
  233603. BEGIN_JUCE_NAMESPACE
  233604. class WebBrowserComponentInternal : public NSViewComponent
  233605. {
  233606. public:
  233607. WebBrowserComponentInternal (WebBrowserComponent* owner)
  233608. {
  233609. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  233610. frameName: @""
  233611. groupName: @""];
  233612. setView (webView);
  233613. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  233614. [webView setPolicyDelegate: clickListener];
  233615. }
  233616. ~WebBrowserComponentInternal()
  233617. {
  233618. [webView setPolicyDelegate: nil];
  233619. [clickListener release];
  233620. setView (0);
  233621. }
  233622. void goToURL (const String& url,
  233623. const StringArray* headers,
  233624. const MemoryBlock* postData)
  233625. {
  233626. NSMutableURLRequest* r
  233627. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  233628. cachePolicy: NSURLRequestUseProtocolCachePolicy
  233629. timeoutInterval: 30.0];
  233630. if (postData != 0 && postData->getSize() > 0)
  233631. {
  233632. [r setHTTPMethod: @"POST"];
  233633. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  233634. length: postData->getSize()]];
  233635. }
  233636. if (headers != 0)
  233637. {
  233638. for (int i = 0; i < headers->size(); ++i)
  233639. {
  233640. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  233641. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  233642. [r setValue: juceStringToNS (headerValue)
  233643. forHTTPHeaderField: juceStringToNS (headerName)];
  233644. }
  233645. }
  233646. stop();
  233647. [[webView mainFrame] loadRequest: r];
  233648. }
  233649. void goBack()
  233650. {
  233651. [webView goBack];
  233652. }
  233653. void goForward()
  233654. {
  233655. [webView goForward];
  233656. }
  233657. void stop()
  233658. {
  233659. [webView stopLoading: nil];
  233660. }
  233661. void refresh()
  233662. {
  233663. [webView reload: nil];
  233664. }
  233665. private:
  233666. WebView* webView;
  233667. DownloadClickDetector* clickListener;
  233668. };
  233669. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  233670. : browser (0),
  233671. blankPageShown (false),
  233672. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  233673. {
  233674. setOpaque (true);
  233675. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  233676. }
  233677. WebBrowserComponent::~WebBrowserComponent()
  233678. {
  233679. deleteAndZero (browser);
  233680. }
  233681. void WebBrowserComponent::goToURL (const String& url,
  233682. const StringArray* headers,
  233683. const MemoryBlock* postData)
  233684. {
  233685. lastURL = url;
  233686. lastHeaders.clear();
  233687. if (headers != 0)
  233688. lastHeaders = *headers;
  233689. lastPostData.setSize (0);
  233690. if (postData != 0)
  233691. lastPostData = *postData;
  233692. blankPageShown = false;
  233693. browser->goToURL (url, headers, postData);
  233694. }
  233695. void WebBrowserComponent::stop()
  233696. {
  233697. browser->stop();
  233698. }
  233699. void WebBrowserComponent::goBack()
  233700. {
  233701. lastURL = String::empty;
  233702. blankPageShown = false;
  233703. browser->goBack();
  233704. }
  233705. void WebBrowserComponent::goForward()
  233706. {
  233707. lastURL = String::empty;
  233708. browser->goForward();
  233709. }
  233710. void WebBrowserComponent::refresh()
  233711. {
  233712. browser->refresh();
  233713. }
  233714. void WebBrowserComponent::paint (Graphics&)
  233715. {
  233716. }
  233717. void WebBrowserComponent::checkWindowAssociation()
  233718. {
  233719. if (isShowing())
  233720. {
  233721. if (blankPageShown)
  233722. goBack();
  233723. }
  233724. else
  233725. {
  233726. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  233727. {
  233728. // when the component becomes invisible, some stuff like flash
  233729. // carries on playing audio, so we need to force it onto a blank
  233730. // page to avoid this, (and send it back when it's made visible again).
  233731. blankPageShown = true;
  233732. browser->goToURL ("about:blank", 0, 0);
  233733. }
  233734. }
  233735. }
  233736. void WebBrowserComponent::reloadLastURL()
  233737. {
  233738. if (lastURL.isNotEmpty())
  233739. {
  233740. goToURL (lastURL, &lastHeaders, &lastPostData);
  233741. lastURL = String::empty;
  233742. }
  233743. }
  233744. void WebBrowserComponent::parentHierarchyChanged()
  233745. {
  233746. checkWindowAssociation();
  233747. }
  233748. void WebBrowserComponent::resized()
  233749. {
  233750. browser->setSize (getWidth(), getHeight());
  233751. }
  233752. void WebBrowserComponent::visibilityChanged()
  233753. {
  233754. checkWindowAssociation();
  233755. }
  233756. bool WebBrowserComponent::pageAboutToLoad (const String&)
  233757. {
  233758. return true;
  233759. }
  233760. #else
  233761. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  233762. {
  233763. }
  233764. WebBrowserComponent::~WebBrowserComponent()
  233765. {
  233766. }
  233767. void WebBrowserComponent::goToURL (const String& url,
  233768. const StringArray* headers,
  233769. const MemoryBlock* postData)
  233770. {
  233771. }
  233772. void WebBrowserComponent::stop()
  233773. {
  233774. }
  233775. void WebBrowserComponent::goBack()
  233776. {
  233777. }
  233778. void WebBrowserComponent::goForward()
  233779. {
  233780. }
  233781. void WebBrowserComponent::refresh()
  233782. {
  233783. }
  233784. void WebBrowserComponent::paint (Graphics& g)
  233785. {
  233786. }
  233787. void WebBrowserComponent::checkWindowAssociation()
  233788. {
  233789. }
  233790. void WebBrowserComponent::reloadLastURL()
  233791. {
  233792. }
  233793. void WebBrowserComponent::parentHierarchyChanged()
  233794. {
  233795. }
  233796. void WebBrowserComponent::resized()
  233797. {
  233798. }
  233799. void WebBrowserComponent::visibilityChanged()
  233800. {
  233801. }
  233802. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  233803. {
  233804. return true;
  233805. }
  233806. #endif
  233807. #endif
  233808. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  233809. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  233810. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233811. // compiled on its own).
  233812. #if JUCE_INCLUDED_FILE
  233813. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  233814. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  233815. #endif
  233816. #undef log
  233817. #if JUCE_COREAUDIO_LOGGING_ENABLED
  233818. #define log(a) Logger::writeToLog (a)
  233819. #else
  233820. #define log(a)
  233821. #endif
  233822. #undef OK
  233823. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  233824. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  233825. {
  233826. if (err == noErr)
  233827. return true;
  233828. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  233829. jassertfalse;
  233830. return false;
  233831. }
  233832. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  233833. #else
  233834. #define OK(a) (a == noErr)
  233835. #endif
  233836. class CoreAudioInternal : public Timer
  233837. {
  233838. public:
  233839. CoreAudioInternal (AudioDeviceID id)
  233840. : inputLatency (0),
  233841. outputLatency (0),
  233842. callback (0),
  233843. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  233844. audioProcID (0),
  233845. #endif
  233846. isSlaveDevice (false),
  233847. deviceID (id),
  233848. started (false),
  233849. sampleRate (0),
  233850. bufferSize (512),
  233851. numInputChans (0),
  233852. numOutputChans (0),
  233853. callbacksAllowed (true),
  233854. numInputChannelInfos (0),
  233855. numOutputChannelInfos (0)
  233856. {
  233857. jassert (deviceID != 0);
  233858. updateDetailsFromDevice();
  233859. AudioObjectPropertyAddress pa;
  233860. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  233861. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233862. pa.mElement = kAudioObjectPropertyElementWildcard;
  233863. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  233864. }
  233865. ~CoreAudioInternal()
  233866. {
  233867. AudioObjectPropertyAddress pa;
  233868. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  233869. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233870. pa.mElement = kAudioObjectPropertyElementWildcard;
  233871. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  233872. stop (false);
  233873. }
  233874. void allocateTempBuffers()
  233875. {
  233876. const int tempBufSize = bufferSize + 4;
  233877. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  233878. tempInputBuffers.calloc (numInputChans + 2);
  233879. tempOutputBuffers.calloc (numOutputChans + 2);
  233880. int i, count = 0;
  233881. for (i = 0; i < numInputChans; ++i)
  233882. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  233883. for (i = 0; i < numOutputChans; ++i)
  233884. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  233885. }
  233886. // returns the number of actual available channels
  233887. void fillInChannelInfo (const bool input)
  233888. {
  233889. int chanNum = 0;
  233890. UInt32 size;
  233891. AudioObjectPropertyAddress pa;
  233892. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  233893. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233894. pa.mElement = kAudioObjectPropertyElementMaster;
  233895. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233896. {
  233897. HeapBlock <AudioBufferList> bufList;
  233898. bufList.calloc (size, 1);
  233899. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  233900. {
  233901. const int numStreams = bufList->mNumberBuffers;
  233902. for (int i = 0; i < numStreams; ++i)
  233903. {
  233904. const AudioBuffer& b = bufList->mBuffers[i];
  233905. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  233906. {
  233907. String name;
  233908. {
  233909. char channelName [256];
  233910. zerostruct (channelName);
  233911. UInt32 nameSize = sizeof (channelName);
  233912. UInt32 channelNum = chanNum + 1;
  233913. pa.mSelector = kAudioDevicePropertyChannelName;
  233914. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  233915. name = String::fromUTF8 (channelName, nameSize);
  233916. }
  233917. if (input)
  233918. {
  233919. if (activeInputChans[chanNum])
  233920. {
  233921. inputChannelInfo [numInputChannelInfos].streamNum = i;
  233922. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  233923. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  233924. ++numInputChannelInfos;
  233925. }
  233926. if (name.isEmpty())
  233927. name << "Input " << (chanNum + 1);
  233928. inChanNames.add (name);
  233929. }
  233930. else
  233931. {
  233932. if (activeOutputChans[chanNum])
  233933. {
  233934. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  233935. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  233936. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  233937. ++numOutputChannelInfos;
  233938. }
  233939. if (name.isEmpty())
  233940. name << "Output " << (chanNum + 1);
  233941. outChanNames.add (name);
  233942. }
  233943. ++chanNum;
  233944. }
  233945. }
  233946. }
  233947. }
  233948. }
  233949. void updateDetailsFromDevice()
  233950. {
  233951. stopTimer();
  233952. if (deviceID == 0)
  233953. return;
  233954. const ScopedLock sl (callbackLock);
  233955. Float64 sr;
  233956. UInt32 size = sizeof (Float64);
  233957. AudioObjectPropertyAddress pa;
  233958. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  233959. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233960. pa.mElement = kAudioObjectPropertyElementMaster;
  233961. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  233962. sampleRate = sr;
  233963. UInt32 framesPerBuf;
  233964. size = sizeof (framesPerBuf);
  233965. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  233966. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  233967. {
  233968. bufferSize = framesPerBuf;
  233969. allocateTempBuffers();
  233970. }
  233971. bufferSizes.clear();
  233972. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  233973. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233974. {
  233975. HeapBlock <AudioValueRange> ranges;
  233976. ranges.calloc (size, 1);
  233977. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  233978. {
  233979. bufferSizes.add ((int) ranges[0].mMinimum);
  233980. for (int i = 32; i < 2048; i += 32)
  233981. {
  233982. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  233983. {
  233984. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  233985. {
  233986. bufferSizes.addIfNotAlreadyThere (i);
  233987. break;
  233988. }
  233989. }
  233990. }
  233991. if (bufferSize > 0)
  233992. bufferSizes.addIfNotAlreadyThere (bufferSize);
  233993. }
  233994. }
  233995. if (bufferSizes.size() == 0 && bufferSize > 0)
  233996. bufferSizes.add (bufferSize);
  233997. sampleRates.clear();
  233998. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  233999. String rates;
  234000. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  234001. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234002. {
  234003. HeapBlock <AudioValueRange> ranges;
  234004. ranges.calloc (size, 1);
  234005. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  234006. {
  234007. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  234008. {
  234009. bool ok = false;
  234010. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  234011. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  234012. ok = true;
  234013. if (ok)
  234014. {
  234015. sampleRates.add (possibleRates[i]);
  234016. rates << possibleRates[i] << ' ';
  234017. }
  234018. }
  234019. }
  234020. }
  234021. if (sampleRates.size() == 0 && sampleRate > 0)
  234022. {
  234023. sampleRates.add (sampleRate);
  234024. rates << sampleRate;
  234025. }
  234026. log ("sr: " + rates);
  234027. inputLatency = 0;
  234028. outputLatency = 0;
  234029. UInt32 lat;
  234030. size = sizeof (lat);
  234031. pa.mSelector = kAudioDevicePropertyLatency;
  234032. pa.mScope = kAudioDevicePropertyScopeInput;
  234033. //if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  234034. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  234035. inputLatency = (int) lat;
  234036. pa.mScope = kAudioDevicePropertyScopeOutput;
  234037. size = sizeof (lat);
  234038. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  234039. outputLatency = (int) lat;
  234040. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  234041. inChanNames.clear();
  234042. outChanNames.clear();
  234043. inputChannelInfo.calloc (numInputChans + 2);
  234044. numInputChannelInfos = 0;
  234045. outputChannelInfo.calloc (numOutputChans + 2);
  234046. numOutputChannelInfos = 0;
  234047. fillInChannelInfo (true);
  234048. fillInChannelInfo (false);
  234049. }
  234050. const StringArray getSources (bool input)
  234051. {
  234052. StringArray s;
  234053. HeapBlock <OSType> types;
  234054. const int num = getAllDataSourcesForDevice (deviceID, types);
  234055. for (int i = 0; i < num; ++i)
  234056. {
  234057. AudioValueTranslation avt;
  234058. char buffer[256];
  234059. avt.mInputData = &(types[i]);
  234060. avt.mInputDataSize = sizeof (UInt32);
  234061. avt.mOutputData = buffer;
  234062. avt.mOutputDataSize = 256;
  234063. UInt32 transSize = sizeof (avt);
  234064. AudioObjectPropertyAddress pa;
  234065. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  234066. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234067. pa.mElement = kAudioObjectPropertyElementMaster;
  234068. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  234069. {
  234070. DBG (buffer);
  234071. s.add (buffer);
  234072. }
  234073. }
  234074. return s;
  234075. }
  234076. int getCurrentSourceIndex (bool input) const
  234077. {
  234078. OSType currentSourceID = 0;
  234079. UInt32 size = sizeof (currentSourceID);
  234080. int result = -1;
  234081. AudioObjectPropertyAddress pa;
  234082. pa.mSelector = kAudioDevicePropertyDataSource;
  234083. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234084. pa.mElement = kAudioObjectPropertyElementMaster;
  234085. if (deviceID != 0)
  234086. {
  234087. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  234088. {
  234089. HeapBlock <OSType> types;
  234090. const int num = getAllDataSourcesForDevice (deviceID, types);
  234091. for (int i = 0; i < num; ++i)
  234092. {
  234093. if (types[num] == currentSourceID)
  234094. {
  234095. result = i;
  234096. break;
  234097. }
  234098. }
  234099. }
  234100. }
  234101. return result;
  234102. }
  234103. void setCurrentSourceIndex (int index, bool input)
  234104. {
  234105. if (deviceID != 0)
  234106. {
  234107. HeapBlock <OSType> types;
  234108. const int num = getAllDataSourcesForDevice (deviceID, types);
  234109. if (((unsigned int) index) < (unsigned int) num)
  234110. {
  234111. AudioObjectPropertyAddress pa;
  234112. pa.mSelector = kAudioDevicePropertyDataSource;
  234113. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234114. pa.mElement = kAudioObjectPropertyElementMaster;
  234115. OSType typeId = types[index];
  234116. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  234117. }
  234118. }
  234119. }
  234120. const String reopen (const BigInteger& inputChannels,
  234121. const BigInteger& outputChannels,
  234122. double newSampleRate,
  234123. int bufferSizeSamples)
  234124. {
  234125. String error;
  234126. log ("CoreAudio reopen");
  234127. callbacksAllowed = false;
  234128. stopTimer();
  234129. stop (false);
  234130. activeInputChans = inputChannels;
  234131. activeInputChans.setRange (inChanNames.size(),
  234132. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  234133. false);
  234134. activeOutputChans = outputChannels;
  234135. activeOutputChans.setRange (outChanNames.size(),
  234136. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  234137. false);
  234138. numInputChans = activeInputChans.countNumberOfSetBits();
  234139. numOutputChans = activeOutputChans.countNumberOfSetBits();
  234140. // set sample rate
  234141. AudioObjectPropertyAddress pa;
  234142. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  234143. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234144. pa.mElement = kAudioObjectPropertyElementMaster;
  234145. Float64 sr = newSampleRate;
  234146. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  234147. {
  234148. error = "Couldn't change sample rate";
  234149. }
  234150. else
  234151. {
  234152. // change buffer size
  234153. UInt32 framesPerBuf = bufferSizeSamples;
  234154. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  234155. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  234156. {
  234157. error = "Couldn't change buffer size";
  234158. }
  234159. else
  234160. {
  234161. // Annoyingly, after changing the rate and buffer size, some devices fail to
  234162. // correctly report their new settings until some random time in the future, so
  234163. // after calling updateDetailsFromDevice, we need to manually bodge these values
  234164. // to make sure we're using the correct numbers..
  234165. updateDetailsFromDevice();
  234166. sampleRate = newSampleRate;
  234167. bufferSize = bufferSizeSamples;
  234168. if (sampleRates.size() == 0)
  234169. error = "Device has no available sample-rates";
  234170. else if (bufferSizes.size() == 0)
  234171. error = "Device has no available buffer-sizes";
  234172. else if (inputDevice != 0)
  234173. error = inputDevice->reopen (inputChannels,
  234174. outputChannels,
  234175. newSampleRate,
  234176. bufferSizeSamples);
  234177. }
  234178. }
  234179. callbacksAllowed = true;
  234180. return error;
  234181. }
  234182. bool start (AudioIODeviceCallback* cb)
  234183. {
  234184. if (! started)
  234185. {
  234186. callback = 0;
  234187. if (deviceID != 0)
  234188. {
  234189. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234190. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  234191. #else
  234192. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  234193. #endif
  234194. {
  234195. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  234196. {
  234197. started = true;
  234198. }
  234199. else
  234200. {
  234201. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234202. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  234203. #else
  234204. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  234205. audioProcID = 0;
  234206. #endif
  234207. }
  234208. }
  234209. }
  234210. }
  234211. if (started)
  234212. {
  234213. const ScopedLock sl (callbackLock);
  234214. callback = cb;
  234215. }
  234216. if (inputDevice != 0)
  234217. return started && inputDevice->start (cb);
  234218. else
  234219. return started;
  234220. }
  234221. void stop (bool leaveInterruptRunning)
  234222. {
  234223. {
  234224. const ScopedLock sl (callbackLock);
  234225. callback = 0;
  234226. }
  234227. if (started
  234228. && (deviceID != 0)
  234229. && ! leaveInterruptRunning)
  234230. {
  234231. OK (AudioDeviceStop (deviceID, audioIOProc));
  234232. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234233. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  234234. #else
  234235. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  234236. audioProcID = 0;
  234237. #endif
  234238. started = false;
  234239. { const ScopedLock sl (callbackLock); }
  234240. // wait until it's definately stopped calling back..
  234241. for (int i = 40; --i >= 0;)
  234242. {
  234243. Thread::sleep (50);
  234244. UInt32 running = 0;
  234245. UInt32 size = sizeof (running);
  234246. AudioObjectPropertyAddress pa;
  234247. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  234248. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234249. pa.mElement = kAudioObjectPropertyElementMaster;
  234250. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  234251. if (running == 0)
  234252. break;
  234253. }
  234254. const ScopedLock sl (callbackLock);
  234255. }
  234256. if (inputDevice != 0)
  234257. inputDevice->stop (leaveInterruptRunning);
  234258. }
  234259. double getSampleRate() const
  234260. {
  234261. return sampleRate;
  234262. }
  234263. int getBufferSize() const
  234264. {
  234265. return bufferSize;
  234266. }
  234267. void audioCallback (const AudioBufferList* inInputData,
  234268. AudioBufferList* outOutputData)
  234269. {
  234270. int i;
  234271. const ScopedLock sl (callbackLock);
  234272. if (callback != 0)
  234273. {
  234274. if (inputDevice == 0)
  234275. {
  234276. for (i = numInputChans; --i >= 0;)
  234277. {
  234278. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  234279. float* dest = tempInputBuffers [i];
  234280. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  234281. + info.dataOffsetSamples;
  234282. const int stride = info.dataStrideSamples;
  234283. if (stride != 0) // if this is zero, info is invalid
  234284. {
  234285. for (int j = bufferSize; --j >= 0;)
  234286. {
  234287. *dest++ = *src;
  234288. src += stride;
  234289. }
  234290. }
  234291. }
  234292. }
  234293. if (! isSlaveDevice)
  234294. {
  234295. if (inputDevice == 0)
  234296. {
  234297. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  234298. numInputChans,
  234299. tempOutputBuffers,
  234300. numOutputChans,
  234301. bufferSize);
  234302. }
  234303. else
  234304. {
  234305. jassert (inputDevice->bufferSize == bufferSize);
  234306. // Sometimes the two linked devices seem to get their callbacks in
  234307. // parallel, so we need to lock both devices to stop the input data being
  234308. // changed while inside our callback..
  234309. const ScopedLock sl2 (inputDevice->callbackLock);
  234310. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  234311. inputDevice->numInputChans,
  234312. tempOutputBuffers,
  234313. numOutputChans,
  234314. bufferSize);
  234315. }
  234316. for (i = numOutputChans; --i >= 0;)
  234317. {
  234318. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  234319. const float* src = tempOutputBuffers [i];
  234320. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  234321. + info.dataOffsetSamples;
  234322. const int stride = info.dataStrideSamples;
  234323. if (stride != 0) // if this is zero, info is invalid
  234324. {
  234325. for (int j = bufferSize; --j >= 0;)
  234326. {
  234327. *dest = *src++;
  234328. dest += stride;
  234329. }
  234330. }
  234331. }
  234332. }
  234333. }
  234334. else
  234335. {
  234336. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  234337. {
  234338. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  234339. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  234340. + info.dataOffsetSamples;
  234341. const int stride = info.dataStrideSamples;
  234342. if (stride != 0) // if this is zero, info is invalid
  234343. {
  234344. for (int j = bufferSize; --j >= 0;)
  234345. {
  234346. *dest = 0.0f;
  234347. dest += stride;
  234348. }
  234349. }
  234350. }
  234351. }
  234352. }
  234353. // called by callbacks
  234354. void deviceDetailsChanged()
  234355. {
  234356. if (callbacksAllowed)
  234357. startTimer (100);
  234358. }
  234359. void timerCallback()
  234360. {
  234361. stopTimer();
  234362. log ("CoreAudio device changed callback");
  234363. const double oldSampleRate = sampleRate;
  234364. const int oldBufferSize = bufferSize;
  234365. updateDetailsFromDevice();
  234366. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  234367. {
  234368. callbacksAllowed = false;
  234369. stop (false);
  234370. updateDetailsFromDevice();
  234371. callbacksAllowed = true;
  234372. }
  234373. }
  234374. CoreAudioInternal* getRelatedDevice() const
  234375. {
  234376. UInt32 size = 0;
  234377. ScopedPointer <CoreAudioInternal> result;
  234378. AudioObjectPropertyAddress pa;
  234379. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  234380. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234381. pa.mElement = kAudioObjectPropertyElementMaster;
  234382. if (deviceID != 0
  234383. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  234384. && size > 0)
  234385. {
  234386. HeapBlock <AudioDeviceID> devs;
  234387. devs.calloc (size, 1);
  234388. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  234389. {
  234390. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  234391. {
  234392. if (devs[i] != deviceID && devs[i] != 0)
  234393. {
  234394. result = new CoreAudioInternal (devs[i]);
  234395. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  234396. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  234397. if (thisIsInput != otherIsInput
  234398. || (inChanNames.size() + outChanNames.size() == 0)
  234399. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  234400. break;
  234401. result = 0;
  234402. }
  234403. }
  234404. }
  234405. }
  234406. return result.release();
  234407. }
  234408. juce_UseDebuggingNewOperator
  234409. int inputLatency, outputLatency;
  234410. BigInteger activeInputChans, activeOutputChans;
  234411. StringArray inChanNames, outChanNames;
  234412. Array <double> sampleRates;
  234413. Array <int> bufferSizes;
  234414. AudioIODeviceCallback* callback;
  234415. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  234416. AudioDeviceIOProcID audioProcID;
  234417. #endif
  234418. ScopedPointer<CoreAudioInternal> inputDevice;
  234419. bool isSlaveDevice;
  234420. private:
  234421. CriticalSection callbackLock;
  234422. AudioDeviceID deviceID;
  234423. bool started;
  234424. double sampleRate;
  234425. int bufferSize;
  234426. HeapBlock <float> audioBuffer;
  234427. int numInputChans, numOutputChans;
  234428. bool callbacksAllowed;
  234429. struct CallbackDetailsForChannel
  234430. {
  234431. int streamNum;
  234432. int dataOffsetSamples;
  234433. int dataStrideSamples;
  234434. };
  234435. int numInputChannelInfos, numOutputChannelInfos;
  234436. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  234437. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  234438. CoreAudioInternal (const CoreAudioInternal&);
  234439. CoreAudioInternal& operator= (const CoreAudioInternal&);
  234440. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  234441. const AudioTimeStamp* /*inNow*/,
  234442. const AudioBufferList* inInputData,
  234443. const AudioTimeStamp* /*inInputTime*/,
  234444. AudioBufferList* outOutputData,
  234445. const AudioTimeStamp* /*inOutputTime*/,
  234446. void* device)
  234447. {
  234448. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  234449. return noErr;
  234450. }
  234451. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  234452. {
  234453. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  234454. switch (pa->mSelector)
  234455. {
  234456. case kAudioDevicePropertyBufferSize:
  234457. case kAudioDevicePropertyBufferFrameSize:
  234458. case kAudioDevicePropertyNominalSampleRate:
  234459. case kAudioDevicePropertyStreamFormat:
  234460. case kAudioDevicePropertyDeviceIsAlive:
  234461. intern->deviceDetailsChanged();
  234462. break;
  234463. case kAudioDevicePropertyBufferSizeRange:
  234464. case kAudioDevicePropertyVolumeScalar:
  234465. case kAudioDevicePropertyMute:
  234466. case kAudioDevicePropertyPlayThru:
  234467. case kAudioDevicePropertyDataSource:
  234468. case kAudioDevicePropertyDeviceIsRunning:
  234469. break;
  234470. }
  234471. return noErr;
  234472. }
  234473. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  234474. {
  234475. AudioObjectPropertyAddress pa;
  234476. pa.mSelector = kAudioDevicePropertyDataSources;
  234477. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234478. pa.mElement = kAudioObjectPropertyElementMaster;
  234479. UInt32 size = 0;
  234480. if (deviceID != 0
  234481. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234482. {
  234483. types.calloc (size, 1);
  234484. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  234485. return size / (int) sizeof (OSType);
  234486. }
  234487. return 0;
  234488. }
  234489. };
  234490. class CoreAudioIODevice : public AudioIODevice
  234491. {
  234492. public:
  234493. CoreAudioIODevice (const String& deviceName,
  234494. AudioDeviceID inputDeviceId,
  234495. const int inputIndex_,
  234496. AudioDeviceID outputDeviceId,
  234497. const int outputIndex_)
  234498. : AudioIODevice (deviceName, "CoreAudio"),
  234499. inputIndex (inputIndex_),
  234500. outputIndex (outputIndex_),
  234501. isOpen_ (false),
  234502. isStarted (false)
  234503. {
  234504. CoreAudioInternal* device = 0;
  234505. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  234506. {
  234507. jassert (inputDeviceId != 0);
  234508. device = new CoreAudioInternal (inputDeviceId);
  234509. }
  234510. else
  234511. {
  234512. device = new CoreAudioInternal (outputDeviceId);
  234513. if (inputDeviceId != 0)
  234514. {
  234515. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  234516. device->inputDevice = secondDevice;
  234517. secondDevice->isSlaveDevice = true;
  234518. }
  234519. }
  234520. internal = device;
  234521. AudioObjectPropertyAddress pa;
  234522. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234523. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234524. pa.mElement = kAudioObjectPropertyElementWildcard;
  234525. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  234526. }
  234527. ~CoreAudioIODevice()
  234528. {
  234529. AudioObjectPropertyAddress pa;
  234530. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234531. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234532. pa.mElement = kAudioObjectPropertyElementWildcard;
  234533. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  234534. }
  234535. const StringArray getOutputChannelNames()
  234536. {
  234537. return internal->outChanNames;
  234538. }
  234539. const StringArray getInputChannelNames()
  234540. {
  234541. if (internal->inputDevice != 0)
  234542. return internal->inputDevice->inChanNames;
  234543. else
  234544. return internal->inChanNames;
  234545. }
  234546. int getNumSampleRates()
  234547. {
  234548. return internal->sampleRates.size();
  234549. }
  234550. double getSampleRate (int index)
  234551. {
  234552. return internal->sampleRates [index];
  234553. }
  234554. int getNumBufferSizesAvailable()
  234555. {
  234556. return internal->bufferSizes.size();
  234557. }
  234558. int getBufferSizeSamples (int index)
  234559. {
  234560. return internal->bufferSizes [index];
  234561. }
  234562. int getDefaultBufferSize()
  234563. {
  234564. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  234565. if (getBufferSizeSamples(i) >= 512)
  234566. return getBufferSizeSamples(i);
  234567. return 512;
  234568. }
  234569. const String open (const BigInteger& inputChannels,
  234570. const BigInteger& outputChannels,
  234571. double sampleRate,
  234572. int bufferSizeSamples)
  234573. {
  234574. isOpen_ = true;
  234575. if (bufferSizeSamples <= 0)
  234576. bufferSizeSamples = getDefaultBufferSize();
  234577. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  234578. isOpen_ = lastError.isEmpty();
  234579. return lastError;
  234580. }
  234581. void close()
  234582. {
  234583. isOpen_ = false;
  234584. internal->stop (false);
  234585. }
  234586. bool isOpen()
  234587. {
  234588. return isOpen_;
  234589. }
  234590. int getCurrentBufferSizeSamples()
  234591. {
  234592. return internal != 0 ? internal->getBufferSize() : 512;
  234593. }
  234594. double getCurrentSampleRate()
  234595. {
  234596. return internal != 0 ? internal->getSampleRate() : 0;
  234597. }
  234598. int getCurrentBitDepth()
  234599. {
  234600. return 32; // no way to find out, so just assume it's high..
  234601. }
  234602. const BigInteger getActiveOutputChannels() const
  234603. {
  234604. return internal != 0 ? internal->activeOutputChans : BigInteger();
  234605. }
  234606. const BigInteger getActiveInputChannels() const
  234607. {
  234608. BigInteger chans;
  234609. if (internal != 0)
  234610. {
  234611. chans = internal->activeInputChans;
  234612. if (internal->inputDevice != 0)
  234613. chans |= internal->inputDevice->activeInputChans;
  234614. }
  234615. return chans;
  234616. }
  234617. int getOutputLatencyInSamples()
  234618. {
  234619. if (internal == 0)
  234620. return 0;
  234621. // this seems like a good guess at getting the latency right - comparing
  234622. // this with a round-trip measurement, it gets it to within a few millisecs
  234623. // for the built-in mac soundcard
  234624. return internal->outputLatency + internal->getBufferSize() * 2;
  234625. }
  234626. int getInputLatencyInSamples()
  234627. {
  234628. if (internal == 0)
  234629. return 0;
  234630. return internal->inputLatency + internal->getBufferSize() * 2;
  234631. }
  234632. void start (AudioIODeviceCallback* callback)
  234633. {
  234634. if (internal != 0 && ! isStarted)
  234635. {
  234636. if (callback != 0)
  234637. callback->audioDeviceAboutToStart (this);
  234638. isStarted = true;
  234639. internal->start (callback);
  234640. }
  234641. }
  234642. void stop()
  234643. {
  234644. if (isStarted && internal != 0)
  234645. {
  234646. AudioIODeviceCallback* const lastCallback = internal->callback;
  234647. isStarted = false;
  234648. internal->stop (true);
  234649. if (lastCallback != 0)
  234650. lastCallback->audioDeviceStopped();
  234651. }
  234652. }
  234653. bool isPlaying()
  234654. {
  234655. if (internal->callback == 0)
  234656. isStarted = false;
  234657. return isStarted;
  234658. }
  234659. const String getLastError()
  234660. {
  234661. return lastError;
  234662. }
  234663. int inputIndex, outputIndex;
  234664. juce_UseDebuggingNewOperator
  234665. private:
  234666. ScopedPointer<CoreAudioInternal> internal;
  234667. bool isOpen_, isStarted;
  234668. String lastError;
  234669. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  234670. {
  234671. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  234672. switch (pa->mSelector)
  234673. {
  234674. case kAudioHardwarePropertyDevices:
  234675. intern->deviceDetailsChanged();
  234676. break;
  234677. case kAudioHardwarePropertyDefaultOutputDevice:
  234678. case kAudioHardwarePropertyDefaultInputDevice:
  234679. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  234680. break;
  234681. }
  234682. return noErr;
  234683. }
  234684. CoreAudioIODevice (const CoreAudioIODevice&);
  234685. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  234686. };
  234687. class CoreAudioIODeviceType : public AudioIODeviceType
  234688. {
  234689. public:
  234690. CoreAudioIODeviceType()
  234691. : AudioIODeviceType ("CoreAudio"),
  234692. hasScanned (false)
  234693. {
  234694. }
  234695. ~CoreAudioIODeviceType()
  234696. {
  234697. }
  234698. void scanForDevices()
  234699. {
  234700. hasScanned = true;
  234701. inputDeviceNames.clear();
  234702. outputDeviceNames.clear();
  234703. inputIds.clear();
  234704. outputIds.clear();
  234705. UInt32 size;
  234706. AudioObjectPropertyAddress pa;
  234707. pa.mSelector = kAudioHardwarePropertyDevices;
  234708. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234709. pa.mElement = kAudioObjectPropertyElementMaster;
  234710. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  234711. {
  234712. HeapBlock <AudioDeviceID> devs;
  234713. devs.calloc (size, 1);
  234714. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  234715. {
  234716. const int num = size / (int) sizeof (AudioDeviceID);
  234717. for (int i = 0; i < num; ++i)
  234718. {
  234719. char name [1024];
  234720. size = sizeof (name);
  234721. pa.mSelector = kAudioDevicePropertyDeviceName;
  234722. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  234723. {
  234724. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  234725. const int numIns = getNumChannels (devs[i], true);
  234726. const int numOuts = getNumChannels (devs[i], false);
  234727. if (numIns > 0)
  234728. {
  234729. inputDeviceNames.add (nameString);
  234730. inputIds.add (devs[i]);
  234731. }
  234732. if (numOuts > 0)
  234733. {
  234734. outputDeviceNames.add (nameString);
  234735. outputIds.add (devs[i]);
  234736. }
  234737. }
  234738. }
  234739. }
  234740. }
  234741. inputDeviceNames.appendNumbersToDuplicates (false, true);
  234742. outputDeviceNames.appendNumbersToDuplicates (false, true);
  234743. }
  234744. const StringArray getDeviceNames (bool wantInputNames) const
  234745. {
  234746. jassert (hasScanned); // need to call scanForDevices() before doing this
  234747. if (wantInputNames)
  234748. return inputDeviceNames;
  234749. else
  234750. return outputDeviceNames;
  234751. }
  234752. int getDefaultDeviceIndex (bool forInput) const
  234753. {
  234754. jassert (hasScanned); // need to call scanForDevices() before doing this
  234755. AudioDeviceID deviceID;
  234756. UInt32 size = sizeof (deviceID);
  234757. // if they're asking for any input channels at all, use the default input, so we
  234758. // get the built-in mic rather than the built-in output with no inputs..
  234759. AudioObjectPropertyAddress pa;
  234760. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  234761. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234762. pa.mElement = kAudioObjectPropertyElementMaster;
  234763. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  234764. {
  234765. if (forInput)
  234766. {
  234767. for (int i = inputIds.size(); --i >= 0;)
  234768. if (inputIds[i] == deviceID)
  234769. return i;
  234770. }
  234771. else
  234772. {
  234773. for (int i = outputIds.size(); --i >= 0;)
  234774. if (outputIds[i] == deviceID)
  234775. return i;
  234776. }
  234777. }
  234778. return 0;
  234779. }
  234780. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  234781. {
  234782. jassert (hasScanned); // need to call scanForDevices() before doing this
  234783. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  234784. if (d == 0)
  234785. return -1;
  234786. return asInput ? d->inputIndex
  234787. : d->outputIndex;
  234788. }
  234789. bool hasSeparateInputsAndOutputs() const { return true; }
  234790. AudioIODevice* createDevice (const String& outputDeviceName,
  234791. const String& inputDeviceName)
  234792. {
  234793. jassert (hasScanned); // need to call scanForDevices() before doing this
  234794. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  234795. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  234796. String deviceName (outputDeviceName);
  234797. if (deviceName.isEmpty())
  234798. deviceName = inputDeviceName;
  234799. if (index >= 0)
  234800. return new CoreAudioIODevice (deviceName,
  234801. inputIds [inputIndex],
  234802. inputIndex,
  234803. outputIds [outputIndex],
  234804. outputIndex);
  234805. return 0;
  234806. }
  234807. juce_UseDebuggingNewOperator
  234808. private:
  234809. StringArray inputDeviceNames, outputDeviceNames;
  234810. Array <AudioDeviceID> inputIds, outputIds;
  234811. bool hasScanned;
  234812. static int getNumChannels (AudioDeviceID deviceID, bool input)
  234813. {
  234814. int total = 0;
  234815. UInt32 size;
  234816. AudioObjectPropertyAddress pa;
  234817. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  234818. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234819. pa.mElement = kAudioObjectPropertyElementMaster;
  234820. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234821. {
  234822. HeapBlock <AudioBufferList> bufList;
  234823. bufList.calloc (size, 1);
  234824. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  234825. {
  234826. const int numStreams = bufList->mNumberBuffers;
  234827. for (int i = 0; i < numStreams; ++i)
  234828. {
  234829. const AudioBuffer& b = bufList->mBuffers[i];
  234830. total += b.mNumberChannels;
  234831. }
  234832. }
  234833. }
  234834. return total;
  234835. }
  234836. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  234837. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  234838. };
  234839. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  234840. {
  234841. return new CoreAudioIODeviceType();
  234842. }
  234843. #undef log
  234844. #endif
  234845. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  234846. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  234847. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234848. // compiled on its own).
  234849. #if JUCE_INCLUDED_FILE
  234850. #if JUCE_MAC
  234851. #undef log
  234852. #define log(a) Logger::writeToLog(a)
  234853. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  234854. {
  234855. if (err == noErr)
  234856. return true;
  234857. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  234858. jassertfalse;
  234859. return false;
  234860. }
  234861. #undef OK
  234862. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  234863. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  234864. {
  234865. String result;
  234866. CFStringRef str = 0;
  234867. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  234868. if (str != 0)
  234869. {
  234870. result = PlatformUtilities::cfStringToJuceString (str);
  234871. CFRelease (str);
  234872. str = 0;
  234873. }
  234874. MIDIEntityRef entity = 0;
  234875. MIDIEndpointGetEntity (endpoint, &entity);
  234876. if (entity == 0)
  234877. return result; // probably virtual
  234878. if (result.isEmpty())
  234879. {
  234880. // endpoint name has zero length - try the entity
  234881. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  234882. if (str != 0)
  234883. {
  234884. result += PlatformUtilities::cfStringToJuceString (str);
  234885. CFRelease (str);
  234886. str = 0;
  234887. }
  234888. }
  234889. // now consider the device's name
  234890. MIDIDeviceRef device = 0;
  234891. MIDIEntityGetDevice (entity, &device);
  234892. if (device == 0)
  234893. return result;
  234894. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  234895. if (str != 0)
  234896. {
  234897. const String s (PlatformUtilities::cfStringToJuceString (str));
  234898. CFRelease (str);
  234899. // if an external device has only one entity, throw away
  234900. // the endpoint name and just use the device name
  234901. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  234902. {
  234903. result = s;
  234904. }
  234905. else if (! result.startsWithIgnoreCase (s))
  234906. {
  234907. // prepend the device name to the entity name
  234908. result = (s + " " + result).trimEnd();
  234909. }
  234910. }
  234911. return result;
  234912. }
  234913. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  234914. {
  234915. String result;
  234916. // Does the endpoint have connections?
  234917. CFDataRef connections = 0;
  234918. int numConnections = 0;
  234919. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  234920. if (connections != 0)
  234921. {
  234922. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  234923. if (numConnections > 0)
  234924. {
  234925. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  234926. for (int i = 0; i < numConnections; ++i, ++pid)
  234927. {
  234928. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  234929. MIDIObjectRef connObject;
  234930. MIDIObjectType connObjectType;
  234931. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  234932. if (err == noErr)
  234933. {
  234934. String s;
  234935. if (connObjectType == kMIDIObjectType_ExternalSource
  234936. || connObjectType == kMIDIObjectType_ExternalDestination)
  234937. {
  234938. // Connected to an external device's endpoint (10.3 and later).
  234939. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  234940. }
  234941. else
  234942. {
  234943. // Connected to an external device (10.2) (or something else, catch-all)
  234944. CFStringRef str = 0;
  234945. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  234946. if (str != 0)
  234947. {
  234948. s = PlatformUtilities::cfStringToJuceString (str);
  234949. CFRelease (str);
  234950. }
  234951. }
  234952. if (s.isNotEmpty())
  234953. {
  234954. if (result.isNotEmpty())
  234955. result += ", ";
  234956. result += s;
  234957. }
  234958. }
  234959. }
  234960. }
  234961. CFRelease (connections);
  234962. }
  234963. if (result.isNotEmpty())
  234964. return result;
  234965. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  234966. return getEndpointName (endpoint, false);
  234967. }
  234968. const StringArray MidiOutput::getDevices()
  234969. {
  234970. StringArray s;
  234971. const ItemCount num = MIDIGetNumberOfDestinations();
  234972. for (ItemCount i = 0; i < num; ++i)
  234973. {
  234974. MIDIEndpointRef dest = MIDIGetDestination (i);
  234975. if (dest != 0)
  234976. {
  234977. String name (getConnectedEndpointName (dest));
  234978. if (name.isEmpty())
  234979. name = "<error>";
  234980. s.add (name);
  234981. }
  234982. else
  234983. {
  234984. s.add ("<error>");
  234985. }
  234986. }
  234987. return s;
  234988. }
  234989. int MidiOutput::getDefaultDeviceIndex()
  234990. {
  234991. return 0;
  234992. }
  234993. static MIDIClientRef globalMidiClient;
  234994. static bool hasGlobalClientBeenCreated = false;
  234995. static bool makeSureClientExists()
  234996. {
  234997. if (! hasGlobalClientBeenCreated)
  234998. {
  234999. String name ("JUCE");
  235000. if (JUCEApplication::getInstance() != 0)
  235001. name = JUCEApplication::getInstance()->getApplicationName();
  235002. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  235003. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  235004. CFRelease (appName);
  235005. }
  235006. return hasGlobalClientBeenCreated;
  235007. }
  235008. class MidiPortAndEndpoint
  235009. {
  235010. public:
  235011. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  235012. : port (port_), endPoint (endPoint_)
  235013. {
  235014. }
  235015. ~MidiPortAndEndpoint()
  235016. {
  235017. if (port != 0)
  235018. MIDIPortDispose (port);
  235019. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  235020. MIDIEndpointDispose (endPoint);
  235021. }
  235022. MIDIPortRef port;
  235023. MIDIEndpointRef endPoint;
  235024. };
  235025. MidiOutput* MidiOutput::openDevice (int index)
  235026. {
  235027. MidiOutput* mo = 0;
  235028. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  235029. {
  235030. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  235031. CFStringRef pname;
  235032. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  235033. {
  235034. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  235035. if (makeSureClientExists())
  235036. {
  235037. MIDIPortRef port;
  235038. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  235039. {
  235040. mo = new MidiOutput();
  235041. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  235042. }
  235043. }
  235044. CFRelease (pname);
  235045. }
  235046. }
  235047. return mo;
  235048. }
  235049. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  235050. {
  235051. MidiOutput* mo = 0;
  235052. if (makeSureClientExists())
  235053. {
  235054. MIDIEndpointRef endPoint;
  235055. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  235056. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  235057. {
  235058. mo = new MidiOutput();
  235059. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  235060. }
  235061. CFRelease (name);
  235062. }
  235063. return mo;
  235064. }
  235065. MidiOutput::~MidiOutput()
  235066. {
  235067. delete (MidiPortAndEndpoint*) internal;
  235068. }
  235069. void MidiOutput::reset()
  235070. {
  235071. }
  235072. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  235073. {
  235074. return false;
  235075. }
  235076. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  235077. {
  235078. }
  235079. void MidiOutput::sendMessageNow (const MidiMessage& message)
  235080. {
  235081. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  235082. if (message.isSysEx())
  235083. {
  235084. const int maxPacketSize = 256;
  235085. int pos = 0, bytesLeft = message.getRawDataSize();
  235086. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  235087. HeapBlock <MIDIPacketList> packets;
  235088. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  235089. packets->numPackets = numPackets;
  235090. MIDIPacket* p = packets->packet;
  235091. for (int i = 0; i < numPackets; ++i)
  235092. {
  235093. p->timeStamp = 0;
  235094. p->length = jmin (maxPacketSize, bytesLeft);
  235095. memcpy (p->data, message.getRawData() + pos, p->length);
  235096. pos += p->length;
  235097. bytesLeft -= p->length;
  235098. p = MIDIPacketNext (p);
  235099. }
  235100. if (mpe->port != 0)
  235101. MIDISend (mpe->port, mpe->endPoint, packets);
  235102. else
  235103. MIDIReceived (mpe->endPoint, packets);
  235104. }
  235105. else
  235106. {
  235107. MIDIPacketList packets;
  235108. packets.numPackets = 1;
  235109. packets.packet[0].timeStamp = 0;
  235110. packets.packet[0].length = message.getRawDataSize();
  235111. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  235112. if (mpe->port != 0)
  235113. MIDISend (mpe->port, mpe->endPoint, &packets);
  235114. else
  235115. MIDIReceived (mpe->endPoint, &packets);
  235116. }
  235117. }
  235118. const StringArray MidiInput::getDevices()
  235119. {
  235120. StringArray s;
  235121. const ItemCount num = MIDIGetNumberOfSources();
  235122. for (ItemCount i = 0; i < num; ++i)
  235123. {
  235124. MIDIEndpointRef source = MIDIGetSource (i);
  235125. if (source != 0)
  235126. {
  235127. String name (getConnectedEndpointName (source));
  235128. if (name.isEmpty())
  235129. name = "<error>";
  235130. s.add (name);
  235131. }
  235132. else
  235133. {
  235134. s.add ("<error>");
  235135. }
  235136. }
  235137. return s;
  235138. }
  235139. int MidiInput::getDefaultDeviceIndex()
  235140. {
  235141. return 0;
  235142. }
  235143. struct MidiPortAndCallback
  235144. {
  235145. MidiInput* input;
  235146. MidiPortAndEndpoint* portAndEndpoint;
  235147. MidiInputCallback* callback;
  235148. MemoryBlock pendingData;
  235149. int pendingBytes;
  235150. double pendingDataTime;
  235151. bool active;
  235152. void processSysex (const uint8*& d, int& size, const double time)
  235153. {
  235154. if (*d == 0xf0)
  235155. {
  235156. pendingBytes = 0;
  235157. pendingDataTime = time;
  235158. }
  235159. pendingData.ensureSize (pendingBytes + size, false);
  235160. uint8* totalMessage = (uint8*) pendingData.getData();
  235161. uint8* dest = totalMessage + pendingBytes;
  235162. while (size > 0)
  235163. {
  235164. if (pendingBytes > 0 && *d >= 0x80)
  235165. {
  235166. if (*d >= 0xfa || *d == 0xf8)
  235167. {
  235168. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  235169. ++d;
  235170. --size;
  235171. }
  235172. else
  235173. {
  235174. if (*d == 0xf7)
  235175. {
  235176. *dest++ = *d++;
  235177. pendingBytes++;
  235178. --size;
  235179. }
  235180. break;
  235181. }
  235182. }
  235183. else
  235184. {
  235185. *dest++ = *d++;
  235186. pendingBytes++;
  235187. --size;
  235188. }
  235189. }
  235190. if (totalMessage [pendingBytes - 1] == 0xf7)
  235191. {
  235192. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  235193. pendingBytes = 0;
  235194. }
  235195. else
  235196. {
  235197. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  235198. }
  235199. }
  235200. };
  235201. namespace CoreMidiCallbacks
  235202. {
  235203. static CriticalSection callbackLock;
  235204. static Array<void*> activeCallbacks;
  235205. }
  235206. static void midiInputProc (const MIDIPacketList* pktlist,
  235207. void* readProcRefCon,
  235208. void* /*srcConnRefCon*/)
  235209. {
  235210. double time = Time::getMillisecondCounterHiRes() * 0.001;
  235211. const double originalTime = time;
  235212. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  235213. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235214. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  235215. {
  235216. const MIDIPacket* packet = &pktlist->packet[0];
  235217. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  235218. {
  235219. const uint8* d = (const uint8*) (packet->data);
  235220. int size = packet->length;
  235221. while (size > 0)
  235222. {
  235223. time = originalTime;
  235224. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  235225. {
  235226. mpc->processSysex (d, size, time);
  235227. }
  235228. else
  235229. {
  235230. int used = 0;
  235231. const MidiMessage m (d, size, used, 0, time);
  235232. if (used <= 0)
  235233. {
  235234. jassertfalse; // malformed midi message
  235235. break;
  235236. }
  235237. else
  235238. {
  235239. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  235240. }
  235241. size -= used;
  235242. d += used;
  235243. }
  235244. }
  235245. packet = MIDIPacketNext (packet);
  235246. }
  235247. }
  235248. }
  235249. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  235250. {
  235251. MidiInput* mi = 0;
  235252. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  235253. {
  235254. MIDIEndpointRef endPoint = MIDIGetSource (index);
  235255. if (endPoint != 0)
  235256. {
  235257. CFStringRef pname;
  235258. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  235259. {
  235260. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  235261. if (makeSureClientExists())
  235262. {
  235263. MIDIPortRef port;
  235264. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  235265. mpc->active = false;
  235266. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  235267. {
  235268. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  235269. {
  235270. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  235271. mpc->callback = callback;
  235272. mpc->pendingBytes = 0;
  235273. mpc->pendingData.ensureSize (128);
  235274. mi = new MidiInput (getDevices() [index]);
  235275. mpc->input = mi;
  235276. mi->internal = mpc;
  235277. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235278. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  235279. }
  235280. else
  235281. {
  235282. OK (MIDIPortDispose (port));
  235283. }
  235284. }
  235285. }
  235286. }
  235287. CFRelease (pname);
  235288. }
  235289. }
  235290. return mi;
  235291. }
  235292. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  235293. {
  235294. MidiInput* mi = 0;
  235295. if (makeSureClientExists())
  235296. {
  235297. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  235298. mpc->active = false;
  235299. MIDIEndpointRef endPoint;
  235300. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  235301. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  235302. {
  235303. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  235304. mpc->callback = callback;
  235305. mpc->pendingBytes = 0;
  235306. mpc->pendingData.ensureSize (128);
  235307. mi = new MidiInput (deviceName);
  235308. mpc->input = mi;
  235309. mi->internal = mpc;
  235310. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235311. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  235312. }
  235313. CFRelease (name);
  235314. }
  235315. return mi;
  235316. }
  235317. MidiInput::MidiInput (const String& name_)
  235318. : name (name_)
  235319. {
  235320. }
  235321. MidiInput::~MidiInput()
  235322. {
  235323. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  235324. mpc->active = false;
  235325. {
  235326. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235327. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  235328. }
  235329. if (mpc->portAndEndpoint->port != 0)
  235330. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  235331. delete mpc->portAndEndpoint;
  235332. delete mpc;
  235333. }
  235334. void MidiInput::start()
  235335. {
  235336. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235337. ((MidiPortAndCallback*) internal)->active = true;
  235338. }
  235339. void MidiInput::stop()
  235340. {
  235341. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235342. ((MidiPortAndCallback*) internal)->active = false;
  235343. }
  235344. #undef log
  235345. #else
  235346. MidiOutput::~MidiOutput()
  235347. {
  235348. }
  235349. void MidiOutput::reset()
  235350. {
  235351. }
  235352. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  235353. {
  235354. return false;
  235355. }
  235356. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  235357. {
  235358. }
  235359. void MidiOutput::sendMessageNow (const MidiMessage& message)
  235360. {
  235361. }
  235362. const StringArray MidiOutput::getDevices()
  235363. {
  235364. return StringArray();
  235365. }
  235366. MidiOutput* MidiOutput::openDevice (int index)
  235367. {
  235368. return 0;
  235369. }
  235370. const StringArray MidiInput::getDevices()
  235371. {
  235372. return StringArray();
  235373. }
  235374. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  235375. {
  235376. return 0;
  235377. }
  235378. #endif
  235379. #endif
  235380. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  235381. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  235382. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235383. // compiled on its own).
  235384. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  235385. #if ! JUCE_QUICKTIME
  235386. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  235387. #endif
  235388. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  235389. class QTCameraDeviceInteral;
  235390. END_JUCE_NAMESPACE
  235391. @interface QTCaptureCallbackDelegate : NSObject
  235392. {
  235393. @public
  235394. CameraDevice* owner;
  235395. QTCameraDeviceInteral* internal;
  235396. int64 firstPresentationTime;
  235397. int64 averageTimeOffset;
  235398. }
  235399. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  235400. - (void) dealloc;
  235401. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  235402. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  235403. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235404. fromConnection: (QTCaptureConnection*) connection;
  235405. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  235406. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235407. fromConnection: (QTCaptureConnection*) connection;
  235408. @end
  235409. BEGIN_JUCE_NAMESPACE
  235410. class QTCameraDeviceInteral
  235411. {
  235412. public:
  235413. QTCameraDeviceInteral (CameraDevice* owner, int index)
  235414. {
  235415. const ScopedAutoReleasePool pool;
  235416. session = [[QTCaptureSession alloc] init];
  235417. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  235418. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  235419. input = 0;
  235420. audioInput = 0;
  235421. audioDevice = 0;
  235422. fileOutput = 0;
  235423. imageOutput = 0;
  235424. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  235425. internalDev: this];
  235426. NSError* err = 0;
  235427. [device retain];
  235428. [device open: &err];
  235429. if (err == 0)
  235430. {
  235431. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  235432. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  235433. [session addInput: input error: &err];
  235434. if (err == 0)
  235435. {
  235436. resetFile();
  235437. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  235438. [imageOutput setDelegate: callbackDelegate];
  235439. if (err == 0)
  235440. {
  235441. [session startRunning];
  235442. return;
  235443. }
  235444. }
  235445. }
  235446. openingError = nsStringToJuce ([err description]);
  235447. DBG (openingError);
  235448. }
  235449. ~QTCameraDeviceInteral()
  235450. {
  235451. [session stopRunning];
  235452. [session removeOutput: imageOutput];
  235453. [session release];
  235454. [input release];
  235455. [device release];
  235456. [audioDevice release];
  235457. [audioInput release];
  235458. [fileOutput release];
  235459. [imageOutput release];
  235460. [callbackDelegate release];
  235461. }
  235462. void resetFile()
  235463. {
  235464. [fileOutput recordToOutputFileURL: nil];
  235465. [session removeOutput: fileOutput];
  235466. [fileOutput release];
  235467. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  235468. [session removeInput: audioInput];
  235469. [audioInput release];
  235470. audioInput = 0;
  235471. [audioDevice release];
  235472. audioDevice = 0;
  235473. [fileOutput setDelegate: callbackDelegate];
  235474. }
  235475. void addDefaultAudioInput()
  235476. {
  235477. NSError* err = nil;
  235478. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  235479. if ([audioDevice open: &err])
  235480. [audioDevice retain];
  235481. else
  235482. audioDevice = nil;
  235483. if (audioDevice != 0)
  235484. {
  235485. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  235486. [session addInput: audioInput error: &err];
  235487. }
  235488. }
  235489. void addListener (CameraDevice::Listener* listenerToAdd)
  235490. {
  235491. const ScopedLock sl (listenerLock);
  235492. if (listeners.size() == 0)
  235493. [session addOutput: imageOutput error: nil];
  235494. listeners.addIfNotAlreadyThere (listenerToAdd);
  235495. }
  235496. void removeListener (CameraDevice::Listener* listenerToRemove)
  235497. {
  235498. const ScopedLock sl (listenerLock);
  235499. listeners.removeValue (listenerToRemove);
  235500. if (listeners.size() == 0)
  235501. [session removeOutput: imageOutput];
  235502. }
  235503. void callListeners (CIImage* frame, int w, int h)
  235504. {
  235505. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  235506. Image image (cgImage);
  235507. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  235508. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  235509. CGContextFlush (cgImage->context);
  235510. const ScopedLock sl (listenerLock);
  235511. for (int i = listeners.size(); --i >= 0;)
  235512. {
  235513. CameraDevice::Listener* const l = listeners[i];
  235514. if (l != 0)
  235515. l->imageReceived (image);
  235516. }
  235517. }
  235518. QTCaptureDevice* device;
  235519. QTCaptureDeviceInput* input;
  235520. QTCaptureDevice* audioDevice;
  235521. QTCaptureDeviceInput* audioInput;
  235522. QTCaptureSession* session;
  235523. QTCaptureMovieFileOutput* fileOutput;
  235524. QTCaptureDecompressedVideoOutput* imageOutput;
  235525. QTCaptureCallbackDelegate* callbackDelegate;
  235526. String openingError;
  235527. Array<CameraDevice::Listener*> listeners;
  235528. CriticalSection listenerLock;
  235529. };
  235530. END_JUCE_NAMESPACE
  235531. @implementation QTCaptureCallbackDelegate
  235532. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  235533. internalDev: (QTCameraDeviceInteral*) d
  235534. {
  235535. [super init];
  235536. owner = owner_;
  235537. internal = d;
  235538. firstPresentationTime = 0;
  235539. averageTimeOffset = 0;
  235540. return self;
  235541. }
  235542. - (void) dealloc
  235543. {
  235544. [super dealloc];
  235545. }
  235546. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  235547. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  235548. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235549. fromConnection: (QTCaptureConnection*) connection
  235550. {
  235551. if (internal->listeners.size() > 0)
  235552. {
  235553. const ScopedAutoReleasePool pool;
  235554. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  235555. CVPixelBufferGetWidth (videoFrame),
  235556. CVPixelBufferGetHeight (videoFrame));
  235557. }
  235558. }
  235559. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  235560. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235561. fromConnection: (QTCaptureConnection*) connection
  235562. {
  235563. const Time now (Time::getCurrentTime());
  235564. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  235565. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  235566. #else
  235567. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  235568. #endif
  235569. int64 presentationTime = (hosttime != nil)
  235570. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  235571. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  235572. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  235573. if (firstPresentationTime == 0)
  235574. {
  235575. firstPresentationTime = presentationTime;
  235576. averageTimeOffset = timeDiff;
  235577. }
  235578. else
  235579. {
  235580. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  235581. }
  235582. }
  235583. @end
  235584. BEGIN_JUCE_NAMESPACE
  235585. class QTCaptureViewerComp : public NSViewComponent
  235586. {
  235587. public:
  235588. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  235589. {
  235590. const ScopedAutoReleasePool pool;
  235591. captureView = [[QTCaptureView alloc] init];
  235592. [captureView setCaptureSession: internal->session];
  235593. setSize (640, 480); // xxx need to somehow get the movie size - how?
  235594. setView (captureView);
  235595. }
  235596. ~QTCaptureViewerComp()
  235597. {
  235598. setView (0);
  235599. [captureView setCaptureSession: nil];
  235600. [captureView release];
  235601. }
  235602. QTCaptureView* captureView;
  235603. };
  235604. CameraDevice::CameraDevice (const String& name_, int index)
  235605. : name (name_)
  235606. {
  235607. isRecording = false;
  235608. internal = new QTCameraDeviceInteral (this, index);
  235609. }
  235610. CameraDevice::~CameraDevice()
  235611. {
  235612. stopRecording();
  235613. delete static_cast <QTCameraDeviceInteral*> (internal);
  235614. internal = 0;
  235615. }
  235616. Component* CameraDevice::createViewerComponent()
  235617. {
  235618. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  235619. }
  235620. const String CameraDevice::getFileExtension()
  235621. {
  235622. return ".mov";
  235623. }
  235624. void CameraDevice::startRecordingToFile (const File& file, int quality)
  235625. {
  235626. stopRecording();
  235627. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  235628. d->callbackDelegate->firstPresentationTime = 0;
  235629. file.deleteFile();
  235630. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  235631. // out wrong, so we'll put some audio in there too..,
  235632. d->addDefaultAudioInput();
  235633. [d->session addOutput: d->fileOutput error: nil];
  235634. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  235635. for (;;)
  235636. {
  235637. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  235638. if (connection == 0)
  235639. break;
  235640. QTCompressionOptions* options = 0;
  235641. NSString* mediaType = [connection mediaType];
  235642. if ([mediaType isEqualToString: QTMediaTypeVideo])
  235643. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  235644. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  235645. : @"QTCompressionOptions240SizeH264Video"];
  235646. else if ([mediaType isEqualToString: QTMediaTypeSound])
  235647. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  235648. [d->fileOutput setCompressionOptions: options forConnection: connection];
  235649. }
  235650. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  235651. isRecording = true;
  235652. }
  235653. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  235654. {
  235655. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  235656. if (d->callbackDelegate->firstPresentationTime != 0)
  235657. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  235658. return Time();
  235659. }
  235660. void CameraDevice::stopRecording()
  235661. {
  235662. if (isRecording)
  235663. {
  235664. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  235665. isRecording = false;
  235666. }
  235667. }
  235668. void CameraDevice::addListener (Listener* listenerToAdd)
  235669. {
  235670. if (listenerToAdd != 0)
  235671. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  235672. }
  235673. void CameraDevice::removeListener (Listener* listenerToRemove)
  235674. {
  235675. if (listenerToRemove != 0)
  235676. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  235677. }
  235678. const StringArray CameraDevice::getAvailableDevices()
  235679. {
  235680. const ScopedAutoReleasePool pool;
  235681. StringArray results;
  235682. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  235683. for (int i = 0; i < (int) [devs count]; ++i)
  235684. {
  235685. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  235686. results.add (nsStringToJuce ([dev localizedDisplayName]));
  235687. }
  235688. return results;
  235689. }
  235690. CameraDevice* CameraDevice::openDevice (int index,
  235691. int minWidth, int minHeight,
  235692. int maxWidth, int maxHeight)
  235693. {
  235694. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  235695. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  235696. return d.release();
  235697. return 0;
  235698. }
  235699. #endif
  235700. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  235701. #endif
  235702. #endif
  235703. END_JUCE_NAMESPACE
  235704. #endif
  235705. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  235706. #endif
  235707. #endif